Repository navigation
Description
In the BVDOutbreakSize port, the onset table, the in-care census and the first-gradient compile time are still slower than the hand-written code.
What is known
- The renewal, delay, patch, zone, two-clock and abscond rows are at parity or close to it (1 December).
- Onset table: the Mooncake gradient is 1.1 to 1.6 times the hand rule; two fused prototypes were slower (Cohort and hazard kernels must be built element by element, which dominates the gradient #329).
- In-care census (
bvd_census): 2.3 times the hand code, forward and in reverse (Run a grouped modifier's groups in the series step, on the host and on a device #946). - First-gradient compile time: 16 to 17 s more than the hand code for the patch and occupancy models; Run a grouped modifier's groups in the series step, on the host and on a device #946 added about 2 s for grouped cases.
- The occupancy kernel's gap is tracked in Occupancy kernel gradient is about 3 times BVDOutbreakSize's hand rule #914.
Done when
- Each remaining row is within about 1.3 times the hand code, or the maintainer records that it stays as it is.
Earlier text
Earlier title: Forward pass, allocations and gradient compile time against hand-written code in the BVDOutbreakSize port
epiforecasts/BVDOutbreakSize#1152 ports that package's kernels to this package.
Values and gradients match the hand-written code to round-off, but the port is slower to run forward and to compile gradients, as well as in reverse mode (#329, #427, #487).
The downstream aim is to be faster than the hand-written code, so this issue records the forward and compile-time gaps.
Forward pass
Per kernel, one call, Julia 1.13.2, one thread, minimum of 40 timings, this package at ebc78e6.
"Hand" is BVDOutbreakSize main (1f70a2f), "CR" is the port.
| Kernel | CR spelling | Hand (µs) | CR (µs) | Ratio | Hand (bytes) | CR (bytes) | Ratio |
|---|---|---|---|---|---|---|---|
accumulate_occupancy, 220 days |
Depletion, three pools, Derived count flows over Recent |
4.2 | 26.9 | 6.5 | 9,200 | 31,920 | 3.5 |
abscond_thinned_flows, 220 days |
PerStratum(pmfs) * Survival(κ * Survival(TimeVarying(h))), Primary() |
11.9 | 42.3 | 3.6 | 3,680 | 97,912 | 26.6 |
onset_report_cdf_table, D 30, 191 dates |
kernel_weights(TimeVarying(1 - Survival(Derived(…)), Primary()), n) |
36.7 | 93.2 | 2.5 | 45,976 | 71,440 | 1.6 |
two_clock_confirmed, 220 days, L 35 |
Convolution(TimeVarying(S * (1 - Survival(TimeVarying(h))), Primary())) |
9.0 | 20.7 | 2.3 | 1,840 | 44,520 | 24.2 |
zone_share_renewal unmixed, 64 × 150 |
Recurrence with Allocate |
211 | 392 | 1.9 | 558,008 | 800,648 | 1.4 |
zone_share_renewal mixed, 64 × 150 |
Recurrence with Allocate, imports, Redistribute spill |
438 | 684 | 1.6 | 558,136 | 1,108,400 | 2.0 |
patch_infections, 4 × 220 |
Recurrence, Redistribute, Depletion(PerStratum(N)), record = (:trace,) |
38.2 | 63.1 | 1.7 | 28,736 | 63,576 | 2.2 |
convolve_delay, 220, D 35 |
Convolution(delay)(x) |
1.5 | 1.9 | 1.25 | 1,840 | 5,552 | 3.0 |
renewal_infections, 220, G 35 |
Recurrence with Depletion |
11.5 | 7.5 | 0.65 | 5,856 | 4,352 | 0.7 |
The largest allocation gaps are the computed Primary() kernels (abscond_thinned_flows, two_clock_confirmed): the hand code walks each cohort's survival in place, while the package materialises the L × T weights (and the nested Survival's intermediate) before the convolution.
A fused path that evaluates a computed kernel's weights inside the convolution's loop, without the table, would close most of this; it is the forward half of #329.
convolve_delay allocates three times the output for a plain vector convolution with a fixed kernel.
Gradient compile time
Wall time to build a Mooncake gradient (LogDensityFunction with AutoMooncake, which prepares the cache) in a fresh session, two repeats each:
| Model | Hand (s) | CR (s) | Change |
|---|---|---|---|
treatment_flow_model (care flows, occupancy) |
165–166 | 229 | +38% |
onset_reporting_model (onset table) |
104–107 | 122–131 | +17–23% |
bvd_zone (zone renewal) |
201–204 | 238 | +17% |
bvd_joint (everything) |
558–566 | 634–654 | +15% |
Package load (about 9.5 s) and precompile (22 s for BVDOutbreakSize; 3.4 s for this package) are level, so the extra time is Mooncake deriving rules through the package's call tree.
The care flows and occupancy balance, which go through Survival, Derived, Recent and the Depletion flows, add the most.
Fewer code paths per call (#383) and whole-operator rules that Mooncake treats as primitive, rather than rules it derives through, would both cut this.
Reproducing
The timing scripts run every kernel with the same arguments on both checkouts; they are in epiforecasts/BVDOutbreakSize#1152's discussion and can be shared as a gist if useful.
Generated by Claude Code
Activity
seabbs-bot commentedon Nov 10, 2026
Forward-pass and gradient table update on main 4505741. These come from the benchmark matrix's BVD cases (
bvd_*), package arm against thehandrulearm, Julia 1.13.3, one thread,@belapsed, in µs.convolve_delay(bvd_delay, T220 L35)patch_infections(bvd_patches, T220 L20, S1 / S4 / S11)renewal_infections(bvd_renewal, T220 L35)zone_share_renewal(bvd_zones, T150 S64)accumulate_occupancyabscond_thinned_flows,two_clock_confirmed,onset_report_cdf_tableThe port's higher forward ratios (1.25–1.9×) came from its fuller spellings at ebc78e6, for example
record = (:trace,)and glue around the calls, not from these kernels.The compile-time section still stands as measured.
I've closed nothing myself.
Generated by Claude Code
seabbs-bot commentedon Nov 15, 2026
Re-measured every kernel of epiforecasts/BVDOutbreakSize#1152 against BVDOutbreakSize's hand kernels and hand Mooncake rules, on the production-sized case of each (the
perf = truecases in BVDOutbreakSize'stest/test_mooncake_rules.jl, plus three added below), at this package'smain(40bf737).Julia 1.13.4, one thread, minimum over 1 s of Chairmarks samples.
Ranges are over three runs; a single figure is one run.
The same harness at ebc78e6 gives the same table within noise, so none of this is a regression.
"Gradient" is Mooncake
value_and_pullback!!from a prepared cache, with the same output cotangent for both arms.renewal_infections, n 220, G 35convolve_pmf, 45 ⊕ 45convolve_delay, vector, n 220, D 35convolve_delay, 8 × 260 matrix, D 42patch_infections, 3 × 220patch_infections, 11 × 220abscond_thinned_flows, 220two_clock_confirmed, 220, L 45accumulate_occupancy, 220onset_report_cdf_table, D 28onset_report_anchor_series, D 28zone_share_renewal_kernel, 62 zones, mixedzone_share_renewal_kernel, 62 zones, unmixedzone_pre_convolution, 4 × 227sum_to_zero_knots, 11 patches, 32 knots¹ The pool-size argument's gradient, about 1e-10 and 4e-7, differing by 7e-21 and 2e-19 absolute; every other argument agrees to 2e-15.
² With respect to the within-patch kernel
KofRedistribute(K, ε)the two differ by a constant down each column (up to 0.41 relative, spread 5e-15), becauseRedistributechargesε_q Σ_p K_pqwhere the hand code assumes the columns sum to one; they agree through the model's per-patch softmax. See #487.So on BVDOutbreakSize's own code only
renewal_infections,convolve_pmfand the vectorconvolve_delayare at parity or faster at run time.This differs from the 10 November status for
patch_infections(gradient 1.3–1.7×), the matrixconvolve_delay(2.1×, now #620) and the zone renewal (1.4–2.3×).That status may have come from this package's frozen BVD reference in
benchmark/bvd_handrule.jl, which predates BVDOutbreakSize's current kernels.Two kernels not tracked elsewhere:
onset_report_anchor_series(a transposedConvolutionof the table, summed by parts) is faster forward but 2.4–2.5× in reverse, with 12.6× the bytes.sum_to_zero_knots(Recurrence([φ])(; history, add), a one-lag recurrence over 11 strata and 31 steps) is 3.5× forward on 0.8 µs of hand work, which reads as fixed per-call overhead; its gradient is faster.Gradient compile time follows in a separate comment.
Harness
The hand arm is BVDOutbreakSize
main(73c575b) loaded as a second package: in a worktree ofmain, renamesrc/BVDOutbreakSize.jltosrc/BVDMain.jl, replace the module name insrc/*.jl, and giveProject.tomlthe nameBVDMain, a new UUID, and no[workspace],[weakdeps],[extensions]or their compat entries.The CR arm is epiforecasts/BVDOutbreakSize#1152's head (036fab3).
The environment:
julia --project=. kernels.jl timeprints the table;extrathe three added cases;compile NAME ARM(ARMhandorcr) one case's first-gradient wall time in a fresh process.Generated by Claude Code
seabbs-bot commentedon Nov 15, 2026
Compile times for the same kernels, at CR main 40bf737, Julia 1.13.4, one thread.
Each number is the wall time of
prepare_pullback_cacheplus the firstvalue_and_pullback!!in a fresh process, in seconds, over two runs.The hand arm is mostly Mooncake's fixed cost of about 12–15 s, so the ratio understates the gap in the kernel itself.
Convolution, vector, n = 220, D = 35delay_masses, 45 ⊕ 45Convolution, matrix 8 × 260, D = 42Recurrence+Depletion, n = 220, G = 35The kernels built from
Redistribute,AllocateandSurvivaltake 40–65 s to compile against about 14 s for a hand rule.That cost does not show up in the whole model, though.
Building the production joint's Mooncake gradient and taking the first one, after a forward warm-up, takes 800–828 s with every kernel on hand rules and 790–816 s with renewal,
convolve_delayandconvolve_pmfon CR.So in a large model the per-operator compile cost is shared or hidden, and it is the stand-alone use that pays it.
The harness is the one in the comment above, run with
kernels.jl compile NAME ARMfor each case.Generated by Claude Code
seabbs commentedon Nov 17, 2026
Prototype of lever (b), a structural Mooncake rule for building a
Depletion, is shelved.The figures are below so this can be revisited.
Design
@is_primitive DefaultCtx ReverseModeonTuple{typeof(_depletion), Any, Tuple{Vararg{Union{Flow, Hazard, Floor, Truncate}}}, Any}.The signature restriction means other piece types fall back to the derived rule.
Forward mode is left to the derived rule.
_runs,_place_run,_placedand theFlow(_Placed(), ...)rebuild.IdDictfrom each input array to its shadow, so the built operator's arrays share the shadows of the arrays it was given.N.Flowconstructor was tried as well.A placed
Flowhas the same tangent type as the givenFlow, since its ends carry no tangent.Figures
Fresh-process first
prepare_gradient_cacheplus the first gradient, Mooncake warmed on an unrelated function first, three rounds, in seconds.Flowrule adds no measurable gain.The first A/B showed no gain at all.
The occupancy port passes
poolsas aTupleofSymbols, and the first signature allowed onlyNothingor aNamedTuple, so the derived rule was still used.Widening
poolstoAnyfixed this, and the tests now assert the rule applies to each model's own arguments.About 4 s on one kernel is below the bar for the added code, so this is shelved.
Most of the remaining gap per kernel is Base and Mooncake generic code (
collect,Generator,zero_tangent) and the call on the built operator, not CR's own inference.A bug found while building it (the default hazard of a
Depletionwith no pieces dropping the population's cotangent) was in the prototype only.On main, Mooncake's gradient for that case matches ForwardDiff to 1e-14.
The prototype is on the branch
perf/depletion-construction-rule, with no PR.The rules are in
ext/ComposableRecurrencesMooncakeExt.jland the tests intest/ad/construction.jl.Generated by Claude Code
seabbs commentedon Nov 17, 2026
Status, 17 November.
Done:
renewal_infections,convolve_pmf, vectorconvolve_delay: at parity or faster. Matrixconvolve_delay: Convolve a plain array call in the layout of its input #626.patch_infections: timed against the rule (Time the port's patch renewal against the backend's rule #664); traced reverse cut (Make a recorded trace cheaper in the reverse pass #639); Redistribute pullback fused (Fuse Redistribute's pullback over a kernel's movement #646, Skip the diagonal walk in the fused movement pullback when it is unread #653).abscond_thinned_flows,two_clock_confirmed: Walk a computed kernel one cohort at a time in a convolution and kernel_weights #632, Tidy the cohort walk after review, and test more of its paths #644, Read each stratum's computed weights lag by lag from a contiguous copy #668, timed in the matrix (Time the port's abscond-thinned flows and two-clock confirmed stock against the backend's rules #661) with tests (Cover the strata-lags type check, and test strata with no lags matrix #671).accumulate_occupancy: Read a count's demand once per step in the reverse pass #453, Add the BVD occupancy balance to the benchmark matrix, against the backend's hand rule #645, Time the occupancy port's current spelling, and let Enzyme differentiate its case #660.onset_report_cdf_table: Time the port's onset report-delay CDF table against the backend's rule #665.sum_to_zero_knots: Add BVD's sum_to_zero_knots to the matrix and run plain strata calls in the output's layout #667.Left:
onset_report_anchor_series(Transpose of a time-varying Convolution: gradient 2.4–2.5× a hand rule, 12.6× the bytes (BVD onset_report_anchor_series) #627),patch_infectionswith a trace (Make a recorded trace cheap in the reverse pass: fold a modifier's state-trace into its step, and stop rebuilding the cache #631, Let record build only the traces a caller reads #630), the zone import pattern (Read an Allocate import pattern built from a kernel and a weight per origin, without building the matrix #634), the knots historyhcat(Enzyme reverse cannot differentiate a user's hcat of a view history and a Recurrence output #672), fixed per-call cost (Fixed per-call cost of small Recurrence and Convolution calls: where it goes, and batching rather than a package change #649): each waits on a decision.Generated by Claude Code
seabbs commentedon Nov 21, 2026
Current table, main at 97563ad, with an A/A control
Setup:
rulearm against the hand arm: BVD's hand rule, or BVD's loop where there is no rule.renewal_infectionsbvd_renewal, T200–400bvd_renewal_call(seeded, joined)convolve_delaybvd_delaypatch_infectionsbvd_patches, S1 and S11bvd_patches_port, S3 and S11bvd_patches_call(traced), S1bvd_patches_call, S5 and S11zone_share_renewalbvd_zones, S5 and S64two_clock_confirmedbvd_two_clockbvd_two_clock_portabscond_thinned_flowsbvd_abscond(frozen hand rule)bvd_abscond_port(current hand rule)onset_report_cdf_tablebvd_onsetbvd_onset_portaccumulate_occupancybvd_occupancyThe first-gradient column is the wall time of
prepare_gradientplus the first gradient, in a fresh process after Mooncake has been warmed on an unrelated function. It is the minimum of the A and A′ runs. Those agree within about 2 s.What is left, and why
The unread traces and Mooncake's zero tangent of them are 18% of the gradient. That is Let record build only the traces a caller reads #630,
recordselection, which is the maintainer's decision (details on Mooncake gradient of a seeded hazard Depletion recurrence is slower than a hand-written rule in its real call shape #296, now closed).This waits on Depletion with Derived count flows over Recent pools: Mooncake gradient 28x a hand rule #427's proportional-split API.
_walk_cohort_back!17%,_add_value!12%), the forward convolution (14%), and BVD's ownabscond_inputsglue (18%). No line holds more than 6%.In an A/A/B over 7 computed-kernel and control cases at two sizes each, 6 rounds, with bitwise identical gradients, it halves the onset cases' bytes but makes them 1.06–1.51× slower. Every other case is unchanged. So keeping the partials is right, and the lever is ruled out.
Closing it needs a fused walk per coefficient shape, a design change rather than a performance fix.
It is about +16–17 s for the patch calls and ports and for occupancy, and 5 s or less for every other kernel.
The construction-rule prototype is shelved (17 November comment), and no other lever has been found.
Recommendation
The traced-patches and occupancy rows are tracked by Let record build only the traces a caller reads #630 and Depletion with Derived count flows over Recent pools: Mooncake gradient 28x a hand rule #427.
Generated by Claude Code
seabbs-bot commentedon Nov 30, 2026
Forward pass and allocations against the hand loops, on main 63dbaea.
These are the benchmark's primal timings, realistic and docs tiers, CR rule arm over the hand loop arm.
The cases over 1.3× in time or bytes:
#895 removes the output copy of a plain
Convolutioncall with a history: one output vector fewer, and 20–24% faster at T200 on delay_fixed and bvd_delay.The largest time gap left is the blockwise
Depletionstep (occupancy, ward_flows), next.Generated by Claude Code
seabbs-bot commentedon Nov 30, 2026
Blockwise
Depletionforward pass (occupancy), no generic win found. Main 63dbaea, T200, one call:RecurrenceandDepletionoccupancy_outputsThe gap is all in the step.
The profile is diffuse: the flows' branch-free arms (
ifelse,+,==) about a third, the stage loops over three strata about 12%, writes into the buffer about 8%, and the output transpose about 7%.There is no dynamic dispatch: a serial run calls the loops statically.
Tried: running the clamp
Transformon the whole vector, instead of per stratum through slots. 4.63–5.24 against 5.04–5.74 µs, inside the A/A noise, so dropped.A fused group step would close more, but it needs the type-level group count that was ruled out before.
The bytes are close: 10.4 KB against the hand loop's 8.4 KB, the history buffer.
Generated by Claude Code
seabbs-bot commentedon Nov 30, 2026
Byte gaps from the table above, after #895.
Allocations profiled by call site, T200:
permutedimsin and outNo further clear generic win:
_INPLACE_BYTES).Generated by Claude Code
seabbs-bot commentedon Dec 1, 2026
Outcome: not finished; left open with what remains
This one does not wait on anyone else.
It is open because two of its three parts are not done, and they need design work that was not finished here.
Gradients against the hand rules, today
Measured on the redesigned branch (#907 at 21fb0bb), Julia 1.13.4, Mooncake 0.5.74, one thread,
benchmark/matrix.jl --tier=realistic --targets="Mooncake reverse", minimum times.This machine is shared and the same arm moved by up to 50% between runs, so each ratio is given for every run made.
Package over hand rule:
bvd_two_clockbvd_abscond, three runsbvd_onset, three runsbvd_occupancy, the model's lossbvd_occupancy_kernel, the kernels aloneWhat remains
Depletionstep (occupancy, ward flows). Forward it is 2.2 to 2.5 times the hand loop (30 November comment), and the kernel's gradient alone is 3 to 3.9 times the hand rule. Its home is Occupancy kernel gradient is about 3 times BVDOutbreakSize's hand rule #914.The renewal, delay, patch and zone rows were at parity or ahead on 30 November and are not re-listed.
Done when
The three rows above are within about 1.3× of the hand code, or the maintainer decides a row stays as it is.
Generated by Claude Code
seabbs-bot commentedon Dec 2, 2026
Outcome: the blockwise
Depletionstep is faster; compile time is not better; left open#946 has the change and the full tables.
Measured with
benchmark/ab.jl, three interleaved rounds,mainat 4ce03f8 against the branch, T = 200; the A/A band was 12 to 31% on a noisy machine.1. The blockwise
Depletionstep (occupancy)Cause: the step's arithmetic was level with the hand loop (14 to 15 ns a step in a bare loop); the package's 30 ns a step was the vector step around one group (row and column copies, gathers, scatters and accumulators per modifier at every step).
#946 runs one group in the series step.
bvd_occupancy_kernelThe call alone, given the built
Depletion, went from 6.0 µs to about 4.0 µs against 2.8 µs for the hand loop.What is left forward is the buffer, the transposed output copy and BVD's separate
occupancy_outputspass; the hand loop writes its outputs as it goes.The bytes did not move: they are the buffer and the output, which the time × strata layout needs.
The gradient is on #914: about 3.1 times the hand rule, from 3.6 to 4.0.
2. A new case: the in-care census
bvd_censustimes BVD'sincare_censusagainst the same read-out written as a pure step with nostep_pullback.bvd_censusSo a read-out of four series costs about 2.3 times its hand rule through the generic step: fixed per-call arrays, and one dual pass with ten partials a day.
BVD's zone read-out has no operator of this package in it, so there is nothing of the package to time there.
3. The onset table
Not touched.
4. First-gradient compile time
Not improved, and about 2 s worse for the grouped cases: the occupancy kernel's prepare-plus-first-gradient under Mooncake went from 18.8 s to 21.0 s, and the census from 5.1 s to 6.9 s (medians of six base and three candidate runs inside the matrix process).
The series step is compiled for the group as well as the vector step.
The whole BVD models were not timed.
No other case moved
Forward pass over the whole
citier: 31 cells, 2 faster, 0 slower.Forward, Mooncake and Enzyme gradients over seven cases: 74 cells, 8 faster, 0 slower.
Mooncake and Enzyme gradients of the remaining
cicases were not run.Still open
The occupancy gap (#914), the onset table and compile time.
Generated by Claude Code
[-]Forward pass, allocations and gradient compile time against hand-written code in the BVDOutbreakSize port[/-][+]BVDOutbreakSize port: onset table and gradient compile time are behind hand-written code[/+]