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
24 changes: 23 additions & 1 deletion .github/workflows/lean_action_ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,30 @@ on:

jobs:
build:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
instructions: false
- os: macos-latest
instructions: false
# Of GitHub's runners, only the Linux ARM ones expose a CPU instruction counter.
- os: ubuntu-26.04-arm
instructions: true
runs-on: ${{ matrix.os }}

steps:
- uses: actions/checkout@v5

# Ubuntu's default `kernel.perf_event_paranoid` refuses perf_event_open to unprivileged users.
- name: Allow perf_event_open
if: matrix.instructions
run: sudo sysctl -w kernel.perf_event_paranoid=2

- uses: leanprover/lean-action@v1

- name: Run the Bignum suite
run: |
lake env lean -DElab.async=false --load-dynlib="$(lake query -q perfDynlib)" \
-Dbench.instructions=${{ matrix.instructions }} example/Suites/Bignum.lean
38 changes: 27 additions & 11 deletions MetaBench/Command.lean
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ term.

When `bench.kernelUnfolds n` is set the report also lists the `n` most frequently unfolded
declarations during kernel checking.

When `bench.instructions` is set each phase also reports the CPU instructions used. This depends on
the native library for Metabench.Perf being loaded.
-/

open Lean Elab Command Term Meta
Expand Down Expand Up @@ -72,6 +75,12 @@ meta register_option bench.tag : String := {
descr := "#benchmark: a tag recorded with the JSON output, e.g. a git revision"
}

meta register_option bench.instructions : Bool := {
defValue := false
descr := "#benchmark: if set, count the number of CPU instructions per-benchmark.\
The native shared library associted with MetaBench.Perf must be laoded with `--load-dynlib`."
}

/-- The start time of this process, so every benchmark of one run carries the same `run` stamp. -/
meta initialize runStamp : String ←
return (Std.Time.DateTime.ofTimestamp (← Std.Time.Timestamp.now) .UTC).toISO8601String
Expand Down Expand Up @@ -193,26 +202,29 @@ meta def Spec.label (spec : Spec) : String :=
else "example"

/-- Sample all phases of a single theorem. Returns the `PhaseSamples` and the checked theorem. -/
meta def samplePhases (spec : Spec) : TermElabM (PhaseSamples × TheoremVal) :=
meta def samplePhases (spec : Spec) (instrCounter? : Option Perf.InstrCounter) :
TermElabM (PhaseSamples × TheoremVal) :=
Term.withoutErrToSorry <| Term.withDeclName spec.declName <| Term.withLevelNames spec.levelNames do
let s0 ← Sample.now
let now := Sample.now instrCounter?
let s0 ← now
Term.elabBinders spec.binders fun fvars => do
let goal ← elabGoal spec.goal
let s1 ← Sample.now
let s1 ← now
let proof ← elabProof spec.proof goal
let thm ← mkTheorem spec.declName fvars goal proof
let s2 ← Sample.now
let s2 ← now
kernelCheck thm
let s3 ← Sample.now
let s3 ← now
let phases := fun
| .goal => s1.sub s0
| .proof => s2.sub s1
| .kernel => s3.sub s2
return (phases, thm)

/-- One iteration under the ambient `maxHeartbeats`. -/
meta def runSample (spec : Spec) : TermElabM (PhaseSamples × TheoremVal) :=
Core.withCurrHeartbeats (samplePhases spec)
meta def runSample (spec : Spec) (instrCounter? : Option Perf.InstrCounter) :
TermElabM (PhaseSamples × TheoremVal) :=
Core.withCurrHeartbeats (samplePhases spec instrCounter?)

structure BenchRun where
thm : TheoremVal
Expand All @@ -221,7 +233,8 @@ structure BenchRun where
/-- The kernel's unfolds for the declarations the warmup added, e.g. `decide +kernel`'s lemmas. -/
auxUnfolds : Std.TreeMap String Nat compare

