Repository navigation
A cheaper resumed step: the state stays in the run's buffer, a state as one vector, PerStratum histories, and advance! as a proposal - #1009
Conversation
… strata select(state, strata) gathers the history and each modifier's state along the strata, keeping the groups of a blockwise modifier whole. select(parameter, strata) is a Gather at the selected rows. Batched(K) mixes each batch of strata by one matrix as a reshape and a matrix product, and a history with a batch axis runs as strata. A Gather of a per-stratum kernel is a kernel shared by strata, with its cotangent added into the rows read. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7iw4kbwPDdUfYWEftXa
…d add the fitting tutorial Resume states that a run in chunks is the single run, with every chunk reading its inputs at absolute times. One test runs every registry scenario in chunks on the host and on JLArrays, with every stratum selected in place between chunks, and checks the gradient on a slice with Mooncake. select takes blocks of strata with each, and vcat joins states along the strata. The Fitting to data tutorial builds a bootstrap particle filter and SMC² from resumed calls, select, Gather and vcat. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7iw4kbwPDdUfYWEftXa
…es on every backend The buffer is written in the order it is stored, which halves the load of a history at 10 000 strata. One test item puts a Batched coupling, a kernel and gain shared by strata, a history with a batch axis and a resumed selected state through ForwardDiff, Mooncake and Enzyme. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7iw4kbwPDdUfYWEftXa
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7iw4kbwPDdUfYWEftXa
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7iw4kbwPDdUfYWEftXa
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7iw4kbwPDdUfYWEftXa
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7iw4kbwPDdUfYWEftXa
…ect's checks The page is retitled for what it shows, states the model and the algorithms with their references, and builds the filter and SMC² from the same small functions, with the model passed in. Every select method checks its indices through one helper. The select, Batched and Gather docstrings keep the formula, the arguments and an example. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7iw4kbwPDdUfYWEftXa
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7iw4kbwPDdUfYWEftXa
A reversed run has no chunks, so the wrapper passes reverse through to the recurrence. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7iw4kbwPDdUfYWEftXa
…ry in blocks of strata A call zeroed the `D` history rows of its buffer and then overwrote them with the history, and loaded a strata history a stratum at a time, which reads every value from its own cache line. The buffer now zeroes only the rows the history does not load, and the load reads each history column in runs of 64 strata. An offset history is still refused with a `BoundsError`. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ix9xAETVug2e6sHBJ6
A call with `record = Resume()` built its state's history by copying the last outputs out of the run buffer into a new array in the public layout, strata × time, and a resumed call transposed that array back into a new buffer. On host memory the state's history is now the last rows of the run's buffer, read in the public layout through a lazy transpose, with no copy. A resumed call loads each stratum's rows in order, and `select` and `vcat` gather into a buffer of the same layout, so a selected state has the type of a run's. A run longer than twice its history moves the rows to a buffer of their own, so a state does not keep a long buffer alive. The call that returns a state copies its output out of the buffer, where a single series used to take the buffer over. States on a device, and in a rule's forward pass on wide dual numbers, are copies as before. `State.history` is still an `AbstractVector` or strata × time `AbstractMatrix`; a test that asked for a `Vector` asks for that. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ix9xAETVug2e6sHBJ6
A method that keeps its own state vector, such as a filter from another package, had no documented way to read a `State` as a vector or to build one. `vec(state)` returns each stratum's outputs, oldest first, then each modifier's state; `State(like, x; t)` is its inverse, in the shape of `like` with the next step at time `t`; `length(state)` is the vector's length. Time is absolute in every call and is not in the vector, so the caller passes it. Both run on device arrays and with any number type. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ix9xAETVug2e6sHBJ6
A vector `history` is the lags of one series, so one value for each of `S` strata had to be reshaped to `S × 1` by the caller. `history = PerStratum(x)` reads a vector as one value for each stratum, in a `Recurrence` and a `Convolution`, and a matrix as strata × lags. Two scenarios join the registry, so every backend and the device and chunked-run checks cover it. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ix9xAETVug2e6sHBJ6
… tier The benchmark matrix had no case that resumes, so `benchmark/ab.jl` could not compare two revisions on a stepwise run. `resumed_steps` runs independent strata with a pool each, one resumed call a step, with the same steps written by hand in one buffer as its `loop` baseline. The `stepwise` tier times it at 1, 100, 1,000 and 10,000 strata. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ix9xAETVug2e6sHBJ6
A public API decision for the owner; the commits before this one stand without it. A resumed call copies its state's outputs into a new buffer on every call, which a loop of single steps pays once a step. `advance!(r, state, gain; add, stop, record)` returns the outputs and state of `r(gain; state, add, stop, record = Resume())` and writes the new outputs after the old ones in the buffer the state already has, and steps each modifier's state where it is. The state passed is used up. A state owns its buffer when a run, `select`, `vcat` or `State(like, x)` built it on host memory; one built on a caller's arrays, on a device or inside a rule's forward pass does not, and is moved to a new buffer first. A buffer keeps four rows free after a run that moved its state and one after `select` and `State(like, x)`. The chunked-run contract test runs every registry scenario a step at a time through `advance!`, on the host and on a device, and its gradient. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ix9xAETVug2e6sHBJ6
…ric copy A run on dual numbers wider than 64 bytes holds its buffer strata × time and reads it through `transpose`. With the state kept in the run's buffer, that run built its output and its state through generic indexing of the transposed buffer, and a ForwardDiff gradient of a run a step at a time was 1.4 to 1.6 times slower than before the state was kept there. The output of such a run is now a block copy of the buffer's columns, its state's history is those columns with no copy, and a resumed call loads them column by column. A view of the buffer's rows names its strata by their axis, not by a colon. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ix9xAETVug2e6sHBJ6
…g, a Recurrence the step The page carried a hand-written bootstrap filter and SMC² sampler. It now filters with `AdvancedParticleFilter` and samples the parameters with `log_likelihood_fun` and `metropolis` from LowLevelParticleFilters.jl, with a `Recurrence` as the one-step dynamics of a particle through `State(like, x)`, `advance!` and `vec`. A third part runs the same filter with the particles as strata, which is faster and runs unchanged on a device array, and the page closes with what a run on a GPU needs. The model, the noise and the observation density are three small objects that both filters share. LowLevelParticleFilters and StaticArrays join the docs environment only. The page moves to a "Fitting" group in the navigation, and `docs/pages.jl` is regenerated by the kit. Two references are added, each checked against Crossref by DOI: Liu and Chen (1998) and Carpenter et al. (1999). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ix9xAETVug2e6sHBJ6
… JLArrays The page's filter with particles as strata had no test of its device path. With the noise and the ancestors passed in, it gives the log likelihood estimate of a filter written a particle at a time from the model's equations, on host arrays and on JLArrays with a host or a device index. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ix9xAETVug2e6sHBJ6
Resolved by replaying this branch's seven commits onto main: the stepwise changes are main's, and the docstring and page edits of #928's review are kept, with advance!, vec, State(like, x; t) and history = PerStratum(x) added to them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7iw944WSUChz7VfmbXi
…orter state docstrings A batch is S × B × h and S × B × T, time last as in every time-indexed input, so it is a reshape of the B S strata: one step at 1,000 strata took 56 µs with the batch axis against 21 µs without, and now takes the same. A resumed call takes inputs with a batch axis too. The cotangent of a kernel shared by strata is summed on the device, a thread per entry through the strata sorted by row, where it went to the host and back on each reverse pass. advance! gets a one-sentence docstring and a row in the Calls table. State(like, x) and vec copy through _moved, and the ownership comment and the vec and State docstrings are cut. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7iw944WSUChz7VfmbXi
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7iw944WSUChz7VfmbXi
Inlined together into a loop that records the pressure and the trace, their integer slots shared a stack slot with the loop's arrays, which Enzyme reverse could not type (EnzymeNoTypeError). Fixes #1025. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7iw944WSUChz7VfmbXi
|
#1009 is ready to merge at Agreed batching design (its own PR, from
Next:
Generated by Claude Code |
Try this Pull Request!Option 1: Julia Package ManagerOpen Julia and type: import Pkg
Pkg.activate(temp=true)
Pkg.add(url="https://github.com/EpiAware/ComposableRecurrences.jl", rev="claude/cheap-resumed-step")
using ComposableRecurrencesOption 2: Local CheckoutIf you have the repo locally: git checkout claude/cheap-resumed-step
julia --project=. -e "using Pkg; Pkg.instantiate()" |
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7iyQ7UVVTRf6G38zdjA
Benchmark comparison vs baseMinimum time per call. Buckets are PR time as a % of base, so lower is faster (🟢 faster, ⚪ within 5%, 🔴 slower). Counts of benchmarks per bucket:
Evaluation — 24 benchmarks (by time change)
AD gradients — 63 benchmarks (by time change)
|
Main made State public, and a public type's docstring names each field. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7iyQ7UVVTRf6G38zdjA
|
📖 Documentation preview is ready! View the docs for this PR at: https://EpiAware.github.io/ComposableRecurrences.jl/previews/PR1009/ This preview will be updated automatically when you push new commits. |
…r's cotangent A returned state's history is a window on the run's buffer, so the reverse pass adds the cotangent of that whole buffer, not only the rows the window shows. The rule's forward pass builds the state as the plain run does, owned included, with copies of the modifier states, which the cache keeps for the reverse pass. The three test_adjoint items for operators returning a state now pass under Enzyme, and a loss on the series and the state is checked against finite differences under each rule. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7iyQ7UVVTRf6G38zdjA
The page goes under Forecasting and fitting after the conjugate page, and in the tutorial list of the getting-started index. The conjugate page links it and names the variations its model has. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7iyQ7UVVTRf6G38zdjA
Main's #1008 holds a cached run's buffer strata × time and lets the Mooncake rule's output share the cache's buffer. The run now picks its buffer in three ways: the strata × time buffer of a cached run, the time × strata buffer of a cached run (both from main, history at row D), and a plain run's buffer, which may be the resumed state's own (this branch). The step loop takes the row before its first step and whether it steps the caller's modifier states in place.
…ime forward state advance! uses up its state: a second call from it returns wrong values, not an error, and the docstring now says so and how to keep a copy. A test pins that a copy through vec(state) resumes as the state did. Main now holds a cached run's buffer strata × time for a few-lag fixed kernel over strata. A test checks that the state of such a forward pass is the plain run's and that stepping from it leaves the cache unchanged. The device state's length is checked against its vector.
Main's #1008 holds a cached run's buffer strata × time for a few-lag fixed kernel over strata, and the state of such a forward pass read that buffer through a column view. Its type then differed from the plain run's state, which the Enzyme rule must return: the rule failed to convert it, and a stepped run's union of the two failed Enzyme's type analysis. On floats the state now moves to a time × strata buffer of its own, as only a cached run holds that layout. The wide dual numbers that hold the layout in a plain run keep the column view.
The particle filtering page cites both, and the merge that folded it in kept the other side of the bibliography.
The fixtures job loads the registry against the last releases, which reject a PerStratum history. A probe gates the two scenarios.
The core takes a history on the rows of a host buffer in _buffer and _zeros, which made the Reactant extension's traced methods ambiguous. The extension's host-array methods now cover those rows too.
A single method on the union of host arrays and a state's buffer rows was less specific than the core's method on each, and ambiguous with both.
Documenter did not resolve the reference to vec(::State) on the generated page; the page links State and State(like, x) already.
The core run now takes whether the call returns a state and whether it steps in the state's own buffer; the traced method named its keywords and rejected those two. It now passes them all on.
Both run forward under Reactant, and the convolution's gradient does. The recurrence's gradient fails in Reactant's post_op_transpose_reshape pass with a product of a 12 x 1 and a 1 x 12 array, the failure already listed for the capacity scenarios, so it joins that list. The rows are from a CPU run of the two scenarios at 12 steps.
RESULTS.md is generated with results.tsv, and the quality item counts its works cells against the file. The four rows from the CPU run are added by hand, in the generated layout, rather than by a 50-minute full run.
Main moved the tutorials into docs/src/tutorials/ by group (#1035); the particle filtering page moves to forecasting-and-fitting/ with the conjugate page, and its entries in pages.jl and docs_config.jl follow.
A host history read its strata from the vector's length over its depth, so a depth of zero gave no strata, and a resumed call then rejected the gain. The strata come from the history's shape, as on a device.
Part of #918. A resumed call is now about twice as cheap at 1,000 strata and above, a state can be read as one vector and built from one, a history can give one value per stratum, and
advance!is proposed for stepping a state in its own buffer.This PR also carries the particle filtering tutorial from #1016, which was closed in its favour.
Needs your decision: whether to keep
advance!(see "For the owner to decide" below); dropping it is a revert of73365af. With it, whetherlength(state)staysBase.lengthor becomes a named function.Claude Opus 5.5 [medium]
Since the last update
mainalone.mainwas merged in atf5a14f9,1c6f490andf482c6d(no rebase). The last brings Update to EpiAwarePackageTools 0.5 #1035's layout, so the particle filtering page is atdocs/src/tutorials/forecasting-and-fitting/particle-filter.jl.2d28edb: a cached run's state on floats moves to a time × strata buffer, so it has the plain run's type. Enzyme failed to convert it in the rule, and a union of the two types failed its type analysis.11e9b2f: theGordon1993andAndrieu2010bib entries that folding in Particle filtering page with LowLevelParticleFilters.jl, and the same filter with particles as strata #1016's page dropped.aa69aca: the twoPerStratumhistory scenarios are left out against releases that lack it, which the fixtures job checks.dcd406b,e2de184,3db88e7: the Reactant extension's traced methods cover a history on a state's buffer rows without ambiguity, and pass every run keyword on.52fbf9a: the particle filtering page namesvecwithout a cross-reference Documenter did not resolve.b7b8701,2ef35b4: Reactant rows for the twoPerStratumhistory scenarios. The recurrence's gradient fails in Reactant'spost_op_transpose_reshapepass, the break already listed for the capacity scenarios, so it joins that list.5f7742a:State(like, x)keeps the strata of a history with no outputs (depth 0), found by an independent review.465efd8documents and tests thatadvance!uses up its state, and tests a device state'slength.Benchmarks after the merge
The CI comparison against
mainafter #1008 puts every Evaluation case within 5%. Five ForwardDiff cells read 5 to 15% slower there. The earlier comment's 1.57× (bvd_census) and 3.34× (conv_fixed) were runner noise: base and PR run on separate runners, andconv_fixedis aConvolution, whose code this PR does not change.Timed locally with
benchmark/ab.jl --base=origin/main --rounds=3, one thread, interleaved:No cell of the 24 is outside its noise band.
CI on the merged tree
On
b7b8701every job passed except these, each also failing or timing out onmain:ad (Julia 1.12, registry): "NoAdjoint Convolution lag contributions of a table cut at a report day: no rule fires", the same failure as onmainat228db42.ad / Enzyme reverseandad / Mooncake reverse: cancelled at the job's time limit, as onmain. Before that, Enzyme reverse fails "two draws on one pool with a flow between" in the chunked item. It fails the same way onmainunder--code-coverage=userand passes without it (Enzyme reverse fails type analysis on a chunked run with two draws when coverage is on #1042).test (1, macOS-latest): cancelled at the time limit, as onmain.Documenter: the performance page'stracked()fails on the benchmark history data thatmainpublishes. This PR does not touch that page or its data. Onmainthe job timed out before reaching it.In plain words
vec(state),State(like, x; t)andlength(state), for a method that keeps its own state vector, such as a filter from another package.history = PerStratum(x)reads a vector as one value before the start for each stratum.advance!(r, state, gain)runs the steps of a resumed call in the buffer the state already has. It takes a one-step call from 218 to 152–164 µs at 10,000 strata. It is a public API decision and the rest stands without it.Where the time of a one-step resumed call went
Measured on
95ec588with a 14-lag kernel and a pool per stratum, one thread, on a shared 4-core container.A hand-written step on one time × strata buffer is the reference; a single long run costs the same per step as the hand step up to 1,000 strata.
Causes, each checked by timing the part alone:
What changed
1. Buffer zero fill and load (
2b32b51).The buffer zeroes only the history rows the history does not load, and the load reads each history column in runs of 64 strata.
2. A state's outputs stay in the run's buffer (
8550755,7ceba22).On host memory
State.historyis the last rows of the run's buffer read through a lazy transpose, so building it copies nothing, and a resumed call loads each stratum's rows in order.selectandvcatgather into the same layout, so a selected state has the type of a run's.A run longer than twice its history plus 8 rows moves the rows to a buffer of their own, so a state does not keep a long buffer alive.
A run on dual numbers wider than 64 bytes holds its buffer strata × time, and its state's history is columns of that buffer (
7ceba22, a fix found by the benchmark below: the first version was 1.4 to 1.6 times slower under ForwardDiff).States on a device are copies as before.
State.historyis still anAbstractVectoror a strata × timeAbstractMatrix; its fields were already documented as internal.3.
vec(state),State(like, x; t),length(state)(7a91254).The vector holds each stratum's outputs, oldest first, then each modifier's state.
Time is absolute in every call and is not in the vector, so the caller passes
t: this is the rule a method with its own clock needs.Of the list in the #918 comment, #928 already gave the zero-step call for an initial state, the absolute-time rule and
select; this adds the documented way to build aState, the flat form and its layout.4.
history = PerStratum(x)(d78b0fa), forRecurrenceandConvolution; a state from such a run resumes and selects as any other. Two scenarios join the registry.5. Benchmark case (
9eaa7b5):resumed_stepsin astepwisetier, with the same steps by hand as itslooparm.6. Proposal:
advance!(73365af). See below.Measured
benchmark/ab.jl --base=origin/claude/stepwise-select-918 --cand=HEAD --rounds=3 --tier=stepwise, 20 one-step resumed calls of the public call (notadvance!), minimum times.The band is the A/A noise of the two base runs; the machine was shared, so bands are wide.
No cell is slower.
Mooncake's plain-AD arm (
NoAdjoint) is faster at 100 strata and above (0.61, 0.36, 0.42).The reverse-mode rule is unchanged: its forward pass keeps a buffer of its own for the reverse pass, so it takes none of this.
One call, interleaved rounds (base, this PR, base, twice), functions called directly, µs:
advance!selectWhat is left of the public call at 10,000 strata is one pass that copies the window into a new buffer; at one stratum it is the allocations of a call (buffer, output, modifier state), about 100 ns.
What it costs calls that do not resume.
A call without
recordruns the code it ran, less the zero fill.benchmark/ab.jl --tier=ci --cases=renewal,strata_mixing,overview,delay_fixed, forward and Mooncake reverse: 27 cells, none outside its noise band.A call with
record = Resume()now copies its output out of the buffer where a single series took the buffer over, and a run longer than twice its history copies its last rows once.A 200-step recorded run timed 5.8 to 6.1 µs on base and 5.1 to 6.3 µs here for one series, and 2.5 to 3.3 ms against 2.6 to 2.7 ms at 1,000 strata: inside the spread of the base's own runs.
For the owner to decide:
advance!(73365af)r(gain; state, add, stop, record = Resume()).advance!does not.advance!after a copy of the state. There is no second step loop and no flag in the loop; the run takes the row its first step writes as an argument.select,vcatorState(like, x)built it on host memory. A state on a caller's arrays, on a device or from a rule's forward pass does not, and is moved to a new buffer first, so the result is the same. A buffer keeps four rows free after such a move and one afterselectandState(like, x); more rows free slowed every pass in the measurements (they sit between the strata's rows).73365af(and of theadvance!lines of the tests it adds);7ceba22does not depend on it.Alternatives I did not build: a mutable stepper object that owns two buffers and resamples between them, which would also remove the allocation in
select(89 µs at 10,000 strata) at the price of a second stateful API; and aselectthat defers its gather to the next call's load, which saves the same pass asadvance!for a filter that resamples every step, with no new name, but makes a selected state a different type from a run's.Tested
On the final tree unless stated; Julia 1.13.4.
2b32b51.test/ad/chunked.jlandtest/ad/stepwise.jl(test/ad environment): 819 pass. Every registry scenario runs a step at a time throughadvance!, with the state selected in place and passed through its vector, on the host and on JLArrays; Mooncake reverse gradients of the stepped runs match the single run on every sixth scenario; the new stepwise item matches ForwardDiff on Mooncake and Enzyme, forward and reverse.advance!: 411 pass.8550755): 25,094 pass on the recurrence, select, gather, buffer, show, batched and adjoint unit files. The tree withoutadvance!: quality items pass.7ceba22: the recurrence, select, advance, state vector, strata history, gather, eltype and precision unit files, 24,774 pass, and a new item for resumed runs on wide dual numbers.Not run: the full Mooncake, Enzyme, ForwardDiff and ReverseDiff registry suites (about 90 minutes each), JET, the trim suite, Reactant, CUDA and OpenCL, Julia 1.11 and 1.12, the docs build, and the full unit suite after
7ceba22.Tests changed because the behaviour they pinned changed: two that asserted the buffer zeroes all its history rows, and one that asked
state.history isa Vector(nowAbstractVector).This was opened by a bot. Please ping @seabbs for any questions.