Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions .github/scripts/benchmark-report.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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('&', '&amp;').replaceAll('<', '&lt;')
.replaceAll('>', '&gt;').replaceAll('|', '&#124;').replaceAll('`', '&#96;').replaceAll('\n', ' ');

Expand All @@ -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 };
Expand Down Expand Up @@ -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('', '<details>', `<summary>${backend.label} (${backend.topology}) — ${backend.available ? `${backend.regressions.length} regressions, ${backend.improvements.length} improvements` : 'results unavailable'}</summary>`, '',
Expand Down
14 changes: 14 additions & 0 deletions .github/scripts/benchmark-report.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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/<x|y>\`-${n}`, 2));
Expand Down
6 changes: 6 additions & 0 deletions benchmark/benchmarks.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
47 changes: 36 additions & 11 deletions benchmark/ci.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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), "%")

Expand Down Expand Up @@ -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

Expand All @@ -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")

Expand All @@ -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 > ",
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down
55 changes: 53 additions & 2 deletions benchmark/compare.jl
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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))
Expand Down Expand Up @@ -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
Expand Down
68 changes: 68 additions & 0 deletions benchmark/compare_tests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
Loading
Loading