meta def runBenchmark (spec : Spec) : TermElabM BenchRun := do
/-- Run the warmup and the iterations, counting instructions with `instrCounter?` when there is one. -/
meta def runBenchmark (spec : Spec) (instrCounter? : Option Perf.InstrCounter) : TermElabM BenchRun := do
let iters := bench.iters.get (← getOptions)
awaitPendingKernelChecks

Expand All @@ -230,7 +243,7 @@ meta def runBenchmark (spec : Spec) : TermElabM BenchRun := do
let messages := (← getThe Core.State).messages
let info ← getInfoState
let initEnv ← getEnv
let (warmup, thm) ← tryFinally (withOptions (diagnostics.set · true) (runSample spec))
let (warmup, thm) ← tryFinally (withOptions (diagnostics.set · true) (runSample spec instrCounter?))
(modifyEnv (Kernel.enableDiag · (Kernel.isDiagnosticsEnabled initEnv)))
let auxUnfolds := counterDiff (Kernel.getDiagnostics initEnv).unfoldCounter
(Kernel.getDiagnostics (← getEnv)).unfoldCounter
Expand All @@ -241,7 +254,7 @@ meta def runBenchmark (spec : Spec) : TermElabM BenchRun := do
for _ in [0:iters] do
-- Each iteration starts as a fresh declaration would do, where the elaborator caches are empty
-- and `initEnv` is without the auxiliary lemmas the warmup added.
let (ps, _) ← withoutModifyingState <| withEnv initEnv <| withFreshCache <| runSample spec
let (ps, _) ← withoutModifyingState <| withEnv initEnv <| withFreshCache <| runSample spec instrCounter?
samples := samples.push ps
return { thm, warmup, iters := samples, auxUnfolds }

Expand Down Expand Up @@ -277,7 +290,10 @@ public meta def elabBenchmarkCmd : CommandElab := fun stx => do
let label := (label?.map (·.getString)).getD spec.label
withScope (fun s => { s with opts := Elab.async.set s.opts false }) do
runTermElabM fun _ => do
let { thm, warmup, iters := iterations, auxUnfolds } ← runBenchmark spec
-- The counter is opened here, on the thread that runs the benchmark, and closed after it.
let run := runBenchmark spec
let { thm, warmup, iters := iterations, auxUnfolds } ←
if bench.instructions.get (← getOptions) then Perf.withInstrCounter (run ∘ some) else run none
-- Before the declaration is added: the diagnostic check adds it to a kernel environment again.
let kernelUnfolds := (← checkUnfolds thm).foldl (fun m n c => m.insert n (m.getD n 0 + c)) auxUnfolds
if spec.addDecl? then
Expand Down
39 changes: 30 additions & 9 deletions MetaBench/Core.lean
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ module

public import Std.Time.Duration
public import Lean.Data.Json
public import MetaBench.Perf
import Lean

open Lean Elab Std.Time
Expand All @@ -11,21 +12,35 @@ namespace MetaBench
public section

/-- A `Sample` is a pair of a monotonic clock value (in nanoseconds) and the heartbeat count at that
moment. -/
moment, with the measuring thread's instruction count when instructions are counted. -/
structure Sample where
nanos : Nat
heartbeats : Nat
deriving ToJson, FromJson
/-- A count of CPU instructions if they are counted. -/
instructions : Option Nat := none
deriving FromJson

instance : ToJson Sample where
toJson s := Json.mkObj <|
[("nanos", toJson s.nanos), ("heartbeats", toJson s.heartbeats)]
++ Json.opt "instructions" s.instructions

@[inline] def Sample.now : BaseIO Sample := do
return { nanos := ← IO.monoNanosNow, heartbeats := ← IO.getNumHeartbeats }
/-- The sample of this moment, with the count of `instrCounter?` when there is one. -/
@[inline] def Sample.now (instrCounter? : Option Perf.InstrCounter) : IO Sample := do
return { nanos := ← IO.monoNanosNow
heartbeats := ← IO.getNumHeartbeats
instructions := ← instrCounter?.mapM (·.read) }

