diff --git a/.gitignore b/.gitignore index fea5c43f8..bffbb08db 100644 --- a/.gitignore +++ b/.gitignore @@ -63,6 +63,5 @@ matrix-results/ # Convolution method benchmark output (benchmark/methods.jl). methods-results/ -# Benchmark harness outputs: the A/B rounds and the suite's unsaved runs. +# Benchmark harness outputs: the A/B rounds. ab-results/ -benchmark/suite/results/ diff --git a/benchmark/README.md b/benchmark/README.md index fc3e9bb49..5560d7ad0 100644 --- a/benchmark/README.md +++ b/benchmark/README.md @@ -25,22 +25,6 @@ The revisions are checked out as worktrees of commits, with this checkout's `ben `ab-results/REPORT.md` holds the report and `ab-results/ab.tsv` its rows. A rerun with the same `--out` resumes the run with the same commits. -## Record a commit: `suite/run.jl` - -```sh -julia benchmark/suite/run.jl --no-save # print only -julia benchmark/suite/run.jl # save to the benchmark-results branch -julia benchmark/suite/run.jl --store=DIR # save to a directory -``` - -The suite is run by hand on one named machine. -A run is one file, `runs//-.tsv`, whose head records the commit, the machine and the AD package versions. -`` is `BENCHMARK_MACHINE`, or the CPU model and thread count. -Each target runs `--repeats` times (default 2), and a target's noise band is the 90th percentile of the absolute log ratio between repeats. -Saving rewrites `history.html` beside `runs/`, which compares two runs and plots every run in commit order, one machine at a time. -A run with uncommitted changes is not saved. -`--release` labels a run `v` and requires that tag on the commit. - ## Time a modifier's gradient routes: `routes/run.jl` ```sh diff --git a/benchmark/Taskfile.yml b/benchmark/Taskfile.yml index 064489c90..d75361fe4 100644 --- a/benchmark/Taskfile.yml +++ b/benchmark/Taskfile.yml @@ -65,13 +65,6 @@ tasks: cmds: - julia --startup-file=no benchmark/ab.jl {{.CLI_ARGS}} - suite: - desc: "Time this commit on this machine and save the run (usage: task -t benchmark/Taskfile.yml suite -- --no-save)" - dir: '{{.TASKFILE_DIR}}/..' - cmds: - - julia --project=benchmark -e 'using Pkg; Pkg.instantiate()' - - julia --startup-file=no benchmark/suite/run.jl {{.CLI_ARGS}} - figures: desc: "Draw the performance figures from an A/B result directory (usage: task -t benchmark/Taskfile.yml figures -- ab-results)" dir: '{{.TASKFILE_DIR}}/..' diff --git a/benchmark/harness.jl b/benchmark/harness.jl index 1636ba83b..ed7de34d7 100644 --- a/benchmark/harness.jl +++ b/benchmark/harness.jl @@ -1,11 +1,11 @@ -# Shared by `ab.jl` and `suite/run.jl`: options, git, the machine's +# Used by `ab.jl`: options, git, the machine's # description and one timed process of `matrix.jl`. using LinearAlgebra: BLAS const REPO = normpath(joinpath(@__DIR__, "..")) -@doc raw"The targets of `matrix.jl` a comparison or a suite run times." +@doc raw"The targets of `matrix.jl` a comparison times." const HARNESS_TARGETS = [ "primal", "ForwardDiff", "Mooncake reverse", "Mooncake forward", "Enzyme reverse", "Enzyme forward", diff --git a/benchmark/suite/history.jl b/benchmark/suite/history.jl deleted file mode 100644 index 29e98b0ed..000000000 --- a/benchmark/suite/history.jl +++ /dev/null @@ -1,95 +0,0 @@ -# The history page of the suite's runs: `history.html`, one self-contained -# file beside `runs/`, with a compare view of two runs and a chart of every -# run in commit order. Run alone to rewrite the page of a store: -# -# julia benchmark/suite/history.jl STORE -# -# It needs `harness.jl`, `verdict.jl` and `store.jl`, which `run.jl` -# includes first. - -if !@isdefined(read_meta) - include(joinpath(@__DIR__, "..", "harness.jl")) - include(joinpath(@__DIR__, "..", "verdict.jl")) - include(joinpath(@__DIR__, "store.jl")) -end - -const HISTORY_TEMPLATE = joinpath(@__DIR__, "history_template.html") - -@doc raw""" - read_suite_run(file) - -A run file as its `meta`, the `times` of its cells, each the fastest -minimum over the repeats in nanoseconds, by `(target, case, size, arm)`, -and the noise `bands` of its targets. - -A target's band is the [`BAND_QUANTILE`](@ref) quantile, over its cells, of -the absolute log ratio of the minimum times of each pair of repeats; a run -with one repeat has none. -""" -function read_suite_run(file) - meta = read_meta(file) - lines = filter(l -> !startswith(l, "# "), readlines(file)) - header = split(first(lines), '\t') - rows = [Dict(zip(header, split(l, '\t'))) for l in lines[2:end]] - repeats = Dict{NTuple{4, String}, Vector{Float64}}() - for r in rows - _ok(r) || continue - push!(get!(repeats, _cell_key(r), Float64[]), _num(r, "min_ns")) - end - times = Dict(k => minimum(v) for (k, v) in repeats) - spread = Dict{String, Vector{Float64}}() - for (k, v) in repeats, i in eachindex(v), j in (i + 1):length(v) - push!(get!(spread, k[1], Float64[]), abs(log(v[j] / v[i]))) - end - bands = Dict(t => quantile(v, BAND_QUANTILE) for (t, v) in spread) - return (; meta, times, bands) -end - -# ---- JSON, for the page's data -------------------------------------------- - -_json(io, x::AbstractString) = print(io, '"', escape_string(x, '/'), '"') -_json(io, x::Real) = print(io, isfinite(x) ? x : "null") -function _json(io, x::AbstractVector) - print(io, '[') - for (i, v) in enumerate(x) - i > 1 && print(io, ',') - _json(io, v) - end - return print(io, ']') -end -function _json(io, x::AbstractDict) - print(io, '{') - for (i, k) in enumerate(sort!(collect(keys(x)))) - i > 1 && print(io, ',') - _json(io, string(k)) - print(io, ':') - _json(io, x[k]) - end - return print(io, '}') -end - -function _run_json(file, store) - run = read_suite_run(file) - return Dict( - "file" => relpath(file, store), "meta" => run.meta, - "bands" => run.bands, - "times" => Dict(join(k, '|') => round(t) for (k, t) in run.times), - ) -end - -@doc raw""" - write_history(store) - -Write `store/history.html` from the runs under `store/runs`. -""" -function write_history(store) - runs = [_run_json(f, store) for f in run_files(store)] - data = sprint(_json, runs) - page = replace(read(HISTORY_TEMPLATE, String), "/*RUNS*/[]" => data) - return write(joinpath(store, "history.html"), page) -end - -if abspath(PROGRAM_FILE) == @__FILE__() - write_history(abspath(only(ARGS))) - println("wrote ", joinpath(abspath(only(ARGS)), "history.html")) -end diff --git a/benchmark/suite/history_template.html b/benchmark/suite/history_template.html deleted file mode 100644 index e0cf969e0..000000000 --- a/benchmark/suite/history_template.html +++ /dev/null @@ -1,309 +0,0 @@ - - - - - -Benchmark history - - - -
-

