Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,7 @@ matrix-results/

# Convolution method benchmark output (benchmark/methods.jl).
methods-results/

# Benchmark harness outputs: the A/B rounds and the suite's unsaved runs.
ab-results/
benchmark/suite/results/
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,10 @@
- The extension API is public: `forward`, `forward!`, `pullback!`, `blocks`, `nstate`, `depth`, `param`, `add_param!`, `cotangent`, `add_cotangent!`, `uses_adjoint`, `test_adjoint`, `Executor` and `each!` ([extending][extending]).
- `blocks(m)` marks a modifier that steps groups of compartments together, and `nstate(m, S)` sizes a modifier's state; a resumed call checks each state against it.
- Extensions for Distributions, ForwardDiff, Enzyme, Mooncake, EnzymeTestUtils, FFTW, KernelAbstractions, GPUArraysCore, GPUArrays and Reactant, each loaded with its package ([extensions][extensions]).
- `gradient_routes(backend, r, x; history)` times the gradient of a recurrence by each route its pure steps can take: with each `step_pullback` as written, with the local derivative, and by plain AD of the whole operator ([extending][extending]).
It checks the `step_pullback` first, reports allocations, and times the rule's own passes on device arrays such as `JLArray`s.
The method comes from an extension on ADTypes and DifferentiationInterface.
- `benchmark/ab.jl` compares two revisions interleaved on one machine and gives a verdict per benchmark only outside the noise band of an A/A run, and `benchmark/suite/run.jl` records a hand-run of the suite by commit and machine with a history page.

### Changed

Expand Down
3 changes: 3 additions & 0 deletions Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
ADTypes = "47edcb42-4c32-4615-8424-f2b9edc5f35b"
Adapt = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
CensoredDistributions = "b2eeebe4-5992-4301-9193-7ebc9f62c855"
DifferentiationInterface = "a0c0ee7d-e4b9-4e03-894e-1c5f64a51d63"
Distributions = "31c24e10-a181-5473-b8eb-7969acd0382f"
Enzyme = "7da242da-08ed-463a-9acd-ee780be4f1d9"
EnzymeTestUtils = "12d8515a-0907-448a-8884-5fe00fdf1c5a"
Expand All @@ -33,6 +34,7 @@ Reactant = "3c362404-f566-11ee-1572-e11a4b42c853"

[extensions]
ComposableRecurrencesCensoredDistributionsExt = ["CensoredDistributions", "Distributions"]
ComposableRecurrencesDifferentiationInterfaceExt = ["ADTypes", "DifferentiationInterface"]
ComposableRecurrencesDistributionsExt = "Distributions"
ComposableRecurrencesEnzymeExt = "Enzyme"
ComposableRecurrencesEnzymeTestUtilsExt = ["ADTypes", "Enzyme", "EnzymeTestUtils"]
Expand All @@ -50,6 +52,7 @@ ADTypes = "1"
Adapt = "4"
CensoredDistributions = "0.2.22"
ConstructionBase = "1.6"
DifferentiationInterface = "0.6, 0.7"
Distributions = "0.25"
DocStringExtensions = "0.9.5, 0.10"
Enzyme = "0.13"
Expand Down
63 changes: 63 additions & 0 deletions benchmark/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Benchmarks

Three tools time the package.
Each runs `matrix.jl`, one fresh process a target, on one Julia thread and
one BLAS thread.

## Compare two revisions: `ab.jl`

```sh
julia benchmark/ab.jl --base=origin/main --rounds=3
```

A round runs the base, the candidate and the base again, one process at a
time, in an order that rotates by round.
The two base runs time the same code, so their ratio is the noise of the
machine: the A/A band.
A cell is called faster or slower only when its minimum and its median are
both outside their bands and every round agrees.
The report is `ab-results/REPORT.md`, and `ab-results/ab.tsv` holds its
rows.
Both revisions are checked out as worktrees of commits, with this
checkout's `benchmark` and `test/ADFixtures` folders copied over them, so
commit the package changes to be timed first.

## Keep a history: `suite/run.jl`

```sh
julia benchmark/suite/run.jl --no-save # print only
julia benchmark/suite/run.jl # save to benchmark-results
julia benchmark/suite/run.jl --store=DIR # save to a directory
```