/-- The interval from `earlier` to `later`. -/
def Sample.sub (later earlier : Sample) : Sample :=
{ nanos := later.nanos - earlier.nanos, heartbeats := later.heartbeats - earlier.heartbeats }
{ nanos := later.nanos - earlier.nanos
heartbeats := later.heartbeats - earlier.heartbeats
instructions := (· - ·) <$> later.instructions <*> earlier.instructions }

def Sample.add (s1 s2 : Sample) : Sample :=
{ nanos := s1.nanos + s2.nanos, heartbeats := s1.heartbeats + s2.heartbeats }
{ nanos := s1.nanos + s2.nanos
heartbeats := s1.heartbeats + s2.heartbeats
instructions := (· + ·) <$> s1.instructions <*> s2.instructions }

/-- Elapsed time as a `Duration`, for display. -/
def Sample.toDuration (s : Sample) : Duration := .ofNanoseconds (.ofNat s.nanos)
Expand All @@ -50,7 +65,7 @@ theorem Phase.mem_all (p : Phase) : p ∈ Phase.all :=
abbrev PhaseSamples := Phase → Sample

def PhaseSamples.total (ps : PhaseSamples) : Sample :=
Phase.all.foldl (fun acc p => acc.add (ps p) ) ⟨0, 0⟩
Phase.all.foldl (fun acc p => acc.add (ps p) ) { nanos := 0, heartbeats := 0, instructions := some 0 }

/-- Format a float with `prec` digits after the decimal point. -/
public def fmtFloat (x : Float) (precision : Nat := 2) : String :=
Expand All @@ -75,8 +90,9 @@ def summarize (xs : Array Nat) : Summary :=
let sorted := xs.qsort (· < ·)
{ min := sorted[0]?.getD 0, median := sorted[sorted.size / 2]?.getD 0, max := sorted.back?.getD 0 }

def Summary.cells (s : Summary) (iterations : Nat) (scale : Float) : Array String :=
let fmt (x : Nat) := fmtFloat (x.toFloat / scale)
def Summary.cells (s : Summary) (iterations : Nat) (scale : Float) (precision : Nat := 2) :
Array String :=
let fmt (x : Nat) := fmtFloat (x.toFloat / scale) precision
#[fmt s.median] ++ if iterations > 1 then #[fmt s.min ++ "…" ++ fmt s.max] else #[]

instance : ToJson PhaseSamples where
Expand Down Expand Up @@ -131,10 +147,15 @@ def renderReport (r : Report) : String :=
let proofNodes := r.proofNodes
let n := iters.size
let heading (unit : String) : Array String := #[unit] ++ if n > 1 then #["min…max"] else #[]
let instructions_counted := !iters.isEmpty && iters.all fun it => Phase.all.all fun p => (it p).instructions.isSome
let header := #["phase"] ++ heading "kHB" ++ heading "ms"
++ if instructions_counted then heading "Minstr" else #[]
let row (name : String) (samples : Array Sample) : Array String :=
#[name] ++ (summarize (samples.map (·.heartbeats))).cells n 1000.0
++ (summarize (samples.map (·.nanos))).cells n 1_000_000
++ if instructions_counted then
(summarize (samples.map (·.instructions.getD 0))).cells n 1_000_000 (precision := 3)
else #[]
let rows := #[header] ++ Phase.all.map (fun p => row p.name (iters.map (· p)))
|>.push (row "total" (iters.map (·.total)))
let kernelNs := (summarize (iters.map fun it => (it .kernel).nanos)).median
Expand Down
119 changes: 119 additions & 0 deletions MetaBench/Perf.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
module

/-!
# CPU Instruction counting

A `Perf.InstrCounter` counts the CPU instructions on a thread.

