Traces
This page is for a reader who wants a new modifier to record a series that a loss or a plot can read. 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.
| Part | Method | Without a method |
|---|---|---|
| the values recorded | trace(m, θ, v, s, v′, s′) returns a tuple | an ArgumentError at a call that records |
| the number of rows | ntrace(m, S) | nstate(m, S) |
| the names of the rows | trace_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
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.75The single stratum gives two rows, the smoothed value and then the difference.
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.
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])trueThe 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.
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).left1×4 view(::Matrix{Float64}, 2:2, :) with eltype Float64:
0.5 1.0 1.25 1.75A whole-step modifier records its trace through the roles.