Run it by hand on one named machine, not on CI.
A run is one file under `runs/<machine>/`, named by time and commit, with
the commit, the machine and the AD package versions in its head.
`<machine>` is `BENCHMARK_MACHINE`, or the CPU model and thread count.
Each target runs twice, and the spread of the two is the run's noise band.
Saving rewrites `history.html` beside `runs/`: a page that compares two
runs and charts every run in commit order, one machine at a time.
`--release` labels a run with the release's tag.

## Time a modifier's routes: `gradient_routes`

`ComposableRecurrences.gradient_routes` is the tool for users.
Given a recurrence with a user's modifier it checks the modifier's
`step_pullback` and then times the gradient with it, with the local
derivative and by plain AD, on host arrays and on a device.
See its docstring.

## Figures: `figures.jl`

```sh
julia --project=docs benchmark/figures.jl ab-results docs/src/assets/benchmarks
```

It draws the figures of the performance page from an `ab.jl` result
directory and from the device and route timings in `benchmark/results`.

## Older tools

`run.jl` and `compare.jl` are managed files that the CI workflows call.
`matrix.jl` runs the full grid once and `matrix_report.jl` tabulates it.
`threshold.jl`, `methods.jl` and `step_pullback_ab.jl` are one-off studies.
23 changes: 23 additions & 0 deletions benchmark/Taskfile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
# task -t benchmark/Taskfile.yml matrix-docs
# task -t benchmark/Taskfile.yml threshold -- --target=gradient
# task -t benchmark/Taskfile.yml benchmark-methods
# task -t benchmark/Taskfile.yml ab -- --base=origin/main
# task -t benchmark/Taskfile.yml suite -- --no-save
# task -t benchmark/Taskfile.yml figures -- ab-results
version: '3'

tasks:
Expand Down Expand Up @@ -55,3 +58,23 @@ tasks:
cmds:
- julia --project=benchmark -e 'using Pkg; Pkg.instantiate()'
- julia --project=benchmark --threads=1 benchmark/methods.jl {{.CLI_ARGS}}

ab:
desc: "Compare HEAD with a base revision, interleaved, with an A/A noise band (usage: task -t benchmark/Taskfile.yml ab -- --base=origin/main)"
dir: '{{.TASKFILE_DIR}}/..'
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}}/..'
cmds:
- julia --project=docs -e 'using Pkg; Pkg.instantiate()'
- julia --project=docs --startup-file=no benchmark/figures.jl {{.CLI_ARGS}}
165 changes: 165 additions & 0 deletions benchmark/ab.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
#!/usr/bin/env julia
# Compare a candidate revision with a base revision, interleaved on one
# machine, and give a verdict per benchmark only outside the noise the run
# itself measures.
#
# julia benchmark/ab.jl [options]
# task -t benchmark/Taskfile.yml ab -- [options]
#
# Options:
# --base=REV base revision (default origin/main)
# --cand=REV candidate revision (default HEAD)
# --rounds=N rounds (default 3)
# --tier=NAME size tier of `matrix.jl` (default ci)
# --targets=a,b targets of `matrix.jl` (default primal and
# the five gradient backends)
# --cases=a,b cases (default every case in the tier)
# --seconds=SECONDS BenchmarkTools budget per cell (default 1)
# --timeout=SECONDS per process (default 3600)
# --heap=SIZE heap size hint per process (default 6G)
# --out=DIR result directory (default ab-results)
# --report only rewrite the report of DIR
#
# A round runs the base, the candidate and the base again for each target,
# each a fresh process of `matrix.jl`, one at a time, in an order that
# rotates by round so drift in the machine falls on every slot.
# The two base runs time the same code: their ratio is the A/A noise, and
# `verdict.jl` calls a cell faster or slower only outside it.
#
# Each revision is checked out as a git worktree under DIR, with this
# checkout's `benchmark` and `test/ADFixtures` folders copied over it and
# one resolved manifest, so both run the same benchmark code on the same
# dependency versions and differ in the package alone.
# The worktrees are of commits: uncommitted changes to the package are not
# timed, and this checkout can be edited while a run is going.
# Results go to `DIR/round-<r>/<slot>`, the report to `DIR/REPORT.md` and
# the verdict rows to `DIR/ab.tsv`.
# A rerun with the same DIR resumes: it keeps the commits the run started
# with and the slots that finished.

include(joinpath(@__DIR__, "harness.jl"))
include(joinpath(@__DIR__, "verdict.jl"))

