repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
Mooncake.jl
github_2023
others
525
compintell
willtebbutt
@@ -169,8 +205,86 @@ struct Cache{Trule,Ty_cache,Ttangents<:Tuple} tangents::Ttangents end -_copy!!(dst, src) = copy!(dst, src) -_copy!!(::Number, src::Number) = src +const supportedcollections = Union{Tuple,NamedTuple} + +""" + is_user_defined_struct(T) + +Required for checking if datatype `T` is a immutable Composite, Mutable Composite type (returns true) or a built in collection type (returns false). +Helps in identifying user defined struct for recursing over fields correctly. +""" +function is_user_defined_struct(T) + return isconcretetype(T) && + !isprimitivetype(T) && + !(T <: supportedcollections) && + !(T <: Array) && + (@static VERSION >= v"1.11" ? !(T <: Memory) : true) +end + +""" + __exclude_unsupported_output(y) + +Required for the robust design of [`value_and_pullback`](@ref), [`prepare_pullback_cache`](@ref). +Ensures that `y` contains no aliasing, circular references, `Ptr`s or non differentiable datatypes. +In the forward pass f(args...) output can only return a "Tree" like datastructure with leaf nodes as primitive types. +Refer https://github.com/compintell/Mooncake.jl/issues/517#issuecomment-2715202789 and related issue for details. +Internally calls [`__exclude_unsupported_output_internal!`](@ref). +The design is modelled after `zero_tangent`. +""" +function __exclude_unsupported_output(y::T) where {T} + if (T <: Union{Dict,Set}) + throw_datastructure_output_error(y) + end + __exclude_unsupported_output_internal!(y, Set{UInt}()) + return nothing +end + +""" + __exclude_unsupported_output_internal(y::T, address_set::Set{UInt}) where {T} + +For checking if output`y` is a valid Mutable/immutable composite or a primitive type. +Performs a recursive depth first search over the function output `y` with an `isbitstype()` check base case. The visited memory addresses are stored inside `address_set`. +If the set already contains a newly visited address, it errors out indicating an Alais or Circular reference. +Also errors out if `y` is or contains a Pointer. +It is called internally by [`__exclude_unsupported_output(y)`](@ref). +""" +function __exclude_unsupported_output_internal!(y::T, address_set::Set{UInt}) where {T} + isbitstype(T) && return nothing + if objectid(y) in address_set + throw_circular_reference_or_alias_error(y) + end + + push!(address_set, objectid(y)) + + if is_user_defined_struct(T) + # recurse over a composite type. + for y_sub in fieldnames(T) + # isassigned, isdefined are not defined for Tuples, NamedTuples. + if !(T <: supportedcollections) && !isdefined(y, y_sub)
Would it be easier just to add a method of `__exclude_unsupported_output_internal!` that explicitly handles `Tuple`s and `NamedTuple`s? i.e. something like ```julia function __exclude_unsupported_output_internal!(y::Union{Tuple,NamedTuple}, address_set::Set{UInt}) map(Base.Fix2(__exclude_unsupported_output_internal!, address_set), y) return nothing end ``` I'm just thinking that it's more in line with the way that we handle other things.
Mooncake.jl
github_2023
others
525
compintell
willtebbutt
@@ -169,8 +205,86 @@ struct Cache{Trule,Ty_cache,Ttangents<:Tuple} tangents::Ttangents end -_copy!!(dst, src) = copy!(dst, src) -_copy!!(::Number, src::Number) = src +const supportedcollections = Union{Tuple,NamedTuple}
```suggestion ``` See below.
Mooncake.jl
github_2023
others
525
compintell
willtebbutt
@@ -47,6 +47,39 @@ function throw_val_and_grad_ret_type_error(y) ) end +function throw_forward_ret_type_error(y) + throw( + ValueAndGradientReturnTypeError( + "Found a value of type $(typeof(y)) in output, but output is not permitted to be or contain a pointer. This is because the amount of memory to which it refers is unknown, therefore Mooncake.jl is unable to allocate appropriate memory for its gradients.", + ), + ) +end + +function throw_circular_reference_or_alias_error(y) + throw( + ValueAndGradientReturnTypeError( + "Object with address $(objectid(y)) and type $(typeof(y)) appears more than once." * + " Output cannot contain Circular references or aliases", + ), + ) +end + +function throw_datastructure_output_error(y) + throw( + ValueAndGradientReturnTypeError( + "Error: Object of type $(typeof(y)) does not have a Real finite Hilbert space. " + ), + ) +end + +function throw_undef_err(y) + throw( + ValueAndGradientReturnTypeError( + "Error: Object $(y) cannot be or contain undefined memory addresses. " + ), + ) +end
```suggestion ``` I think we can get rid of this. See below.
Mooncake.jl
github_2023
others
525
compintell
willtebbutt
@@ -47,6 +47,39 @@ function throw_val_and_grad_ret_type_error(y) ) end +function throw_forward_ret_type_error(y) + throw( + ValueAndGradientReturnTypeError( + "Found a value of type $(typeof(y)) in output, but output is not permitted to be or contain a pointer. This is because the amount of memory to which it refers is unknown, therefore Mooncake.jl is unable to allocate appropriate memory for its gradients.", + ), + ) +end + +function throw_circular_reference_or_alias_error(y) + throw( + ValueAndGradientReturnTypeError( + "Object with address $(objectid(y)) and type $(typeof(y)) appears more than once." * + " Output cannot contain Circular references or aliases", + ), + ) +end + +function throw_datastructure_output_error(y) + throw( + ValueAndGradientReturnTypeError( + "Error: Object of type $(typeof(y)) does not have a Real finite Hilbert space. " + ), + ) +end
```suggestion ``` I think we can also get rid of this. See below
Mooncake.jl
github_2023
others
525
compintell
willtebbutt
@@ -169,8 +205,86 @@ struct Cache{Trule,Ty_cache,Ttangents<:Tuple} tangents::Ttangents end -_copy!!(dst, src) = copy!(dst, src) -_copy!!(::Number, src::Number) = src +const supportedcollections = Union{Tuple,NamedTuple} + +""" + is_user_defined_struct(T) + +Required for checking if datatype `T` is a immutable Composite, Mutable Composite type (returns true) or a built in collection type (returns false). +Helps in identifying user defined struct for recursing over fields correctly. +""" +function is_user_defined_struct(T) + return isconcretetype(T) && + !isprimitivetype(T) && + !(T <: supportedcollections) && + !(T <: Array) && + (@static VERSION >= v"1.11" ? !(T <: Memory) : true) +end + +""" + __exclude_unsupported_output(y) + +Required for the robust design of [`value_and_pullback`](@ref), [`prepare_pullback_cache`](@ref). +Ensures that `y` contains no aliasing, circular references, `Ptr`s or non differentiable datatypes. +In the forward pass f(args...) output can only return a "Tree" like datastructure with leaf nodes as primitive types. +Refer https://github.com/compintell/Mooncake.jl/issues/517#issuecomment-2715202789 and related issue for details. +Internally calls [`__exclude_unsupported_output_internal!`](@ref). +The design is modelled after `zero_tangent`. +""" +function __exclude_unsupported_output(y::T) where {T} + if (T <: Union{Dict,Set}) + throw_datastructure_output_error(y) + end + __exclude_unsupported_output_internal!(y, Set{UInt}()) + return nothing +end + +""" + __exclude_unsupported_output_internal(y::T, address_set::Set{UInt}) where {T} + +For checking if output`y` is a valid Mutable/immutable composite or a primitive type. +Performs a recursive depth first search over the function output `y` with an `isbitstype()` check base case. The visited memory addresses are stored inside `address_set`. +If the set already contains a newly visited address, it errors out indicating an Alais or Circular reference. +Also errors out if `y` is or contains a Pointer. +It is called internally by [`__exclude_unsupported_output(y)`](@ref). +""" +function __exclude_unsupported_output_internal!(y::T, address_set::Set{UInt}) where {T} + isbitstype(T) && return nothing + if objectid(y) in address_set + throw_circular_reference_or_alias_error(y) + end + + push!(address_set, objectid(y)) + + if is_user_defined_struct(T) + # recurse over a composite type. + for y_sub in fieldnames(T) + # isassigned, isdefined are not defined for Tuples, NamedTuples. + if !(T <: supportedcollections) && !isdefined(y, y_sub) + throw_undef_err(y) + else + __exclude_unsupported_output_internal!(getfield(y, y_sub), address_set) + end + end + else + # recurse over built in collections. + for i in eachindex(y) + # isassigned is valid for Arrays. + if !(T <: supportedcollections) && !isassigned(y, i) + throw_undef_err(y)
Is there a particular problem that arises if the output contains unassigned elements?
Mooncake.jl
github_2023
others
525
compintell
willtebbutt
@@ -169,8 +205,86 @@ struct Cache{Trule,Ty_cache,Ttangents<:Tuple} tangents::Ttangents end -_copy!!(dst, src) = copy!(dst, src) -_copy!!(::Number, src::Number) = src +const supportedcollections = Union{Tuple,NamedTuple} + +""" + is_user_defined_struct(T) + +Required for checking if datatype `T` is a immutable Composite, Mutable Composite type (returns true) or a built in collection type (returns false). +Helps in identifying user defined struct for recursing over fields correctly. +""" +function is_user_defined_struct(T) + return isconcretetype(T) && + !isprimitivetype(T) && + !(T <: supportedcollections) && + !(T <: Array) && + (@static VERSION >= v"1.11" ? !(T <: Memory) : true) +end + +""" + __exclude_unsupported_output(y) + +Required for the robust design of [`value_and_pullback`](@ref), [`prepare_pullback_cache`](@ref). +Ensures that `y` contains no aliasing, circular references, `Ptr`s or non differentiable datatypes. +In the forward pass f(args...) output can only return a "Tree" like datastructure with leaf nodes as primitive types. +Refer https://github.com/compintell/Mooncake.jl/issues/517#issuecomment-2715202789 and related issue for details. +Internally calls [`__exclude_unsupported_output_internal!`](@ref). +The design is modelled after `zero_tangent`. +""" +function __exclude_unsupported_output(y::T) where {T} + if (T <: Union{Dict,Set}) + throw_datastructure_output_error(y) + end + __exclude_unsupported_output_internal!(y, Set{UInt}()) + return nothing +end + +""" + __exclude_unsupported_output_internal(y::T, address_set::Set{UInt}) where {T} + +For checking if output`y` is a valid Mutable/immutable composite or a primitive type. +Performs a recursive depth first search over the function output `y` with an `isbitstype()` check base case. The visited memory addresses are stored inside `address_set`. +If the set already contains a newly visited address, it errors out indicating an Alais or Circular reference. +Also errors out if `y` is or contains a Pointer. +It is called internally by [`__exclude_unsupported_output(y)`](@ref). +""" +function __exclude_unsupported_output_internal!(y::T, address_set::Set{UInt}) where {T} + isbitstype(T) && return nothing + if objectid(y) in address_set + throw_circular_reference_or_alias_error(y) + end + + push!(address_set, objectid(y))
Ah, also, we only need to add items to the `address_set` if their identity is given by their address in memory, so we can restrict this to only run if `ismutabletype(T)` is `true` I think.
Mooncake.jl
github_2023
others
525
compintell
willtebbutt
@@ -98,4 +98,81 @@ end end end end + + @testset "prepare_pullback_cache errors" begin + # Test when function outputs a valid type. + struct userdefinedstruct
```suggestion struct UserDefinedStruct ``` style
Mooncake.jl
github_2023
others
525
compintell
willtebbutt
@@ -98,4 +98,81 @@ end end end end + + @testset "prepare_pullback_cache errors" begin + # Test when function outputs a valid type. + struct userdefinedstruct + a::Int64 + b::Vector{Float64} + c::Vector{Vector{Float64}} + end + + mutable struct userdefinedmutablestruct
```suggestion mutable struct UserDefinedMutableStruct ``` style
Mooncake.jl
github_2023
others
525
compintell
willtebbutt
@@ -98,4 +98,81 @@ end end end end + + @testset "prepare_pullback_cache errors" begin + # Test when function outputs a valid type. + struct userdefinedstruct + a::Int64 + b::Vector{Float64} + c::Vector{Vector{Float64}} + end + + mutable struct userdefinedmutablestruct + a::Int64 + b::Vector{Float64} + c::Vector{Vector{Float64}} + end + + test_topass_cases = [
```suggestion test_to_pass_cases = [ ```
Mooncake.jl
github_2023
others
525
compintell
willtebbutt
@@ -47,6 +47,23 @@ function throw_val_and_grad_ret_type_error(y) ) end +function throw_forward_ret_type_error(y) + throw( + ValueAndGradientReturnTypeError(
```suggestion ValueAndPullbackReturnTypeError( ``` This is super picky, but I wonder whether we could have a separate error type for pullback return-type errors?
Mooncake.jl
github_2023
others
525
compintell
willtebbutt
@@ -169,8 +193,82 @@ struct Cache{Trule,Ty_cache,Ttangents<:Tuple} tangents::Ttangents end -_copy!!(dst, src) = copy!(dst, src) -_copy!!(::Number, src::Number) = src +""" + is_user_defined_struct(T) + +Required for checking if datatype `T` is a immutable Composite, Mutable Composite type (returns true) or a built in collection type (returns false). +Helps in identifying user defined struct for recursing over fields correctly. +""" +function is_user_defined_struct(T) + return isconcretetype(T) && + !isprimitivetype(T) && + !(T <: Union{Tuple,NamedTuple,Array}) && + (@static VERSION >= v"1.11" ? !(T <: Memory) : true) +end
(Hopefully) the last thing I'd like to discuss is this. I'm wondering whether it makes more sense to just add methods of `__exclude_unsupported_output` for `Array` and `Memory` (the latter only on 1.11)? This would mean that we could get rid of this function entirely, and just keep the loop over `fieldnames(T)` in the method of `__exclude_unsupported_output_internal` below. The advantage of doing this is again that it would be more in line with what we've done elsewhere in the package, and would reduce the symbol count by 1 (so there's one fewer docstring to maintain, and one fewer functions for people reading the code to have to understand).
Mooncake.jl
github_2023
others
525
compintell
willtebbutt
@@ -169,8 +193,82 @@ struct Cache{Trule,Ty_cache,Ttangents<:Tuple} tangents::Ttangents end -_copy!!(dst, src) = copy!(dst, src) -_copy!!(::Number, src::Number) = src +""" + __exclude_unsupported_output(y) + +Required for the robust design of [`value_and_pullback`](@ref), [`prepare_pullback_cache`](@ref). +Ensures that `y` contains no aliasing, circular references, `Ptr`s or non differentiable datatypes. +In the forward pass f(args...) output can only return a "Tree" like datastructure with leaf nodes as primitive types. +Refer https://github.com/compintell/Mooncake.jl/issues/517#issuecomment-2715202789 and related issue for details. +Internally calls [`__exclude_unsupported_output_internal!`](@ref). +The design is modelled after `zero_tangent`. +""" +function __exclude_unsupported_output(y::T) where {T} + __exclude_unsupported_output_internal!(y, Set{UInt}()) + return nothing +end + +""" + __exclude_unsupported_output_internal(y::T, address_set::Set{UInt}) where {T} + +For checking if output`y` is a valid Mutable/immutable composite or a primitive type. +Performs a recursive depth first search over the function output `y` with an `isbitstype()` check base case. The visited memory addresses are stored inside `address_set`. +If the set already contains a newly visited address, it errors out indicating an Alais or Circular reference. +Also errors out if `y` is or contains a Pointer. +It is called internally by [`__exclude_unsupported_output(y)`](@ref). +""" +function __exclude_unsupported_output_internal!(y::T, address_set::Set{UInt}) where {T} + isbitstype(T) && return nothing + if objectid(y) in address_set + throw_circular_reference_or_alias_error(y) + end + + # immutable types are copied on the stack. + ismutable(y) && push!(address_set, objectid(y)) + + # recurse over a composite type's fields. + for y_sub in fieldnames(T) + # isdefined() is valid for Mutable Structs, Structs. + !isdefined(y, y_sub) && continue + __exclude_unsupported_output_internal!(getfield(y, y_sub), address_set) + end + + return nothing +end + +const IterableCollections = @static VERSION >= v"1.11" ? Union{Array,Memory} : Array + +function __exclude_unsupported_output_internal!( + y::T, address_set::Set{UInt} +) where {T<:IterableCollections}
```suggestion const __BuiltinArrays = @static VERSION >= v"1.11" ? Union{Array,Memory} : Array function __exclude_unsupported_output_internal!( y::T, address_set::Set{UInt} ) where {T<:__BuiltinArrays} ``` so sorry, would you mind if we renamed `IterableCollections`? It's just a very general name, and I think we would be better off with something more specific. (I otherwise very much like what you've done here to avoid having to duplicate code for `Array`s and `Memory`s)
Mooncake.jl
github_2023
others
514
compintell
willtebbutt
@@ -10,6 +10,7 @@ ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" DiffRules = "b552c78f-8df3-52c6-915a-8e097449b14b" DiffTests = "de460e47-3fe3-5279-bb4a-814414816d5d" ExprTools = "e2ba6199-217a-4e67-a87a-7c52f15ade04" +Flux = "587475ba-b771-5e3f-ad9e-33799f191a9c"
Could we please make this a package extension, rather than making Flux a dep of Mooncake?
Mooncake.jl
github_2023
others
514
compintell
willtebbutt
@@ -33,3 +33,55 @@ end function generate_derived_rrule!!_test_cases(rng_ctor, ::Val{:linear_algebra}) return Any[], Any[] end + +@is_primitive DefaultCtx Tuple{ + typeof(Losses.mse),AbstractArray{<:IEEEFloat},AbstractArray{<:IEEEFloat} +} + +function rrule!!( + ::CoDual{typeof(Losses.mse)}, + X::CoDual{<:AbstractArray{P}}, + Y::CoDual{<:AbstractArray{P}}, +) where {P<:IEEEFloat} + N = P(2) / P(length(X.x)) .* (X.x - Y.x) + + function FluxMSE_pullback(dloss::P)
```suggestion function flux_mse_pullback(dloss::P) ``` style
Mooncake.jl
github_2023
others
514
compintell
willtebbutt
@@ -33,3 +33,55 @@ end function generate_derived_rrule!!_test_cases(rng_ctor, ::Val{:linear_algebra}) return Any[], Any[] end + +@is_primitive DefaultCtx Tuple{ + typeof(Losses.mse),AbstractArray{<:IEEEFloat},AbstractArray{<:IEEEFloat} +} + +function rrule!!( + ::CoDual{typeof(Losses.mse)}, + X::CoDual{<:AbstractArray{P}}, + Y::CoDual{<:AbstractArray{P}}, +) where {P<:IEEEFloat} + N = P(2) / P(length(X.x)) .* (X.x - Y.x) + + function FluxMSE_pullback(dloss::P) + # adjoints got by VJP reverse pass equations. + temp = N .* dloss + @. X.dx += temp + @. Y.dx -= temp + return NoRData(), NoRData(), NoRData() + end + + # in forward pass it returns codual float64, hence coduals dx is NoFData(). + return CoDual(Losses.mse(X.x, Y.x), NoFData()), FluxMSE_pullback
```suggestion return zero_fcodual(Losses.mse(X.x, Y.x)), flux_mse_pullback ```
Mooncake.jl
github_2023
others
514
compintell
willtebbutt
@@ -33,3 +33,55 @@ end function generate_derived_rrule!!_test_cases(rng_ctor, ::Val{:linear_algebra}) return Any[], Any[] end + +@is_primitive DefaultCtx Tuple{ + typeof(Losses.mse),AbstractArray{<:IEEEFloat},AbstractArray{<:IEEEFloat} +} + +function rrule!!( + ::CoDual{typeof(Losses.mse)}, + X::CoDual{<:AbstractArray{P}}, + Y::CoDual{<:AbstractArray{P}}, +) where {P<:IEEEFloat} + N = P(2) / P(length(X.x)) .* (X.x - Y.x)
```suggestion N = P(2) / P(length(X.x)) .* (X.x .- Y.x) ``` Two things here: 1. could we please use a variable name other than `N`? It's typically used for counts and lengths of things 2. per the suggestion, I think we probably want to fuse the broadcasting here to avoid extra allocations
Mooncake.jl
github_2023
others
514
compintell
willtebbutt
@@ -33,3 +33,55 @@ end function generate_derived_rrule!!_test_cases(rng_ctor, ::Val{:linear_algebra}) return Any[], Any[] end + +@is_primitive DefaultCtx Tuple{ + typeof(Losses.mse),AbstractArray{<:IEEEFloat},AbstractArray{<:IEEEFloat} +} + +function rrule!!( + ::CoDual{typeof(Losses.mse)}, + X::CoDual{<:AbstractArray{P}}, + Y::CoDual{<:AbstractArray{P}},
```suggestion X::CoDual{<:Array{P}}, Y::CoDual{<:Array{P}}, ``` the convention in Mooncake is to provide very strict typing for rules. I'm realising now that I don't have the rationale for this written down anywhere -- in short it's because if you write rules for abstract types, they'll usually be subtly wrong for most input types.
Mooncake.jl
github_2023
others
514
compintell
willtebbutt
@@ -33,3 +33,55 @@ end function generate_derived_rrule!!_test_cases(rng_ctor, ::Val{:linear_algebra}) return Any[], Any[] end + +@is_primitive DefaultCtx Tuple{ + typeof(Losses.mse),AbstractArray{<:IEEEFloat},AbstractArray{<:IEEEFloat} +} + +function rrule!!( + ::CoDual{typeof(Losses.mse)}, + X::CoDual{<:AbstractArray{P}}, + Y::CoDual{<:AbstractArray{P}}, +) where {P<:IEEEFloat} + N = P(2) / P(length(X.x)) .* (X.x - Y.x) + + function FluxMSE_pullback(dloss::P) + # adjoints got by VJP reverse pass equations. + temp = N .* dloss + @. X.dx += temp + @. Y.dx -= temp + return NoRData(), NoRData(), NoRData() + end + + # in forward pass it returns codual float64, hence coduals dx is NoFData(). + return CoDual(Losses.mse(X.x, Y.x), NoFData()), FluxMSE_pullback +end + +function generate_hand_written_rrule!!_test_cases(rng_ctor, ::Val{:linear_algebra}) + # Testing specific floating point precisions as FDM is unstable for certain tests. + # Larger differences can compare well with AD for higher precisions as FDM is relatively stable. + # for smaller differences we get worse FDM gradients for all floating points as FDM error and instability scales + # first test case success starts at a difference of ~ 1e4 + + test_cases = vcat( + map([Float64]) do P + return ( + false, :none, nothing, Losses.mse, P.([1e1, 1e2, 1e3]), P.([1e3, 1e4, 0]) + ) + end, + map([Float16, Float32, Float64]) do P + return ( + true, + :none, + nothing, + Losses.mse, + P.([1e-3, 1e-4, 0]), + P.([1e-1, 1e-2, 1e-3]),
Could you explain why such small numbers are being used here? Rather than e.g. just sampling them via `randn`?
Mooncake.jl
github_2023
others
514
compintell
willtebbutt
@@ -0,0 +1,40 @@ +using Pkg +Pkg.activate(@__DIR__) +Pkg.develop(; path=joinpath(@__DIR__, "..", "..", "..")) + +using Mooncake, StableRNGs, Test +using Flux: Losses +using Mooncake.TestUtils: test_rule + +@testset "flux" begin + @testset "$f, $(typeof(fargs))" for ( + interface_only, perf_flag, is_primitive, f, fargs... + ) in vcat( + # Testing specific floating point precisions as FDM is unstable for certain tests. + # Larger differences can compare well with AD for for higher precisions as FDM is relatively stable. + # for smaller differences we start getting better FDM gradients for smaller floating points. + + map([Float64]) do P + return ( + false, :none, false, Losses.mse, P.([1e1, 1e2, 1e3]), P.([1e3, 1e4, 0])
```suggestion false, :none, true, Losses.mse, randn(StableRNG(1), P, 3), randn(StableRNG(2), P, 3)) ``` Since this is now a primitive, we should tweak the corresponding flag to ensure that the `test_rule` checks to see whether it's hitting the primitive. The same applies to the other test cases in this file. Also, I'd really recommend just generating random numbers here, but using a seeded `StableRNG`, in order to be consistent with the other tests in this package. The same line of reasoning applies to the other test cases in this file. Incidentally, it looks like this extension isn't loading properly (see the Flux extension). I suspect that CI will pick up on this once you change the `is_primitive` flag to `true`.
Mooncake.jl
github_2023
others
514
compintell
willtebbutt
@@ -0,0 +1,29 @@ +module MooncakeFluxExt + +using Mooncake, Flux +using Base: IEEEFloat +import Mooncake: + DefaultCtx, rrule!!, @is_primitive, @mooncake_overlay, CoDual, zero_fcodual, NoRData
```suggestion DefaultCtx, rrule!!, @is_primitive, CoDual, zero_fcodual, NoRData ``` Unless I'm mistaken, mooncake_overlays aren't being used here.
Mooncake.jl
github_2023
others
514
compintell
willtebbutt
@@ -0,0 +1,28 @@ +module MooncakeFluxExt + +using Mooncake, Flux +using Base: IEEEFloat +import Mooncake: DefaultCtx, rrule!!, @is_primitive, CoDual, zero_fcodual, NoRData + +@is_primitive DefaultCtx Tuple{ + typeof(Flux.Losses.mse),Array{P},Array{P} +} where {P<:IEEEFloat} + +function rrule!!( + ::CoDual{typeof(Flux.Losses.mse)}, X::CoDual{<:Array{P}}, Y::CoDual{<:Array{P}} +) where {P<:IEEEFloat} + norm_factor = P(2) / P(length(X.x)) .* (X.x .- Y.x) + + function flux_mse_pullback(dloss::P) + # adjoints got by VJP reverse pass equations. + temp = norm_factor .* dloss + @. X.dx += temp + @. Y.dx -= temp + return NoRData(), NoRData(), NoRData() + end + + # in forward pass it returns codual float64, hence coduals dx is NoFData().
```suggestion ``` I think this comment can go, since the line below it no longer contains a `NoFData` directly.
Mooncake.jl
github_2023
others
514
compintell
willtebbutt
@@ -0,0 +1,29 @@ +using Pkg +Pkg.activate(@__DIR__) +Pkg.develop(; path=joinpath(@__DIR__, "..", "..", "..")) + +using Mooncake, StableRNGs, Test, Flux +using Mooncake.TestUtils: test_rule + +@testset "flux" begin + @testset "$f, $(typeof(fargs))" for ( + interface_only, perf_flag, is_primitive, f, fargs... + ) in vcat( + # Testing specific floating point precisions as FDM is unstable for certain tests. + # Larger differences can compare well with AD only for higher precisions as FDM is relatively stable. + # for smaller differences we start getting better FDM gradients for smaller floating points as well. +
```suggestion ``` Can this comment also go now that we're not changing how we choose the input vector depending on the precision?
Mooncake.jl
github_2023
others
514
compintell
willtebbutt
@@ -0,0 +1,29 @@ +using Pkg +Pkg.activate(@__DIR__) +Pkg.develop(; path=joinpath(@__DIR__, "..", "..", "..")) + +using Mooncake, StableRNGs, Test, Flux +using Mooncake.TestUtils: test_rule + +@testset "flux" begin + @testset "$f, $(typeof(fargs))" for ( + interface_only, perf_flag, is_primitive, f, fargs... + ) in vcat( + # Testing specific floating point precisions as FDM is unstable for certain tests. + # Larger differences can compare well with AD only for higher precisions as FDM is relatively stable. + # for smaller differences we start getting better FDM gradients for smaller floating points as well. + + map([Float32, Float64]) do P + return ( + false, + :none, + false,
```suggestion true, ``` I think maybe this still needs to be changed to `true`?
Mooncake.jl
github_2023
others
514
compintell
willtebbutt
@@ -0,0 +1,29 @@ +using Pkg +Pkg.activate(@__DIR__) +Pkg.develop(; path=joinpath(@__DIR__, "..", "..", "..")) + +using Mooncake, StableRNGs, Test, Flux +using Mooncake.TestUtils: test_rule + +@testset "flux" begin + @testset "$f, $(typeof(fargs))" for ( + interface_only, perf_flag, is_primitive, f, fargs... + ) in vcat( + # Testing specific floating point precisions as FDM is unstable for certain tests. + # Larger differences can compare well with AD only for higher precisions as FDM is relatively stable. + # for smaller differences we start getting better FDM gradients for smaller floating points as well. + + map([Float32, Float64]) do P + return ( + false, + :none,
```suggestion :stability, ``` Could we please change this flag so that we always check that the code is type-stable? (it definitely looks like it ought to be, but best to be sure).
Mooncake.jl
github_2023
others
514
compintell
willtebbutt
@@ -1,3 +1,3 @@ @testset "linear_algebra" begin TestUtils.run_rrule!!_test_cases(StableRNG, Val(:linear_algebra)) -end +end
```suggestion end ``` Do you know what has changed here? Would be good to get this out of the diff.
Mooncake.jl
github_2023
others
514
compintell
willtebbutt
@@ -0,0 +1,28 @@ +module MooncakeFluxExt + +using Mooncake, Flux +using Base: IEEEFloat +import Mooncake: DefaultCtx, rrule!!, @is_primitive, CoDual, zero_fcodual, NoRData + +@is_primitive DefaultCtx Tuple{ + typeof(Flux.Losses.mse),Array{P},Array{P} +} where {P<:IEEEFloat} + +function rrule!!( + ::CoDual{typeof(Flux.Losses.mse)}, X::CoDual{<:Array{P}}, Y::CoDual{<:Array{P}} +) where {P<:IEEEFloat} + norm_factor = P(2) / P(length(X.x)) .* (X.x .- Y.x) + + function flux_mse_pullback(dloss::P) + # adjoints got by VJP reverse pass equations. + temp = norm_factor .* dloss + @. X.dx += temp + @. Y.dx -= temp + return NoRData(), NoRData(), NoRData() + end + + # in forward pass it returns codual float64, hence coduals dx is NoFData(). + return zero_fcodual(Flux.Losses.mse(X.x, Y.x)), flux_mse_pullback +end + +end
```suggestion end ``` I think we maybe need a newline at the end of this file to make github happy.
Mooncake.jl
github_2023
others
514
compintell
willtebbutt
@@ -49,6 +51,7 @@ ChainRulesCore = "1" DiffRules = "1" DiffTests = "0.1" ExprTools = "0.1" +Flux = "0.15.2"
I just dev-ed Flux locally, and it looks like there's a new version, 0.16.3 available. Is there a reason we're pinning ourselves to an old patch version of Flux here, or could we update to the latest version?
Mooncake.jl
github_2023
others
514
compintell
willtebbutt
@@ -0,0 +1,28 @@ +module MooncakeFluxExt + +using Mooncake, Flux +using Base: IEEEFloat +import Mooncake: DefaultCtx, rrule!!, @is_primitive, CoDual, zero_fcodual, NoRData + +@is_primitive DefaultCtx Tuple{ + typeof(Flux.Losses.mse),Array{P},Array{P} +} where {P<:IEEEFloat} + +function rrule!!( + ::CoDual{typeof(Flux.Losses.mse)}, X::CoDual{<:Array{P}}, Y::CoDual{<:Array{P}} +) where {P<:IEEEFloat} + norm_factor = P(2) / P(length(X.x)) .* (X.x .- Y.x) + + function flux_mse_pullback(dloss::P) + # adjoints got by VJP reverse pass equations. + temp = norm_factor .* dloss + @. X.dx += temp + @. Y.dx -= temp
```suggestion tmp = dloss * P(2 / length(X.x)) @inbounds for n in eachindex(X.x) d = X.x[n] - Y.x[n] X.dx[n] += tmp * d Y.dx[n] -= tmp * d end ``` I did some benchmarking locally, and I think this might be the best way to implement the reverse-pass. It avoids creating a new `Array{P}`, and still only loads the memory from each of the arrays involved into memory a single time. Could you let me know whether you are also seeing that this gives better performance than the current implementation?
Mooncake.jl
github_2023
others
514
compintell
willtebbutt
@@ -0,0 +1,31 @@ +module MooncakeFluxExt + +using Mooncake, Flux +using Base: IEEEFloat +import Mooncake: DefaultCtx, rrule!!, @is_primitive, CoDual, zero_fcodual, NoRData + +@is_primitive DefaultCtx Tuple{ + typeof(Flux.Losses.mse),Array{P},Array{P} +} where {P<:IEEEFloat} + +function rrule!!( + ::CoDual{typeof(Flux.Losses.mse)}, X::CoDual{<:Array{P}}, Y::CoDual{<:Array{P}} +) where {P<:IEEEFloat} + norm_factor = P(2) / P(length(X.x)) .* (X.x .- Y.x)
```suggestion ```
Mooncake.jl
github_2023
others
514
compintell
yebai
@@ -0,0 +1,29 @@ +module MooncakeFluxExt + +using Mooncake, Flux +using Base: IEEEFloat +import Mooncake: DefaultCtx, rrule!!, @is_primitive, CoDual, zero_fcodual, NoRData + +@is_primitive DefaultCtx Tuple{ + typeof(Flux.Losses.mse),Array{P},Array{P} +} where {P<:IEEEFloat} + +function rrule!!(
```suggestion # This is a performance-specific rule motivated by https://github.com/compintell/Mooncake.jl/issues/466 function rrule!!( ```
Mooncake.jl
github_2023
others
512
compintell
yebai
@@ -1,7 +1,47 @@ -# See the docstring for `BBCode` for some context on this file. +""" + module BBCode
Gemini [suggests](https://g.co/gemini/share/261dc2571263) ```suggestion module BasicBlockIR ```
Mooncake.jl
github_2023
others
512
compintell
yebai
@@ -1,7 +1,72 @@ -# See the docstring for `BBCode` for some context on this file. +""" + module BBCode
```suggestion module BasicBlockCode ```
Mooncake.jl
github_2023
others
477
compintell
willtebbutt
@@ -141,33 +141,27 @@ include("interface.jl") include("config.jl") include("developer_tools.jl") -export primal, - tangent, - randn_tangent, - increment!!, - NoTangent, - Tangent, - MutableTangent, - PossiblyUninitTangent, - set_to_zero!!, - tangent_type, - zero_tangent, - _scale, - _add_to_primal, - _diff, - _dot, - zero_codual, - codual_type, - rrule!!, - build_rrule, - value_and_gradient!!, - value_and_pullback!!, - NoFData, - NoRData, - fdata_type, - rdata_type, - fdata, - rdata, - get_interpreter +# Public, not exported + +include("public.jl") + +@public set_to_zero!!, increment!! +@public get_interpreter +@public zero_adjoint, var"@zero_adjoint" +@public is_primitive, build_primitive_rrule +@public var"@mooncake_overlay", var"@from_rrule" +@public Config + +# Public, exported + +export CoDual, codual_type, zero_codual +export primal
```suggestion ```
Mooncake.jl
github_2023
others
477
compintell
willtebbutt
@@ -141,33 +141,27 @@ include("interface.jl") include("config.jl") include("developer_tools.jl") -export primal, - tangent, - randn_tangent, - increment!!, - NoTangent, - Tangent, - MutableTangent, - PossiblyUninitTangent, - set_to_zero!!, - tangent_type, - zero_tangent, - _scale, - _add_to_primal, - _diff, - _dot, - zero_codual, - codual_type, - rrule!!, - build_rrule, - value_and_gradient!!, - value_and_pullback!!, - NoFData, - NoRData, - fdata_type, - rdata_type, - fdata, - rdata, - get_interpreter +# Public, not exported + +include("public.jl") + +@public set_to_zero!!, increment!! +@public get_interpreter +@public zero_adjoint, var"@zero_adjoint" +@public is_primitive, build_primitive_rrule +@public var"@mooncake_overlay", var"@from_rrule" +@public Config + +# Public, exported + +export CoDual, codual_type, zero_codual +export primal +export Tangent, MutableTangent, PossiblyUninitTangent, NoTangent +export tangent_type, tangent, zero_tangent
```suggestion export tangent_type ```
Mooncake.jl
github_2023
others
477
compintell
willtebbutt
@@ -141,33 +141,27 @@ include("interface.jl") include("config.jl") include("developer_tools.jl") -export primal, - tangent, - randn_tangent, - increment!!, - NoTangent, - Tangent, - MutableTangent, - PossiblyUninitTangent, - set_to_zero!!, - tangent_type, - zero_tangent, - _scale, - _add_to_primal, - _diff, - _dot, - zero_codual, - codual_type, - rrule!!, - build_rrule, - value_and_gradient!!, - value_and_pullback!!, - NoFData, - NoRData, - fdata_type, - rdata_type, - fdata, - rdata, - get_interpreter +# Public, not exported + +include("public.jl") + +@public set_to_zero!!, increment!! +@public get_interpreter
```suggestion @public set_to_zero!!, increment!! ```
Mooncake.jl
github_2023
others
477
compintell
willtebbutt
@@ -141,33 +141,27 @@ include("interface.jl") include("config.jl") include("developer_tools.jl") -export primal, - tangent, - randn_tangent, - increment!!, - NoTangent, - Tangent, - MutableTangent, - PossiblyUninitTangent, - set_to_zero!!, - tangent_type, - zero_tangent, - _scale, - _add_to_primal, - _diff, - _dot, - zero_codual, - codual_type, - rrule!!, - build_rrule, - value_and_gradient!!, - value_and_pullback!!, - NoFData, - NoRData, - fdata_type, - rdata_type, - fdata, - rdata, - get_interpreter +# Public, not exported + +include("public.jl") + +@public set_to_zero!!, increment!! +@public get_interpreter +@public zero_adjoint, var"@zero_adjoint" +@public is_primitive, build_primitive_rrule +@public var"@mooncake_overlay", var"@from_rrule" +@public Config + +# Public, exported + +export CoDual, codual_type, zero_codual +export primal +export Tangent, MutableTangent, PossiblyUninitTangent, NoTangent +export tangent_type, tangent, zero_tangent +export NoFData, fdata_type, fdata +export NoRData, rdata_type, rdata +export rrule!!, build_rrule
```suggestion export rrule!! ```
Mooncake.jl
github_2023
others
477
compintell
willtebbutt
@@ -142,33 +142,11 @@ include("interface.jl") include("config.jl") include("developer_tools.jl") -export primal, - tangent, - randn_tangent, - increment!!, - NoTangent, - Tangent, - MutableTangent, - PossiblyUninitTangent, - set_to_zero!!, - tangent_type, - zero_tangent, - _scale, - _add_to_primal, - _diff, - _dot, - zero_codual, - codual_type, - rrule!!, - build_rrule, - value_and_gradient!!, - value_and_pullback!!, - NoFData, - NoRData, - fdata_type, - rdata_type, - fdata, - rdata, - get_interpreter +# Public, not exported +include("public.jl") +@public value_and_pullback!!, prepare_pullback_cache + +# Public, exported +export Config, value_and_gradient!!, prepare_gradient_cache
Very good point. No, we almost certainly do not.
Mooncake.jl
github_2023
others
477
compintell
willtebbutt
@@ -142,33 +142,11 @@ include("interface.jl") include("config.jl") include("developer_tools.jl") -export primal, - tangent, - randn_tangent, - increment!!, - NoTangent, - Tangent, - MutableTangent, - PossiblyUninitTangent, - set_to_zero!!, - tangent_type, - zero_tangent, - _scale, - _add_to_primal, - _diff, - _dot, - zero_codual, - codual_type, - rrule!!, - build_rrule, - value_and_gradient!!, - value_and_pullback!!, - NoFData, - NoRData, - fdata_type, - rdata_type, - fdata, - rdata, - get_interpreter +# Public, not exported +include("public.jl") +@public value_and_pullback!!, prepare_pullback_cache +
Why is it that DI needs `zero_tangent`? I know that it need `tangent_type` to check whether the user has provided the correct thing before calling `Mooncake.value_and_pullback!!`, but I'm not sure why we need `zero_tangent`.
Mooncake.jl
github_2023
others
477
compintell
willtebbutt
@@ -0,0 +1,14 @@ +# Interface + +This is the public interface that day-to-day users of AD are expected to interact with if +for some reason DifferentiationInterface.jl does not suffice. +If you have not tried using Mooncake.jl via DifferentiationInterface.jl, please do so. +See [Tutorial](@ref) for more info. + +```@docs; canonical=false
Right you are. I had to apply a filter to handle the unexported bits of the public interface, but I think I've now got it working.
Mooncake.jl
github_2023
others
496
compintell
willtebbutt
@@ -24,6 +24,8 @@ end const MatrixOrView{T} = Union{Matrix{T},SubArray{T,2,<:Array{T}}} const VecOrView{T} = Union{Vector{T},SubArray{T,1,<:Array{T}}} const BlasRealFloat = Union{Float32,Float64} +const BlasComplexFloat = Union{ComplexF32,ComplexF64} +const BlasRealOrComplexFloat = Union{BlasRealFloat,BlasComplexFloat}
I think this is equal to `BLAS.BlasFloat`, so maybe just import that [here](https://github.com/compintell/Mooncake.jl/blob/6c99c65600345800ba07829683cd469494eeed6c/src/Mooncake.jl#L46)?
Mooncake.jl
github_2023
others
496
compintell
willtebbutt
@@ -36,6 +38,11 @@ function arrayify(x::CoDual{A}) where {A<:AbstractArray{<:BlasRealFloat}} return arrayify(primal(x), tangent(x))::Tuple{A,A} end arrayify(x::Array{P}, dx::Array{P}) where {P<:BlasRealFloat} = (x, dx) + +function arrayify(x::CoDual{A}) where {A<:AbstractArray{<:Union{ComplexF32, ComplexF64}}} + return arrayify(primal(x), tangent(x)) +end
```suggestion ``` I think it should be fine to just change the element types permitted in the existing method of `arrayify` which accepts `CoDual`s from `BlasRealFloat` to `BlasFloat`.
Mooncake.jl
github_2023
others
496
compintell
willtebbutt
@@ -36,6 +38,11 @@ function arrayify(x::CoDual{A}) where {A<:AbstractArray{<:BlasRealFloat}} return arrayify(primal(x), tangent(x))::Tuple{A,A} end arrayify(x::Array{P}, dx::Array{P}) where {P<:BlasRealFloat} = (x, dx) + +function arrayify(x::CoDual{A}) where {A<:AbstractArray{<:Union{ComplexF32, ComplexF64}}} + return arrayify(primal(x), tangent(x)) +end +arrayify(x::Array{P}, dx::Array{<:Tangent}) where P<:Union{ComplexF32, ComplexF64} = x, reinterpret(P, dx)
```suggestion arrayify(x::Array{P}, dx::Array{<:Tangent}) where P<:BlasComplexFloat = x, reinterpret(P, dx) ```
Mooncake.jl
github_2023
others
496
compintell
willtebbutt
@@ -299,6 +306,51 @@ function rrule!!( return y_dy, symv!_adjoint end +@is_primitive( + MinimalCtx, + Tuple{ + typeof(BLAS.nrm2), + Int, + X, + Int, + } where {T<:Union{Float64, Float32, ComplexF64, ComplexF32}, X<:Union{Ptr{T},AbstractArray{T}}},
```suggestion } where {T<:BlasFloat, X<:Union{Ptr{T},AbstractArray{T}}}, ```
Mooncake.jl
github_2023
others
496
compintell
willtebbutt
@@ -299,6 +306,51 @@ function rrule!!( return y_dy, symv!_adjoint end +@is_primitive( + MinimalCtx, + Tuple{ + typeof(BLAS.nrm2), + Int, + X, + Int, + } where {T<:Union{Float64, Float32, ComplexF64, ComplexF32}, X<:Union{Ptr{T},AbstractArray{T}}}, +) +function rrule!!( + ::CoDual{typeof(BLAS.nrm2)}, + n::CoDual{<:Integer}, + X_dX::CoDual{<:Union{Ptr{T},AbstractArray{T}} where {T<:Union{Float64, Float32, ComplexF64, ComplexF32}}},
```suggestion X_dX::CoDual{<:Union{Ptr{T},AbstractArray{T}} where {T<:BlasFloat}}, ```
Mooncake.jl
github_2023
others
496
compintell
willtebbutt
@@ -299,6 +306,51 @@ function rrule!!( return y_dy, symv!_adjoint end +@is_primitive( + MinimalCtx, + Tuple{ + typeof(BLAS.nrm2), + Int, + X, + Int, + } where {T<:Union{Float64, Float32, ComplexF64, ComplexF32}, X<:Union{Ptr{T},AbstractArray{T}}}, +) +function rrule!!( + ::CoDual{typeof(BLAS.nrm2)}, + n::CoDual{<:Integer}, + X_dX::CoDual{<:Union{Ptr{T},AbstractArray{T}} where {T<:Union{Float64, Float32, ComplexF64, ComplexF32}}}, + incx::CoDual{<:Integer}, +) + X, dX = arrayify(X_dX) + y = BLAS.nrm2(n.x, X, incx.x) + function nrm2_pb!!(dy) + view(dX, 1:incx.x:incx.x*n.x) .+= view(X, 1:incx.x:incx.x*n.x) .* (dy / y) + return NoRData(), NoRData(), NoRData(), NoRData() + end + return CoDual(y, NoFData()), nrm2_pb!! +end + +@is_primitive( + MinimalCtx, + Tuple{ + typeof(BLAS.nrm2), + X, + } where {T<:Union{Float64, Float32, ComplexF64, ComplexF32}, X<:Union{Ptr{T},AbstractArray{T}}},
```suggestion } where {T<:BlasFloat, X<:Union{Ptr{T},AbstractArray{T}}}, ```
Mooncake.jl
github_2023
others
496
compintell
willtebbutt
@@ -299,6 +306,51 @@ function rrule!!( return y_dy, symv!_adjoint end +@is_primitive( + MinimalCtx, + Tuple{ + typeof(BLAS.nrm2), + Int, + X, + Int, + } where {T<:Union{Float64, Float32, ComplexF64, ComplexF32}, X<:Union{Ptr{T},AbstractArray{T}}}, +) +function rrule!!( + ::CoDual{typeof(BLAS.nrm2)}, + n::CoDual{<:Integer}, + X_dX::CoDual{<:Union{Ptr{T},AbstractArray{T}} where {T<:Union{Float64, Float32, ComplexF64, ComplexF32}}}, + incx::CoDual{<:Integer}, +) + X, dX = arrayify(X_dX) + y = BLAS.nrm2(n.x, X, incx.x) + function nrm2_pb!!(dy) + view(dX, 1:incx.x:incx.x*n.x) .+= view(X, 1:incx.x:incx.x*n.x) .* (dy / y) + return NoRData(), NoRData(), NoRData(), NoRData() + end + return CoDual(y, NoFData()), nrm2_pb!! +end + +@is_primitive( + MinimalCtx, + Tuple{ + typeof(BLAS.nrm2), + X, + } where {T<:Union{Float64, Float32, ComplexF64, ComplexF32}, X<:Union{Ptr{T},AbstractArray{T}}}, +) +function rrule!!( + ::CoDual{typeof(BLAS.nrm2)}, + X_dX::CoDual{<:Union{Ptr{T},AbstractArray{T}} where {T<:Union{Float64, Float32, ComplexF64, ComplexF32}}},
```suggestion X_dX::CoDual{<:Union{Ptr{T},AbstractArray{T}} where {T<:BlasFloat}}, ```
Mooncake.jl
github_2023
others
496
compintell
willtebbutt
@@ -755,7 +807,7 @@ for (trsm, elty) in ((:dtrsm_, :Float64), (:strsm_, :Float32)) end end -function blas_matrices(rng::AbstractRNG, P::Type{<:BlasRealFloat}, p::Int, q::Int) +function blas_matrices(rng::AbstractRNG, P::Type{<:BlasRealOrComplexFloat}, p::Int, q::Int)
```suggestion function blas_matrices(rng::AbstractRNG, P::Type{<:BlasFloat}, p::Int, q::Int) ```
Mooncake.jl
github_2023
others
496
compintell
willtebbutt
@@ -767,7 +819,7 @@ function blas_matrices(rng::AbstractRNG, P::Type{<:BlasRealFloat}, p::Int, q::In return Xs end -function blas_vectors(rng::AbstractRNG, P::Type{<:BlasRealFloat}, p::Int) +function blas_vectors(rng::AbstractRNG, P::Type{<:BlasRealOrComplexFloat}, p::Int)
```suggestion function blas_vectors(rng::AbstractRNG, P::Type{<:BlasFloat}, p::Int) ```
Mooncake.jl
github_2023
others
496
compintell
willtebbutt
@@ -24,6 +24,8 @@ end const MatrixOrView{T} = Union{Matrix{T},SubArray{T,2,<:Array{T}}} const VecOrView{T} = Union{Vector{T},SubArray{T,1,<:Array{T}}} const BlasRealFloat = Union{Float32,Float64} +const BlasComplexFloat = Union{ComplexF32,ComplexF64} +const BlasRealOrComplexFloat = Union{BlasRealFloat,BlasComplexFloat} """ arrayify(x::CoDual{<:AbstractArray{<:BlasRealFloat}})
```suggestion arrayify(x::CoDual{<:AbstractArray{<:BlasFloat}}) ```
Mooncake.jl
github_2023
others
476
compintell
willtebbutt
@@ -2,15 +2,15 @@ [![Build Status](https://github.com/compintell/Mooncake.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/compintell/Mooncake.jl/actions/workflows/CI.yml?query=branch%3Amain) [![codecov](https://codecov.io/github/compintell/Mooncake.jl/graph/badge.svg?token=NUPWTB4IAP)](https://codecov.io/github/compintell/Mooncake.jl) -[![Code Style: Blue](https://img.shields.io/badge/code%20style-blue-4495d1.svg)](https://github.com/invenia/BlueStyle) +[![Code Style: Blue](https://img.shields.io/badge/code%20style-blue-4495d1.svg)](https://github.com/JuliaDiff/BlueStyle) [![ColPrac: Contributor's Guide on Collaborative Practices for Community Packages](https://img.shields.io/badge/ColPrac-Contributor's%20Guide-blueviolet)](https://github.com/SciML/ColPrac) -[![](https://img.shields.io/badge/docs-blue.svg)](https://compintell.github.io/Mooncake.jl/dev) +[![Dev docs](https://img.shields.io/badge/docs-dev-blue.svg)](https://compintell.github.io/Mooncake.jl/dev)
```suggestion [![Docs](https://img.shields.io/badge/docs-dev-blue.svg)](https://compintell.github.io/Mooncake.jl/dev) ``` I'd rather not use stable vs dev docs in Mooncake's case, because we should never have anything on main that hasn't been released. Do you think we need to call them dev docs anyway?
Mooncake.jl
github_2023
others
476
compintell
willtebbutt
@@ -0,0 +1,125 @@ +# Tutorial + +There are two ways to compute gradients with Mooncake.jl: + +- through the standardized [DifferentiationInterface.jl](https://github.com/JuliaDiff/DifferentiationInterface.jl) API +- through the native Mooncake.jl API + +We recommend the former to start with, especially if you want to experiment with other automatic differentiation packages. + +```@example tuto +import DifferentiationInterface as DI +import Mooncake +``` + +## DifferentiationInterface.jl API + +DifferentiationInterface.jl (or DI for short) provides a common entry point for every automatic differentiation package in Julia. +To specify that you want to use Mooncake.jl, just create the right "backend" object (with an optional [`Mooncake.Config`](@ref)): + +```@example tuto +backend = DI.AutoMooncake(; config=nothing) +``` + +This object is actually defined by a third package called [ADTypes.jl](https://github.com/SciML/ADTypes.jl), but re-exported by DI. + +### Single argument + +Suppose you want to differentiate the following function + +```@example tuto +f(x) = sum(abs2, x) +``` + +on the following input + +```@example tuto +x = float.(1:3) +``` + +The naive way is to simply call [`DI.gradient`](@extref DifferentiationInterface.gradient): + +```@example tuto +DI.gradient(f, backend, x) # slow, do not do this +``` + +This returns the correct gradient, but it is very slow because it includes the time taken by Mooncake.jl to compute a differentiation rule for `f` (see [Mooncake.jl's Rule System](@ref)). +If you anticipate you will need more than one gradient, it is better to call [`DI.prepare_gradient`](@extref DifferentiationInterface.prepare_gradient) on a typical (e.g. random) input first: + +```@example tuto +typical_x = rand(3) +prep = DI.prepare_gradient(f, backend, typical_x) +``` + +The typical input should have the same size and type as the actual inputs we will provide later on. +As for the contents of the preparation result, they do not matter. +What matters is that it captures everything you need for `DI.gradient` to be fast: + +```@example tuto +DI.gradient(f, prep, backend, x) # fast +``` + +For optimal speed, you can provide storage space for the gradient and call [`DI.gradient!`](@extref DifferentiationInterface.gradient!) instead: + +```@example tuto +grad = similar(x) +DI.gradient!(f, grad, prep, backend, x) # very fast +``` + +If you also need the value of the function, check out [`DI.value_and_gradient`](@extref DifferentiationInterface.value_and_gradient) or [`DI.value_and_gradient!`](@extref DifferentiationInterface.value_and_gradient!): + +```@example tuto +DI.value_and_gradient(f, prep, backend, x) +``` + +### Multiple arguments + +What should you do if your function takes more than one input argument? +Well, DI can still handle it, _assuming that you only want the derivative with respect to one of them_ (the first one, by convention). +For instance, consider the function + +```@example tuto +g(x, a, b) = a * f(x) + b +``` + +You can easily compute the gradient with respect to `x`, while keeping `a` and `b` fixed. +To do that, just wrap these two arguments inside [`DI.Constant`](@extref DifferentiationInterface.Constant), like so: + +```@example tuto +typical_a, typical_b = 1.0, 1.0 +prep = DI.prepare_gradient(g, backend, typical_x, DI.Constant(typical_a), DI.Constant(typical_b)) + +a, b = 42.0, 3.14 +DI.value_and_gradient(g, prep, backend, x, DI.Constant(a), DI.Constant(b)) +``` + +Note that this works even when you change the value of `a` or `b` (those are not baked into the preparation result). + +If one of your additional arguments behaves like a scratch space in memory (instead of a meaningful constant), you can use [`DI.Cache`](@extref DifferentiationInterface.Cache) instead. + +Now what if you care about the derivatives with respect to every argument? +You can always go back to the single-argument case by putting everything inside a tuple: + +```@example tuto +g_tup(xab) = xab[2] * f(xab[1]) + xab[3] +prep = DI.prepare_gradient(g_tup, backend, (typical_x, typical_a, typical_b)) +DI.value_and_gradient(g_tup, prep, backend, (x, a, b)) +``` + +Another, perhaps more natural alternative, is to use the native API of Mooncake.jl.
```suggestion You can also use the native API of Mooncake.jl, discussed below. ``` I don't think that it's really more natural to use the Mooncake.jl API -- I'm perfectly happy to really suggest to users that they use DI.jl.
Mooncake.jl
github_2023
others
457
compintell
willtebbutt
@@ -409,36 +410,110 @@ This "vector-Jacobian product" expression is commonly used to explain AD, and is # Directional Derivatives and Gradients -Now we turn to using reverse-mode AD to compute the gradient of a function. -In short, given a function ``g : \mathcal{X} \to \RR`` with derivative ``D g [x]`` at ``x``, its gradient is equal to ``D g [x]^\ast (1)``. -We explain why in this section. +Now we turn to using forwards- and reverse-mode AD to compute the gradient of a function. -The derivative discussed here can be used to compute directional derivatives. -Consider a function ``f : \mathcal{X} \to \RR`` with Frechet derivative ``D f [x] : \mathcal{X} \to \RR`` at ``x \in \mathcal{X}``. -Then ``D f[x](\dot{x})`` returns the directional derivative in direction ``\dot{x}``. +Recall that if ``D f[x] : \mathcal{X} \to \mathbb{R}`` is the Frechet derivative discussed here then ``D f[x](\dot{x})`` is the _directional derivative_ in the ``\dot{x}`` direction. -Gradients are closely related to the adjoint of the derivative. -Recall that the gradient of ``f`` at ``x`` is defined to be the vector ``\nabla f (x) \in \mathcal{X}`` such that ``\langle \nabla f (x), \dot{x} \rangle`` gives the directional derivative of ``f`` at ``x`` in direction ``\dot{x}``. -Having noted that ``D f[x](\dot{x})`` is exactly this directional derivative, we can equivalently say that +The _gradient_ of ``f : \mathcal{X} \to \mathbb{R}`` at ``x`` is defined to be the vector ``\nabla f (x) \in \mathcal{X}`` such that ```math -D f[x](\dot{x}) = \langle \nabla f (x), \dot{x} \rangle . +\langle \nabla f (x), \dot{x} \rangle = D f[x](\dot{x}) ``` +for any direction ``\dot{x}``. +In other words, the vector ``\nabla f`` encodes all the information about the directional derivatives of ``f``, and we use the inner product to retrieve each one. -The role of the adjoint is revealed when we consider ``f := \mathcal{l} \circ g``, where ``g : \mathcal{X} \to \mathcal{Y}``, ``\mathcal{l}(y) := \langle \bar{y}, y \rangle``, and ``\bar{y} \in \mathcal{Y}`` is some fixed vector. -Noting that ``D \mathcal{l} [y](\dot{y}) = \langle \bar{y}, \dot{y} \rangle``, we apply the chain rule to obtain +An alternative characterisation is that ``\nabla f(x)`` is the vector pointing in the direction of steepest ascent on ``f`` at ``x``, with magnitude equal to the directional derivative in that steepest direction.
I think I'm not quite clear what is meant by `with magnitude equal to the directional derivative in that steepest direction.` -- is there a precise mathematical statement by which you can explain what this means?
Mooncake.jl
github_2023
others
457
compintell
willtebbutt
@@ -409,36 +410,110 @@ This "vector-Jacobian product" expression is commonly used to explain AD, and is # Directional Derivatives and Gradients -Now we turn to using reverse-mode AD to compute the gradient of a function. -In short, given a function ``g : \mathcal{X} \to \RR`` with derivative ``D g [x]`` at ``x``, its gradient is equal to ``D g [x]^\ast (1)``. -We explain why in this section. +Now we turn to using forwards- and reverse-mode AD to compute the gradient of a function. -The derivative discussed here can be used to compute directional derivatives. -Consider a function ``f : \mathcal{X} \to \RR`` with Frechet derivative ``D f [x] : \mathcal{X} \to \RR`` at ``x \in \mathcal{X}``. -Then ``D f[x](\dot{x})`` returns the directional derivative in direction ``\dot{x}``. +Recall that if ``D f[x] : \mathcal{X} \to \mathbb{R}`` is the Frechet derivative discussed here then ``D f[x](\dot{x})`` is the _directional derivative_ in the ``\dot{x}`` direction. -Gradients are closely related to the adjoint of the derivative. -Recall that the gradient of ``f`` at ``x`` is defined to be the vector ``\nabla f (x) \in \mathcal{X}`` such that ``\langle \nabla f (x), \dot{x} \rangle`` gives the directional derivative of ``f`` at ``x`` in direction ``\dot{x}``. -Having noted that ``D f[x](\dot{x})`` is exactly this directional derivative, we can equivalently say that +The _gradient_ of ``f : \mathcal{X} \to \mathbb{R}`` at ``x`` is defined to be the vector ``\nabla f (x) \in \mathcal{X}`` such that ```math -D f[x](\dot{x}) = \langle \nabla f (x), \dot{x} \rangle . +\langle \nabla f (x), \dot{x} \rangle = D f[x](\dot{x}) ``` +for any direction ``\dot{x}``. +In other words, the vector ``\nabla f`` encodes all the information about the directional derivatives of ``f``, and we use the inner product to retrieve each one. -The role of the adjoint is revealed when we consider ``f := \mathcal{l} \circ g``, where ``g : \mathcal{X} \to \mathcal{Y}``, ``\mathcal{l}(y) := \langle \bar{y}, y \rangle``, and ``\bar{y} \in \mathcal{Y}`` is some fixed vector. -Noting that ``D \mathcal{l} [y](\dot{y}) = \langle \bar{y}, \dot{y} \rangle``, we apply the chain rule to obtain +An alternative characterisation is that ``\nabla f(x)`` is the vector pointing in the direction of steepest ascent on ``f`` at ``x``, with magnitude equal to the directional derivative in that steepest direction. + +_**Aside: The choice of inner product**_ + +Notice that the value of the gradient depends on how the inner product on ``\mathcal{X}`` is defined. +Indeed, different choices of inner product result in different values of ``\nabla f``. +Adjoints such as ``D f[x]^*`` are also inner product dependent. +However, the actual derivative ``D f[x]`` is of course invariant -- it makes no reference to the inner product.
Is this correct, technically? We make use of the norms for both X and Y in the definition of the Frechet derivative, which I've been assuming we take to be the norms induced by whichever inner products we pick on X and Y. Would it be more accurate to point out that the definition is invariant because all norms in are equivalent in finite dimensions?
Mooncake.jl
github_2023
others
457
compintell
willtebbutt
@@ -409,36 +410,110 @@ This "vector-Jacobian product" expression is commonly used to explain AD, and is # Directional Derivatives and Gradients -Now we turn to using reverse-mode AD to compute the gradient of a function. -In short, given a function ``g : \mathcal{X} \to \RR`` with derivative ``D g [x]`` at ``x``, its gradient is equal to ``D g [x]^\ast (1)``. -We explain why in this section. +Now we turn to using forwards- and reverse-mode AD to compute the gradient of a function. -The derivative discussed here can be used to compute directional derivatives. -Consider a function ``f : \mathcal{X} \to \RR`` with Frechet derivative ``D f [x] : \mathcal{X} \to \RR`` at ``x \in \mathcal{X}``. -Then ``D f[x](\dot{x})`` returns the directional derivative in direction ``\dot{x}``. +Recall that if ``D f[x] : \mathcal{X} \to \mathbb{R}`` is the Frechet derivative discussed here then ``D f[x](\dot{x})`` is the _directional derivative_ in the ``\dot{x}`` direction. -Gradients are closely related to the adjoint of the derivative. -Recall that the gradient of ``f`` at ``x`` is defined to be the vector ``\nabla f (x) \in \mathcal{X}`` such that ``\langle \nabla f (x), \dot{x} \rangle`` gives the directional derivative of ``f`` at ``x`` in direction ``\dot{x}``. -Having noted that ``D f[x](\dot{x})`` is exactly this directional derivative, we can equivalently say that +The _gradient_ of ``f : \mathcal{X} \to \mathbb{R}`` at ``x`` is defined to be the vector ``\nabla f (x) \in \mathcal{X}`` such that ```math -D f[x](\dot{x}) = \langle \nabla f (x), \dot{x} \rangle . +\langle \nabla f (x), \dot{x} \rangle = D f[x](\dot{x}) ``` +for any direction ``\dot{x}``. +In other words, the vector ``\nabla f`` encodes all the information about the directional derivatives of ``f``, and we use the inner product to retrieve each one. -The role of the adjoint is revealed when we consider ``f := \mathcal{l} \circ g``, where ``g : \mathcal{X} \to \mathcal{Y}``, ``\mathcal{l}(y) := \langle \bar{y}, y \rangle``, and ``\bar{y} \in \mathcal{Y}`` is some fixed vector. -Noting that ``D \mathcal{l} [y](\dot{y}) = \langle \bar{y}, \dot{y} \rangle``, we apply the chain rule to obtain +An alternative characterisation is that ``\nabla f(x)`` is the vector pointing in the direction of steepest ascent on ``f`` at ``x``, with magnitude equal to the directional derivative in that steepest direction. + +_**Aside: The choice of inner product**_ + +Notice that the value of the gradient depends on how the inner product on ``\mathcal{X}`` is defined. +Indeed, different choices of inner product result in different values of ``\nabla f``. +Adjoints such as ``D f[x]^*`` are also inner product dependent. +However, the actual derivative ``D f[x]`` is of course invariant -- it makes no reference to the inner product. + +In practice, Mooncake uses the Euclidean inner product, extended in the "obvious way" to other composite data types (that is, as if everything is flattened and embedded in ``\mathbb{R}^N``). +But we endeavour to keep the discussion general in order to make the role of the inner product explicit.
```suggestion In practice, Mooncake uses the Euclidean inner product, extended in the "obvious way" to other composite data types (that is, as if everything is flattened and embedded in ``\mathbb{R}^N``), but we endeavour to keep the discussion general in order to make the role of the inner product explicit. ``` grammar
Mooncake.jl
github_2023
others
457
compintell
willtebbutt
@@ -409,36 +410,110 @@ This "vector-Jacobian product" expression is commonly used to explain AD, and is # Directional Derivatives and Gradients -Now we turn to using reverse-mode AD to compute the gradient of a function. -In short, given a function ``g : \mathcal{X} \to \RR`` with derivative ``D g [x]`` at ``x``, its gradient is equal to ``D g [x]^\ast (1)``. -We explain why in this section. +Now we turn to using forwards- and reverse-mode AD to compute the gradient of a function. -The derivative discussed here can be used to compute directional derivatives. -Consider a function ``f : \mathcal{X} \to \RR`` with Frechet derivative ``D f [x] : \mathcal{X} \to \RR`` at ``x \in \mathcal{X}``. -Then ``D f[x](\dot{x})`` returns the directional derivative in direction ``\dot{x}``. +Recall that if ``D f[x] : \mathcal{X} \to \mathbb{R}`` is the Frechet derivative discussed here then ``D f[x](\dot{x})`` is the _directional derivative_ in the ``\dot{x}`` direction. -Gradients are closely related to the adjoint of the derivative. -Recall that the gradient of ``f`` at ``x`` is defined to be the vector ``\nabla f (x) \in \mathcal{X}`` such that ``\langle \nabla f (x), \dot{x} \rangle`` gives the directional derivative of ``f`` at ``x`` in direction ``\dot{x}``. -Having noted that ``D f[x](\dot{x})`` is exactly this directional derivative, we can equivalently say that +The _gradient_ of ``f : \mathcal{X} \to \mathbb{R}`` at ``x`` is defined to be the vector ``\nabla f (x) \in \mathcal{X}`` such that ```math -D f[x](\dot{x}) = \langle \nabla f (x), \dot{x} \rangle . +\langle \nabla f (x), \dot{x} \rangle = D f[x](\dot{x}) ``` +for any direction ``\dot{x}``. +In other words, the vector ``\nabla f`` encodes all the information about the directional derivatives of ``f``, and we use the inner product to retrieve each one. -The role of the adjoint is revealed when we consider ``f := \mathcal{l} \circ g``, where ``g : \mathcal{X} \to \mathcal{Y}``, ``\mathcal{l}(y) := \langle \bar{y}, y \rangle``, and ``\bar{y} \in \mathcal{Y}`` is some fixed vector. -Noting that ``D \mathcal{l} [y](\dot{y}) = \langle \bar{y}, \dot{y} \rangle``, we apply the chain rule to obtain +An alternative characterisation is that ``\nabla f(x)`` is the vector pointing in the direction of steepest ascent on ``f`` at ``x``, with magnitude equal to the directional derivative in that steepest direction. + +_**Aside: The choice of inner product**_ + +Notice that the value of the gradient depends on how the inner product on ``\mathcal{X}`` is defined. +Indeed, different choices of inner product result in different values of ``\nabla f``. +Adjoints such as ``D f[x]^*`` are also inner product dependent. +However, the actual derivative ``D f[x]`` is of course invariant -- it makes no reference to the inner product. + +In practice, Mooncake uses the Euclidean inner product, extended in the "obvious way" to other composite data types (that is, as if everything is flattened and embedded in ``\mathbb{R}^N``). +But we endeavour to keep the discussion general in order to make the role of the inner product explicit. + + + +#### Computing the gradient from forwards-mode + +To compute the gradient in forwards-mode, we need to evaluate the forwards pass ``\dim \mathcal{X}`` times. +We also need to refer to a basis ``\{\mathbf{e}_i\}`` of ``\mathcal{X}`` and its reciprocal basis ``\{\mathbf{e}^i\}`` defined by ``\langle \mathbf{e}_i, \mathbf{e}^j \rangle = \delta_i^j``. +(For any basis there exists such a reciprocal basis, and they are the same if the basis is orthonormal.) + +Equipped with such a pair of bases, we can always decompose a vector ``x = \sum_i x^i \mathbf{e}_i`` into its components ``x^i = \langle x, \mathbf{e}^i \rangle``. +Therefore, the gradient is given by ```math -\begin{align} -D f [x] (\dot{x}) &= [(D \mathcal{l} [g(x)]) \circ (D g [x])](\dot{x}) \nonumber \\ - &= \langle \bar{y}, D g [x] (\dot{x}) \rangle \nonumber \\ - &= \langle D g [x]^\ast (\bar{y}), \dot{x} \rangle, \nonumber -\end{align} +\nabla f(x) + = \sum_i \langle \nabla f(x), \mathbf{e}^i \rangle \mathbf{e}_i + = \sum_i D f[x](\mathbf{e}^i) \, \mathbf{e}_i ``` -from which we conclude that ``D g [x]^\ast (\bar{y})`` is the gradient of the composition ``l \circ g`` at ``x``. +where the second equality follows from the gradient's implicit definition.
```suggestion where the second equality follows from the gradient's definition. ``` Reading this, I briefly thought that we had multiple definitions of the gradient lying around, and the one you are using here is the "implicit" one, before realising you're just trying to point out that our definition of the gradient is implicit. I wonder if others might read it in the same way, meaning that it's better just to refer to the "gradient's definition"?
Mooncake.jl
github_2023
others
457
compintell
willtebbutt
@@ -409,36 +410,110 @@ This "vector-Jacobian product" expression is commonly used to explain AD, and is # Directional Derivatives and Gradients -Now we turn to using reverse-mode AD to compute the gradient of a function. -In short, given a function ``g : \mathcal{X} \to \RR`` with derivative ``D g [x]`` at ``x``, its gradient is equal to ``D g [x]^\ast (1)``. -We explain why in this section. +Now we turn to using forwards- and reverse-mode AD to compute the gradient of a function. -The derivative discussed here can be used to compute directional derivatives. -Consider a function ``f : \mathcal{X} \to \RR`` with Frechet derivative ``D f [x] : \mathcal{X} \to \RR`` at ``x \in \mathcal{X}``. -Then ``D f[x](\dot{x})`` returns the directional derivative in direction ``\dot{x}``. +Recall that if ``D f[x] : \mathcal{X} \to \mathbb{R}`` is the Frechet derivative discussed here then ``D f[x](\dot{x})`` is the _directional derivative_ in the ``\dot{x}`` direction. -Gradients are closely related to the adjoint of the derivative. -Recall that the gradient of ``f`` at ``x`` is defined to be the vector ``\nabla f (x) \in \mathcal{X}`` such that ``\langle \nabla f (x), \dot{x} \rangle`` gives the directional derivative of ``f`` at ``x`` in direction ``\dot{x}``. -Having noted that ``D f[x](\dot{x})`` is exactly this directional derivative, we can equivalently say that +The _gradient_ of ``f : \mathcal{X} \to \mathbb{R}`` at ``x`` is defined to be the vector ``\nabla f (x) \in \mathcal{X}`` such that ```math -D f[x](\dot{x}) = \langle \nabla f (x), \dot{x} \rangle . +\langle \nabla f (x), \dot{x} \rangle = D f[x](\dot{x}) ``` +for any direction ``\dot{x}``. +In other words, the vector ``\nabla f`` encodes all the information about the directional derivatives of ``f``, and we use the inner product to retrieve each one. -The role of the adjoint is revealed when we consider ``f := \mathcal{l} \circ g``, where ``g : \mathcal{X} \to \mathcal{Y}``, ``\mathcal{l}(y) := \langle \bar{y}, y \rangle``, and ``\bar{y} \in \mathcal{Y}`` is some fixed vector. -Noting that ``D \mathcal{l} [y](\dot{y}) = \langle \bar{y}, \dot{y} \rangle``, we apply the chain rule to obtain +An alternative characterisation is that ``\nabla f(x)`` is the vector pointing in the direction of steepest ascent on ``f`` at ``x``, with magnitude equal to the directional derivative in that steepest direction. + +_**Aside: The choice of inner product**_ + +Notice that the value of the gradient depends on how the inner product on ``\mathcal{X}`` is defined. +Indeed, different choices of inner product result in different values of ``\nabla f``. +Adjoints such as ``D f[x]^*`` are also inner product dependent. +However, the actual derivative ``D f[x]`` is of course invariant -- it makes no reference to the inner product. + +In practice, Mooncake uses the Euclidean inner product, extended in the "obvious way" to other composite data types (that is, as if everything is flattened and embedded in ``\mathbb{R}^N``). +But we endeavour to keep the discussion general in order to make the role of the inner product explicit. + + + +#### Computing the gradient from forwards-mode + +To compute the gradient in forwards-mode, we need to evaluate the forwards pass ``\dim \mathcal{X}`` times. +We also need to refer to a basis ``\{\mathbf{e}_i\}`` of ``\mathcal{X}`` and its reciprocal basis ``\{\mathbf{e}^i\}`` defined by ``\langle \mathbf{e}_i, \mathbf{e}^j \rangle = \delta_i^j``. +(For any basis there exists such a reciprocal basis, and they are the same if the basis is orthonormal.) + +Equipped with such a pair of bases, we can always decompose a vector ``x = \sum_i x^i \mathbf{e}_i`` into its components ``x^i = \langle x, \mathbf{e}^i \rangle``. +Therefore, the gradient is given by ```math -\begin{align} -D f [x] (\dot{x}) &= [(D \mathcal{l} [g(x)]) \circ (D g [x])](\dot{x}) \nonumber \\ - &= \langle \bar{y}, D g [x] (\dot{x}) \rangle \nonumber \\ - &= \langle D g [x]^\ast (\bar{y}), \dot{x} \rangle, \nonumber -\end{align} +\nabla f(x) + = \sum_i \langle \nabla f(x), \mathbf{e}^i \rangle \mathbf{e}_i + = \sum_i D f[x](\mathbf{e}^i) \, \mathbf{e}_i ``` -from which we conclude that ``D g [x]^\ast (\bar{y})`` is the gradient of the composition ``l \circ g`` at ``x``. +where the second equality follows from the gradient's implicit definition. -The consequence is that we can always view the computation performed by reverse-mode AD as computing the gradient of the composition of the function in question and an inner product with the argument to the adjoint. +If the inner product is Euclidean, then ``\mathbf{e}^i = \mathbf{e}_i`` and we can interpret the ``i``th component of ``\nabla f`` as the directional derivative when moving in the ``i``th direction. -The above shows that if ``\mathcal{Y} = \RR`` and ``g`` is the function we wish to compute the gradient of, we can simply set ``\bar{y} = 1`` and compute ``D g [x]^\ast (\bar{y})`` to obtain the gradient of ``g`` at ``x``. +_**Example**_ +Consider again the Julia `function` +```julia +f(x::Float64, y::Tuple{Float64, Float64}) = x + y[1] * y[2] +``` +corresponding to ``f(x, y) = x + y_1 y_2``. +An orthonormal basis for the function's domain ``\mathbb{R} \times \mathbb{R}^2`` is +```math +\mathbf{e}_1 = \mathbf{e}^1 = (1, (0, 0)), \quad +\mathbf{e}_2 = \mathbf{e}^2 = (0, (1, 0)), \quad +\mathbf{e}_3 = \mathbf{e}^3 = (0, (0, 1)), \quad +``` +so the gradient is +```math +\begin{align*} +\nabla f(x, y) + &= \sum_i D f[x, y](\mathbf{e}^i) \mathbf{e}_i \\ + &= \Big(D f[x, y](1, (0, 0)), \big(D f[x, y](0, (1, 0)), D f[x, y](0, (0, 1))\big)\Big) \\ + &= (1, (y_2, y_1)) +\end{align*} +``` +referring [above](#AD-of-a-Julia-function:-a-slightly-less-trivial-example) for the form of ``D f[x, y]``. + +#### Computing the gradient from reverse-mode +If we perform a single reverse-pass on a function ``f : \mathcal{X} \to \RR`` to obtain ``D f[x]^\ast``, then the gradient is simply +```math +\nabla f (x) = D f[x]^\ast (1) . +``` + +To show this, note that ``D f [x] (\dot{x}) = \langle 1, D f[x] (\dot{x}) \rangle = \langle D f[x]^\ast (1), \dot{x} \rangle`` using the definition of the adjoint. +Then, the definition of the gradient gives +```math +\langle \nabla f (x), \dot{x} \rangle = \langle D f[x]^\ast (1), \dot{x} \rangle +``` +which implies ``\nabla f (x) = D f[x]^\ast (1)`` since ``\dot{x}`` is arbitrary. + +_**Example**_ + +The adjoint derivative of ``f(x, y) = x + y_1 y_2`` (see [above](#AD-of-a-Julia-function:-a-slightly-less-trivial-example)) immediately gives
```suggestion The adjoint of the derivative of ``f(x, y) = x + y_1 y_2`` (see [above](#AD-of-a-Julia-function:-a-slightly-less-trivial-example)) immediately gives ``` nit-pick: I don't _believe_ we refer to the "adjoint derivative" anywhere, but we do refer to the "adjoint" and the "adjoint of the derivative" interchangeably. Is this a typo, or ought we to be talking about the "adjoint derivative"?
Mooncake.jl
github_2023
others
457
compintell
willtebbutt
@@ -409,36 +410,110 @@ This "vector-Jacobian product" expression is commonly used to explain AD, and is # Directional Derivatives and Gradients -Now we turn to using reverse-mode AD to compute the gradient of a function. -In short, given a function ``g : \mathcal{X} \to \RR`` with derivative ``D g [x]`` at ``x``, its gradient is equal to ``D g [x]^\ast (1)``. -We explain why in this section. +Now we turn to using forwards- and reverse-mode AD to compute the gradient of a function. -The derivative discussed here can be used to compute directional derivatives. -Consider a function ``f : \mathcal{X} \to \RR`` with Frechet derivative ``D f [x] : \mathcal{X} \to \RR`` at ``x \in \mathcal{X}``. -Then ``D f[x](\dot{x})`` returns the directional derivative in direction ``\dot{x}``. +Recall that if ``D f[x] : \mathcal{X} \to \mathbb{R}`` is the Frechet derivative discussed here then ``D f[x](\dot{x})`` is the _directional derivative_ in the ``\dot{x}`` direction. -Gradients are closely related to the adjoint of the derivative. -Recall that the gradient of ``f`` at ``x`` is defined to be the vector ``\nabla f (x) \in \mathcal{X}`` such that ``\langle \nabla f (x), \dot{x} \rangle`` gives the directional derivative of ``f`` at ``x`` in direction ``\dot{x}``. -Having noted that ``D f[x](\dot{x})`` is exactly this directional derivative, we can equivalently say that +The _gradient_ of ``f : \mathcal{X} \to \mathbb{R}`` at ``x`` is defined to be the vector ``\nabla f (x) \in \mathcal{X}`` such that ```math -D f[x](\dot{x}) = \langle \nabla f (x), \dot{x} \rangle . +\langle \nabla f (x), \dot{x} \rangle = D f[x](\dot{x}) ``` +for any direction ``\dot{x}``. +In other words, the vector ``\nabla f`` encodes all the information about the directional derivatives of ``f``, and we use the inner product to retrieve each one. -The role of the adjoint is revealed when we consider ``f := \mathcal{l} \circ g``, where ``g : \mathcal{X} \to \mathcal{Y}``, ``\mathcal{l}(y) := \langle \bar{y}, y \rangle``, and ``\bar{y} \in \mathcal{Y}`` is some fixed vector. -Noting that ``D \mathcal{l} [y](\dot{y}) = \langle \bar{y}, \dot{y} \rangle``, we apply the chain rule to obtain +An alternative characterisation is that ``\nabla f(x)`` is the vector pointing in the direction of steepest ascent on ``f`` at ``x``, with magnitude equal to the directional derivative in that steepest direction. + +_**Aside: The choice of inner product**_ + +Notice that the value of the gradient depends on how the inner product on ``\mathcal{X}`` is defined. +Indeed, different choices of inner product result in different values of ``\nabla f``. +Adjoints such as ``D f[x]^*`` are also inner product dependent. +However, the actual derivative ``D f[x]`` is of course invariant -- it makes no reference to the inner product. + +In practice, Mooncake uses the Euclidean inner product, extended in the "obvious way" to other composite data types (that is, as if everything is flattened and embedded in ``\mathbb{R}^N``). +But we endeavour to keep the discussion general in order to make the role of the inner product explicit. + + + +#### Computing the gradient from forwards-mode + +To compute the gradient in forwards-mode, we need to evaluate the forwards pass ``\dim \mathcal{X}`` times. +We also need to refer to a basis ``\{\mathbf{e}_i\}`` of ``\mathcal{X}`` and its reciprocal basis ``\{\mathbf{e}^i\}`` defined by ``\langle \mathbf{e}_i, \mathbf{e}^j \rangle = \delta_i^j``. +(For any basis there exists such a reciprocal basis, and they are the same if the basis is orthonormal.) + +Equipped with such a pair of bases, we can always decompose a vector ``x = \sum_i x^i \mathbf{e}_i`` into its components ``x^i = \langle x, \mathbf{e}^i \rangle``. +Therefore, the gradient is given by ```math -\begin{align} -D f [x] (\dot{x}) &= [(D \mathcal{l} [g(x)]) \circ (D g [x])](\dot{x}) \nonumber \\ - &= \langle \bar{y}, D g [x] (\dot{x}) \rangle \nonumber \\ - &= \langle D g [x]^\ast (\bar{y}), \dot{x} \rangle, \nonumber -\end{align} +\nabla f(x) + = \sum_i \langle \nabla f(x), \mathbf{e}^i \rangle \mathbf{e}_i + = \sum_i D f[x](\mathbf{e}^i) \, \mathbf{e}_i ``` -from which we conclude that ``D g [x]^\ast (\bar{y})`` is the gradient of the composition ``l \circ g`` at ``x``. +where the second equality follows from the gradient's implicit definition. -The consequence is that we can always view the computation performed by reverse-mode AD as computing the gradient of the composition of the function in question and an inner product with the argument to the adjoint. +If the inner product is Euclidean, then ``\mathbf{e}^i = \mathbf{e}_i`` and we can interpret the ``i``th component of ``\nabla f`` as the directional derivative when moving in the ``i``th direction. -The above shows that if ``\mathcal{Y} = \RR`` and ``g`` is the function we wish to compute the gradient of, we can simply set ``\bar{y} = 1`` and compute ``D g [x]^\ast (\bar{y})`` to obtain the gradient of ``g`` at ``x``. +_**Example**_ +Consider again the Julia `function` +```julia +f(x::Float64, y::Tuple{Float64, Float64}) = x + y[1] * y[2] +``` +corresponding to ``f(x, y) = x + y_1 y_2``. +An orthonormal basis for the function's domain ``\mathbb{R} \times \mathbb{R}^2`` is +```math +\mathbf{e}_1 = \mathbf{e}^1 = (1, (0, 0)), \quad +\mathbf{e}_2 = \mathbf{e}^2 = (0, (1, 0)), \quad +\mathbf{e}_3 = \mathbf{e}^3 = (0, (0, 1)), \quad +``` +so the gradient is +```math +\begin{align*} +\nabla f(x, y) + &= \sum_i D f[x, y](\mathbf{e}^i) \mathbf{e}_i \\ + &= \Big(D f[x, y](1, (0, 0)), \big(D f[x, y](0, (1, 0)), D f[x, y](0, (0, 1))\big)\Big) \\ + &= (1, (y_2, y_1)) +\end{align*} +``` +referring [above](#AD-of-a-Julia-function:-a-slightly-less-trivial-example) for the form of ``D f[x, y]``. + +#### Computing the gradient from reverse-mode +If we perform a single reverse-pass on a function ``f : \mathcal{X} \to \RR`` to obtain ``D f[x]^\ast``, then the gradient is simply +```math +\nabla f (x) = D f[x]^\ast (1) . +``` + +To show this, note that ``D f [x] (\dot{x}) = \langle 1, D f[x] (\dot{x}) \rangle = \langle D f[x]^\ast (1), \dot{x} \rangle`` using the definition of the adjoint. +Then, the definition of the gradient gives +```math +\langle \nabla f (x), \dot{x} \rangle = \langle D f[x]^\ast (1), \dot{x} \rangle +``` +which implies ``\nabla f (x) = D f[x]^\ast (1)`` since ``\dot{x}`` is arbitrary. + +_**Example**_ + +The adjoint derivative of ``f(x, y) = x + y_1 y_2`` (see [above](#AD-of-a-Julia-function:-a-slightly-less-trivial-example)) immediately gives +```math +\nabla f(x, y) = D f[x, y]^\ast (1) = (1, (y_2, y_1)) . +``` + +_**Aside: Adjoint Derivatives as Gradients**_
Same here -- "Adjoint Derivatives" vs "Adjoint" or "Adjoint of the Derivative" etc
Mooncake.jl
github_2023
others
457
compintell
willtebbutt
@@ -409,36 +410,110 @@ This "vector-Jacobian product" expression is commonly used to explain AD, and is # Directional Derivatives and Gradients -Now we turn to using reverse-mode AD to compute the gradient of a function. -In short, given a function ``g : \mathcal{X} \to \RR`` with derivative ``D g [x]`` at ``x``, its gradient is equal to ``D g [x]^\ast (1)``. -We explain why in this section. +Now we turn to using forwards- and reverse-mode AD to compute the gradient of a function. -The derivative discussed here can be used to compute directional derivatives. -Consider a function ``f : \mathcal{X} \to \RR`` with Frechet derivative ``D f [x] : \mathcal{X} \to \RR`` at ``x \in \mathcal{X}``. -Then ``D f[x](\dot{x})`` returns the directional derivative in direction ``\dot{x}``. +Recall that if ``D f[x] : \mathcal{X} \to \mathbb{R}`` is the Frechet derivative discussed here then ``D f[x](\dot{x})`` is the _directional derivative_ in the ``\dot{x}`` direction. -Gradients are closely related to the adjoint of the derivative. -Recall that the gradient of ``f`` at ``x`` is defined to be the vector ``\nabla f (x) \in \mathcal{X}`` such that ``\langle \nabla f (x), \dot{x} \rangle`` gives the directional derivative of ``f`` at ``x`` in direction ``\dot{x}``. -Having noted that ``D f[x](\dot{x})`` is exactly this directional derivative, we can equivalently say that +The _gradient_ of ``f : \mathcal{X} \to \mathbb{R}`` at ``x`` is defined to be the vector ``\nabla f (x) \in \mathcal{X}`` such that ```math -D f[x](\dot{x}) = \langle \nabla f (x), \dot{x} \rangle . +\langle \nabla f (x), \dot{x} \rangle = D f[x](\dot{x}) ``` +for any direction ``\dot{x}``. +In other words, the vector ``\nabla f`` encodes all the information about the directional derivatives of ``f``, and we use the inner product to retrieve each one. -The role of the adjoint is revealed when we consider ``f := \mathcal{l} \circ g``, where ``g : \mathcal{X} \to \mathcal{Y}``, ``\mathcal{l}(y) := \langle \bar{y}, y \rangle``, and ``\bar{y} \in \mathcal{Y}`` is some fixed vector. -Noting that ``D \mathcal{l} [y](\dot{y}) = \langle \bar{y}, \dot{y} \rangle``, we apply the chain rule to obtain +An alternative characterisation is that ``\nabla f(x)`` is the vector pointing in the direction of steepest ascent on ``f`` at ``x``, with magnitude equal to the directional derivative in that steepest direction. + +_**Aside: The choice of inner product**_ + +Notice that the value of the gradient depends on how the inner product on ``\mathcal{X}`` is defined. +Indeed, different choices of inner product result in different values of ``\nabla f``. +Adjoints such as ``D f[x]^*`` are also inner product dependent. +However, the actual derivative ``D f[x]`` is of course invariant -- it makes no reference to the inner product. + +In practice, Mooncake uses the Euclidean inner product, extended in the "obvious way" to other composite data types (that is, as if everything is flattened and embedded in ``\mathbb{R}^N``). +But we endeavour to keep the discussion general in order to make the role of the inner product explicit. + + + +#### Computing the gradient from forwards-mode + +To compute the gradient in forwards-mode, we need to evaluate the forwards pass ``\dim \mathcal{X}`` times. +We also need to refer to a basis ``\{\mathbf{e}_i\}`` of ``\mathcal{X}`` and its reciprocal basis ``\{\mathbf{e}^i\}`` defined by ``\langle \mathbf{e}_i, \mathbf{e}^j \rangle = \delta_i^j``. +(For any basis there exists such a reciprocal basis, and they are the same if the basis is orthonormal.)
```suggestion For any basis there exists such a reciprocal basis, and they are the same for orthonormal bases such as the standard basis. As a result, you can replace any occurrences of ``\{\mathbf{e}^i\}`` with ``\{\mathbf{e}_i\}`` in what follows and still have a correct understanding of the mathematics underpinning Mooncake. ``` nip-pick: I don't think we need the brackets here, and I think it would be good to allude to the standard basis. What are your thoughts on my bit about "replace occurences of..."? I'm not 100% certain I've phrased this perfectly, but I would like to reassure readers that this is indeed the consequence of the previous sentence. Maybe I'm overthinking it...
Mooncake.jl
github_2023
others
458
compintell
yebai
@@ -0,0 +1,93 @@ +# All of the code here purely exists to work around current performance limitations of +# Mooncake.jl. In order to prevent this from getting out of hand, there are several +# conventions to which we adhere when writing these rules: +# +# 1. for each rule, a comment is added containing a link to the issue or issues that are +# believed to describe the deficiencies of Mooncake.jl which cause the rule to be needed. +# 2. the number of concrete types for which the signature is valid is finite, and all are +# tested. For example, `Array{<:IEEEFloat}` is a permissible type. The only exception to +# this is the dimension of an `Array` argument. For example, it is fine to write rules for +# `Array{Float64}`, despite the fact that this technically includes `Array{Float64,1}`, +# `Array{Float64,2}`, `Array{Float64,3}`, etc. +# `Diagonal{<:IEEEFloat}` is not, on the other hand, permissible. This is because we do +# not know what the type of its `diag` field is, and it _could_ be any `AbstractVector`. +# Something more precise like `Diagonal{P, Vector{P}} where {P<:IEEEFloat}` is fine. +# This convention ensures that we are confident the rules here confident a strict +# improvement over what we currently have, and prevents the addition of flakey rules which +# cause robustness or correctness problems. + +# Performance issue: https://github.com/compintell/Mooncake.jl/issues/156 +# Complicated implementation involving low-level machinery needed due to +# https://github.com/compintell/Mooncake.jl/issues/238 +@is_primitive( + DefaultCtx, + Tuple{ + typeof(Base._mapreduce), + typeof(identity), + typeof(Base.add_sum), + Base.IndexLinear, + Array{<:IEEEFloat}, + }, +) +function rrule!!( + ::CoDual{typeof(Base._mapreduce)}, + ::CoDual{typeof(identity)}, + ::CoDual{typeof(Base.add_sum)}, + ::CoDual{Base.IndexLinear}, + x::CoDual{<:Array{P}} +) where {P<:IEEEFloat} + dx = x.dx + function sum_pb!!(dz::P) + dx .+= dz + return NoRData(), NoRData(), NoRData(), NoRData(), NoRData() + end + return zero_fcodual(sum(x.x)), sum_pb!! +end + +# Performance issue: https://github.com/compintell/Mooncake.jl/issues/156 +# Complicated implementation involving low-level machinery needed due to +# https://github.com/compintell/Mooncake.jl/issues/238 +@is_primitive( + DefaultCtx, + Tuple{ + typeof(Base._mapreduce), + typeof(abs2), + typeof(Base.add_sum), + Base.IndexLinear, + Array{<:IEEEFloat}, + }, +) +function rrule!!( + ::CoDual{typeof(Base._mapreduce)}, + ::CoDual{typeof(abs2)}, + ::CoDual{typeof(Base.add_sum)}, + ::CoDual{Base.IndexLinear}, + x::CoDual{<:Array{P}} +) where {P<:IEEEFloat} + dx = x.dx + function sum_pb!!(dz::P) + x.dx .+= 2 .* dz .* x.x
Perhaps ```suggestion dx .+= 2 .* dz .* x.x ```
Mooncake.jl
github_2023
others
469
compintell
gdalle
@@ -202,16 +202,16 @@ end WARNING: experimental functionality. Interface subject to change without warning! -Like other methods of `value_and_pullback!!`, but makes use of the `cache` object in order -to avoid having to re-allocate various tangent objects repeatedly. +Like other methods of `value_and_pullback!!`, but makes use of the `cache` object returned +by [`prepare_pullback_cache`](@ref) in order to avoid having to re-allocate various tangent +objects repeatedly. You must ensure that `f` and `x` are the same types and sizes as those +used to construct `cache`. -You must ensure that `f` and `x` are the same types and sizes as those used to construct -`cache`. - -Warning: any mutable components of values returned by `value_and_gradient!!` will be mutated -if you run this function again with different arguments. Therefore, if you need to keep the -values returned by this function around over multiple calls to this function with the same -`cache`, you should take a copy of them before calling again. +Warning: `cache` owns any mutable state returned by this function, meaning that mutable +components of values returned by it will be mutated if you run this function again with +different arguments. Therefore, if you need to keep the values returned by this function +around over multiple calls to this function with the same `cache`, you should take a copy
Maybe specify "or `deepcopy`"? I think this may come back to bite us more than once. Otherwise good to go, thanks!
Mooncake.jl
github_2023
others
382
compintell
willtebbutt
@@ -0,0 +1,80 @@ +# Compilation process + +The whole rule building is done statically based on types. The first method of `build_rrule` turns argument values into a signature: + +```julia +build_rrule(args...; debug_mode=false) +``` + +The actual action happens in [`s2s_reverse_mode_ad.jl`](https://github.com/compintell/Mooncake.jl/blob/main/src/interpreter/s2s_reverse_mode_ad.jl). +This method handles either the function signature or the method instance: + +```julia +build_rrule(interp::MooncakeInterpreter{C}, sig_or_mi; debug_mode=false) +``` + +If there is a custom rule, we take it, otherwise generate the IR and differentiate it. + +The forward- and reverse-pass IRs are created by `generate_ir`. +The `OpaqueClosure` allows going back from the IR to a callable object. More precisely we use `MistyClosure` to store the associated IR. + +The `Pullback` and `DerivedRule` structs are convenience wrappers for `MistyClosure`s with some bookkeeping. + +Diving one level deeper, in the following method: + +```julia +generate_ir( + interp::MooncakeInterpreter, sig_or_mi; debug_mode=false, do_inline=true +) +``` + +The function `lookup_ir` calls `Core.Compiler.typeinf_ircode` on a method instance, which is a lower-level version of `Base.code_ircode`. + +The IR considered is of type `IRCode`, which is different from the `CodeInfo` returned by `@code_typed`. +This format is obtained from `CodeInfo`, used to perform most optimizations in the Julia IR in the [evaluation pipeline](https://docs.julialang.org/en/v1/devdocs/eval/), then converted back to `CodeInfo`. + +The function `normalise!` is a custom pass to modify `IRCode` and make some expressions nicer to work with. +The possible expressions one can encountered in lowered ASTs are documented [here](https://docs.julialang.org/en/v1/devdocs/ast/#Lowered-form). + +Reverse-mode specific stuff: return type retrieval, `ADInfo`, `bbcode.jl`, `zero_like_rdata.jl`. The `BBCode` structure was a convenience for IR transformation. + +Beyond the [`interpreter`](https://github.com/compintell/Mooncake.jl/blob/main/src/interpreter/) folder, check out [`tangents.jl`](https://github.com/compintell/Mooncake.jl/blob/main/src/tangents.jl) for forward mode. + +`FData` and `RData` are not useful in forward mode, `Tangent` is the right representation. + +For testing, `generate_test_functions` from [`test_resources.jl`](https://github.com/compintell/Mooncake.jl/blob/src/test_utils.jl) should all pass. +Recycle the functionality from reverse mode test utils. + +To manipulate `IRCode`, check out the fields: + +- `ir.argtypes` is the signature. Some are annotated with `Core.Const` to facilitate constant propagation for instance. Other annotations are `PartialStruct`, `Conditional`, `PartialTypeVar` (see `_type`)
```suggestion - `ir.argtypes` is the signature. Some are annotated with `Core.Const` to facilitate constant propagation for instance. Other annotations are `PartialStruct`, `Conditional`, `PartialTypeVar`. `Core.Compiler.widenconst` is used to extract types from these. ```
Mooncake.jl
github_2023
others
382
compintell
willtebbutt
@@ -0,0 +1,80 @@ +# Compilation process + +The whole rule building is done statically based on types. The first method of `build_rrule` turns argument values into a signature: + +```julia +build_rrule(args...; debug_mode=false) +``` + +The actual action happens in [`s2s_reverse_mode_ad.jl`](https://github.com/compintell/Mooncake.jl/blob/main/src/interpreter/s2s_reverse_mode_ad.jl). +This method handles either the function signature or the method instance: + +```julia +build_rrule(interp::MooncakeInterpreter{C}, sig_or_mi; debug_mode=false) +``` + +If there is a custom rule, we take it, otherwise generate the IR and differentiate it. + +The forward- and reverse-pass IRs are created by `generate_ir`. +The `OpaqueClosure` allows going back from the IR to a callable object. More precisely we use `MistyClosure` to store the associated IR. + +The `Pullback` and `DerivedRule` structs are convenience wrappers for `MistyClosure`s with some bookkeeping. + +Diving one level deeper, in the following method: + +```julia +generate_ir( + interp::MooncakeInterpreter, sig_or_mi; debug_mode=false, do_inline=true +) +``` + +The function `lookup_ir` calls `Core.Compiler.typeinf_ircode` on a method instance, which is a lower-level version of `Base.code_ircode`. + +The IR considered is of type `IRCode`, which is different from the `CodeInfo` returned by `@code_typed`. +This format is obtained from `CodeInfo`, used to perform most optimizations in the Julia IR in the [evaluation pipeline](https://docs.julialang.org/en/v1/devdocs/eval/), then converted back to `CodeInfo`. + +The function `normalise!` is a custom pass to modify `IRCode` and make some expressions nicer to work with. +The possible expressions one can encountered in lowered ASTs are documented [here](https://docs.julialang.org/en/v1/devdocs/ast/#Lowered-form). + +Reverse-mode specific stuff: return type retrieval, `ADInfo`, `bbcode.jl`, `zero_like_rdata.jl`. The `BBCode` structure was a convenience for IR transformation. + +Beyond the [`interpreter`](https://github.com/compintell/Mooncake.jl/blob/main/src/interpreter/) folder, check out [`tangents.jl`](https://github.com/compintell/Mooncake.jl/blob/main/src/tangents.jl) for forward mode. + +`FData` and `RData` are not useful in forward mode, `Tangent` is the right representation. + +For testing, `generate_test_functions` from [`test_resources.jl`](https://github.com/compintell/Mooncake.jl/blob/src/test_utils.jl) should all pass. +Recycle the functionality from reverse mode test utils. + +To manipulate `IRCode`, check out the fields: + +- `ir.argtypes` is the signature. Some are annotated with `Core.Const` to facilitate constant propagation for instance. Other annotations are `PartialStruct`, `Conditional`, `PartialTypeVar` (see `_type`) +- `ir.stmts` contains 5 vectors of the same length: + - `stmts.stmt` is a vector of expressions (or other IR node types), see [AST docs](https://docs.julialang.org/en/v1/devdocs/ast/#Lowered-form) + - `stmts.type` is a vector of types for the left-hand side of the assignment +- `ir.cfg` is the Control Flow Graph of type `Core.Compiler.CFG` +- `ir.meta` is metadata, not important +- `ir.new_nodes` is an optimization buffer, not important +- `ir.sptypes` is for type parameters of the called function + +We must maintain coherence between the various components of `IRCode` (especially `ir.stmts` and `ir.cfg`). That is the reason behind `BBCode`, to make coherence easier. +We can deduce the CFG from the statements but not the other way around: it's only composed of blocks of statement indices. +In forward mode we shouldn't have to modify anything but `ir.stmts`. +Do line by line transformation of the statements and then possibly refresh the CFG. + +Example of line-by-line transformations are in `make_ad_stmts!`. +The `IRCode` nodes are not explicitly documented in <https://docs.julialang.org/en/v1/devdocs/ast/#Lowered-form> or <https://docs.julialang.org/en/v1/devdocs/ssair/#Main-SSA-data-structure>. Might need completion of official docs, but Mooncake docs in the meantime. + +Inlining pass can prevent us from using high-level rules by inlining the function (e.g. unrolling a loop). +The contexts in [`interpreter/contexts.jl`](https://github.com/compintell/Mooncake.jl/blob/src/interpreter/contexts.jl) are `MinimalCtx` (necessary for AD to work) and `DefaultCtx` (ensure that we hit all of the rules). +Distinction between rules is not well maintained in Mooncake at the moment. +The function `is_primitive` defines whether we should recurse into the function during AD and break it into parts, or look for a rule. +Typically if we define a rule we should set `is_primitive` to `true` for the corresponding function.
```suggestion If we define a rule we should set `is_primitive` to `true` for the corresponding function. ```
Mooncake.jl
github_2023
others
408
compintell
willtebbutt
@@ -168,27 +168,32 @@ Following either resource will yield the derivative: ```math D f [X] (\dot{X}) = \dot{X}^\top X + X^\top \dot{X} ``` -Observe that this is indeed a linear operator (i.e. it is linear in its argument, ``\dot{X}``). -(You can always plug it in to the definition of the Frechet derivative to confirm that it is indeed the derivative.) +Observe that this is indeed a linear operator (i.e. it is linear in its argument, ``\dot{X}``). For the rest of this example, we use the matrix A as the coordinate-form representation of the operator ``Df\left[X\right]:\mathbb{R}^{N\times M}\rightarrow\mathbb{R}^{N\times M}``, with respect to the elementary basis of ``\mathbb{R}^{N\times M}``.
Does the matrix `A` exist? Unless I'm mistaken, it's not the case that you can necessarily represent any linear operator on a matrix via multiplication with another matrix. If you treat a matrix `X` of size `P x Q` as a vector of length `PQ`, you can certainly represent any linear transform via a matrix of size `PQ x PQ`, but (if my understanding of what you're doing here is correct), that's not what's happening here.
Mooncake.jl
github_2023
others
408
compintell
willtebbutt
@@ -168,27 +168,32 @@ Following either resource will yield the derivative: ```math D f [X] (\dot{X}) = \dot{X}^\top X + X^\top \dot{X} ``` -Observe that this is indeed a linear operator (i.e. it is linear in its argument, ``\dot{X}``). -(You can always plug it in to the definition of the Frechet derivative to confirm that it is indeed the derivative.) +Observe that this is indeed a linear operator (i.e. it is linear in its argument, ``\dot{X}``). For the rest of this example, we use the matrix A as the coordinate-form representation of the operator ``Df\left[X\right]:\mathbb{R}^{N\times M}\rightarrow\mathbb{R}^{N\times M}``, with respect to the elementary basis of ``\mathbb{R}^{N\times M}``. -In order to perform reverse-mode AD, we need to find the adjoint operator. -Using the usual definition of the inner product between matrices, +Our goal is to find the adjoint operator by inspection. The equation that we inspect comes from the definition of the usual inner product of matrices: ```math -\langle X, Y \rangle := \textrm{tr} (X^\top Y) +\begin{align*} +\forall A,B\in\mathbb{R}^{N\times M}, & \left\langle A,B\right\rangle :=\text{tr}\left(A^{T}B\right). +\end{align*} ``` -we can rearrange the inner product as follows: +Let ``V:=\dot{X}`` and ``U:=\bar{Y}`` to reduce clutter. Apply this inner product to the adjoint operator condition, where the matrix ``B`` is the coordinate-form representation of the adjoint operator: ```math -\begin{align} - \langle \bar{Y}, D f [X] (\dot{X}) \rangle &= \langle \bar{Y}, \dot{X}^\top X + X^\top \dot{X} \rangle \nonumber \\ - &= \textrm{tr} (\bar{Y}^\top \dot{X}^\top X) + \textrm{tr}(\bar{Y}^\top X^\top \dot{X}) \nonumber \\ - &= \textrm{tr} ( [\bar{Y} X^\top]^\top \dot{X}) + \textrm{tr}( [X \bar{Y}]^\top \dot{X}) \nonumber \\ - &= \langle \bar{Y} X^\top + X \bar{Y}, \dot{X} \rangle. \nonumber -\end{align} -``` -We can read off the adjoint operator from the first argument to the inner product: +\begin{align*} +\left\langle BU,V\right\rangle & =\left\langle U,AV\right\rangle ,\\ + & =\left\langle U,V^{T}X+X^{T}V\right\rangle ,\\
To my previous point regarding the existence of `A`, it's not obvious to me that the jump between these two lines -- substituting `V^T X + X^T V` for `AV` -- can be made sense of. Concretely: does there exist a matrix `A` such that `AV = V^T X + X^T V` for any `X` and `V`?
Mooncake.jl
github_2023
others
408
compintell
willtebbutt
@@ -168,27 +168,32 @@ Following either resource will yield the derivative: ```math D f [X] (\dot{X}) = \dot{X}^\top X + X^\top \dot{X} ``` -Observe that this is indeed a linear operator (i.e. it is linear in its argument, ``\dot{X}``). -(You can always plug it in to the definition of the Frechet derivative to confirm that it is indeed the derivative.) +Observe that this is indeed a linear operator (i.e. it is linear in its argument, ``\dot{X}``). For the rest of this example, we use the matrix A as the coordinate-form representation of the operator ``Df\left[X\right]:\mathbb{R}^{N\times M}\rightarrow\mathbb{R}^{N\times M}``, with respect to the elementary basis of ``\mathbb{R}^{N\times M}``. -In order to perform reverse-mode AD, we need to find the adjoint operator. -Using the usual definition of the inner product between matrices, +Our goal is to find the adjoint operator by inspection. The equation that we inspect comes from the definition of the usual inner product of matrices: ```math -\langle X, Y \rangle := \textrm{tr} (X^\top Y) +\begin{align*} +\forall A,B\in\mathbb{R}^{N\times M}, & \left\langle A,B\right\rangle :=\text{tr}\left(A^{T}B\right). +\end{align*} ``` -we can rearrange the inner product as follows: +Let ``V:=\dot{X}`` and ``U:=\bar{Y}`` to reduce clutter. Apply this inner product to the adjoint operator condition, where the matrix ``B`` is the coordinate-form representation of the adjoint operator: ```math -\begin{align} - \langle \bar{Y}, D f [X] (\dot{X}) \rangle &= \langle \bar{Y}, \dot{X}^\top X + X^\top \dot{X} \rangle \nonumber \\ - &= \textrm{tr} (\bar{Y}^\top \dot{X}^\top X) + \textrm{tr}(\bar{Y}^\top X^\top \dot{X}) \nonumber \\ - &= \textrm{tr} ( [\bar{Y} X^\top]^\top \dot{X}) + \textrm{tr}( [X \bar{Y}]^\top \dot{X}) \nonumber \\ - &= \langle \bar{Y} X^\top + X \bar{Y}, \dot{X} \rangle. \nonumber -\end{align} -``` -We can read off the adjoint operator from the first argument to the inner product: +\begin{align*} +\left\langle BU,V\right\rangle & =\left\langle U,AV\right\rangle ,\\ + & =\left\langle U,V^{T}X+X^{T}V\right\rangle ,\\ + & =\text{tr}\left(U^{T}\left(V^{T}X+X^{T}V\right)\right),\\ + & =\text{tr}\left(V^{T}XU^{T}\right)+\text{tr}\left(U^{T}X^{T}V\right),\\ + & =\left\langle V,XU^{T}\right\rangle +\left\langle U^{T}X^{T},V\right\rangle ,\\ + & =\left\langle XU^{T}+XU,V\right\rangle , +\end{align*} +``` + for any matrices ``A\in\mathbb{R}^{N\times M}``, ``B\in\mathbb{R}^{M\times L}``, and ``C\in\mathbb{R}^{L\times N}`` for some ``N``, ``M``, ``L``. By inspection, the coordinate-form of the adjoint operator is given by the matrix
Unless I'm mistaken, `C` is not used anywhere?
Mooncake.jl
github_2023
others
408
compintell
willtebbutt
@@ -168,27 +168,32 @@ Following either resource will yield the derivative: ```math D f [X] (\dot{X}) = \dot{X}^\top X + X^\top \dot{X} ``` -Observe that this is indeed a linear operator (i.e. it is linear in its argument, ``\dot{X}``). -(You can always plug it in to the definition of the Frechet derivative to confirm that it is indeed the derivative.) +Observe that this is indeed a linear operator (i.e. it is linear in its argument, ``\dot{X}``). For the rest of this example, we use the matrix A as the coordinate-form representation of the operator ``Df\left[X\right]:\mathbb{R}^{N\times M}\rightarrow\mathbb{R}^{N\times M}``, with respect to the elementary basis of ``\mathbb{R}^{N\times M}``. -In order to perform reverse-mode AD, we need to find the adjoint operator. -Using the usual definition of the inner product between matrices, +Our goal is to find the adjoint operator by inspection. The equation that we inspect comes from the definition of the usual inner product of matrices: ```math -\langle X, Y \rangle := \textrm{tr} (X^\top Y) +\begin{align*} +\forall A,B\in\mathbb{R}^{N\times M}, & \left\langle A,B\right\rangle :=\text{tr}\left(A^{T}B\right). +\end{align*} ``` -we can rearrange the inner product as follows: +Let ``V:=\dot{X}`` and ``U:=\bar{Y}`` to reduce clutter. Apply this inner product to the adjoint operator condition, where the matrix ``B`` is the coordinate-form representation of the adjoint operator: ```math -\begin{align} - \langle \bar{Y}, D f [X] (\dot{X}) \rangle &= \langle \bar{Y}, \dot{X}^\top X + X^\top \dot{X} \rangle \nonumber \\ - &= \textrm{tr} (\bar{Y}^\top \dot{X}^\top X) + \textrm{tr}(\bar{Y}^\top X^\top \dot{X}) \nonumber \\ - &= \textrm{tr} ( [\bar{Y} X^\top]^\top \dot{X}) + \textrm{tr}( [X \bar{Y}]^\top \dot{X}) \nonumber \\ - &= \langle \bar{Y} X^\top + X \bar{Y}, \dot{X} \rangle. \nonumber -\end{align} -``` -We can read off the adjoint operator from the first argument to the inner product: +\begin{align*} +\left\langle BU,V\right\rangle & =\left\langle U,AV\right\rangle ,\\ + & =\left\langle U,V^{T}X+X^{T}V\right\rangle ,\\ + & =\text{tr}\left(U^{T}\left(V^{T}X+X^{T}V\right)\right),\\ + & =\text{tr}\left(V^{T}XU^{T}\right)+\text{tr}\left(U^{T}X^{T}V\right),\\ + & =\left\langle V,XU^{T}\right\rangle +\left\langle U^{T}X^{T},V\right\rangle ,\\ + & =\left\langle XU^{T}+XU,V\right\rangle , +\end{align*} +``` + for any matrices ``A\in\mathbb{R}^{N\times M}``, ``B\in\mathbb{R}^{M\times L}``, and ``C\in\mathbb{R}^{L\times N}`` for some ``N``, ``M``, ``L``. By inspection, the coordinate-form of the adjoint operator is given by the matrix ```math -D f [X]^\ast (\bar{Y}) = \bar{Y} X^\top + X \bar{Y}. +\begin{align*} +B=Df\left[X\right]^{*}\left(U\right)= & XU^{T}+XU, +\end{align*} ``` +where ``U:=\bar{Y}`` in this example.
This is defined further up. Perhaps we can remove it?
Mooncake.jl
github_2023
others
408
compintell
willtebbutt
@@ -168,27 +168,32 @@ Following either resource will yield the derivative: ```math D f [X] (\dot{X}) = \dot{X}^\top X + X^\top \dot{X} ``` -Observe that this is indeed a linear operator (i.e. it is linear in its argument, ``\dot{X}``). -(You can always plug it in to the definition of the Frechet derivative to confirm that it is indeed the derivative.) +Observe that this is indeed a linear operator (i.e. it is linear in its argument, ``\dot{X}``). For the rest of this example, we use the matrix A as the coordinate-form representation of the operator ``Df\left[X\right]:\mathbb{R}^{N\times M}\rightarrow\mathbb{R}^{N\times M}``, with respect to the elementary basis of ``\mathbb{R}^{N\times M}``. -In order to perform reverse-mode AD, we need to find the adjoint operator. -Using the usual definition of the inner product between matrices, +Our goal is to find the adjoint operator by inspection. The equation that we inspect comes from the definition of the usual inner product of matrices: ```math -\langle X, Y \rangle := \textrm{tr} (X^\top Y) +\begin{align*} +\forall A,B\in\mathbb{R}^{N\times M}, & \left\langle A,B\right\rangle :=\text{tr}\left(A^{T}B\right). +\end{align*} ``` -we can rearrange the inner product as follows: +Let ``V:=\dot{X}`` and ``U:=\bar{Y}`` to reduce clutter. Apply this inner product to the adjoint operator condition, where the matrix ``B`` is the coordinate-form representation of the adjoint operator: ```math -\begin{align} - \langle \bar{Y}, D f [X] (\dot{X}) \rangle &= \langle \bar{Y}, \dot{X}^\top X + X^\top \dot{X} \rangle \nonumber \\ - &= \textrm{tr} (\bar{Y}^\top \dot{X}^\top X) + \textrm{tr}(\bar{Y}^\top X^\top \dot{X}) \nonumber \\ - &= \textrm{tr} ( [\bar{Y} X^\top]^\top \dot{X}) + \textrm{tr}( [X \bar{Y}]^\top \dot{X}) \nonumber \\ - &= \langle \bar{Y} X^\top + X \bar{Y}, \dot{X} \rangle. \nonumber -\end{align} -``` -We can read off the adjoint operator from the first argument to the inner product: +\begin{align*} +\left\langle BU,V\right\rangle & =\left\langle U,AV\right\rangle ,\\ + & =\left\langle U,V^{T}X+X^{T}V\right\rangle ,\\ + & =\text{tr}\left(U^{T}\left(V^{T}X+X^{T}V\right)\right),\\ + & =\text{tr}\left(V^{T}XU^{T}\right)+\text{tr}\left(U^{T}X^{T}V\right),\\ + & =\left\langle V,XU^{T}\right\rangle +\left\langle U^{T}X^{T},V\right\rangle ,\\ + & =\left\langle XU^{T}+XU,V\right\rangle , +\end{align*} +``` + for any matrices ``A\in\mathbb{R}^{N\times M}``, ``B\in\mathbb{R}^{M\times L}``, and ``C\in\mathbb{R}^{L\times N}`` for some ``N``, ``M``, ``L``. By inspection, the coordinate-form of the adjoint operator is given by the matrix ```math -D f [X]^\ast (\bar{Y}) = \bar{Y} X^\top + X \bar{Y}. +\begin{align*} +B=Df\left[X\right]^{*}\left(U\right)= & XU^{T}+XU,
I'm not sure how to make sense of this line. My understanding is that you're saying we should view `B` as the coordinate form representation of the adjoint of the derivative. So it seems like we have a "type" error -- `D f [X]^\ast (U)` is the matrix resulting from applying the adjoint operator to `U`, but `B` is the operator itself. Should there be a `U` on the rhs of `B`? (I have similar concerns about the existence of `B` as I do `A` -- so let's resolve the discussion around that before addressing this line)
Mooncake.jl
github_2023
others
408
compintell
willtebbutt
@@ -178,16 +178,17 @@ Using the usual definition of the inner product between matrices, ``` we can rearrange the inner product as follows: ```math -\begin{align} - \langle \bar{Y}, D f [X] (\dot{X}) \rangle &= \langle \bar{Y}, \dot{X}^\top X + X^\top \dot{X} \rangle \nonumber \\ - &= \textrm{tr} (\bar{Y}^\top \dot{X}^\top X) + \textrm{tr}(\bar{Y}^\top X^\top \dot{X}) \nonumber \\ - &= \textrm{tr} ( [\bar{Y} X^\top]^\top \dot{X}) + \textrm{tr}( [X \bar{Y}]^\top \dot{X}) \nonumber \\ - &= \langle \bar{Y} X^\top + X \bar{Y}, \dot{X} \rangle. \nonumber -\end{align} -``` -We can read off the adjoint operator from the first argument to the inner product: +\begin{align*} +\langle\bar{Y},Df[X](\dot{X})\rangle & =\langle\bar{Y},\dot{X}^{\top}X+X^{\top}\dot{X}\rangle\\ + & =\textrm{tr}(\bar{Y}^{\top}\left(\dot{X}^{T}X+X^{T}\dot{X}\right))\\
```suggestion & =\textrm{tr}(\bar{Y}^{\top}\left(\dot{X}^{\top}X+X^{\top}\dot{X}\right))\\ ```
Mooncake.jl
github_2023
others
408
compintell
willtebbutt
@@ -178,16 +178,17 @@ Using the usual definition of the inner product between matrices, ``` we can rearrange the inner product as follows: ```math -\begin{align} - \langle \bar{Y}, D f [X] (\dot{X}) \rangle &= \langle \bar{Y}, \dot{X}^\top X + X^\top \dot{X} \rangle \nonumber \\ - &= \textrm{tr} (\bar{Y}^\top \dot{X}^\top X) + \textrm{tr}(\bar{Y}^\top X^\top \dot{X}) \nonumber \\ - &= \textrm{tr} ( [\bar{Y} X^\top]^\top \dot{X}) + \textrm{tr}( [X \bar{Y}]^\top \dot{X}) \nonumber \\ - &= \langle \bar{Y} X^\top + X \bar{Y}, \dot{X} \rangle. \nonumber -\end{align} -``` -We can read off the adjoint operator from the first argument to the inner product: +\begin{align*} +\langle\bar{Y},Df[X](\dot{X})\rangle & =\langle\bar{Y},\dot{X}^{\top}X+X^{\top}\dot{X}\rangle\\ + & =\textrm{tr}(\bar{Y}^{\top}\left(\dot{X}^{T}X+X^{T}\dot{X}\right))\\ + & =\textrm{tr}(\dot{X}^{\top}X\bar{Y}^{\top})+\textrm{tr}(\bar{Y}^{\top}X^{\top}\dot{X})\\ + & =\langle\dot{X},X\bar{Y}^{\top}\rangle+\langle\bar{Y}^{\top}X^{\top},\dot{X}\rangle\\
```suggestion & =\langle\dot{X},X\bar{Y}^{\top}\rangle+\langle X\bar{Y},\dot{X}\rangle\\ ``` I think the first arg to the second inner product should be transposed, since `<A, B> = tr(A^T B)`
Mooncake.jl
github_2023
others
408
compintell
willtebbutt
@@ -178,16 +178,17 @@ Using the usual definition of the inner product between matrices, ``` we can rearrange the inner product as follows: ```math -\begin{align} - \langle \bar{Y}, D f [X] (\dot{X}) \rangle &= \langle \bar{Y}, \dot{X}^\top X + X^\top \dot{X} \rangle \nonumber \\ - &= \textrm{tr} (\bar{Y}^\top \dot{X}^\top X) + \textrm{tr}(\bar{Y}^\top X^\top \dot{X}) \nonumber \\ - &= \textrm{tr} ( [\bar{Y} X^\top]^\top \dot{X}) + \textrm{tr}( [X \bar{Y}]^\top \dot{X}) \nonumber \\ - &= \langle \bar{Y} X^\top + X \bar{Y}, \dot{X} \rangle. \nonumber -\end{align} -``` -We can read off the adjoint operator from the first argument to the inner product: +\begin{align*} +\langle\bar{Y},Df[X](\dot{X})\rangle & =\langle\bar{Y},\dot{X}^{\top}X+X^{\top}\dot{X}\rangle\\ + & =\textrm{tr}(\bar{Y}^{\top}\left(\dot{X}^{T}X+X^{T}\dot{X}\right))\\ + & =\textrm{tr}(\dot{X}^{\top}X\bar{Y}^{\top})+\textrm{tr}(\bar{Y}^{\top}X^{\top}\dot{X})\\ + & =\langle\dot{X},X\bar{Y}^{\top}\rangle+\langle\bar{Y}^{\top}X^{\top},\dot{X}\rangle\\ + & =\langle X\bar{Y}^{\top}+X\bar{Y},\dot{X}\rangle.
```suggestion & =\langle X(\bar{Y}^{\top} + \bar{Y}),\dot{X}\rangle. ``` should we simplify to this?
Mooncake.jl
github_2023
others
408
compintell
willtebbutt
@@ -178,16 +178,17 @@ Using the usual definition of the inner product between matrices, ``` we can rearrange the inner product as follows: ```math -\begin{align} - \langle \bar{Y}, D f [X] (\dot{X}) \rangle &= \langle \bar{Y}, \dot{X}^\top X + X^\top \dot{X} \rangle \nonumber \\ - &= \textrm{tr} (\bar{Y}^\top \dot{X}^\top X) + \textrm{tr}(\bar{Y}^\top X^\top \dot{X}) \nonumber \\ - &= \textrm{tr} ( [\bar{Y} X^\top]^\top \dot{X}) + \textrm{tr}( [X \bar{Y}]^\top \dot{X}) \nonumber \\ - &= \langle \bar{Y} X^\top + X \bar{Y}, \dot{X} \rangle. \nonumber -\end{align} -``` -We can read off the adjoint operator from the first argument to the inner product: +\begin{align*} +\langle\bar{Y},Df[X](\dot{X})\rangle & =\langle\bar{Y},\dot{X}^{\top}X+X^{\top}\dot{X}\rangle\\ + & =\textrm{tr}(\bar{Y}^{\top}\left(\dot{X}^{T}X+X^{T}\dot{X}\right))\\ + & =\textrm{tr}(\dot{X}^{\top}X\bar{Y}^{\top})+\textrm{tr}(\bar{Y}^{\top}X^{\top}\dot{X})\\ + & =\langle\dot{X},X\bar{Y}^{\top}\rangle+\langle\bar{Y}^{\top}X^{\top},\dot{X}\rangle\\ + & =\langle X\bar{Y}^{\top}+X\bar{Y},\dot{X}\rangle. +\end{align*} +``` +The linearity of inner products and trace, and the [cyclic property of trace](https://en.wikipedia.org/wiki/Trace_(linear_algebra)#Cyclic_property) was used in the above. We can read off the adjoint operator from the first argument to the inner product: ```math -D f [X]^\ast (\bar{Y}) = \bar{Y} X^\top + X \bar{Y}. +D f [X]^\ast (\bar{Y}) = \bar{Y}^{\top} X + X \bar{Y}.
I think this now has a different typo haha -- the multiplication order of `X` and `\bar{Y}` has been swapped, and I don't believe it should have been. ```suggestion D f [X]^\ast (\bar{Y}) = X (\bar{Y}^{\top} + \bar{Y}). ```
Mooncake.jl
github_2023
others
422
compintell
yebai
@@ -1044,6 +1044,8 @@ function tangent_test_cases() (a=3, b=randn(10)), (a=randn(10), b=randn(10)), (Base.TOML.ErrorType(1), NoTangent()), # Enum + (((((randn(33)...,),),),),),
```suggestion # Regression tests to catch type inference failures, see https://github.com/compintell/Mooncake.jl/pull/422 (((((randn(33)...,),),),),), ```
Mooncake.jl
github_2023
others
421
compintell
willtebbutt
@@ -94,7 +94,7 @@ _simple_mlp(W2, W1, Y, X) = sum(abs2, Y - W2 * map(x -> x * (0 <= x), W1 * X)) _gp_lml(x, y, s) = logpdf(GP(SEKernel())(x, s), y) should_run_benchmark(::Val{:reverse_diff}, ::typeof(_gp_lml), x...) = false -should_run_benchmark(::Val{:enzyme}, ::typeof(_gp_lml), x...) = false +should_run_benchmark(::Val{:enzyme}, ::typeof(_gp_lml), x...) = true
```suggestion ``` This can just be removed
Mooncake.jl
github_2023
others
390
compintell
willtebbutt
@@ -256,31 +254,31 @@ function increment_and_get_rdata!(f, r, t::CRC.Thunk) return increment_and_get_rdata!(f, r, CRC.unthunk(t)) end -@doc""" - rrule_wrapper(f::CoDual, args::CoDual...) +@doc """ + rrule_wrapper(f::CoDual, args::CoDual...) -Used to implement `rrule!!`s via `ChainRulesCore.rrule`. + Used to implement `rrule!!`s via `ChainRulesCore.rrule`. -Given a function `foo`, argument types `arg_types`, and a method of `ChainRulesCore.rrule` -which applies to these, you can make use of this function as follows: -```julia -Mooncake.@is_primitive DefaultCtx Tuple{typeof(foo), arg_types...} -function Mooncake.rrule!!(f::CoDual{typeof(foo)}, args::CoDual...) - return rrule_wrapper(f, args...) -end -``` -Assumes that methods of `to_cr_tangent` and `to_mooncake_tangent` are defined such that you -can convert between the different representations of tangents that Mooncake and -ChainRulesCore expect. + Given a function `foo`, argument types `arg_types`, and a method of `ChainRulesCore.rrule` + which applies to these, you can make use of this function as follows: + ```julia + Mooncake.@is_primitive DefaultCtx Tuple{typeof(foo), arg_types...} + function Mooncake.rrule!!(f::CoDual{typeof(foo)}, args::CoDual...) + return rrule_wrapper(f, args...) + end + ``` + Assumes that methods of `to_cr_tangent` and `to_mooncake_tangent` are defined such that you + can convert between the different representations of tangents that Mooncake and + ChainRulesCore expect. -Furthermore, it is _essential_ that -1. `f(args)` does not mutate `f` or `args`, and -2. the result of `f(args)` does not alias any data stored in `f` or `args`. + Furthermore, it is _essential_ that + 1. `f(args)` does not mutate `f` or `args`, and + 2. the result of `f(args)` does not alias any data stored in `f` or `args`.
This looks like a bug to me. Does it also look like a bug to you @gdalle ?
Mooncake.jl
github_2023
others
390
compintell
willtebbutt
@@ -3,6 +3,7 @@ include("front_matter.jl") @testset "Mooncake.jl" begin if test_group == "aqua"
We should probably rename this test group to "automated quality assurance", or really anything which highlights that it's not just Aqua.jl anymore.
Mooncake.jl
github_2023
others
320
compintell
ChrisRackauckas
@@ -0,0 +1,20 @@ +module MooncakeDiffEqBaseExt + +using DiffEqBase, Mooncake + +Mooncake.@from_rrule(
I think you'll need the solution adjoints as well. Should this all live with DiffEqBase?
Mooncake.jl
github_2023
others
354
compintell
mhauru
@@ -494,9 +494,42 @@ tangent field. This function uses [`Mooncake.build_rrule`](@ref) to construct a rule. This will use an `rrule!!` if one exists, and derive a rule otherwise. + +# Arguments +- `rng::AbstractRNG`: a random number generator +- `x...`: the function (first element) and its arguments (the remainder) + +# Keyword Arguments +- `interface_only::Bool=false`: test only that the interface is satisfied, without testing + correctness. This should generally be set to `true` (the default value), and only + disabled if the testing infrastructure is unable to test correctness for some reason
Is the default value the wrong way around here?
Mooncake.jl
github_2023
others
353
compintell
willtebbutt
@@ -0,0 +1,123 @@ +using Pkg +Pkg.activate(@__DIR__) +Pkg.develop(; path = joinpath(@__DIR__, "..", "..", "..")) + +using Bijectors: Bijectors +using LinearAlgebra: LinearAlgebra +using Random: randn + +""" +Type for specifying a test case for `test_rule`. +""" +struct TestCase + func::Function + arg::Any + name::Union{String,Nothing} +end + +TestCase(f, arg; name = nothing) = TestCase(f, arg, name) + +""" +A helper function that returns a TestCase that evaluates sum(bijector(inverse(bijector)(x))) +""" +function sum_b_binv_test_case(bijector, dim; name = nothing, rng = Xoshiro(23))
Why is is that you're summing over the output in all cases?
Mooncake.jl
github_2023
others
301
compintell
sunxd3
@@ -0,0 +1,23 @@ +# Running Tests Locally + +Mooncake.jl's test suite is fairly extensive. While you can use `Pkg.test` to run the test suite in the standard manner, this is not usually optimal in Mooncake.jl. When editing some code, you typically only want to run the tests associated with it, not the entire test suite. + +Mooncake's tests are organised as follows: +1. Things that are required for most / all test suites are loaded up in `test/front_matter.jl`. +1. The tests for something in `src` are located in an identically-named file in `test`. e.g. the unit tests for `src/rrules/new.jl` are located in `test/rrules/new.jl`. + +Thus, a workflow that I (Will) find works very well is the following: +1. Ensure that you have Revise.jl and TestEnv.jl installed in your default environment. +1. start the REPL, `dev` Mooncake.jl, and navigate to the top level of the Mooncake.jl directory. +1. `using TestEnv, Revise`. Better still, load both of these in your `.julia/config/startup.jl` file so that you don't ever forget to load them. +1. Run the following: `using Pkg; Pkg.activate("."); TestEnv.activate(); include("test/front_matter.jl");` to set up your environment.
not a suggestion, just a anecdotal point from me: I configure VSCode to automatically do the `Pkg.activate()` for the package folder I open. But what you wrote is better as it assumes less.
Mooncake.jl
github_2023
others
254
compintell
yebai
@@ -1,17 +1,9 @@ module MooncakeDynamicPPLExt -if isdefined(Base, :get_extension) - using DynamicPPL: DynamicPPL, istrans - using Mooncake: Mooncake -else - using ..DynamicPPL: DynamicPPL, istrans - using ..Mooncake: Mooncake -end - -using Mooncake: DefaultCtx, CoDual, simple_zero_adjoint +using DynamicPPL: DynamicPPL, istrans +using Mooncake: Mooncake # This is purely an optimisation. -Mooncake.@is_primitive DefaultCtx Tuple{typeof(istrans), Vararg} -Mooncake.rrule!!(f::CoDual{typeof(istrans)}, x::CoDual...) = simple_zero_adjoint(f, x...) +Mooncake.@zero_adjoint Mooncake.DefaultCtx Tuple{typeof(istrans), Vararg}
It looks good; can we remove the need for users to pass `Mooncake.DefaultCtx` explicitly, mainly if there is a `DefaultCtx` for most cases? We can still support users in specifying customised contexts if needed.
Mooncake.jl
github_2023
others
254
compintell
yebai
@@ -0,0 +1,66 @@ +module MooncakeNNlibExt + +using NNlib, Random, Mooncake +using Base: IEEEFloat +using NNlib: dropout + +using NNlib: conv, depthwiseconv +import Mooncake: @from_rrule, DefaultCtx, MinimalCtx + +@from_rrule( + MinimalCtx, + Tuple{typeof(batched_mul), Array{P, 3}, Array{P, 3}} where {P<:IEEEFloat}, +) +@from_rrule( + MinimalCtx, + Tuple{typeof(dropout), AbstractRNG, Array{P}, P} where {P<:IEEEFloat}, + true, +) +@from_rrule(MinimalCtx, Tuple{typeof(softmax), Array{<:IEEEFloat}}, true) +@from_rrule(MinimalCtx, Tuple{typeof(logsoftmax), Array{<:IEEEFloat}}, true) +@from_rrule(MinimalCtx, Tuple{typeof(logsumexp), Array{<:IEEEFloat}}, true) +@from_rrule( + MinimalCtx, + Tuple{typeof(upsample_nearest), Array{<:IEEEFloat}, NTuple{N, Int} where {N}}, +) +@from_rrule( + MinimalCtx, + Tuple{ + typeof(NNlib.fold), Array{<:IEEEFloat}, NTuple{N, Int} where {N}, DenseConvDims, + }, +) +@from_rrule( + MinimalCtx, Tuple{typeof(NNlib.unfold), Array{<:IEEEFloat}, DenseConvDims} +) +@from_rrule( + MinimalCtx, + Tuple{typeof(NNlib.scatter), Any, Array, Array{<:Union{Integer, Tuple}}}, + true, +) +for conv in [:conv, :depthwiseconv] + local ∇conv_data, ∇conv_filter = Symbol.(:∇, conv, [:_data, :_filter]) + + @eval @from_rrule( + MinimalCtx, + Tuple{typeof($conv), Array{P}, Array{P}, ConvDims} where {P<:IEEEFloat}, + true, + ) + @eval @from_rrule( + MinimalCtx, + Tuple{typeof($∇conv_data), Array{P}, Array{P}, ConvDims} where {P<:IEEEFloat}, + true, + ) +end +@eval @from_rrule(
I am slightly confused about the use of `@eval` in some places but not others. Can you clarify the differences? ```suggestion @from_rrule( ```
Mooncake.jl
github_2023
others
254
compintell
yebai
@@ -0,0 +1,477 @@ +# +# General utilities +# + +function parse_signature_expr(sig::Expr) + # Different parsing is required for `Tuple{...}` vs `Tuple{...} where ...`. + if sig.head == :curly + @assert sig.args[1] == :Tuple + arg_type_symbols = sig.args[2:end] + where_params = nothing + elseif sig.head == :where + @assert sig.args[1].args[1] == :Tuple + arg_type_symbols = sig.args[1].args[2:end] + where_params = sig.args[2:end] + else + throw(ArgumentError("Expected either a `Tuple{...}` or `Tuple{...} where {...}")) + end + return arg_type_symbols, where_params +end + +function construct_def(arg_names, arg_types, where_params, body) + name = :(Mooncake.rrule!!) + arg_exprs = map((n, t) -> :($n::$t), arg_names, arg_types) + def = Dict(:head => :function, :name => name, :args => arg_exprs, :body => body) + where_params !== nothing && setindex!(def, where_params, :whereparams) + return ExprTools.combinedef(def) +end + +# +# Functionality supporting @mooncake_overlay +# + +""" + @mooncake_overlay method_expr + +Define a method of a function which only Mooncake can see. This can be used to write
Consider adding a reference to Julia's overlay docs for people who don't know what method overlays are yet (I didn't know until recently seeing them in Reactant).
Mooncake.jl
github_2023
others
254
compintell
yebai
@@ -0,0 +1,477 @@ +# +# General utilities +# + +function parse_signature_expr(sig::Expr) + # Different parsing is required for `Tuple{...}` vs `Tuple{...} where ...`. + if sig.head == :curly + @assert sig.args[1] == :Tuple + arg_type_symbols = sig.args[2:end] + where_params = nothing + elseif sig.head == :where + @assert sig.args[1].args[1] == :Tuple + arg_type_symbols = sig.args[1].args[2:end] + where_params = sig.args[2:end] + else + throw(ArgumentError("Expected either a `Tuple{...}` or `Tuple{...} where {...}")) + end + return arg_type_symbols, where_params +end + +function construct_def(arg_names, arg_types, where_params, body) + name = :(Mooncake.rrule!!) + arg_exprs = map((n, t) -> :($n::$t), arg_names, arg_types) + def = Dict(:head => :function, :name => name, :args => arg_exprs, :body => body) + where_params !== nothing && setindex!(def, where_params, :whereparams) + return ExprTools.combinedef(def) +end + +# +# Functionality supporting @mooncake_overlay +# + +""" + @mooncake_overlay method_expr + +Define a method of a function which only Mooncake can see. This can be used to write +versions of methods which can be successfully differentiated by Mooncake if the original +cannot be. + +For example, suppose that you have a function +```jldoctest overlay +julia> foo(x::Float64) = bar(x) +foo (generic function with 1 method) +``` +where Mooncake.jl fails to differentiate `bar` for some reason. +If you have access to another function `baz`, which does the same thing as `bar`, but does + so in a way which Mooncake.jl can differentiate, you can simply write: +```jldoctest overlay +julia> Mooncake.@mooncake_overlay foo(x::Float64) = baz(x) + +``` +When looking up the code for `foo(::Float64)`, Mooncake.jl will see this method, rather than +the original, and differentiate it instead. + +# A Worked Example + +To demonstrate how to use `@mooncake_overlay`s in practice, we here demonstrate how the +answer that Mooncake.jl gives changes if you change the definition of a function using a +`@mooncake_overlay`. +Do not do this in practice -- this is just a simple way to demonostrate how to use overlays! + +First, consider a simple example: +```jldoctest overlay-doctest +julia> scale(x) = 2x +scale (generic function with 1 method) + +julia> rule = Mooncake.build_rrule(Tuple{typeof(scale), Float64}); + +julia> Mooncake.value_and_gradient!!(rule, scale, 5.0) +(10.0, (NoTangent(), 2.0)) +``` + +We can use `@mooncake_overlay` to change the definition which Mooncake.jl sees: +```jldoctest overlay-doctest +julia> Mooncake.@mooncake_overlay scale(x) = 3x + +julia> rule = Mooncake.build_rrule(Tuple{typeof(scale), Float64}); + +julia> Mooncake.value_and_gradient!!(rule, scale, 5.0) +(15.0, (NoTangent(), 3.0)) +``` +As can be seen from the output, the result of differentiating using Mooncake.jl has changed +to reflect the overlay-ed definition of the method. + +Additionally, it is possible to use the usual multi-line syntax to declare an overlay: +```jldoctest overlay-doctest +julia> Mooncake.@mooncake_overlay function scale(x) + return 4x + end + +julia> rule = Mooncake.build_rrule(Tuple{typeof(scale), Float64}); + +julia> Mooncake.value_and_gradient!!(rule, scale, 5.0) +(20.0, (NoTangent(), 4.0)) +``` +""" +macro mooncake_overlay(method_expr) + def = splitdef(method_expr) + def[:name] = Expr(:overlay, :(Mooncake.mooncake_method_table), def[:name]) + return esc(combinedef(def)) +end + +# +# Functionality supporting @zero_adjoint +# + +""" + zero_adjoint(f::CoDual, x::Vararg{CoDual, N}) where {N} + +Utility functionality for constructing `rrule!!`s for functions which produce adjoints which +always return zero. + +NOTE: you should only make use of this function if you cannot make use of the +[`@zero_adjoint`](@ref) macro. + +You make use of this functionality by writing a method of `Mooncake.rrule!!`, and +passing all of its arguments (including the function itself) to this function. For example: +```jldoctest +julia> import Mooncake: zero_adjoint, DefaultCtx, zero_fcodual, rrule!!, is_primitive, CoDual + +julia> foo(x::Vararg{Int}) = 5 +foo (generic function with 1 method) + +julia> is_primitive(::Type{DefaultCtx}, ::Type{<:Tuple{typeof(foo), Vararg{Int}}}) = true; + +julia> rrule!!(f::CoDual{typeof(foo)}, x::Vararg{CoDual{Int}}) = zero_adjoint(f, x...); + +julia> rrule!!(zero_fcodual(foo), zero_fcodual(3), zero_fcodual(2))[2](NoRData()) +(NoRData(), NoRData(), NoRData()) +``` + +WARNING: this is only correct if the output of `primal(f)(map(primal, x)...)` does not alias +anything in `f` or `x`. This is always the case if the result is a bits type, but more care +may be required if it is not. +``` +""" +@inline function zero_adjoint(f::CoDual, x::Vararg{CoDual, N}) where {N} + return zero_fcodual(primal(f)(map(primal, x)...)), NoPullback(f, x...) +end + +""" + @zero_adjoint ctx sig
As commented above, it is helpful to have a variant of `@zero_adjoint` with a default `ctx`, so users don't need to pass it explicitly unless in exceptional circumstances.
Mooncake.jl
github_2023
others
254
compintell
yebai
@@ -0,0 +1,477 @@ +# +# General utilities +# + +function parse_signature_expr(sig::Expr) + # Different parsing is required for `Tuple{...}` vs `Tuple{...} where ...`. + if sig.head == :curly + @assert sig.args[1] == :Tuple + arg_type_symbols = sig.args[2:end] + where_params = nothing + elseif sig.head == :where + @assert sig.args[1].args[1] == :Tuple + arg_type_symbols = sig.args[1].args[2:end] + where_params = sig.args[2:end] + else + throw(ArgumentError("Expected either a `Tuple{...}` or `Tuple{...} where {...}")) + end + return arg_type_symbols, where_params +end + +function construct_def(arg_names, arg_types, where_params, body) + name = :(Mooncake.rrule!!) + arg_exprs = map((n, t) -> :($n::$t), arg_names, arg_types) + def = Dict(:head => :function, :name => name, :args => arg_exprs, :body => body) + where_params !== nothing && setindex!(def, where_params, :whereparams) + return ExprTools.combinedef(def) +end + +# +# Functionality supporting @mooncake_overlay +# + +""" + @mooncake_overlay method_expr + +Define a method of a function which only Mooncake can see. This can be used to write +versions of methods which can be successfully differentiated by Mooncake if the original +cannot be. + +For example, suppose that you have a function +```jldoctest overlay +julia> foo(x::Float64) = bar(x) +foo (generic function with 1 method) +``` +where Mooncake.jl fails to differentiate `bar` for some reason. +If you have access to another function `baz`, which does the same thing as `bar`, but does + so in a way which Mooncake.jl can differentiate, you can simply write: +```jldoctest overlay +julia> Mooncake.@mooncake_overlay foo(x::Float64) = baz(x) + +``` +When looking up the code for `foo(::Float64)`, Mooncake.jl will see this method, rather than +the original, and differentiate it instead. + +# A Worked Example + +To demonstrate how to use `@mooncake_overlay`s in practice, we here demonstrate how the +answer that Mooncake.jl gives changes if you change the definition of a function using a +`@mooncake_overlay`. +Do not do this in practice -- this is just a simple way to demonostrate how to use overlays! + +First, consider a simple example: +```jldoctest overlay-doctest +julia> scale(x) = 2x +scale (generic function with 1 method) + +julia> rule = Mooncake.build_rrule(Tuple{typeof(scale), Float64}); + +julia> Mooncake.value_and_gradient!!(rule, scale, 5.0) +(10.0, (NoTangent(), 2.0)) +``` + +We can use `@mooncake_overlay` to change the definition which Mooncake.jl sees: +```jldoctest overlay-doctest +julia> Mooncake.@mooncake_overlay scale(x) = 3x + +julia> rule = Mooncake.build_rrule(Tuple{typeof(scale), Float64}); + +julia> Mooncake.value_and_gradient!!(rule, scale, 5.0) +(15.0, (NoTangent(), 3.0)) +``` +As can be seen from the output, the result of differentiating using Mooncake.jl has changed +to reflect the overlay-ed definition of the method. + +Additionally, it is possible to use the usual multi-line syntax to declare an overlay: +```jldoctest overlay-doctest +julia> Mooncake.@mooncake_overlay function scale(x) + return 4x + end + +julia> rule = Mooncake.build_rrule(Tuple{typeof(scale), Float64}); + +julia> Mooncake.value_and_gradient!!(rule, scale, 5.0) +(20.0, (NoTangent(), 4.0)) +``` +""" +macro mooncake_overlay(method_expr) + def = splitdef(method_expr) + def[:name] = Expr(:overlay, :(Mooncake.mooncake_method_table), def[:name]) + return esc(combinedef(def)) +end + +# +# Functionality supporting @zero_adjoint +# + +""" + zero_adjoint(f::CoDual, x::Vararg{CoDual, N}) where {N} + +Utility functionality for constructing `rrule!!`s for functions which produce adjoints which +always return zero. + +NOTE: you should only make use of this function if you cannot make use of the +[`@zero_adjoint`](@ref) macro. + +You make use of this functionality by writing a method of `Mooncake.rrule!!`, and +passing all of its arguments (including the function itself) to this function. For example: +```jldoctest +julia> import Mooncake: zero_adjoint, DefaultCtx, zero_fcodual, rrule!!, is_primitive, CoDual + +julia> foo(x::Vararg{Int}) = 5 +foo (generic function with 1 method) + +julia> is_primitive(::Type{DefaultCtx}, ::Type{<:Tuple{typeof(foo), Vararg{Int}}}) = true; + +julia> rrule!!(f::CoDual{typeof(foo)}, x::Vararg{CoDual{Int}}) = zero_adjoint(f, x...); + +julia> rrule!!(zero_fcodual(foo), zero_fcodual(3), zero_fcodual(2))[2](NoRData()) +(NoRData(), NoRData(), NoRData()) +``` + +WARNING: this is only correct if the output of `primal(f)(map(primal, x)...)` does not alias +anything in `f` or `x`. This is always the case if the result is a bits type, but more care +may be required if it is not. +``` +""" +@inline function zero_adjoint(f::CoDual, x::Vararg{CoDual, N}) where {N} + return zero_fcodual(primal(f)(map(primal, x)...)), NoPullback(f, x...) +end + +""" + @zero_adjoint ctx sig + +Defines `is_primitive(context_type, sig) = true`, and defines a method of +`Mooncake.rrule!!` which returns zero for all inputs. +Users of ChainRules.jl should be familiar with this functionality -- it is morally the same +as `ChainRulesCore.@non_differentiable`.
I find the name `@non_differentiable` more intuitive. Is there any good reason for preferring the name `zero_adjoint` over `non_differentiable`?
Mooncake.jl
github_2023
others
254
compintell
mhauru
@@ -0,0 +1,33 @@ +# Tools for Rules + +Most of the time, Mooncake.jl can just differentiate your code, but you will need to intervene if you make use of a language feature which is unsupported. +However, this does not always necessitate writing your own `rrule!!` from scratch. +In this section, we detail some useful strategies which can help you avoid having to write `rrule!!`s in many situations. + +## Simplfiying Code via Overlays + +```@docs +Mooncake.@mooncake_overlay +``` + +## Functions with Zero Adjoint + +If the above strategy does not work, but you find yourself in the surprisingly common +situation that the adjoint of the derivative of your function is always zero, you can very +straightforwardly write a rule by making use of the following: +```@docs +Mooncake.@zero_adjoint +Mooncake.zero_adjoint +``` + +## Using ChainRules.jl + +[ChainRules.jl](https://github.com/JuliaDiff/ChainRules.jl) provides a large number of rules for differentiating functions in reverse-mode. +These rules are methods of the `ChainRulesCore.rrule` function. +There are some instances where there is it most convenient to implement a `Mooncake.rrule!!` by wrapping an existing `ChainRulesCore.rrule`.
```suggestion There are some instances where it is most convenient to implement a `Mooncake.rrule!!` by wrapping an existing `ChainRulesCore.rrule`. ```
Mooncake.jl
github_2023
others
254
compintell
mhauru
@@ -181,18 +184,31 @@ there is no code found, or if more than one `IRCode` instance returned. Returns a tuple containing the `IRCode` and its return type. """ -function lookup_ir(interp::CC.AbstractInterpreter, sig::Type{<:Tuple}) - output = Base.code_ircode_by_type(sig; interp) - if isempty(output) - throw(ArgumentError("No methods found for signature $sig")) - elseif length(output) > 1 - throw(ArgumentError("$(length(output)) methods found for signature $sig")) +function lookup_ir(interp::CC.AbstractInterpreter, tt::Type{<:Tuple}; optimize_until=nothing)
The docstring says "Get the IR unique IR associated", probably a typo.
Mooncake.jl
github_2023
others
254
compintell
mhauru
@@ -0,0 +1,477 @@ +# +# General utilities +# + +function parse_signature_expr(sig::Expr) + # Different parsing is required for `Tuple{...}` vs `Tuple{...} where ...`. + if sig.head == :curly + @assert sig.args[1] == :Tuple + arg_type_symbols = sig.args[2:end] + where_params = nothing + elseif sig.head == :where + @assert sig.args[1].args[1] == :Tuple + arg_type_symbols = sig.args[1].args[2:end] + where_params = sig.args[2:end] + else + throw(ArgumentError("Expected either a `Tuple{...}` or `Tuple{...} where {...}")) + end + return arg_type_symbols, where_params +end + +function construct_def(arg_names, arg_types, where_params, body) + name = :(Mooncake.rrule!!) + arg_exprs = map((n, t) -> :($n::$t), arg_names, arg_types) + def = Dict(:head => :function, :name => name, :args => arg_exprs, :body => body) + where_params !== nothing && setindex!(def, where_params, :whereparams) + return ExprTools.combinedef(def) +end + +# +# Functionality supporting @mooncake_overlay +# + +""" + @mooncake_overlay method_expr + +Define a method of a function which only Mooncake can see. This can be used to write +versions of methods which can be successfully differentiated by Mooncake if the original +cannot be. + +For example, suppose that you have a function +```jldoctest overlay +julia> foo(x::Float64) = bar(x) +foo (generic function with 1 method) +``` +where Mooncake.jl fails to differentiate `bar` for some reason. +If you have access to another function `baz`, which does the same thing as `bar`, but does + so in a way which Mooncake.jl can differentiate, you can simply write: +```jldoctest overlay +julia> Mooncake.@mooncake_overlay foo(x::Float64) = baz(x) + +``` +When looking up the code for `foo(::Float64)`, Mooncake.jl will see this method, rather than +the original, and differentiate it instead. + +# A Worked Example + +To demonstrate how to use `@mooncake_overlay`s in practice, we here demonstrate how the +answer that Mooncake.jl gives changes if you change the definition of a function using a +`@mooncake_overlay`. +Do not do this in practice -- this is just a simple way to demonostrate how to use overlays! + +First, consider a simple example: +```jldoctest overlay-doctest +julia> scale(x) = 2x +scale (generic function with 1 method) + +julia> rule = Mooncake.build_rrule(Tuple{typeof(scale), Float64}); + +julia> Mooncake.value_and_gradient!!(rule, scale, 5.0) +(10.0, (NoTangent(), 2.0)) +``` + +We can use `@mooncake_overlay` to change the definition which Mooncake.jl sees: +```jldoctest overlay-doctest +julia> Mooncake.@mooncake_overlay scale(x) = 3x + +julia> rule = Mooncake.build_rrule(Tuple{typeof(scale), Float64}); + +julia> Mooncake.value_and_gradient!!(rule, scale, 5.0) +(15.0, (NoTangent(), 3.0)) +``` +As can be seen from the output, the result of differentiating using Mooncake.jl has changed +to reflect the overlay-ed definition of the method. + +Additionally, it is possible to use the usual multi-line syntax to declare an overlay: +```jldoctest overlay-doctest +julia> Mooncake.@mooncake_overlay function scale(x) + return 4x + end + +julia> rule = Mooncake.build_rrule(Tuple{typeof(scale), Float64}); + +julia> Mooncake.value_and_gradient!!(rule, scale, 5.0) +(20.0, (NoTangent(), 4.0)) +``` +""" +macro mooncake_overlay(method_expr) + def = splitdef(method_expr) + def[:name] = Expr(:overlay, :(Mooncake.mooncake_method_table), def[:name]) + return esc(combinedef(def)) +end + +# +# Functionality supporting @zero_adjoint +# + +""" + zero_adjoint(f::CoDual, x::Vararg{CoDual, N}) where {N} + +Utility functionality for constructing `rrule!!`s for functions which produce adjoints which +always return zero. + +NOTE: you should only make use of this function if you cannot make use of the +[`@zero_adjoint`](@ref) macro. + +You make use of this functionality by writing a method of `Mooncake.rrule!!`, and +passing all of its arguments (including the function itself) to this function. For example: +```jldoctest +julia> import Mooncake: zero_adjoint, DefaultCtx, zero_fcodual, rrule!!, is_primitive, CoDual + +julia> foo(x::Vararg{Int}) = 5 +foo (generic function with 1 method) + +julia> is_primitive(::Type{DefaultCtx}, ::Type{<:Tuple{typeof(foo), Vararg{Int}}}) = true; + +julia> rrule!!(f::CoDual{typeof(foo)}, x::Vararg{CoDual{Int}}) = zero_adjoint(f, x...); + +julia> rrule!!(zero_fcodual(foo), zero_fcodual(3), zero_fcodual(2))[2](NoRData()) +(NoRData(), NoRData(), NoRData()) +``` + +WARNING: this is only correct if the output of `primal(f)(map(primal, x)...)` does not alias +anything in `f` or `x`. This is always the case if the result is a bits type, but more care +may be required if it is not. +``` +""" +@inline function zero_adjoint(f::CoDual, x::Vararg{CoDual, N}) where {N} + return zero_fcodual(primal(f)(map(primal, x)...)), NoPullback(f, x...) +end + +""" + @zero_adjoint ctx sig + +Defines `is_primitive(context_type, sig) = true`, and defines a method of +`Mooncake.rrule!!` which returns zero for all inputs. +Users of ChainRules.jl should be familiar with this functionality -- it is morally the same +as `ChainRulesCore.@non_differentiable`. + +For example: +```jldoctest +julia> using Mooncake: @zero_adjoint, DefaultCtx, zero_fcodual, rrule!!, is_primitive + +julia> foo(x) = 5 +foo (generic function with 1 method) + +julia> @zero_adjoint DefaultCtx Tuple{typeof(foo), Any} + +julia> is_primitive(DefaultCtx, Tuple{typeof(foo), Any}) +true + +julia> rrule!!(zero_fcodual(foo), zero_fcodual(3.0))[2](NoRData()) +(NoRData(), 0.0) +``` + +Limited support for `Vararg`s is also available. For example +```jldoctest +julia> using Mooncake: @zero_adjoint, DefaultCtx, zero_fcodual, rrule!!, is_primitive + +julia> foo_varargs(x...) = 5 +foo_varargs (generic function with 1 method) + +julia> @zero_adjoint DefaultCtx Tuple{typeof(foo_varargs), Vararg} + +julia> is_primitive(DefaultCtx, Tuple{typeof(foo_varargs), Any, Float64, Int}) +true + +julia> rrule!!(zero_fcodual(foo_varargs), zero_fcodual(3.0), zero_fcodual(5))[2](NoRData()) +(NoRData(), 0.0, NoRData()) +``` +Be aware that it is not currently possible to specify any of the type parameters of the +`Vararg`. For example, the signature `Tuple{typeof(foo), Vararg{Float64, 5}}` will not work
Will it error in some understandable way?
Mooncake.jl
github_2023
others
254
compintell
mhauru
@@ -0,0 +1,477 @@ +# +# General utilities +# + +function parse_signature_expr(sig::Expr) + # Different parsing is required for `Tuple{...}` vs `Tuple{...} where ...`. + if sig.head == :curly + @assert sig.args[1] == :Tuple + arg_type_symbols = sig.args[2:end] + where_params = nothing + elseif sig.head == :where + @assert sig.args[1].args[1] == :Tuple + arg_type_symbols = sig.args[1].args[2:end] + where_params = sig.args[2:end] + else + throw(ArgumentError("Expected either a `Tuple{...}` or `Tuple{...} where {...}")) + end + return arg_type_symbols, where_params +end + +function construct_def(arg_names, arg_types, where_params, body) + name = :(Mooncake.rrule!!) + arg_exprs = map((n, t) -> :($n::$t), arg_names, arg_types) + def = Dict(:head => :function, :name => name, :args => arg_exprs, :body => body) + where_params !== nothing && setindex!(def, where_params, :whereparams) + return ExprTools.combinedef(def) +end + +# +# Functionality supporting @mooncake_overlay +# + +""" + @mooncake_overlay method_expr + +Define a method of a function which only Mooncake can see. This can be used to write +versions of methods which can be successfully differentiated by Mooncake if the original +cannot be. + +For example, suppose that you have a function +```jldoctest overlay +julia> foo(x::Float64) = bar(x) +foo (generic function with 1 method) +``` +where Mooncake.jl fails to differentiate `bar` for some reason. +If you have access to another function `baz`, which does the same thing as `bar`, but does + so in a way which Mooncake.jl can differentiate, you can simply write: +```jldoctest overlay +julia> Mooncake.@mooncake_overlay foo(x::Float64) = baz(x) + +``` +When looking up the code for `foo(::Float64)`, Mooncake.jl will see this method, rather than +the original, and differentiate it instead. + +# A Worked Example + +To demonstrate how to use `@mooncake_overlay`s in practice, we here demonstrate how the +answer that Mooncake.jl gives changes if you change the definition of a function using a +`@mooncake_overlay`. +Do not do this in practice -- this is just a simple way to demonostrate how to use overlays! + +First, consider a simple example: +```jldoctest overlay-doctest +julia> scale(x) = 2x +scale (generic function with 1 method) + +julia> rule = Mooncake.build_rrule(Tuple{typeof(scale), Float64}); + +julia> Mooncake.value_and_gradient!!(rule, scale, 5.0) +(10.0, (NoTangent(), 2.0)) +``` + +We can use `@mooncake_overlay` to change the definition which Mooncake.jl sees: +```jldoctest overlay-doctest +julia> Mooncake.@mooncake_overlay scale(x) = 3x + +julia> rule = Mooncake.build_rrule(Tuple{typeof(scale), Float64}); + +julia> Mooncake.value_and_gradient!!(rule, scale, 5.0) +(15.0, (NoTangent(), 3.0)) +``` +As can be seen from the output, the result of differentiating using Mooncake.jl has changed +to reflect the overlay-ed definition of the method. + +Additionally, it is possible to use the usual multi-line syntax to declare an overlay: +```jldoctest overlay-doctest +julia> Mooncake.@mooncake_overlay function scale(x) + return 4x + end + +julia> rule = Mooncake.build_rrule(Tuple{typeof(scale), Float64}); + +julia> Mooncake.value_and_gradient!!(rule, scale, 5.0) +(20.0, (NoTangent(), 4.0)) +``` +""" +macro mooncake_overlay(method_expr) + def = splitdef(method_expr) + def[:name] = Expr(:overlay, :(Mooncake.mooncake_method_table), def[:name]) + return esc(combinedef(def)) +end + +# +# Functionality supporting @zero_adjoint +# + +""" + zero_adjoint(f::CoDual, x::Vararg{CoDual, N}) where {N} + +Utility functionality for constructing `rrule!!`s for functions which produce adjoints which +always return zero. + +NOTE: you should only make use of this function if you cannot make use of the +[`@zero_adjoint`](@ref) macro. + +You make use of this functionality by writing a method of `Mooncake.rrule!!`, and +passing all of its arguments (including the function itself) to this function. For example: +```jldoctest +julia> import Mooncake: zero_adjoint, DefaultCtx, zero_fcodual, rrule!!, is_primitive, CoDual + +julia> foo(x::Vararg{Int}) = 5 +foo (generic function with 1 method) + +julia> is_primitive(::Type{DefaultCtx}, ::Type{<:Tuple{typeof(foo), Vararg{Int}}}) = true; + +julia> rrule!!(f::CoDual{typeof(foo)}, x::Vararg{CoDual{Int}}) = zero_adjoint(f, x...); + +julia> rrule!!(zero_fcodual(foo), zero_fcodual(3), zero_fcodual(2))[2](NoRData()) +(NoRData(), NoRData(), NoRData()) +``` + +WARNING: this is only correct if the output of `primal(f)(map(primal, x)...)` does not alias +anything in `f` or `x`. This is always the case if the result is a bits type, but more care +may be required if it is not. +``` +""" +@inline function zero_adjoint(f::CoDual, x::Vararg{CoDual, N}) where {N} + return zero_fcodual(primal(f)(map(primal, x)...)), NoPullback(f, x...) +end + +""" + @zero_adjoint ctx sig + +Defines `is_primitive(context_type, sig) = true`, and defines a method of +`Mooncake.rrule!!` which returns zero for all inputs. +Users of ChainRules.jl should be familiar with this functionality -- it is morally the same +as `ChainRulesCore.@non_differentiable`. + +For example: +```jldoctest +julia> using Mooncake: @zero_adjoint, DefaultCtx, zero_fcodual, rrule!!, is_primitive + +julia> foo(x) = 5 +foo (generic function with 1 method) + +julia> @zero_adjoint DefaultCtx Tuple{typeof(foo), Any} + +julia> is_primitive(DefaultCtx, Tuple{typeof(foo), Any}) +true + +julia> rrule!!(zero_fcodual(foo), zero_fcodual(3.0))[2](NoRData()) +(NoRData(), 0.0) +``` + +Limited support for `Vararg`s is also available. For example +```jldoctest +julia> using Mooncake: @zero_adjoint, DefaultCtx, zero_fcodual, rrule!!, is_primitive + +julia> foo_varargs(x...) = 5 +foo_varargs (generic function with 1 method) + +julia> @zero_adjoint DefaultCtx Tuple{typeof(foo_varargs), Vararg} + +julia> is_primitive(DefaultCtx, Tuple{typeof(foo_varargs), Any, Float64, Int}) +true + +julia> rrule!!(zero_fcodual(foo_varargs), zero_fcodual(3.0), zero_fcodual(5))[2](NoRData()) +(NoRData(), 0.0, NoRData()) +``` +Be aware that it is not currently possible to specify any of the type parameters of the +`Vararg`. For example, the signature `Tuple{typeof(foo), Vararg{Float64, 5}}` will not work +with this macro. + +WARNING: this is only correct if the output of the function does not alias any fields of the +function, or any of its arguments. For example, applying this macro to the function `x -> x` +will yield incorrect results. + +As always, you should use [`TestUtils.test_rule`](@ref) to ensure that you've not +made a mistake. + +# Signatures Unsupported By This Macro + +If the signature you wish to apply `@zero_adjoint` to is not supported, for example because +it uses a `Vararg` with a type parameter, you can still make use of +[`zero_adjoint`](@ref). +""" +macro zero_adjoint(ctx, sig) + + # Parse the signature, and construct the rule definition. If it is a vararg definition, + # then the last argument requires special treatment. + arg_type_symbols, where_params = parse_signature_expr(sig) + arg_names = map(n -> Symbol("x_$n"), eachindex(arg_type_symbols)) + is_vararg = arg_type_symbols[end] === :Vararg + if is_vararg + arg_types = vcat( + map(t -> :(Mooncake.CoDual{<:$t}), arg_type_symbols[1:end-1]), + :(Vararg{Mooncake.CoDual}), + ) + splat_symbol = Expr(Symbol("..."), arg_names[end]) + body = Expr( + :call, Mooncake.zero_adjoint, arg_names[1:end-1]..., splat_symbol, + ) + else + arg_types = map(t -> :(Mooncake.CoDual{<:$t}), arg_type_symbols) + body = Expr(:call, Mooncake.zero_adjoint, arg_names...) + end + + # Return code to create a method of is_primitive and a rule. + ex = quote + Mooncake.is_primitive(::Type{$ctx}, ::Type{<:$sig}) = true + $(construct_def(arg_names, arg_types, where_params, body)) + end + return esc(ex) +end + +# +# Functionality supporting @from_rrule +# + +""" + to_cr_tangent(t) + +Convert a Mooncake tangent into a type that ChainRules.jl `rrule`s expect to see. +""" +to_cr_tangent(t::IEEEFloat) = t +to_cr_tangent(t::Array{<:IEEEFloat}) = t +to_cr_tangent(::NoTangent) = ChainRulesCore.NoTangent() + +""" + increment_and_get_rdata!(fdata, zero_rdata, cr_tangent) + +Increment `fdata` by the fdata component of the ChainRules.jl-style tangent, `cr_tangent`, +and return the rdata component of `cr_tangent` by adding it to `zero_rdata`. +""" +increment_and_get_rdata!(::NoFData, r::T, t::T) where {T<:IEEEFloat} = r + t +function increment_and_get_rdata!(f::Array{P}, ::NoRData, t::Array{P}) where {P<:IEEEFloat} + increment!!(f, t)
I don't really know what this does, but it jumps at me as a call to `!!` that ignores the return value. If `increment!!` is guaranteed to mutate rather than create a new instance, could it be called `increment!`? If not, might this fail to do what is expected of it?
Mooncake.jl
github_2023
others
254
compintell
mhauru
@@ -0,0 +1,477 @@ +# +# General utilities +# + +function parse_signature_expr(sig::Expr) + # Different parsing is required for `Tuple{...}` vs `Tuple{...} where ...`. + if sig.head == :curly + @assert sig.args[1] == :Tuple + arg_type_symbols = sig.args[2:end] + where_params = nothing + elseif sig.head == :where + @assert sig.args[1].args[1] == :Tuple + arg_type_symbols = sig.args[1].args[2:end] + where_params = sig.args[2:end] + else + throw(ArgumentError("Expected either a `Tuple{...}` or `Tuple{...} where {...}")) + end + return arg_type_symbols, where_params +end + +function construct_def(arg_names, arg_types, where_params, body) + name = :(Mooncake.rrule!!) + arg_exprs = map((n, t) -> :($n::$t), arg_names, arg_types) + def = Dict(:head => :function, :name => name, :args => arg_exprs, :body => body) + where_params !== nothing && setindex!(def, where_params, :whereparams) + return ExprTools.combinedef(def) +end + +# +# Functionality supporting @mooncake_overlay +# + +""" + @mooncake_overlay method_expr + +Define a method of a function which only Mooncake can see. This can be used to write +versions of methods which can be successfully differentiated by Mooncake if the original +cannot be. + +For example, suppose that you have a function +```jldoctest overlay +julia> foo(x::Float64) = bar(x) +foo (generic function with 1 method) +``` +where Mooncake.jl fails to differentiate `bar` for some reason. +If you have access to another function `baz`, which does the same thing as `bar`, but does + so in a way which Mooncake.jl can differentiate, you can simply write: +```jldoctest overlay +julia> Mooncake.@mooncake_overlay foo(x::Float64) = baz(x) + +``` +When looking up the code for `foo(::Float64)`, Mooncake.jl will see this method, rather than +the original, and differentiate it instead. + +# A Worked Example + +To demonstrate how to use `@mooncake_overlay`s in practice, we here demonstrate how the +answer that Mooncake.jl gives changes if you change the definition of a function using a +`@mooncake_overlay`. +Do not do this in practice -- this is just a simple way to demonostrate how to use overlays! + +First, consider a simple example: +```jldoctest overlay-doctest +julia> scale(x) = 2x +scale (generic function with 1 method) + +julia> rule = Mooncake.build_rrule(Tuple{typeof(scale), Float64}); + +julia> Mooncake.value_and_gradient!!(rule, scale, 5.0) +(10.0, (NoTangent(), 2.0)) +``` + +We can use `@mooncake_overlay` to change the definition which Mooncake.jl sees: +```jldoctest overlay-doctest +julia> Mooncake.@mooncake_overlay scale(x) = 3x + +julia> rule = Mooncake.build_rrule(Tuple{typeof(scale), Float64}); + +julia> Mooncake.value_and_gradient!!(rule, scale, 5.0) +(15.0, (NoTangent(), 3.0)) +``` +As can be seen from the output, the result of differentiating using Mooncake.jl has changed +to reflect the overlay-ed definition of the method. + +Additionally, it is possible to use the usual multi-line syntax to declare an overlay: +```jldoctest overlay-doctest +julia> Mooncake.@mooncake_overlay function scale(x) + return 4x + end + +julia> rule = Mooncake.build_rrule(Tuple{typeof(scale), Float64}); + +julia> Mooncake.value_and_gradient!!(rule, scale, 5.0) +(20.0, (NoTangent(), 4.0)) +``` +""" +macro mooncake_overlay(method_expr) + def = splitdef(method_expr) + def[:name] = Expr(:overlay, :(Mooncake.mooncake_method_table), def[:name]) + return esc(combinedef(def)) +end + +# +# Functionality supporting @zero_adjoint +# + +""" + zero_adjoint(f::CoDual, x::Vararg{CoDual, N}) where {N} + +Utility functionality for constructing `rrule!!`s for functions which produce adjoints which +always return zero. + +NOTE: you should only make use of this function if you cannot make use of the +[`@zero_adjoint`](@ref) macro. + +You make use of this functionality by writing a method of `Mooncake.rrule!!`, and +passing all of its arguments (including the function itself) to this function. For example: +```jldoctest +julia> import Mooncake: zero_adjoint, DefaultCtx, zero_fcodual, rrule!!, is_primitive, CoDual + +julia> foo(x::Vararg{Int}) = 5 +foo (generic function with 1 method) + +julia> is_primitive(::Type{DefaultCtx}, ::Type{<:Tuple{typeof(foo), Vararg{Int}}}) = true; + +julia> rrule!!(f::CoDual{typeof(foo)}, x::Vararg{CoDual{Int}}) = zero_adjoint(f, x...); + +julia> rrule!!(zero_fcodual(foo), zero_fcodual(3), zero_fcodual(2))[2](NoRData()) +(NoRData(), NoRData(), NoRData()) +``` + +WARNING: this is only correct if the output of `primal(f)(map(primal, x)...)` does not alias +anything in `f` or `x`. This is always the case if the result is a bits type, but more care +may be required if it is not. +``` +""" +@inline function zero_adjoint(f::CoDual, x::Vararg{CoDual, N}) where {N} + return zero_fcodual(primal(f)(map(primal, x)...)), NoPullback(f, x...) +end + +""" + @zero_adjoint ctx sig + +Defines `is_primitive(context_type, sig) = true`, and defines a method of +`Mooncake.rrule!!` which returns zero for all inputs. +Users of ChainRules.jl should be familiar with this functionality -- it is morally the same +as `ChainRulesCore.@non_differentiable`. + +For example: +```jldoctest +julia> using Mooncake: @zero_adjoint, DefaultCtx, zero_fcodual, rrule!!, is_primitive + +julia> foo(x) = 5 +foo (generic function with 1 method) + +julia> @zero_adjoint DefaultCtx Tuple{typeof(foo), Any} + +julia> is_primitive(DefaultCtx, Tuple{typeof(foo), Any}) +true + +julia> rrule!!(zero_fcodual(foo), zero_fcodual(3.0))[2](NoRData()) +(NoRData(), 0.0) +``` + +Limited support for `Vararg`s is also available. For example +```jldoctest +julia> using Mooncake: @zero_adjoint, DefaultCtx, zero_fcodual, rrule!!, is_primitive + +julia> foo_varargs(x...) = 5 +foo_varargs (generic function with 1 method) + +julia> @zero_adjoint DefaultCtx Tuple{typeof(foo_varargs), Vararg} + +julia> is_primitive(DefaultCtx, Tuple{typeof(foo_varargs), Any, Float64, Int}) +true + +julia> rrule!!(zero_fcodual(foo_varargs), zero_fcodual(3.0), zero_fcodual(5))[2](NoRData()) +(NoRData(), 0.0, NoRData()) +``` +Be aware that it is not currently possible to specify any of the type parameters of the +`Vararg`. For example, the signature `Tuple{typeof(foo), Vararg{Float64, 5}}` will not work +with this macro. + +WARNING: this is only correct if the output of the function does not alias any fields of the +function, or any of its arguments. For example, applying this macro to the function `x -> x` +will yield incorrect results. + +As always, you should use [`TestUtils.test_rule`](@ref) to ensure that you've not +made a mistake. + +# Signatures Unsupported By This Macro + +If the signature you wish to apply `@zero_adjoint` to is not supported, for example because +it uses a `Vararg` with a type parameter, you can still make use of +[`zero_adjoint`](@ref). +""" +macro zero_adjoint(ctx, sig) + + # Parse the signature, and construct the rule definition. If it is a vararg definition, + # then the last argument requires special treatment. + arg_type_symbols, where_params = parse_signature_expr(sig) + arg_names = map(n -> Symbol("x_$n"), eachindex(arg_type_symbols)) + is_vararg = arg_type_symbols[end] === :Vararg + if is_vararg + arg_types = vcat( + map(t -> :(Mooncake.CoDual{<:$t}), arg_type_symbols[1:end-1]), + :(Vararg{Mooncake.CoDual}), + ) + splat_symbol = Expr(Symbol("..."), arg_names[end]) + body = Expr( + :call, Mooncake.zero_adjoint, arg_names[1:end-1]..., splat_symbol, + ) + else + arg_types = map(t -> :(Mooncake.CoDual{<:$t}), arg_type_symbols) + body = Expr(:call, Mooncake.zero_adjoint, arg_names...) + end + + # Return code to create a method of is_primitive and a rule. + ex = quote + Mooncake.is_primitive(::Type{$ctx}, ::Type{<:$sig}) = true + $(construct_def(arg_names, arg_types, where_params, body)) + end + return esc(ex) +end + +# +# Functionality supporting @from_rrule +# + +""" + to_cr_tangent(t) + +Convert a Mooncake tangent into a type that ChainRules.jl `rrule`s expect to see. +""" +to_cr_tangent(t::IEEEFloat) = t +to_cr_tangent(t::Array{<:IEEEFloat}) = t +to_cr_tangent(::NoTangent) = ChainRulesCore.NoTangent() + +""" + increment_and_get_rdata!(fdata, zero_rdata, cr_tangent) + +Increment `fdata` by the fdata component of the ChainRules.jl-style tangent, `cr_tangent`, +and return the rdata component of `cr_tangent` by adding it to `zero_rdata`. +""" +increment_and_get_rdata!(::NoFData, r::T, t::T) where {T<:IEEEFloat} = r + t +function increment_and_get_rdata!(f::Array{P}, ::NoRData, t::Array{P}) where {P<:IEEEFloat} + increment!!(f, t) + return NoRData() +end +increment_and_get_rdata!(::Any, r, ::ChainRulesCore.NoTangent) = r +function increment_and_get_rdata!(f, r, t::ChainRulesCore.Thunk) + return increment_and_get_rdata!(f, r, ChainRulesCore.unthunk(t)) +end + +@doc""" + rrule_wrapper(f::CoDual, args::CoDual...) + +Used to implement `rrule!!`s via `ChainRulesCore.rrule`. + +Given a function `foo`, argument types `arg_types`, and a method `ChainRulesCore.rrule` of
```suggestion Given a function `foo`, argument types `arg_types`, and a method of `ChainRulesCore.rrule` ```
Mooncake.jl
github_2023
others
254
compintell
mhauru
@@ -0,0 +1,136 @@ +overlay_tester(x) = 2x +Mooncake.@mooncake_overlay overlay_tester(x) = 3x + +zero_tester(x) = 0 +Mooncake.@zero_adjoint MinimalCtx Tuple{typeof(zero_tester), Float64} + +vararg_zero_tester(x...) = 0 +Mooncake.@zero_adjoint MinimalCtx Tuple{typeof(vararg_zero_tester), Vararg} +
Is there a reason to have these outside the module?
Mooncake.jl
github_2023
others
281
compintell
willtebbutt
@@ -59,8 +59,12 @@ function logdensity_and_gradient(∇l::MooncakeGradientLogDensity, x::Vector{Flo end # Interop with ADTypes. +function getconfig(x::ADTypes.AutoMooncake) + c = x.config + isnothing(c) ? Mooncake.DEFAULT_CONFIG : c
```suggestion return isnothing(c) ? Mooncake.DEFAULT_CONFIG : c ``` formatting
Mooncake.jl
github_2023
others
228
compintell
willtebbutt
@@ -474,45 +448,36 @@ end stackdict[x] = zt return _map_if_assigned!(Base.Fix2(zero_tangent_internal, stackdict), zt, x)::Array{tangent_type(P), N} end -@inline function zero_tangent_internal(x::P, stackdict::IdDict) where {P<:Union{Tuple, NamedTuple}} - return tangent_type(P) == NoTangent ? NoTangent() : tuple_map(Base.Fix2(zero_tangent_internal, stackdict), x) -end -function zero_tangent_internal(x::P, stackdict::IdDict) where {P} - +function zero_tangent_internal(x::P, stackdict) where {P} tangent_type(P) == NoTangent && return NoTangent() if tangent_type(P) <: MutableTangent + stackdict isa IdDict || error("...")
Would you mind fleshing out the error message here. This should probably be `throw(ArgumentError("informative message"))`, rather than just a plain error.
Mooncake.jl
github_2023
others
228
compintell
willtebbutt
@@ -474,45 +448,36 @@ end stackdict[x] = zt return _map_if_assigned!(Base.Fix2(zero_tangent_internal, stackdict), zt, x)::Array{tangent_type(P), N} end -@inline function zero_tangent_internal(x::P, stackdict::IdDict) where {P<:Union{Tuple, NamedTuple}} - return tangent_type(P) == NoTangent ? NoTangent() : tuple_map(Base.Fix2(zero_tangent_internal, stackdict), x) -end -function zero_tangent_internal(x::P, stackdict::IdDict) where {P} - +function zero_tangent_internal(x::P, stackdict) where {P} tangent_type(P) == NoTangent && return NoTangent() if tangent_type(P) <: MutableTangent + stackdict isa IdDict || error("...") if haskey(stackdict, x) return stackdict[x]::tangent_type(P) end stackdict[x] = tangent_type(P)() # create a uninitialised MutableTangent # if circular reference exists, then the recursive call will first look up the stackdict # and return the uninitialised MutableTangent # after the recursive call returns, the stackdict will be initialised - stackdict[x].fields = backing_type(P)(zero_tangent_struct_field(x, stackdict)) + stackdict[x].fields = zero_tangent_struct_field(x, stackdict) return stackdict[x]::tangent_type(P) else - if isbitstype(P) - return zero_tangent_internal(x) - else - return tangent_type(P)(backing_type(P)(zero_tangent_struct_field(x, stackdict))) - end + return tangent_type(P)(zero_tangent_struct_field(x, stackdict)) end end -@inline function zero_tangent_struct_field(x::P, stackdict::IdDict) where {P} - return ntuple(fieldcount(P)) do n +@generated function zero_tangent_struct_field(x::P, stackdict::Union{IdDict, Nothing}) where {P}
You've gone for `Union{IdDict, Nothing}` here as the restriction on the type of `stackdict`, whereas in other places `Any` has been used. Can we use `Any` here as well, or is there a good reason not to that I'm missing?
Mooncake.jl
github_2023
others
228
compintell
willtebbutt
@@ -529,47 +494,56 @@ details -- this docstring is intentionally non-specific in order to avoid becomi Required for testing. Generate a randomly-chosen tangent to `x`. +The design is closely modelled after `zero_tangent`. """ -randn_tangent(::AbstractRNG, ::NoTangent) = NoTangent() -randn_tangent(rng::AbstractRNG, ::T) where {T<:IEEEFloat} = randn(rng, T) -function randn_tangent(rng::AbstractRNG, x::Array{T, N}) where {T, N} - dx = Array{tangent_type(T), N}(undef, size(x)...) - return _map_if_assigned!(Base.Fix1(randn_tangent, rng), dx, x) +function randn_tangent(rng::AbstractRNG, x::T) where {T} + return randn_tangent_internal(rng, x, isbitstype(T) ? nothing : IdDict()) +end + +randn_tangent_internal(::AbstractRNG, ::NoTangent, ::Any) = NoTangent() +randn_tangent_internal(rng::AbstractRNG, ::T, ::Any) where {T<:IEEEFloat} = randn(rng, T) +function randn_tangent_internal(rng::AbstractRNG, x::P, stackdict::Any) where {P<:Union{Tuple, NamedTuple}} + return tangent_type(P) == NoTangent ? NoTangent() : tuple_map(x -> randn_tangent_internal(rng, x, stackdict), x) end -function randn_tangent(rng::AbstractRNG, x::SimpleVector) +function randn_tangent_internal(rng::AbstractRNG, x::SimpleVector, stackdict::IdDict) return map!(Vector{Any}(undef, length(x)), eachindex(x)) do n - return randn_tangent(rng, x[n]) + return randn_tangent_internal(rng, x[n], stackdict) end end -function randn_tangent(rng::AbstractRNG, x::P) where {P <: Union{Tuple, NamedTuple}} - tangent_type(P) == NoTangent && return NoTangent() - return tuple_map(x -> randn_tangent(rng, x), x) -end -function randn_tangent(rng::AbstractRNG, x::T) where {T<:Union{Tangent, MutableTangent}} - return T(randn_tangent(rng, x.fields)) +function randn_tangent_internal(rng::AbstractRNG, x::Array{T, N}, stackdict::IdDict) where {T, N} + haskey(stackdict, x) && return stackdict[x]::tangent_type(typeof(x)) + + dx = Array{tangent_type(T), N}(undef, size(x)...) + stackdict[x] = dx + return _map_if_assigned!(x -> randn_tangent_internal(rng, x, stackdict), dx, x) end -@generated function randn_tangent(rng::AbstractRNG, x::P) where {P} - - # If `P` doesn't have a tangent space, always return `NoTangent()`. - tangent_type(P) === NoTangent && return NoTangent() +function randn_tangent_internal(rng::AbstractRNG, x::P, stackdict) where {P} + tangent_type(P) == NoTangent && return NoTangent() - # This method can only handle struct types. Tell user to implement tangent type - # directly for primitive types. - isprimitivetype(P) && throw(error( - "$P is a primitive type. Implement a method of `randn_tangent` for it." - )) + if tangent_type(P) <: MutableTangent + stackdict isa IdDict || error("...") + if haskey(stackdict, x) + return stackdict[x]::tangent_type(P) + end + stackdict[x] = tangent_type(P)() + stackdict[x].fields = randn_tangent_struct_field(rng, x, stackdict) + return stackdict[x]::tangent_type(P) + else + return tangent_type(P)(randn_tangent_struct_field(rng, x, stackdict)) + end +end - # Assume `P` is a generic struct type, and derive the tangent recursively. +@generated function randn_tangent_struct_field(rng::AbstractRNG, x::P, stackdict::Union{IdDict, Nothing}) where {P}
Same thing here re type constraints.
Mooncake.jl
github_2023
others
228
compintell
willtebbutt
@@ -163,51 +163,46 @@ end end -# TODO: ideally we want to add the following test to the above testset (defined src/tangent.jl) -# but we have to delay this until `randn_tangent` is implemented and working. -@testset "zero_tangent" begin +# TODO: add the following test to `tangent_test_cases` +@testset "zero_tangent and randn_tangent" begin @testset "circular reference" begin - foo = Tapir.TestResources.TypeUnstableMutableStruct(5.0, nothing) - foo.b = foo + foo = make_circular_reference_struct() zt = Tapir.zero_tangent(foo) - @test zt.fields.b === zt + @test zt.fields.b.tangent === zt + rt = Tapir.randn_tangent(Xoshiro(123456), foo) + @test rt.fields.b.tangent === rt end @testset "struct with non-concrete fields" begin bar = Tapir.TestResources.TypeUnstableStruct(5.0, 1.0) - @test Tapir.zero_tangent(bar) == Tangent{@NamedTuple{a::Float64, b}}(@NamedTuple{a::Float64, b}((0.0, 0.0))) + @test Tapir.zero_tangent(bar) == Tangent{@NamedTuple{a::PossiblyUninitTangent{Float64}, b::PossiblyUninitTangent{Any}}}((a=PossiblyUninitTangent{Float64}(0.0), b=PossiblyUninitTangent{Any}(0.0)))
Formatting, maybe consider something like ```suggestion @test ==( Tapir.zero_tangent(bar), Tangent{@NamedTuple{a::PossiblyUninitTangent{Float64}, b::PossiblyUninitTangent{Any}}}( (a=PossiblyUninitTangent{Float64}(0.0), b=PossiblyUninitTangent{Any}(0.0)) ) ) ``` I really need to set up formatting CI...
Mooncake.jl
github_2023
others
242
compintell
yebai
@@ -0,0 +1,19 @@ +module TapirDynamicPPLExt + +if isdefined(Base, :get_extension) + using DynamicPPL: DynamicPPL + using Tapir: Tapir +else + using ..DynamicPPL: DynamicPPL + using ..Tapir: Tapir +end + +using Tapir: DefaultCtx, CoDual, NoPullback, primal, zero_fcodual + +# This is purely an optimisation. +Tapir.@is_primitive DefaultCtx Tuple{typeof(DynamicPPL.istrans), Vararg}
Can we have a macro / function to automate the process of specifying these skipping gradients rules? IIRC, ReverseDiff has SkipOptimise which does similar things.
Mooncake.jl
github_2023
others
220
compintell
willtebbutt
@@ -118,7 +115,7 @@ We then generalise. _**Reverse-Mode AD: what does it do in Euclidean space?**_ In this setting, the goal of reverse-mode AD is the following: given a function ``f : \RR^P \to \RR^Q`` which is differentiable at ``x \in \RR^P`` with Jacobian ``J[x]`` at ``x``, compute ``J[x]^\top \bar{y}`` for any ``\bar{y} \in \RR^Q``. -This is useful because we can obtain the gradient from this when ``Q = 1`` by letting ``\bar{y} = 1``. +A special case is: obtaining the gradient (of scalar output) correcponds to when ``Q = 1``, by letting ``\bar{y} = 1``.
Could we stick with the original wording here?
Mooncake.jl
github_2023
others
220
compintell
willtebbutt
@@ -259,11 +256,9 @@ g -> (g, (y[2] * g, y[1] * g)) As before, we work through in detail. - - _**Step 1: Differentiable Mathematical Model**_ -There are a couple of aspects of `f` which require thought: +There are a couple of aspects of `f` which require thoughts:
```suggestion There are a couple of aspects of `f` which require thought: ``` I'm pretty sure the original wording is correct (grammatically speaking)
Mooncake.jl
github_2023
others
220
compintell
willtebbutt
@@ -173,7 +173,8 @@ Consider the usual inner product to derive the adjoint: ```math \begin{align} \langle \bar{y}, D f [x] (\dot{x}) \rangle &= \langle (\bar{y}_1, \bar{y}_2), (\dot{x}, D \varphi [x](\dot{x})) \rangle \nonumber \\ - &= \langle \bar{y}_1, \dot{x} \rangle + \langle D \varphi [x]^\ast (\bar{y}_2), \dot{x} \rangle \nonumber \\ + &= \langle \bar{y}_1, \dot{x} \rangle + \langle \bar{y}_2, D \varphi [x](\dot{x}) \rangle \nonumber \\ + &= \langle \bar{y}_1, \dot{x} \rangle + \langle D \varphi [x]^\ast (\bar{y}_2), \dot{x} \rangle \nonumber \quad \text{(by definition of the adjoint)} \\
This is great -- much clearer now
Mooncake.jl
github_2023
others
220
compintell
willtebbutt
@@ -340,6 +341,7 @@ where ``\mathbf{1}`` is the vector of length ``N`` in which each element is equa (Observe that this agrees with the result we derived earlier for functions which don't mutate their arguments). Now that we know what the adjoint is, we'll write down the `rrule!!`, and then explain what is going on in terms of the adjoint. +Tapir.jl will generate `rrule!!`s of similar effect (mostly) automatically, but it is good to see a manual implementation for understanding.
I like this. I think I'd like to re-word very slightly to: ```suggestion This hand-written implementation is to aid your understanding -- Tapir.jl should be relied upon to generate this code automatically in practice. ```