* On Linux it is a hardware counter from `perf_event_open`. It records only user-space CPU instructions.
* On macOS it is the kernel's count for the current thread using `thread_selfcounts`. The count includes the
instructions the kernel runs on the thread's behalf.

Native implementations are in `native/perf_linux.c` and `native/perf_macos.c`.
-/

namespace MetaBench.Perf

/-- Open a counter for the calling thread. Returns its descriptor, or `-errno`. -/
@[extern "metabench_instr_count_open"]
opaque openRaw : BaseIO Int32

/-- The count of the counter with descriptor `fd`, or `-errno`. -/
@[extern "metabench_instr_count_read"]
opaque readRaw (fd : Int32) : BaseIO Int64

/-- Close the counter with descriptor `fd`. Returns `0` or `-errno`. -/
@[extern "metabench_instr_count_close"]
opaque closeRaw (fd : Int32) : BaseIO Int32

/-- macOS native errnos. -/
inductive MacOSErrno where
| ENOTSUP

def MacOSErrno.ofInt32? : Int32 → Option MacOSErrno
| 45 => some .ENOTSUP
| _ => none

instance : ToString MacOSErrno where
toString
| .ENOTSUP => "ENOTSUP"

/-- Linux native errnos. -/
inductive LinuxErrno where
| EPERM | ENOENT | EIO | EACCES | ENODEV | ENOSYS | EOPNOTSUPP

def LinuxErrno.ofInt32? : Int32 → Option LinuxErrno
| 1 => some .EPERM
| 2 => some .ENOENT
| 5 => some .EIO
| 13 => some .EACCES
| 19 => some .ENODEV
| 38 => some .ENOSYS
| 95 => some .EOPNOTSUPP
| _ => none

instance : ToString LinuxErrno where
toString
| .EPERM => "EPERM"
| .ENOENT => "ENOENT"
| .EIO => "EIO"
| .EACCES => "EACCES"
| .ENODEV => "ENODEV"
| .ENOSYS => "ENOSYS"
| .EOPNOTSUPP => "EOPNOTSUPP"

def MacOSErrno.explain : MacOSErrno → String
| .ENOTSUP => "this machine does not record an instruction count"

def LinuxErrno.explain : LinuxErrno → String
| .EPERM | .EACCES =>
"the kernel refused perf_event_open: it needs `kernel.perf_event_paranoid` at 2 or lower"
| .ENOENT | .ENODEV | .EOPNOTSUPP => "this machine exposes no hardware instruction counter"
| .ENOSYS => "the kernel has no perf_event_open"
| .EIO => "perf_event_open or the read of its counter failed"

def describe {ε : Type} [ToString ε] (errno : Int32) (e? : Option ε) (explain : ε → String)
(unnamed : String) : String :=
match e? with
| some e => s!"{explain e} ({e}, errno {errno})"
| none => s!"{unnamed} (errno {errno})"

def explain (errno : Int32) : String :=
if System.Platform.isOSX then
describe errno (MacOSErrno.ofInt32? errno) MacOSErrno.explain "thread_selfcounts failed"
else
describe errno (LinuxErrno.ofInt32? errno) LinuxErrno.explain
"perf_event_open or the read of its counter failed"

/-- A counter of CPU instructions. -/
public structure InstrCounter where
private mk ::
/-- The descriptor `perf_event_open` returned on Linux. Unused on macOS. -/
fd : Int32

/-- Open an instruction counter for the calling thread. -/
def InstrCounter.open : IO InstrCounter := do
unless System.Platform.isLinux || System.Platform.isOSX do
throw <| .userError "bench.instructions: instructions can only be counted on Linux and macOS"
let fd ← openRaw
if fd < 0 then
throw <| .userError s!"bench.instructions: {explain (-fd)}"
return { fd }

def InstrCounter.close (instrCounter : InstrCounter) : IO Unit :=
discard <| closeRaw instrCounter.fd