# The folders that define the benchmarks, copied onto each revision.
const SHARED = ("benchmark", joinpath("test", "ADFixtures"))

const AB_DEFAULTS = Dict(
"base" => "origin/main", "cand" => "HEAD", "rounds" => "3",
"tier" => "ci", "targets" => join(HARNESS_TARGETS, ","), "cases" => "",
"seconds" => "1", "timeout" => "3600", "heap" => "6G",
"out" => "ab-results", "report" => "false",
)

@doc raw"""
revision_tree(out, name, rev)

Check `rev` out as the worktree `name` under `out` and copy this checkout's
benchmark code over it.
Returns the worktree's path.
"""
function revision_tree(out, name, rev)
tree = joinpath(out, name)
isdir(tree) && run(`git -C $REPO worktree remove --force $tree`)
run(`git -C $REPO worktree add --detach $tree $rev`)
for d in SHARED
rm(joinpath(tree, d); recursive = true, force = true)
cp(joinpath(REPO, d), joinpath(tree, d))
end
return tree
end

# Resolve the candidate's benchmark environment, give the base the same
# manifest and precompile both, so no timed process compiles a package.
function instantiate(trees)
julia = Base.julia_cmd()
setup(tree, code) = run(
`$julia --project=$(joinpath(tree, "benchmark")) --startup-file=no
-e $code`
)
cand, base = trees
setup(cand, "using Pkg; Pkg.instantiate()")
cp(
joinpath(cand, "benchmark", "Manifest.toml"),
joinpath(base, "benchmark", "Manifest.toml"); force = true
)
code = "using Pkg; Pkg.instantiate(); Pkg.precompile()"
foreach(t -> setup(t, code), trees)
return nothing
end

@doc raw"""
revisions(opts)

The base and the candidate of the run in `opts["out"]`, each its name and
its commit.
They are fixed when the run starts and kept in `revisions.tsv`, so a run
that is resumed, or reported later, keeps its commits whatever the names
point to by then.
"""
function revisions(opts)
file = joinpath(mkpath(opts["out"]), "revisions.tsv")
isfile(file) || open(file, "w") do io
for k in ("base", "cand")
println(io, join((k, opts[k], git("rev-parse", opts[k])), '\t'))
end
end
rows = map(l -> split(l, '\t'), readlines(file))
return Dict(
r[1] => (; name = String(r[2]), sha = String(r[3])) for r in rows
)
end

# Whether a slot's run of `target` finished: `matrix.jl` ends a result file
# with a `finished` line.
function finished(dir, target, opts)
name = string(opts["tier"], "-", replace(target, ' ' => '_'), ".tsv")
file = joinpath(dir, name)
return isfile(file) && any(startswith("# finished="), eachline(file))
end

function run_rounds(opts, trees)
out = opts["out"]
targets = String.(split(opts["targets"], ','))
slots = collect(zip(SLOTS, (trees.base, trees.cand, trees.base)))
for r in 1:parse(Int, opts["rounds"]), target in targets
for (slot, tree) in circshift(slots, r - 1)
dir = joinpath(out, "round-$r", slot)
# A rerun into the same directory resumes where it stopped.
finished(dir, target, opts) && continue
t0 = time()
ok = run_target(tree, dir, target, opts)
println(
"round ", r, " ", rpad(target, 17), rpad(slot, 6),
ok ? "done" : "FAILED", " in ", round(Int, time() - t0), " s"
)
end
end
return nothing
end

function write_report(opts, names)
out = opts["out"]
write(joinpath(out, "REPORT.md"), ab_report(out; names...))
write(joinpath(out, "ab.tsv"), ab_tsv(out))
println("wrote ", joinpath(out, "REPORT.md"))
return nothing
end

function ab_main(args)
opts = options(args, AB_DEFAULTS)
out = opts["out"] = abspath(opts["out"])
revs = revisions(opts)
named(r) = string(r.name, " at ", first(r.sha, 7))
names = (; base = named(revs["base"]), cand = named(revs["cand"]))
if opts["report"] == "false"
trees = (;
cand = revision_tree(out, "cand-tree", revs["cand"].sha),
base = revision_tree(out, "base-tree", revs["base"].sha),
)
instantiate(trees)
run_rounds(opts, trees)
end
return write_report(opts, names)
end

abspath(PROGRAM_FILE) == @__FILE__() && ab_main(ARGS)
Loading
Loading