Skip to content

Commit

Permalink
Broadcast the propagation_expr for vector mode AD (#93)
Browse files Browse the repository at this point in the history
* Broadcast the `propagation_expr` for vector mode AD

* Use the `muladd` macro to optimize `propagation_expr`

* New release

* Fix propagation_expr

* Explicit broadcast

* Revert "Explicit broadcast"

This reverts commit b7d1da2.
  • Loading branch information
YingboMa authored Jan 13, 2020
2 parents de61cd3 + 91b0be4 commit 932b704
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
6 changes: 5 additions & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
name = "ChainRulesCore"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "0.5.1"
version = "0.5.2"

[deps]
MuladdMacro = "46d2c3a1-f734-5fdb-9937-b9b9aeba4221"

[compat]
julia = "^1.0"
MuladdMacro = "0.2.1"

[extras]
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
Expand Down
21 changes: 19 additions & 2 deletions src/rule_definition_tools.jl
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# These are some macros (and supporting functions) to make it easier to define rules.
using MuladdMacro: @muladd

"""
@scalar_rule(f(x₁, x₂, ...),
Expand Down Expand Up @@ -208,9 +209,25 @@ end
function propagation_expr(Δs, ∂s)
# This is basically Δs ⋅ ∂s
∂s = map(esc, ∂s)
n∂s = length(∂s)

∂_mul_Δs = ntuple(i->:($(∂s[i]) * $(Δs[i])), length(∂s))
return :(+($(∂_mul_Δs...)))
# Due to bugs in Julia 1.0, we can't use `.+` or `.*` inside expression
# literals.
∂_mul_Δs = ntuple(i->:($(∂s[i]) * $(Δs[i])), n∂s)

# Avoiding the extra `+` operation, it is potentially expensive for vector
# mode AD.
sumed_∂_mul_Δs = if n∂s > 1
# we use `@.` to broadcast `*` and `+`
:(@. +($(∂_mul_Δs...)))
else
# Note: we don't want to do broadcasting with only 1 multiply (no `+`),
# because some arrays overload multiply with scalar. Avoiding
# broadcasting saves compilation time.
∂_mul_Δs[1]
end

return :(@muladd $sumed_∂_mul_Δs)
end

"""
Expand Down

2 comments on commit 932b704

@YingboMa
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/7863

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.5.2 -m "<description of version>" 932b704a4844b2781065318c0855e7a2641432c6
git push origin v0.5.2

Please sign in to comment.