From 49af56598769387498d45f598ad74930239051af Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sun, 29 Nov 2026 11:09:52 -0700 Subject: [PATCH 1/2] Benchmark LU and addition with fixed Distributed tile ownership An allocating kernel may move whole tile payloads between processes even when both samples use the same input grid. Preserve those end-to-end measurements and add in-place leaves that hold workspace ownership fixed. Provide a separate diagnostic for ownership and process-level allocations. --- benchmark/benchmarks.jl | 6 ++ benchmark/placement_probe.jl | 106 +++++++++++++++++++++++++++++++++++ benchmark/suites/array.jl | 8 +++ benchmark/suites/linalg.jl | 8 +++ 4 files changed, 128 insertions(+) create mode 100644 benchmark/placement_probe.jl diff --git a/benchmark/benchmarks.jl b/benchmark/benchmarks.jl index e497d711f..303f79e32 100644 --- a/benchmark/benchmarks.jl +++ b/benchmark/benchmarks.jl @@ -96,6 +96,12 @@ # starts `numprocs` Distributed workers *inside the benchmark worker process*, # each with `numthreads` threads. Defaults to no extra workers (everything # runs on the worker process, which uses the orchestrator's thread count). +# On Distributed CPU, the array and linalg suites also run addition into a +# cyclic destination and LU! on a fresh cyclic workspace. Their matching +# allocating leaves retain the scheduler's placement choices. Run the +# optional `benchmark/placement_probe.jl` with the benchmark environment +# and `julia -p 3 -t 1` to inspect per-tile owners and allocations across +# processes separately from BenchmarkTools' driver-only allocation metrics. # - BENCHMARK_REMOTES: Remote hosts on which to start workers, in the format # accepted by `Distributed.addprocs` (colon-separated). Optional. # - BENCHMARK_MPI_RANKS: When set to a positive integer, runs the benchmark diff --git a/benchmark/placement_probe.jl b/benchmark/placement_probe.jl new file mode 100644 index 000000000..439f5caf7 --- /dev/null +++ b/benchmark/placement_probe.jl @@ -0,0 +1,106 @@ +# Run as julia --project= -p 3 -t 1 benchmark/placement_probe.jl +# Optional positional arguments are matrix size, block size, samples and warmups. +# JSON lines report ownership and both driver and all-process allocation deltas. +using Distributed, Dagger, LinearAlgebra, Random +import JSON3 + +length(procs()) > 1 || error("Start Julia with -p to add Distributed workers") +@everywhere using Dagger, LinearAlgebra +@everywhere BLAS.set_num_threads(1) + +function tile_owners(A) + return map(Dagger.chunks(A)) do tile + Dagger.root_worker_id(Dagger._resolved_chunk(tile)) + end +end + +function expected_tile_owners(A) + dims = size(A) + blocks = A.partitioning.blocksize + grid = Dagger.build_procgrid(:cyclicrow, dims, blocks, Dagger.current_acceleration()) + return map(CartesianIndices(Dagger.chunks(A))) do tile + Dagger.root_worker_id(Dagger.procgrid_processor(grid, tile)) + end +end + +function measure(f) + # Take the driver snapshots inside the remote snapshots to exclude all + # counter RPCs from the driver delta. Worker deltas include their ends of + # those control messages and any other process activity in the interval. + foreach(pid -> remotecall_fetch(GC.gc, pid), workers()) + GC.gc() + worker_start = [remotecall_fetch(Base.gc_num, pid) for pid in workers()] + driver_start = Base.gc_num() + start = time_ns() + result = f() + elapsed_ns = time_ns() - start + driver_stop = Base.gc_num() + worker_stop = [remotecall_fetch(Base.gc_num, pid) for pid in workers()] + deltas = [Base.GC_Diff(driver_stop, driver_start); Base.GC_Diff.(worker_stop, worker_start)] + allocations = map(Base.gc_alloc_count, deltas) + bytes = map(d -> d.allocd, deltas) + return result, (; elapsed_ns, allocations, bytes, + total_allocations=sum(allocations), total_bytes=sum(bytes)) +end + +function run_lu(factor, A) + F = factor(A, RowMaximum()) + wait(F.factors) + wait(F.ipiv) + return F +end + +function run_placement_probe(N, b, samples, warmups) + host = rand(MersenneTwister(31), Float64, N, N) + expected_lu = lu(host, RowMaximum()) + blocks = Blocks(b, b) + pids = [myid(); workers()] + cases = ("lu", "lu_fixed", "add", "add_fixed") + for sample in (1-warmups):samples, name in cases + X = DArray(host, blocks, :cyclicrow) + wait(X) + expected = expected_tile_owners(X) + input = tile_owners(X) + @assert input == expected + + if name == "lu" + result, stats = measure(() -> run_lu(lu, X)) + elseif name == "lu_fixed" + result, stats = measure(() -> run_lu(lu!, X)) + elseif name == "add" + result, stats = measure(() -> (Y = X + X; wait(Y); Y)) + else + Y = DArray{Float64}(undef, blocks, N, N; assignment=:cyclicrow) + wait(Y) + @assert tile_owners(Y) == expected + result, stats = measure(() -> (Y .= X .+ X; wait(Y); Y)) + end + + matrix = result isa LU ? result.factors : result + owners = tile_owners(matrix) + pivots = result isa LU ? vec(tile_owners(result.ipiv)) : nothing + if name == "lu_fixed" || name == "add_fixed" + @assert owners == expected + end + if sample == samples + if result isa LU + @assert collect(result.factors) ≈ expected_lu.factors + @assert collect(result.ipiv) == expected_lu.ipiv + else + @assert collect(result) == host + host + end + end + if sample > 0 + JSON3.write(stdout, (; name, sample, pids, tile_grid=size(expected), + input=vec(input), output=vec(owners), pivots, stats...)) + println() + flush(stdout) + end + end +end + +defaults = (1024, 128, 12, 10) +length(ARGS) <= length(defaults) || error("Expected N, block size, samples, warmups") +N, b, samples, warmups = ntuple(i -> i <= length(ARGS) ? parse(Int, ARGS[i]) : defaults[i], 4) +N > 0 && b > 0 && samples > 0 && warmups >= 0 || error("Expected positive dimensions and samples") +run_placement_probe(N, b, samples, warmups) diff --git a/benchmark/suites/array.jl b/benchmark/suites/array.jl index 62f3e0c50..1a1cae656 100644 --- a/benchmark/suites/array.jl +++ b/benchmark/suites/array.jl @@ -50,6 +50,14 @@ function array_suite(ctx; method, accels) setup = (X = rand(Blocks($b, $b), $T, $N, $N; assignment=$fixture_assignment); wait(X)), teardown = (X = nothing; @everywhere GC.gc())) + if fixture_assignment === :cyclicrow + sub["add! (fixed destination)"] = @benchmarkable(wait(Y .= X .+ X), + setup = (X = rand(Blocks($b, $b), $T, $N, $N; assignment=$fixture_assignment); + Y = DArray{$T}(undef, Blocks($b, $b), $N, $N; assignment=$fixture_assignment); + wait(X); wait(Y)), + teardown = (X = nothing; Y = nothing; @everywhere GC.gc())) + end + sub["map (sin.(X))"] = @benchmarkable(wait(sin.(X)), setup = (X = rand(Blocks($b, $b), $T, $N, $N; assignment=$fixture_assignment); wait(X)), teardown = (X = nothing; @everywhere GC.gc())) diff --git a/benchmark/suites/linalg.jl b/benchmark/suites/linalg.jl index f89b14909..df69a0517 100644 --- a/benchmark/suites/linalg.jl +++ b/benchmark/suites/linalg.jl @@ -91,6 +91,14 @@ function linalg_suite(ctx; method, accels) setup = (A = rand(Blocks($b, $b), $T, $N, $N; assignment=$fixture_assignment); wait(A)), teardown = (A = nothing; @everywhere GC.gc())) + if fixture_assignment === :cyclicrow + # lu(A) allocates its own factors, independently of A's + # placement. Factor a fresh, cyclic workspace per sample. + sub["lu! (fixed workspace)"] = @benchmarkable(wait(lu!(A, RowMaximum()).factors), + setup = (A = rand(Blocks($b, $b), $T, $N, $N; assignment=$fixture_assignment); wait(A)), + teardown = (A = nothing; @everywhere GC.gc()), evals = 1) + end + sub["qr"] = @benchmarkable(wait(qr(A).factors), setup = (A = rand(Blocks($b, $b), $T, $N, $N; assignment=$fixture_assignment); wait(A)), teardown = (A = nothing; @everywhere GC.gc())) From 14c09946ce67c4e75c6b07c105d97277d4c30dcd Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sun, 29 Nov 2026 11:25:09 -0700 Subject: [PATCH 2/2] Gate paired Distributed allocations on fixed-placement leaves Keep allocating LU count and byte changes and ordinary addition byte changes visible for review when five measured samples on the matched fixed leaf provide that allocation gate on both revisions. Preserve the addition count gate, timing, the original fallback, and the other leaves and backends. --- .github/scripts/benchmark-report.cjs | 18 ++++-- .github/scripts/benchmark-report.test.cjs | 14 +++++ benchmark/ci.jl | 47 ++++++++++++---- benchmark/compare.jl | 55 +++++++++++++++++- benchmark/compare_tests.jl | 68 +++++++++++++++++++++++ 5 files changed, 185 insertions(+), 17 deletions(-) diff --git a/.github/scripts/benchmark-report.cjs b/.github/scripts/benchmark-report.cjs index 7073de3d4..35d220336 100644 --- a/.github/scripts/benchmark-report.cjs +++ b/.github/scripts/benchmark-report.cjs @@ -11,6 +11,9 @@ const backends = [ { id: 'mpi-threads', label: 'MPI+Threads', topology: '2 ranks × 2 threads' }, ]; const categories = ['regressions', 'improvements', 'within_noise', 'insufficient']; +const advisory = 'advisory_allocations'; +const entryIsValid = (entry, metrics) => typeof entry.name === 'string' && + metrics.includes(entry.metric) && Number.isFinite(entry.ratio); const escape = value => String(value).replaceAll('&', '&').replaceAll('<', '<') .replaceAll('>', '>').replaceAll('|', '|').replaceAll('`', '`').replaceAll('\n', ' '); @@ -21,15 +24,16 @@ function readBackend(root, backend) { try { const data = JSON.parse(fs.readFileSync(file, 'utf8')); if (data.schema_version !== 1 || !Array.isArray(data.jobs) || !data.jobs.length || - !categories.every(key => Array.isArray(data[key]) && data[key].every(entry => - typeof entry.name === 'string' && ['time', 'allocs', 'memory'].includes(entry.metric) && - Number.isFinite(entry.ratio)))) throw new Error('invalid summary'); + !categories.every(key => Array.isArray(data[key]) && + data[key].every(entry => entryIsValid(entry, ['time', 'allocs', 'memory']))) || + (data[advisory] !== undefined && (!Array.isArray(data[advisory]) || + !data[advisory].every(entry => entryIsValid(entry, ['allocs', 'memory']))))) throw new Error('invalid summary'); return { suite, data }; } catch { return { suite, error: 'invalid report' }; } }); - const entries = Object.fromEntries(categories.map(key => [key, + const entries = Object.fromEntries([...categories, advisory].map(key => [key, shards.flatMap(shard => (shard.data?.[key] ?? []).map(entry => ({ ...entry, backend: backend.label }))), ])); return { ...backend, shards, ...entries, available: shards.filter(shard => shard.data).length }; @@ -78,6 +82,12 @@ function renderReport(results, runUrl, limit) { changesTable(sortChanges(totals.regressions), limit), '', '### Improvements across all backends', '', changesTable(sortChanges(totals.improvements, true), limit)); + const advisories = results.flatMap(backend => backend[advisory]); + if (advisories.length) { + parts.push('', '### Advisory allocation changes', '', + 'Paired fixed-placement measurements gate Distributed CPU allocating LU counts and bytes and allocating X + X bytes. Review the advisory changes for costs specific to the allocating path. The original X + X count gate still applies.', '', + changesTable(sortChanges(advisories), limit)); + } for (const backend of results) { parts.push('', '
', `${backend.label} (${backend.topology}) — ${backend.available ? `${backend.regressions.length} regressions, ${backend.improvements.length} improvements` : 'results unavailable'}`, '', diff --git a/.github/scripts/benchmark-report.test.cjs b/.github/scripts/benchmark-report.test.cjs index 49c9686a3..ab9a78288 100644 --- a/.github/scripts/benchmark-report.test.cjs +++ b/.github/scripts/benchmark-report.test.cjs @@ -54,6 +54,20 @@ test('missing and invalid shards are visible, never reported as zero regressions assert.ok(body.includes(`1/${backends.length * suites.length}`)); }); +test('lists advisory allocation changes separately and accepts older summaries', t => { + const root = fixture(t); + const lu = 'linalg/dagger/N=1024 (block 128)/lu'; + write(root, 'distributed', 'linalg', { advisory_allocations: [entry(lu, 1.6, 'memory')] }); + write(root, 'default', 'array', { regressions: [entry('array/dagger/broadcast', 1.7)] }); + const body = buildReport(root, 'https://example.com/run'); + const [before, advisory] = body.split('### Advisory allocation changes'); + assert.ok(before.includes('array/dagger/broadcast')); + assert.ok(!before.includes(lu)); + assert.ok(advisory.includes(`| Distributed | \`${lu}\` | memory | +60.0% |`)); + assert.match(before, /\| Distributed \| 0 \| 0 \| 0 \| 0 \| 1\/4 \|/); + assert.match(before, /\| Threads \| 1 \| 0 \| 0 \| 0 \| 1\/4 \|/); +}); + test('escapes benchmark names and bounds oversized comments without losing totals', t => { const root = fixture(t); const changes = Array.from({ length: 1000 }, (_, n) => entry(`array/dagger/\`-${n}`, 2)); diff --git a/benchmark/ci.jl b/benchmark/ci.jl index a5f9a0c77..b0aeee518 100644 --- a/benchmark/ci.jl +++ b/benchmark/ci.jl @@ -17,6 +17,10 @@ # These are process-local minima across timed evaluations. Placement and # incomplete warmup can affect them, so investigate flags with repeated, # warmed runs rather than assuming they describe global allocation growth. +# Distributed CPU allocating LU counts and bytes and allocating X + X +# bytes are advisory when the fixed-placement peer measures that metric at +# the same size and block size with at least five actual samples per revision. +# Review those advisory changes for costs specific to the allocating path. # - BENCHMARK_NOISE_TOLERANCE: multiple of the reported timing spread that a # change must clear before it is called a regression or an improvement # (default "1.0"). See "Regression check" below; set to "0" to disable the @@ -142,7 +146,8 @@ cur = combined[CUR_REV] # Require five actual samples in both revisions, then confirm timing flags in # fresh processes with revision order reversed to expose run-order effects. comparison_options = (; threshold=THRESHOLD, alloc_threshold=ALLOC_THRESHOLD, - noise_tolerance=NOISE_TOLERANCE) + noise_tolerance=NOISE_TOLERANCE, + pair_distributed_allocations=is_distributed_benchmark(ENV)) comparison = compare_benchmarks(base, cur; comparison_options...) confirmation = nothing if any(entry -> entry[2] == "time", comparison.regressions) @@ -156,7 +161,7 @@ if any(entry -> entry[2] == "time", comparison.regressions) repeated = compare_benchmarks(confirmation[BASE_REV], confirmation[CUR_REV]; comparison_options...) comparison = confirm_timing_regressions(comparison, repeated) end -(; regressions, improvements, within_noise, insufficient) = comparison +(; regressions, improvements, within_noise, insufficient, advisory_allocations) = comparison pct(r) = string(round((r - 1) * 100; digits = 1), "%") @@ -187,18 +192,21 @@ job_regression_counts = job_tally(regressions) job_improvement_counts = job_tally(improvements) job_noise_counts = job_tally(within_noise) job_insufficient_counts = job_tally(insufficient) +job_advisory_counts = job_tally(advisory_allocations) # Worst jobs (most regressions, then fewest improvements) sort to the top. job_summary_rows = [(j, get(job_regression_counts, j, 0), get(job_improvement_counts, j, 0), - get(job_noise_counts, j, 0), get(job_insufficient_counts, j, 0)) for j in job_names] + get(job_noise_counts, j, 0), get(job_insufficient_counts, j, 0), + get(job_advisory_counts, j, 0)) for j in job_names] sort!(job_summary_rows; by = r -> (-r[2], -r[3], r[1])) function job_summary_table(io, rows) - println(io, "| Job | Regressions | Improvements | Within noise | Inconclusive time |") - println(io, "|:---|---:|---:|---:|---:|") - for (job, nreg, nimp, nnoise, ninsufficient) in rows + println(io, "| Job | Regressions | Improvements | Within noise | Inconclusive time | Advisory allocations |") + println(io, "|:---|---:|---:|---:|---:|---:|") + for (job, nreg, nimp, nnoise, ninsufficient, nadvisory) in rows marker = nreg > 0 ? " ⚠️" : (nimp > 0 ? " ✅" : "") - println(io, "| `", job, "`", marker, " | ", nreg, " | ", nimp, " | ", nnoise, " | ", ninsufficient, " |") + println(io, "| `", job, "`", marker, " | ", nreg, " | ", nimp, " | ", nnoise, " | ", + ninsufficient, " | ", nadvisory, " |") end end @@ -210,9 +218,11 @@ summary = (; thresholds=(; time=THRESHOLD, allocations=ALLOC_THRESHOLD, noise=NOISE_TOLERANCE, min_samples=5), timing_confirmation_run=confirmation !== nothing, jobs=[(; name, regressions=nreg, improvements=nimp, within_noise=nnoise, - insufficient=ninsufficient) for (name, nreg, nimp, nnoise, ninsufficient) in job_summary_rows], + insufficient=ninsufficient, advisory_allocations=nadvisory) + for (name, nreg, nimp, nnoise, ninsufficient, nadvisory) in job_summary_rows], regressions=entries_json(regressions), improvements=entries_json(improvements), within_noise=entries_json(within_noise), insufficient=entries_json(insufficient), + advisory_allocations=entries_json(advisory_allocations), ) open(io -> JSON3.write(io, summary), joinpath(OUTPUT_DIR, "summary.json"), "w") @@ -226,9 +236,7 @@ open(joinpath(OUTPUT_DIR, "report.md"), "w") do io job_summary_table(io, job_summary_rows) println(io) if isempty(regressions) - println(io, "No time regressions beyond ", pct(1 + THRESHOLD), - " or allocation regressions beyond ", pct(1 + ALLOC_THRESHOLD), - " (timing changes inside the reported ±spread don't count) 🎉") + println(io, "No benchmark changes exceeded the regression gates 🎉") else println(io, "#### ⚠️ Regressions (time > ", pct(1 + THRESHOLD), " and outside the reported ±spread; allocs/memory > ", @@ -246,6 +254,16 @@ open(joinpath(OUTPUT_DIR, "report.md"), "w") do io println(io, "- `", name, "` (", metric, "): ", pct(r)) end end + if !isempty(advisory_allocations) + println(io) + println(io, "#### Advisory allocation changes") + println(io) + println(io, "Paired fixed-placement measurements gate allocating LU counts and bytes and allocating X + X bytes. Review the advisory changes for costs specific to the allocating path. The original X + X count gate still applies.") + println(io) + for (name, metric, r) in advisory_allocations + println(io, "- `", name, "` (", metric, "): ", pct(r)) + end + end if !isempty(within_noise) # Listed, but deliberately not counted as either outcome: these cleared # their threshold while staying inside the run-to-run spread, so they @@ -315,6 +333,13 @@ if !isempty(insufficient) println("\n$(length(insufficient)) timing change(s) are inconclusive: fewer than five samples, missing spread, or no independent confirmation.") end +if !isempty(advisory_allocations) + println("\n$(length(advisory_allocations)) advisory allocation change(s) with a paired fixed-placement measurement:") + for (name, metric, r) in advisory_allocations + println(" - $name ($metric): $(pct(r))") + end +end + if isempty(regressions) println("\nNo confirmed benchmark regressions (time > $(round(THRESHOLD * 100))%, allocs/memory > $(round(ALLOC_THRESHOLD * 100))%).") exit(0) diff --git a/benchmark/compare.jl b/benchmark/compare.jl index 9f90dad7d..8493c856b 100644 --- a/benchmark/compare.jl +++ b/benchmark/compare.jl @@ -1,10 +1,54 @@ # Shared by the CI driver and its tests; no package installation or benchmark run. +function is_distributed_benchmark(env) + tryparse(Int, get(env, "BENCHMARK_MPI_RANKS", "0")) == 0 || return false + workers = tryparse(Int, first(split(get(env, "BENCHMARK_PROCS", "0:1"), ':'; limit=2))) + return something(workers, 0) > 0 || !isempty(get(env, "BENCHMARK_REMOTES", "")) +end + +function fixed_allocation_peer(name, key) + parts = split(name, '/'; limit=4) + length(parts) == 4 || return nothing + suite, method, size, leaf = parts + method == "dagger" && startswith(size, "N=") || return nothing + if suite == "linalg" && leaf == "lu" + fixed = "lu! (fixed workspace)" + elseif suite == "array" && leaf == "add (X + X)" && key == "memory" + # The fixed destination uses broadcast submission. Keep the count + # gate on ordinary addition, whose placement noise showed up in bytes. + fixed = "add! (fixed destination)" + else + return nothing + end + return join((suite, method, size, fixed), '/') +end + +is_allocation_value(value) = value isa Real && !(value isa Bool) && isfinite(value) && value >= 0 + +function sampled_allocation(results, name, key, min_samples) + stats = get(results, name, nothing) + stats === nothing && return nothing + count = get(stats, "samples", 0) + count isa Integer && !(count isa Bool) && count > 0 && count >= min_samples || return nothing + value = get(stats, key, nothing) + return is_allocation_value(value) ? value : nothing +end + +function has_sampled_allocation_pair(base, cur, name, key, min_samples) + peer = fixed_allocation_peer(name, key) + peer === nothing && return false + baseline = sampled_allocation(base, peer, key, min_samples) + baseline !== nothing && baseline > 0 || return false + return sampled_allocation(cur, peer, key, min_samples) !== nothing +end + function compare_benchmarks(base, cur; threshold=0.10, alloc_threshold=0.25, - noise_tolerance=1.0, min_samples=5) + noise_tolerance=1.0, min_samples=5, + pair_distributed_allocations=false) regressions = Tuple{String,String,Float64}[] improvements = Tuple{String,String,Float64}[] within_noise = Tuple{String,String,Float64}[] insufficient = Tuple{String,String,Float64}[] + advisory_allocations = Tuple{String,String,Float64}[] metrics = (("time", "median", threshold), ("allocs", "allocs", alloc_threshold), ("memory", "memory", alloc_threshold)) for (name, stats) in cur @@ -14,10 +58,16 @@ function compare_benchmarks(base, cur; threshold=0.10, alloc_threshold=0.25, bm = get(base[name], key, nothing) cm = get(stats, key, nothing) (bm === nothing || cm === nothing || bm == 0) && continue + key != "median" && !(is_allocation_value(bm) && is_allocation_value(cm)) && continue ratio = cm / bm regression = ratio > 1 + limit improvement = ratio < 1 - limit (regression || improvement) || continue + if key != "median" && pair_distributed_allocations && + has_sampled_allocation_pair(base, cur, name, key, min_samples) + push!(advisory_allocations, (name, label, ratio)) + continue + end if key == "median" && (get(base[name], "samples", 0) < min_samples || get(stats, "samples", 0) < min_samples) push!(insufficient, (name, label, ratio)) @@ -46,7 +96,8 @@ function compare_benchmarks(base, cur; threshold=0.10, alloc_threshold=0.25, sort!(improvements; by=last) sort!(within_noise; by=last, rev=true) sort!(insufficient; by=last, rev=true) - return (; regressions, improvements, within_noise, insufficient) + sort!(advisory_allocations; by=last, rev=true) + return (; regressions, improvements, within_noise, insufficient, advisory_allocations) end # Airspeed's flattened statistics omit the number of measurements. Recover the diff --git a/benchmark/compare_tests.jl b/benchmark/compare_tests.jl index 4af3b6647..73fc93d1e 100644 --- a/benchmark/compare_tests.jl +++ b/benchmark/compare_tests.jl @@ -32,6 +32,74 @@ include(joinpath(@__DIR__, "compare.jl")) Dict("op" => stats(100))).regressions) end +@testset "Distributed allocation pairs" begin + stats(; time=100, allocs=100, memory=1000, samples=5) = + Dict{String,Any}("median"=>time, "25"=>time, "75"=>time, + "allocs"=>allocs, "memory"=>memory, "samples"=>samples) + lu = "linalg/dagger/N=1024 (block 128)/lu" + fixed_lu = "linalg/dagger/N=1024 (block 128)/lu! (fixed workspace)" + add = "array/dagger/N=1024 (block 128)/add (X + X)" + fixed_add = "array/dagger/N=1024 (block 128)/add! (fixed destination)" + other = "linalg/dagger/N=1024 (block 128)/qr" + gpu = replace(add, "dagger/"=>"dagger+cuda/") + fixed_gpu = replace(fixed_add, "dagger/"=>"dagger+cuda/") + + base = Dict(name=>stats() for name in (lu, fixed_lu, add, fixed_add, other, gpu, fixed_gpu)) + cur = merge(base, Dict(lu=>stats(; time=150, allocs=150, memory=1600), + fixed_lu=>stats(; memory=1550), + add=>stats(; allocs=150, memory=700), other=>stats(; memory=1450), + gpu=>stats(; memory=1400))) + compare(base, cur; env=Dict("BENCHMARK_PROCS"=>"3:1")) = + compare_benchmarks(base, cur; pair_distributed_allocations=is_distributed_benchmark(env)) + + result = compare(base, cur) + @test Set(result.advisory_allocations) == + Set([(lu, "allocs", 1.5), (lu, "memory", 1.6), (add, "memory", 0.7)]) + @test Set(result.regressions) == + Set([(lu, "time", 1.5), (fixed_lu, "memory", 1.55), + (add, "allocs", 1.5), (other, "memory", 1.45), (gpu, "memory", 1.4)]) + @test isempty(result.improvements) + @test confirm_timing_regressions(result, result).advisory_allocations == result.advisory_allocations + @test !isempty(compare(base, cur; env=Dict("BENCHMARK_PROCS"=>"1:2")).advisory_allocations) + @test !isempty(compare(base, cur; env=Dict("BENCHMARK_REMOTES"=>"worker")).advisory_allocations) + for env in (Dict{String,String}(), Dict("BENCHMARK_PROCS"=>"0:4"), + Dict("BENCHMARK_MPI_RANKS"=>"4", "BENCHMARK_PROCS"=>"3:1")) + fallback = compare(base, cur; env) + @test isempty(fallback.advisory_allocations) + @test (lu, "memory", 1.6) in fallback.regressions + @test (add, "memory", 0.7) in fallback.improvements + end + + # A peer must match the shape, metric, and actual sample count in both + # revisions. Missing or incomplete results preserve the original gate. + for remove_from_base in (true, false) + prior, current = copy(base), copy(cur) + side = remove_from_base ? prior : current + misplaced = replace(fixed_lu, "block 128"=>"block 512") + side[misplaced] = pop!(side, fixed_lu) + fallback = compare(prior, current) + @test (lu, "allocs", 1.5) in fallback.regressions + @test (lu, "memory", 1.6) in fallback.regressions + end + for missing_sample in (nothing, 0, 4) + partial = stats(; samples=missing_sample) + fallback = compare(base, merge(cur, Dict(fixed_lu=>partial))) + @test (lu, "memory", 1.6) in fallback.regressions + @test (lu, "allocs", 1.5) in fallback.regressions + end + for invalid_memory in (nothing, NaN, Inf, -1, "unknown", true) + partial = stats(; memory=invalid_memory) + fallback = compare(base, merge(cur, Dict(fixed_lu=>partial))) + @test (lu, "memory", 1.6) in fallback.regressions + @test (lu, "allocs", 1.5) in fallback.advisory_allocations + end + zero_base = compare(merge(base, Dict(fixed_lu=>stats(; memory=0))), cur) + @test (lu, "memory", 1.6) in zero_base.regressions + zero_cur = compare(base, merge(cur, Dict(fixed_lu=>stats(; memory=0)))) + @test (lu, "memory", 1.6) in zero_cur.advisory_allocations + @test (fixed_lu, "memory", 0.0) in zero_cur.improvements +end + @testset "Sample count and independent confirmation" begin stats(t, n) = Dict("median"=>t, "25"=>t, "75"=>t, "samples"=>n) baseline = Dict("op"=>stats(100, 5))