From e3932c563678cbbbb159dd14bc739fc08027b5df Mon Sep 17 00:00:00 2001 From: CarloLucibello Date: Sun, 22 Nov 2026 08:54:12 +0100 Subject: [PATCH] Add `frule` and `rrule` for `oftype` on numbers 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 --- Project.toml | 2 +- src/rulesets/Base/base.jl | 11 +++++++++++ test/rulesets/Base/base.jl | 9 +++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/Project.toml b/Project.toml index 1d8c5e7b6..6f9e69e11 100644 --- a/Project.toml +++ b/Project.toml @@ -1,6 +1,6 @@ name = "ChainRules" uuid = "082447d4-558c-5d27-93f4-14fc19e9eca2" -version = "1.74.14" +version = "1.74.15" [deps] Adapt = "79e6a3ab-5dfb-504d-930d-738a2a938a0e" diff --git a/src/rulesets/Base/base.jl b/src/rulesets/Base/base.jl index 8a50a7a05..1d495b3e8 100644 --- a/src/rulesets/Base/base.jl +++ b/src/rulesets/Base/base.jl @@ -62,6 +62,17 @@ end @scalar_rule Float32(x::Real) true @scalar_rule AbstractFloat(x::Real) true +# `oftype` +# Base's `oftype` branches on `y isa typeof(x)`, which defeats inference of Zygote's pullback. + +frule((_, _, ẏ), ::typeof(oftype), x::Number, y::Number) = (oftype(x, y), ProjectTo(x)(ẏ)) + +function rrule(::typeof(oftype), x::Number, y::Number) + project_y = ProjectTo(y) + oftype_pullback(Ω̄) = (NoTangent(), ZeroTangent(), project_y(Ω̄)) + return oftype(x, y), oftype_pullback +end + # `imag` @scalar_rule imag(x::Real) ZeroTangent() diff --git a/test/rulesets/Base/base.jl b/test/rulesets/Base/base.jl index 8c2e807eb..e21859aac 100644 --- a/test/rulesets/Base/base.jl +++ b/test/rulesets/Base/base.jl @@ -310,6 +310,15 @@ end @test frule(NoRules, 1.0) === nothing @test rrule(NoRules, 1.0) === nothing end + + @testset "oftype" begin + for (x, y) in ((1.0, 2.5), (1.0f0, 2.5), (1.0im, 2.5)) + test_frule(oftype, x, y; rtol=1.0e-3, atol=1.0e-3) + 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) + end @testset "map(f, ::Tuple...)" begin test_rrule(map, identity, (1.0, 2.0), check_inferred=false)