Skip to content

Commit

Permalink
Merge pull request #782 from nmheim/nh/subtract-rule
Browse files Browse the repository at this point in the history
Add missing subtract rule
  • Loading branch information
oxinabox authored Feb 12, 2024
2 parents b3f9f9b + f44437c commit 971069c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/rulesets/Base/arraymath.jl
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,21 @@ function rrule(::typeof(-), x::AbstractArray)
return -x, negation_pullback
end

#####
##### Subtraction
#####

frule((_, Δx, Δy), ::typeof(-), x::AbstractArray, y::AbstractArray) = x - y, Δx - Δy

function rrule(::typeof(-), x::AbstractArray, y::AbstractArray)
xproj = ProjectTo(x)
yproj = ProjectTo(y)
function subtract_pullback(dy_raw)
dy = unthunk(dy_raw) # projs will otherwise unthunk twice
return (NoTangent(), xproj(dy), yproj(-dy))
end
return x - y, subtract_pullback
end

#####
##### Addition (Multiarg `+`)
Expand Down
9 changes: 9 additions & 0 deletions test/rulesets/Base/arraymath.jl
Original file line number Diff line number Diff line change
Expand Up @@ -217,4 +217,13 @@
@gpu test_rrule(+, randn(4, 4), randn(4, 4), randn(4, 4))
@gpu test_rrule(+, randn(3), randn(3,1), randn(3,1,1))
end

@testset "subtraction" begin
# fwd
@gpu test_frule(-, randn(2), randn(2))
# rev
@gpu test_rrule(-, randn(4, 4), randn(4, 4))
@gpu test_rrule(-, randn(4), randn(ComplexF64, 4))
@gpu test_rrule(-, randn(3), randn(3, 1))
end
end

0 comments on commit 971069c

Please sign in to comment.