Benchmark history

-

Runs of the hand-run suite, each on one named machine. -Times are the fastest of a run's repeats. -A change counts only outside the noise band the repeats of the two runs -measure.

-
- - - - -
-
- -

History

-

Each line is a target's time relative to its time in the first run -shown, on a log scale, in commit order. The grey band is the noise band -of the latest run.

-
- -

Compare: tip against base

-

Ratio of the tip's time to the base's. A cell is marked only when the -ratio is outside the noise band; the rest are within noise.

-
-
-
- - - diff --git a/benchmark/suite/run.jl b/benchmark/suite/run.jl deleted file mode 100644 index f7c08b173..000000000 --- a/benchmark/suite/run.jl +++ /dev/null @@ -1,184 +0,0 @@ -#!/usr/bin/env julia -# The hand-run benchmark suite: time this commit on this machine and keep -# the result with the earlier runs, so performance can be read over time. -# -# julia benchmark/suite/run.jl [options] -# task -t benchmark/Taskfile.yml suite -- [options] -# -# Options: -# --no-save print the results and keep them only in -# `benchmark/suite/results/`, which git ignores -# --store=DIR save into the directory DIR, not onto the -# `benchmark-results` branch -# --label=TEXT label of the run (default: the commit's -# subject line) -# --release label the run `v`; the commit must -# have that tag -# --repeats=N runs of each target (default 2) -# --tier=NAME --targets=a,b --cases=a,b --seconds=S --timeout=S --heap=SIZE -# as `ab.jl` -# -# It is run by hand on one named machine, not on CI: a shared runner's -# timings differ more from job to job than most changes do. -# Each target of `matrix.jl` runs `--repeats` times, each a fresh process on -# one Julia thread and one BLAS thread. -# The repeats time the same code, so their spread is the run's own noise -# band, which the history page uses to tell a change from noise. -# -# A run is one file, `-.tsv`, with the commit, the -# machine and the package versions in its head. -# It is saved under `runs//`, where `` is -# `BENCHMARK_MACHINE` or the CPU model and thread count, and the history -# page `history.html` beside `runs/` is rewritten. -# A run with uncommitted changes is not saved: its commit would not -# describe the code that was timed. - -using Dates: Dates, UTC, now, @dateformat_str -using TOML: TOML - -include(joinpath(@__DIR__, "..", "harness.jl")) -include(joinpath(@__DIR__, "..", "verdict.jl")) -include(joinpath(@__DIR__, "store.jl")) -include(joinpath(@__DIR__, "history.jl")) - -const SUITE_DEFAULTS = Dict( - "no-save" => "false", "store" => "", "label" => "", "release" => "false", - "repeats" => "2", "tier" => "ci", "targets" => join(HARNESS_TARGETS, ","), - "cases" => "", "seconds" => "1", "timeout" => "3600", "heap" => "6G", -) -# The columns of a run file: the repeat, then those of `matrix.jl`. -const RUN_COLUMNS = [ - "repeat", "case", "size", "target", "arm", "status", "min_ns", - "median_ns", "allocs", "memory", "prep_s", "relerr", -] -# The packages whose versions a run records. -const RECORDED = [ - "Mooncake", "Enzyme", "ForwardDiff", "DifferentiationInterface", -] - -function release_label() - version = TOML.parsefile(joinpath(REPO, "Project.toml"))["version"] - tag = "v" * version - tag in split(git("tag", "--points-at", "HEAD")) || error( - "this commit does not have the tag $tag; check the tag out first" - ) - return tag -end - -function run_label(opts, dirty) - opts["release"] == "true" && return release_label() - isempty(opts["label"]) || return opts["label"] - subject = git("log", "-1", "--format=%s") - return dirty ? subject * " (dirty)" : subject -end - -function versions(dir) - found = Dict{String, String}() - for f in readdir(dir; join = true), (k, v) in read_meta_tsv(f) - k in RECORDED && (found[k] = v) - end - return [k => found[k] for k in RECORDED if haskey(found, k)] -end -read_meta_tsv(f) = endswith(f, ".tsv") ? read_meta(f) : Dict{String, String}() - -@doc raw""" - run_meta(opts, label, dirty, dirs) - -The head of a run file as `name => value` pairs: the commit, the label, the -machine and the versions the workers under `dirs` recorded. -""" -function run_meta(opts, label, dirty, dirs) - date = `git -C $REPO log -1 --format=%cd - --date=format-local:%Y-%m-%dT%H:%M:%SZ` - return [ - "schema" => "1", - "timestamp" => Dates.format(now(UTC), dateformat"yyyy-mm-ddTHH:MM:SSZ"), - "git_sha" => git("rev-parse", "HEAD"), - "commit_date" => readchomp(addenv(date, "TZ" => "UTC")), - "label" => label, "dirty" => string(dirty), - "machine" => machine_id(), machine()..., - "tier" => opts["tier"], "targets" => opts["targets"], - "repeats" => opts["repeats"], "seconds" => opts["seconds"], - versions(first(dirs))..., - ] -end - -function write_run(file, meta, dirs) - mkpath(dirname(file)) - open(file, "w") do io - foreach(((k, v),) -> println(io, "# ", k, "=", v), meta) - println(io, join(RUN_COLUMNS, '\t')) - for (i, dir) in enumerate(dirs), r in read_run(dir).rows - r["repeat"] = string(i) - println(io, join((get(r, c, "") for c in RUN_COLUMNS), '\t')) - end - end - return file -end - -@doc raw""" - print_run(io, file) - -A table of the run in `file`: the fastest `rule` time of each case over the -repeats, by target, and the run's noise band. -""" -function print_run(io, file) - run = read_suite_run(file) - targets = unique(k[1] for k in keys(run.times)) - cells = sort!(unique((k[2], k[3]) for k in keys(run.times))) - println(io, rpad("case", 46), join(lpad.(targets, 18))) - for (case, size) in cells - print(io, rpad("$case $size", 46)) - for t in targets - ns = get(run.times, (t, case, size, "rule"), NaN) - print(io, lpad(isnan(ns) ? "-" : fmt_time(ns), 18)) - end - println(io) - end - println(io, "\nNoise band between the repeats, by target:") - for t in targets - b = get(run.bands, t, NaN) - println(io, " ", rpad(t, 18), isnan(b) ? "one repeat" : _pct(exp(b))) - end - return nothing -end - -function suite_main(args) - opts = options(args, SUITE_DEFAULTS) - save = opts["no-save"] == "false" - dirty = !isempty(git("status", "--porcelain", "--untracked-files=no")) - save && dirty && error( - "there are uncommitted changes: commit them or pass --no-save" - ) - label = run_label(opts, dirty) - sha = git("rev-parse", "--short", "HEAD") - println("Commit: ", sha, "\nLabel: ", label, "\nMachine: ", machine_id()) - stamp = Dates.format(now(UTC), dateformat"yyyymmddTHHMMSSZ") - work = mktempdir() - dirs = [joinpath(work, "repeat-$i") for i in 1:parse(Int, opts["repeats"])] - for dir in dirs, target in split(opts["targets"], ',') - t0 = time() - ok = run_target(REPO, dir, String(target), opts) - println( - basename(dir), " ", rpad(target, 17), ok ? "done" : "FAILED", - " in ", round(Int, time() - t0), " s" - ) - end - file = write_run( - joinpath(@__DIR__, "results", "$stamp-$sha.tsv"), - run_meta(opts, label, dirty, dirs), dirs - ) - print_run(stdout, file) - println("\nwrote ", file) - save || return nothing - store(root) = save_run(root, file, machine_id()) - if isempty(opts["store"]) - update_results_branch(store, "Add benchmark results for $sha") - println("saved to the ", RESULTS_BRANCH, " branch") - else - println("saved to ", store(mkpath(abspath(opts["store"])))) - end - return nothing -end - -abspath(PROGRAM_FILE) == @__FILE__() && suite_main(ARGS) diff --git a/benchmark/suite/store.jl b/benchmark/suite/store.jl deleted file mode 100644 index 6fdcc3a01..000000000 --- a/benchmark/suite/store.jl +++ /dev/null @@ -1,78 +0,0 @@ -# Where the suite's runs are kept: a `runs//` folder on the -# `benchmark-results` branch, or in a directory. Shared by `run.jl` and -# `history.jl`. - -const RESULTS_BRANCH = "benchmark-results" - -@doc raw""" - read_meta(file) - -The `# name=value` lines at the head of a run file, as a dictionary. -""" -function read_meta(file) - meta = Dict{String, String}() - for line in eachline(file) - startswith(line, "# ") || break - k, v = split(line[3:end], '='; limit = 2) - meta[k] = v - end - return meta -end - -@doc raw""" - run_files(store) - -The run files under `store/runs`, oldest commit first. -""" -function run_files(store) - runs = joinpath(store, "runs") - isdir(runs) || return String[] - files = [ - joinpath(root, f) for (root, _, fs) in walkdir(runs) for f in fs - if endswith(f, ".tsv") - ] - order(f) = (m = read_meta(f); (m["commit_date"], m["timestamp"])) - return sort!(files; by = order) -end - -@doc raw""" - save_run(store, file, machine) - -Copy the run `file` into `store/runs//` and rewrite the store's -history page. -""" -function save_run(store, file, machine) - dir = mkpath(joinpath(store, "runs", machine)) - cp(file, joinpath(dir, basename(file)); force = true) - write_history(store) - return joinpath(dir, basename(file)) -end - -@doc raw""" - update_results_branch(f, message) - -Check the results branch out in a temporary worktree, call `f(store)` on -its root, commit with `message` and push, leaving this checkout untouched. -The branch is started, with no history, when the remote has none. -""" -function update_results_branch(f, message) - dir = mktempdir() - fetched = success(`git -C $REPO fetch origin $RESULTS_BRANCH`) - if fetched - run(`git -C $REPO worktree add --detach $dir origin/$RESULTS_BRANCH`) - else - run(`git -C $REPO worktree add --detach $dir`) - run(`git -C $dir checkout --orphan $RESULTS_BRANCH`) - run(`git -C $dir rm -rfq .`) - end - try - f(dir) - run(`git -C $dir add --all runs history.html`) - commit = `git -C $dir commit -m $message` - run(addenv(commit, "PRE_COMMIT_ALLOW_NO_CONFIG" => "1")) - run(`git -C $dir push origin HEAD:$RESULTS_BRANCH`) - finally - run(`git -C $REPO worktree remove --force $dir`) - end - return nothing -end diff --git a/src/adjoints/adjoints.jl b/src/adjoints/adjoints.jl index 0e09fa8fb..136adf03c 100644 --- a/src/adjoints/adjoints.jl +++ b/src/adjoints/adjoints.jl @@ -467,10 +467,14 @@ The first two are also timed as the rule's forward and reverse pass alone, on host arrays and on each device. Before any time is taken, each `step_pullback` must pass the `step` -component of [`ComposableRecurrences.PieceInterface`](@ref) and -[`ComposableRecurrences.test_adjoint`](@ref), where `backend` has a method. -The gradients of the routes must then agree at `rtol`, and a failed check -throws. +component of [`ComposableRecurrences.PieceInterface`](@ref) at the first +outputs and the starting state. +The rule must pass [`ComposableRecurrences.test_adjoint`](@ref) where +`backend` has a method, and the gradients of the routes must agree at +`rtol`; a failed check throws. + +The method is defined when `ADTypes` and `DifferentiationInterface` are +loaded. # Arguments - `backend`: the AD backend, an `ADTypes` type. diff --git a/test/unit/benchmark_harness.jl b/test/unit/benchmark_harness.jl index 732e56089..76d2407bb 100644 --- a/test/unit/benchmark_harness.jl +++ b/test/unit/benchmark_harness.jl @@ -1,6 +1,5 @@ # The benchmark harness scripts, run as a user runs them, on result files -# written here: the verdicts of `benchmark/ab.jl` and the history page of -# `benchmark/suite`. No benchmark is timed. +# written here: the verdicts of `benchmark/ab.jl`. No benchmark is timed. @testsnippet BenchmarkFiles begin using ComposableRecurrences @@ -91,38 +90,3 @@ end @test !any(r -> r[3] == "broken", rows) @test isfile(joinpath(out, "REPORT.md")) end - -@testitem "Benchmarks: the history page holds a saved run and its band" setup = [ - BenchmarkFiles, -] begin - store = mktempdir() - head(sha, date) = [ - "timestamp=$date", "git_sha=$sha", "commit_date=$date", - "label=run $sha", "machine=test-machine", "targets=primal", - ] - for (sha, date, t) in ( - ("aaaaaaa1", "2026-01-01T00:00:00Z", 1000.0), - ("bbbbbbb2", "2026-01-02T00:00:00Z", 1500.0), - ) - dir = joinpath(store, "runs", "test-machine") - mkpath(dir) - open(joinpath(dir, "$sha.tsv"), "w") do io - foreach(l -> println(io, "# ", l), head(sha, date)) - println(io, join(["repeat"; COLUMNS], '\t')) - for (rep, j) in enumerate((1.0, 1.05)) - cell = ("renewal", "T200_L20_S1", "primal", "rule", "ok") - row = (rep, cell..., t * j, t * j) - println(io, join(row, '\t')) - end - end - end - script(joinpath(BENCH, "suite", "history.jl"), store) - page = read(joinpath(store, "history.html"), String) - @test occursin("\"git_sha\":\"aaaaaaa1\"", page) - @test occursin("\"primal|renewal|T200_L20_S1|rule\":1500", page) - # The band is the spread of the two repeats, log(1.05). - @test occursin("\"bands\":{\"primal\":0.0487", page) - # Older commit first, whatever the file order. - @test findfirst("aaaaaaa1", page)[1] < findfirst("bbbbbbb2", page)[1] - @test !occursin("/*RUNS*/[]", page) -end