Skip to content

Commit

Permalink
gradients of channels
Browse files Browse the repository at this point in the history
  • Loading branch information
MikeInnes committed Aug 20, 2019
1 parent 1a049a2 commit e2fcd61
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/compiler/reverse.jl
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ function instrument(ir::IR)
pr = Pipe(ir)
for (v, st) in pr
ex = st.expr
isexpr(ex, :foreigncall) && continue
isexpr(ex, :foreigncall, :isdefined) && continue
isexpr(ex, :enter, :leave) && error("try/catch is not supported.")
ex = instrument_new!(pr, v, ex)
ex = instrument_literals!(pr, v, ex)
Expand Down
20 changes: 20 additions & 0 deletions src/lib/base.jl
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,23 @@ end
(nothing, Δ, nothing)
end
end

# Channels

@nograd Channel

grad_mut(ch::Channel) = Channel(ch.sz_max)

@adjoint! function put!(ch::Channel, x)
put!(ch, x), function (ȳ)
= take!(grad_mut(__context__, ch))
(nothing, accum(x̄, ȳ), nothing)
end
end

@adjoint! function take!(ch::Channel)
take!(ch), function (x̄)
put!(grad_mut(__context__, ch), x̄)
return
end
end
4 changes: 4 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ end
include("features.jl")
end

@testset "Data Structures" begin
include("structures.jl")
end

@testset "Gradients" begin
include("gradcheck.jl")
end
Expand Down
8 changes: 8 additions & 0 deletions test/structures.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using Zygote, Test

function f(x)
ch = Channel(Inf)
put!(ch, x^2) + take!(ch)
end

@test gradient(f, 5) == (20,)

2 comments on commit e2fcd61

@MikeInnes
Copy link
Member Author

Choose a reason for hiding this comment

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

@JuliaRegistrator register()

@JuliaRegistrator
Copy link

Choose a reason for hiding this comment

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

Registration pull request created: JuliaRegistries/General/2811

After the above pull request is merged, it is recommended that a tag is created on this repository for the registered package version.

This will be done automatically if Julia TagBot is installed, or can be done manually through the github interface, or via:

git tag -a v0.3.4 -m "<description of version>" e2fcd614478199d7839d11cbf70b36bb6335ae95
git push origin v0.3.4

Please sign in to comment.