/-- The instruction counter's running total. It must be read on the thread that opened the counter. -/
public def InstrCounter.read (instrCounter : InstrCounter) : IO Nat := do
let count ← readRaw instrCounter.fd
if count < 0 then
throw <| .userError s!"bench.instructions: {explain (-count).toInt32}"
return count.toNatClampNeg

/-- Run `act` with a CPU instruction counter opened for the calling thread, and close it when `act` is done. -/
public def withInstrCounter {m : Type → Type} {α : Type} [Monad m] [MonadLiftT IO m] [MonadFinally m]
(act : InstrCounter → m α) : m α := do
let instrCounter ← InstrCounter.open
try act instrCounter finally instrCounter.close

end MetaBench.Perf
31 changes: 28 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,31 @@ Each object has the fields:
- `warmup`: the samples of the warmup, per phase.
- `iters`: the samples of every measured iteration, per phase.

A sample is `{"heartbeats": n, "nanos": n}` and the phases are `goal`, `proof` and `kernel`. The
file loads into pandas with `pd.read_json(path, lines=True)`. On the Lean side the same record is
`MetaBench.Report`, with `ToJson` and `FromJson` instances.
A sample is `{"heartbeats": n, "nanos": n}` and the phases are `goal`, `proof` and `kernel`. When
[instructions are counted](#counting-instructions) a sample also contains the `"instructions"` field.

## Counting CPU instructions

Pass the `-Dbench.instructions=true` flag to count the CPU instructions run on each phase. Unlike
heartbeats the count sees arithmetic on large numbers, and it varies less than the clock.

```
METABENCH=. example/bench-run.sh <mathlib-checkout> example/Suites/Det.lean -Dbench.instructions=true
```

The report has a `Minstr` column in units of millions of CPU instructions.

This feature is provided as a native library in the `perfDynlib` target that lake builds with the
system's C compiler. The path to the built shared library (which can be obtained using
`lake query -q perfDynlib`) must be passed to lean using its `--load-dynlib` flag whenever the
`-Dbench.instructions=true` flag is used.

If a system C compiler is available then `example/bench-run.sh` automatically builds the `perfDynlib` target and passes `--load-dynlib`.

The Linux and macOS implementations count instructions differently, so the numbers are not comparable with each other:

- **Linux** ([`native/perf_linux.c`](native/perf_linux.c)) reads a hardware counter with
`perf_event_open`. Some CI and container hosts do not expose this counter and this feature will
not work in this case. `kernel.perf_event_paranoid` must be 2 or lower.
- **macOS** ([`native/perf_macos.c`](native/perf_macos.c)) reads the kernel's count for the thread
with `thread_selfcounts`.
19 changes: 19 additions & 0 deletions example/Suites/Bignum.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/-
Run in the root of the repo with:

METABENCH=. example/bench-run.sh <mathlib-checkout> example/Suites/Bignum.lean -Dbench.instructions=true
-/
import MetaBench

-- `decide` only evaluates `3 ^ n` for exponents up to this threshold, which is 256 by default.
set_option exponentiation.threshold 1000000

#benchmark "pow-mod/1000" in example : 3 ^ 1000 % 1000003 = 73216 := by decide
#benchmark "pow-mod/10000" in example : 3 ^ 10000 % 1000003 = 218751 := by decide
#benchmark "pow-mod/100000" in example : 3 ^ 100000 % 1000003 = 799099 := by decide
#benchmark "pow-mod/1000000" in example : 3 ^ 1000000 % 1000003 = 222223 := by decide

#benchmark "gcd/1000" in example : Nat.gcd (3 ^ 1000) (5 ^ 1000) = 1 := by decide
#benchmark "gcd/10000" in example : Nat.gcd (3 ^ 10000) (5 ^ 10000) = 1 := by decide
#benchmark "gcd/100000" in example : Nat.gcd (3 ^ 100000) (5 ^ 100000) = 1 := by decide
#benchmark "gcd/1000000" in example : Nat.gcd (3 ^ 1000000) (5 ^ 1000000) = 1 := by decide
Loading
Loading