Skip to content

BVDOutbreakSize port: onset table and gradient compile time are behind hand-written code #572

Open

Description

@seabbs-bot

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

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.

Related: #329, #383, #427, #487, #536.


Generated by Claude Code

Activity

  1. seabbs-bot commented on Nov 10, 2026

    @seabbs-bot
    CollaboratorAuthor

    Forward-pass and gradient table update on main 4505741. These come from the benchmark matrix's BVD cases (bvd_*), package arm against the handrule arm, Julia 1.13.3, one thread, @belapsed, in µs.

    Kernel Forward, package / hand Mooncake gradient, package / hand Recommendation
    convolve_delay (bvd_delay, T220 L35) 1.32 / 1.62 7.8 / 12.2 ahead; close the row
    patch_infections (bvd_patches, T220 L20, S1 / S4 / S11) 13 / 16, 34 / 43, 81 / 123 45 / 58, 114 / 189, 315 / 585 ahead; close the row
    renewal_infections (bvd_renewal, T220 L35) 8.3 / 13.6 25.5 / 37.5 ahead; close the row
    zone_share_renewal (bvd_zones, T150 S64) 405 / 406 1.01× once both arms take the same gain and drive (#577) level; close after #577
    accumulate_occupancy — — waits on #427's proportional-split API
    abscond_thinned_flows, two_clock_confirmed, onset_report_cdf_table — — belong to #329

    The 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

  2. seabbs-bot commented on Nov 15, 2026

    @seabbs-bot
    CollaboratorAuthor

    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 = true cases in BVDOutbreakSize's test/test_mooncake_rules.jl, plus three added below), at this package's main (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.

    Kernel, case Forward ratio Bytes, hand → CR Gradient ratio Max rel Δ value Max rel Δ gradient
    renewal_infections, n 220, G 35 0.56–0.62 5,856 → 4,352 0.89–0.95 4.8e-16 1.9e-11 ¹
    convolve_pmf, 45 ⊕ 45 1.01–1.05 768 → 768 0.60–0.68 0 4.3e-16
    convolve_delay, vector, n 220, D 35 1.00–1.03 1,840 → 5,552 0.74–1.09 4.0e-16 4.0e-16
    convolve_delay, 8 × 260 matrix, D 42 2.31–2.47 16,728 → 50,184 2.08–2.16 4.5e-16 5.0e-16
    patch_infections, 3 × 220 0.91–1.01 21,776 → 48,216 1.49–1.72 4.0e-16 5.9e-13 ¹
    patch_infections, 11 × 220 0.84 78,288 → 172,408 1.27 6.2e-16 6.9e-13 ¹
    abscond_thinned_flows, 220 3.37–3.55 3,680 → 95,688 3.85–4.09 9.7e-16 1.2e-15
    two_clock_confirmed, 220, L 45 1.81–1.89 1,840 → 43,424 2.01–2.11 6.9e-16 4.4e-16
    accumulate_occupancy, 220 5.28–5.35 9,200 → 31,920 12.08–12.09 9.2e-16 1.9e-15
    onset_report_cdf_table, D 28 1.42–1.49 22,744 → 38,744 2.20–2.27 0 1.0e-15
    onset_report_anchor_series, D 28 0.73–0.78 928 → 11,680 2.41–2.53 1.3e-15 3.3e-15
    zone_share_renewal_kernel, 62 zones, mixed 1.47–1.48 778,104 → 1,506,080 1.43–1.51 4.2e-16 ²
    zone_share_renewal_kernel, 62 zones, unmixed 1.54 777,976 → 1,108,472 2.34 3.7e-16 2.2e-14
    zone_pre_convolution, 4 × 227 0.94–0.99 7,384 → 30,208 2.04–2.15 5.3e-16 8.3e-16
    sum_to_zero_knots, 11 patches, 32 knots 3.54 5,888 → 11,808 0.71 0 2.4e-16

    ¹ 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 K of Redistribute(K, ε) the two differ by a constant down each column (up to 0.41 relative, spread 5e-15), because Redistribute charges ε_q Σ_p K_pq where 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_pmf and the vector convolve_delay are at parity or faster at run time.
    This differs from the 10 November status for patch_infections (gradient 1.3–1.7×), the matrix convolve_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 transposed Convolution of 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 of main, rename src/BVDOutbreakSize.jl to src/BVDMain.jl, replace the module name in src/*.jl, and give Project.toml the name BVDMain, a new UUID, and no [workspace], [weakdeps], [extensions] or their compat entries.
    The CR arm is epiforecasts/BVDOutbreakSize#1152's head (036fab3).
    The environment:

    [deps]
    BVDMain = "0b7d9a52-5e7c-4c11-9a0e-4b0c1d2e3f40"
    BVDOutbreakSize = "7c2a1f8e-9d4b-4a16-bf3e-1f5c8c3a90e2"
    Chairmarks = "0ca39b1e-fe0b-4e98-acfc-b1656634c4de"
    ComposableRecurrences = "4e7e49c6-d082-4112-9a58-49588f39a74b"
    Distributions = "31c24e10-a181-5473-b8eb-7969acd0382f"
    Mooncake = "da2b9cff-9c12-43a0-ae48-6db2b0edb7d6"
    Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
    Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
    
    [sources]
    BVDMain = {path = "path/to/renamed/main"}
    BVDOutbreakSize = {path = "path/to/1152/checkout"}
    ComposableRecurrences = {url = "https://github.com/EpiAware/ComposableRecurrences.jl", rev = "main"}

    julia --project=. kernels.jl time prints the table; extra the three added cases; compile NAME ARM (ARM hand or cr) one case's first-gradient wall time in a fresh process.

    ## Per-kernel comparison of the port (BVDOutbreakSize, this branch) against
    ## the hand kernels and rules (BVDMain, a renamed copy of `main`).
    ##
    ## julia --project=. kernels.jl [time|extra|list|compile NAME ARM]
    using BVDOutbreakSize, BVDMain
    using Mooncake: Mooncake
    using Chairmarks: @be
    using Random: Xoshiro
    using Printf: @printf
    
    ## The test file's case snippet, evaluated here.
    const TESTFILE = joinpath(
        pkgdir(BVDOutbreakSize), "test", "test_mooncake_rules.jl"
    )
    function snippet_body(file, name)
        ex = Meta.parseall(read(file, String); filename = file)
        for a in ex.args
            a isa Expr && a.head === :macrocall || continue
            a.args[1] === Symbol("@testsnippet") || continue
            a.args[3] === name && return a.args[4]
        end
        error("no snippet $name")
    end
    module Cases end
    Core.eval(Cases, :(using BVDOutbreakSize))
    foreach(
        a -> Core.eval(Cases, a),
        snippet_body(TESTFILE, :ADRuleCases).args
    )
    
    ## Extra production cases for kernels without a `perf` case.
    function extra_cases()
        rng = Xoshiro(42)
        C = Cases
        cs = NamedTuple[]
        add!(name, f, args...) = push!(cs, (; name, f, args, perf = true))
        np = 11
        K = rand(rng, np, np) .* 0.2
        foreach(p -> K[p, p] = 0, 1:np)
        add!(
            "patch_infections: 11 patches, n = 220",
            BVDOutbreakSize.patch_infections,
            abs.(randn(rng, np, 220)) .* 0.3 .+ 1.0, C.pmf(rng, 35),
            rand(rng, np, 14) .+ 1.0, K, rand(rng, np, 220) .* 0.5,
            1.0e6 .* (rand(rng, np) .+ 0.5)
        )
        za = Base.invokelatest(
            C.zone_args, rng, [21, 21, 20];
            nd = 220, t0 = 30, L = 12, mixing = false
        )
        add!(
            "zone_share_renewal_kernel: 62 zones unmixed, n = 220",
            BVDOutbreakSize.zone_share_renewal_kernel, za...
        )
        nb = 32
        F_level = randn(rng, np, np - 1) .* 0.3
        F_drift = randn(rng, np, np - 1) .* 0.1
        add!(
            "sum_to_zero_knots: 11 patches, 32 knots",
            BVDOutbreakSize.sum_to_zero_knots, F_level, F_drift,
            randn(rng, np - 1), randn(rng, np - 1, nb - 1), 0.8
        )
        return cs
    end
    
    function cases()
        cs = filter(
            c -> c.perf && c.f in Cases.PACKAGE_KERNELS,
            Base.invokelatest(Cases.rule_cases, Xoshiro(20260923))
        )
        return vcat(cs, extra_cases())
    end
    
    hand(f, args) = f === BVDOutbreakSize.convolve_delay &&
        first(args) isa AbstractMatrix ? BVDMain.convolve_rows :
        getfield(BVDMain, nameof(f))
    
    flat(x::Real) = [Float64(x)]
    flat(x::AbstractArray{<:Real}) = vec(Float64.(x))
    flat(x::Union{Tuple, NamedTuple}) = reduce(vcat, map(flat, values(x)))
    flat(x::AbstractArray) = reduce(vcat, map(flat, x); init = Float64[])
    flat(x) = Float64[]
    
    reldiff(a, b) = (
        d = flat(a) .- flat(b);
        isempty(d) ? 0.0 :
            maximum(abs, d) / max(maximum(abs, flat(b)), floatmin())
    )
    
    ## Minimum time of the forward call and its allocation in bytes.
    function forward(f, args)
        b = @be f(args...) seconds = 1
        t = minimum(x.time for x in b.samples)
        bytes = minimum(x.bytes for x in b.samples)
        return t, bytes
    end
    
    ## Value and pullback with the cotangent of the hand output, and its time.
    function pullback(f, args, ȳ)
        cache = Mooncake.prepare_pullback_cache(f, args...)
        run() = Mooncake.value_and_pullback!!(cache, ȳ, f, args...)
        res = deepcopy(run())
        b = @be run() seconds = 1
        return res, minimum(x.time for x in b.samples)
    end
    
    function time_all(only_extra = false)
        @printf(
            "%-46s %9s %9s %6s %10s %10s %6s %9s %9s %6s %8s %8s\n",
            "case", "fwd hand", "fwd CR", "ratio", "B hand", "B CR", "ratio",
            "grad hand", "grad CR", "ratio", "Δ value", "Δ grad"
        )
        for c in (only_extra ? extra_cases() : cases())
            h = hand(c.f, c.args)
            ȳ = Mooncake.randn_tangent(Xoshiro(1), h(c.args...))
            th, bh = forward(h, c.args)
            tc, bc = forward(c.f, c.args)
            rh, gh = pullback(h, c.args, ȳ)
            rc, gc = pullback(c.f, c.args, ȳ)
            dv = reldiff(rc[1], rh[1])
            dg = maximum(
                reldiff(a, b) for (a, b) in zip(rc[2][2:end], rh[2][2:end]);
                init = 0.0
            )
            @printf(
                "%-46s %9.2f %9.2f %6.2f %10d %10d %6.2f %9.2f %9.2f %6.2f %8.1e %8.1e\n",
                c.name, 1.0e6th, 1.0e6tc, tc / th, bh, bc, bc / max(bh, 1),
                1.0e6gh, 1.0e6gc, gc / gh, dv, dg
            )
        end
        return nothing
    end
    
    function compile_one(name, arm)
        c = only(filter(c -> c.name == name, cases()))
        f = arm == "hand" ? hand(c.f, c.args) : c.f
        ȳ = Mooncake.randn_tangent(Xoshiro(1), f(c.args...))
        t = @elapsed begin
            cache = Mooncake.prepare_pullback_cache(f, c.args...)
            Mooncake.value_and_pullback!!(cache, ȳ, f, c.args...)
        end
        @printf("COMPILE\t%s\t%s\t%.2f\n", name, arm, t)
        return nothing
    end
    
    if isempty(ARGS) || ARGS[1] == "time"
        time_all()
    elseif ARGS[1] == "extra"
        time_all(true)
    elseif ARGS[1] == "list"
        foreach(c -> println(c.name), cases())
    elseif ARGS[1] == "compile"
        compile_one(ARGS[2], ARGS[3])
    end

    Generated by Claude Code

  3. seabbs-bot commented on Nov 15, 2026

    @seabbs-bot
    CollaboratorAuthor

    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_cache plus the first value_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.

    Kernel (BVDOutbreakSize size) Hand rule CR Ratio
    Convolution, vector, n = 220, D = 35 12.8–14.5 19.5–23.9 1.52
    delay_masses, 45 ⊕ 45 12.1–16.2 22.1–28.1 1.84
    Convolution, matrix 8 × 260, D = 42 13.8–14.1 21.5–23.1 1.57
    Recurrence + Depletion, n = 220, G = 35 12.8–13.4 30.4–32.6 2.36
    patch renewal, 3 patches, n = 220 13.4–13.8 59.8–65.3 4.45
    patch renewal, 11 patches, n = 220 12.7–14.9 61.1–62.1 4.83
    abscond thinned flows, n = 220 13.6–13.9 54.6–61.8 4.01
    two-clock confirmed, n = 220, L = 45 12.0–12.2 26.7–27.2 2.22
    occupancy, n = 220 12.0–12.7 53.1–60.4 4.44
    onset-report cdf table, D = 28 13.3–14.7 29.1–30.9 2.18
    onset-report anchor series, D = 28 13.2–13.8 35.4–40.8 2.69
    zone share renewal, 62 zones mixed 14.5–14.6 54.4–55.7 3.75
    zone share renewal, 62 zones unmixed 13.4–14.4 40.8–41.0 3.04
    zone pre-convolution, 4 patches, n = 227 13.2–13.8 36.4–41.6 2.77
    sum-to-zero knots, 11 patches, 32 knots 27.0–27.1 32.8–34.3 1.21

    The kernels built from Redistribute, Allocate and Survival take 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_delay and convolve_pmf on 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 ARM for each case.


    Generated by Claude Code

  4. seabbs commented on Nov 17, 2026

    @seabbs
    Member

    Prototype of lever (b), a structural Mooncake rule for building a Depletion, is shelved.
    The figures are below so this can be revisited.

    Design

    • A @is_primitive DefaultCtx ReverseMode on Tuple{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.
    • The rule runs the primal build, then maps tangents by structure instead of differentiating _runs, _place_run, _placed and the Flow(_Placed(), ...) rebuild.
    • Fdata is matched by leaf identity: an IdDict from each input array to its shadow, so the built operator's arrays share the shadows of the arrays it was given.
    • Rdata is matched by position: each placed piece's cotangent goes back to the piece it came from, and the default hazard's population cotangent goes back to N.
    • A second rule on the Flow constructor was tried as well.
      A placed Flow has the same tangent type as the given Flow, since its ends carry no tangent.
    • About 190 lines of extension code, with tests against ForwardDiff and Mooncake forward mode for every demand kind, draws, populations and pools given as names.

    Figures

    Fresh-process first prepare_gradient_cache plus the first gradient, Mooncake warmed on an unrelated function first, three rounds, in seconds.

    Kernel main rule + Flow rule rule alone
    occupancy 33.0 / 33.5 / 35.3 28.3 / 30.1 / 30.4 29.4 / 29.4 / 31.1
    patches 34.3 / 34.9 / 37.2 34.3 / 34.5 / 34.5 34.1 / 34.4 / 36.5
    • Occupancy gains about 4 s; patches is within noise.
    • The Flow rule adds no measurable gain.
    • Gradient run times show no regression over five rounds (minima): occupancy 68 vs 73 µs, patches 93 vs 95 µs, renewal 19.4 vs 19.4 µs.

    The first A/B showed no gain at all.
    The occupancy port passes pools as a Tuple of Symbols, and the first signature allowed only Nothing or a NamedTuple, so the derived rule was still used.
    Widening pools to Any fixed 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 Depletion with 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.jl and the tests in test/ad/construction.jl.


    Generated by Claude Code

  5. seabbs commented on Nov 17, 2026

    @seabbs
    Member

    Status, 17 November.

    Done:

    Left:


    Generated by Claude Code

  6. seabbs commented on Nov 21, 2026

    @seabbs
    Member

    Current table, main at 97563ad, with an A/A control

    Setup:

    • The benchmark matrix's BVD cases, the package's rule arm against the hand arm: BVD's hand rule, or BVD's loop where there is no rule.
    • Each case at its docs sizes (BVD's production shapes) and its realistic sizes.
    • Julia 1.13.3, one thread, Mooncake reverse through DI with prepared gradients.
    • Two worktrees of main compiled separately (A and A′), fresh processes, 4 interleaved rounds. Minimum over rounds.
    • The A/A ratio of the rule arm's gradient has a geometric mean of 1.00 over all 66 rows. Small cases spread to 0.86–1.33, so read a single row's gap under about 10% as noise.
    • Take the rule for a wide call on Enzyme reverse from 10 lags per stratum #781 has merged since; it changes only Enzyme reverse, so these Mooncake figures stand for the current main.
    BVD kernel matrix case, sizes forward, rule / hand gradient, rule / hand gradient bytes, rule / hand first gradient, rule − hand (s) state
    renewal_infections bvd_renewal, T200–400 0.51–0.92 0.71–0.93 0.61–0.62 +2.5 ahead
    bvd_renewal_call (seeded, joined) 0.61–0.98 0.89–1.07 1.76–1.79 +4.1 level
    convolve_delay bvd_delay 0.93–0.97 0.62–0.70 1.25–1.26 −0.7 ahead
    patch_infections bvd_patches, S1 and S11 0.59–0.80 0.52–0.72 0.84–0.88 +5.2 ahead
    bvd_patches_port, S3 and S11 0.72–1.10 0.71–1.09 1.78–1.84 +17.4 ahead, except level at T200 S3
    bvd_patches_call (traced), S1 1.07–1.20 1.26–1.59 2.09–2.10 +16.8 gap at one patch: #630
    bvd_patches_call, S5 and S11 0.74–1.00 0.98–1.18 2.19–2.24 level
    zone_share_renewal bvd_zones, S5 and S64 0.50–0.93 0.72–0.82 0.96–1.05 +5.0 ahead
    two_clock_confirmed bvd_two_clock 1.18–1.50 0.94–1.09 1.04–1.06 +1.2 level on gradient; forward behind
    bvd_two_clock_port 1.21–1.46 1.07–1.18 1.38–1.42 +2.2 gap, small
    abscond_thinned_flows bvd_abscond (frozen hand rule) 0.84–1.24 1.09–1.15 1.95–2.05 +5.0 level
    bvd_abscond_port (current hand rule) 1.70–2.49 1.44–1.53 1.94–2.11 +2.8 gap
    onset_report_cdf_table bvd_onset 1.12–1.20 1.10–1.30 1.30–1.32 −1.3 gap, small
    bvd_onset_port 1.17–1.19 1.32–1.42 1.47–1.49 +0.3 gap
    accumulate_occupancy bvd_occupancy 3.84–4.59 2.47–2.49 1.41 +16.2 gap: #427

    The first-gradient column is the wall time of prepare_gradient plus 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

    • Traced patches at one patch (1.26–1.59).
      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, record selection, 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).
    • Occupancy (gradient 2.5×, forward 4×).
      This waits on Depletion with Derived count flows over Recent pools: Mooncake gradient 28x a hand rule #427's proportional-split API.
    • The computed survival kernels: abscond port 1.44–1.53, onset port 1.32–1.42, two-clock port 1.07–1.18.
      • In abscond, the time is spread across the cohort walk and its pullback (_walk_cohort_back! 17%, _add_value! 12%), the forward convolution (14%), and BVD's own abscond_inputs glue (18%). No line holds more than 6%.
      • In onset, the hazard map's derivative takes 38%, and the GC triggered at the walk's scratch allocations about 23%.
      • I tested the one internal lever this suggested: not keeping each cohort's hazard partials, so the reverse pass recomputes them.
        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.
      • The remaining gap is the generic cohort walk against a fused hand loop.
        Closing it needs a fused walk per coefficient shape, a design change rather than a performance fix.
    • First-gradient compile time.
      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


    Generated by Claude Code

  7. seabbs-bot commented on Nov 30, 2026

    @seabbs-bot
    CollaboratorAuthor

    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:

    case time bytes
    window_weights_construction (not a BVD spelling now) 3.3–4.7 2.5
    bvd_occupancy_kernel / bvd_occupancy 2.2–2.5 1.1–1.7
    ward_flows 1.3–2.4 1.5–1.6
    delay_fixed, delay_primary 0.2–1.0 2.0–2.2
    bvd_abscond 0.8–1.5 1.9
    transform, reproduction_pressure 0.5–0.9 1.5–1.6

    #895 removes the output copy of a plain Convolution call 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 Depletion step (occupancy, ward_flows), next.


    Generated by Claude Code

  8. seabbs-bot commented on Nov 30, 2026

    @seabbs-bot
    CollaboratorAuthor

    Blockwise Depletion forward pass (occupancy), no generic win found. Main 63dbaea, T200, one call:

    µs
    CR spelling, whole 5.57
    building the Recurrence and Depletion 0.18
    the call 5.42 (27 ns a step)
    occupancy_outputs 0.58, same bytes as the hand outputs
    BVD hand loop 2.56 (12.8 ns a step)

    The 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 Transform on 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

  9. seabbs-bot commented on Nov 30, 2026

    @seabbs-bot
    CollaboratorAuthor

    Byte gaps from the table above, after #895.
    Allocations profiled by call site, T200:

    case CR / loop bytes CR's allocations the rest
    delay_fixed 5456 / 3328 input buffer (history then input) 1824, lag sums 1664 the loss's own
    bvd_abscond 28824 / 15472 input buffer, lag sums and output transpose, 3272 each about 17 KB is the fixture's permutedims in and out
    transform (S 5) 26760 / 17104 history buffer 8872, output transpose 8072
    reproduction_pressure (S 3) 31248 / 20432 pressure buffer and pressures, 5352 + 4872 buffer 5352, output transpose 4872

    No further clear generic win:

    • The convolution's input buffer is how the buffered path reads its history; dropping it means reading the history and the input apart, which is a larger change.
    • A strata output transposes out of the buffer. For 8-byte floats a copy was chosen over the in-place transpose because it is faster (_INPLACE_BYTES).
    • With one stratum the transpose is its own layout, so the output could take over the buffer. No benchmark case has a single-stratum matrix call (abscond has one stratum per flow), so the gain would not show, and I left it out.
    • abscond's bytes are mostly the fixture's own layout changes, not the package's.

    Generated by Claude Code

  10. seabbs-bot commented on Dec 1, 2026

    @seabbs-bot
    CollaboratorAuthor

    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:

    Case T200 T400
    bvd_two_clock 0.97 0.89
    bvd_abscond, three runs 1.40, 1.01, 1.32 1.04, 1.05, 1.03
    bvd_onset, three runs 1.39, 1.50, 1.10 1.57, 1.21, 1.17
    bvd_occupancy, the model's loss 0.98 1.00
    bvd_occupancy_kernel, the kernels alone 3.9 3.0

    What remains

    1. The blockwise Depletion step (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.
    2. The onset table, 1.1× to 1.6×: the generic cohort walk against a fused hand loop. Two fused prototypes measured slower (Cohort and hazard kernels must be built element by element, which dominates the gradient #329), so no change is known that closes it.
    3. First-gradient compile time, 16 to 17 s more than the hand code for the patch and occupancy models and 5 s or less elsewhere (the comment before the 30 November ones). Not re-measured today: it needs the BVDOutbreakSize models, which this session cannot reach. No lever has been found.

    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

  11. seabbs-bot commented on Dec 2, 2026

    @seabbs-bot
    CollaboratorAuthor

    Outcome: the blockwise Depletion step 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, main at 4ce03f8 against the branch, T = 200; the A/A band was 12 to 31% on a noisy machine.

    1. The blockwise Depletion step (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_kernel main #946 hand loop
    Forward 11.9 µs, 30,432 B 8.5 µs, 30,256 B 4.3 µs, 18,368 B
    Ratio to the hand loop 2.6 1.9

    The 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_outputs pass; 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_census times BVD's incare_census against the same read-out written as a pure step with no step_pullback.

    bvd_census main #946 hand code #946 / hand
    Forward 8.0 µs 3.8 µs 1.7 µs 2.3
    Mooncake reverse 24.0 µs 15.6 µs 6.7 µs (hand rule) 2.3

    So 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 ci tier: 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 ci cases were not run.

    Still open

    The occupancy gap (#914), the onset table and compile time.


    Generated by Claude Code

  12. changed the title [-]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[/+] on Dec 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions