Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
11 changes: 11 additions & 0 deletions src/rulesets/Base/base.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
9 changes: 9 additions & 0 deletions test/rulesets/Base/base.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)

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)

end

@testset "map(f, ::Tuple...)" begin
test_rrule(map, identity, (1.0, 2.0), check_inferred=false)
Expand Down
Loading