Skip to content

Traces ​

The trace of a modifier is the series it records at each step of a call with record = Trace(). The examples use the smoothing modifier Smooth of Writing new types.

The parts of a trace ​

A call with record = Trace() returns (; y, trace), where trace holds one matrix per modifier that keeps state, with ntrace rows and one column per step.

PartMethodWithout a method
the values recordedtrace(m, θ, v, s, v′, s′) returns a tuplean ArgumentError at a call that records
the number of rowsntrace(m, S)nstate(m, S)
the names of the rowstrace_rows(m, S)no names

A pure step that keeps state has no default trace. trace(::Smooth, θ, v, s, v′, s′) = (s′,) records the state after the step, which has the default number of rows. A call that does not record needs no trace method. A modifier declared isstateless records nothing, and the call leaves it out of trace; a trace method of such a modifier is not called.

The trace method ​

The method trace is a pure function of one stratum at one step, under the same requirements as step. Its arguments are the parameters θ, the value and state before the step, v and s, and the value and state after it, v′ and s′. It returns the values to record as a tuple.

The example records the smoothed value and the difference between the value received and the smoothed value,

where is the state after step and the value received. Two values per stratum give rows for strata: the first value of every stratum, then the second.

julia
CR.ntrace(::Smooth, S) = 2S
CR.trace(::Smooth, θ, v, s, v′, s′) = (s′, v - s′)

r = Recurrence([0.5, 0.5]; modifiers = (Smooth(0.5),))
run = r(2.0; history = [1.0, 2.0], stop = 4, record = CR.Trace())
only(run.trace)
2×4 Matrix{Float64}:
 2.5  3.5  4.75  6.5
 0.5  1.0  1.25  1.75

A loss may depend on the trace. The rule differentiates trace with one forward-mode pass over (v, s, v′, s′, θ), as it does step.

julia
using DifferentiationInterface, ForwardDiff, Mooncake

function loss(a)
    r = Recurrence([0.5, 0.5]; modifiers = (Smooth(a[1]),))
    run = r(2.0; history = [1.0, 2.0], stop = 4, record = CR.Trace())
    return sum(abs2, only(run.trace))
end
gradient(loss, AutoMooncake(; config = nothing), [0.5]) ≈
    gradient(loss, AutoForwardDiff(), [0.5])
true

The trace of a blockwise modifier takes the tuples of its group's values and state entries, and ntrace(m, S) is the number of recorded values per group times the number of groups.

Named rows ​

trace_rows names the rows of a trace with a named tuple of row counts, in row order. A call then returns the trace as a named tuple of views of its matrix, one per name.

julia
CR.trace_rows(::Smooth, S) = (; smoothed = S, left = S)
run = r(2.0; history = [1.0, 2.0], stop = 4, record = CR.Trace())
only(run.trace).left
1×4 view(::Matrix{Float64}, 2:2, :) with eltype Float64:
 0.5  1.0  1.25  1.75

A whole-step modifier records its trace through the roles.