Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rules needed for mutation #738

Merged
merged 4 commits into from
Feb 1, 2024
Merged
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
Expand Up @@ -20,7 +20,7 @@ SuiteSparse = "4607b0f0-06f3-5cda-b6b1-a6196a1729e9"

[compat]
Adapt = "3.4.0, 4"
ChainRulesCore = "1.15.3"
ChainRulesCore = "1.20"
ChainRulesTestUtils = "1.5"
Compat = "3.46, 4.2"
Distributed = "1"
Expand Down
8 changes: 7 additions & 1 deletion src/rulesets/Base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,13 @@ _instantiate_zeros(ẋs::AbstractArray{<:AbstractArray}, xs) = ẋs
#####

function frule((_, ẏ, ẋ), ::typeof(copyto!), y::AbstractArray, x)
return copyto!(y, x), copyto!(ẏ, ẋ)
if ẏ isa AbstractZero
# it's allowed to have an imutable zero tangent for ẏ as long as ẋ is zero
@assert iszero(ẋ)
else
copyto!(ẏ, ẋ)
end
return copyto!(y, x), ẏ
end

function frule((_, ẏ, _, ẋ), ::typeof(copyto!), y::AbstractArray, i::Integer, x, js::Integer...)
Expand Down
8 changes: 8 additions & 0 deletions src/rulesets/Base/base.jl
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ function rrule(::typeof(one), x)
return (one(x), one_pullback)
end


oxinabox marked this conversation as resolved.
Show resolved Hide resolved
function ChainRulesCore.frule((_, ȯbj, _, ẋ), ::typeof(setfield!), obj, field, x)
ȯbj::MutableTangent
y = setfield!(obj, field, x)
ẏ = setproperty!(ȯbj, field, ẋ)
return y, ẏ
end

# `adjoint`

frule((_, Δz), ::typeof(adjoint), z::Number) = (z', Δz')
Expand Down
9 changes: 9 additions & 0 deletions test/rulesets/Base/base.jl
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
mutable struct MDemo
x::Float64
end

@testset "base.jl" begin
@testset "zero/one" begin
for f in [zero, one]
Expand All @@ -18,6 +22,11 @@
end
end
end

@testset "setfield!" begin
test_frule(setfield!, MDemo(3.5) ⊢ MutableTangent{MDemo}(; x=2.0), :x, 5.0)
test_frule(setfield!, MDemo(3.5) ⊢ MutableTangent{MDemo}(; x=2.0), 1, 5.0)
end

@testset "Trig" begin
@testset "Basics" for x = (Float64(π)-0.01, Complex(π, π/2))
Expand Down
Loading