Skip to content

Add frule and rrule for oftype on numbers - #877

Open
CarloLucibello wants to merge 1 commit into
mainfrom
cl/oftype
Open

CarloLucibello wants to merge 1 commit into
mainfrom
cl/oftype

Conversation

@CarloLucibello

Copy link
Copy Markdown
Member

Base.oftype(x, y) = y isa typeof(x) ? y : convert(typeof(x), y) branches, so in Zygote the pullback of any function that calls it is not inferred and gets much slower. FluxML/Zygote.jl#1751 has the benchmarks.

This adds rules for oftype(::Number, ::Number). The cotangent is projected onto y, and the frule's tangent onto x. With the rule, Zygote infers the pullback of f(x, y) = sin(x) * cos(y) + x * oftype(x, y) and its gradient allocates nothing (1760 bytes before), the same as with convert(typeof(x), y).

Fixes FluxML/Zygote.jl#1751

🧔‍♂️🤖 Assisted by AI

Base's `oftype` branches on `y isa typeof(x)`, so Zygote's pullback of any
function calling it is not inferred (FluxML/Zygote.jl#1751).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
test_rrule(oftype, x, y; rtol=1.0e-3, atol=1.0e-3)
end
@test rrule(oftype, 1.0, 2)[2](3.0) === (NoTangent(), ZeroTangent(), 3.0)
@test rrule(oftype, 1.0, 2.0 + 0im)[2](3.0) === (NoTangent(), ZeroTangent(), 3.0 + 0im)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[JuliaFormatter] reported by reviewdog 🐶

Suggested change
@test rrule(oftype, 1.0, 2.0 + 0im)[2](3.0) === (NoTangent(), ZeroTangent(), 3.0 + 0im)
@test rrule(oftype, 1.0, 2.0 + 0im)[2](3.0) ===
(NoTangent(), ZeroTangent(), 3.0 + 0im)

@codecov

codecov Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.65%. Comparing base (98dc481) to head (e3932c5).

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #877   +/-   ##
=======================================
  Coverage   96.65%   96.65%           
=======================================
  Files          28       28           
  Lines        3615     3620    +5     
=======================================
+ Hits         3494     3499    +5     
  Misses        121      121           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Pullback of oftype is not inferred (≈1000× slower gradient than convert(typeof(x), y))

1 participant