diff --git a/.gitignore b/.gitignore index cad9aab..1673264 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,11 @@ /docs/build/ .vscode .perftest_logs -.perftests \ No newline at end of file +.perftests + +._* +.DS_Store +.ipynb_checkpoints/ +core +experiments/ +.claude diff --git a/AGENT.md b/AGENT.md new file mode 100644 index 0000000..ed990eb --- /dev/null +++ b/AGENT.md @@ -0,0 +1,268 @@ +# AGENT.md — PerfTest.jl developer guide + +Orientation for AI agents doing package-wide work on **PerfTest.jl**, a Julia package +(`JuliaPerf/PerfTest.jl`, module `PerfTest`, currently v0.2.1) that compiles ordinary +`Test.jl`-style recipe scripts into performance-regression test suites. Originated as a +Master's thesis at USI, supervised with CSCS. Read this before touching `src/`. + +## Mental model: two phases + +1. **Transform (parse) time** — `PerfTest.transform` (alias of `treeRun`) reads a *recipe* + script (plain Julia using `@testset`/`@test` plus PerfTest macros like `@perftest`, + `@regression`, `@roofline`), walks its AST twice with `MacroTools.prewalk`, and emits a + new Julia `Expr` for a self-contained test-suite module (`__PERFTEST__`). No benchmarking + happens in this phase — it is pure macro expansion via a custom rule engine (PerfTest does + **not** use real Julia macros for `@perftest` etc.; they are ordinary macrocalls matched + and rewritten by pattern, then the not-yet-`@`-expanded generated code is written to disk). +2. **Execution (run) time** — the generated suite (saved as `_perfsuite.jl`) is + `include`d/launched as its own process. It runs real `BenchmarkTools.@benchmark`s, computes + metrics/methodology results (`Test_Result`, `Methodology_Result`, ...), persists them via + JLD2, and optionally uploads to bencher.dev. + +`runperftests(file)` is the public one-call entry point: transform → save → execute. +`PerfTest.retrievePerfTests(datafile; ...)` is the public post-hoc query API over saved results. + +## Directory map (`src/`) + +``` +src/PerfTest.jl module root: exports, include order, rule-engine driver, treeRun/runperftests +src/extension_stubs.jl forward-declares functions implemented in ext/*, is_loaded(), Mode types +src/logs.jl Logger + per-channel log buffers, log folder save +src/printing.jl colored console print helpers + +src/transform/ ── PARSE TIME ── + datastruct.jl ASTRule, MacroParameter, Context/LocalContext/GlobalContext, generic combinators + configuration.jl `Configuration` submodule: CONFIG_SHAPE schema, load/save/merge TOML config + prefix.jl / suffix.jl boilerplate injected at top/bottom of the generated suite module + auxiliar.jl AST utility grab-bag (see below) — included LAST, used throughout + dummy.jl trivial fixture recipe, used only by @compile_workload + metrics/{primitives,custom}.jl built-in metrics (median_time, min_time, ...) + @define_metric machinery + methodologies/{common,manual,regression,roofline,mem_bandwidth}.jl + one file per assertion "methodology" (@perfcompare/@regression/@roofline/@def_eff_mem) + validation/{errors,formula,macro,export_vars}.jl + generic macro-arg validator, error collection, formula symbol table + parsing/{rules,hierarchy_transform,target_transform,formula_transform}.jl + the actual ASTRule instances + testset/target/formula AST rewriters + +src/execution/ ── RUN TIME ── + structs.jl Metric_Result, Test_Result, Suite_Execution_Result, Perftest_Datafile_Root, ... + testset.jl PerfTestSet <: AbstractTestSet — custom Test.jl testset that records results + machine_topology.jl `Topology` submodule: NUMA/thread pinning (hwloc/ThreadPinningCore) + machine_benchmarking.jl measures machine peak FLOPs / memory bandwidth (used by @roofline) + retrieve.jl public query API: retrievePerfTests, inTestSet, hasMetric, testPassed/testFailed + data_handling.jl JLD2 save/load of Perftest_Datafile_Root + units.jl magnitudeAdjust — magnitude-prefix normalization for display + printing.jl runtime output (roofline UnicodePlots, hierarchical test-name printing) + launch_suite.jl `Launch` submodule: runs the generated `_perfsuite.jl` as a subprocess + macros/ one file per user-facing macro: perftest, perfcompare, roofline, regression, + exec_ignore (@on_perftest_exec/_ignore), customs (@define_metric &c.), + configuration (@perftest_config), topology (@perftest_threads, WIP) + +src/bencher/ bencher.dev integration: REST client, JSON report export, submitReport + +ext/ package extensions (Julia weakdeps), loaded only when the dep is present: + PerfTest_LIKWIDExt.jl LIKWID hardware performance counters + PerfTest_MPIExt.jl MPI-aware multi-rank benchmarking + PerfTest_CUDAExt.jl CUDA GPU energy/power sampling (WIP) + PerfTest_AMDGPUExt.jl AMDGPU energy/power via ROCm SMI ccall (WIP) +``` + +## Core concepts + +### The rule engine (`ASTRule`) +- `struct ASTRule` = `(match, validation, transformation)` functions (`src/transform/datastruct.jl`). + Most are built via `ASTRule(match, macro_params::Dict{Symbol,MacroParameter}, transformation)`, + which auto-wraps `validateMacro(macro_params)` as the validation step. +- `ruleSet(context, rules::Vector{ASTRule})` (`src/PerfTest.jl`) builds a closure applying rules + to one AST node. **Only the first matching rule in the vector runs — order matters.** +- `first_pass_rules` (testset/perftest/regression/roofline/... macro rules) run first via + `MacroTools.prewalk`, producing sentinel tokens `:__PERFTEST_FW__`/`:__PERFTEST_AFTER__`. + `second_pass_rules` (`prefix_macro_rule`, `suffix_macro_rule`) replace those sentinels with + real prefix/suffix boilerplate. This two-pass split is why prefix/suffix code can't simply be + emitted in the first pass — it depends on info only fully known after the first pass completes. +- A separate mini rule-set, `perftest_expression_ruleset` (`transform/parsing/target_transform.jl`), + is used only inside `parseTarget` to interpolate outer-scope variables into a `@perftest` + target so `BenchmarkTools.@benchmark` (which runs in module/global scope) can see them. +- `_treeRun`/`treeRun` in `src/PerfTest.jl` drive the whole pipeline; `treeRun`'s final step is + `rewrapDoBlockBodies(MacroTools.prettify(module_full))` — see "Known rough edges" for why the + `rewrapDoBlockBodies` wrapper exists. + +### Context objects (`src/transform/datastruct.jl`) +Parse-time state, not thread-safe by design (one `PerfTest.ctx` module-global per transform): +- `GlobalContext` — whole-file: original path, error collection, valid formula symbols, `in_recursion`. +- `LocalContext` — scope-local: `depth_record` (testset-nesting stack), `custom_metrics` and + `enabled_methodologies` (one inner vector per nesting level — pushed/popped as testsets open/close). +- `Context` wraps both plus `test_tree_expr_builder` (unused leftover from a removed tree-builder + implementation — see "Known rough edges"). + +### Generic macro-argument validation (`src/transform/validation/macro.jl`) +Nearly every DSL macro (`@regression`, `@define_metric`, `@roofline`, `@perftest_config`, ...) is +declared declaratively as a `Dict{Symbol,MacroParameter}` (built via `defineMacroParams`, e.g. in +`src/execution/macros/regression.jl`) and parsed by one of two shared functions: +- `validateMacro(params)` — for macros with a trailing positional block arg (e.g. + `@define_metric name=... units=... begin ... end`). +- `validateBlocklessMacro(params)` — for all-keyword macros (e.g. `@regression metrics=... threshold=...`). + +Both type-check each `a = b` argument against `MacroParameter.type`. If the raw AST node's own +type doesn't satisfy it directly, they fall back to `resolveLiteral(b)` (unwraps `QuoteNode`s and +`Expr(:vect, ...)` literals into real `Symbol`/`String`/`Vector` values) plus `typeMatches`, which +additionally accepts a real `Vector{ET}` against a declared `Vector{Union{...}}` parameter type — +working around Julia's invariant generic typing. **Validation runs against the resolved value** +when the fallback path is used, not the raw AST — keep this in mind when adding new parameter types. + +### Formula mini-language (`src/transform/validation/formula.jl`, `parsing/formula_transform.jl`) +`@define_metric`/`@roofline`/etc. bodies accept quoted-symbol "formulas" (e.g. `:min_time`, +`:median_time`, dotted chains like `:flop.double.vector_512` for LIKWID counters). `:autoflop` is still in the +whitelist but is legacy: the primitive is hard-wired to 0 (`transformPerftest`), so every use of it (in a formula, as a +`@regression` metric, or `general.autoflops = true` for a `@roofline` without `actual_flops`) is reported as a parse +error by `reportAutoflopUse!` (`validation/formula.jl`); the key alone is not. `formula_symbols` +is the built-in whitelist; `transformFormula`/`SBMID` resolve a symbol at runtime by checking, in +order: `_PRFT_GLOBALS.custom_benchmarks` → builtins → `test_res.metrics` → `test_res.auxiliar` → +(if LIKWID loaded) hardware counters. Dotted chains are collapsed by `collectSymbolChain` before +substitution so genuine field access isn't misparsed as a metric reference. A custom metric or benchmark +(`@define_metric`/`@auxiliary_metric`/`@define_benchmark`) is referred to by its optional `symbol = :s` parameter, or +`Symbol(name)` when it is absent (`metricSymbol` in `metrics/custom.jl`). + +### Methodologies and scope inheritance (`src/transform/methodologies/`) +Each methodology (regression/roofline/perfcompare/mem-bandwidth) stores a `MethodologyParameters` +(id, `override::Bool`, `params::Dict`) per open testset scope. `captureMethodologyInfo(id, ...)` +(`methodologies/common.jl`) walks the scope stack **innermost-first**, merging `params` keys +first-write-wins and stopping early at the first `override=true` entry — this implements "inner +scope inherits outer scope's methodology config unless it opts to fully override it." `@regression` +redeclared in the same scope extends the existing entry in place (rather than pushing a competing +second entry that would lose under first-key-wins merge) — see `onRegressionDefinition`. + +### Package extensions +CUDA/AMDGPU/LIKWID/MPI support lives in `ext/*.jl` as Julia package extensions (weakdeps in +`Project.toml`), loaded only when the user's environment has the corresponding package. Code in +`src/` checks `is_loaded(:LIKWID)` etc. (`src/extension_stubs.jl`) before calling extension +functionality, and extension-provided functions are forward-declared as stubs there. + +## Public API surface (exports from `src/PerfTest.jl`) + +Macros: `@perftest`, `@perftest_config`, `@perftest_threads`, `@on_perftest_exec`, +`@on_perftest_ignore`, `@export_vars` (deprecated), `@define_benchmark`, +`@define_eff_memory_throughput`/`@def_eff_mem`, `@define_metric`, `@define_test_metric`, +`@auxiliary_metric`, `@roofline`, `@perfcompare`/`@perfcmp`, `@regression`. +Functions: `runperftests`, `PerfTest.transform` (= `treeRun`), `magnitudeAdjust`, +`PerfTest.retrievePerfTests` (+ predicates `inTestSet`/`hasMetric`/`testPassed`/`testFailed`). + +## Configuration system + +`Configuration` submodule (`src/transform/configuration.jl`) defines `CONFIG_SHAPE` (schema), +`DEFAULT`/`PRECOMPILATION_CONFIG` dicts, and TOML-backed `load_config`/`save_config`/`merge_configs` +(deep merge, override wins). Sections: `general`, `regression`, `roofline`, `memory_bandwidth`, +`perfcompare`, `machine_benchmarking`, `MPI`, `bencher`. Users override via a `perftest_config.toml` +file and/or an inline `@perftest_config "toml string"` in the recipe (merged at both parse time and +re-emitted into the generated suite so the same config applies at execution time). Full key +reference: `docs/src/configuration_params.MD`. + +## Testing + +- `test/runtests.jl` is a **custom subprocess runner**, not a plain `include`-everything script: it + `walkdir`s `test/`, picks up every `t*.jl` file, and runs each as its own `julia -O3 + --startup-file=no ` subprocess (so each `tN-*.jl` is an independent process/testset, not + aggregated into one `Test` tree). Cleans up `.perftest_logs`/`.perftests` afterward. +- Individual files can be run standalone for fast iteration: `julia --project test/t2-validation-macro.jl`. +- `test/t1`–`t6` cover: formula transformation, generic macro-arg validation, end-to-end AST + transforms (asserted via `PerfTest.dumpLogsString()` log content), a full transform→execute→ + persist→query pass (`t4`), the regression methodology across repeated runs (`t5`, run 3× in a + loop to exercise baseline-then-compare behavior), and the no-perftest-macros passthrough case (`t6`). +- `test/test-recipes/ex*.jl` are fixture recipe scripts (not tests themselves) fed through + `PerfTest.transform` by `t3`–`t6`. When fixing a transform/validation bug, the pattern is: + add a minimal fixture recipe here, then assert on it from `t3` (or add a new `tN` file). +- **CI does not run the test suite.** `.github/workflows/CI.yml`'s `test:` job is commented out; + only the `docs:` job (Documenter build + doctest) runs on push/PR. Always run + `julia --project test/runtests.jl` (or the specific `tN` file you touched) manually — don't + assume a green PR check means tests passed. Per user preference, the user runs the Julia test + suite / `Pkg.instantiate` themselves; AST-only `julia -e` checks are an acceptable substitute + when you can't run the full suite. +- `examples/` (e.g. `example-kkt-cholesky-regression`, `example-quickstart`) double as real-world + integration tests: at least two recent bugs (vector-literal macro args rejected by validation; + `do`-block tuple bodies corrupted by `MacroTools.prettify`) were discovered via a real example + recipe rather than the unit tests. When debugging a transform issue, check whether an example + under `examples/` reproduces it before writing a synthetic fixture. + +## Known rough edges (read before refactoring nearby code) + +- `src/transform/auxiliar.jl`'s `genTestName!`/`testsetUpdate!` reference `state.depth` and + `ASTWalkDepthRecord`, which do not exist under those names in current `datastruct.jl` + (`LocalContext.depth_record::Vector{DepthEntry}` is the real field). These two functions appear + to be orphaned from a prior refactor — the actual test-naming logic lives inline in + `transformPerftest` (`parsing/hierarchy_transform.jl`). Verify call sites before relying on them. +- The older explicit-stack tree-builder (`hierarchy_transform_test_region.jl` / + `hierarchy_transform_benchmark_region.jl`, plus `suffix.jl`'s `oldperftestsuffix`) that predated the + "hierarchy fusion" refactor (`f935fc7`) has been removed — `transformTestset`/`transformPerftest`/ + `backTokenToContextUpdate!` in `hierarchy_transform.jl` are the live implementation. + `Context.test_tree_expr_builder` (`datastruct.jl`) is dead state left over from that removal (no + remaining writer populates it meaningfully) — a candidate for a future follow-up cleanup, not yet + removed. + `@export_vars` (`validation/export_vars.jl`) is marked `# DEPRECATED` at its rule-definition site. +- `treeRun`'s final line, `rewrapDoBlockBodies(MacroTools.prettify(module_full))` + (`src/PerfTest.jl`): `MacroTools.prettify`'s `flatten` pass strips a `:block` wrapper around a + single-statement body — including a `do`-block's lambda body. If that single statement is itself + a non-`:block` form (e.g. a tuple literal), Julia's `Base.show` for `:do` (unlike `:for`/`:if`/ + `:let`) doesn't defensively re-wrap it, so it gets printed as several bare comma-free statements + instead of one tuple once written to the generated suite file. `rewrapDoBlockBodies` + (`src/transform/auxiliar.jl`) walks the post-`prettify` tree and restores the block. Any future + change to how the generated suite is prettified/serialized must preserve this fix. +- Thread lists in `@perftest_threads` (`execution/machine_topology.jl` `Topology`, `execution/launch_suite.jl` + `Launch`) are not fully supported, though the transform accepts them: + - A mixed list such as `[(1,1), :numa]` passes `validateArrangement` (each element is valid), but there is no + `literallizeArrangement(::Vector{Any})`: the generated suite throws a `MethodError` (its `literallizeArrangement` + call, see `parseThreadsMacro`, is outside the `try`), and so do `Launch.retrieveThreadConfig` and `suiteCommand`, + so `runperftests` cannot launch it. + - A list of tuples such as `[(1,1),(1,1//2)]` is literalized element-wise into a `Vector` of tuples, which + `suiteCommand` then multiplies (`configurations[1] * configurations[2]`, a `MethodError` for two tuples). + - A manual pinning list rejects CPU id 0 at transform (`validateArrangement(::Vector{<:Integer})`, "must be + positive integers"), although hwloc's OS indices start at 0, so CPU 0 can never be pinned. An id the machine + does not have throws `MethodError: min(::Flatten)` at execution (`literallizeArrangement(::Vector{<:Integer})`) + instead of its intended message. + - A manual pinning list `[1, 2, 3]` is launched with `--threads=2`, the product of its first two ids (the same + `configurations[1] * configurations[2]`), instead of its length, and `[1]` throws a `BoundsError`. + - `Launch.suiteArrangementOrigin` (behind `suiteArrangement`/`retrieveThreadConfig`/`suiteCommand`) takes the first + `specs = …` assignment a prewalk of the whole suite finds as the `@perftest_threads` (whose expansion assigns + `specs = ` in a `let`) and `eval`s it in `Launch`. A user assignment `specs = (2, 2)` anywhere in the recipe + before the `@perftest_threads`, or in a recipe without one, therefore sets the arrangement the suite is launched with. +- MPI mode left from a previous transform: in `transformWith` (`src/PerfTest.jl`, the MPI decision), when `MPI.enabled` + is true but `Main.MPI` is not defined, it warns "defaulting to non-MPI mode" but does not reset the global `mode`, + which keeps its previous value. That is `NormalMode` unless something left `MPIMode`: the deprecated `toggleMPI()`, or + `MPItransform`, which toggles back after the transform and so leaves `MPIMode` when the transform set `NormalMode`. + The transform then generates MPI code despite the warning and, without the MPI extension loaded, throws + `MethodError: machineBenchmarks(::Type{MPIMode}, ::Context)` from the prefix. The MPI test of `t14-decisions.jl` + asserts `NormalMode` only because the previous mode was `NormalMode`. +- `MacroParameter` (`datastruct.jl`) has a long stack of positional-argument constructors kept + purely for backward compatibility with existing macro-parameter definitions under + `src/execution/macros/` — prefer the keyword constructor for new code, don't remove the old ones + without checking every macro definition file. + +## Repo hygiene + +- Numerous macOS AppleDouble `._*` files and `.DS_Store` are scattered through `src/`, `test/`, + `ext/`, and the repo root as untracked junk from a filesystem copy — never commit these, and + don't treat them as real source files if they show up in a directory listing. +- `examples/example-llama-energy/` currently contains a large amount of untracked working-directory + cruft (logs, `.ipynb_checkpoints`, a `core` dump, build artifacts) — treat it as scratch, not a + clean reference example. `examples/example-kkt-cholesky-regression/`, `example-quickstart/`, + `example-paper-implicitglobalgrid/`, and `example-paper-pardiso/` are the cleaner reference examples. + +## Common development tasks + +- **Add a new macro parameter type / relax validation** → `src/transform/validation/macro.jl` + (`validateMacro`/`validateBlocklessMacro`) and `src/transform/datastruct.jl` + (`MacroParameter`, `resolveLiteral`, `typeMatches`). Add a fixture recipe in + `test/test-recipes/` + assertions in `test/t2-validation-macro.jl` (unit) and + `test/t3-transforms.jl` (end-to-end). +- **Add a new user-facing macro** → define its `MacroParameter` dict + validation in a new file + under `src/execution/macros/`, add the corresponding `ASTRule` in + `src/transform/parsing/rules.jl`, register it in `first_pass_rules` in `src/PerfTest.jl` + (mind ordering — first match wins), and export it from `src/PerfTest.jl` if user-facing. +- **Add a new methodology** (like regression/roofline) → new file under + `src/transform/methodologies/`, following the `onXDefinition`/`buildX` pattern, wired through + `captureMethodologyInfo`. +- **Add a new built-in metric** → `src/transform/metrics/primitives.jl` + (`buildPrimitiveMetrics!`) for always-computed metrics, or point users at + `@define_metric`/`@auxiliary_metric` (`metrics/custom.jl`) for user-defined ones. +- **Docs**: `docs/src/*.MD` mirrors this file at a more user-facing level (macros.md, + configuration_params.MD, internals.MD documents exact rule-priority ordering, limitations.md). + Update the relevant `docs/src/` page alongside any public-API or config-schema change. diff --git a/Project.toml b/Project.toml index 73702a2..f20a5ef 100644 --- a/Project.toml +++ b/Project.toml @@ -9,6 +9,7 @@ BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" Configurations = "5218b696-f38b-4ac9-8b61-a12ec717816d" CountFlops = "1db9610d-79e1-487a-8d40-77f3295c7593" DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" +DataStructures = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8" Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" HTTP = "cd3eb016-35fb-5094-929b-558a96fad6f3" Hwloc = "0e44f5e4-bd66-52a0-8798-143a42290a1d" @@ -28,13 +29,18 @@ ThreadPinningCore = "6f48bc29-05ce-4cc8-baad-4adcba581a18" UnicodePlots = "b8865327-cd53-5732-bb35-84acbb429228" [weakdeps] +LIKWID = "bf22376a-e803-4184-b2ed-56326e3bff83" MPI = "da04e1cc-30fd-572f-bb4f-1f8673147195" +CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" +AMDGPU = "21141c5a-9bdb-4563-92ae-f87d6854732e" [extensions] +PerfTest_LIKWIDExt = "LIKWID" PerfTest_MPIExt = "MPI" +PerfTest_CUDAExt = "CUDA" +PerfTest_AMDGPUExt = "AMDGPU" [compat] -julia = "1, 1.11" BandwidthBenchmark = "0.2.0" BenchmarkTools = "1" Configurations = "0" @@ -50,3 +56,4 @@ PrecompileTools = "1.2" Suppressor = "0" ThreadPinningCore = "0.4" UnicodePlots = "3" +julia = "1, 1.11" diff --git a/docs/src/configuration_params.MD b/docs/src/configuration_params.MD index 7427f43..c82cf01 100644 --- a/docs/src/configuration_params.MD +++ b/docs/src/configuration_params.MD @@ -2,6 +2,16 @@ This document describes all configuration parameters available. Parameters are organized by section, they are specified in TOML format. +Every transformation starts from the default values below, overridden by the `perftest_config.toml` file in the working directory. If the file does not exist it is created with the default values. The file does not need to define every parameter: missing sections or parameters keep their default value, and a parameter with an incorrect type is reported as an error and keeps its default value as well. A section or parameter that does not exist (e.g. a misspelled one) is reported as an error, naming it along with the existing sections, or the existing parameters of its section, and is ignored while the rest of the file applies. A file that cannot be parsed is reported as an error and left untouched, and the default configuration is used instead. + +The configuration is used when a recipe is transformed, and the generated suite keeps the configuration it was generated with: when it executes, wherever and however that happens, it uses those same values. The only exception is the `[bencher]` section, see below. Values that depend on the machine are fixed at generation as well, but the ones that describe it relatively (e.g. a thread arrangement like `:numa`, or a buffer size of `0`) are resolved on the machine that executes the suite. A `@perftest_config` macro applies from its place in the recipe onwards. In an included recipe (see `recursive`) it applies only to the part of the suite generated from that recipe, the including recipe gets its own configuration back after it. + +The argument of `@perftest_config` must be a string literal, as it is read when the recipe is transformed (a variable or any other expression is reported as a parse error). Its content is checked against the parameters below: invalid TOML, a section or parameter that does not exist (naming the existing ones, as for the file), a parameter with an incorrect type (naming the expected and the given type) and a parameter that is used before the recipe is read (`[MPI]` `enabled`) are reported as parse errors, so the suite is not generated. The rest of its parameters still apply during the transform, so the errors of the rest of the recipe are reported as well. + +The `@perftest_config` string may interpolate values inside TOML strings, e.g. `dedicated_reference_file = 'ref_$(gethostname()).JLD2'`. Those keys take their value when the generated suite executes, during the transform they keep their previous value while the rest of the keys are applied as usual. An interpolated value is therefore always a string, so interpolation can only set parameters that take a `String` (e.g. not `verbose = '$(level)'`), otherwise it is reported as a parse error. Interpolation anywhere else (as a whole value, in a key or in a table name) is reported as a parse error as well. + +The parameters given with the `config` keyword argument of `runperftests` or `PerfTest.transform` take priority over the file, and are checked one by one: one with an incorrect type is reported as an error and ignored, the rest apply. A section or parameter that does not exist is reported as an error as well, naming the existing ones as for the file, and ignored. The same type check happens when a generated suite executes, in case it was generated by a version of PerfTest with different parameters. + --- ## `[general]` @@ -10,15 +20,15 @@ General settings that control the overall behavior of the package. | Parameter | Type | Default | Description | |---|---|---|---| -| `autoflops` | `Bool` | `true` | Whether the autoflop counter is enabled and accessible during testing. | -| `numas` | `String \| Integer \| Float64` | `"single"` | Amount of NUMAS to use when pinning threads. | -| `threads_per_numa` | `String \| Integer \| Float64` | `"single"` | Amount of threads to pin per NUMA. | -| `save_results` | `Bool` | `true` | Whether to record the results of executing the performance suite. | -| `logs_enabled` | `Bool` | `true` | Enable or disable the log subsystem. If false, this will prevent PerfTest from creating a log folder and log files.| -| `save_folder` | `String` | `".perftests"` | Folder where performance suite results shall be stored. | +| `autoflops` | `Bool` | `false` | Deprecated: automatic flop counting is outdated and not supported (the `:autoflop` primitive is always 0). While it is true, a `@roofline` without `actual_flops` is reported as a parse error: give the flop count of the target to `@roofline` with `actual_flops` instead. Setting the key alone is not an error. A formula or a `@regression` metric that uses `:autoflop` is reported as a parse error regardless of this key. | +| `numas` | `String \| Integer \| Float64` | `"single"` | Amount of NUMA domains whose threads the suite uses, along with `threads_per_numa`. Together they are the thread setting of the suite, which `runperftests` launches it with: it sets the number of threads of the process that executes the suite (`--threads`), it does not pin them. A string names a whole arrangement and is given in both keys: `"single"` (1 thread), `"numa"` (every thread of 1 NUMA domain) or `"all"` (every thread of every NUMA domain). Otherwise both are numbers, each one an integer n ≥ 1 or a float in (0, 1], the ratio of the available ones (e.g. `numas = 1` and `threads_per_numa = 0.5` is half of the threads of 1 NUMA domain). Anything else, e.g. two different names or a name along with a number, is reported as an error, naming the reason and where each key comes from: a parse error if a `@perftest_config` sets one of them. The arrangement is resolved on the machine that executes the suite. A suite has a single thread setting: each key takes its value from the last `@perftest_config` that sets it, even when it is in an included recipe, and a `@perftest_threads` in the recipe takes priority over both. | +| `threads_per_numa` | `String \| Integer \| Float64` | `"single"` | Amount of threads to use per NUMA domain, see `numas`. | +| `save_results` | `Bool` | `true` | Whether to record the results of executing the performance suite. If false, an execution writes neither the result file (see `save_folder`) nor the `[regression]` `dedicated_reference_file`, the existing ones are still used as regression reference. | +| `logs_enabled` | `Bool` | `true` | Enable or disable the log subsystem. If false, nothing is logged from where it is set (neither kept in memory nor printed by `verbose`), and no log folder nor log file is written: the transform saves its logs (see `verbose`) only if it is true in the configuration in force at the end of the recipe. The generated suite writes no log file. | +| `save_folder` | `String` | `".perftests"` | Folder where performance suite results shall be stored, the suite creates it when it saves its results. | | `max_saved_results` | `Int` | `20` | Maximum amount of performance test suite execution results to be saved in the result file for each suite. | | `plotting` | `Bool` | `true` | Whether to have plots in the test output of methodologies that support it. | -| `verbose` | `Int` | `0` | Whether to output the collected logs in the standard output. | +| `verbose` | `Int` | `0` | Whether to output the collected logs in the standard output. From 2 on, the logs of the transform are saved in the `.perftest_logs` folder, as decided by the value in force at the end of the recipe (e.g. a `@perftest_config` of the recipe that sets it). | | `recursive` | `Bool` | `true` | If enabled, whenever a file is included inside a recipe that is being transformed, it will be transformed as well. | | `safe_formulas` | `Bool` | `false` | Deprecated. | | `suppress_output` | `Bool` | `true` | Whether to hide the output of the test targets. If false the output of each execution will be shown, which will be probably a long output. | @@ -33,7 +43,7 @@ Settings for regression testing. |---|---|---|---| | `enabled` | `Bool` | `true` | Whether to use regression testing in this suite. | | `dedicated_reference_file` | `String` | `""` | If not an empty string, a succesful suite execution will be saved into this file, as well as in the (result file see `[general] save_folder`). The last saved execution will be used as reference for regression testing. If empty the package will look at the result file instead, and find the latest sucessful execution as reference. | -| `default_threshold` | `Number` | `1.1` | The default threshold of the `@regression` macro if no threshold is specified. | +| `default_threshold` | `Number` | `1.1` | The threshold of a `@regression` that gives none, and of the regression every top level testset gets. A metric with `low_is_bad = false` (e.g. a time, the default regression) takes this value, its ratio new/reference must stay below it. A metric with `low_is_bad = true` (the default of `@regression`, e.g. a throughput) takes 2 − this value, its ratio must stay above it: 1.1 tolerates a time up to 10% higher and a throughput up to 10% lower (0.9). A value of 2 or more leaves no threshold for a metric with `low_is_bad = true`, such a `@regression` is reported as a parse error, give it an explicit threshold. | | `use_bencher` | `Bool` | `false` | Whether to enable Bencher to upload results to an online CI/CD performance benchmark platform. THIS FEATURE IS EXPERIMENTAL and likely unstable. | --- @@ -76,7 +86,7 @@ Settings for benchmarking the underlying machine. | Parameter | Type | Default | Description | |---|---|---|---| -| `memory_bandwidth_test_buffer_size` | `Int` | `0` | If 0 a buffer size for bandwith benchmarks is used so its at least 4 times bigger than the biggest cache level of the machine. If non-zero this value is used to set the buffer size instead. | +| `memory_bandwidth_test_buffer_size` | `Int` | `0` | If 0 a buffer size for bandwith benchmarks is used so its at least 4 times bigger than the biggest cache level of the machine that executes the suite. If non-zero this value is used to set the buffer size instead. | --- @@ -86,7 +96,7 @@ Settings for MPI-based execution. | Parameter | Type | Default | Description | |---|---|---|---| -| `enabled` | `Bool` | `false` | Whether to enable the MPI aware performance suite generation, this will mainly make sure tests are measured in all ranks but evaluated on the main rank only, and that machine benchmarks take into account all ranks.| +| `enabled` | `Bool` | `false` | Whether to enable the MPI aware performance suite generation, this will mainly make sure tests are measured in all ranks but evaluated on the main rank only, and that machine benchmarks take into account all ranks. The MPI mode is decided before the recipe is read, so it can only be set in the `perftest_config.toml` file or with the `config` argument of `runperftests` or `PerfTest.transform`, a `@perftest_config` that sets it is reported as a parse error.| | `mode` | `String` | `"reduce"` | This has no function as of now, but it will be used in future versions of perftest. | --- @@ -95,6 +105,8 @@ Settings for MPI-based execution. Settings for [Bencher](https://bencher.dev) integration. This feature is experimental, and likely prone to bugs. +Unlike the rest of the configuration, this section is read when the suite executes, from the `perftest_config.toml` file of the working directory (the default values are used if there is none), so the credentials are never written into a generated suite. A `@perftest_config` in the recipe that sets these keys takes priority over the file, but its values are written into the suite: interpolate secrets to keep them out of it, e.g. `api_key = '$(ENV["BENCHER_API_KEY"])'`. + | Parameter | Type | Default | Description | |---|---|---|---| | `api_key` | `String` | `""` | The Bencher platform key to use to connect to bencher. | diff --git a/docs/src/limitations.md b/docs/src/limitations.md index 257d947..bdd42d8 100644 --- a/docs/src/limitations.md +++ b/docs/src/limitations.md @@ -4,6 +4,7 @@ There are a couple of things to keep into consideration when using the package: 1. GPU testing is technically supported, but it requires more effort from the developer to set up since the automatic measurements apart from time elapsed do not apply to GPUs (as of now). 2. The automatic flop counting feature works exclusively for Julia native functions, it can not measure the flops in C calls given the limitations of the subjacent package [CountFlops.jl] +3. LIKWID and GPU (CUDA/AMDGPU) energy/power measurements are repeated to match the actual number of samples `BenchmarkTools` took for the same test (median-aggregated, with the spread preserved as a standard-error-of-the-mean interval when `showvar=true` and at least 30 samples were taken — see `@regression`/`@perfcompare`'s `showvar` argument), so their cost scales with whatever `samples=`/`seconds=`/`evals=` the test uses — tune those explicitly on tests using these extensions if you don't want extension sampling to inherit `BenchmarkTools`' adaptive defaults. ## Features to be expected in the next versions: diff --git a/docs/src/usage.MD b/docs/src/usage.MD index fd35468..a619ee2 100644 --- a/docs/src/usage.MD +++ b/docs/src/usage.MD @@ -15,8 +15,8 @@ using ExampleModule : innerProduct, Test, PerfTest # Importing the target and @testset "Roofline Test" begin a,b = rand(1e6),rand(1e6) - @roofline actual_flops=:autoflop target_ratio=0.5 - :autoflop / (2 * 8 * 1e6) + @roofline actual_flops=2e6 target_ratio=0.5 begin + 2e6 / (2 * 8 * 1e6) end @perftest innerProduct(a, b) @@ -27,7 +27,7 @@ end The following things can be appreciated in this example: 1. This is a combined functional and performance unit test suite (there is both @test and @perftest present) 2. The target of the perftest is the innerProduct function -3. The performance test methodology is a roofline model, the developer expects innerProduct to perform at least at 50% of the maximum flop performance set by the roofline. The operational intensity is defined on the main block of the macro. :autoflop is a symbol that enables the use of an automatic flop count feature. +3. The performance test methodology is a roofline model, the developer expects innerProduct to perform at least at 50% of the maximum flop performance set by the roofline. The operational intensity is defined on the main block of the macro, and `actual_flops` gives the flop count of the target (2 flops per element of the vectors), from which the attained flops are computed. Automatic flop counting (`:autoflop`) is outdated and not supported, so the flop count is always given explicitly. ## How to use, a first PerfTest.jl recipe diff --git a/examples/example-kkt-cholesky-regression/KktCholesky.jl b/examples/example-kkt-cholesky-regression/KktCholesky.jl new file mode 100644 index 0000000..24232b4 --- /dev/null +++ b/examples/example-kkt-cholesky-regression/KktCholesky.jl @@ -0,0 +1,121 @@ +module KktCholesky + +using LinearAlgebra +using Random + +export build_kkt_system, cholesky_factor_fast!, cholesky_factor_regressed!, + forward_substitution!, back_substitution!, solve_kkt, relative_residual + +# Synthetic SPD "condensed KKT" system K = AᵀA + σI, b -- representative of +# the normal-equations/Newton system solved every iteration of a QP/SOCP +# interior-point method (Clarabel.jl, OSQP, ECOS, ...). A is m×n with m0, making K strictly positive definite regardless of rank. +function build_kkt_system(n::Int, m::Int; seed::Int=1, sigma::Float64=1e-2) + rng = MersenneTwister(seed) + A = randn(rng, m, n) + K = Matrix(Symmetric(A' * A)) + @inbounds for i in 1:n + K[i, i] += sigma + end + b = randn(rng, n) + return K, b +end + +# Unblocked right-looking Cholesky (K = L*Lᵀ), "kji" loop order: for each +# pivot k, the trailing-submatrix rank-1 update loops columns j (outer) then +# rows i (inner), so the innermost loop walks straight down a column of L -- +# contiguous in Julia's column-major storage. This is the textbook loop +# order for column-major languages (Julia, Fortran, MATLAB, R). +function cholesky_factor_fast!(L::Matrix{Float64}, K::Matrix{Float64}) + n = size(K, 1) + copyto!(L, K) + @inbounds for k in 1:n + L[k, k] = sqrt(L[k, k]) + invLkk = 1.0 / L[k, k] + for i in (k+1):n + L[i, k] *= invLkk + end + for j in (k+1):n + ljk = L[j, k] + @simd for i in j:n + L[i, j] -= L[i, k] * ljk + end + end + end + @inbounds for j in 1:n, i in 1:(j-1) + L[i, j] = 0.0 + end + return L +end + +# THE REGRESSION. Same algorithm, same operations, same floating-point +# results as `cholesky_factor_fast!` (bit-for-bit identical L, see README) -- +# only the trailing-submatrix loop nest is transposed to "kij" order: rows i +# outer, columns j inner. `L[i, j]` for fixed i is now walked across a *row*, +# i.e. striding n elements through memory instead of 1. This is the kind of +# one-line-diff bug that shows up when porting/refactoring from a row-major +# reference (C, NumPy) without adjusting loop order for Julia's layout: no +# functional test can ever catch it (@simd is still there, the answer is +# still exactly right), only a performance-regression suite can. +function cholesky_factor_regressed!(L::Matrix{Float64}, K::Matrix{Float64}) + n = size(K, 1) + copyto!(L, K) + @inbounds for k in 1:n + L[k, k] = sqrt(L[k, k]) + invLkk = 1.0 / L[k, k] + for i in (k+1):n + L[i, k] *= invLkk + end + for i in (k+1):n + lik = L[i, k] + @simd for j in (k+1):i + L[i, j] -= lik * L[j, k] + end + end + end + @inbounds for j in 1:n, i in 1:(j-1) + L[i, j] = 0.0 + end + return L +end + +function forward_substitution!(z::Vector{Float64}, L::Matrix{Float64}, b::Vector{Float64}) + n = length(b) + @inbounds for i in 1:n + s = b[i] + @simd for k in 1:(i-1) + s -= L[i, k] * z[k] + end + z[i] = s / L[i, i] + end + return z +end + +# Solves Lᵀx = z; Lᵀ[i, k] = L[k, i]. +function back_substitution!(x::Vector{Float64}, L::Matrix{Float64}, z::Vector{Float64}) + n = length(z) + @inbounds for i in n:-1:1 + s = z[i] + @simd for k in (i+1):n + s -= L[k, i] * x[k] + end + x[i] = s / L[i, i] + end + return x +end + +function solve_kkt(K::Matrix{Float64}, b::Vector{Float64}, fast::Bool=true) + n = size(K, 1) + L = Matrix{Float64}(undef, n, n) + fast ? cholesky_factor_fast!(L, K) : cholesky_factor_regressed!(L, K) + z = Vector{Float64}(undef, n) + x = Vector{Float64}(undef, n) + forward_substitution!(z, L, b) + back_substitution!(x, L, z) + return x +end + +relative_residual(K, b, x) = norm(K * x - b) / norm(b) + +end # module diff --git a/examples/example-kkt-cholesky-regression/KktLDLT.jl b/examples/example-kkt-cholesky-regression/KktLDLT.jl new file mode 100644 index 0000000..8dd4796 --- /dev/null +++ b/examples/example-kkt-cholesky-regression/KktLDLT.jl @@ -0,0 +1,81 @@ +module KktLDLT + +export ldlt_factor_regressed!, ldlt_solve! + +# THE REGRESSION: a naive, hand-rolled dense LDLᵀ (K = L*D*Lᵀ, L unit lower +# triangular, D diagonal with signed entries), generalized from +# KktCholesky.jl to the *indefinite* systems real interior-point solvers +# actually factor (a KKT/Newton matrix has a mixed-sign diagonal; it is not +# SPD, so plain Cholesky's `sqrt` doesn't apply). Standing in for "someone +# replaced the specialized sparse solver backend with a naive dense one" -- +# see clarabel_perftest.jl, where `USE_FAST_FACTORIZATION = true` instead +# calls Clarabel's own real QDLDL backend directly, and only `false` routes +# through this kernel. +# +# K only needs to be *quasi-definite* (not necessarily SPD) for this to be +# numerically safe without pivoting: quasi-definite matrices admit an LDLᵀ +# factorization under *any* symmetric row/column permutation, including the +# identity, which is exactly the structural property that lets solvers like +# Clarabel.jl, OSQP, and QDLDL skip pivoting altogether. +# +# The trailing-submatrix update is embarrassingly parallel across rows: for +# fixed k, each iteration of `i` reads column k of L (already finalized this +# step) and writes only row i of L, so distinct `i`s touch disjoint memory -- +# safe to hand to `Threads.@threads` with no synchronization. It still walks +# `L[i, j]` across a row (stride n, "kij" order) rather than down a column +# (stride 1, "kji" order), so per-core throughput remains the cache-unfriendly +# one from the original regression; threading only adds cores, it doesn't fix +# the access pattern. +function ldlt_factor_regressed!(L::Matrix{Float64}, D::Vector{Float64}, K::Matrix{Float64}) + n = size(K, 1) + copyto!(L, K) + @inbounds for k in 1:n + D[k] = L[k, k] + invDk = 1.0 / D[k] + for i in (k+1):n + L[i, k] *= invDk + end + Dk = D[k] + Threads.@threads for i in (k+1):n + @inbounds begin + lik_Dk = L[i, k] * Dk + @simd for j in (k+1):i + L[i, j] -= lik_Dk * L[j, k] + end + end + end + end + @inbounds for k in 1:n + L[k, k] = 1.0 + for i in 1:(k-1) + L[i, k] = 0.0 + end + end + return L, D +end + +# Solves K x = b given K = L*D*Lᵀ, in place into x. +function ldlt_solve!(x::Vector{Float64}, L::Matrix{Float64}, D::Vector{Float64}, b::Vector{Float64}) + n = length(b) + z = similar(b) + @inbounds for i in 1:n + s = b[i] + @simd for k in 1:(i-1) + s -= L[i, k] * z[k] + end + z[i] = s + end + @inbounds for i in 1:n + z[i] /= D[i] + end + @inbounds for i in n:-1:1 + s = z[i] + @simd for k in (i+1):n + s -= L[k, i] * x[k] + end + x[i] = s + end + return x +end + +end # module diff --git a/examples/example-kkt-cholesky-regression/Manifest.toml b/examples/example-kkt-cholesky-regression/Manifest.toml new file mode 100644 index 0000000..292f2fd --- /dev/null +++ b/examples/example-kkt-cholesky-regression/Manifest.toml @@ -0,0 +1,924 @@ +# This file is machine-generated - editing it directly is not advised + +julia_version = "1.10.10" +manifest_format = "2.0" +project_hash = "b6ca99cf3358da36d85840cb62ef13074d9b5bfd" + +[[deps.AMD]] +deps = ["LinearAlgebra", "SparseArrays", "SuiteSparse_jll"] +git-tree-sha1 = "344f3d221a6bee75925b5c97a30cfd870f12a138" +uuid = "14f7f29c-3bd6-536c-9a0b-7339e30b5a3e" +version = "0.5.4" + +[[deps.AliasTables]] +deps = ["PtrArrays", "Random"] +git-tree-sha1 = "9876e1e164b144ca45e9e3198d0b689cadfed9ff" +uuid = "66dad0bd-aa9a-41b7-9441-69ab47430ed8" +version = "1.1.3" + +[[deps.ArgTools]] +uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" +version = "1.1.1" + +[[deps.Artifacts]] +uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" + +[[deps.BandwidthBenchmark]] +deps = ["DataFrames", "PrettyTables", "Printf", "Requires", "Statistics", "ThreadPinning"] +git-tree-sha1 = "6b0c18db2cdb386e332cedac2f9fcaf85ab757d2" +uuid = "68eb07c1-04fd-4e62-9736-d6127c4c03c6" +version = "0.2.0" + +[[deps.Base64]] +uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" + +[[deps.BenchmarkTools]] +deps = ["Compat", "JSON", "Logging", "PrecompileTools", "Printf", "Profile", "Statistics", "UUIDs"] +git-tree-sha1 = "9670d3febc2b6da60a0ae57846ba74670290653f" +uuid = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" +version = "1.8.0" + +[[deps.BitFlags]] +git-tree-sha1 = "bbe1079eecf9c9fbb52765193ad2bae27ae09bc8" +uuid = "d1d4a3ce-64b1-5f1a-9ba4-7e7e69966f35" +version = "0.1.10" + +[[deps.Bzip2_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "1b96ea4a01afe0ea4090c5c8039690672dd13f2e" +uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0" +version = "1.0.9+0" + +[[deps.CEnum]] +git-tree-sha1 = "389ad5c84de1ae7cf0e28e381131c98ea87d54fc" +uuid = "fa961155-64e5-5f13-b03f-caf6b980ea82" +version = "0.5.0" + +[[deps.Cassette]] +git-tree-sha1 = "f8764df8d9d2aec2812f009a1ac39e46c33354b8" +uuid = "7057c7e9-c182-5462-911a-8362d720325c" +version = "0.3.14" + +[[deps.ChunkCodecCore]] +git-tree-sha1 = "3496e2b359c27793d12bec54ec94be7983a6ceb2" +uuid = "0b6fb165-00bc-4d37-ab8b-79f91016dbe1" +version = "1.0.2" + +[[deps.ChunkCodecLibZlib]] +deps = ["ChunkCodecCore", "Zlib_jll"] +git-tree-sha1 = "d4101e848e8d3f585d61d244c2fe0c80a70e6b3b" +uuid = "4c0bbee4-addc-4d73-81a0-b6caacae83c8" +version = "1.1.0" + +[[deps.ChunkCodecLibZstd]] +deps = ["ChunkCodecCore", "Zstd_jll"] +git-tree-sha1 = "34d9873079e4cb3d0c62926a225136824677073f" +uuid = "55437552-ac27-4d47-9aa3-63184e8fd398" +version = "1.0.0" + +[[deps.Clarabel]] +deps = ["AMD", "DataStructures", "GenericLinearAlgebra", "JSON", "LinearAlgebra", "MathOptInterface", "Printf", "QDLDL", "SnoopPrecompile", "SparseArrays", "StaticArrays", "SuiteSparse", "TOML", "TimerOutputs"] +git-tree-sha1 = "9f5dcd866a1cee6fb2e853db82286e4cdf06c622" +uuid = "61c947e1-3e6d-4ee4-985a-eec8c727bd6e" +version = "0.11.1" + + [deps.Clarabel.extensions] + HSLExt = "HSL" + PardisoExt = "Pardiso" + + [deps.Clarabel.weakdeps] + HSL = "34c5aeac-e683-54a6-a0e9-6e0fdc586c50" + Pardiso = "46dd5b70-b6fb-5a00-ae2d-e8fea33afaf2" + +[[deps.CodecBzip2]] +deps = ["Bzip2_jll", "TranscodingStreams"] +git-tree-sha1 = "84990fa864b7f2b4901901ca12736e45ee79068c" +uuid = "523fee87-0ab8-5b00-afb7-3ecf72e48cfd" +version = "0.8.5" + +[[deps.CodecZlib]] +deps = ["TranscodingStreams", "Zlib_jll"] +git-tree-sha1 = "970758a3d591a2a5c2a907c53f2e2f8c1b1d3537" +uuid = "944b1d66-785c-5afd-91f1-9de20f533193" +version = "0.7.9" + +[[deps.ColorSchemes]] +deps = ["ColorTypes", "ColorVectorSpace", "Colors", "FixedPointNumbers", "PrecompileTools", "Random"] +git-tree-sha1 = "b0fd3f56fa442f81e0a47815c92245acfaaa4e34" +uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4" +version = "3.31.0" + +[[deps.ColorTypes]] +deps = ["FixedPointNumbers", "Random"] +git-tree-sha1 = "67e11ee83a43eb71ddc950302c53bf33f0690dfe" +uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f" +version = "0.12.1" + + [deps.ColorTypes.extensions] + StyledStringsExt = "StyledStrings" + + [deps.ColorTypes.weakdeps] + StyledStrings = "f489334b-da3d-4c2e-b8f0-e476e12c162b" + +[[deps.ColorVectorSpace]] +deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "Requires", "Statistics", "TensorCore"] +git-tree-sha1 = "8b3b6f87ce8f65a2b4f857528fd8d70086cd72b1" +uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4" +version = "0.11.0" +weakdeps = ["SpecialFunctions"] + + [deps.ColorVectorSpace.extensions] + SpecialFunctionsExt = "SpecialFunctions" + +[[deps.Colors]] +deps = ["ColorTypes", "FixedPointNumbers", "Reexport"] +git-tree-sha1 = "37ea44092930b1811e666c3bc38065d7d87fcc74" +uuid = "5ae59095-9a9b-59fe-a467-6f913c188581" +version = "0.13.1" + +[[deps.CommonSubexpressions]] +deps = ["MacroTools"] +git-tree-sha1 = "cda2cfaebb4be89c9084adaca7dd7333369715c5" +uuid = "bbf7d656-a473-5ed7-a52c-81e309532950" +version = "0.3.1" + +[[deps.Compat]] +deps = ["TOML", "UUIDs"] +git-tree-sha1 = "9d8a54ce4b17aa5bdce0ea5c34bc5e7c340d16ad" +uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" +version = "4.18.1" +weakdeps = ["Dates", "LinearAlgebra"] + + [deps.Compat.extensions] + CompatLinearAlgebraExt = "LinearAlgebra" + +[[deps.CompilerSupportLibraries_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae" +version = "1.1.1+0" + +[[deps.ConcurrentUtilities]] +deps = ["Serialization", "Sockets"] +git-tree-sha1 = "3c9be947934c38475bafe822c6d61aaed17f0738" +uuid = "f0e56b4a-5159-44fe-b623-3e5288b988bb" +version = "2.6.0" + +[[deps.Configurations]] +deps = ["ExproniconLite", "OrderedCollections", "TOML"] +git-tree-sha1 = "4358750bb58a3caefd5f37a4a0c5bfdbbf075252" +uuid = "5218b696-f38b-4ac9-8b61-a12ec717816d" +version = "0.17.6" + +[[deps.Contour]] +git-tree-sha1 = "439e35b0b36e2e5881738abc8857bd92ad6ff9a8" +uuid = "d38c429a-6771-53c6-b99e-75d170b6e991" +version = "0.6.3" + +[[deps.CountFlops]] +deps = ["Cassette"] +git-tree-sha1 = "3d4b4b334a3a78d1339e4ab2878c688233a469aa" +uuid = "1db9610d-79e1-487a-8d40-77f3295c7593" +version = "0.1.0" + +[[deps.Crayons]] +git-tree-sha1 = "54b76cbb40d9a0f5368c880725b2f141da77c94f" +uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f" +version = "4.2.0" + +[[deps.DataAPI]] +git-tree-sha1 = "abe83f3a2f1b857aac70ef8b269080af17764bbe" +uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a" +version = "1.16.0" + +[[deps.DataFrames]] +deps = ["Compat", "DataAPI", "DataStructures", "Future", "InlineStrings", "InvertedIndices", "IteratorInterfaceExtensions", "LinearAlgebra", "Markdown", "Missings", "PooledArrays", "PrecompileTools", "PrettyTables", "Printf", "Random", "Reexport", "SentinelArrays", "SortingAlgorithms", "Statistics", "TableTraits", "Tables", "Unicode"] +git-tree-sha1 = "5fab31e2e01e70ad66e3e24c968c264d1cf166d6" +uuid = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" +version = "1.8.2" + +[[deps.DataStructures]] +deps = ["OrderedCollections"] +git-tree-sha1 = "b0bc6d2cad1fed8b7fd59a1551a991cb3d2809e6" +uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8" +version = "0.19.6" + +[[deps.DataValueInterfaces]] +git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6" +uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464" +version = "1.0.0" + +[[deps.Dates]] +deps = ["Printf"] +uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" + +[[deps.DelimitedFiles]] +deps = ["Mmap"] +git-tree-sha1 = "9e2f36d3c96a820c678f2f1f1782582fcf685bae" +uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab" +version = "1.9.1" + +[[deps.DiffResults]] +deps = ["StaticArraysCore"] +git-tree-sha1 = "782dd5f4561f5d267313f23853baaaa4c52ea621" +uuid = "163ba53b-c6d8-5494-b064-1a9d43ac40c5" +version = "1.1.0" + +[[deps.DiffRules]] +deps = ["IrrationalConstants", "LogExpFunctions", "NaNMath", "Random", "SpecialFunctions"] +git-tree-sha1 = "79a2aca180a85c690c58a020d47b426954b590f8" +uuid = "b552c78f-8df3-52c6-915a-8e097449b14b" +version = "1.16.0" + +[[deps.DocStringExtensions]] +git-tree-sha1 = "7442a5dfe1ebb773c29cc2962a8980f47221d76c" +uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" +version = "0.9.5" + +[[deps.Downloads]] +deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"] +uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" +version = "1.6.0" + +[[deps.ExceptionUnwrapping]] +deps = ["Test"] +git-tree-sha1 = "d36f682e590a83d63d1c7dbd287573764682d12a" +uuid = "460bff9d-24e4-43bc-9d9f-a8973cb893f4" +version = "0.1.11" + +[[deps.ExprTools]] +git-tree-sha1 = "d2e49e7efd29719d6f28b891b0e0e159daa9d2b4" +uuid = "e2ba6199-217a-4e67-a87a-7c52f15ade04" +version = "0.1.11" + +[[deps.ExproniconLite]] +git-tree-sha1 = "c13f0b150373771b0fdc1713c97860f8df12e6c2" +uuid = "55351af7-c7e9-48d6-89ff-24e801d99491" +version = "0.10.14" + +[[deps.FileIO]] +deps = ["Pkg", "Requires", "UUIDs"] +git-tree-sha1 = "6621fef488e496356c9c9625d0562c12a6070819" +uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549" +version = "1.20.0" +weakdeps = ["HTTP"] + + [deps.FileIO.extensions] + HTTPExt = "HTTP" + +[[deps.FileWatching]] +uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" + +[[deps.FixedPointNumbers]] +deps = ["Random", "Statistics"] +git-tree-sha1 = "59af96b98217c6ef4ae0dfe065ac7c20831d1a84" +uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93" +version = "0.8.6" + +[[deps.ForwardDiff]] +deps = ["CommonSubexpressions", "DiffResults", "DiffRules", "LinearAlgebra", "LogExpFunctions", "NaNMath", "Preferences", "Printf", "Random", "SpecialFunctions"] +git-tree-sha1 = "3b0f72e2ffef1a139ac450725c9ecd01c0a3c050" +uuid = "f6369f11-7733-5829-9624-2563aa707210" +version = "1.4.6" +weakdeps = ["StaticArrays"] + + [deps.ForwardDiff.extensions] + ForwardDiffStaticArraysExt = "StaticArrays" + +[[deps.Future]] +deps = ["Random"] +uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820" + +[[deps.GenericLinearAlgebra]] +deps = ["LinearAlgebra", "Printf", "Random", "libblastrampoline_jll"] +git-tree-sha1 = "fc6236b7fbc40bc283e0dc5a84ead1169a6d7dda" +uuid = "14197337-ba66-59df-a3e3-ca00e7dcff7a" +version = "0.3.19" + +[[deps.HTTP]] +deps = ["Base64", "CodecZlib", "ConcurrentUtilities", "Dates", "ExceptionUnwrapping", "Logging", "LoggingExtras", "MbedTLS", "NetworkOptions", "OpenSSL", "PrecompileTools", "Random", "SimpleBufferStream", "Sockets", "URIs", "UUIDs"] +git-tree-sha1 = "51059d23c8bb67911a2e6fd5130229113735fc7e" +uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3" +version = "1.11.0" + +[[deps.HashArrayMappedTries]] +git-tree-sha1 = "2eaa69a7cab70a52b9687c8bf950a5a93ec895ae" +uuid = "076d061b-32b6-4027-95e0-9a2c6f6d7e74" +version = "0.2.0" + +[[deps.Hwloc]] +deps = ["CEnum", "Hwloc_jll", "Printf"] +git-tree-sha1 = "6a3d80f31ff87bc94ab22a7b8ec2f263f9a6a583" +uuid = "0e44f5e4-bd66-52a0-8798-143a42290a1d" +version = "3.3.0" + + [deps.Hwloc.extensions] + HwlocTrees = "AbstractTrees" + + [deps.Hwloc.weakdeps] + AbstractTrees = "1520ce14-60c1-5f80-bbc7-55ef81b5835c" + +[[deps.Hwloc_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "XML2_jll", "Xorg_libpciaccess_jll"] +git-tree-sha1 = "c35847ca5b4997fc8418836354a56c459bcf48d8" +uuid = "e33a78d0-f292-5ffc-b300-72abe9b543c8" +version = "2.14.0+0" + +[[deps.InlineStrings]] +git-tree-sha1 = "06b65886c7577a3784d616e29f1302c2e36e389d" +uuid = "842dd82b-1e85-43dc-bf29-5d0ee9dffc48" +version = "1.4.6" + + [deps.InlineStrings.extensions] + ArrowTypesExt = "ArrowTypes" + ParsersExt = "Parsers" + + [deps.InlineStrings.weakdeps] + ArrowTypes = "31f734f8-188a-4ce0-8406-c8a06bd891cd" + Parsers = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" + +[[deps.InteractiveUtils]] +deps = ["Markdown"] +uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" + +[[deps.InvertedIndices]] +git-tree-sha1 = "6da3c4316095de0f5ee2ebd875df8721e7e0bdbe" +uuid = "41ab1584-1d38-5bbf-9106-f11c6c58b48f" +version = "1.3.1" + +[[deps.IrrationalConstants]] +git-tree-sha1 = "b2d91fe939cae05960e760110b328288867b5758" +uuid = "92d709cd-6900-40b7-9082-c6be49f344b6" +version = "0.2.6" + +[[deps.IteratorInterfaceExtensions]] +git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856" +uuid = "82899510-4779-5014-852e-03e436cf321d" +version = "1.0.0" + +[[deps.JLD2]] +deps = ["ChunkCodecLibZlib", "ChunkCodecLibZstd", "FileIO", "MacroTools", "Mmap", "OrderedCollections", "PrecompileTools", "ScopedValues"] +git-tree-sha1 = "877edc1d2f51adcef0bfacd19464a19e7cfddddb" +uuid = "033835bb-8acc-5ee8-8aae-3f567f8a3819" +version = "0.6.6" + + [deps.JLD2.extensions] + UnPackExt = "UnPack" + + [deps.JLD2.weakdeps] + UnPack = "3a884ed6-31ef-47d7-9d2a-63182c4928ed" + +[[deps.JLLWrappers]] +deps = ["Artifacts", "Preferences"] +git-tree-sha1 = "7204148362dafe5fe6a273f855b8ccbe4df8173e" +uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210" +version = "1.8.0" + +[[deps.JSON]] +deps = ["Dates", "Mmap", "Parsers", "Unicode"] +git-tree-sha1 = "31e996f0a15c7b280ba9f76636b3ff9e2ae58c9a" +uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" +version = "0.21.4" + +[[deps.LIKWID]] +deps = ["CEnum", "Libdl", "OrderedCollections", "PrettyTables", "Unitful"] +git-tree-sha1 = "b21dcbf20aca355bd2e1039d9731dd1d879cc0d4" +uuid = "bf22376a-e803-4184-b2ed-56326e3bff83" +version = "0.4.5" + +[[deps.LaTeXStrings]] +git-tree-sha1 = "f88f3ccef05a6a72a0cf0ed417c8fd68530f4ab2" +uuid = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f" +version = "1.4.1" + +[[deps.LibCURL]] +deps = ["LibCURL_jll", "MozillaCACerts_jll"] +uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" +version = "0.6.4" + +[[deps.LibCURL_jll]] +deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"] +uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" +version = "8.4.0+0" + +[[deps.LibGit2]] +deps = ["Base64", "LibGit2_jll", "NetworkOptions", "Printf", "SHA"] +uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" + +[[deps.LibGit2_jll]] +deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll"] +uuid = "e37daf67-58a4-590a-8e99-b0245dd2ffc5" +version = "1.6.4+0" + +[[deps.LibSSH2_jll]] +deps = ["Artifacts", "Libdl", "MbedTLS_jll"] +uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" +version = "1.11.0+1" + +[[deps.Libdl]] +uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" + +[[deps.Libiconv_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "be484f5c92fad0bd8acfef35fe017900b0b73809" +uuid = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531" +version = "1.18.0+0" + +[[deps.LinearAlgebra]] +deps = ["Libdl", "OpenBLAS_jll", "libblastrampoline_jll"] +uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" + +[[deps.LogExpFunctions]] +deps = ["DocStringExtensions", "IrrationalConstants", "LinearAlgebra"] +git-tree-sha1 = "bba2d9aa057d8f126415de240573e86a8f39d2a1" +uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688" +version = "1.0.1" + + [deps.LogExpFunctions.extensions] + LogExpFunctionsChainRulesCoreExt = "ChainRulesCore" + LogExpFunctionsChangesOfVariablesExt = "ChangesOfVariables" + LogExpFunctionsInverseFunctionsExt = "InverseFunctions" + + [deps.LogExpFunctions.weakdeps] + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + ChangesOfVariables = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0" + InverseFunctions = "3587e190-3f89-42d0-90ee-14403ec27112" + +[[deps.Logging]] +uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" + +[[deps.LoggingExtras]] +deps = ["Dates", "Logging"] +git-tree-sha1 = "f00544d95982ea270145636c181ceda21c4e2575" +uuid = "e6f89c97-d47a-5376-807f-9c37f3926c36" +version = "1.2.0" + +[[deps.MLStyle]] +git-tree-sha1 = "bc38dff0548128765760c79eb7388a4b37fae2c8" +uuid = "d8e11817-5142-5d16-987a-aa16d5891078" +version = "0.4.17" + +[[deps.MacroTools]] +git-tree-sha1 = "1e0228a030642014fe5cfe68c2c0a818f9e3f522" +uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09" +version = "0.5.16" + +[[deps.MarchingCubes]] +deps = ["PrecompileTools", "StaticArrays"] +git-tree-sha1 = "0e893025924b6becbae4109f8020ac0e12674b01" +uuid = "299715c1-40a9-479a-aaf9-4a633d36f717" +version = "0.1.11" + +[[deps.Markdown]] +deps = ["Base64"] +uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" + +[[deps.MathOptInterface]] +deps = ["CodecBzip2", "CodecZlib", "ForwardDiff", "JSON", "LinearAlgebra", "MutableArithmetics", "NaNMath", "OrderedCollections", "PrecompileTools", "Printf", "SparseArrays", "SpecialFunctions", "Test"] +git-tree-sha1 = "d10ba577e0b5a0481fab01dfd31fb20af3326954" +uuid = "b8f27783-ece8-5eb3-8dc8-9495eed66fee" +version = "1.53.0" + + [deps.MathOptInterface.extensions] + MathOptInterfaceBenchmarkToolsExt = "BenchmarkTools" + MathOptInterfaceCliqueTreesExt = "CliqueTrees" + + [deps.MathOptInterface.weakdeps] + BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" + CliqueTrees = "60701a23-6482-424a-84db-faee86b9b1f8" + +[[deps.MbedTLS]] +deps = ["Dates", "MbedTLS_jll", "MozillaCACerts_jll", "NetworkOptions", "Random", "Sockets"] +git-tree-sha1 = "8785729fa736197687541f7053f6d8ab7fc44f92" +uuid = "739be429-bea8-5141-9913-cc70e7f3736d" +version = "1.1.10" + +[[deps.MbedTLS_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1" +version = "2.28.2+1" + +[[deps.Missings]] +deps = ["DataAPI"] +git-tree-sha1 = "ec4f7fbeab05d7747bdf98eb74d130a2a2ed298d" +uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28" +version = "1.2.0" + +[[deps.Mmap]] +uuid = "a63ad114-7e13-5084-954f-fe012c677804" + +[[deps.MozillaCACerts_jll]] +uuid = "14a3606d-f60d-562e-9121-12d972cd8159" +version = "2023.1.10" + +[[deps.MutableArithmetics]] +deps = ["LinearAlgebra", "SparseArrays", "Test"] +git-tree-sha1 = "dc5b2c4c111c46bc79ac4405eeb563523b39c004" +uuid = "d8a4904e-b15c-11e9-3269-09a3773c0cb0" +version = "1.8.0" + +[[deps.NaNMath]] +deps = ["OpenLibm_jll"] +git-tree-sha1 = "dbd2e8cd2c1c27f0b584f6661b4309609c5a685e" +uuid = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3" +version = "1.1.4" + +[[deps.NetworkOptions]] +uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" +version = "1.2.0" + +[[deps.OpenBLAS_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"] +uuid = "4536629a-c528-5b80-bd46-f80d51c5b363" +version = "0.3.23+4" + +[[deps.OpenLibm_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "05823500-19ac-5b8b-9628-191a04bc5112" +version = "0.8.5+0" + +[[deps.OpenSSL]] +deps = ["BitFlags", "Dates", "MozillaCACerts_jll", "NetworkOptions", "OpenSSL_jll", "Sockets"] +git-tree-sha1 = "1d1aaa7d449b58415f97d2839c318b70ffb525a0" +uuid = "4d8831e6-92b7-49fb-bdf8-b643e874388c" +version = "1.6.1" + +[[deps.OpenSSL_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "7787087cbc5ec110986e94d9aa1f17639a79c5de" +uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95" +version = "3.5.8+0" + +[[deps.OpenSpecFun_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl"] +git-tree-sha1 = "1346c9208249809840c91b26703912dff463d335" +uuid = "efe28fd5-8261-553b-a9e1-b2916fc3738e" +version = "0.5.6+0" + +[[deps.OrderedCollections]] +git-tree-sha1 = "94ba93778373a53bfd5a0caaf7d809c445292ff4" +uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d" +version = "1.8.2" + +[[deps.Parsers]] +deps = ["Dates", "PrecompileTools", "UUIDs"] +git-tree-sha1 = "ba0dc8a8a67cacac4842631f960c046e4e563675" +uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" +version = "2.8.8" + +[[deps.PerfTest]] +deps = ["BandwidthBenchmark", "BenchmarkTools", "Configurations", "CountFlops", "DataFrames", "DataStructures", "Dates", "HTTP", "Hwloc", "JLD2", "JSON", "LibGit2", "LinearAlgebra", "MLStyle", "MacroTools", "Pkg", "PrecompileTools", "Printf", "Suppressor", "TOML", "Test", "ThreadPinningCore", "UnicodePlots"] +path = "../.." +uuid = "1dca261b-fc56-4a8c-a7e2-9798d8a75978" +version = "0.2.1" + + [deps.PerfTest.extensions] + PerfTest_AMDGPUExt = "AMDGPU" + PerfTest_CUDAExt = "CUDA" + PerfTest_LIKWIDExt = "LIKWID" + PerfTest_MPIExt = "MPI" + + [deps.PerfTest.weakdeps] + AMDGPU = "21141c5a-9bdb-4563-92ae-f87d6854732e" + CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" + LIKWID = "bf22376a-e803-4184-b2ed-56326e3bff83" + MPI = "da04e1cc-30fd-572f-bb4f-1f8673147195" + +[[deps.Pkg]] +deps = ["Artifacts", "Dates", "Downloads", "FileWatching", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"] +uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" +version = "1.10.0" + +[[deps.PooledArrays]] +deps = ["DataAPI", "Future"] +git-tree-sha1 = "36d8b4b899628fb92c2749eb488d884a926614d3" +uuid = "2dfb63ee-cc39-5dd5-95bd-886bf059d720" +version = "1.4.3" + +[[deps.PrecompileTools]] +deps = ["Preferences"] +git-tree-sha1 = "5aa36f7049a63a1528fe8f7c3f2113413ffd4e1f" +uuid = "aea7be01-6a6a-4083-8856-8a6e6704d82a" +version = "1.2.1" + +[[deps.Preferences]] +deps = ["TOML"] +git-tree-sha1 = "5005266de4bfe50e53ff44a5cb5c540b6e47a254" +uuid = "21216c6a-2e73-6563-6e65-726566657250" +version = "1.6.0" + +[[deps.PrettyTables]] +deps = ["Crayons", "LaTeXStrings", "Markdown", "PrecompileTools", "Printf", "Reexport", "StringManipulation", "Tables"] +git-tree-sha1 = "1101cd475833706e4d0e7b122218257178f48f34" +uuid = "08abe8d2-0d0c-5749-adfa-8a2ac140af0d" +version = "2.4.0" + +[[deps.Printf]] +deps = ["Unicode"] +uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" + +[[deps.Profile]] +deps = ["Printf"] +uuid = "9abbd945-dff8-562f-b5e8-e1ebf5ef1b79" + +[[deps.PtrArrays]] +git-tree-sha1 = "4fbbafbc6251b883f4d2705356f3641f3652a7fe" +uuid = "43287f4e-b6f4-7ad1-bb20-aadabca52c3d" +version = "1.4.0" + +[[deps.QDLDL]] +deps = ["AMD", "LinearAlgebra", "SparseArrays"] +git-tree-sha1 = "5a3c14e534faf5b66c4633b5770a665ec1a87503" +uuid = "bfc457fd-c171-5ab7-bd9e-d5dbfc242d63" +version = "0.4.1" + +[[deps.REPL]] +deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"] +uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" + +[[deps.Random]] +deps = ["SHA"] +uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" + +[[deps.Reexport]] +git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b" +uuid = "189a3867-3050-52da-a836-e630ba90ab69" +version = "1.2.2" + +[[deps.Requires]] +deps = ["UUIDs"] +git-tree-sha1 = "62389eeff14780bfe55195b7204c0d8738436d64" +uuid = "ae029012-a4dd-5104-9daa-d747884805df" +version = "1.3.1" + +[[deps.SHA]] +uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" +version = "0.7.0" + +[[deps.ScopedValues]] +deps = ["HashArrayMappedTries", "Logging"] +git-tree-sha1 = "67a144433c4ce877ee6d1ada69a124d6b1ecf7be" +uuid = "7e506255-f358-4e82-b7e4-beb19740aa63" +version = "1.6.2" + +[[deps.SentinelArrays]] +deps = ["Dates", "Random"] +git-tree-sha1 = "084c47c7c5ce5cfecefa0a98dff69eb3646b5a80" +uuid = "91c51154-3ec4-41a3-a24f-3f23e20d615c" +version = "1.4.10" + +[[deps.Serialization]] +uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" + +[[deps.SimpleBufferStream]] +git-tree-sha1 = "f305871d2f381d21527c770d4788c06c097c9bc1" +uuid = "777ac1f9-54b0-4bf8-805c-2214025038e7" +version = "1.2.0" + +[[deps.SnoopPrecompile]] +deps = ["Preferences"] +git-tree-sha1 = "e760a70afdcd461cf01a575947738d359234665c" +uuid = "66db9d55-30c0-4569-8b51-7e840670fc0c" +version = "1.0.3" + +[[deps.Sockets]] +uuid = "6462fe0b-24de-5631-8697-dd941f90decc" + +[[deps.SortingAlgorithms]] +deps = ["DataStructures"] +git-tree-sha1 = "13cd91cc9be159e3f4d95b857fa2aa383b53772a" +uuid = "a2af1166-a08f-5f64-846c-94a0d3cef48c" +version = "1.2.3" + +[[deps.SparseArrays]] +deps = ["Libdl", "LinearAlgebra", "Random", "Serialization", "SuiteSparse_jll"] +uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" +version = "1.10.0" + +[[deps.SpecialFunctions]] +deps = ["IrrationalConstants", "LogExpFunctions", "OpenLibm_jll", "OpenSpecFun_jll"] +git-tree-sha1 = "429071b23f4c9a13fb6582f807cc2ef454082408" +uuid = "276daf66-3868-5448-9aa4-cd146d93841b" +version = "2.9.0" + + [deps.SpecialFunctions.extensions] + SpecialFunctionsChainRulesCoreExt = "ChainRulesCore" + + [deps.SpecialFunctions.weakdeps] + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + +[[deps.StableTasks]] +git-tree-sha1 = "c4f6610f85cb965bee5bfafa64cbeeda55a4e0b2" +uuid = "91464d47-22a1-43fe-8b7f-2d57ee82463f" +version = "0.1.7" + +[[deps.StaticArrays]] +deps = ["LinearAlgebra", "PrecompileTools", "Random", "StaticArraysCore"] +git-tree-sha1 = "e206cf4850fd7ac4255ffd2b98922f563e18ac53" +uuid = "90137ffa-7385-5640-81b9-e52037218182" +version = "1.9.20" + + [deps.StaticArrays.extensions] + StaticArraysChainRulesCoreExt = "ChainRulesCore" + StaticArraysStatisticsExt = "Statistics" + + [deps.StaticArrays.weakdeps] + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" + +[[deps.StaticArraysCore]] +git-tree-sha1 = "6ab403037779dae8c514bad259f32a447262455a" +uuid = "1e83bf80-4336-4d27-bf5d-d5a4f845583c" +version = "1.4.4" + +[[deps.Statistics]] +deps = ["LinearAlgebra", "SparseArrays"] +uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" +version = "1.10.0" + +[[deps.StatsAPI]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "178ed29fd5b2a2cfc3bd31c13375ae925623ff36" +uuid = "82ae8749-77ed-4fe6-ae5f-f523153014b0" +version = "1.8.0" + +[[deps.StatsBase]] +deps = ["AliasTables", "DataAPI", "DataStructures", "IrrationalConstants", "LinearAlgebra", "LogExpFunctions", "Missings", "Printf", "Random", "SortingAlgorithms", "SparseArrays", "Statistics", "StatsAPI"] +git-tree-sha1 = "adb9da019510162e67a4493fc235c23203d8b09e" +uuid = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91" +version = "0.34.13" + +[[deps.StringManipulation]] +deps = ["PrecompileTools"] +git-tree-sha1 = "8a90c1d77c3277a5d43b83927b3cbe2c70a37484" +uuid = "892a3eda-7b42-436c-8928-eab12a02cf0e" +version = "0.4.7" + +[[deps.SuiteSparse]] +deps = ["Libdl", "LinearAlgebra", "Serialization", "SparseArrays"] +uuid = "4607b0f0-06f3-5cda-b6b1-a6196a1729e9" + +[[deps.SuiteSparse_jll]] +deps = ["Artifacts", "Libdl", "libblastrampoline_jll"] +uuid = "bea87d4a-7f5b-5778-9afe-8cc45184846c" +version = "7.2.1+1" + +[[deps.Suppressor]] +deps = ["Logging"] +git-tree-sha1 = "6dbb5b635c5437c68c28c2ac9e39b87138f37c0a" +uuid = "fd094767-a336-5f1f-9728-57cf17d0bbfb" +version = "0.2.8" + +[[deps.TOML]] +deps = ["Dates"] +uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" +version = "1.0.3" + +[[deps.TableTraits]] +deps = ["IteratorInterfaceExtensions"] +git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39" +uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c" +version = "1.0.1" + +[[deps.Tables]] +deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "OrderedCollections", "TableTraits"] +git-tree-sha1 = "a94d9bdda1b7bed0046cea645639ab3f62196fac" +uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c" +version = "1.14.0" + +[[deps.Tar]] +deps = ["ArgTools", "SHA"] +uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" +version = "1.10.0" + +[[deps.TensorCore]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "1feb45f88d133a655e001435632f019a9a1bcdb6" +uuid = "62fd8b95-f654-4bbd-a8a5-9c27f68ccd50" +version = "0.1.1" + +[[deps.Test]] +deps = ["InteractiveUtils", "Logging", "Random", "Serialization"] +uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" + +[[deps.ThreadPinning]] +deps = ["DelimitedFiles", "DocStringExtensions", "Libdl", "LinearAlgebra", "PrecompileTools", "Preferences", "Random", "StableTasks"] +git-tree-sha1 = "333748c6fa62868fa039f00ba670d619776a6752" +uuid = "811555cd-349b-4f26-b7bc-1f208b848042" +version = "0.7.22" + +[[deps.ThreadPinningCore]] +deps = ["LinearAlgebra", "PrecompileTools", "StableTasks"] +git-tree-sha1 = "bb3c6f3b5600fbff028c43348365681b34d06499" +uuid = "6f48bc29-05ce-4cc8-baad-4adcba581a18" +version = "0.4.5" + +[[deps.TimerOutputs]] +deps = ["ExprTools", "Printf"] +git-tree-sha1 = "3748bd928e68c7c346b52125cf41fff0de6937d0" +uuid = "a759f4b9-e2f1-59dc-863e-4aeb61b1ea8f" +version = "0.5.29" + + [deps.TimerOutputs.extensions] + FlameGraphsExt = "FlameGraphs" + + [deps.TimerOutputs.weakdeps] + FlameGraphs = "08572546-2f56-4bcf-ba4e-bab62c3a3f89" + +[[deps.TranscodingStreams]] +git-tree-sha1 = "0c45878dcfdcfa8480052b6ab162cdd138781742" +uuid = "3bb67fe8-82b1-5028-8e26-92a6c54297fa" +version = "0.11.3" + +[[deps.URIs]] +git-tree-sha1 = "908fec9df6c5de98548ead82a468c95ccf6cd263" +uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4" +version = "1.7.0" + +[[deps.UUIDs]] +deps = ["Random", "SHA"] +uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" + +[[deps.Unicode]] +uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" + +[[deps.UnicodePlots]] +deps = ["ColorSchemes", "ColorTypes", "Contour", "Crayons", "Dates", "LinearAlgebra", "MarchingCubes", "NaNMath", "PrecompileTools", "Printf", "SparseArrays", "StaticArrays", "StatsBase"] +git-tree-sha1 = "24d2e39c49110ffe5ab6b298a9b53a56f3ac57eb" +uuid = "b8865327-cd53-5732-bb35-84acbb429228" +version = "3.8.4" + + [deps.UnicodePlots.extensions] + FreeTypeExt = ["FileIO", "FreeType"] + ImageInTerminalExt = "ImageInTerminal" + IntervalSetsExt = "IntervalSets" + TermExt = "Term" + UnitfulExt = "Unitful" + + [deps.UnicodePlots.weakdeps] + FileIO = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549" + FreeType = "b38be410-82b0-50bf-ab77-7b57e271db43" + ImageInTerminal = "d8c32880-2388-543b-8c61-d9f865259254" + IntervalSets = "8197267c-284f-5f27-9208-e0e47529a953" + Term = "22787eb5-b846-44ae-b979-8e399b8463ab" + Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d" + +[[deps.Unitful]] +deps = ["Dates", "LinearAlgebra", "Random"] +git-tree-sha1 = "1f0f9f401753701a7e4113b5056ca38d33875b55" +uuid = "1986cc42-f94f-5a68-af5c-568840ba703d" +version = "1.29.0" + + [deps.Unitful.extensions] + ConstructionBaseUnitfulExt = "ConstructionBase" + ForwardDiffExt = "ForwardDiff" + InverseFunctionsUnitfulExt = "InverseFunctions" + LatexifyExt = ["Latexify", "LaTeXStrings"] + NaNMathExt = "NaNMath" + PrintfExt = "Printf" + + [deps.Unitful.weakdeps] + ConstructionBase = "187b0558-2788-49d3-abe0-74a17ed4e7c9" + ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" + InverseFunctions = "3587e190-3f89-42d0-90ee-14403ec27112" + LaTeXStrings = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f" + Latexify = "23fbe1c1-3f47-55db-b15f-69d7ec21a316" + NaNMath = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3" + Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7" + +[[deps.XML2_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Libiconv_jll", "Zlib_jll"] +git-tree-sha1 = "80d3930c6347cfce7ccf96bd3bafdf079d9c0390" +uuid = "02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a" +version = "2.13.9+0" + +[[deps.Xorg_libpciaccess_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Zlib_jll"] +git-tree-sha1 = "58972370b81423fc546c56a60ed1a009450177c3" +uuid = "a65dc6b1-eb27-53a1-bb3e-dea574b5389e" +version = "0.19.0+0" + +[[deps.Zlib_jll]] +deps = ["Libdl"] +uuid = "83775a58-1f1d-513f-b197-d71354ab007a" +version = "1.2.13+1" + +[[deps.Zstd_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "446b23e73536f84e8037f5dce465e92275f6a308" +uuid = "3161d3a3-bdf6-5164-811a-617609db77b4" +version = "1.5.7+1" + +[[deps.libblastrampoline_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "8e850b90-86db-534c-a0d3-1478176c7d93" +version = "5.11.0+0" + +[[deps.nghttp2_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" +version = "1.52.0+1" + +[[deps.p7zip_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" +version = "17.4.0+2" diff --git a/examples/example-kkt-cholesky-regression/Project.toml b/examples/example-kkt-cholesky-regression/Project.toml new file mode 100644 index 0000000..78ea7d2 --- /dev/null +++ b/examples/example-kkt-cholesky-regression/Project.toml @@ -0,0 +1,19 @@ +[deps] +Clarabel = "61c947e1-3e6d-4ee4-985a-eec8c727bd6e" +LIKWID = "bf22376a-e803-4184-b2ed-56326e3bff83" +LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +PerfTest = "1dca261b-fc56-4a8c-a7e2-9798d8a75978" +Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7" +QDLDL = "bfc457fd-c171-5ab7-bd9e-d5dbfc242d63" +Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" +SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" +Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" + +# Clarabel pinned to 0.11: clarabel_perftest.jl redefines/relies on internals +# of Clarabel's own QDLDLDirectLDLSolver (not public API) and QDLDL's private +# `_get_amd_ordering` helper (not public API either) -- re-verify both still +# match before bumping either pin. +[compat] +Clarabel = "0.11" +QDLDL = "0.4" +julia = "1, 1.11" diff --git a/examples/example-kkt-cholesky-regression/README.md b/examples/example-kkt-cholesky-regression/README.md new file mode 100644 index 0000000..386e042 --- /dev/null +++ b/examples/example-kkt-cholesky-regression/README.md @@ -0,0 +1,401 @@ +# KKT Cholesky regression demo + +This example shows PerfTest.jl's LIKWID-backed regression detection catching +a class of performance bug that no correctness test can ever see: a loop +reordered so it fights Julia's memory layout instead of working with it. + +It comes in two parts, each demonstrating a different performance-bug class +that no correctness test can see: + +- **Part 1** (`KktCholesky.jl` + `kkt_perftest.jl`): a small, self-contained, + hand-rolled Cholesky kernel — no dependency beyond PerfTest/LIKWID. The + regression is a transposed loop order (same algorithm, worse memory + access pattern). +- **Part 2** (`clarabel_perftest.jl`): plugged directly into + [Clarabel.jl](https://github.com/oxfordcontrol/Clarabel.jl) — a real + interior-point QP/SOCP solver — by redefining one of its own internals at + runtime. The regression is a disabled fill-reducing permutation (same + Clarabel/QDLDL code end to end, worse elimination order). + +## Background + +Interior-point methods for convex optimization — Clarabel.jl, OSQP, ECOS, +and friends — spend nearly all of their time doing one thing over and over: +factorizing and solving a symmetric "KKT" (or condensed normal-equations) +linear system once per Newton iteration. Part 1 hand-rolls a kernel doing the +same kind of work — build a synthetic SPD system `K = AᵀA + σI`, factorize it +with Cholesky, solve by forward/back substitution — with no dependency on +any real solver, so we have full control over its implementation and can +inject a realistic regression into it. Part 2 takes that same idea — a +performance bug invisible to correctness tests — and drives it through +Clarabel.jl's actual factorization step instead of a synthetic stand-in, +via a different kind of bug: a disabled fill-reducing permutation, rather +than a transposed loop order. + +## Part 1: the self-contained kernel + +### The kernel, and the regression + +Cholesky factorization has several textbook-equivalent loop orderings +(`kji`, `kij`, `jki`, ... — see Golub & Van Loan). They all do the exact same +arithmetic; they differ only in which array dimension the innermost loop +walks. Julia (like Fortran and MATLAB) stores matrices **column-major**, so +the innermost loop should walk down a column (stride 1) rather than across a +row (stride `n`). + +`cholesky_factor_fast!` uses the `kji` order — column outer, row inner — +which is the right choice for Julia: + +```julia +for j in (k+1):n + ljk = L[j, k] + @simd for i in j:n + L[i, j] -= L[i, k] * ljk + end +end +``` + +`cholesky_factor_regressed!` is the *same algorithm*, updating the exact +same set of matrix entries in the exact same order relative to the outer `k` +loop — just with the inner two loops transposed (`kij` order, row outer, +column inner): + +```julia +for i in (k+1):n + lik = L[i, k] + @simd for j in (k+1):i + L[i, j] -= lik * L[j, k] + end +end +``` + +This is exactly the kind of one-line-diff bug that shows up when porting or +refactoring numerical code from a row-major reference implementation (C, +NumPy) without adjusting for Julia's layout. Because each matrix entry is +still updated by the same single subtraction in the same relative order, +**the two implementations produce bit-for-bit identical results** — every +`@test` you could write against the output will pass either way. Note also +that `@simd` is still sitting right there on the regressed loop: the +annotation alone doesn't fix a strided access pattern, which is exactly why +you need hardware counters, not source inspection, to catch this. + +Measured locally (Apple M-series, n=512 dense system — absolute numbers will +differ on the real target machine, but the qualitative effect is a basic +cache/memory-hierarchy phenomenon that reproduces on any CPU): + +| implementation | time (median of 5) | +|---|---| +| `cholesky_factor_fast!` | ~6 ms | +| `cholesky_factor_regressed!` | ~130 ms (≈20×) | + +### The recipe (`kkt_perftest.jl`) + +```julia +using Test, PerfTest, LIKWID +using LinearAlgebra + +include("KktCholesky.jl") +using .KktCholesky + +const USE_FAST_FACTORIZATION = true # <- the toggle you flip to "introduce the regression" + +@perftest_config " +[general] +verbose = 3 +[regression] +enabled = true +dedicated_reference_file = 'kkt_reference.JLD2' +" + +@testset "KKT Cholesky solve" begin + n, m = 512, 256 + K, b = build_kkt_system(n, m; seed=1) + + @define_metric name="attained_gflops" units="GFLOP/s" begin + :flops / 1e9 + end + @define_metric name="l3_miss_ratio" units="ratio" begin + :miss.l3 + end + @define_metric name="mem_bandwidth" units="MB/s" begin + :bw.mem.read_write + end + + @regression metrics=[:median_time, :l3_miss_ratio, :attained_gflops] threshold=[1.15, 1.20, 0.85] low_is_bad=[false, false, true] + + x = @perftest samples=15 solve_kkt(K, b; fast=USE_FAST_FACTORIZATION) + + @test relative_residual(K, b, x) < 1e-8 +end +``` + +`using LIKWID` activates PerfTest's `PerfTest_LIKWIDExt` extension. Any +`@perftest` target in a testset that references LIKWID-backed formula +symbols (`:flop`, `:flops`, `:bw`, `:miss`, `:energy`, `:power` — see +`ext/PerfTest_LIKWIDExt.jl` for the full alias table) is automatically +wrapped in `LIKWID.perfmon` with the right counter groups — there's no +manual group selection. + +- `:flops` reads LIKWID's `FLOPS_DP` group's precomputed rate metric + (reported internally in raw FLOP/s, hence `/ 1e9` for GFLOP/s). +- `:miss.l3` reads the `L3CACHE` group's "L3 miss ratio". +- `:bw.mem.read_write` reads the `MEM` group's "Memory bandwidth [MBytes/s]". + +The `@regression` declaration tracks three metrics at once — wall time, +attained GFLOP/s, and L3 miss ratio — so a failing run doesn't just say "this +got slower", it tells you the mechanism: did the FLOP rate collapse, did the +cache miss ratio spike, or both? + +### Running the Part 1 demo + +```sh +julia --project=. -e 'using Pkg; Pkg.instantiate()' +``` + +Then, from this directory: + +1. With `USE_FAST_FACTORIZATION = true` (the shipped default), run: + ```sh + julia --project=. -e 'using PerfTest; runperftests("kkt_perftest.jl")' + ``` + First run: no baseline exists yet, everything passes, the baseline is + recorded to `kkt_reference.JLD2`. +2. Run the exact same command again — confirms stability (still compared + against the run-1 baseline, still passes). +3. Edit `kkt_perftest.jl`, flip `USE_FAST_FACTORIZATION` to `false`, rerun. + The `:median_time`, `l3_miss_ratio`, and `attained_gflops` regression + checks fail; the correctness `@test` still passes. Because this run + wasn't fully green, `kkt_reference.JLD2` is **not** updated — the + original baseline persists. +4. Flip `USE_FAST_FACTORIZATION` back to `true` and rerun — recovers, passes + again against the same original baseline from step 1. + +Or run all four steps with `./run_demo.sh kkt_perftest.jl`. + +*(TODO: paste real console output and measured metric values here after +running steps 1–4 on the target Linux/LIKWID machine.)* + +Optionally, to see programmatically which metrics tripped a failing run +(mirrors `test/t5-regression.jl`'s style): + +```julia +using PerfTest +PerfTest.retrievePerfTests("kkt_reference.JLD2"; get=:tests, where_pred=PerfTest.testFailed, pathonly=true) +``` + +## Part 2: plugging into Clarabel.jl directly + +Part 1 proves the regression-detection idea works in isolation. Part 2 +drives a *different* regression class through a real solver: +[Clarabel.jl](https://github.com/oxfordcontrol/Clarabel.jl), a pure-Julia +interior-point solver for QPs/SOCPs/SDPs, used here as a dependency rather +than reimplemented. + +### The extension point, and the redefinition + +Clarabel's default direct linear-solve backend, `QDLDLDirectLDLSolver`, +wraps [QDLDL.jl](https://github.com/osqp/QDLDL.jl), a sparse `K = L D Lᵀ` +factorization for symmetric quasi-definite matrices — the structural +property (positive-definite (1,1) block, negative-definite (2,2) block) +that Clarabel's KKT/Newton systems always have, which guarantees an `LDLᵀ` +factorization exists under *any* symmetric permutation, including the +identity, without pivoting. + +QDLDL picks *which* permutation to use exactly once, at `Clarabel.Solver(...)` +construction time, via its own `qdldl(K; perm=..., ...)` constructor. The +default (`perm` left unspecified) computes a fill-reducing AMD ordering; +passing `perm=nothing` is QDLDL's own documented "factor without reordering" +mode — a first-class, publicly supported code path, not a hack. Every +`refactor!`/`solve!` call afterward — one pair per Newton iteration, plus +extra `solve!` calls for iterative refinement — is purely numeric and +reuses whatever permutation was chosen at construction; it never revisits +ordering. + +This gives Part 2 a regression class that's arguably more representative +than a transposed loop order: **a disabled or broken fill-reducing +permutation**, a real, common sparse-solver performance bug. Crucially, it +can be injected without touching `refactor!`/`solve!` at all, and without +introducing any different algorithm — both `USE_FAST_FACTORIZATION = true` +and `false` run Clarabel's real, unmodified QDLDL numeric code end to end; +the only thing that differs is which permutation got baked in at +construction: + +```julia +using QDLDL + +function QDLDL._get_amd_ordering(A, amd_dense_scale) + if USE_FAST_FACTORIZATION + # Stock QDLDL behavior, verbatim. + meta = QDLDL.AMD.Amd() + meta.control[QDLDL.AMD.AMD_DENSE] *= Float64(amd_dense_scale) + return QDLDL.AMD.amd(A, meta) + else + return nothing + end +end +``` + +`_get_amd_ordering(A, amd_dense_scale)` is the private helper QDLDL uses to +compute `perm`'s default value. After `using QDLDL`, Julia lets this module +add or replace methods on any generic function for any type it doesn't +own — ordinary multiple dispatch, sometimes called "monkey-patching" (the +same mechanism Part 2 used to rely on for overriding `refactor!`/`solve!` +directly, before the regression moved to this construction-time hook). It's +private (underscore-prefixed), not public API — re-verify its name and +signature if the pinned QDLDL version (`Project.toml` pins `QDLDL = "0.4"` +alongside `Clarabel = "0.11"`) is ever bumped. + +**Why `P` had to become genuinely sparse.** The naive version of this +regression — just flip AMD off on whatever QP happens to be at hand — turns +out to depend entirely on the problem: if the KKT matrix's dominant block is +already fully **dense**, no permutation can avoid roughly the same O(n³) +elimination cost either way, so disabling AMD barely registers. `build_qp` +therefore builds `P` as a genuinely sparse SPD matrix — a random sparse +graph (~6 edges/node) with diagonal dominance for guaranteed SPD-ness — and +then randomly shuffles its variable labeling. AMD's ordering is derived +purely from the sparsity graph, so it recovers a good elimination order +regardless of labeling; the *natural* (post-shuffle) order has no such +luck. That asymmetry — AMD is labeling-invariant, natural order isn't — is +exactly what makes "someone disabled AMD" a dramatic, realistic regression +on a sparse problem instead of a cosmetic one. + +**Verified correctness**: both branches converge Clarabel to `SOLVED` on +the same QPs, to the same answer — they're the same algorithm and the same +code, just under two different permutations of the same quasi-definite +matrix, so (unlike Part 1's bit-for-bit identical loop-order variants) exact +floating-point agreement isn't guaranteed, but both should agree well +within Clarabel's own solver tolerance. + +*(TODO: paste real fast-vs-regressed timing/GFLOP-s numbers here after +running on the target Linux/LIKWID machine.)* + +### The recipe (`clarabel_perftest.jl`) + +Same shape as Part 1 — inline `@perftest_config`, the same LIKWID-backed +metrics, the same multi-metric `@regression`, the same +`USE_FAST_FACTORIZATION` toggle — except the `@perftest` target constructs +and solves a real `Clarabel.Solver`, and it sweeps `n_vars` over +`[32, 64, 128, 256, 512, 1024, 2048]` instead of running a single fixed +size: + +```julia +function solve_fresh_qp(P, q, A, b, cones, settings) + solver = Clarabel.Solver(P, q, A, b, cones, settings) + Clarabel.solve!(solver) + return solver +end + +solver = @perftest samples=5 evals=1 solve_fresh_qp(P, q, A, b, cones, settings) +@test solver.solution.status == Clarabel.SOLVED +``` + +Constructing a fresh solver inside the timed target (rather than via +`@perftest`'s `setup=`) keeps the target self-contained and measures "cost +of solving this QP", not just "cost of one factorization" — the regression +still shows up clearly since the bad permutation is paid for on every +Newton iteration inside the same call. + +Note there's no intra-algorithm parallelism on either branch here — QDLDL +is single-threaded by design, regardless of AMD ordering. `@perftest_threads +:all` at the top of the file controls something different: how many Julia +threads the *perftest harness* itself may use across samples, not anything +inside Clarabel/QDLDL's own solve. + +#### Why a ratio metric like `l3_miss_ratio` wouldn't be the right catch here either + +`l3_miss_ratio` (`:miss.l3`) is a *rate* — L3 misses ÷ L3 references — not +a count. A disabled fill-reducing permutation genuinely increases both the +absolute amount of arithmetic (`:flop` — a worse elimination order creates +more fill-in in `L`, so QDLDL does more real work, not just the same work +laid out worse) and the memory traffic needed to do it, so a pure hit/miss +*ratio* can end up roughly flat even as both numerator and denominator grow +together — a ratio metric doesn't distinguish "twice the work, same +locality" from "the same work, half the locality." + +`clarabel_perftest.jl` instead defines an operational-intensity metric that +normalizes L3 traffic by useful work directly: + +```julia +@define_metric name="l3_operational_intensity" units="GFLOP/MB" begin + (:flop / 1e9) / (:bw.l3.read_write * :median_time) +end +``` + +`:bw.l3.read_write` reads the `L3` group's "L3 bandwidth [MBytes/s]" — MB/s +of traffic at the L2/L3 boundary. Multiplying by `:median_time` turns that +rate into total MB moved for one call; dividing GFLOP of useful work +(`:flop / 1e9`) by that gives GFLOP done per MB of L3 traffic — the +roofline-style "operational intensity" (flop/byte, see +`example-paper-pardiso`), sourced from LIKWID counters instead of +solver-printed stats. `@regression` tracks it with `low_is_bad=false` (a +*decrease* is the failure signal): a disabled fill-reducing permutation +should make QDLDL do measurably more work per byte of L3 traffic it moves, +since the scattered fill-in it creates is exactly the kind of irregular, +low-reuse access pattern a good ordering exists to avoid. + +### Running the Part 2 demo + +Identical walkthrough to Part 1, just against the other recipe: + +```sh +julia --project=. -e 'using PerfTest; runperftests("clarabel_perftest.jl")' +``` + +or `./run_demo.sh clarabel_perftest.jl` for all four steps at once. + +*(TODO: paste real console output and measured metric values here after +running on the target Linux/LIKWID machine.)* + +## Requirements + +- **Linux only.** LIKWID reads hardware performance counters via the MSR + interface or the `likwid-accessD` daemon; it does not run on macOS. Both + kernels' correctness can be authored and sanity-checked anywhere Julia + runs (see below), but run the actual `runperftests` demos on the target + Linux machine. +- LIKWID needs counter access: either run as root, have the `msr` kernel + module loaded with appropriate permissions, or have `likwid-accessD` + installed and running. This is a LIKWID/OS-level concern — PerfTest.jl has + no configuration for it. +- Part 1's `n = 512` dense system is sized to clear typical L2/L3 caches on + the dev machine used above; if the regression doesn't show up clearly in + `l3_miss_ratio`/`mem_bandwidth` on your target machine, scale up until the + dense factor comfortably exceeds its L2/L3 size. Slowdown magnitude is + also sensitive to whether the matrix dimension happens to alias badly + against cache set size (e.g. powers of two are frequently pathological) — + don't read too much into the exact multiplier, only into the fact that + there reliably is one. +- Part 2's regression magnitude is driven by fill-in, not raw problem size: + `build_qp`'s sparse, randomly-relabeled `P` (see above) needs the + natural-order factorization to actually generate substantially more + fill-in than AMD's — controlled by `avg_degree` (graph density) as much as + by `n_vars`. If the regression doesn't show up clearly in + `l3_operational_intensity`/`median_time` on your target machine, or if the + natural-order branch blows up disproportionately at the largest `n_vars` + in the sweep, tune `avg_degree` and/or trim the sweep rather than assuming + the current values are universally correct — they haven't been tuned + against a specific target machine yet. +- Part 2 pins `Clarabel = "0.11"` and `QDLDL = "0.4"` in `Project.toml`: it + redefines QDLDL's private `_get_amd_ordering` helper, which is not public + API and can change name or signature across QDLDL releases. If you bump + either pin, re-verify the override still matches before trusting the + patched results. + +## Running these recipes via bare `include()` + +Like `example-quickstart`'s `testfile.jl`, both recipes can also be run as +plain functional tests via `include("kkt_perftest.jl")` / +`include("clarabel_perftest.jl")`, bypassing `PerfTest.transform`/ +`runperftests` entirely (all PerfTest macros are no-ops outside the +transform, so only the final `@test` actually runs, using whatever +`USE_FAST_FACTORIZATION` is currently set to). This requires `@perftest`'s +keyword arguments to always precede the target expression, which is the +last argument (`@perftest samples=15 solve_kkt(...)`, not +`@perftest solve_kkt(...) samples=15`) — this is also the order the real +transform pipeline expects. `KktCholesky.jl` has no such restriction either +way — it can be `include()`d and exercised directly for correctness checks +independent of PerfTest. (`KktLDLT.jl`, the hand-rolled dense `LDLᵀ` kernel +from an earlier version of Part 2's regression, is no longer used by +`clarabel_perftest.jl` — Part 2's regression now lives entirely inside +Clarabel/QDLDL's own code, see above — but the file is left in place +unreferenced rather than deleted.) diff --git a/examples/example-kkt-cholesky-regression/clarabel_perftest.jl b/examples/example-kkt-cholesky-regression/clarabel_perftest.jl new file mode 100644 index 0000000..7868788 --- /dev/null +++ b/examples/example-kkt-cholesky-regression/clarabel_perftest.jl @@ -0,0 +1,243 @@ +using Test, PerfTest, LIKWID +using Clarabel, QDLDL, LinearAlgebra, SparseArrays, Random + +@perftest_threads :all + +# Single, obviously-editable toggle simulating "a regression was introduced" +# -- same convention and demo walkthrough as kkt_perftest.jl (see README.md), +# except now it's plugged directly into Clarabel.jl's own solve. +# true -> the real, unmodified Clarabel/QDLDL backend, AMD-ordered +# (sparse, specialized, exactly stock Clarabel) +# false -> THE REGRESSION: the *same* real Clarabel/QDLDL backend, but +# factored in natural (unpermuted) variable order instead of +# AMD's fill-reducing order -- standing in for "someone +# accidentally disabled/broke the fill-reducing permutation in +# the sparse solver" -- see the QDLDL._get_amd_ordering override +# below. +const USE_FAST_FACTORIZATION = true + +# Which synthetic sparsity pattern build_qp() gives P (see build_qp below). +# Independent of, and orthogonal to, USE_FAST_FACTORIZATION above: this +# toggle controls *which QP gets solved*, not *how* it gets factored. A +# second top-level const, edited the same manual way as USE_FAST_FACTORIZATION +# (run_demo.sh only auto-sweeps that one; this one you flip by hand between +# full 4-step runs -- see README.md). +# :random -> Erdos-Renyi-style: edges between uniformly-random pairs of +# variables. The original/only model this file ever had; +# kept as the default so existing reference-file history +# still matches the model it was recorded against. +# :geometric -> random geometric graph (RGG): n_vars points placed +# uniformly at random in [0,1]^2, edges are the +# (n_vars*avg_degree)/2 globally-closest pairs by Euclidean +# distance -- same target edge count as :random, so +# avg_degree stays a comparable density knob across both +# models; only the *connectivity pattern* differs (spatially +# local vs. uniform-random). See geometric_edges below. +const GRAPH_MODEL = :random #:geometric + +# Only used when GRAPH_MODEL === :geometric (ignored otherwise). `nothing` +# is the original single-blob behavior: n_vars points spread uniformly over +# the whole [0,1]^2 domain, exactly as geometric_edges behaved before this +# toggle existed. Setting it to a number k softly caps how big a +# locally-dense group of points gets: points are drawn from +# ~n_vars/k randomly-placed Gaussian blobs instead of one uniform spread -- +# "soft" because cluster membership is a random draw per point, not an +# exact/hard partition, so realized cluster sizes vary around k rather than +# being forced equal. See geometric_edges below for the mechanism and an +# important caveat: small k tends to fully *disconnect* the graph into +# separate components (nearest-neighbor edge selection exhausts a cluster's +# internal pairs before ever reaching another cluster), and disconnected +# components can never get fill-in between them under *any* ordering -- +# so very small clusters should shrink AMD's relative advantage rather than +# grow it, the opposite direction from GRAPH_MODEL=:random's lack of +# separator structure. +const GRAPH_CLUSTER_SIZE = 512 + +# --- Override QDLDL's own fill-reducing-ordering selection --------------- +# +# QDLDL's permutation is chosen exactly once, at Clarabel.Solver(...) +# construction time, inside Clarabel.QDLDLDirectLDLSolver's constructor, via +# QDLDL.qdldl(KKT; ...)'s `perm` keyword. That keyword's default value is +# computed by the private helper QDLDL._get_amd_ordering(A, amd_dense_scale) +# (see QDLDL.jl's own doc comment on `qdldl`: "qdldl(A) uses the default AMD +# ordering ... qdldl(A,perm=nothing) factors without reordering" -- natural +# order is a first-class QDLDL-supported mode, not a hack). Every +# refactor!/solve! call afterward, one pair per Newton iteration, is purely +# numeric and reuses whatever permutation was picked here -- so overriding +# this one helper is enough to toggle AMD vs. natural order for the whole +# solve, and Clarabel.refactor!/Clarabel.solve! never need to be touched: +# both branches run Clarabel's real, unmodified QDLDL numeric code the +# entire time, only the permutation baked in at construction differs. +# +# After `using QDLDL`, Julia lets this module add or replace methods on any +# generic function for any type it doesn't own -- ordinary multiple +# dispatch, sometimes called "monkey-patching" (same mechanism the old +# refactor!/solve! overrides used). `_get_amd_ordering` is private +# (underscore-prefixed), not public API -- re-verify its name/signature if +# the pinned QDLDL version is ever bumped. +function QDLDL._get_amd_ordering(A, amd_dense_scale) + if USE_FAST_FACTORIZATION + # Stock QDLDL behavior, verbatim. + meta = QDLDL.AMD.Amd() + meta.control[QDLDL.AMD.AMD_DENSE] *= Float64(amd_dense_scale) + return QDLDL.AMD.amd(A, meta) + else + return nothing + end +end + +# --- A small box-constrained QP: min 0.5 x'Px + q'x s.t. 0 <= x <= u ----- +# P is a genuinely *sparse* SPD matrix -- a sparse graph (~avg_degree +# edges/node, model selected by GRAPH_MODEL above), diagonally dominant for +# guaranteed SPD-ness -- with its variable labeling randomly shuffled +# *after* the graph is built (load-bearing for either graph model: it hides +# any accidental good ordering from the natural-order branch). AMD's +# ordering is derived purely from the sparsity graph, so it recovers a good +# elimination order regardless of labeling; the *natural* (post-shuffle) +# order has no such luck. This is what makes disabling AMD (see +# USE_FAST_FACTORIZATION above) a dramatic, realistic regression: with a +# fully dense P, no permutation could avoid O(n^3) work either way, so +# disabling AMD would barely register. + +# Uniformly-random edges between distinct variable pairs (Erdos-Renyi-style). +function random_edges(rng::AbstractRNG, n_vars::Int, nedges::Int) + Ii = rand(rng, 1:n_vars, nedges) + Jj = rand(rng, 1:n_vars, nedges) + return Ii, Jj +end + +# Random geometric graph (RGG): n_vars points placed uniformly at random in +# [0,1]^dim (or, if avg_cluster_size is given, drawn from randomly-placed +# Gaussian blobs instead -- see below); edges are the `nedges` +# globally-closest (i,j) pairs by Euclidean distance -- build_qp passes it +# the exact same `nedges` it computes for random_edges, so avg_degree stays +# a comparable density knob between the two graph models. +# +# Only the upper triangle (i SPD + P0 = P0 - spdiagm(0 => diag(P0)) + spdiagm(0 => d) + perm = randperm(rng, n_vars) + P = P0[perm, perm] + q = randn(rng, n_vars) + A = sparse([-I(n_vars); I(n_vars)] .* 1.0) + b = [zeros(n_vars); fill(5.0, n_vars)] + cones = [Clarabel.NonnegativeConeT(n_vars), Clarabel.NonnegativeConeT(n_vars)] + return P, q, A, b, cones +end + +# Constructing a fresh Solver and solving it in one call keeps this @perftest +# target self-contained (no BenchmarkTools `setup=` interpolation needed). +function solve_fresh_qp(P, q, A, b, cones, settings) + solver = Clarabel.Solver(P, q, A, b, cones, settings) + Clarabel.solve!(solver) + return solver +end + +@perftest_config " +[general] +verbose = 3 +[regression] +enabled = true +dedicated_reference_file = 'clarabel_reference_$(gethostname())_$(GRAPH_MODEL).JLD2' +" + + +@testset "Wrapper" begin + + @testset "Clarabel QP solve" for n_vars in [32, 64, 128, 256, 512, 1024, 2048, 2560] + #n_vars = 256 + @info n_vars + P, q, A, b, cones = build_qp(n_vars; graph_model=GRAPH_MODEL, avg_cluster_size=GRAPH_CLUSTER_SIZE) + settings = Clarabel.Settings(verbose=false) + + @define_metric name="attained_gflops" units="GFLOP/s" begin + :flop / 1e9 / :median_time + end + @define_metric name="l3_bandwidth" units="GBytes/s" begin +# (:flop / 1e6) / (:bw.l3.read_write * :median_time) + :bw.l3.read_write_volume + end + + @regression metrics=[:median_time, :attained_gflops, :l3_bandwidth] threshold=[1.15, 0.85, 1.15] low_is_bad=[false, true, false] + + solver = @perftest samples=20 evals=1 solve_fresh_qp(P, q, A, b, cones, settings) + + # Always passes: AMD-ordered and naturally-ordered QDLDL solve the + # exact same problem to the same answer (see README.md) -- only + # Clarabel's performance ever regresses, never its correctness. + @test solver.solution.status == Clarabel.SOLVED + end + +end diff --git a/examples/example-kkt-cholesky-regression/clarabel_perftest_perfsuite.jl b/examples/example-kkt-cholesky-regression/clarabel_perftest_perfsuite.jl new file mode 100644 index 0000000..f88f310 --- /dev/null +++ b/examples/example-kkt-cholesky-regression/clarabel_perftest_perfsuite.jl @@ -0,0 +1,439 @@ +module __PERFTEST__ +using Test, PerfTest, LIKWID +using Clarabel, QDLDL, LinearAlgebra, SparseArrays, Random +let + specs = :all + arrgmt_l = PerfTest.Topology.literallizeArrangement(:all) + arrgmt_e = PerfTest.Topology.isExecutableArrangement(arrgmt_l) + if arrgmt_e === nothing + @warn "Ignoring pinning." + else + try + PerfTest.Topology.enforceThreadArrangement(arrgmt_e) + catch e + if Sys.iswindows() || Sys.isapple() + @warn "Thread pinning is not supported on this OS. Ignoring specified arrangement." + else + @warn "Failed to enforce thread pinning: $(e), ignoring specified arrangement." + end + end + end +end +const USE_FAST_FACTORIZATION = true +const GRAPH_MODEL = :random +const GRAPH_CLUSTER_SIZE = 512 +function QDLDL._get_amd_ordering(A, amd_dense_scale) + if USE_FAST_FACTORIZATION + meta = QDLDL.AMD.Amd() + meta.control[QDLDL.AMD.AMD_DENSE] *= Float64(amd_dense_scale) + return QDLDL.AMD.amd(A, meta) + else + return nothing + end +end +function random_edges(rng::AbstractRNG, n_vars::Int, nedges::Int) + Ii = rand(rng, 1:n_vars, nedges) + Jj = rand(rng, 1:n_vars, nedges) + return (Ii, Jj) +end +function geometric_edges(rng::AbstractRNG, n_vars::Int, nedges::Int; dim::Int = 2, avg_cluster_size::Union{Nothing, Real} = nothing) + pts = if avg_cluster_size === nothing + rand(rng, dim, n_vars) + else + nclusters = clamp(round(Int, n_vars / avg_cluster_size), 1, n_vars) + centers = rand(rng, dim, nclusters) + spread = 0.3 * nclusters ^ (-1.0 / dim) + assign = rand(rng, 1:nclusters, n_vars) + out = Matrix{Float64}(undef, dim, n_vars) + @inbounds for v = 1:n_vars + @views out[:, v] .= clamp.(centers[:, assign[v]] .+ spread .* randn(rng, dim), 0.0, 1.0) + end + out + end + npairs = (n_vars * (n_vars - 1)) ÷ 2 + dists = Vector{Float64}(undef, npairs) + Is = Vector{Int}(undef, npairs) + Js = Vector{Int}(undef, npairs) + k = 0 + @inbounds for i = 1:n_vars, j = i + 1:n_vars + k += 1 + s = 0.0 + for d = 1:dim + s += (pts[d, i] - pts[d, j]) ^ 2 + end + dists[k] = sqrt(s) + Is[k] = i + Js[k] = j + end + order = partialsortperm(dists, 1:nedges) + return (Is[order], Js[order]) +end +function build_qp(n_vars::Int; seed::Int = 1, avg_degree::Int = 6, graph_model::Symbol = :random, avg_cluster_size::Union{Nothing, Real} = nothing) + rng = MersenneTwister(seed) + nedges = (n_vars * avg_degree) ÷ 2 + if graph_model === :random + (Ii, Jj) = random_edges(rng, n_vars, nedges) + elseif graph_model === :geometric + (Ii, Jj) = geometric_edges(rng, n_vars, nedges; avg_cluster_size = avg_cluster_size) + else + error("build_qp: unknown graph_model = $(repr(graph_model)); expected :random or :geometric") + end + keep = Ii .!= Jj + (Ii, Jj) = (Ii[keep], Jj[keep]) + vals = -((abs.(randn(rng, length(Ii))) .+ 0.1)) + P0 = sparse(Ii, Jj, vals, n_vars, n_vars) + P0 = P0 + P0' + d = vec(sum(abs, P0; dims = 2)) .+ 1.0 + P0 = (P0 - spdiagm(0 => diag(P0))) + spdiagm(0 => d) + perm = randperm(rng, n_vars) + P = P0[perm, perm] + q = randn(rng, n_vars) + A = sparse([-(I(n_vars)); I(n_vars)] .* 1.0) + b = [zeros(n_vars); fill(5.0, n_vars)] + cones = [Clarabel.NonnegativeConeT(n_vars), Clarabel.NonnegativeConeT(n_vars)] + return (P, q, A, b, cones) +end +function solve_fresh_qp(P, q, A, b, cones, settings) + solver = Clarabel.Solver(P, q, A, b, cones, settings) + Clarabel.solve!(solver) + return solver +end +PerfTest._perftest_config("\n[general]\nverbose = 3\n[regression]\nenabled = true\ndedicated_reference_file = 'clarabel_reference_$(gethostname())_$(GRAPH_MODEL).JLD2'\n") +using Test, Dates +nothing +using PerfTest: DepthRecord, Metric_Test, Methodology_Result, StrOrSym, Metric_Result, magnitudeAdjust, MPISetup, newMetricResult, buildPrimitiveMetrics!, measureCPUPeakFlops!, measureMemBandwidth!, addLog, @PRFTBenchmark, PRFTBenchmarkGroup, @PRFTCapture_out, @PRFTCount_ops, PRFTflop, @PRFTSuppress, Test_Result, by_index, regression, Suite_Execution_Result, savePrimitives, main_rank, GlobalSuiteData, @perftestset, PerfTestSet, extractTestResults, saveMethodologyData, Configuration, metricSampledValue, SampledValue +_t_begin = time() +_GLOBAL_MODE = PerfTest.NormalMode +if main_rank(PerfTest.NormalMode) + path = "./.perftests/clarabel_perftest.jl_PERFORMANCE.JLD2" + nofile = true + if isfile(path) + nofile = false + datafile = PerfTest.openDataFile(path) + else + datafile = PerfTest.Perftest_Datafile_Root(PerfTest.Suite_Execution_Result[]) + end + regression_path = (Configuration.CONFIG["regression"])["dedicated_reference_file"] + if regression_path != "" && isfile(regression_path) + regression_file = PerfTest.openDataFile(regression_path) + else + if regression_path != "" + regression_file = PerfTest.Perftest_Datafile_Root(PerfTest.Suite_Execution_Result[]) + else + regression_file = datafile + regression_path = path + end + end + _PRFT_GLOBALS = GlobalSuiteData(datafile, path, "clarabel_perftest.jl") + if length(regression_file.results) > 0 + for i = length(regression_file.results):-1:1 + if length(retrievePerfTests(regression_path, get = :tests, where_pred = testFailed, execution = i)) == 0 + _PRFT_GLOBALS.old = (regression_file.results[i]).perftests + println("Regression: Previous performance reference for this configuration has been found, regression tests could be performed. Regression is currenctly $(if true + "enabled" +else + "disabled" +end)).") + break + end + end + else + _PRFT_GLOBALS.old = nothing + end +else + _PRFT_GLOBALS = GlobalSuiteData() +end +let + PerfTest.Topology.getMachineTopology!() + _PRFT_GLOBALS.builtins[:MEM_CACHE_SIZES] = PerfTest.Topology.getCacheSizes() +end +TS = @perftestset(PerfTestSet, "Wrapper", begin + local ts = Test.get_testset() + ts.old_test_results = _PRFT_GLOBALS.old + nothing + TS = @perftestset(PerfTestSet, "Clarabel QP solve", for n_vars = [32, 64, 128, 256, 512, 1024, 2048, 2560] + local ts = Test.get_testset() + ts.iterator = n_vars + nothing + @info n_vars + (P, q, A, b, cones) = build_qp(n_vars; graph_model = GRAPH_MODEL, avg_cluster_size = GRAPH_CLUSTER_SIZE) + settings = Clarabel.Settings(verbose = false) + nothing + nothing + nothing + solver = begin + ts.benchmarks["Test 1"] = @PRFTBenchmark(($solve_fresh_qp)($P, $q, $A, $b, $cones, $settings), samples = 20, evals = 1) + extensions = PerfTest.ExtensionData[] + (metrics, events) = PerfTest.perfmon((()->solve_fresh_qp(P, q, A, b, cones, settings)), ["L3", "FLOPS_DP"]; autopin = false, print = false, nsamples = length(ts.benchmarks["Test 1"])) + push!(extensions, PerfTest.LIKWIDExtensionData(metrics, events)) + push!(extensions, PerfTest.NoExtensionData()) + push!(extensions, PerfTest.NoExtensionData()) + test_res = Test_Result("Test 1", extensions) + ts.test_results["Test 1"] = test_res + keys = ["Wrapper", string("Clarabel QP solve", "_", n_vars)] + append!(keys, ["Test 1"]) + old_test_res = _PRFT_GLOBALS.old + for key = keys + if !(old_test_res isa Nothing) && haskey(old_test_res, key) + old_test_res = old_test_res[key] + else + old_test_res = nothing + break + end + end + test_res.primitives[:autoflop] = 0 + test_res.primitives[:printed_output] = @PRFTCapture_out(test_res.primitives[:ret_value] = solve_fresh_qp(P, q, A, b, cones, settings)) + buildPrimitiveMetrics!(PerfTest.NormalMode, ts, test_res) + let m = newMetricResult(PerfTest.NormalMode, name = "attained_gflops", units = "GFLOP/s", value = (if haskey(_PRFT_GLOBALS.custom_benchmarks, :flop) + PerfTest.metricSampledValue(_PRFT_GLOBALS.custom_benchmarks[:flop]) + else + if haskey(_PRFT_GLOBALS.builtins, :flop) + _PRFT_GLOBALS.builtins[:flop] + else + if haskey(test_res.metrics, :flop) + PerfTest.metricSampledValue(test_res.metrics[:flop]) + else + if haskey(test_res.auxiliar, :flop) + PerfTest.metricSampledValue(test_res.auxiliar[:flop]) + else + sum(PerfTest.likwidMetricsRetrieve(test_res, :FLOPS_DP, "DP [MFLOP/s]")) * 1.0e6 * test_res.primitives[:median_time] + end + end + end + end / 1.0e9) / test_res.primitives[:median_time], auxiliary = false, showvar = false) + test_res.metrics[:attained_gflops] = m + end + let m = newMetricResult(PerfTest.NormalMode, name = "l3_bandwidth", units = "GBytes/s", value = sum(PerfTest.likwidMetricsRetrieve(test_res, :L3, "L3 data volume [GBytes]")), auxiliary = false, showvar = false) + test_res.metrics[:l3_bandwidth] = m + end + if main_rank(PerfTest.NormalMode) + let + methodology_res = Methodology_Result(name = "Performance Regression Testing") + all_succeeded = true + if haskey(test_res.metrics, :median_time) && (!(old_test_res isa Nothing) && haskey(old_test_res.metrics, :median_time)) + ratio_sv = metricSampledValue(test_res.metrics[:median_time]) / metricSampledValue(old_test_res.metrics[:median_time]) + ratio = if ratio_sv isa SampledValue + ratio_sv.value + else + ratio_sv + end + success = ratio < 1.15 + result = newMetricResult(PerfTest.NormalMode, name = ":median_time Difference", units = "%", value = ratio_sv * 100, showvar = false) + test = Metric_Test(reference = 100.0, threshold_min_percent = 1.15 * 100, threshold_max_percent = nothing, low_is_bad = false, succeeded = success, custom_plotting = Symbol[], full_print = true, showvar = false) + push!(methodology_res.metrics, result => test) + methodology_res.custom_elements[:median_time] = newMetricResult(PerfTest.NormalMode, name = (test_res.metrics[:median_time]).name, units = (test_res.metrics[:median_time]).units, value = metricSampledValue(test_res.metrics[:median_time]), showvar = false) => test + all_succeeded &= success + elseif !(old_test_res isa Nothing) && (!(haskey(test_res.metrics, :median_time)) && (haskey(test_res.primitives, :median_time) && haskey(old_test_res.primitives, :median_time))) + ratio_sv = test_res.primitives[:median_time] / old_test_res.primitives[:median_time] + ratio = if ratio_sv isa SampledValue + ratio_sv.value + else + ratio_sv + end + success = ratio < 1.15 + result = newMetricResult(PerfTest.NormalMode, name = ":median_time Difference", units = "%", value = ratio_sv * 100, showvar = false) + test = Metric_Test(reference = 100.0, threshold_min_percent = 1.15 * 100, threshold_max_percent = nothing, low_is_bad = false, succeeded = success, custom_plotting = Symbol[], full_print = true, showvar = false) + push!(methodology_res.metrics, result => test) + methodology_res.custom_elements[:median_time] = newMetricResult(PerfTest.NormalMode, name = ":median_time", units = "s", value = test_res.primitives[:median_time], showvar = false) => test + all_succeeded &= success + end + if (Configuration.CONFIG["general"])["verbose"] >= 2 && !(old_test_res isa Nothing) + methodology_res.custom_elements[:reference] = newMetricResult(PerfTest.NormalMode, name = ":median_time Reference value", units = if haskey(old_test_res.metrics, :median_time) + (old_test_res.metrics[:median_time]).units + else + "s" + end, value = if haskey(old_test_res.metrics, :median_time) + metricSampledValue(old_test_res.metrics[:median_time]) + else + if haskey(old_test_res.primitives, :median_time) + old_test_res.primitives[:median_time] + else + NaN + end + end, showvar = false) + end + methodology_res.custom_elements[:median_time] = newMetricResult(PerfTest.NormalMode, name = ":median_time", units = if haskey(test_res.metrics, :median_time) + (test_res.metrics[:median_time]).units + else + "s" + end, value = if haskey(test_res.metrics, :median_time) + metricSampledValue(test_res.metrics[:median_time]) + else + if haskey(test_res.primitives, :median_time) + test_res.primitives[:median_time] + else + NaN + end + end, showvar = false) + if haskey(test_res.metrics, :attained_gflops) && (!(old_test_res isa Nothing) && haskey(old_test_res.metrics, :attained_gflops)) + ratio_sv = metricSampledValue(test_res.metrics[:attained_gflops]) / metricSampledValue(old_test_res.metrics[:attained_gflops]) + ratio = if ratio_sv isa SampledValue + ratio_sv.value + else + ratio_sv + end + success = ratio > 0.85 + result = newMetricResult(PerfTest.NormalMode, name = ":attained_gflops Difference", units = "%", value = ratio_sv * 100, showvar = false) + test = Metric_Test(reference = 100.0, threshold_min_percent = 0.85 * 100, threshold_max_percent = nothing, low_is_bad = true, succeeded = success, custom_plotting = Symbol[], full_print = true, showvar = false) + push!(methodology_res.metrics, result => test) + methodology_res.custom_elements[:attained_gflops] = newMetricResult(PerfTest.NormalMode, name = (test_res.metrics[:attained_gflops]).name, units = (test_res.metrics[:attained_gflops]).units, value = metricSampledValue(test_res.metrics[:attained_gflops]), showvar = false) => test + all_succeeded &= success + elseif !(old_test_res isa Nothing) && (!(haskey(test_res.metrics, :attained_gflops)) && (haskey(test_res.primitives, :attained_gflops) && haskey(old_test_res.primitives, :attained_gflops))) + ratio_sv = test_res.primitives[:attained_gflops] / old_test_res.primitives[:attained_gflops] + ratio = if ratio_sv isa SampledValue + ratio_sv.value + else + ratio_sv + end + success = ratio > 0.85 + result = newMetricResult(PerfTest.NormalMode, name = ":attained_gflops Difference", units = "%", value = ratio_sv * 100, showvar = false) + test = Metric_Test(reference = 100.0, threshold_min_percent = 0.85 * 100, threshold_max_percent = nothing, low_is_bad = true, succeeded = success, custom_plotting = Symbol[], full_print = true, showvar = false) + push!(methodology_res.metrics, result => test) + methodology_res.custom_elements[:attained_gflops] = newMetricResult(PerfTest.NormalMode, name = ":attained_gflops", units = "s", value = test_res.primitives[:attained_gflops], showvar = false) => test + all_succeeded &= success + end + if (Configuration.CONFIG["general"])["verbose"] >= 2 && !(old_test_res isa Nothing) + methodology_res.custom_elements[:reference] = newMetricResult(PerfTest.NormalMode, name = ":attained_gflops Reference value", units = if haskey(old_test_res.metrics, :attained_gflops) + (old_test_res.metrics[:attained_gflops]).units + else + "s" + end, value = if haskey(old_test_res.metrics, :attained_gflops) + metricSampledValue(old_test_res.metrics[:attained_gflops]) + else + if haskey(old_test_res.primitives, :attained_gflops) + old_test_res.primitives[:attained_gflops] + else + NaN + end + end, showvar = false) + end + methodology_res.custom_elements[:attained_gflops] = newMetricResult(PerfTest.NormalMode, name = ":attained_gflops", units = if haskey(test_res.metrics, :attained_gflops) + (test_res.metrics[:attained_gflops]).units + else + "s" + end, value = if haskey(test_res.metrics, :attained_gflops) + metricSampledValue(test_res.metrics[:attained_gflops]) + else + if haskey(test_res.primitives, :attained_gflops) + test_res.primitives[:attained_gflops] + else + NaN + end + end, showvar = false) + if haskey(test_res.metrics, :l3_bandwidth) && (!(old_test_res isa Nothing) && haskey(old_test_res.metrics, :l3_bandwidth)) + ratio_sv = metricSampledValue(test_res.metrics[:l3_bandwidth]) / metricSampledValue(old_test_res.metrics[:l3_bandwidth]) + ratio = if ratio_sv isa SampledValue + ratio_sv.value + else + ratio_sv + end + success = ratio < 1.15 + result = newMetricResult(PerfTest.NormalMode, name = ":l3_bandwidth Difference", units = "%", value = ratio_sv * 100, showvar = false) + test = Metric_Test(reference = 100.0, threshold_min_percent = 1.15 * 100, threshold_max_percent = nothing, low_is_bad = false, succeeded = success, custom_plotting = Symbol[], full_print = true, showvar = false) + push!(methodology_res.metrics, result => test) + methodology_res.custom_elements[:l3_bandwidth] = newMetricResult(PerfTest.NormalMode, name = (test_res.metrics[:l3_bandwidth]).name, units = (test_res.metrics[:l3_bandwidth]).units, value = metricSampledValue(test_res.metrics[:l3_bandwidth]), showvar = false) => test + all_succeeded &= success + elseif !(old_test_res isa Nothing) && (!(haskey(test_res.metrics, :l3_bandwidth)) && (haskey(test_res.primitives, :l3_bandwidth) && haskey(old_test_res.primitives, :l3_bandwidth))) + ratio_sv = test_res.primitives[:l3_bandwidth] / old_test_res.primitives[:l3_bandwidth] + ratio = if ratio_sv isa SampledValue + ratio_sv.value + else + ratio_sv + end + success = ratio < 1.15 + result = newMetricResult(PerfTest.NormalMode, name = ":l3_bandwidth Difference", units = "%", value = ratio_sv * 100, showvar = false) + test = Metric_Test(reference = 100.0, threshold_min_percent = 1.15 * 100, threshold_max_percent = nothing, low_is_bad = false, succeeded = success, custom_plotting = Symbol[], full_print = true, showvar = false) + push!(methodology_res.metrics, result => test) + methodology_res.custom_elements[:l3_bandwidth] = newMetricResult(PerfTest.NormalMode, name = ":l3_bandwidth", units = "s", value = test_res.primitives[:l3_bandwidth], showvar = false) => test + all_succeeded &= success + end + if (Configuration.CONFIG["general"])["verbose"] >= 2 && !(old_test_res isa Nothing) + methodology_res.custom_elements[:reference] = newMetricResult(PerfTest.NormalMode, name = ":l3_bandwidth Reference value", units = if haskey(old_test_res.metrics, :l3_bandwidth) + (old_test_res.metrics[:l3_bandwidth]).units + else + "s" + end, value = if haskey(old_test_res.metrics, :l3_bandwidth) + metricSampledValue(old_test_res.metrics[:l3_bandwidth]) + else + if haskey(old_test_res.primitives, :l3_bandwidth) + old_test_res.primitives[:l3_bandwidth] + else + NaN + end + end, showvar = false) + end + methodology_res.custom_elements[:l3_bandwidth] = newMetricResult(PerfTest.NormalMode, name = ":l3_bandwidth", units = if haskey(test_res.metrics, :l3_bandwidth) + (test_res.metrics[:l3_bandwidth]).units + else + "s" + end, value = if haskey(test_res.metrics, :l3_bandwidth) + metricSampledValue(test_res.metrics[:l3_bandwidth]) + else + if haskey(test_res.primitives, :l3_bandwidth) + test_res.primitives[:l3_bandwidth] + else + NaN + end + end, showvar = false) + for (r, test) = methodology_res.metrics + PerfTest.@_prftest test.succeeded + end + saveMethodologyData(test_res.name, methodology_res) + end + end + end + nothing + end) + nothing + nothing + end) +if main_rank(PerfTest.NormalMode) + testresdict = Dict{String, Union{Dict, Test_Result}}() + if TS isa Vector + benchmarks = PerfTest.newBenchmarkGroup() + for ts = TS + testresdict[ts.description * "_" * string(ts.iterator)] = extractTestResults(ts) + benchmarks[ts.description * "_" * string(ts.iterator)] = ts.benchmarks + end + newres = Suite_Execution_Result(timestamp = datetime2unix(now()), elapsed = time() - _t_begin, benchmarks = benchmarks, perftests = testresdict) + else + testresdict[TS.description] = extractTestResults(TS) + newres = Suite_Execution_Result(timestamp = datetime2unix(now()), elapsed = time() - _t_begin, benchmarks = TS.benchmarks, perftests = testresdict) + end + if PerfTest.testsSucceeded(TS) && ((Configuration.CONFIG["regression"])["enabled"] && regression_path != _PRFT_GLOBALS.datafile_path) + println("All performance tests have passed. Values will be registered as reference for regression testing.") + push!(regression_file.results, newres) + let + res_num = length(regression_file.results) + if (excess = 20 - res_num) <= 0 + PerfTest.p_yellow("[ℹ]") + println(" Regression: Exceeded maximum recorded results. The oldest $(-1 * excess + 1) result/s will be removed.") + for i = 1:-1 * excess + 1 + popfirst!(regression_file.results) + end + end + end + PerfTest.saveDataFile(regression_path, regression_file) + else + println("Some tests failed or errored.") + end + let + push!(_PRFT_GLOBALS.datafile.results, newres) + res_num = length(_PRFT_GLOBALS.datafile.results) + if (excess = 20 - res_num) <= 0 + PerfTest.p_yellow("[ℹ]") + println(" Results File: Exceeded maximum recorded results. The oldest $(-1 * excess + 1) result/s will be removed.") + for i = 1:-1 * excess + 1 + popfirst!(_PRFT_GLOBALS.datafile.results) + end + end + end + PerfTest.saveDataFile(_PRFT_GLOBALS.datafile_path, _PRFT_GLOBALS.datafile) + println("[✓] $(path) Performance tests have been finished (elapsed $(newres.elapsed) s)") + if (Configuration.CONFIG["regression"])["use_bencher"] + bencher_config = Configuration.CONFIG["bencher"] + PerfTest.BencherREST.exportSuiteToBencher(_PRFT_GLOBALS.datafile, bencher_config) + end + PerfTest.clean(PerfTest.NormalMode) +end +end \ No newline at end of file diff --git a/examples/example-kkt-cholesky-regression/clarabel_slurm.sh b/examples/example-kkt-cholesky-regression/clarabel_slurm.sh new file mode 100755 index 0000000..53a66c3 --- /dev/null +++ b/examples/example-kkt-cholesky-regression/clarabel_slurm.sh @@ -0,0 +1,28 @@ +#!/bin/bash +#SBATCH --job-name=clarabel +#SBATCH --nodes=1 +#SBATCH --ntasks-per-node=1 +#SBATCH --exclusive +#SBATCH --output=clarabel-%j.out +#SBATCH --time=6:00:00 +#SBATCH --nodelist=icx32 # Specify a particular node +#SBATCH --constraint=hwperf # Specify a node constraint + +echo "Job started on $(hostname) at $(date)" +echo "Job ID: $SLURM_JOB_ID" +echo "Nodes: $SLURM_JOB_NODELIST" +echo "----------------------------------------------------------------" + +# Load modules +# module load +# +module load likwid + +# Set environment variables +# export VAR=value + +# User commands +./run_demo.sh clarabel_perftest.jl + +echo "----------------------------------------------------------------" +echo "Job completed at $(date)" diff --git a/examples/example-kkt-cholesky-regression/clarabel_slurm_amd.sh b/examples/example-kkt-cholesky-regression/clarabel_slurm_amd.sh new file mode 100755 index 0000000..7d97bf5 --- /dev/null +++ b/examples/example-kkt-cholesky-regression/clarabel_slurm_amd.sh @@ -0,0 +1,28 @@ +#!/bin/bash +#SBATCH --job-name=clarabel +#SBATCH --nodes=1 +#SBATCH --ntasks-per-node=1 +#SBATCH --output=clarabel-%j.out +#SBATCH --time=6:00:00 +#SBATCH --exclusive +#SBATCH --nodelist=milan1 # Specify a particular node +#SBATCH --constraint=hwperf # Specify a node constraint + +echo "Job started on $(hostname) at $(date)" +echo "Job ID: $SLURM_JOB_ID" +echo "Nodes: $SLURM_JOB_NODELIST" +echo "----------------------------------------------------------------" + +# Load modules +# module load +# +module load likwid + +# Set environment variables +# export VAR=value + +# User commands +./run_demo.sh clarabel_perftest.jl + +echo "----------------------------------------------------------------" +echo "Job completed at $(date)" diff --git a/examples/example-kkt-cholesky-regression/clarabel_slurm_arm.sh b/examples/example-kkt-cholesky-regression/clarabel_slurm_arm.sh new file mode 100755 index 0000000..87e80a6 --- /dev/null +++ b/examples/example-kkt-cholesky-regression/clarabel_slurm_arm.sh @@ -0,0 +1,27 @@ +#!/bin/bash +#SBATCH --job-name=clarabel +#SBATCH --nodes=1 +#SBATCH --ntasks-per-node=1 +#SBATCH --output=clarabel-%j.out +#SBATCH --time=6:00:00 +#SBATCH --nodelist=lukewarm # Specify a particular node +#SBATCH --constraint=hwperf # Specify a node constraint + +echo "Job started on $(hostname) at $(date)" +echo "Job ID: $SLURM_JOB_ID" +echo "Nodes: $SLURM_JOB_NODELIST" +echo "----------------------------------------------------------------" + +# Load modules +# module load +# +module load likwid + +# Set environment variables +# export VAR=value + +# User commands +./run_demo.sh clarabel_perftest.jl + +echo "----------------------------------------------------------------" +echo "Job completed at $(date)" diff --git a/examples/example-kkt-cholesky-regression/fill b/examples/example-kkt-cholesky-regression/fill new file mode 100755 index 0000000..7162dd0 --- /dev/null +++ b/examples/example-kkt-cholesky-regression/fill @@ -0,0 +1,28 @@ +#!/bin/bash + +# Check if at least 2 arguments are provided (input and at least one replacement string) +if [ "$#" -lt 2 ]; then + echo "Usage: $0 ... " + exit 1 +fi + +# The first argument can be a string or a file +input="$1" + +# Shift the arguments so that "$@" only contains the replacement strings +shift + +# Check if the first input is a file and read from it if it exists +if [ -f "$input" ]; then + cont=$(cat "$input") +else + cont="$input" +fi + +# Replace each occurrence of #$# with the corresponding string argument +for i in "${!}"; do + cont=$(echo $cont | sed "s/\#\$\#/${!i}/g") +done + +# Output the result to stdout +echo "$cont" diff --git a/examples/example-kkt-cholesky-regression/kkt_perftest.jl b/examples/example-kkt-cholesky-regression/kkt_perftest.jl new file mode 100644 index 0000000..1012d67 --- /dev/null +++ b/examples/example-kkt-cholesky-regression/kkt_perftest.jl @@ -0,0 +1,56 @@ +using Test, LIKWID, PerfTest +using LinearAlgebra + +include("KktCholesky.jl") +using .KktCholesky + +# Single, obviously-editable toggle simulating "a regression was introduced". +# Demo walkthrough (see README.md): +# 1. run with USE_FAST_FACTORIZATION = true -> records the baseline +# 2. run again unchanged -> confirms stability +# 3. flip to false, run again -> regression caught +# 4. flip back to true, run again -> recovery (vs. baseline from step 1) +const USE_FAST_FACTORIZATION = true + +@perftest_config " +[general] +verbose = 3 +[regression] +enabled = true +dedicated_reference_file = 'kkt_reference.JLD2' +" + +@testset "KKT Cholesky solve" begin + # n×n dense SPD system, large enough that L (n²·8 bytes ≈ 2MB) clears + # typical L2 caches, so the loop-order regression shows up clearly in + # LIKWID's cache-miss and bandwidth counters. Tune against the target + # machine's actual cache sizes if the effect isn't visible. + n, m = 512, 256 + K, b = build_kkt_system(n, m; seed=1) + + # LIKWID-backed custom metrics (see ext/PerfTest_LIKWIDExt.jl for the + # full alias table). + @define_metric name="l3_miss_ratio" units="ratio" begin + :miss.l3 + end + @define_metric name="mem_bandwidth" units="MB/s" begin + :bw.mem.read_write + end + @define_metric name="attained_gflops" units="GFLOP/s" begin + :flop / 1e9 / :median_time + end + + # Regression tracked across wall time AND two LIKWID hardware-counter + # metrics, so a failure explains *why* it got slower, not just *that* it + # did. + #@regression metrics=Symbol[:median_time, :l3_miss_ratio, :attained_gflops] threshold=Float64[1.15, 1.20, 0.85] low_is_bad=Bool[false, false, true] + @regression metrics=median_time threshold=1.15 low_is_bad=false + @regression metrics=l3_miss_ratio threshold=1.2 low_is_bad=false + @regression metrics=attained_gflops threshold=0.85 low_is_bad=true + + x = @perftest samples=15 solve_kkt(K, b, USE_FAST_FACTORIZATION) + + # Always passes: fast and regressed factorizations are bit-for-bit + # identical (see KktCholesky.jl), so only performance ever regresses. + @test relative_residual(K, b, x) < 1e-8 +end diff --git a/examples/example-kkt-cholesky-regression/kkt_perftest_perfsuite.jl b/examples/example-kkt-cholesky-regression/kkt_perftest_perfsuite.jl new file mode 100644 index 0000000..74d1ccc --- /dev/null +++ b/examples/example-kkt-cholesky-regression/kkt_perftest_perfsuite.jl @@ -0,0 +1,405 @@ +module __PERFTEST__ +using Test, LIKWID, PerfTest +using LinearAlgebra +module KktCholesky +using LinearAlgebra +using Random +export build_kkt_system, cholesky_factor_fast!, cholesky_factor_regressed!, forward_substitution!, back_substitution!, solve_kkt, relative_residual +function build_kkt_system(n::Int, m::Int; seed::Int = 1, sigma::Float64 = 0.01) + rng = MersenneTwister(seed) + A = randn(rng, m, n) + K = Matrix(Symmetric(A' * A)) + @inbounds for i = 1:n + K[i, i] += sigma + end + b = randn(rng, n) + return (K, b) +end +function cholesky_factor_fast!(L::Matrix{Float64}, K::Matrix{Float64}) + n = size(K, 1) + copyto!(L, K) + @inbounds for k = 1:n + L[k, k] = sqrt(L[k, k]) + invLkk = 1.0 / L[k, k] + for i = k + 1:n + L[i, k] *= invLkk + end + for j = k + 1:n + ljk = L[j, k] + @simd for i = j:n + L[i, j] -= L[i, k] * ljk + end + end + end + @inbounds for j = 1:n, i = 1:j - 1 + L[i, j] = 0.0 + end + return L +end +function cholesky_factor_regressed!(L::Matrix{Float64}, K::Matrix{Float64}) + n = size(K, 1) + copyto!(L, K) + @inbounds for k = 1:n + L[k, k] = sqrt(L[k, k]) + invLkk = 1.0 / L[k, k] + for i = k + 1:n + L[i, k] *= invLkk + end + for i = k + 1:n + lik = L[i, k] + @simd for j = k + 1:i + L[i, j] -= lik * L[j, k] + end + end + end + @inbounds for j = 1:n, i = 1:j - 1 + L[i, j] = 0.0 + end + return L +end +function forward_substitution!(z::Vector{Float64}, L::Matrix{Float64}, b::Vector{Float64}) + n = length(b) + @inbounds for i = 1:n + s = b[i] + @simd for k = 1:i - 1 + s -= L[i, k] * z[k] + end + z[i] = s / L[i, i] + end + return z +end +function back_substitution!(x::Vector{Float64}, L::Matrix{Float64}, z::Vector{Float64}) + n = length(z) + @inbounds for i = n:-1:1 + s = z[i] + @simd for k = i + 1:n + s -= L[k, i] * x[k] + end + x[i] = s / L[i, i] + end + return x +end +function solve_kkt(K::Matrix{Float64}, b::Vector{Float64}, fast::Bool = true) + n = size(K, 1) + L = Matrix{Float64}(undef, n, n) + if fast + cholesky_factor_fast!(L, K) + else + cholesky_factor_regressed!(L, K) + end + z = Vector{Float64}(undef, n) + x = Vector{Float64}(undef, n) + forward_substitution!(z, L, b) + back_substitution!(x, L, z) + return x +end +relative_residual(K, b, x) = norm(K * x - b) / norm(b) +end +using .KktCholesky +const USE_FAST_FACTORIZATION = true +PerfTest._perftest_config("[perfcompare]\nenabled = true\n\n[MPI]\nmode = \"reduce\"\nenabled = false\n\n[general]\nsave_results = true\nmax_saved_results = 20\nsuppress_output = true\nsave_folder = \".perftests\"\nthreads_per_numa = \"single\"\nrecursive = true\nverbose = 3\nautoflops = false\nplotting = true\nnumas = \"single\"\nlogs_enabled = true\nsafe_formulas = false\n\n[regression]\nenabled = true\ndedicated_reference_file = \"kkt_reference.JLD2\"\ndefault_threshold = 1.1\nuse_bencher = false\n\n[roofline]\nenabled = true\ndefault_threshold = 0.5\n\n[memory_bandwidth]\nenabled = true\ndefault_threshold = 0.5\n\n[machine_benchmarking]\nmemory_bandwidth_test_buffer_size = 0\n\n[bencher]\napi_key = \"\"\norganization = \"\"\napi_url = \"https://api.bencher.dev\"\nproject_name = \"\"\ncustom_testbed_name = \"\"\n") +using Test, Dates +nothing +using PerfTest: DepthRecord, Metric_Test, Methodology_Result, StrOrSym, Metric_Result, magnitudeAdjust, MPISetup, newMetricResult, buildPrimitiveMetrics!, measureCPUPeakFlops!, measureMemBandwidth!, addLog, @PRFTBenchmark, PRFTBenchmarkGroup, @PRFTCapture_out, @PRFTCount_ops, PRFTflop, @PRFTSuppress, Test_Result, by_index, regression, Suite_Execution_Result, savePrimitives, main_rank, GlobalSuiteData, @perftestset, PerfTestSet, extractTestResults, saveMethodologyData, Configuration +_t_begin = time() +_GLOBAL_MODE = PerfTest.NormalMode +if main_rank(PerfTest.NormalMode) + path = "./.perftests/kkt_perftest.jl_PERFORMANCE.JLD2" + nofile = true + if isfile(path) + nofile = false + datafile = PerfTest.openDataFile(path) + else + datafile = PerfTest.Perftest_Datafile_Root(PerfTest.Suite_Execution_Result[]) + end + regression_path = (Configuration.CONFIG["regression"])["dedicated_reference_file"] + if regression_path != "" && isfile(regression_path) + regression_file = PerfTest.openDataFile(regression_path) + else + if regression_path != "" + regression_file = PerfTest.Perftest_Datafile_Root(PerfTest.Suite_Execution_Result[]) + else + regression_file = datafile + regression_path = path + end + end + _PRFT_GLOBALS = GlobalSuiteData(datafile, path, "kkt_perftest.jl") + if length(regression_file.results) > 0 + for i = length(regression_file.results):-1:1 + if length(retrievePerfTests(regression_path, get = :tests, where_pred = testFailed, execution = i)) == 0 + _PRFT_GLOBALS.old = (regression_file.results[i]).perftests + println("Regression: Previous performance reference for this configuration has been found, regression tests could be performed. Regression is currenctly $(if true + "enabled" +else + "disabled" +end)).") + break + end + end + else + _PRFT_GLOBALS.old = nothing + end +else + _PRFT_GLOBALS = GlobalSuiteData() +end +let + PerfTest.Topology.getMachineTopology!() + _PRFT_GLOBALS.builtins[:MEM_CACHE_SIZES] = PerfTest.Topology.getCacheSizes() +end +TS = @perftestset(PerfTestSet, "KKT Cholesky solve", begin + local ts = Test.get_testset() + ts.old_test_results = _PRFT_GLOBALS.old + (n, m) = (512, 256) + (K, b) = build_kkt_system(n, m; seed = 1) + nothing + nothing + nothing + nothing + nothing + nothing + x = begin + ts.benchmarks["Test 1"] = @PRFTBenchmark(($solve_kkt)($K, $b, $USE_FAST_FACTORIZATION), samples = 15) + extensions = PerfTest.ExtensionData[] + (metrics, events) = PerfTest.perfmon((()->solve_kkt(K, b, USE_FAST_FACTORIZATION)), ["L3CACHE", "MEM", "FLOPS_DP"]; autopin = false, print = false) + push!(extensions, PerfTest.LIKWIDExtensionData(metrics, events)) + push!(extensions, PerfTest.NoExtensionData()) + push!(extensions, PerfTest.NoExtensionData()) + test_res = Test_Result("Test 1", extensions) + ts.test_results["Test 1"] = test_res + keys = ["KKT Cholesky solve"] + append!(keys, ["Test 1"]) + old_test_res = _PRFT_GLOBALS.old + for key = keys + if !(old_test_res isa Nothing) && haskey(old_test_res, key) + old_test_res = old_test_res[key] + else + old_test_res = nothing + break + end + end + test_res.primitives[:autoflop] = 0 + test_res.primitives[:printed_output] = @PRFTCapture_out(test_res.primitives[:ret_value] = solve_kkt(K, b, USE_FAST_FACTORIZATION)) + buildPrimitiveMetrics!(PerfTest.NormalMode, ts, test_res) + let m = newMetricResult(PerfTest.NormalMode, name = "l3_miss_ratio", units = "ratio", value = sum(PerfTest.likwidMetricsRetrieve(test_res, :L3CACHE, "L3 miss ratio")), auxiliary = false) + test_res.metrics[:l3_miss_ratio] = m + end + let m = newMetricResult(PerfTest.NormalMode, name = "mem_bandwidth", units = "MB/s", value = sum(PerfTest.likwidMetricsRetrieve(test_res, :MEM, "Memory bandwidth [MBytes/s]")), auxiliary = false) + test_res.metrics[:mem_bandwidth] = m + end + let m = newMetricResult(PerfTest.NormalMode, name = "attained_gflops", units = "GFLOP/s", value = (if haskey(_PRFT_GLOBALS.custom_benchmarks, :flop) + (_PRFT_GLOBALS.custom_benchmarks[:flop]).value + else + if haskey(_PRFT_GLOBALS.builtins, :flop) + _PRFT_GLOBALS.builtins[:flop] + else + if haskey(test_res.metrics, :flop) + (test_res.metrics[:flop]).value + else + if haskey(test_res.auxiliar, :flop) + (test_res.auxiliar[:flop]).value + else + sum(((PerfTest.likwidEventsRetrieve(test_res, :FLOPS_DP, :FP_ARITH_INST_RETIRED_SCALAR_DOUBLE; required = false) .* 1 .+ PerfTest.likwidEventsRetrieve(test_res, :FLOPS_DP, :FP_ARITH_INST_RETIRED_128B_PACKED_DOUBLE; required = false) .* 2) .+ PerfTest.likwidEventsRetrieve(test_res, :FLOPS_DP, :FP_ARITH_INST_RETIRED_256B_PACKED_DOUBLE; required = false) .* 4) .+ PerfTest.likwidEventsRetrieve(test_res, :FLOPS_DP, :FP_ARITH_INST_RETIRED_512B_PACKED_DOUBLE; required = false) .* 8) + end + end + end + end / 1.0e9) / test_res.primitives[:median_time], auxiliary = false) + test_res.metrics[:attained_gflops] = m + end + if main_rank(PerfTest.NormalMode) + let + methodology_res = Methodology_Result(name = "Performance Regression Testing") + all_succeeded = true + if haskey(test_res.metrics, :median_time) && (!(old_test_res isa Nothing) && haskey(old_test_res.metrics, :median_time)) + ratio = (test_res.metrics[:median_time]).value / (old_test_res.metrics[:median_time]).value + success = ratio < 1.15 + result = newMetricResult(PerfTest.NormalMode, name = ":median_time Difference", units = "%", value = ratio * 100) + test = Metric_Test(reference = 100.0, threshold_min_percent = 1.15 * 100, threshold_max_percent = nothing, low_is_bad = false, succeeded = success, custom_plotting = Symbol[], full_print = true) + push!(methodology_res.metrics, result => test) + methodology_res.custom_elements[:median_time] = newMetricResult(PerfTest.NormalMode, name = (test_res.metrics[:median_time]).name, units = (test_res.metrics[:median_time]).units, value = (test_res.metrics[:median_time]).value) => test + all_succeeded &= success + elseif !(old_test_res isa Nothing) && (!(haskey(test_res.metrics, :median_time)) && (haskey(test_res.primitives, :median_time) && haskey(old_test_res.primitives, :median_time))) + ratio = test_res.primitives[:median_time] / old_test_res.primitives[:median_time] + success = ratio < 1.15 + result = newMetricResult(PerfTest.NormalMode, name = ":median_time Difference", units = "%", value = ratio * 100) + test = Metric_Test(reference = 100.0, threshold_min_percent = 1.15 * 100, threshold_max_percent = nothing, low_is_bad = false, succeeded = success, custom_plotting = Symbol[], full_print = true) + push!(methodology_res.metrics, result => test) + methodology_res.custom_elements[:median_time] = newMetricResult(PerfTest.NormalMode, name = ":median_time", units = "s", value = test_res.primitives[:median_time]) => test + all_succeeded &= success + end + if (Configuration.CONFIG["general"])["verbose"] >= 2 && !(old_test_res isa Nothing) + methodology_res.custom_elements[:reference] = newMetricResult(PerfTest.NormalMode, name = ":median_time Reference value", units = if haskey(old_test_res.metrics, :median_time) + (old_test_res.metrics[:median_time]).units + else + "s" + end, value = if haskey(old_test_res.metrics, :median_time) + (old_test_res.metrics[:median_time]).value + else + if haskey(old_test_res.primitives, :median_time) + old_test_res.primitives[:median_time] + else + NaN + end + end) + end + methodology_res.custom_elements[:median_time] = newMetricResult(PerfTest.NormalMode, name = ":median_time", units = if haskey(test_res.metrics, :median_time) + (test_res.metrics[:median_time]).units + else + "s" + end, value = if haskey(test_res.metrics, :median_time) + (test_res.metrics[:median_time]).value + else + if haskey(test_res.primitives, :median_time) + test_res.primitives[:median_time] + else + NaN + end + end) + if haskey(test_res.metrics, :l3_miss_ratio) && (!(old_test_res isa Nothing) && haskey(old_test_res.metrics, :l3_miss_ratio)) + ratio = (test_res.metrics[:l3_miss_ratio]).value / (old_test_res.metrics[:l3_miss_ratio]).value + success = ratio < 1.2 + result = newMetricResult(PerfTest.NormalMode, name = ":l3_miss_ratio Difference", units = "%", value = ratio * 100) + test = Metric_Test(reference = 100.0, threshold_min_percent = 1.2 * 100, threshold_max_percent = nothing, low_is_bad = false, succeeded = success, custom_plotting = Symbol[], full_print = true) + push!(methodology_res.metrics, result => test) + methodology_res.custom_elements[:l3_miss_ratio] = newMetricResult(PerfTest.NormalMode, name = (test_res.metrics[:l3_miss_ratio]).name, units = (test_res.metrics[:l3_miss_ratio]).units, value = (test_res.metrics[:l3_miss_ratio]).value) => test + all_succeeded &= success + elseif !(old_test_res isa Nothing) && (!(haskey(test_res.metrics, :l3_miss_ratio)) && (haskey(test_res.primitives, :l3_miss_ratio) && haskey(old_test_res.primitives, :l3_miss_ratio))) + ratio = test_res.primitives[:l3_miss_ratio] / old_test_res.primitives[:l3_miss_ratio] + success = ratio < 1.2 + result = newMetricResult(PerfTest.NormalMode, name = ":l3_miss_ratio Difference", units = "%", value = ratio * 100) + test = Metric_Test(reference = 100.0, threshold_min_percent = 1.2 * 100, threshold_max_percent = nothing, low_is_bad = false, succeeded = success, custom_plotting = Symbol[], full_print = true) + push!(methodology_res.metrics, result => test) + methodology_res.custom_elements[:l3_miss_ratio] = newMetricResult(PerfTest.NormalMode, name = ":l3_miss_ratio", units = "s", value = test_res.primitives[:l3_miss_ratio]) => test + all_succeeded &= success + end + if (Configuration.CONFIG["general"])["verbose"] >= 2 && !(old_test_res isa Nothing) + methodology_res.custom_elements[:reference] = newMetricResult(PerfTest.NormalMode, name = ":l3_miss_ratio Reference value", units = if haskey(old_test_res.metrics, :l3_miss_ratio) + (old_test_res.metrics[:l3_miss_ratio]).units + else + "s" + end, value = if haskey(old_test_res.metrics, :l3_miss_ratio) + (old_test_res.metrics[:l3_miss_ratio]).value + else + if haskey(old_test_res.primitives, :l3_miss_ratio) + old_test_res.primitives[:l3_miss_ratio] + else + NaN + end + end) + end + methodology_res.custom_elements[:l3_miss_ratio] = newMetricResult(PerfTest.NormalMode, name = ":l3_miss_ratio", units = if haskey(test_res.metrics, :l3_miss_ratio) + (test_res.metrics[:l3_miss_ratio]).units + else + "s" + end, value = if haskey(test_res.metrics, :l3_miss_ratio) + (test_res.metrics[:l3_miss_ratio]).value + else + if haskey(test_res.primitives, :l3_miss_ratio) + test_res.primitives[:l3_miss_ratio] + else + NaN + end + end) + if haskey(test_res.metrics, :attained_gflops) && (!(old_test_res isa Nothing) && haskey(old_test_res.metrics, :attained_gflops)) + ratio = (test_res.metrics[:attained_gflops]).value / (old_test_res.metrics[:attained_gflops]).value + success = ratio > 0.85 + result = newMetricResult(PerfTest.NormalMode, name = ":attained_gflops Difference", units = "%", value = ratio * 100) + test = Metric_Test(reference = 100.0, threshold_min_percent = 0.85 * 100, threshold_max_percent = nothing, low_is_bad = true, succeeded = success, custom_plotting = Symbol[], full_print = true) + push!(methodology_res.metrics, result => test) + methodology_res.custom_elements[:attained_gflops] = newMetricResult(PerfTest.NormalMode, name = (test_res.metrics[:attained_gflops]).name, units = (test_res.metrics[:attained_gflops]).units, value = (test_res.metrics[:attained_gflops]).value) => test + all_succeeded &= success + elseif !(old_test_res isa Nothing) && (!(haskey(test_res.metrics, :attained_gflops)) && (haskey(test_res.primitives, :attained_gflops) && haskey(old_test_res.primitives, :attained_gflops))) + ratio = test_res.primitives[:attained_gflops] / old_test_res.primitives[:attained_gflops] + success = ratio > 0.85 + result = newMetricResult(PerfTest.NormalMode, name = ":attained_gflops Difference", units = "%", value = ratio * 100) + test = Metric_Test(reference = 100.0, threshold_min_percent = 0.85 * 100, threshold_max_percent = nothing, low_is_bad = true, succeeded = success, custom_plotting = Symbol[], full_print = true) + push!(methodology_res.metrics, result => test) + methodology_res.custom_elements[:attained_gflops] = newMetricResult(PerfTest.NormalMode, name = ":attained_gflops", units = "s", value = test_res.primitives[:attained_gflops]) => test + all_succeeded &= success + end + if (Configuration.CONFIG["general"])["verbose"] >= 2 && !(old_test_res isa Nothing) + methodology_res.custom_elements[:reference] = newMetricResult(PerfTest.NormalMode, name = ":attained_gflops Reference value", units = if haskey(old_test_res.metrics, :attained_gflops) + (old_test_res.metrics[:attained_gflops]).units + else + "s" + end, value = if haskey(old_test_res.metrics, :attained_gflops) + (old_test_res.metrics[:attained_gflops]).value + else + if haskey(old_test_res.primitives, :attained_gflops) + old_test_res.primitives[:attained_gflops] + else + NaN + end + end) + end + methodology_res.custom_elements[:attained_gflops] = newMetricResult(PerfTest.NormalMode, name = ":attained_gflops", units = if haskey(test_res.metrics, :attained_gflops) + (test_res.metrics[:attained_gflops]).units + else + "s" + end, value = if haskey(test_res.metrics, :attained_gflops) + (test_res.metrics[:attained_gflops]).value + else + if haskey(test_res.primitives, :attained_gflops) + test_res.primitives[:attained_gflops] + else + NaN + end + end) + for (r, test) = methodology_res.metrics + PerfTest.@_prftest test.succeeded + end + saveMethodologyData(test_res.name, methodology_res) + end + end + end + nothing + end) +if main_rank(PerfTest.NormalMode) + testresdict = Dict{String, Union{Dict, Test_Result}}() + if TS isa Vector + benchmarks = PerfTest.newBenchmarkGroup() + for ts = TS + testresdict[ts.description * "_" * string(ts.iterator)] = extractTestResults(TS) + benchmarks[ts.description * "_" * string(ts.iterator)] = ts.benchmarks + end + newres = Suite_Execution_Result(timestamp = datetime2unix(now()), elapsed = time() - _t_begin, benchmarks = benchmarks, perftests = testresdict) + else + testresdict[TS.description] = extractTestResults(TS) + newres = Suite_Execution_Result(timestamp = datetime2unix(now()), elapsed = time() - _t_begin, benchmarks = TS.benchmarks, perftests = testresdict) + end + if PerfTest.testsSucceeded(TS) && ((Configuration.CONFIG["regression"])["enabled"] && regression_path != _PRFT_GLOBALS.datafile_path) + println("All performance tests have passed. Values will be registered as reference for regression testing.") + push!(regression_file.results, newres) + let + res_num = length(regression_file.results) + if (excess = 20 - res_num) <= 0 + PerfTest.p_yellow("[ℹ]") + println(" Regression: Exceeded maximum recorded results. The oldest $(-1 * excess + 1) result/s will be removed.") + for i = 1:-1 * excess + 1 + popfirst!(regression_file.results) + end + end + end + PerfTest.saveDataFile(regression_path, regression_file) + else + println("Some tests failed or errored.") + end + let + push!(_PRFT_GLOBALS.datafile.results, newres) + res_num = length(_PRFT_GLOBALS.datafile.results) + if (excess = 20 - res_num) <= 0 + PerfTest.p_yellow("[ℹ]") + println(" Results File: Exceeded maximum recorded results. The oldest $(-1 * excess + 1) result/s will be removed.") + for i = 1:-1 * excess + 1 + popfirst!(_PRFT_GLOBALS.datafile.results) + end + end + end + PerfTest.saveDataFile(_PRFT_GLOBALS.datafile_path, _PRFT_GLOBALS.datafile) + println("[✓] $(path) Performance tests have been finished (elapsed $(newres.elapsed) s)") + if (Configuration.CONFIG["regression"])["use_bencher"] + bencher_config = Configuration.CONFIG["bencher"] + PerfTest.BencherREST.exportSuiteToBencher(_PRFT_GLOBALS.datafile, bencher_config) + end + PerfTest.clean(PerfTest.NormalMode) +end +end \ No newline at end of file diff --git a/examples/example-kkt-cholesky-regression/perftest_config.toml b/examples/example-kkt-cholesky-regression/perftest_config.toml new file mode 100644 index 0000000..f5e75ce --- /dev/null +++ b/examples/example-kkt-cholesky-regression/perftest_config.toml @@ -0,0 +1,44 @@ +[perfcompare] +enabled = true + +[MPI] +mode = "reduce" +enabled = false + +[general] +save_results = true +max_saved_results = 20 +suppress_output = true +save_folder = ".perftests" +threads_per_numa = "single" +recursive = true +verbose = 0 +autoflops = false +plotting = true +numas = "single" +logs_enabled = true +safe_formulas = false + +[regression] +enabled = true +dedicated_reference_file = "" +default_threshold = 1.1 +use_bencher = false + +[roofline] +enabled = true +default_threshold = 0.5 + +[memory_bandwidth] +enabled = true +default_threshold = 0.5 + +[machine_benchmarking] +memory_bandwidth_test_buffer_size = 0 + +[bencher] +api_key = "" +organization = "" +api_url = "https://api.bencher.dev" +project_name = "" +custom_testbed_name = "" diff --git a/examples/example-kkt-cholesky-regression/run_demo.sh b/examples/example-kkt-cholesky-regression/run_demo.sh new file mode 100755 index 0000000..beb4e19 --- /dev/null +++ b/examples/example-kkt-cholesky-regression/run_demo.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# Runs the 4-step regression demo end to end: +# 1) baseline 2) confirm stable 3) regress 4) recover +# Requires: Linux + LIKWID set up (see README.md). +# Usage: ./run_demo.sh [kkt_perftest.jl|clarabel_perftest.jl] +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")" + +RECIPE="${1:-kkt_perftest.jl}" +TOGGLE_LINE='const USE_FAST_FACTORIZATION = ' +THREADS="${SLURM_CPUS_PER_TASK:-${SLURM_JOB_CPUS_PER_NODE:-$(nproc)}}" + +case "$(uname -m)" in + x86_64|amd64) + JULIA="$JX86" + ;; + arm64|aarch64) + JULIA="$JARM" + ;; + *) + echo "Unsupported architecture: $(uname -m)" >&2 + exit 1 + ;; +esac + +set_toggle() { + sed -i.bak "s/^${TOGGLE_LINE}.*/${TOGGLE_LINE}${1}/" "$RECIPE" + rm -f "${RECIPE}.bak" +} + +run() { + echo "=== $1 (USE_FAST_FACTORIZATION=$(grep -o 'true\|false' <(grep "$TOGGLE_LINE" "$RECIPE"))) ===" + $JULIA --project=. --threads="$THREADS" -e 'using LIKWID, PerfTest; runperftests("'"$RECIPE"'")' +} + +set_toggle true +run "Step 1/4: establish baseline" +run "Step 2/4: confirm stable" + +set_toggle false +run "Step 3/4: introduce regression" + +set_toggle true +run "Step 4/4: recover" diff --git a/examples/example-llama-energy/LlamaFFI.jl b/examples/example-llama-energy/LlamaFFI.jl new file mode 100644 index 0000000..c43d62f --- /dev/null +++ b/examples/example-llama-energy/LlamaFFI.jl @@ -0,0 +1,475 @@ +""" + LlamaFFI + +Minimal, self-contained in-process `ccall` binding to a **CUDA-enabled** build of +`libllama` (llama.cpp). This is the layer that lets PerfTest.jl bracket real +`llama_decode` calls with NVML energy readings *in the same process as the tests*. + +WHY A CUSTOM BUILD? +------------------- +The registered `llama_cpp_jll` artifact ships **CPU-only** binaries (no +`libggml_cuda`, no CUDA dependency). To measure GPU energy of llama.cpp inference +you MUST build llama.cpp yourself with `-DGGML_CUDA=ON` and point this module at +the resulting `libllama.so` via the `LLAMA_LIB` environment variable +(see `build_llama_cuda.sh`). + +STATUS: PRELIMINARY DRAFT +------------------------- +This binding targets a recent llama.cpp C API (the `llama_model_load_from_file` / +`llama_init_from_model` generation, roughly late-2024/2025 API). The llama.cpp C +API and, especially, the *layout* of `llama_model_params` / `llama_context_params` +change across commits. The struct mirrors below MUST be verified against the exact +commit you build (`llama.h`). For a robust binding, regenerate with `Clang.jl` +against your pinned `llama.h`. The functions used here are intentionally a minimal +subset so that verification is quick. + +Greedy (argmax) decoding is implemented directly in Julia over the returned logits +so we do not depend on the (frequently changing) sampler-chain API. Greedy keeps +generation deterministic, which is important for a controlled energy study. +""" +module LlamaFFI + +using Libdl + +# --------------------------------------------------------------------------- +# Library handle +# --------------------------------------------------------------------------- + +const LIBLLAMA = Ref{String}("") +const LIBHANDLE = Ref{Ptr{Cvoid}}(C_NULL) + +""" + lib() + +Path to the CUDA-enabled `libllama`. Resolved from the `LLAMA_CPP_LIB` +environment variable the first time it is needed. Also caches the dlopen handle +so we can probe for version-dependent symbols with [`sym`](@ref). +""" +function lib() + if isempty(LIBLLAMA[]) + path = get(ENV, "LLAMA_LIB", "") + isempty(path) && error( + "Set LLAMA_LIB to your CUDA-enabled libllama (e.g. " * + "/path/to/llama.cpp/build/bin/libllama.so). See build_llama_cuda.sh.") + isfile(path) || error("LLAMA_LIB does not point to a file: $path") + # Load with RTLD_GLOBAL so the ggml/ggml-cuda backends resolve. + LIBHANDLE[] = Libdl.dlopen(path, Libdl.RTLD_LAZY | Libdl.RTLD_GLOBAL) + LIBLLAMA[] = path + end + return LIBLLAMA[] +end + +"Resolve a symbol pointer, or C_NULL if this llama.cpp build does not export it." +function sym(name::Symbol) + lib() + return Libdl.dlsym(LIBHANDLE[], name; throw_error=false) +end + +# llama_token is int32 +const LlamaToken = Int32 +const LlamaPos = Int32 +const LlamaSeqId = Int32 + +# --------------------------------------------------------------------------- +# Parameter structs (⚠ VERIFY LAYOUT AGAINST YOUR llama.h) +# --------------------------------------------------------------------------- +# These mirror the C structs so we can call the *_default_params() functions +# (which return by value) and then tweak individual fields. Field order and +# size must exactly match the header of the commit you build. + +struct LlamaModelParams + devices::Ptr{Cvoid} # ggml_backend_dev_t * + tensor_buft_overrides::Ptr{Cvoid} # const llama_model_tensor_buft_override * + n_gpu_layers::Cint + split_mode::Cint # enum llama_split_mode + load_mode::Cint # enum llama_load_mode + main_gpu::Cint + tensor_split::Ptr{Cfloat} + progress_callback::Ptr{Cvoid} + progress_callback_ud::Ptr{Cvoid} + kv_overrides::Ptr{Cvoid} + vocab_only::Bool + check_tensors::Bool + use_extra_bufts::Bool + no_host::Bool + no_alloc::Bool + load_mtp::Bool +end + +# enum llama_flash_attn_type +const LLAMA_FLASH_ATTN_TYPE_DISABLED = Cint(0) +const LLAMA_FLASH_ATTN_TYPE_ENABLED = Cint(1) + +struct LlamaContextParams + n_ctx::Cuint + n_batch::Cuint + n_ubatch::Cuint + n_seq_max::Cuint + n_rs_seq::Cuint + n_outputs_max::Cuint + n_threads::Cint + n_threads_batch::Cint + ctx_type::Cint # enum llama_context_type + rope_scaling_type::Cint + pooling_type::Cint + attention_type::Cint + flash_attn_type::Cint # enum llama_flash_attn_type + rope_freq_base::Cfloat + rope_freq_scale::Cfloat + yarn_ext_factor::Cfloat + yarn_attn_factor::Cfloat + yarn_beta_fast::Cfloat + yarn_beta_slow::Cfloat + yarn_orig_ctx::Cuint + defrag_thold::Cfloat + cb_eval::Ptr{Cvoid} + cb_eval_ud::Ptr{Cvoid} + type_k::Cint + type_v::Cint + abort_callback::Ptr{Cvoid} + abort_callback_data::Ptr{Cvoid} + embeddings::Bool + offload_kqv::Bool + no_perf::Bool + op_offload::Bool + swa_full::Bool + kv_unified::Bool + samplers::Ptr{Cvoid} # struct llama_sampler_seq_config * + n_samplers::Csize_t + ctx_other::Ptr{Cvoid} # struct llama_context * +end + +# llama_batch is isbits (all pointers), so it can be returned/passed by value. +struct LlamaBatch + n_tokens::Cint + token::Ptr{LlamaToken} + embd::Ptr{Cfloat} + pos::Ptr{LlamaPos} + n_seq_id::Ptr{Cint} + seq_id::Ptr{Ptr{LlamaSeqId}} + logits::Ptr{Int8} +end + +# --------------------------------------------------------------------------- +# Backend lifecycle +# --------------------------------------------------------------------------- + +backend_init() = ccall((:llama_backend_init, lib()), Cvoid, ()) +backend_free() = ccall((:llama_backend_free, lib()), Cvoid, ()) + +# --------------------------------------------------------------------------- +# Model / context +# --------------------------------------------------------------------------- + +model_default_params() = ccall((:llama_model_default_params, lib()), LlamaModelParams, ()) +context_default_params() = ccall((:llama_context_default_params, lib()), LlamaContextParams, ()) + +""" + load_model(path; n_gpu_layers=999) -> Ptr + +Load a GGUF model with the requested number of layers offloaded to the GPU. +`n_gpu_layers=999` means "offload everything". +""" +function load_model(path::AbstractString; n_gpu_layers::Integer=999) + p = model_default_params() + # mparams.split_mode = LLAMA_SPLIT_MODE_NONE; // don't spread model across GPUs + # mparams.main_gpu = 1; // use device index 1 only + # mparams.n_gpu_layers = 999; // offload all layers to that GPU + p = LlamaModelParams( + p.devices, p.tensor_buft_overrides, Cint(n_gpu_layers), Cint(0), p.load_mode, + Cint(0), p.tensor_split, p.progress_callback, p.progress_callback_ud, + p.kv_overrides, p.vocab_only, p.check_tensors, p.use_extra_bufts, p.no_host, + p.no_alloc, p.load_mtp) + m = ccall((:llama_model_load_from_file, lib()), Ptr{Cvoid}, (Cstring, LlamaModelParams), path, p) + m == C_NULL && error("Failed to load model: $path") + return m +end + +function new_context(model::Ptr{Cvoid}; n_ctx::Integer=4096, n_batch::Integer=2048, + flash_attn::Bool=true, n_threads::Integer=Sys.CPU_THREADS) + p = context_default_params() + p = LlamaContextParams( + Cuint(n_ctx), Cuint(n_batch), p.n_ubatch, p.n_seq_max, p.n_rs_seq, p.n_outputs_max, + Cint(n_threads), Cint(n_threads), p.ctx_type, p.rope_scaling_type, p.pooling_type, + p.attention_type, + flash_attn ? LLAMA_FLASH_ATTN_TYPE_ENABLED : LLAMA_FLASH_ATTN_TYPE_DISABLED, + p.rope_freq_base, p.rope_freq_scale, p.yarn_ext_factor, p.yarn_attn_factor, + p.yarn_beta_fast, p.yarn_beta_slow, p.yarn_orig_ctx, p.defrag_thold, + p.cb_eval, p.cb_eval_ud, p.type_k, p.type_v, p.abort_callback, p.abort_callback_data, + p.embeddings, p.offload_kqv, p.no_perf, p.op_offload, p.swa_full, p.kv_unified, + p.samplers, p.n_samplers, p.ctx_other) + ctx = ccall((:llama_init_from_model, lib()), Ptr{Cvoid}, (Ptr{Cvoid}, LlamaContextParams), model, p) + ctx == C_NULL && error("Failed to create context") + return ctx +end + +free_model(model::Ptr{Cvoid}) = ccall((:llama_model_free, lib()), Cvoid, (Ptr{Cvoid},), model) +free_context(ctx::Ptr{Cvoid}) = ccall((:llama_free, lib()), Cvoid, (Ptr{Cvoid},), ctx) + +get_vocab(model::Ptr{Cvoid}) = ccall((:llama_model_get_vocab, lib()), Ptr{Cvoid}, (Ptr{Cvoid},), model) +n_vocab(vocab::Ptr{Cvoid}) = Int(ccall((:llama_vocab_n_tokens, lib()), Cint, (Ptr{Cvoid},), vocab)) +model_size_bytes(model::Ptr{Cvoid}) = Int(ccall((:llama_model_size, lib()), UInt64, (Ptr{Cvoid},), model)) + +# --------------------------------------------------------------------------- +# Tokenization +# --------------------------------------------------------------------------- + +function tokenize(vocab::Ptr{Cvoid}, text::AbstractString; add_special::Bool=true, + parse_special::Bool=true) + cap = ncodeunits(text) + 16 + toks = Vector{LlamaToken}(undef, cap) + n = ccall((:llama_tokenize, lib()), Cint, + (Ptr{Cvoid}, Cstring, Cint, Ptr{LlamaToken}, Cint, Bool, Bool), + vocab, text, ncodeunits(text), toks, cap, add_special, parse_special) + n < 0 && error("tokenize: buffer too small (needed $(-n))") + return toks[1:n] +end + +is_eog(vocab::Ptr{Cvoid}, tok::LlamaToken) = + ccall((:llama_vocab_is_eog, lib()), Bool, (Ptr{Cvoid}, LlamaToken), vocab, tok) + +# --------------------------------------------------------------------------- +# Decode helpers +# --------------------------------------------------------------------------- + +# batch containing a contiguous run of tokens for a single sequence, starting at +# position `pos0`, only the last token's logits requested if `logits_last`. +batch_get_one(tokens::Vector{LlamaToken}) = + ccall((:llama_batch_get_one, lib()), LlamaBatch, (Ptr{LlamaToken}, Cint), + tokens, Cint(length(tokens))) + +function decode!(ctx::Ptr{Cvoid}, batch::LlamaBatch) + rc = ccall((:llama_decode, lib()), Cint, (Ptr{Cvoid}, LlamaBatch), ctx, batch) + rc != 0 && error("llama_decode failed: rc=$rc") + return nothing +end + +# logits for the i-th token of the last batch (-1 == last token) +function logits_ith(ctx::Ptr{Cvoid}, i::Integer, nvoc::Integer) + p = ccall((:llama_get_logits_ith, lib()), Ptr{Cfloat}, (Ptr{Cvoid}, Cint), ctx, Cint(i)) + p == C_NULL && error("llama_get_logits_ith returned NULL") + return unsafe_wrap(Array, p, nvoc) +end + +argmax_token(logits::AbstractVector{<:Real}) = LlamaToken(argmax(logits) - 1) + +# --------------------------------------------------------------------------- +# High-level: a controlled prefill + decode split +# --------------------------------------------------------------------------- + +""" + Session + +Holds a loaded model + context and cached vocab size. Create once per +quantization level, reuse for warmup + measurement runs. +""" +mutable struct Session + model::Ptr{Cvoid} + ctx::Ptr{Cvoid} + vocab::Ptr{Cvoid} + nvoc::Int +end + +binit = false + +function open_session(gguf_path::AbstractString; n_gpu_layers=999, n_ctx=4096, + flash_attn=true) + backend_init() + model = load_model(gguf_path; n_gpu_layers=n_gpu_layers) + ctx = new_context(model; n_ctx=n_ctx, flash_attn=flash_attn) + vocab = get_vocab(model) + return Session(model, ctx, vocab, n_vocab(vocab)) +end + +function close_session(s::Session) + free_context(s.ctx) + free_model(s.model) + backend_free() + return nothing +end + +# --------------------------------------------------------------------------- +# State reset (⚠ API name varies across llama.cpp versions) +# --------------------------------------------------------------------------- +# Clearing the KV cache is what makes generation idempotent: without it, each +# decode run continues from the previous run's state and eventually overflows +# n_ctx. The clearing entry point has been renamed several times: +# newest : llama_get_memory(ctx) + llama_memory_clear(mem, data) +# older : llama_kv_self_clear(ctx) +# oldest : llama_kv_cache_clear(ctx) +# We resolve whichever the built library exports. +const _RESET_KIND = Ref{Symbol}(:unresolved) + +function _resolve_reset() + if sym(:llama_get_memory) != C_NULL && sym(:llama_memory_clear) != C_NULL + _RESET_KIND[] = :memory + elseif sym(:llama_kv_self_clear) != C_NULL + _RESET_KIND[] = :kv_self + elseif sym(:llama_kv_cache_clear) != C_NULL + _RESET_KIND[] = :kv_cache + else + error("No known KV-cache clear symbol found in libllama; check your version.") + end + return _RESET_KIND[] +end + +""" + reset!(s) + +Clear the context KV cache so the next `prefill!`/`decode_n!` starts from a +clean state. This is the key to idempotent, repeatable measurements. +""" +function reset!(s::Session) + _RESET_KIND[] == :unresolved && _resolve_reset() + if _RESET_KIND[] == :memory + mem = ccall((:llama_get_memory, lib()), Ptr{Cvoid}, (Ptr{Cvoid},), s.ctx) + ccall((:llama_memory_clear, lib()), Cvoid, (Ptr{Cvoid}, Bool), mem, true) + elseif _RESET_KIND[] == :kv_self + ccall((:llama_kv_self_clear, lib()), Cvoid, (Ptr{Cvoid},), s.ctx) + else + ccall((:llama_kv_cache_clear, lib()), Cvoid, (Ptr{Cvoid},), s.ctx) + end + return nothing +end + +# --------------------------------------------------------------------------- +# Model/context free (⚠ API name for model-free also varies across versions) +# --------------------------------------------------------------------------- +# newer : llama_model_free(model) +# older : llama_free_model(model) +const _MODEL_FREE_KIND = Ref{Symbol}(:unresolved) + +function _resolve_model_free() + if sym(:llama_model_free) != C_NULL + _MODEL_FREE_KIND[] = :new + elseif sym(:llama_free_model) != C_NULL + _MODEL_FREE_KIND[] = :old + else + error("No known model-free symbol found in libllama; check your version.") + end + return _MODEL_FREE_KIND[] +end + +""" + destroy!(s::Session) + +Free the context (KV cache + compute buffers) and the model (tensor weight +buffers) that were allocated on the GPU for this Session. `reset!` alone only +clears KV-cache *contents*; it never releases the VRAM allocations, which is +why memory climbs across models unless this is called too. + +`s.vocab` is *not* freed here — it's a pointer owned by the model +(`llama_model_get_vocab`), not a separate allocation, and becomes invalid +automatically once `s.model` is freed. + +Safe to call multiple times; no-ops once fields are already null. +""" +function destroy!(s::Session) + # Context first — must be freed before the model it references. + if s.ctx != C_NULL + ccall((:llama_free, lib()), Cvoid, (Ptr{Cvoid},), s.ctx) + s.ctx = C_NULL + end + + if s.model != C_NULL + _MODEL_FREE_KIND[] == :unresolved && _resolve_model_free() + if _MODEL_FREE_KIND[] == :new + ccall((:llama_model_free, lib()), Cvoid, (Ptr{Cvoid},), s.model) + else + ccall((:llama_free_model, lib()), Cvoid, (Ptr{Cvoid},), s.model) + end + s.model = C_NULL + end + + # vocab pointer is borrowed from the model — just null it out, don't free. + s.vocab = C_NULL + s.nvoc = 0 + + GC.gc() # drop any lingering Julia-side refs before the next model loads + + return nothing +end + + +""" + prefill!(s, prompt) -> (last_token, n_prompt_tokens) + +Run the prompt through the model in a single batch (the "prefill" / prompt +processing phase). Returns the greedily-selected first generated token and the +number of prompt tokens. + +NOTE: this is a **stateful** primitive — it appends to the KV cache. Call +[`reset!`](@ref) first if you need a clean state. For measurement targets use +the idempotent [`generate!`](@ref) / [`prefill_only!`](@ref) instead. +""" +function prefill!(s::Session, prompt::AbstractString) + toks = tokenize(s.vocab, prompt) + decode!(s.ctx, batch_get_one(toks)) + next = argmax_token(logits_ith(s.ctx, -1, s.nvoc)) + return next, length(toks) +end + +""" + decode_n!(s, first_token, n) -> n_generated + +Autoregressively generate up to `n` tokens starting from `first_token` +(greedy), stopping early on EOG. + +NOTE: **stateful** — advances the KV cache. Not idempotent on its own; use it +via [`generate!`](@ref) for repeatable measurements. +""" +function decode_n!(s::Session, first_token::LlamaToken, n::Integer) + tok = first_token + generated = 0 + scratch = LlamaToken[0] + for _ in 1:n + is_eog(s.vocab, tok) && break + generated += 1 + scratch[1] = tok + decode!(s.ctx, batch_get_one(scratch)) + tok = argmax_token(logits_ith(s.ctx, -1, s.nvoc)) + end + return generated +end + +# --------------------------------------------------------------------------- +# Idempotent measurement targets +# --------------------------------------------------------------------------- +# These reset the KV cache at the start of every call, so they can be safely +# invoked many times (BenchmarkTools samples/evals) AND once more by the energy +# probe, each starting from an identical state. This is why the recipe needs no +# @perftest setup/teardown: idempotency is built into the target. +# +# IMPORTANT: the current PerfTest CUDA energy path measures the target ONCE, +# with no setup/teardown, and AFTER the timing loop. A `@perftest setup=...` +# would therefore NOT reset state for the energy measurement. Making the target +# self-resetting is the robust way to keep both the timing and energy runs +# consistent until the extension gains setup/teardown support around the probe. + +""" + generate!(s, prompt, n_gen) -> n_generated + +Idempotent full request: clear KV cache, prefill `prompt`, then greedily decode +up to `n_gen` tokens. Safe to call repeatedly. This is the primary measured +target; whole-request energy divided by `n_generated` gives Joules per token. +""" +function generate!(s::Session, prompt::AbstractString, n_gen::Integer) + reset!(s) + first_tok, _ = prefill!(s, prompt) + return decode_n!(s, first_tok, n_gen) +end + +""" + prefill_only!(s, prompt) -> n_prompt_tokens + +Idempotent prefill: clear KV cache and process the prompt only. Measure this as +a second target to isolate prefill energy, so decode energy ≈ generate! energy − +prefill_only! energy. +""" +function prefill_only!(s::Session, prompt::AbstractString) + reset!(s) + _, n_prompt = prefill!(s, prompt) + return n_prompt +end + +end # module diff --git a/examples/example-llama-energy/LocalPreferences.toml b/examples/example-llama-energy/LocalPreferences.toml new file mode 100644 index 0000000..97163f6 --- /dev/null +++ b/examples/example-llama-energy/LocalPreferences.toml @@ -0,0 +1,3 @@ +[CUDA_Runtime_jll] +__clear__ = ["version"] +local = "true" diff --git a/examples/example-llama-energy/Manifest.toml b/examples/example-llama-energy/Manifest.toml new file mode 100644 index 0000000..4b32708 --- /dev/null +++ b/examples/example-llama-energy/Manifest.toml @@ -0,0 +1,1099 @@ +# This file is machine-generated - editing it directly is not advised + +julia_version = "1.10.10" +manifest_format = "2.0" +project_hash = "c44aeef04bb61bcd5a26532b2912306fcda68e25" + +[[deps.AMDGPU]] +deps = ["AbstractFFTs", "AcceleratedKernels", "Adapt", "Atomix", "CEnum", "ExprTools", "GPUArrays", "GPUCompiler", "GPUToolbox", "KernelAbstractions", "LLD_jll", "LLVM", "LLVM_jll", "Libdl", "LinearAlgebra", "Pkg", "Preferences", "PrettyTables", "Printf", "ROCmDeviceLibs_jll", "Random", "Random123", "RandomNumbers", "SparseArrays", "SpecialFunctions", "StaticArraysCore", "Statistics", "UnsafeAtomics"] +git-tree-sha1 = "83ba9288a975f5e6f620e3f392d04d660b2decfe" +uuid = "21141c5a-9bdb-4563-92ae-f87d6854732e" +version = "2.1.0" + + [deps.AMDGPU.extensions] + AMDGPUChainRulesCoreExt = "ChainRulesCore" + AMDGPUEnzymeCoreExt = "EnzymeCore" + + [deps.AMDGPU.weakdeps] + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + EnzymeCore = "f151be2c-9106-41f4-ab19-57ee4f262869" + +[[deps.AbstractFFTs]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "d92ad398961a3ed262d8bf04a1a2b8340f915fef" +uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c" +version = "1.5.0" + + [deps.AbstractFFTs.extensions] + AbstractFFTsChainRulesCoreExt = "ChainRulesCore" + AbstractFFTsTestExt = "Test" + + [deps.AbstractFFTs.weakdeps] + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" + +[[deps.AcceleratedKernels]] +deps = ["ArgCheck", "GPUArraysCore", "KernelAbstractions", "Markdown", "UnsafeAtomics"] +git-tree-sha1 = "0de01460ed11e90b42ce666c8ed0265bad59aa6a" +uuid = "6a4ca0a5-0e36-4168-a932-d9be78d558f1" +version = "0.4.3" + + [deps.AcceleratedKernels.extensions] + AcceleratedKernelsoneAPIExt = "oneAPI" + + [deps.AcceleratedKernels.weakdeps] + oneAPI = "8f75cd03-7ff8-4ecb-9b8f-daf728133b1b" + +[[deps.Adapt]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "daa72978cd7a624246e894a4f4f067706d4e17e2" +uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e" +version = "4.7.0" +weakdeps = ["SparseArrays", "StaticArrays"] + + [deps.Adapt.extensions] + AdaptSparseArraysExt = "SparseArrays" + AdaptStaticArraysExt = "StaticArrays" + +[[deps.AliasTables]] +deps = ["PtrArrays", "Random"] +git-tree-sha1 = "9876e1e164b144ca45e9e3198d0b689cadfed9ff" +uuid = "66dad0bd-aa9a-41b7-9441-69ab47430ed8" +version = "1.1.3" + +[[deps.ArgCheck]] +git-tree-sha1 = "f9e9a66c9b7be1ad7372bbd9b062d9230c30c5ce" +uuid = "dce04be8-c92d-5529-be00-80e4d2c0e197" +version = "2.5.0" + +[[deps.ArgTools]] +uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f" +version = "1.1.1" + +[[deps.Artifacts]] +uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" + +[[deps.Atomix]] +deps = ["UnsafeAtomics"] +git-tree-sha1 = "b8651b2eb5796a386b0398a20b519a6a6150f75c" +uuid = "a9b6321e-bd34-4604-b9c9-b65b8de01458" +version = "1.1.3" + + [deps.Atomix.extensions] + AtomixCUDAExt = "CUDA" + AtomixMetalExt = "Metal" + AtomixOpenCLExt = "OpenCL" + AtomixoneAPIExt = "oneAPI" + + [deps.Atomix.weakdeps] + CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" + Metal = "dde4c033-4e86-420c-a63e-0dd931031962" + OpenCL = "08131aa3-fb12-5dee-8b74-c09406e224a2" + oneAPI = "8f75cd03-7ff8-4ecb-9b8f-daf728133b1b" + +[[deps.BFloat16s]] +deps = ["LinearAlgebra", "Printf", "Random"] +git-tree-sha1 = "3b642331600250f592719140c60cf12372b82d66" +uuid = "ab4f0b2a-ad5b-11e8-123f-65d77653426b" +version = "0.5.1" + +[[deps.BandwidthBenchmark]] +deps = ["DataFrames", "PrettyTables", "Printf", "Requires", "Statistics", "ThreadPinning"] +git-tree-sha1 = "6b0c18db2cdb386e332cedac2f9fcaf85ab757d2" +uuid = "68eb07c1-04fd-4e62-9736-d6127c4c03c6" +version = "0.2.0" + +[[deps.Base64]] +uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" + +[[deps.BenchmarkTools]] +deps = ["Compat", "JSON", "Logging", "PrecompileTools", "Printf", "Profile", "Statistics", "UUIDs"] +git-tree-sha1 = "9670d3febc2b6da60a0ae57846ba74670290653f" +uuid = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" +version = "1.8.0" + +[[deps.BitFlags]] +git-tree-sha1 = "bbe1079eecf9c9fbb52765193ad2bae27ae09bc8" +uuid = "d1d4a3ce-64b1-5f1a-9ba4-7e7e69966f35" +version = "0.1.10" + +[[deps.CEnum]] +git-tree-sha1 = "389ad5c84de1ae7cf0e28e381131c98ea87d54fc" +uuid = "fa961155-64e5-5f13-b03f-caf6b980ea82" +version = "0.5.0" + +[[deps.CUDA]] +deps = ["AbstractFFTs", "Adapt", "BFloat16s", "CEnum", "CUDA_Compiler_jll", "CUDA_Driver_jll", "CUDA_Runtime_Discovery", "CUDA_Runtime_jll", "Crayons", "DataFrames", "ExprTools", "GPUArrays", "GPUCompiler", "GPUToolbox", "KernelAbstractions", "LLVM", "LLVMLoopInfo", "LazyArtifacts", "Libdl", "LinearAlgebra", "Logging", "NVTX", "Preferences", "PrettyTables", "Printf", "Random", "Random123", "RandomNumbers", "Reexport", "Requires", "SparseArrays", "StaticArrays", "Statistics", "demumble_jll"] +git-tree-sha1 = "224c078c40f7cbd98f393d1722953f3a7f24a3ca" +uuid = "052768ef-5323-5732-b1bb-66c8b64840ba" +version = "5.8.5" + + [deps.CUDA.extensions] + ChainRulesCoreExt = "ChainRulesCore" + EnzymeCoreExt = "EnzymeCore" + SparseMatricesCSRExt = "SparseMatricesCSR" + SpecialFunctionsExt = "SpecialFunctions" + + [deps.CUDA.weakdeps] + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + EnzymeCore = "f151be2c-9106-41f4-ab19-57ee4f262869" + SparseMatricesCSR = "a0a7dd2c-ebf4-11e9-1f05-cf50bc540ca1" + SpecialFunctions = "276daf66-3868-5448-9aa4-cd146d93841b" + +[[deps.CUDA_Compiler_jll]] +deps = ["Artifacts", "CUDA_Driver_jll", "CUDA_Runtime_jll", "JLLWrappers", "LazyArtifacts", "Libdl", "TOML"] +git-tree-sha1 = "68bac021c5d511fe39c2f4306cc9623a6626dbb4" +uuid = "d1e2174e-dfdc-576e-b43e-73b79eb1aca8" +version = "0.2.2+0" + +[[deps.CUDA_Driver_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "TOML"] +git-tree-sha1 = "ff4a0abf98be36d9fa15ca7e968df562a210ab4b" +uuid = "4ee394cb-3365-5eb0-8335-949819d2adfc" +version = "13.3.0+1" + +[[deps.CUDA_Runtime_Discovery]] +deps = ["Libdl"] +git-tree-sha1 = "f9a521f52d236fe49f1028d69e549e7f2644bb72" +uuid = "1af6417a-86b4-443c-805f-a4643ffb695f" +version = "1.0.0" + +[[deps.CUDA_Runtime_jll]] +deps = ["Artifacts", "CUDA_Driver_jll", "JLLWrappers", "LazyArtifacts", "Libdl", "TOML"] +git-tree-sha1 = "92cd84e2b760e471d647153ea5efc5789fc5e8b2" +uuid = "76a88914-d11a-5bdc-97e0-2f5a05c973a2" +version = "0.19.2+0" + +[[deps.Cassette]] +git-tree-sha1 = "f8764df8d9d2aec2812f009a1ac39e46c33354b8" +uuid = "7057c7e9-c182-5462-911a-8362d720325c" +version = "0.3.14" + +[[deps.ChunkCodecCore]] +git-tree-sha1 = "1a3ad7e16a321667698a19e77362b35a1e94c544" +uuid = "0b6fb165-00bc-4d37-ab8b-79f91016dbe1" +version = "1.0.1" + +[[deps.ChunkCodecLibZlib]] +deps = ["ChunkCodecCore", "Zlib_jll"] +git-tree-sha1 = "d4101e848e8d3f585d61d244c2fe0c80a70e6b3b" +uuid = "4c0bbee4-addc-4d73-81a0-b6caacae83c8" +version = "1.1.0" + +[[deps.ChunkCodecLibZstd]] +deps = ["ChunkCodecCore", "Zstd_jll"] +git-tree-sha1 = "34d9873079e4cb3d0c62926a225136824677073f" +uuid = "55437552-ac27-4d47-9aa3-63184e8fd398" +version = "1.0.0" + +[[deps.CodecZlib]] +deps = ["TranscodingStreams", "Zlib_jll"] +git-tree-sha1 = "962834c22b66e32aa10f7611c08c8ca4e20749a9" +uuid = "944b1d66-785c-5afd-91f1-9de20f533193" +version = "0.7.8" + +[[deps.ColorSchemes]] +deps = ["ColorTypes", "ColorVectorSpace", "Colors", "FixedPointNumbers", "PrecompileTools", "Random"] +git-tree-sha1 = "b0fd3f56fa442f81e0a47815c92245acfaaa4e34" +uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4" +version = "3.31.0" + +[[deps.ColorTypes]] +deps = ["FixedPointNumbers", "Random"] +git-tree-sha1 = "67e11ee83a43eb71ddc950302c53bf33f0690dfe" +uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f" +version = "0.12.1" + + [deps.ColorTypes.extensions] + StyledStringsExt = "StyledStrings" + + [deps.ColorTypes.weakdeps] + StyledStrings = "f489334b-da3d-4c2e-b8f0-e476e12c162b" + +[[deps.ColorVectorSpace]] +deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "Requires", "Statistics", "TensorCore"] +git-tree-sha1 = "8b3b6f87ce8f65a2b4f857528fd8d70086cd72b1" +uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4" +version = "0.11.0" +weakdeps = ["SpecialFunctions"] + + [deps.ColorVectorSpace.extensions] + SpecialFunctionsExt = "SpecialFunctions" + +[[deps.Colors]] +deps = ["ColorTypes", "FixedPointNumbers", "Reexport"] +git-tree-sha1 = "37ea44092930b1811e666c3bc38065d7d87fcc74" +uuid = "5ae59095-9a9b-59fe-a467-6f913c188581" +version = "0.13.1" + +[[deps.Compat]] +deps = ["TOML", "UUIDs"] +git-tree-sha1 = "9d8a54ce4b17aa5bdce0ea5c34bc5e7c340d16ad" +uuid = "34da2185-b29b-5c13-b0c7-acf172513d20" +version = "4.18.1" +weakdeps = ["Dates", "LinearAlgebra"] + + [deps.Compat.extensions] + CompatLinearAlgebraExt = "LinearAlgebra" + +[[deps.CompilerSupportLibraries_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae" +version = "1.1.1+0" + +[[deps.ConcurrentUtilities]] +deps = ["Serialization", "Sockets"] +git-tree-sha1 = "21d088c496ea22914fe80906eb5bce65755e5ec8" +uuid = "f0e56b4a-5159-44fe-b623-3e5288b988bb" +version = "2.5.1" + +[[deps.Configurations]] +deps = ["ExproniconLite", "OrderedCollections", "TOML"] +git-tree-sha1 = "4358750bb58a3caefd5f37a4a0c5bfdbbf075252" +uuid = "5218b696-f38b-4ac9-8b61-a12ec717816d" +version = "0.17.6" + +[[deps.Contour]] +git-tree-sha1 = "439e35b0b36e2e5881738abc8857bd92ad6ff9a8" +uuid = "d38c429a-6771-53c6-b99e-75d170b6e991" +version = "0.6.3" + +[[deps.CountFlops]] +deps = ["Cassette"] +git-tree-sha1 = "3d4b4b334a3a78d1339e4ab2878c688233a469aa" +uuid = "1db9610d-79e1-487a-8d40-77f3295c7593" +version = "0.1.0" + +[[deps.Crayons]] +git-tree-sha1 = "54b76cbb40d9a0f5368c880725b2f141da77c94f" +uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f" +version = "4.2.0" + +[[deps.DataAPI]] +git-tree-sha1 = "abe83f3a2f1b857aac70ef8b269080af17764bbe" +uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a" +version = "1.16.0" + +[[deps.DataFrames]] +deps = ["Compat", "DataAPI", "DataStructures", "Future", "InlineStrings", "InvertedIndices", "IteratorInterfaceExtensions", "LinearAlgebra", "Markdown", "Missings", "PooledArrays", "PrecompileTools", "PrettyTables", "Printf", "Random", "Reexport", "SentinelArrays", "SortingAlgorithms", "Statistics", "TableTraits", "Tables", "Unicode"] +git-tree-sha1 = "5fab31e2e01e70ad66e3e24c968c264d1cf166d6" +uuid = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0" +version = "1.8.2" + +[[deps.DataStructures]] +deps = ["OrderedCollections"] +git-tree-sha1 = "b0bc6d2cad1fed8b7fd59a1551a991cb3d2809e6" +uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8" +version = "0.19.6" + +[[deps.DataValueInterfaces]] +git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6" +uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464" +version = "1.0.0" + +[[deps.Dates]] +deps = ["Printf"] +uuid = "ade2ca70-3891-5945-98fb-dc099432e06a" + +[[deps.DelimitedFiles]] +deps = ["Mmap"] +git-tree-sha1 = "9e2f36d3c96a820c678f2f1f1782582fcf685bae" +uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab" +version = "1.9.1" + +[[deps.DocStringExtensions]] +git-tree-sha1 = "7442a5dfe1ebb773c29cc2962a8980f47221d76c" +uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae" +version = "0.9.5" + +[[deps.Downloads]] +deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"] +uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6" +version = "1.6.0" + +[[deps.ExceptionUnwrapping]] +deps = ["Test"] +git-tree-sha1 = "d36f682e590a83d63d1c7dbd287573764682d12a" +uuid = "460bff9d-24e4-43bc-9d9f-a8973cb893f4" +version = "0.1.11" + +[[deps.ExprTools]] +git-tree-sha1 = "d2e49e7efd29719d6f28b891b0e0e159daa9d2b4" +uuid = "e2ba6199-217a-4e67-a87a-7c52f15ade04" +version = "0.1.11" + +[[deps.ExproniconLite]] +git-tree-sha1 = "c13f0b150373771b0fdc1713c97860f8df12e6c2" +uuid = "55351af7-c7e9-48d6-89ff-24e801d99491" +version = "0.10.14" + +[[deps.FileIO]] +deps = ["Pkg", "Requires", "UUIDs"] +git-tree-sha1 = "6621fef488e496356c9c9625d0562c12a6070819" +uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549" +version = "1.20.0" +weakdeps = ["HTTP"] + + [deps.FileIO.extensions] + HTTPExt = "HTTP" + +[[deps.FileWatching]] +uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee" + +[[deps.FixedPointNumbers]] +deps = ["Random", "Statistics"] +git-tree-sha1 = "59af96b98217c6ef4ae0dfe065ac7c20831d1a84" +uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93" +version = "0.8.6" + +[[deps.Future]] +deps = ["Random"] +uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820" + +[[deps.GPUArrays]] +deps = ["Adapt", "GPUArraysCore", "KernelAbstractions", "LLVM", "LinearAlgebra", "Printf", "Random", "Reexport", "ScopedValues", "Serialization", "SparseArrays", "Statistics"] +git-tree-sha1 = "4ea5e2aecfd52e595ff6c343410e32f83f5b9bbf" +uuid = "0c68f7d7-f131-5f86-a1c3-88cf8149b2d7" +version = "11.5.8" +weakdeps = ["JLD2"] + + [deps.GPUArrays.extensions] + JLD2Ext = "JLD2" + +[[deps.GPUArraysCore]] +deps = ["Adapt"] +git-tree-sha1 = "83cf05ab16a73219e5f6bd1bdfa9848fa24ac627" +uuid = "46192b85-c4d5-4398-a991-12ede77f4527" +version = "0.2.0" + +[[deps.GPUCompiler]] +deps = ["ExprTools", "InteractiveUtils", "LLVM", "Libdl", "Logging", "PrecompileTools", "Preferences", "Scratch", "Serialization", "TOML", "Tracy", "UUIDs"] +git-tree-sha1 = "b863a2e71f89328e2af69069490aec2448106e59" +uuid = "61eb1bfa-7361-4325-ad38-22787b887f55" +version = "1.17.1" + + [deps.GPUCompiler.weakdeps] + LLVMDowngrader_jll = "f52de702-fb25-5922-94ba-81dd59b07444" + +[[deps.GPUToolbox]] +deps = ["LLVM"] +git-tree-sha1 = "5bfe837129bf49e2e049b4f1517546055cc16a93" +uuid = "096a3bc2-3ced-46d0-87f4-dd12716f4bfc" +version = "0.3.0" + +[[deps.HTTP]] +deps = ["Base64", "CodecZlib", "ConcurrentUtilities", "Dates", "ExceptionUnwrapping", "Logging", "LoggingExtras", "MbedTLS", "NetworkOptions", "OpenSSL", "PrecompileTools", "Random", "SimpleBufferStream", "Sockets", "URIs", "UUIDs"] +git-tree-sha1 = "51059d23c8bb67911a2e6fd5130229113735fc7e" +uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3" +version = "1.11.0" + +[[deps.HashArrayMappedTries]] +git-tree-sha1 = "2eaa69a7cab70a52b9687c8bf950a5a93ec895ae" +uuid = "076d061b-32b6-4027-95e0-9a2c6f6d7e74" +version = "0.2.0" + +[[deps.Hwloc]] +deps = ["CEnum", "Hwloc_jll", "Printf"] +git-tree-sha1 = "6a3d80f31ff87bc94ab22a7b8ec2f263f9a6a583" +uuid = "0e44f5e4-bd66-52a0-8798-143a42290a1d" +version = "3.3.0" + + [deps.Hwloc.extensions] + HwlocTrees = "AbstractTrees" + + [deps.Hwloc.weakdeps] + AbstractTrees = "1520ce14-60c1-5f80-bbc7-55ef81b5835c" + +[[deps.Hwloc_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "XML2_jll", "Xorg_libpciaccess_jll"] +git-tree-sha1 = "c35847ca5b4997fc8418836354a56c459bcf48d8" +uuid = "e33a78d0-f292-5ffc-b300-72abe9b543c8" +version = "2.14.0+0" + +[[deps.InlineStrings]] +git-tree-sha1 = "8f3d257792a522b4601c24a577954b0a8cd7334d" +uuid = "842dd82b-1e85-43dc-bf29-5d0ee9dffc48" +version = "1.4.5" + + [deps.InlineStrings.extensions] + ArrowTypesExt = "ArrowTypes" + ParsersExt = "Parsers" + + [deps.InlineStrings.weakdeps] + ArrowTypes = "31f734f8-188a-4ce0-8406-c8a06bd891cd" + Parsers = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" + +[[deps.InteractiveUtils]] +deps = ["Markdown"] +uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240" + +[[deps.InvertedIndices]] +git-tree-sha1 = "6da3c4316095de0f5ee2ebd875df8721e7e0bdbe" +uuid = "41ab1584-1d38-5bbf-9106-f11c6c58b48f" +version = "1.3.1" + +[[deps.IrrationalConstants]] +git-tree-sha1 = "b2d91fe939cae05960e760110b328288867b5758" +uuid = "92d709cd-6900-40b7-9082-c6be49f344b6" +version = "0.2.6" + +[[deps.IteratorInterfaceExtensions]] +git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856" +uuid = "82899510-4779-5014-852e-03e436cf321d" +version = "1.0.0" + +[[deps.JLD2]] +deps = ["ChunkCodecLibZlib", "ChunkCodecLibZstd", "FileIO", "MacroTools", "Mmap", "OrderedCollections", "PrecompileTools", "ScopedValues"] +git-tree-sha1 = "9ebadf3f8f0de07031359917549bbdadc23f5dc3" +uuid = "033835bb-8acc-5ee8-8aae-3f567f8a3819" +version = "0.6.5" + + [deps.JLD2.extensions] + UnPackExt = "UnPack" + + [deps.JLD2.weakdeps] + UnPack = "3a884ed6-31ef-47d7-9d2a-63182c4928ed" + +[[deps.JLLWrappers]] +deps = ["Artifacts", "Preferences"] +git-tree-sha1 = "7204148362dafe5fe6a273f855b8ccbe4df8173e" +uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210" +version = "1.8.0" + +[[deps.JSON]] +deps = ["Dates", "Mmap", "Parsers", "Unicode"] +git-tree-sha1 = "31e996f0a15c7b280ba9f76636b3ff9e2ae58c9a" +uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" +version = "0.21.4" + +[[deps.JuliaNVTXCallbacks_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"] +git-tree-sha1 = "af433a10f3942e882d3c671aacb203e006a5808f" +uuid = "9c1d0b0a-7046-5b2e-a33f-ea22f176ac7e" +version = "0.2.1+0" + +[[deps.KernelAbstractions]] +deps = ["Adapt", "Atomix", "InteractiveUtils", "MacroTools", "PrecompileTools", "Requires", "StaticArrays", "UUIDs"] +git-tree-sha1 = "a5b87110fa95d711355af44832497745aa93fb52" +uuid = "63c18a36-062a-441e-b654-da1e3ab1ce7c" +version = "0.9.42" + + [deps.KernelAbstractions.extensions] + EnzymeExt = "EnzymeCore" + LinearAlgebraExt = "LinearAlgebra" + SparseArraysExt = "SparseArrays" + + [deps.KernelAbstractions.weakdeps] + EnzymeCore = "f151be2c-9106-41f4-ab19-57ee4f262869" + LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" + SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" + +[[deps.LIKWID]] +deps = ["CEnum", "Libdl", "OrderedCollections", "PrettyTables", "Unitful"] +git-tree-sha1 = "b21dcbf20aca355bd2e1039d9731dd1d879cc0d4" +uuid = "bf22376a-e803-4184-b2ed-56326e3bff83" +version = "0.4.5" + +[[deps.LLD_jll]] +deps = ["Artifacts", "Libdl", "Zlib_jll", "libLLVM_jll"] +uuid = "d55e3150-da41-5e91-b323-ecfd1eec6109" +version = "15.0.7+10" + +[[deps.LLVM]] +deps = ["CEnum", "LLVMExtra_jll", "Libdl", "PrecompileTools", "Preferences", "Printf", "Unicode"] +git-tree-sha1 = "39c054c8fd8cef1d405ba7e399d70710fdbae46c" +uuid = "929cbde3-209d-540e-8aea-75f648917ca0" +version = "9.11.0" +weakdeps = ["BFloat16s"] + + [deps.LLVM.extensions] + BFloat16sExt = "BFloat16s" + +[[deps.LLVMExtra_jll]] +deps = ["Artifacts", "JLLWrappers", "LazyArtifacts", "Libdl", "TOML"] +git-tree-sha1 = "8886105e8ed2aa53062ae99870840a1e3622aaac" +uuid = "dad2f222-ce93-54a1-a47d-0025e8a3acab" +version = "0.0.44+0" + +[[deps.LLVMLoopInfo]] +git-tree-sha1 = "2e5c102cfc41f48ae4740c7eca7743cc7e7b75ea" +uuid = "8b046642-f1f6-4319-8d3c-209ddc03c586" +version = "1.0.0" + +[[deps.LLVM_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "TOML", "Zlib_jll", "libLLVM_jll"] +git-tree-sha1 = "3b5a33517a862d32562658f9186838616b09f753" +uuid = "86de99a1-58d6-5da7-8064-bd56ce2e322c" +version = "15.0.7+13" + +[[deps.LaTeXStrings]] +git-tree-sha1 = "dda21b8cbd6a6c40d9d02a73230f9d70fed6918c" +uuid = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f" +version = "1.4.0" + +[[deps.LazyArtifacts]] +deps = ["Artifacts", "Pkg"] +uuid = "4af54fe1-eca0-43a8-85a7-787d91b784e3" + +[[deps.LibCURL]] +deps = ["LibCURL_jll", "MozillaCACerts_jll"] +uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21" +version = "0.6.4" + +[[deps.LibCURL_jll]] +deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"] +uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0" +version = "8.4.0+0" + +[[deps.LibGit2]] +deps = ["Base64", "LibGit2_jll", "NetworkOptions", "Printf", "SHA"] +uuid = "76f85450-5226-5b5a-8eaa-529ad045b433" + +[[deps.LibGit2_jll]] +deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll"] +uuid = "e37daf67-58a4-590a-8e99-b0245dd2ffc5" +version = "1.6.4+0" + +[[deps.LibSSH2_jll]] +deps = ["Artifacts", "Libdl", "MbedTLS_jll"] +uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8" +version = "1.11.0+1" + +[[deps.LibTracyClient_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "d4e20500d210247322901841d4eafc7a0c52642d" +uuid = "ad6e5548-8b26-5c9f-8ef3-ef0ad883f3a5" +version = "0.13.1+0" + +[[deps.Libdl]] +uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb" + +[[deps.Libiconv_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "be484f5c92fad0bd8acfef35fe017900b0b73809" +uuid = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531" +version = "1.18.0+0" + +[[deps.LinearAlgebra]] +deps = ["Libdl", "OpenBLAS_jll", "libblastrampoline_jll"] +uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" + +[[deps.LogExpFunctions]] +deps = ["DocStringExtensions", "IrrationalConstants", "LinearAlgebra"] +git-tree-sha1 = "bba2d9aa057d8f126415de240573e86a8f39d2a1" +uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688" +version = "1.0.1" + + [deps.LogExpFunctions.extensions] + LogExpFunctionsChainRulesCoreExt = "ChainRulesCore" + LogExpFunctionsChangesOfVariablesExt = "ChangesOfVariables" + LogExpFunctionsInverseFunctionsExt = "InverseFunctions" + + [deps.LogExpFunctions.weakdeps] + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + ChangesOfVariables = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0" + InverseFunctions = "3587e190-3f89-42d0-90ee-14403ec27112" + +[[deps.Logging]] +uuid = "56ddb016-857b-54e1-b83d-db4d58db5568" + +[[deps.LoggingExtras]] +deps = ["Dates", "Logging"] +git-tree-sha1 = "f00544d95982ea270145636c181ceda21c4e2575" +uuid = "e6f89c97-d47a-5376-807f-9c37f3926c36" +version = "1.2.0" + +[[deps.MLStyle]] +git-tree-sha1 = "bc38dff0548128765760c79eb7388a4b37fae2c8" +uuid = "d8e11817-5142-5d16-987a-aa16d5891078" +version = "0.4.17" + +[[deps.MacroTools]] +git-tree-sha1 = "1e0228a030642014fe5cfe68c2c0a818f9e3f522" +uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09" +version = "0.5.16" + +[[deps.MarchingCubes]] +deps = ["PrecompileTools", "StaticArrays"] +git-tree-sha1 = "0e893025924b6becbae4109f8020ac0e12674b01" +uuid = "299715c1-40a9-479a-aaf9-4a633d36f717" +version = "0.1.11" + +[[deps.Markdown]] +deps = ["Base64"] +uuid = "d6f4376e-aef5-505a-96c1-9c027394607a" + +[[deps.MbedTLS]] +deps = ["Dates", "MbedTLS_jll", "MozillaCACerts_jll", "NetworkOptions", "Random", "Sockets"] +git-tree-sha1 = "8785729fa736197687541f7053f6d8ab7fc44f92" +uuid = "739be429-bea8-5141-9913-cc70e7f3736d" +version = "1.1.10" + +[[deps.MbedTLS_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1" +version = "2.28.2+1" + +[[deps.Missings]] +deps = ["DataAPI"] +git-tree-sha1 = "ec4f7fbeab05d7747bdf98eb74d130a2a2ed298d" +uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28" +version = "1.2.0" + +[[deps.Mmap]] +uuid = "a63ad114-7e13-5084-954f-fe012c677804" + +[[deps.MozillaCACerts_jll]] +uuid = "14a3606d-f60d-562e-9121-12d972cd8159" +version = "2023.1.10" + +[[deps.NVTX]] +deps = ["JuliaNVTXCallbacks_jll", "Libdl", "NVTX_jll"] +git-tree-sha1 = "a9083c3e469e63cca454d1fc3b19472d9d92c14a" +uuid = "5da4648a-3479-48b8-97b9-01cb529c0a1f" +version = "1.0.3" +weakdeps = ["Colors"] + + [deps.NVTX.extensions] + NVTXColorsExt = "Colors" + +[[deps.NVTX_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "af2232f69447494514c25742ba1503ec7e9877fe" +uuid = "e98f9f5b-d649-5603-91fd-7774390e6439" +version = "3.2.2+0" + +[[deps.NaNMath]] +deps = ["OpenLibm_jll"] +git-tree-sha1 = "dbd2e8cd2c1c27f0b584f6661b4309609c5a685e" +uuid = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3" +version = "1.1.4" + +[[deps.NetworkOptions]] +uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908" +version = "1.2.0" + +[[deps.OpenBLAS_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"] +uuid = "4536629a-c528-5b80-bd46-f80d51c5b363" +version = "0.3.23+4" + +[[deps.OpenLibm_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "05823500-19ac-5b8b-9628-191a04bc5112" +version = "0.8.5+0" + +[[deps.OpenSSL]] +deps = ["BitFlags", "Dates", "MozillaCACerts_jll", "NetworkOptions", "OpenSSL_jll", "Sockets"] +git-tree-sha1 = "1d1aaa7d449b58415f97d2839c318b70ffb525a0" +uuid = "4d8831e6-92b7-49fb-bdf8-b643e874388c" +version = "1.6.1" + +[[deps.OpenSSL_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "d8cce34295c55f47be683580f44791716045b8fe" +uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95" +version = "3.5.7+0" + +[[deps.OpenSpecFun_jll]] +deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl"] +git-tree-sha1 = "1346c9208249809840c91b26703912dff463d335" +uuid = "efe28fd5-8261-553b-a9e1-b2916fc3738e" +version = "0.5.6+0" + +[[deps.OrderedCollections]] +git-tree-sha1 = "94ba93778373a53bfd5a0caaf7d809c445292ff4" +uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d" +version = "1.8.2" + +[[deps.Parsers]] +deps = ["Dates", "PrecompileTools", "UUIDs"] +git-tree-sha1 = "32a4e09c5f29402573d673901778a0e03b0807b9" +uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0" +version = "2.8.6" + +[[deps.PerfTest]] +deps = ["BandwidthBenchmark", "BenchmarkTools", "Configurations", "CountFlops", "DataFrames", "DataStructures", "Dates", "HTTP", "Hwloc", "JLD2", "JSON", "LibGit2", "Libdl", "LinearAlgebra", "MLStyle", "MacroTools", "Pkg", "PrecompileTools", "Printf", "Suppressor", "TOML", "Test", "ThreadPinningCore", "UnicodePlots"] +path = "../.." +uuid = "1dca261b-fc56-4a8c-a7e2-9798d8a75978" +version = "0.2.1" + + [deps.PerfTest.extensions] + PerfTest_AMDGPUExt = "AMDGPU" + PerfTest_CUDAExt = "CUDA" + PerfTest_LIKWIDExt = "LIKWID" + PerfTest_MPIExt = "MPI" + + [deps.PerfTest.weakdeps] + AMDGPU = "21141c5a-9bdb-4563-92ae-f87d6854732e" + CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" + LIKWID = "bf22376a-e803-4184-b2ed-56326e3bff83" + MPI = "da04e1cc-30fd-572f-bb4f-1f8673147195" + +[[deps.Pkg]] +deps = ["Artifacts", "Dates", "Downloads", "FileWatching", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"] +uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" +version = "1.10.0" + +[[deps.PooledArrays]] +deps = ["DataAPI", "Future"] +git-tree-sha1 = "36d8b4b899628fb92c2749eb488d884a926614d3" +uuid = "2dfb63ee-cc39-5dd5-95bd-886bf059d720" +version = "1.4.3" + +[[deps.PrecompileTools]] +deps = ["Preferences"] +git-tree-sha1 = "5aa36f7049a63a1528fe8f7c3f2113413ffd4e1f" +uuid = "aea7be01-6a6a-4083-8856-8a6e6704d82a" +version = "1.2.1" + +[[deps.Preferences]] +deps = ["TOML"] +git-tree-sha1 = "8b770b60760d4451834fe79dd483e318eee709c4" +uuid = "21216c6a-2e73-6563-6e65-726566657250" +version = "1.5.2" + +[[deps.PrettyTables]] +deps = ["Crayons", "LaTeXStrings", "Markdown", "PrecompileTools", "Printf", "Reexport", "StringManipulation", "Tables"] +git-tree-sha1 = "1101cd475833706e4d0e7b122218257178f48f34" +uuid = "08abe8d2-0d0c-5749-adfa-8a2ac140af0d" +version = "2.4.0" + +[[deps.Printf]] +deps = ["Unicode"] +uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7" + +[[deps.Profile]] +deps = ["Printf"] +uuid = "9abbd945-dff8-562f-b5e8-e1ebf5ef1b79" + +[[deps.PtrArrays]] +git-tree-sha1 = "4fbbafbc6251b883f4d2705356f3641f3652a7fe" +uuid = "43287f4e-b6f4-7ad1-bb20-aadabca52c3d" +version = "1.4.0" + +[[deps.REPL]] +deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"] +uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb" + +[[deps.ROCmDeviceLibs_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Zlib_jll"] +git-tree-sha1 = "9c5b123e62df15d3512ecff91cfce00e36387151" +uuid = "873c0968-716b-5aa7-bb8d-d1e2e2aeff2d" +version = "5.6.1+1" + +[[deps.Random]] +deps = ["SHA"] +uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" + +[[deps.Random123]] +deps = ["Random", "RandomNumbers"] +git-tree-sha1 = "dbe5fd0b334694e905cb9fda73cd8554333c46e2" +uuid = "74087812-796a-5b5d-8853-05524746bad3" +version = "1.7.1" + +[[deps.RandomNumbers]] +deps = ["Random"] +git-tree-sha1 = "c6ec94d2aaba1ab2ff983052cf6a606ca5985902" +uuid = "e6cf234a-135c-5ec9-84dd-332b85af5143" +version = "1.6.0" + +[[deps.Reexport]] +git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b" +uuid = "189a3867-3050-52da-a836-e630ba90ab69" +version = "1.2.2" + +[[deps.Requires]] +deps = ["UUIDs"] +git-tree-sha1 = "62389eeff14780bfe55195b7204c0d8738436d64" +uuid = "ae029012-a4dd-5104-9daa-d747884805df" +version = "1.3.1" + +[[deps.SHA]] +uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce" +version = "0.7.0" + +[[deps.ScopedValues]] +deps = ["HashArrayMappedTries", "Logging"] +git-tree-sha1 = "67a144433c4ce877ee6d1ada69a124d6b1ecf7be" +uuid = "7e506255-f358-4e82-b7e4-beb19740aa63" +version = "1.6.2" + +[[deps.Scratch]] +deps = ["Dates"] +git-tree-sha1 = "9b81b8393e50b7d4e6d0a9f14e192294d3b7c109" +uuid = "6c6a2e73-6563-6170-7368-637461726353" +version = "1.3.0" + +[[deps.SentinelArrays]] +deps = ["Dates", "Random"] +git-tree-sha1 = "084c47c7c5ce5cfecefa0a98dff69eb3646b5a80" +uuid = "91c51154-3ec4-41a3-a24f-3f23e20d615c" +version = "1.4.10" + +[[deps.Serialization]] +uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b" + +[[deps.SimpleBufferStream]] +git-tree-sha1 = "f305871d2f381d21527c770d4788c06c097c9bc1" +uuid = "777ac1f9-54b0-4bf8-805c-2214025038e7" +version = "1.2.0" + +[[deps.Sockets]] +uuid = "6462fe0b-24de-5631-8697-dd941f90decc" + +[[deps.SortingAlgorithms]] +deps = ["DataStructures"] +git-tree-sha1 = "13cd91cc9be159e3f4d95b857fa2aa383b53772a" +uuid = "a2af1166-a08f-5f64-846c-94a0d3cef48c" +version = "1.2.3" + +[[deps.SparseArrays]] +deps = ["Libdl", "LinearAlgebra", "Random", "Serialization", "SuiteSparse_jll"] +uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" +version = "1.10.0" + +[[deps.SpecialFunctions]] +deps = ["IrrationalConstants", "LogExpFunctions", "OpenLibm_jll", "OpenSpecFun_jll"] +git-tree-sha1 = "429071b23f4c9a13fb6582f807cc2ef454082408" +uuid = "276daf66-3868-5448-9aa4-cd146d93841b" +version = "2.9.0" + + [deps.SpecialFunctions.extensions] + SpecialFunctionsChainRulesCoreExt = "ChainRulesCore" + + [deps.SpecialFunctions.weakdeps] + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + +[[deps.StableTasks]] +git-tree-sha1 = "c4f6610f85cb965bee5bfafa64cbeeda55a4e0b2" +uuid = "91464d47-22a1-43fe-8b7f-2d57ee82463f" +version = "0.1.7" + +[[deps.StaticArrays]] +deps = ["LinearAlgebra", "PrecompileTools", "Random", "StaticArraysCore"] +git-tree-sha1 = "246a8bb2e6667f832eea063c3a56aef96429a3db" +uuid = "90137ffa-7385-5640-81b9-e52037218182" +version = "1.9.18" + + [deps.StaticArrays.extensions] + StaticArraysChainRulesCoreExt = "ChainRulesCore" + StaticArraysStatisticsExt = "Statistics" + + [deps.StaticArrays.weakdeps] + ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" + Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" + +[[deps.StaticArraysCore]] +git-tree-sha1 = "6ab403037779dae8c514bad259f32a447262455a" +uuid = "1e83bf80-4336-4d27-bf5d-d5a4f845583c" +version = "1.4.4" + +[[deps.Statistics]] +deps = ["LinearAlgebra", "SparseArrays"] +uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" +version = "1.10.0" + +[[deps.StatsAPI]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "178ed29fd5b2a2cfc3bd31c13375ae925623ff36" +uuid = "82ae8749-77ed-4fe6-ae5f-f523153014b0" +version = "1.8.0" + +[[deps.StatsBase]] +deps = ["AliasTables", "DataAPI", "DataStructures", "IrrationalConstants", "LinearAlgebra", "LogExpFunctions", "Missings", "Printf", "Random", "SortingAlgorithms", "SparseArrays", "Statistics", "StatsAPI"] +git-tree-sha1 = "e4d7a1a0edc20af42689ea6f4f3587a2175d50ee" +uuid = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91" +version = "0.34.12" + +[[deps.StringManipulation]] +deps = ["PrecompileTools"] +git-tree-sha1 = "8a90c1d77c3277a5d43b83927b3cbe2c70a37484" +uuid = "892a3eda-7b42-436c-8928-eab12a02cf0e" +version = "0.4.7" + +[[deps.SuiteSparse_jll]] +deps = ["Artifacts", "Libdl", "libblastrampoline_jll"] +uuid = "bea87d4a-7f5b-5778-9afe-8cc45184846c" +version = "7.2.1+1" + +[[deps.Suppressor]] +deps = ["Logging"] +git-tree-sha1 = "6dbb5b635c5437c68c28c2ac9e39b87138f37c0a" +uuid = "fd094767-a336-5f1f-9728-57cf17d0bbfb" +version = "0.2.8" + +[[deps.TOML]] +deps = ["Dates"] +uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76" +version = "1.0.3" + +[[deps.TableTraits]] +deps = ["IteratorInterfaceExtensions"] +git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39" +uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c" +version = "1.0.1" + +[[deps.Tables]] +deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "OrderedCollections", "TableTraits"] +git-tree-sha1 = "0f38a06c83f0007bbab3cf911262841c9a0f07e0" +uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c" +version = "1.13.0" + +[[deps.Tar]] +deps = ["ArgTools", "SHA"] +uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e" +version = "1.10.0" + +[[deps.TensorCore]] +deps = ["LinearAlgebra"] +git-tree-sha1 = "1feb45f88d133a655e001435632f019a9a1bcdb6" +uuid = "62fd8b95-f654-4bbd-a8a5-9c27f68ccd50" +version = "0.1.1" + +[[deps.Test]] +deps = ["InteractiveUtils", "Logging", "Random", "Serialization"] +uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40" + +[[deps.ThreadPinning]] +deps = ["DelimitedFiles", "DocStringExtensions", "Libdl", "LinearAlgebra", "PrecompileTools", "Preferences", "Random", "StableTasks"] +git-tree-sha1 = "333748c6fa62868fa039f00ba670d619776a6752" +uuid = "811555cd-349b-4f26-b7bc-1f208b848042" +version = "0.7.22" + +[[deps.ThreadPinningCore]] +deps = ["LinearAlgebra", "PrecompileTools", "StableTasks"] +git-tree-sha1 = "bb3c6f3b5600fbff028c43348365681b34d06499" +uuid = "6f48bc29-05ce-4cc8-baad-4adcba581a18" +version = "0.4.5" + +[[deps.Tracy]] +deps = ["ExprTools", "LibTracyClient_jll", "Libdl"] +git-tree-sha1 = "73e3ff50fd3990874c59fef0f35d10644a1487bc" +uuid = "e689c965-62c8-4b79-b2c5-8359227902fd" +version = "0.1.6" + + [deps.Tracy.extensions] + TracyProfilerExt = "TracyProfiler_jll" + + [deps.Tracy.weakdeps] + TracyProfiler_jll = "0c351ed6-8a68-550e-8b79-de6f926da83c" + +[[deps.TranscodingStreams]] +git-tree-sha1 = "0c45878dcfdcfa8480052b6ab162cdd138781742" +uuid = "3bb67fe8-82b1-5028-8e26-92a6c54297fa" +version = "0.11.3" + +[[deps.URIs]] +git-tree-sha1 = "3b0738bd7c5645641845da25cbd99800b8718689" +uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4" +version = "1.6.2" + +[[deps.UUIDs]] +deps = ["Random", "SHA"] +uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4" + +[[deps.Unicode]] +uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5" + +[[deps.UnicodePlots]] +deps = ["ColorSchemes", "ColorTypes", "Contour", "Crayons", "Dates", "LinearAlgebra", "MarchingCubes", "NaNMath", "PrecompileTools", "Printf", "SparseArrays", "StaticArrays", "StatsBase"] +git-tree-sha1 = "24d2e39c49110ffe5ab6b298a9b53a56f3ac57eb" +uuid = "b8865327-cd53-5732-bb35-84acbb429228" +version = "3.8.4" + + [deps.UnicodePlots.extensions] + FreeTypeExt = ["FileIO", "FreeType"] + ImageInTerminalExt = "ImageInTerminal" + IntervalSetsExt = "IntervalSets" + TermExt = "Term" + UnitfulExt = "Unitful" + + [deps.UnicodePlots.weakdeps] + FileIO = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549" + FreeType = "b38be410-82b0-50bf-ab77-7b57e271db43" + ImageInTerminal = "d8c32880-2388-543b-8c61-d9f865259254" + IntervalSets = "8197267c-284f-5f27-9208-e0e47529a953" + Term = "22787eb5-b846-44ae-b979-8e399b8463ab" + Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d" + +[[deps.Unitful]] +deps = ["Dates", "LinearAlgebra", "Random"] +git-tree-sha1 = "57e1b2c9de4bd6f40ecb9de4ac1797b81970d008" +uuid = "1986cc42-f94f-5a68-af5c-568840ba703d" +version = "1.28.0" + + [deps.Unitful.extensions] + ConstructionBaseUnitfulExt = "ConstructionBase" + ForwardDiffExt = "ForwardDiff" + InverseFunctionsUnitfulExt = "InverseFunctions" + LatexifyExt = ["Latexify", "LaTeXStrings"] + NaNMathExt = "NaNMath" + PrintfExt = "Printf" + + [deps.Unitful.weakdeps] + ConstructionBase = "187b0558-2788-49d3-abe0-74a17ed4e7c9" + ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" + InverseFunctions = "3587e190-3f89-42d0-90ee-14403ec27112" + LaTeXStrings = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f" + Latexify = "23fbe1c1-3f47-55db-b15f-69d7ec21a316" + NaNMath = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3" + Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7" + +[[deps.UnsafeAtomics]] +git-tree-sha1 = "0f30765c32d66d58e41f4cb5624d4fc8a82ec13b" +uuid = "013be700-e6cd-48c3-b4a1-df204f14c38f" +version = "0.3.1" +weakdeps = ["LLVM"] + + [deps.UnsafeAtomics.extensions] + UnsafeAtomicsLLVM = ["LLVM"] + +[[deps.XML2_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Libiconv_jll", "Zlib_jll"] +git-tree-sha1 = "80d3930c6347cfce7ccf96bd3bafdf079d9c0390" +uuid = "02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a" +version = "2.13.9+0" + +[[deps.Xorg_libpciaccess_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Zlib_jll"] +git-tree-sha1 = "58972370b81423fc546c56a60ed1a009450177c3" +uuid = "a65dc6b1-eb27-53a1-bb3e-dea574b5389e" +version = "0.19.0+0" + +[[deps.Zlib_jll]] +deps = ["Libdl"] +uuid = "83775a58-1f1d-513f-b197-d71354ab007a" +version = "1.2.13+1" + +[[deps.Zstd_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "446b23e73536f84e8037f5dce465e92275f6a308" +uuid = "3161d3a3-bdf6-5164-811a-617609db77b4" +version = "1.5.7+1" + +[[deps.demumble_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl"] +git-tree-sha1 = "6498e3581023f8e530f34760d18f75a69e3a4ea8" +uuid = "1e29f10c-031c-5a83-9565-69cddfc27673" +version = "1.3.0+0" + +[[deps.libLLVM_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "8f36deef-c2a5-5394-99ed-8e07531fb29a" +version = "15.0.7+10" + +[[deps.libblastrampoline_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "8e850b90-86db-534c-a0d3-1478176c7d93" +version = "5.11.0+0" + +[[deps.nghttp2_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d" +version = "1.52.0+1" + +[[deps.p7zip_jll]] +deps = ["Artifacts", "Libdl"] +uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0" +version = "17.4.0+2" diff --git a/examples/example-llama-energy/Project.toml b/examples/example-llama-energy/Project.toml new file mode 100644 index 0000000..74c5926 --- /dev/null +++ b/examples/example-llama-energy/Project.toml @@ -0,0 +1,8 @@ +[deps] +AMDGPU = "21141c5a-9bdb-4563-92ae-f87d6854732e" +CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" +LIKWID = "bf22376a-e803-4184-b2ed-56326e3bff83" +PerfTest = "1dca261b-fc56-4a8c-a7e2-9798d8a75978" + +[extras] +CUDA_Runtime_jll = "76a88914-d11a-5bdc-97e0-2f5a05c973a2" diff --git a/examples/example-llama-energy/README.md b/examples/example-llama-energy/README.md new file mode 100644 index 0000000..feca0b4 --- /dev/null +++ b/examples/example-llama-energy/README.md @@ -0,0 +1,254 @@ +# Case study — Energy efficiency of LLM inference vs. quantization + +> **Status: preliminary draft.** This directory is a self-contained scaffold for a +> PerfTest.jl case study. The Julia recipe, the FFI binding, and the helper +> scripts are written to be runnable in shape, but the FFI struct layouts and the +> exact numbers must be validated on the target machine (see *Caveats*). + +## The question + +Almost every published `llama.cpp` benchmark reports **tokens per second**. For +production inference at scale, the metric that actually drives cost is +**energy per generated token (Joules/token)**. Quantization is the main lever for +reducing it — but it also degrades output quality. + +This case study uses PerfTest.jl's new CUDA/NVML energy feature to answer: + +> **How much energy does quantization save, and what does it cost in quality?** + +The deliverable is a **Pareto plot**: energy-per-token (x) vs. quality loss vs. +the F16 baseline (y), one point per quantization level +(`F16 → Q8_0 → Q6_K → Q5_K_M → Q4_K_M → Q3_K_M → Q2_K`). + +## Why this is a good demonstration of PerfTest.jl + +- It measures a **real, non-Julia GPU workload** (llama.cpp's own CUDA context) + entirely from a Julia test recipe. This works because NVML's + `energy_consumption` is a **device-global** counter — PerfTest.jl (on CUDA.jl) + reads it around each target, capturing whatever the GPU did, regardless of + which CUDA context ran it. +- Inference is driven **in-process** via direct `ccall`s into `libllama` + (`LlamaFFI.jl`), so prefill and decode can be bracketed **separately** and the + energy attributed cleanly, without subprocess or model-load contamination. +- The measured targets are **idempotent by construction** (they reset the KV + cache and re-prefill on every call), so repeated benchmark samples and the + separate energy probe all start from an identical state — see *Idempotency*. +- It exercises PerfTest.jl idioms end-to-end: loop testsets, `@perftest`, + `@export_vars`, custom/auxiliary metrics, a testable energy budget + (`@define_test_metric`), and persisted results. + +## Files + +| File | Purpose | +|------|---------| +| `llama_energy_test.jl` | The PerfTest.jl recipe (quant sweep + energy metrics). | +| `LlamaFFI.jl` | Minimal in-process `ccall` binding to a CUDA `libllama`. | +| `build_llama_cuda.sh` | Build llama.cpp with `-DGGML_CUDA=ON`. | +| `get_models.sh` | Download or quantize the GGUF weights. | +| `plot_results.jl` | Produce the energy/quality Pareto figure. | +| `Project.toml` | Deps (`PerfTest`, `CUDA`; optional plotting). | + +## Requirements + +- A **datacenter-class NVIDIA GPU** (V100 / A100 / H100 …). NVML + `nvmlDeviceGetTotalEnergyConsumption` is supported on Volta+ datacenter cards; + many consumer GeForce cards do **not** expose the cumulative energy counter. +- **A CUDA build of llama.cpp.** The registered `llama_cpp_jll` is **CPU-only** + (no `libggml_cuda`), so it cannot be used here. `build_llama_cuda.sh` also + builds the `llama-perplexity` tool used for the quality axis (see below). +- A fixed text corpus for the quality axis (e.g. a WikiText-2 slice) — see + "Quality axis" for how to fetch one. +- A checkout of PerfTest.jl with the CUDA extension enabled. +- **Disk/VRAM scale.** The default model, Qwen3.8-27B, ranges from + ~26GB (`Q2_K`) to ~141GB (`f16`) per quant. The larger quants (`f16`/`Q8_0`/ + `Q6_K`, and possibly `Q5_K_M`) will not fit in a single GPU's VRAM on most + datacenter cards at `n_ctx=4096` — that's expected, see "Caveats: OOM + behavior" below. `get_models.sh`'s split-file fallback (needed because + those larger quants are published as multiple part files, not one) needs + only `curl`/`grep` plus the `llama-gguf-split` binary already built + alongside `libllama` by `build_llama_cuda.sh`/`build_llama_rocm.sh`. + +## Reproduction + +```bash +# 1. Build CUDA-enabled llama.cpp (set CUDA_ARCH: 70=V100, 80=A100, 90=H100) +CUDA_ARCH=80 ./build_llama_cuda.sh +export LLAMA_CPP_LIB=/abs/path/to/llama.cpp/build/bin/libllama.so + +# 2. Get the weights (A = download prebuilt, B = quantize from an F16 base) +# and the WikiText-2 corpus used for the quality axis. +export LLAMA_MODEL_DIR=$PWD/models +export LLAMA_MODEL_BASE=Qwen3.8-27B +# LLAMA_MODEL_REPO is also available (defaults to +# unsloth/${LLAMA_MODEL_BASE}-GGUF) for the next time the model changes. +./get_models.sh A + +# 3. (Recommended) stabilise the GPU for repeatable energy numbers +sudo nvidia-smi -pm 1 # persistence mode +sudo nvidia-smi -lgc , # lock graphics clocks + +# 4. Run the study +julia --project=. -e 'using PerfTest; runperftests("llama_energy_test.jl")' +``` + +To generate the Pareto figure, populate `results.csv` (see `plot_results.jl` +header for the expected columns) and: + +```bash +julia --project=. plot_results.jl +``` + +## Experimental design + +| Aspect | Choice | +|--------|--------| +| Controlled | one model family, one GPU, full GPU offload, fixed prompt, fixed `N_GEN`, greedy (deterministic) decode, fixed flash-attention, locked clocks | +| Independent variable | GGUF quantization level (loop testset) | +| Primary metric | **Joules per generated token** (`decode_energy / N_GEN`) | +| Secondary | tokens/Joule, avg power (W), throughput (tok/s), VRAM | +| Quality axis | perplexity (or KL-divergence) vs the F16 baseline | + +### Quality axis + +Two ways to obtain perplexity were considered: + +- **Level A (offline, used by the recipe):** shell out to the CUDA-built + `llama-perplexity` tool once per quant against a fixed corpus (e.g. a + WikiText-2 slice), and parse its `Final estimate: PPL = ...` line. + `llama_energy_test.jl`'s `run_llama_perplexity` does this in setup, before + the in-process `LlamaFFI` session opens (so the two CUDA contexts never + share the GPU at once), and reports the result via the `Perplexity` + auxiliary metric. +- **Level B (in-process, dropped):** teacher-force text through `LlamaFFI` + directly and exponentiate the average negative log-likelihood of the gold + next-tokens. This was tried first, using the ~30-token `PROMPT` as the eval + text, and produced non-monotonic, noisy perplexity across quants (e.g. some + quantized levels scoring *better* than F16). A sample that small can't + average out per-token noise from quantization — real perplexity evaluation + needs a corpus of thousands of tokens, which is exactly what + `llama-perplexity`'s sliding-window evaluation provides. Level A was kept + instead of reimplementing that chunking in `LlamaFFI.jl`. + +`get_models.sh` fetches the corpus automatically (`fetch_ppl_corpus`, run +regardless of the `A`/`B` model option). The HF dataset repo now ships that +split as Parquet only (the old `.raw`/`.zip` files are gone — +[wikitext-2-raw-v1](https://huggingface.co/datasets/Salesforce/wikitext/tree/main/wikitext-2-raw-v1)), +so `fetch_ppl_corpus` downloads `test-00000-of-00001.parquet` and reassembles +it into a plain-text file (one physical line per row) using Julia + +Parquet2.jl in a throwaway temp environment — it doesn't touch +`Project.toml`/`Manifest.toml`. To fetch it standalone: + +```bash +mkdir -p wikitext-2-raw +curl -L -o wikitext-2-raw/test-00000-of-00001.parquet \ + https://huggingface.co/datasets/Salesforce/wikitext/resolve/main/wikitext-2-raw-v1/test-00000-of-00001.parquet +julia --startup-file=no -e ' + import Pkg; Pkg.activate(; temp=true); Pkg.add(["Parquet2", "Tables"]) + using Parquet2, Tables + ds = Parquet2.Dataset(ARGS[1]) + open(ARGS[2], "w") do io + for row in Tables.rows(ds) + text = coalesce(row.text, "") + print(io, text) + endswith(text, "\n") || print(io, "\n") + end + end +' wikitext-2-raw/test-00000-of-00001.parquet wikitext-2-raw/wiki.test.raw +``` + +`run_llama_perplexity` looks for `llama-perplexity` next to `$LLAMA_LIB` +(override with `LLAMA_PERPLEXITY_BIN`) and the corpus at +`wikitext-2-raw/wiki.test.raw` next to this recipe (override with +`PPL_CORPUS`). If either is missing it `@warn`s and reports `NaN` rather than +failing the sweep. + +## How the recipe measures energy + +The CUDA extension injects an NVML read before and after each `@perftest` target +(bracketed by a synchronize), storing the per-device delta. In the recipe: + +- `@perftest ... LlamaFFI.generate!(s, PROMPT, N_GEN)` is the measured target + (idempotent full request); its GPU energy is exposed to formulas as + `:gpue.dev0` (Joules) and average power as `:gpup.dev0` (Watts). +- `@auxiliary_metric name="Energy/token" ... :gpue.dev0 / N_GEN` is the headline. +- `@define_test_metric name="Energy budget" reference=0.5 low_is_bad=false ...` + demonstrates a **testable** energy target (fail the build if J/token exceeds + the budget), which is the basis for energy-regression testing in CI. + +## Idempotency (why the measured target self-resets) + +LLM decoding is **stateful**: each `llama_decode` appends to the context KV +cache. A naive `decode_n!` target is therefore *not* idempotent — the 2nd +benchmark sample would continue from the 1st sample's state and eventually +overflow `n_ctx`. + +You might reach for `@perftest setup=... teardown=...` to reset between runs. +That is **not sufficient** here, for two reasons specific to the current CUDA +energy extension: + +1. The energy probe runs the target **once more, with no setup/teardown** + (`hierarchy_transform.jl` injects `gpuPowerMeasure(expr)` directly), so a + BenchmarkTools `setup` never runs for the energy measurement. +2. That energy run happens **after** the timing loop, so it would start from the + most polluted state of all. + +The robust fix used here is to make the measured targets **self-resetting**: +`generate!` and `prefill_only!` call `reset!` (clear the KV cache) at the start +of every invocation, so they are safe to call any number of times and always +start from an identical state — no `setup`/`teardown` required. If the extension +later gains setup/teardown support around the energy probe, the reset could move +there instead. + +## Caveats (must-read for the draft) + +1. **FFI struct layouts.** `LlamaModelParams` / `LlamaContextParams` in + `LlamaFFI.jl` mirror the C structs so the `*_default_params()` calls work. + These layouts change across llama.cpp commits — **verify them against the + `llama.h` of the commit you build**, or regenerate the binding with + `Clang.jl`. Pin and record the commit. +2. **Energy-feature prototype.** The PerfTest CUDA extension is still a prototype. + Before trusting numbers, the known blockers should be fixed: + unit conversion (NVML returns **millijoules**), real power (currently aliased + to energy), honouring the `.devN` device specifier, gating the CUDA branch + properly, and removing debug `@info` logs. See the project plan / issue + tracker. +3. **Single-run energy.** Energy is measured on one execution of the target + (separate from the timing samples). Use warmup + repetitions and report + mean ± std for credibility. +4. **Whole-device counter.** NVML energy is device-global; run on an otherwise + idle GPU, and consider subtracting an idle-power baseline. +5. **Determinism.** Greedy decoding is used so token counts and work are + identical across repetitions; keep sampling out of the measured path. +6. **OOM behavior.** Neither `LlamaFFI.jl` nor PerfTest.jl's testset machinery + has any OOM-specific handling, and at 70B some quants (see "Disk/VRAM + scale" above) are expected to exceed a single GPU's VRAM. Concretely: + - A failed `cudaMalloc`/`hipMalloc` inside llama.cpp's GPU backend either + returns an error/null pointer, or calls `GGML_ABORT`/segfaults — which + one happens depends on the llama.cpp commit/backend, not on anything in + this example. In the first case, `LlamaFFI.jl`'s generic + `... == C_NULL && error(...)` checks turn it into a normal Julia + exception, which `@testset for` records as an `Error` for that one + quant and the sweep continues. In the second case, the crash **cannot + be caught by any Julia `try`/`catch`** — the OS kills the whole process + mid-`ccall`. + - The generated perf-suite always runs as a separate subprocess + (`Launch.launchPerfTestSuite`, spawned via `run(...)`), with no + surrounding `try`/`catch` in `runperftests`. A hard crash there surfaces + as an uncaught `Base.ProcessFailedException` out of `runperftests` — + visible, but not gracefully handled (no retry, no partial results). + - Results are saved **once**, after the *entire* quant sweep finishes. + `QUANTS` sweeps smallest → largest specifically so the quants most + likely to fit are *computed* before the large, VRAM-constrained ones — + but this is only a partial mitigation: if a large quant crashes hard + (rather than just erroring), the process dies before that end-of-run + save executes, so the smaller quants' results, though already computed, + are still lost along with everything else. Full protection would need + incremental per-quant saving, which this recipe does not do. + +## Open questions being finalised + +- ~~Model choice (Qwen2.5-7B, Apache-2.0 vs Llama-3.1-8B) and quant set.~~ + Resolved: **Qwen3.8-27B**, chosen for sharper energy/quality + separation across the quant sweep and to realistically exercise the OOM + path (see "Caveats: OOM behavior"). +- Whether to also demo **energy-regression testing** in CI. diff --git a/examples/example-llama-energy/build_llama_cuda.sh b/examples/example-llama-energy/build_llama_cuda.sh new file mode 100755 index 0000000..8193c45 --- /dev/null +++ b/examples/example-llama-energy/build_llama_cuda.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +#SBATCH --job-name=compilation # Name of the job +#SBATCH --output=output_%j.log # Standard output and error log +#SBATCH --error=error_%j.log # Standard error log +#SBATCH --time=4:00:00 # Time limit hrs:min:sec +#SBATCH --nodes=1 # Number of nodes +#SBATCH --ntasks=1 # Total number of tasks +#SBATCH --nodelist=gracehop1 # Specify the node name +# ============================================================================= +# Build a CUDA-enabled llama.cpp so PerfTest.jl can measure GPU energy. +# +# The registered llama_cpp_jll ships CPU-ONLY binaries (no libggml_cuda), so a +# custom CUDA build is REQUIRED for this case study. +# +# Usage: +# ./build_llama_cuda.sh [SRC_DIR] [LLAMA_COMMIT] +# +# On success prints the LLAMA_CPP_LIB path to export before running the study. +# ============================================================================= +set -euo pipefail + +export TMPDIR=$WORK/nvcctmp +mkdir -p "$TMPDIR" + +# Pin a commit for reproducibility. Record whatever you actually build in the +# README results table. Override by passing an argument. +LLAMA_COMMIT="${2:-master}" + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SRC_DIR="$WORK/llama.cpp" +BUILD_DIR="${SRC_DIR}/build/${HOSTNAME}" + +echo $BUILD_DIR + +if [[ ! -d "${SRC_DIR}" ]]; then + git clone https://github.com/ggml-org/llama.cpp.git "${SRC_DIR}" +fi + +git -C "${SRC_DIR}" fetch --all --tags +git -C "${SRC_DIR}" checkout "${LLAMA_COMMIT}" +echo "Building llama.cpp @ $(git -C "${SRC_DIR}" rev-parse --short HEAD)" + +# -DGGML_CUDA=ON is the crucial flag. Adjust CMAKE_CUDA_ARCHITECTURES to your +# datacenter GPU (70=V100, 80=A100, 90=H100). +cmake -S "${SRC_DIR}" -B "${BUILD_DIR}" \ + -DGGML_CUDA=ON \ + -DCMAKE_BUILD_TYPE=Release \ + -DLLAMA_CURL=OFF \ + -DCMAKE_CUDA_ARCHITECTURES="75;80;86;89;90" \ + -DCMAKE_CUDA_COMPILER="${CUDACXX}" -DCMAKE_INSTALL_RPATH="${CUDA_HOME}/lib64" -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON + +cmake --build "${BUILD_DIR}" --config Release -j"$(nproc)" + +LIB="$(find "${BUILD_DIR}" -name 'libllama.so' -o -name 'libllama.dylib' | head -n1)" +echo "" +echo "==============================================================" +echo " Build complete. Export before running the study:" +echo "" +echo " export LLAMA_CPP_LIB=${LIB}" +echo "" +echo " (also ensure libggml*.so are alongside it; they are in ${BUILD_DIR}/bin)" +echo "==============================================================" diff --git a/examples/example-llama-energy/build_llama_rocm.sh b/examples/example-llama-energy/build_llama_rocm.sh new file mode 100755 index 0000000..442596d --- /dev/null +++ b/examples/example-llama-energy/build_llama_rocm.sh @@ -0,0 +1,73 @@ +#!/usr/bin/env bash +#SBATCH --job-name=compilation # Name of the job +#SBATCH --output=output_%j.log # Standard output and error log +#SBATCH --error=error_%j.log # Standard error log +#SBATCH --time=4:00:00 # Time limit hrs:min:sec +#SBATCH --nodes=1 # Number of nodes +#SBATCH --ntasks=1 # Total number of tasks +#SBATCH --nodelist=amdnode1 # Specify the node name (edit to your ROCm/AMD GPU node) +# ============================================================================= +# Build a ROCm/HIP-enabled llama.cpp so PerfTest.jl can measure GPU energy. +# +# The registered llama_cpp_jll ships CPU-ONLY binaries (no libggml_hip), so a +# custom ROCm build is REQUIRED for this case study. +# +# Usage: +# ./build_llama_rocm.sh [SRC_DIR] [LLAMA_COMMIT] +# +# On success prints the LLAMA_CPP_LIB path to export before running the study. +# ============================================================================= +set -euo pipefail + +export TMPDIR=$WORK/hipcctmp +mkdir -p "$TMPDIR" + +# Pin a commit/tag for reproducibility. Record whatever you actually build in +# the README results table. Override by passing an argument. +# +# OUTDATED: Defaults to the b6652 release rather than `master`: at time of writing, +# master has a real compiler-codegen bug building ggml-cuda/mmf.cu for gfx1100 +# (RDNA3) — clang fails to legalize a GCN/CDNA-only DPP wavefront-shift +# instruction ("Invalid dpp_ctrl value: wavefront shifts are not supported on +# GFX10+"), see https://github.com/ggml-org/llama.cpp/issues/18396. b6652 is +# the release AMD's own ROCm docs build llama.cpp against +# (https://rocm.docs.amd.com/projects/llama-cpp/en/docs-26.02/install/llama-cpp-install.html) +# and is known to build cleanly for this AMDGPU_TARGETS list. +LLAMA_COMMIT="${2:-master}" + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SRC_DIR="$WORK/llama.cpp" +BUILD_DIR="${SRC_DIR}/build/${HOSTNAME}" + +echo $BUILD_DIR + +if [[ ! -d "${SRC_DIR}" ]]; then + git clone https://github.com/ggml-org/llama.cpp.git "${SRC_DIR}" +fi + +git -C "${SRC_DIR}" fetch --all --tags +git -C "${SRC_DIR}" checkout "${LLAMA_COMMIT}" +echo "Building llama.cpp @ $(git -C "${SRC_DIR}" rev-parse --short HEAD)" + +# -DGGML_HIP=ON is the crucial flag. Adjust AMDGPU_TARGETS to your GPU(s): +# gfx906=MI50, gfx908=MI100, gfx90a=MI210/MI250(X), gfx942=MI300A/X, +# gfx1030=RDNA2 (6800/6900 series), gfx1100=RDNA3 (7900 series). +# HIPCXX/HIP_PATH come from the ROCm install via `hipconfig` (must be on PATH). +HIPCXX="$(hipconfig -l)/clang" HIP_PATH="$(hipconfig -R)" \ +cmake -S "${SRC_DIR}" -B "${BUILD_DIR}" \ + -DGGML_HIP=ON \ + -DCMAKE_BUILD_TYPE=Release \ + -DLLAMA_CURL=OFF \ + -DAMDGPU_TARGETS="gfx908;gfx90a;gfx942" + +cmake --build "${BUILD_DIR}" --config Release -j"$(nproc)" + +LIB="$(find "${BUILD_DIR}" -name 'libllama.so' -o -name 'libllama.dylib' | head -n1)" +echo "" +echo "==============================================================" +echo " Build complete. Export before running the study:" +echo "" +echo " export LLAMA_CPP_LIB=${LIB}" +echo "" +echo " (also ensure libggml*.so are alongside it; they are in ${BUILD_DIR}/bin)" +echo "==============================================================" diff --git a/examples/example-llama-energy/build_rocm_smi_lib.sh b/examples/example-llama-energy/build_rocm_smi_lib.sh new file mode 100755 index 0000000..7be45bb --- /dev/null +++ b/examples/example-llama-energy/build_rocm_smi_lib.sh @@ -0,0 +1,107 @@ +#!/usr/bin/env bash +#SBATCH --job-name=rocm_smi_build # Name of the job +#SBATCH --output=output_%j.log # Standard output and error log +#SBATCH --error=error_%j.log # Standard error log +#SBATCH --time=0:30:00 # Time limit hrs:min:sec +#SBATCH --nodes=1 # Number of nodes +#SBATCH --ntasks=1 # Total number of tasks +#SBATCH --nodelist=amdnode1 # Specify the node name (edit to the GPU node you want to build/test against) +# ============================================================================= +# Build librocm_smi64 from source into a user-writable prefix, so PerfTest.jl's +# AMDGPU extension can pick up a rocm_smi_lib version that correctly parses +# this node's gpu_metrics format, instead of whatever is on the +# environment-module ROCm path today. +# +# Why ROCm/amdsmi and not ROCm/rocm_smi_lib: on the MI200A node, gpu_metrics +# reports format_revision=1, content_revision=9 (confirmed via +# `od -An -tu1 -N4 /sys/class/drm/card*/device/gpu_metrics`). content_revision +# 9 is a self-describing attribute-table format (struct gpu_metrics_v1_9 in +# the amdgpu kernel headers - attr_count + {attr_encoding, attr_value} pairs), +# not another fixed-offset struct. The standalone ROCm/rocm_smi_lib repo has +# NO code to walk that format at all (its content-revision dispatch in +# rsmi_dev_gpu_metrics_info_get only ever defines VER_1/2/3, and there is no +# rocm_smi_dyn_gpu_metrics.cc anywhere in that repo's history) - confirmed by +# building its current master and getting RSMI_STATUS_INVALID_ARGS from both +# Julia and the rocm-smi CLI (GetGPUMetricsFormat1's fallback path leaves its +# buffer pointer null for any content_revision it doesn't recognize, so +# GetDevBinaryBlob correctly rejects the null buffer with INVALID_ARGS). +# +# ROCm/amdsmi (the amd-smi CLI's repo) vendors its OWN copy of the same +# rocm_smi/ source tree, with rocm_smi_dyn_gpu_metrics.cc added to walk +# content_revision >= 9 tables (see translate_header_to_flag_version's +# kGpuMetricDynV19Plus branch). It builds that tree into a target literally +# named `rocm_smi64` (rocm_smi/CMakeLists.txt), i.e. the exact same +# librocm_smi64.so our extension already Libdl.find_library's - same +# rsmi_dev_energy_count_get C symbol, same signature. amdsmi_get_energy_count +# in libamd_smi.so is confirmed to be nothing but a thin wrapper around that +# same call. So this fixes MI200A with NO changes needed to +# PerfTest_AMDGPUExt.jl - only which librocm_smi64.so gets loaded. +# +# NOTE this does NOT fix the separate MI100 magnitude issue (energy readings +# ~400,000x too small): kEnergyCounterResolution = 15.3 (uJ/tick) is still +# hard-coded unconditionally for all ASICs in this same tree +# (rocm_smi/src/rocm_smi.cc), so a content_revision the library already +# understood (MI100's is <= 3) sees no behavior change either way. That is a +# separate, still-open problem. +# +# Unlike the standalone rocm_smi_lib repo (zero external deps), this +# monorepo's top-level CMakeLists REQUIRES libdrm + libdrm_amdgpu via +# pkg-config (`pkg_check_modules(... REQUIRED ...)`), even though the +# rocm_smi64 target itself doesn't need much from them. This is almost +# certainly already present (any node running the amdgpu kernel driver needs +# libdrm), but if configure fails looking for libdrm.pc/libdrm_amdgpu.pc, try +# `module load` whatever provides it, or point PKG_CONFIG_PATH at it. +# +# Usage: +# ./build_rocm_smi_lib.sh [AMDSMI_REF] +# +# AMDSMI_REF defaults to `amd-mainline` (this repo's default branch). +# +# On success prints the LD_LIBRARY_PATH to export before running PerfTest.jl. +# IMPORTANT: it must be prepended (not appended) so Libdl.find_library finds +# this build before the environment-module ROCm's librocm_smi64. +# ============================================================================= +set -euo pipefail + +AMDSMI_REF="${1:-amd-mainline}" + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SRC_DIR="$WORK/amdsmi" +BUILD_DIR="${SRC_DIR}/build/${HOSTNAME}" +INSTALL_DIR="${SRC_DIR}/install/${HOSTNAME}" + +if [[ ! -d "${SRC_DIR}" ]]; then + git clone https://github.com/ROCm/amdsmi.git "${SRC_DIR}" +fi + +git -C "${SRC_DIR}" fetch --all --tags +git -C "${SRC_DIR}" checkout "${AMDSMI_REF}" +echo "Building amdsmi @ $(git -C "${SRC_DIR}" rev-parse --short HEAD) (ref: ${AMDSMI_REF})" + +cmake -S "${SRC_DIR}" -B "${BUILD_DIR}" \ + -DCMAKE_BUILD_TYPE=Release + +# Only build the rocm_smi64 target (the piece PerfTest.jl actually loads) - +# skip libamd_smi, amdsmi_cli, py-interface, rust-interface and their extra +# build time/deps entirely. +cmake --build "${BUILD_DIR}" --target rocm_smi64 -j"$(nproc)" + +LIB_BUILD_DIR="$(dirname "$(find "${BUILD_DIR}" -name 'librocm_smi64.so' | head -n1)")" +mkdir -p "${INSTALL_DIR}/lib" +cp -a "${LIB_BUILD_DIR}"/librocm_smi64.so* "${INSTALL_DIR}/lib/" + +LIB="$(find "${INSTALL_DIR}" -name 'librocm_smi64.so*' | head -n1)" +echo "" +echo "==============================================================" +echo " Build complete: ${LIB}" +echo "" +echo " Export before running PerfTest.jl (prepend, don't append, so this" +echo " build is found before the module-loaded ROCm's librocm_smi64):" +echo "" +echo " export LD_LIBRARY_PATH=${INSTALL_DIR}/lib:\$LD_LIBRARY_PATH" +echo "" +echo " Sanity-check independent of Julia - the system rocm-smi CLI also" +echo " dlopens librocm_smi64, so the same export should make it (dis)agree:" +echo "" +echo " rocm-smi --showenergycounter" +echo "==============================================================" diff --git a/examples/example-llama-energy/envvar.sh b/examples/example-llama-energy/envvar.sh new file mode 100644 index 0000000..f43c1f0 --- /dev/null +++ b/examples/example-llama-energy/envvar.sh @@ -0,0 +1,7 @@ +export MODEL_DIR=$WORK/models +# old +export LLAMA_LIB=/home/hpc/j101df/j101df19/llamacpp/llama.cpp/build/bin/libllama.so +# new +export LLAMA_LIB=$WORK/llama.cpp/build/$HOSTNAME/bin/libllama.so +export LLAMA_DIR=$WORK/llama.cpp/build/$HOSTNAME/bin +export LD_LIBRARY_PATH=$LLAMA_DIR:$LD_LIBRARY_PATH diff --git a/examples/example-llama-energy/get_models.sh b/examples/example-llama-energy/get_models.sh new file mode 100755 index 0000000..3a8852c --- /dev/null +++ b/examples/example-llama-energy/get_models.sh @@ -0,0 +1,144 @@ +#!/usr/bin/env bash +# ============================================================================= +# Fetch GGUF weights at several quantization levels for the energy study. +# +# Two options: +# (A) Download prebuilt GGUFs from Hugging Face (fast, less provenance). +# (B) Produce all quants from a single F16 GGUF with llama-quantize so every +# quant derives from an identical base (better provenance; recommended). +# +# Also fetches the WikiText-2 corpus llama_energy_test.jl's quality axis +# (Level A, run_llama_perplexity) evaluates against, at the same default +# location it expects (PPL_CORPUS). +# +# Set MODEL_DIR / LLAMA_MODEL_BASE to match llama_energy_test.jl. +# ============================================================================= +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +MODEL_BASE="${LLAMA_MODEL_BASE:-Qwen3.8-27B}" +# Repo derived from MODEL_BASE by default (bartowski's "-GGUF" naming +# convention); override independently if the next model's repo doesn't follow +# that pattern, or belongs to a different quantizer, without editing this file. +MODEL_REPO="${LLAMA_MODEL_REPO:-unsloth/${MODEL_BASE}-GGUF}" +mkdir -p "${MODEL_DIR}" + +# ---- Option A: download prebuilt quants (edit URLs to your model) ----------- +# Example uses the bartowski GGUF repos. Uncomment the quants you want. +# +# Some quants of larger models (e.g. f16/Q8_0/Q6_K/Q5_K_M of a 70B model) are +# published as multiple split part files rather than one .gguf, since HF +# discourages single files much above ~50GB. fetch_quant tries the direct +# single-file download first, and falls back to discovering + downloading the +# split parts and merging them with llama-gguf-split. +GGUF_SPLIT_BIN="${GGUF_SPLIT_BIN:-${LLAMACPP_HOME}/bin/llama-gguf-split}" + +fetch_quant() { + local repo="$1" q="$2" out="$3" + local base_url="https://huggingface.co/${repo}/resolve/main" + echo "downloading ${q} : ${base_url}/${MODEL_BASE}-${q}.gguf ..." + if curl -L --fail -o "${out}" "${base_url}/${MODEL_BASE}-${q}.gguf" 2>/dev/null; then + return + fi + echo " single-file download failed, checking for split parts ..." + local listing rfilenames parts part local_parts=() local_name + listing="$(curl -s "https://huggingface.co/api/models/${repo}")" + # rfilename entries for split quants are nested under a quant-named + # subdirectory (e.g. "Llama-3.3-70B-Instruct-Q8_0/Llama-3.3-70B-Instruct- + # Q8_0-00001-of-00002.gguf"), so match the whole quoted path rather than + # assuming the filename sits right after the opening quote. + rfilenames="$(grep -o '"[^"]*\.gguf"' <<<"${listing}" | tr -d '"')" + parts=($(grep -E "(^|/)${MODEL_BASE}-${q}-[0-9]{5}-of-[0-9]{5}\.gguf\$" <<<"${rfilenames}" | sort -u)) + if [[ ${#parts[@]} -eq 0 ]]; then + echo " no split parts found for ${q} either; giving up on this quant." >&2 + rm -f "${out}" + return 1 + fi + echo " found ${#parts[@]} split part(s) for ${q}, downloading ..." + for part in "${parts[@]}"; do + # ${part} may include the subdirectory for the URL path, but is + # stored flat locally (llama-gguf-split just needs the parts + # together in one directory, named by their -NNNNN-of-NNNNN suffix). + local_name="${MODEL_DIR}/$(basename "${part}")" + curl -L --fail -o "${local_name}" "${base_url}/${part}" + local_parts+=("${local_name}") + done + echo " merging split parts -> ${out}" + "${GGUF_SPLIT_BIN}" --merge "${local_parts[0]}" "${out}" + rm -f "${local_parts[@]}" +} + +download_prebuilt() { + local repo="${MODEL_REPO}" + for q in Q8_0 UD-Q6_K UD-Q5_K_M UD-Q4_K_M UD-Q3_K_XL UD-Q2_K_XL; do + local out="${MODEL_DIR}/${MODEL_BASE}-${q}.gguf" + [[ -f "${out}" ]] && { echo "have ${out}"; continue; } + fetch_quant "${repo}" "${q}" "${out}" + done +} + +# ---- Option B: quantize from a single F16 base (recommended) ---------------- +# Requires the CUDA (or CPU) llama-quantize built by build_llama_cuda.sh. +quantize_from_f16() { + local f16="${MODEL_DIR}/${MODEL_BASE}-f16.gguf" + local quantize_bin="${QUANTIZE_BIN:-${HERE}/llama.cpp/build/bin/llama-quantize}" + [[ -f "${f16}" ]] || { echo "Provide the F16 base at ${f16} first."; exit 1; } + for q in Q8_0 Q6_K Q5_K_M Q4_K_M Q3_K_M Q2_K; do + local out="${MODEL_DIR}/${MODEL_BASE}-${q}.gguf" + [[ -f "${out}" ]] && { echo "have ${out}"; continue; } + echo "quantizing -> ${q}" + "${quantize_bin}" "${f16}" "${out}" "${q}" + done +} + +# ---- Quality-axis corpus: WikiText-2 test split for llama-perplexity ------- +# Same default location llama_energy_test.jl's PPL_CORPUS expects. +# +# The HF dataset repo dropped the old .raw/.zip files in favor of Parquet +# (https://huggingface.co/datasets/Salesforce/wikitext/tree/main/wikitext-2-raw-v1), +# so we download the test-split parquet and reassemble it into a plain-text +# file the same shape as the old wiki.test.raw (one physical line per row; +# blank rows are blank lines). Uses Julia (already a hard requirement for +# this whole example) with Parquet2.jl in a throwaway temp environment, so +# this doesn't touch Project.toml/Manifest.toml. +fetch_ppl_corpus() { + if [[ -n "${PPL_CORPUS:-}" && -f "${PPL_CORPUS}" ]]; then + echo "have ${PPL_CORPUS}" + return + fi + local corpus_dir="${MODEL_DIR}/wikitext-2-raw" + local corpus_file="${corpus_dir}/wiki.test.raw" + [[ -f "${corpus_file}" ]] && { echo "have ${corpus_file}"; return; } + echo "downloading wikitext-2-raw-v1 test split (parquet) ..." + mkdir -p "${corpus_dir}" + local parquet="${corpus_dir}/test-00000-of-00001.parquet" + curl -L --fail -o "${parquet}" \ + "https://huggingface.co/datasets/Salesforce/wikitext/resolve/main/wikitext-2-raw-v1/test-00000-of-00001.parquet" + echo "extracting text column -> ${corpus_file} ..." + $JX86 --startup-file=no -e ' + import Pkg + Pkg.activate(; temp=true) + Pkg.add(["Parquet2", "Tables"]) + using Parquet2, Tables + ds = Parquet2.Dataset(ARGS[1]) + open(ARGS[2], "w") do io + for row in Tables.rows(ds) + text = coalesce(row.text, "") + print(io, text) + endswith(text, "\n") || print(io, "\n") + end + end + ' "${parquet}" "${corpus_file}" + rm -f "${parquet}" +} + +case "${1:-A}" in + A) download_prebuilt ;; + B) quantize_from_f16 ;; + *) echo "usage: $0 [A|B]"; exit 1 ;; +esac + +fetch_ppl_corpus + +echo "Models in ${MODEL_DIR}:" +ls -lh "${MODEL_DIR}" diff --git a/examples/example-llama-energy/llama_energy_test.jl b/examples/example-llama-energy/llama_energy_test.jl new file mode 100644 index 0000000..84eed9f --- /dev/null +++ b/examples/example-llama-energy/llama_energy_test.jl @@ -0,0 +1,221 @@ +# ============================================================================= +# PerfTest.jl case study: energy efficiency of LLM inference vs. quantization +# ============================================================================= +# +# PRELIMINARY DRAFT. +# +# Story: for a single model, sweep the GGUF quantization level and measure the +# GPU *energy per generated token* using PerfTest.jl's CUDA/NVML energy feature, +# alongside a quality proxy (perplexity). The headline result is the Pareto +# tradeoff: how much energy quantization saves vs. how much quality it costs. +# +# Inference is driven IN-PROCESS via direct `ccall`s into a CUDA-enabled +# libllama (see LlamaFFI.jl). Because NVML's energy counter is device-global, +# PerfTest.jl (running on CUDA.jl) transparently captures the energy consumed by +# llama.cpp's own CUDA context around each measured target. +# +# Perplexity (the quality axis) is obtained offline, "Level A" in README +# "Quality axis": shelling out to the CUDA-built `llama-perplexity` tool +# against a fixed corpus, once per quant. An earlier in-process ("Level B") +# attempt teacher-forced the ~30-token PROMPT through LlamaFFI directly, but +# that sample is far too small for a stable estimate — per-token noise from +# quantization swamped the real, monotonic quality trend. llama-perplexity's +# sliding-window evaluation over a real corpus (thousands of tokens) is what +# gives a trustworthy number. +# +# Run with: +# using PerfTest +# runperftests("llama_energy_test.jl") +# +# Requirements (see README.md): +# - A datacenter-class NVIDIA GPU (NVML energy_consumption supported). +# - LLAMA_CPP_LIB pointing at a CUDA build of libllama (build_llama_cuda.sh). +# - GGUF weights at several quant levels in $LLAMA_MODEL_DIR (get_models.sh). +# - The `llama-perplexity` tool built alongside libllama, and a fixed text +# corpus (see PPL_CORPUS below). +# ============================================================================= + +using Test +using PerfTest +using CUDA + +include("LlamaFFI.jl") + +# ----------------------------------------------------------------------------- +# Configuration +# ----------------------------------------------------------------------------- +@perftest_config " +[general] +verbose = 3 +plotting = true +[regression] +enabled = false +[cuda] +enabled = true +" + +# Directory holding the GGUF files, one per quantization level. +const MODEL_DIR = get(ENV, "MODEL_DIR", joinpath(@__DIR__, "models")) + +# Base model name; the quant tag is appended to form the filename. +# e.g. "Qwen3.8-27B-UD-Q4_K_M.gguf" +const MODEL_BASE = get(ENV, "MODEL_BASE", "Qwen3.8-27B") + +# Quantization levels to sweep, smallest -> largest. F16 is the quality +# baseline. Edit to match the GGUF files you actually downloaded/produced. +# +# Smallest-first (rather than the more natural "quality baseline first") +# is deliberate: at this model's size, the largest quants (f16/Q8_0/UD-Q6_K) may +# not fit in a single GPU's VRAM and can OOM. Running them last means the +# smaller, likely-to-fit quants are at least *computed* earlier in the same +# process before that happens. This is only a partial mitigation, though — +# see README "Caveats: OOM behavior" — since results are still saved once, +# after the whole sweep finishes, so a hard crash on a later quant still +# loses everything computed in that run, regardless of this ordering. +const QUANTS = ["UD-Q2_K_XL", "UD-Q3_K_XL", "UD-Q4_K_M", "UD-Q5_K_M", "UD-Q6_K", "Q8_0", "f16"] + +# Fixed workload. Deterministic (greedy) decoding, fixed token budget so that +# "energy per token" is comparable across quants. +const PROMPT = "Explain, in a single detailed paragraph, why energy efficiency " * + "is becoming the dominant cost metric for large language model " * + "inference in production data centers." +const N_GEN = 256 # generated tokens (decode phase) + +quant_path(q) = joinpath(MODEL_DIR, "$(MODEL_BASE)-$(q).gguf") + +# ----------------------------------------------------------------------------- +# Quality axis: offline perplexity (README "Quality axis", Level A) +# ----------------------------------------------------------------------------- + +# `llama-perplexity` is built alongside `libllama` by build_llama_cuda.sh +# (same build dir's bin/); override if it lives elsewhere. +const LLAMA_PERPLEXITY_BIN = get(ENV, "LLAMA_PERPLEXITY_BIN", + joinpath(dirname(get(ENV, "LLAMA_LIB", "")), "llama-perplexity")) + +# Fixed evaluation corpus (plain text, e.g. a WikiText-2 slice). The same +# corpus is used for every quant so the perplexity numbers are comparable. +const PPL_CORPUS = joinpath(get(ENV, "MODEL_DIR", @__DIR__), "wikitext-2-raw", "wiki.test.raw") + +const PPL_CTX = 512 # llama-perplexity's context/chunk size (its -c flag) + +""" + run_llama_perplexity(model_path) -> Float64 + +Run `llama-perplexity` on `PPL_CORPUS` against the GGUF at `model_path` and +parse its "Final estimate: PPL = ..." line. Returns `NaN` (with a `@warn`) if +the binary or corpus is missing, so the sweep still runs without the quality +axis. +""" +function run_llama_perplexity(model_path::AbstractString) + if !isfile(LLAMA_PERPLEXITY_BIN) + @warn "llama-perplexity binary not found, skipping perplexity" bin=LLAMA_PERPLEXITY_BIN + return NaN + end + if !isfile(PPL_CORPUS) + @warn "Perplexity corpus not found, skipping perplexity" corpus=PPL_CORPUS + return NaN + end + cmd = `$LLAMA_PERPLEXITY_BIN -m $model_path -f $PPL_CORPUS -c $PPL_CTX --n-gpu-layers 999` + out = read(cmd, String) + m = match(r"Final estimate: PPL = ([0-9.]+)", out) + m === nothing && error("Could not parse PPL from llama-perplexity output:\n$out") + return parse(Float64, m.captures[1]) +end + +# ----------------------------------------------------------------------------- +# Sweep +# ----------------------------------------------------------------------------- +@testset "Llama.cpp energy efficiency vs quantization" begin + @testset "quant = " for q in QUANTS + + # Skip quants whose GGUF is not present, so the suite still runs on a + # partial model set. + @on_perftest_ignore begin + # (plain source run: nothing to do) + end + + global s = nothing + n_prompt = 0 + ppl = NaN + # Heavy setup only happens in the generated perf suite. + @on_perftest_exec begin + path = quant_path(q) + if !isfile(path) + @warn "Missing GGUF, skipping" quant=q path=path + continue + end + # Quality axis (Level A): run before opening the in-process FFI + # session below, so the two CUDA contexts (llama-perplexity's + # subprocess and our own) never occupy the GPU at the same time. + #ppl = run_llama_perplexity(path) + + s = LlamaFFI.open_session(path; n_gpu_layers = 999, n_ctx = 4096) + # Warmup (compile kernels, populate caches) — excluded from the + # measured targets below. generate! resets state each call, so this + # leaves the session in a clean, reproducible state. + LlamaFFI.generate!(s, PROMPT, 8) + n_prompt = LlamaFFI.prefill_only!(s, PROMPT) + end + + # Export locals so the metric formulas below can reference them. + @info N_GEN,n_prompt,q + + # ---- Custom metrics ------------------------------------------------- + # Headline: Joules per generated token (whole-request energy / tokens). + # :gpue.dev0 -> per-device GPU energy (Joules) measured around the target. + # For a short prompt and N_GEN >> prompt this ≈ decode J/token; measure + # prefill_only! separately to attribute the split exactly. + @auxiliary_metric name="Energy/token" units="J/token" begin + :gpue / N_GEN + end + + # Energy efficiency: generated tokens per Joule. + @auxiliary_metric name="Efficiency" units="token/J" begin + N_GEN / :gpue + end + + # Average GPU power during decode. + @auxiliary_metric name="Energy" units="W" begin + :gpue + end + + @auxiliary_metric name="Time" units="s" begin :median_time end + + # Decode throughput for context. + @auxiliary_metric name="Throughput" units="token/s" begin + N_GEN / :median_time + end + + # Quality axis: offline llama-perplexity estimate for this quant on + # PPL_CORPUS (run_llama_perplexity, computed once in setup above). + @auxiliary_metric name="Perplexity" units="ppl" begin + ppl + end + + # ---- Pass/fail budget ---------------------------------------------- + # Demonstrates a testable energy target: fail if decode costs more than + # the budget of Joules per generated token. Tune to your GPU/model. + # low_is_bad=false => bigger is worse (energy). + @define_test_metric name="Energy budget" units="J/token" reference=0.5 low_is_bad=false begin + :gpue / N_GEN + end + + # ---- The measured target ------------------------------------------- + # Full request (prefill + decode), IDEMPOTENT: generate! clears the KV + # cache and re-prefills on every call, so all BenchmarkTools samples and + # the separate energy probe start from an identical state. No setup/ + # teardown is needed (and would not help the energy probe anyway — see + # LlamaFFI.jl). Energy is auto-measured by the CUDA extension around this + # call; :gpue.dev0 / N_GEN is the headline Joules-per-token. + @perftest samples=1 evals=1 seconds=120 LlamaFFI.generate!(s, PROMPT, N_GEN) + + # To isolate decode from prefill energy, also measure prefill_only! as a + # second target and subtract; both are idempotent: + # @perftest samples=3 LlamaFFI.prefill_only!(s, PROMPT) + + # Teardown + @on_perftest_exec begin + s === nothing || LlamaFFI.destroy!(s) + end + end +end diff --git a/examples/example-llama-energy/llama_energy_test_amd.jl b/examples/example-llama-energy/llama_energy_test_amd.jl new file mode 100644 index 0000000..61b4c9e --- /dev/null +++ b/examples/example-llama-energy/llama_energy_test_amd.jl @@ -0,0 +1,223 @@ +# ============================================================================= +# PerfTest.jl case study: energy efficiency of LLM inference vs. quantization +# (AMD GPU / ROCm variant) +# ============================================================================= +# +# PRELIMINARY DRAFT. +# +# Story: for a single model, sweep the GGUF quantization level and measure the +# GPU *energy per generated token* using PerfTest.jl's AMDGPU/rocm_smi energy +# feature, alongside a quality proxy (perplexity). The headline result is the +# Pareto tradeoff: how much energy quantization saves vs. how much quality it +# costs. +# +# Identical recipe to llama_energy_test.jl, just on the AMD/ROCm backend: +# inference is driven IN-PROCESS via direct `ccall`s into a HIP-enabled +# libllama (see LlamaFFI.jl — the FFI itself is backend-agnostic; only the +# libllama.so it's pointed at differs). PerfTest.jl's AMDGPU extension +# (../../ext/PerfTest_AMDGPUExt.jl) reads rocm_smi's per-device energy counter +# around each measured target, exposed to formulas as `:amde`/`:amdp` (the +# `:gpue`/`:gpup` analogues from the CUDA extension). +# +# Perplexity (the quality axis) is obtained offline, "Level A" in README +# "Quality axis": shelling out to the ROCm-built `llama-perplexity` tool +# against a fixed corpus, once per quant. See llama_energy_test.jl / README +# for why in-process ("Level B") perplexity was dropped. +# +# Run with: +# using PerfTest +# runperftests("llama_energy_test_amd.jl") +# +# Requirements (see README.md): +# - An AMD GPU with rocm_smi energy-counter support, and ROCm/librocm_smi64 +# installed (see ../../ext/PerfTest_AMDGPUExt.jl). +# - LLAMA_LIB pointing at a ROCm/HIP build of libllama (build_llama_rocm.sh). +# - GGUF weights at several quant levels in $MODEL_DIR (get_models.sh). +# - The `llama-perplexity` tool built alongside libllama, and a fixed text +# corpus (see PPL_CORPUS below). +# ============================================================================= + +using Test +using PerfTest +using AMDGPU + +include("LlamaFFI.jl") + +# ----------------------------------------------------------------------------- +# Configuration +# ----------------------------------------------------------------------------- +@perftest_config " +[general] +verbose = 3 +plotting = true +[regression] +enabled = false +[amdgpu] +enabled = true +" + +# Directory holding the GGUF files, one per quantization level. +const MODEL_DIR = get(ENV, "MODEL_DIR", joinpath(@__DIR__, "models")) + +# Base model name; the quant tag is appended to form the filename. +# e.g. "Qwen3.8-27B-UD-Q4_K_M.gguf" +const MODEL_BASE = get(ENV, "MODEL_BASE", "Qwen3.8-27B") + +# Quantization levels to sweep, smallest -> largest. F16 is the quality +# baseline. Edit to match the GGUF files you actually downloaded/produced. +# +# Smallest-first (rather than the more natural "quality baseline first") +# is deliberate: at this model's size, the largest quants (f16/Q8_0/UD-Q6_K) may +# not fit in a single GPU's VRAM and can OOM. Running them last means the +# smaller, likely-to-fit quants are at least *computed* earlier in the same +# process before that happens. This is only a partial mitigation, though — +# see README "Caveats: OOM behavior" — since results are still saved once, +# after the whole sweep finishes, so a hard crash on a later quant still +# loses everything computed in that run, regardless of this ordering. +const QUANTS = ["UD-Q2_K_XL", "UD-Q3_K_XL", "UD-Q4_K_M", "UD-Q5_K_M", "UD-Q6_K", "Q8_0", "f16"] + +# Fixed workload. Deterministic (greedy) decoding, fixed token budget so that +# "energy per token" is comparable across quants. +const PROMPT = "Explain, in a single detailed paragraph, why energy efficiency " * + "is becoming the dominant cost metric for large language model " * + "inference in production data centers." +const N_GEN = 256 # generated tokens (decode phase) + +quant_path(q) = joinpath(MODEL_DIR, "$(MODEL_BASE)-$(q).gguf") + +# ----------------------------------------------------------------------------- +# Quality axis: offline perplexity (README "Quality axis", Level A) +# ----------------------------------------------------------------------------- + +# `llama-perplexity` is built alongside `libllama` by build_llama_rocm.sh +# (same build dir's bin/); override if it lives elsewhere. +const LLAMA_PERPLEXITY_BIN = get(ENV, "LLAMA_PERPLEXITY_BIN", + joinpath(dirname(get(ENV, "LLAMA_LIB", "")), "llama-perplexity")) + +# Fixed evaluation corpus (plain text, e.g. a WikiText-2 slice). The same +# corpus is used for every quant so the perplexity numbers are comparable. +const PPL_CORPUS = joinpath(get(ENV, "MODEL_DIR", @__DIR__), "wikitext-2-raw", "wiki.test.raw") + +const PPL_CTX = 512 # llama-perplexity's context/chunk size (its -c flag) + +""" + run_llama_perplexity(model_path) -> Float64 + +Run `llama-perplexity` on `PPL_CORPUS` against the GGUF at `model_path` and +parse its "Final estimate: PPL = ..." line. Returns `NaN` (with a `@warn`) if +the binary or corpus is missing, so the sweep still runs without the quality +axis. +""" +function run_llama_perplexity(model_path::AbstractString) + if !isfile(LLAMA_PERPLEXITY_BIN) + @warn "llama-perplexity binary not found, skipping perplexity" bin=LLAMA_PERPLEXITY_BIN + return NaN + end + if !isfile(PPL_CORPUS) + @warn "Perplexity corpus not found, skipping perplexity" corpus=PPL_CORPUS + return NaN + end + cmd = `$LLAMA_PERPLEXITY_BIN -m $model_path -f $PPL_CORPUS -c $PPL_CTX --n-gpu-layers 999` + out = read(cmd, String) + m = match(r"Final estimate: PPL = ([0-9.]+)", out) + m === nothing && error("Could not parse PPL from llama-perplexity output:\n$out") + return parse(Float64, m.captures[1]) +end + +# ----------------------------------------------------------------------------- +# Sweep +# ----------------------------------------------------------------------------- +@testset "Llama.cpp energy efficiency vs quantization (AMD)" begin + @testset "quant = " for q in QUANTS + + # Skip quants whose GGUF is not present, so the suite still runs on a + # partial model set. + @on_perftest_ignore begin + # (plain source run: nothing to do) + end + + global s = nothing + n_prompt = 0 + ppl = NaN + # Heavy setup only happens in the generated perf suite. + @on_perftest_exec begin + path = quant_path(q) + if !isfile(path) + @warn "Missing GGUF, skipping" quant=q path=path + continue + end + # Quality axis (Level A): run before opening the in-process FFI + # session below, so the two GPU contexts (llama-perplexity's + # subprocess and our own) never occupy the GPU at the same time. + #ppl = run_llama_perplexity(path) + + s = LlamaFFI.open_session(path; n_gpu_layers = 999, n_ctx = 4096) + # Warmup (compile kernels, populate caches) — excluded from the + # measured targets below. generate! resets state each call, so this + # leaves the session in a clean, reproducible state. + LlamaFFI.generate!(s, PROMPT, 8) + n_prompt = LlamaFFI.prefill_only!(s, PROMPT) + end + + # Export locals so the metric formulas below can reference them. + @info N_GEN,n_prompt,q + + # ---- Custom metrics ------------------------------------------------- + # Headline: Joules per generated token (whole-request energy / tokens). + # :amde.dev0 -> per-device GPU energy (Joules) measured around the target. + # For a short prompt and N_GEN >> prompt this ≈ decode J/token; measure + # prefill_only! separately to attribute the split exactly. + @auxiliary_metric name="Energy/token" units="J/token" begin + :amde / N_GEN + end + + # Energy efficiency: generated tokens per Joule. + @auxiliary_metric name="Efficiency" units="token/J" begin + N_GEN / :amde + end + + # Average GPU power during decode. + @auxiliary_metric name="Energy" units="W" begin + :amde + end + + @auxiliary_metric name="Time" units="s" begin :median_time end + + # Decode throughput for context. + @auxiliary_metric name="Throughput" units="token/s" begin + N_GEN / :median_time + end + + # Quality axis: offline llama-perplexity estimate for this quant on + # PPL_CORPUS (run_llama_perplexity, computed once in setup above). + @auxiliary_metric name="Perplexity" units="ppl" begin + ppl + end + + # ---- Pass/fail budget ---------------------------------------------- + # Demonstrates a testable energy target: fail if decode costs more than + # the budget of Joules per generated token. Tune to your GPU/model. + # low_is_bad=false => bigger is worse (energy). + @define_test_metric name="Energy budget" units="J/token" reference=0.5 low_is_bad=false begin + :amde / N_GEN + end + + # ---- The measured target ------------------------------------------- + # Full request (prefill + decode), IDEMPOTENT: generate! clears the KV + # cache and re-prefills on every call, so all BenchmarkTools samples and + # the separate energy probe start from an identical state. No setup/ + # teardown is needed (and would not help the energy probe anyway — see + # LlamaFFI.jl). Energy is auto-measured by the AMDGPU extension around + # this call; :amde.dev0 / N_GEN is the headline Joules-per-token. + @perftest samples=1 evals=1 seconds=120 LlamaFFI.generate!(s, PROMPT, N_GEN) + + # To isolate decode from prefill energy, also measure prefill_only! as a + # second target and subtract; both are idempotent: + # @perftest samples=3 LlamaFFI.prefill_only!(s, PROMPT) + + # Teardown + @on_perftest_exec begin + s === nothing || LlamaFFI.destroy!(s) + end + end +end diff --git a/examples/example-llama-energy/llama_energy_test_amd_perfsuite.jl b/examples/example-llama-energy/llama_energy_test_amd_perfsuite.jl new file mode 100644 index 0000000..1142dd3 --- /dev/null +++ b/examples/example-llama-energy/llama_energy_test_amd_perfsuite.jl @@ -0,0 +1,470 @@ +module __PERFTEST__ +using Test +using PerfTest +using AMDGPU +using Libdl +Core.@doc " LlamaFFI\n\nMinimal, self-contained in-process `ccall` binding to a **CUDA-enabled** build of\n`libllama` (llama.cpp). This is the layer that lets PerfTest.jl bracket real\n`llama_decode` calls with NVML energy readings *in the same process as the tests*.\n\nWHY A CUSTOM BUILD?\n-------------------\nThe registered `llama_cpp_jll` artifact ships **CPU-only** binaries (no\n`libggml_cuda`, no CUDA dependency). To measure GPU energy of llama.cpp inference\nyou MUST build llama.cpp yourself with `-DGGML_CUDA=ON` and point this module at\nthe resulting `libllama.so` via the `LLAMA_LIB` environment variable\n(see `build_llama_cuda.sh`).\n\nSTATUS: PRELIMINARY DRAFT\n-------------------------\nThis binding targets a recent llama.cpp C API (the `llama_model_load_from_file` /\n`llama_init_from_model` generation, roughly late-2024/2025 API). The llama.cpp C\nAPI and, especially, the *layout* of `llama_model_params` / `llama_context_params`\nchange across commits. The struct mirrors below MUST be verified against the exact\ncommit you build (`llama.h`). For a robust binding, regenerate with `Clang.jl`\nagainst your pinned `llama.h`. The functions used here are intentionally a minimal\nsubset so that verification is quick.\n\nGreedy (argmax) decoding is implemented directly in Julia over the returned logits\nso we do not depend on the (frequently changing) sampler-chain API. Greedy keeps\ngeneration deterministic, which is important for a controlled energy study.\n" module LlamaFFI + using Libdl + const LIBLLAMA = Ref{String}("") + const LIBHANDLE = Ref{Ptr{Cvoid}}(C_NULL) + Core.@doc " lib()\n\nPath to the CUDA-enabled `libllama`. Resolved from the `LLAMA_CPP_LIB`\nenvironment variable the first time it is needed. Also caches the dlopen handle\nso we can probe for version-dependent symbols with [`sym`](@ref).\n" function lib() + if isempty(LIBLLAMA[]) + path = get(ENV, "LLAMA_LIB", "") + isempty(path) && error("Set LLAMA_LIB to your CUDA-enabled libllama (e.g. " * "/path/to/llama.cpp/build/bin/libllama.so). See build_llama_cuda.sh.") + isfile(path) || error("LLAMA_LIB does not point to a file: $(path)") + LIBHANDLE[] = Libdl.dlopen(path, Libdl.RTLD_LAZY | Libdl.RTLD_GLOBAL) + LIBLLAMA[] = path + end + return LIBLLAMA[] + end + Core.@doc "Resolve a symbol pointer, or C_NULL if this llama.cpp build does not export it." function sym(name::Symbol) + lib() + return Libdl.dlsym(LIBHANDLE[], name; throw_error = false) + end + const LlamaToken = Int32 + const LlamaPos = Int32 + const LlamaSeqId = Int32 + struct LlamaModelParams + devices::Ptr{Cvoid} + tensor_buft_overrides::Ptr{Cvoid} + n_gpu_layers::Cint + split_mode::Cint + load_mode::Cint + main_gpu::Cint + tensor_split::Ptr{Cfloat} + progress_callback::Ptr{Cvoid} + progress_callback_ud::Ptr{Cvoid} + kv_overrides::Ptr{Cvoid} + vocab_only::Bool + check_tensors::Bool + use_extra_bufts::Bool + no_host::Bool + no_alloc::Bool + load_mtp::Bool + end + const LLAMA_FLASH_ATTN_TYPE_DISABLED = Cint(0) + const LLAMA_FLASH_ATTN_TYPE_ENABLED = Cint(1) + struct LlamaContextParams + n_ctx::Cuint + n_batch::Cuint + n_ubatch::Cuint + n_seq_max::Cuint + n_rs_seq::Cuint + n_outputs_max::Cuint + n_threads::Cint + n_threads_batch::Cint + ctx_type::Cint + rope_scaling_type::Cint + pooling_type::Cint + attention_type::Cint + flash_attn_type::Cint + rope_freq_base::Cfloat + rope_freq_scale::Cfloat + yarn_ext_factor::Cfloat + yarn_attn_factor::Cfloat + yarn_beta_fast::Cfloat + yarn_beta_slow::Cfloat + yarn_orig_ctx::Cuint + defrag_thold::Cfloat + cb_eval::Ptr{Cvoid} + cb_eval_ud::Ptr{Cvoid} + type_k::Cint + type_v::Cint + abort_callback::Ptr{Cvoid} + abort_callback_data::Ptr{Cvoid} + embeddings::Bool + offload_kqv::Bool + no_perf::Bool + op_offload::Bool + swa_full::Bool + kv_unified::Bool + samplers::Ptr{Cvoid} + n_samplers::Csize_t + ctx_other::Ptr{Cvoid} + end + struct LlamaBatch + n_tokens::Cint + token::Ptr{LlamaToken} + embd::Ptr{Cfloat} + pos::Ptr{LlamaPos} + n_seq_id::Ptr{Cint} + seq_id::Ptr{Ptr{LlamaSeqId}} + logits::Ptr{Int8} + end + backend_init() = ccall((:llama_backend_init, lib()), Cvoid, ()) + backend_free() = ccall((:llama_backend_free, lib()), Cvoid, ()) + model_default_params() = ccall((:llama_model_default_params, lib()), LlamaModelParams, ()) + context_default_params() = ccall((:llama_context_default_params, lib()), LlamaContextParams, ()) + Core.@doc " load_model(path; n_gpu_layers=999) -> Ptr\n\nLoad a GGUF model with the requested number of layers offloaded to the GPU.\n`n_gpu_layers=999` means \"offload everything\".\n" function load_model(path::AbstractString; n_gpu_layers::Integer = 999) + p = model_default_params() + p = LlamaModelParams(p.devices, p.tensor_buft_overrides, Cint(n_gpu_layers), Cint(0), p.load_mode, Cint(0), p.tensor_split, p.progress_callback, p.progress_callback_ud, p.kv_overrides, p.vocab_only, p.check_tensors, p.use_extra_bufts, p.no_host, p.no_alloc, p.load_mtp) + m = ccall((:llama_model_load_from_file, lib()), Ptr{Cvoid}, (Cstring, LlamaModelParams), path, p) + m == C_NULL && error("Failed to load model: $(path)") + return m + end + function new_context(model::Ptr{Cvoid}; n_ctx::Integer = 4096, n_batch::Integer = 2048, flash_attn::Bool = true, n_threads::Integer = Sys.CPU_THREADS) + p = context_default_params() + p = LlamaContextParams(Cuint(n_ctx), Cuint(n_batch), p.n_ubatch, p.n_seq_max, p.n_rs_seq, p.n_outputs_max, Cint(n_threads), Cint(n_threads), p.ctx_type, p.rope_scaling_type, p.pooling_type, p.attention_type, if flash_attn + LLAMA_FLASH_ATTN_TYPE_ENABLED + else + LLAMA_FLASH_ATTN_TYPE_DISABLED + end, p.rope_freq_base, p.rope_freq_scale, p.yarn_ext_factor, p.yarn_attn_factor, p.yarn_beta_fast, p.yarn_beta_slow, p.yarn_orig_ctx, p.defrag_thold, p.cb_eval, p.cb_eval_ud, p.type_k, p.type_v, p.abort_callback, p.abort_callback_data, p.embeddings, p.offload_kqv, p.no_perf, p.op_offload, p.swa_full, p.kv_unified, p.samplers, p.n_samplers, p.ctx_other) + ctx = ccall((:llama_init_from_model, lib()), Ptr{Cvoid}, (Ptr{Cvoid}, LlamaContextParams), model, p) + ctx == C_NULL && error("Failed to create context") + return ctx + end + free_model(model::Ptr{Cvoid}) = ccall((:llama_model_free, lib()), Cvoid, (Ptr{Cvoid},), model) + free_context(ctx::Ptr{Cvoid}) = ccall((:llama_free, lib()), Cvoid, (Ptr{Cvoid},), ctx) + get_vocab(model::Ptr{Cvoid}) = ccall((:llama_model_get_vocab, lib()), Ptr{Cvoid}, (Ptr{Cvoid},), model) + n_vocab(vocab::Ptr{Cvoid}) = Int(ccall((:llama_vocab_n_tokens, lib()), Cint, (Ptr{Cvoid},), vocab)) + model_size_bytes(model::Ptr{Cvoid}) = Int(ccall((:llama_model_size, lib()), UInt64, (Ptr{Cvoid},), model)) + function tokenize(vocab::Ptr{Cvoid}, text::AbstractString; add_special::Bool = true, parse_special::Bool = true) + cap = ncodeunits(text) + 16 + toks = Vector{LlamaToken}(undef, cap) + n = ccall((:llama_tokenize, lib()), Cint, (Ptr{Cvoid}, Cstring, Cint, Ptr{LlamaToken}, Cint, Bool, Bool), vocab, text, ncodeunits(text), toks, cap, add_special, parse_special) + n < 0 && error("tokenize: buffer too small (needed $(-n))") + return toks[1:n] + end + is_eog(vocab::Ptr{Cvoid}, tok::LlamaToken) = ccall((:llama_vocab_is_eog, lib()), Bool, (Ptr{Cvoid}, LlamaToken), vocab, tok) + batch_get_one(tokens::Vector{LlamaToken}) = ccall((:llama_batch_get_one, lib()), LlamaBatch, (Ptr{LlamaToken}, Cint), tokens, Cint(length(tokens))) + function decode!(ctx::Ptr{Cvoid}, batch::LlamaBatch) + rc = ccall((:llama_decode, lib()), Cint, (Ptr{Cvoid}, LlamaBatch), ctx, batch) + rc != 0 && error("llama_decode failed: rc=$(rc)") + return nothing + end + function logits_ith(ctx::Ptr{Cvoid}, i::Integer, nvoc::Integer) + p = ccall((:llama_get_logits_ith, lib()), Ptr{Cfloat}, (Ptr{Cvoid}, Cint), ctx, Cint(i)) + p == C_NULL && error("llama_get_logits_ith returned NULL") + return unsafe_wrap(Array, p, nvoc) + end + argmax_token(logits::AbstractVector{<:Real}) = LlamaToken(argmax(logits) - 1) + Core.@doc " Session\n\nHolds a loaded model + context and cached vocab size. Create once per\nquantization level, reuse for warmup + measurement runs.\n" mutable struct Session + model::Ptr{Cvoid} + ctx::Ptr{Cvoid} + vocab::Ptr{Cvoid} + nvoc::Int + end + binit = false + function open_session(gguf_path::AbstractString; n_gpu_layers = 999, n_ctx = 4096, flash_attn = true) + backend_init() + model = load_model(gguf_path; n_gpu_layers = n_gpu_layers) + ctx = new_context(model; n_ctx = n_ctx, flash_attn = flash_attn) + vocab = get_vocab(model) + return Session(model, ctx, vocab, n_vocab(vocab)) + end + function close_session(s::Session) + free_context(s.ctx) + free_model(s.model) + backend_free() + return nothing + end + const _RESET_KIND = Ref{Symbol}(:unresolved) + function _resolve_reset() + if sym(:llama_get_memory) != C_NULL && sym(:llama_memory_clear) != C_NULL + _RESET_KIND[] = :memory + elseif sym(:llama_kv_self_clear) != C_NULL + _RESET_KIND[] = :kv_self + elseif sym(:llama_kv_cache_clear) != C_NULL + _RESET_KIND[] = :kv_cache + else + error("No known KV-cache clear symbol found in libllama; check your version.") + end + return _RESET_KIND[] + end + Core.@doc " reset!(s)\n\nClear the context KV cache so the next `prefill!`/`decode_n!` starts from a\nclean state. This is the key to idempotent, repeatable measurements.\n" function reset!(s::Session) + _RESET_KIND[] == :unresolved && _resolve_reset() + if _RESET_KIND[] == :memory + mem = ccall((:llama_get_memory, lib()), Ptr{Cvoid}, (Ptr{Cvoid},), s.ctx) + ccall((:llama_memory_clear, lib()), Cvoid, (Ptr{Cvoid}, Bool), mem, true) + elseif _RESET_KIND[] == :kv_self + ccall((:llama_kv_self_clear, lib()), Cvoid, (Ptr{Cvoid},), s.ctx) + else + ccall((:llama_kv_cache_clear, lib()), Cvoid, (Ptr{Cvoid},), s.ctx) + end + return nothing + end + const _MODEL_FREE_KIND = Ref{Symbol}(:unresolved) + function _resolve_model_free() + if sym(:llama_model_free) != C_NULL + _MODEL_FREE_KIND[] = :new + elseif sym(:llama_free_model) != C_NULL + _MODEL_FREE_KIND[] = :old + else + error("No known model-free symbol found in libllama; check your version.") + end + return _MODEL_FREE_KIND[] + end + Core.@doc " destroy!(s::Session)\n\nFree the context (KV cache + compute buffers) and the model (tensor weight\nbuffers) that were allocated on the GPU for this Session. `reset!` alone only\nclears KV-cache *contents*; it never releases the VRAM allocations, which is\nwhy memory climbs across models unless this is called too.\n\n`s.vocab` is *not* freed here — it's a pointer owned by the model\n(`llama_model_get_vocab`), not a separate allocation, and becomes invalid\nautomatically once `s.model` is freed.\n\nSafe to call multiple times; no-ops once fields are already null.\n" function destroy!(s::Session) + if s.ctx != C_NULL + ccall((:llama_free, lib()), Cvoid, (Ptr{Cvoid},), s.ctx) + s.ctx = C_NULL + end + if s.model != C_NULL + _MODEL_FREE_KIND[] == :unresolved && _resolve_model_free() + if _MODEL_FREE_KIND[] == :new + ccall((:llama_model_free, lib()), Cvoid, (Ptr{Cvoid},), s.model) + else + ccall((:llama_free_model, lib()), Cvoid, (Ptr{Cvoid},), s.model) + end + s.model = C_NULL + end + s.vocab = C_NULL + s.nvoc = 0 + GC.gc() + return nothing + end + Core.@doc " prefill!(s, prompt) -> (last_token, n_prompt_tokens)\n\nRun the prompt through the model in a single batch (the \"prefill\" / prompt\nprocessing phase). Returns the greedily-selected first generated token and the\nnumber of prompt tokens.\n\nNOTE: this is a **stateful** primitive — it appends to the KV cache. Call\n[`reset!`](@ref) first if you need a clean state. For measurement targets use\nthe idempotent [`generate!`](@ref) / [`prefill_only!`](@ref) instead.\n" function prefill!(s::Session, prompt::AbstractString) + toks = tokenize(s.vocab, prompt) + decode!(s.ctx, batch_get_one(toks)) + next = argmax_token(logits_ith(s.ctx, -1, s.nvoc)) + return (next, length(toks)) + end + Core.@doc " decode_n!(s, first_token, n) -> n_generated\n\nAutoregressively generate up to `n` tokens starting from `first_token`\n(greedy), stopping early on EOG.\n\nNOTE: **stateful** — advances the KV cache. Not idempotent on its own; use it\nvia [`generate!`](@ref) for repeatable measurements.\n" function decode_n!(s::Session, first_token::LlamaToken, n::Integer) + tok = first_token + generated = 0 + scratch = LlamaToken[0] + for _ = 1:n + is_eog(s.vocab, tok) && break + generated += 1 + scratch[1] = tok + decode!(s.ctx, batch_get_one(scratch)) + tok = argmax_token(logits_ith(s.ctx, -1, s.nvoc)) + end + return generated + end + Core.@doc " generate!(s, prompt, n_gen) -> n_generated\n\nIdempotent full request: clear KV cache, prefill `prompt`, then greedily decode\nup to `n_gen` tokens. Safe to call repeatedly. This is the primary measured\ntarget; whole-request energy divided by `n_generated` gives Joules per token.\n" function generate!(s::Session, prompt::AbstractString, n_gen::Integer) + reset!(s) + (first_tok, _) = prefill!(s, prompt) + return decode_n!(s, first_tok, n_gen) + end + Core.@doc " prefill_only!(s, prompt) -> n_prompt_tokens\n\nIdempotent prefill: clear KV cache and process the prompt only. Measure this as\na second target to isolate prefill energy, so decode energy ≈ generate! energy −\nprefill_only! energy.\n" function prefill_only!(s::Session, prompt::AbstractString) + reset!(s) + (_, n_prompt) = prefill!(s, prompt) + return n_prompt + end + end +rocm_smi_path = Libdl.find_library(["librocm_smi64"]) +if isempty(rocm_smi_path) + @info "librocm_smi64 not found via Libdl.find_library" +else + resolved = Libdl.dlpath(Libdl.dlopen(rocm_smi_path)) + @info "librocm_smi64 resolved to:" find_library_result = rocm_smi_path dlpath = resolved +end +PerfTest._perftest_config("[perfcompare]\nenabled = true\n\n[MPI]\nmode = \"reduce\"\nenabled = false\n\n[amdgpu]\nenabled = true\n\n[general]\nsave_results = true\nmax_saved_results = 20\nsuppress_output = true\nsave_folder = \".perftests\"\nthreads_per_numa = \"single\"\nrecursive = true\nverbose = 3\nautoflops = false\nplotting = true\nnumas = \"single\"\nlogs_enabled = true\nsafe_formulas = false\n\n[regression]\nenabled = false\ndedicated_reference_file = \"\"\ndefault_threshold = 1.1\nuse_bencher = false\n\n[roofline]\nenabled = true\ndefault_threshold = 0.5\n\n[memory_bandwidth]\nenabled = true\ndefault_threshold = 0.5\n\n[machine_benchmarking]\nmemory_bandwidth_test_buffer_size = 0\n\n[bencher]\napi_key = \"\"\norganization = \"\"\napi_url = \"https://api.bencher.dev\"\nproject_name = \"\"\ncustom_testbed_name = \"\"\n") +const MODEL_DIR = get(ENV, "MODEL_DIR", joinpath(@__DIR__(), "models")) +const MODEL_BASE = get(ENV, "MODEL_BASE", "Qwen3.8-27B") +const QUANTS = ["f16", "Q8_0", "UD-Q6_K", "UD-Q5_K_M", "UD-Q4_K_M", "UD-Q3_K_XL", "UD-Q2_K_XL"] +const PROMPT = "Explain, in a single detailed paragraph, why energy efficiency " * "is becoming the dominant cost metric for large language model " * "inference in production data centers." +const N_GEN = 256 +quant_path(q) = joinpath(MODEL_DIR, "$(MODEL_BASE)-$(q).gguf") +const LLAMA_PERPLEXITY_BIN = get(ENV, "LLAMA_PERPLEXITY_BIN", joinpath(dirname(get(ENV, "LLAMA_LIB", "")), "llama-perplexity")) +const PPL_CORPUS = joinpath(get(ENV, "MODEL_DIR", @__DIR__()), "wikitext-2-raw", "wiki.test.raw") +const PPL_CTX = 512 +Core.@doc " run_llama_perplexity(model_path) -> Float64\n\nRun `llama-perplexity` on `PPL_CORPUS` against the GGUF at `model_path` and\nparse its \"Final estimate: PPL = ...\" line. Returns `NaN` (with a `@warn`) if\nthe binary or corpus is missing, so the sweep still runs without the quality\naxis.\n" function run_llama_perplexity(model_path::AbstractString) + if !(isfile(LLAMA_PERPLEXITY_BIN)) + @warn "llama-perplexity binary not found, skipping perplexity" bin = LLAMA_PERPLEXITY_BIN + return NaN + end + if !(isfile(PPL_CORPUS)) + @warn "Perplexity corpus not found, skipping perplexity" corpus = PPL_CORPUS + return NaN + end + cmd = `$LLAMA_PERPLEXITY_BIN -m $model_path -f $PPL_CORPUS -c $PPL_CTX --n-gpu-layers 999` + out = read(cmd, String) + m = match(r"Final estimate: PPL = ([0-9.]+)", out) + m === nothing && error("Could not parse PPL from llama-perplexity output:\n$(out)") + return parse(Float64, m.captures[1]) + end +using Test, Dates +nothing +using PerfTest: DepthRecord, Metric_Test, Methodology_Result, StrOrSym, Metric_Result, magnitudeAdjust, MPISetup, newMetricResult, buildPrimitiveMetrics!, measureCPUPeakFlops!, measureMemBandwidth!, addLog, @PRFTBenchmark, PRFTBenchmarkGroup, @PRFTCapture_out, @PRFTCount_ops, PRFTflop, @PRFTSuppress, Test_Result, by_index, regression, Suite_Execution_Result, savePrimitives, main_rank, GlobalSuiteData, @perftestset, PerfTestSet, extractTestResults, saveMethodologyData, Configuration +_t_begin = time() +_GLOBAL_MODE = PerfTest.NormalMode +if main_rank(PerfTest.NormalMode) + path = "./.perftests/llama_energy_test_amd.jl_PERFORMANCE.JLD2" + nofile = true + if isfile(path) + nofile = false + datafile = PerfTest.openDataFile(path) + else + datafile = PerfTest.Perftest_Datafile_Root(PerfTest.Suite_Execution_Result[]) + end + regression_path = (Configuration.CONFIG["regression"])["dedicated_reference_file"] + if regression_path != "" && isfile(regression_path) + regression_file = PerfTest.openDataFile(regression_path) + else + if regression_path != "" + regression_file = PerfTest.Perftest_Datafile_Root(PerfTest.Suite_Execution_Result[]) + else + regression_file = datafile + regression_path = path + end + end + _PRFT_GLOBALS = GlobalSuiteData(datafile, path, "llama_energy_test_amd.jl") + if length(regression_file.results) > 0 + for i = length(regression_file.results):-1:1 + if length(retrievePerfTests(regression_path, get = :tests, where_pred = testFailed, execution = i)) == 0 + _PRFT_GLOBALS.old = (regression_file.results[i]).perftests + println("Regression: Previous performance reference for this configuration has been found, regression tests could be performed. Regression is currenctly $(if false + "enabled" +else + "disabled" +end)).") + break + end + end + else + _PRFT_GLOBALS.old = nothing + end +else + _PRFT_GLOBALS = GlobalSuiteData() +end +let + PerfTest.Topology.getMachineTopology!() + _PRFT_GLOBALS.builtins[:MEM_CACHE_SIZES] = PerfTest.Topology.getCacheSizes() +end +TS = @perftestset(PerfTestSet, "Llama.cpp energy efficiency vs quantization (AMD)", begin + local ts = Test.get_testset() + ts.old_test_results = _PRFT_GLOBALS.old + nothing + TS = @perftestset(PerfTestSet, "quant = ", for q = QUANTS + local ts = Test.get_testset() + ts.iterator = q + nothing + global s = nothing + n_prompt = 0 + ppl = NaN + path = quant_path(q) + if !(isfile(path)) + @warn "Missing GGUF, skipping" quant = q path = path + continue + end + s = LlamaFFI.open_session(path; n_gpu_layers = 999, n_ctx = 4096) + LlamaFFI.generate!(s, PROMPT, 8) + n_prompt = LlamaFFI.prefill_only!(s, PROMPT) + @info (N_GEN, n_prompt, q) + nothing + nothing + nothing + nothing + nothing + nothing + @define_test_metric name = "Energy budget" units = "J/token" reference = 0.5 low_is_bad = false :gpue.dev0 / N_GEN + ts.benchmarks["Test 1"] = @PRFTBenchmark(($LlamaFFI).generate!($s, $PROMPT, $N_GEN), samples = 1, evals = 1, seconds = 120) + extensions = PerfTest.ExtensionData[] + push!(extensions, PerfTest.NoExtensionData()) + push!(extensions, PerfTest.NoExtensionData()) + @info PerfTest.amdgpu_devices() + (energy, power) = begin + AMDGPU.synchronize() + devices = PerfTest.amdgpu_devices() + isempty(devices) && @warn("No AMDGPU monitor devices detected via ROCm SMI; energy/power readings will be empty.") + pre = [] + post = [] + for d = devices + push!(pre, PerfTest.read_joule(d)) + end + LlamaFFI.generate!(s, PROMPT, N_GEN) + AMDGPU.synchronize() + for d = devices + push!(post, PerfTest.read_joule(d)) + end + energy = post .- pre + power = energy + @info (energy, power) + (energy, power) + end + push!(extensions, PerfTest.AMDGPUExtensionData(energy, power)) + test_res = Test_Result("Test 1", extensions) + ts.test_results["Test 1"] = test_res + keys = ["Llama.cpp energy efficiency vs quantization (AMD)", "quant = "] + append!(keys, ["Test 1"]) + old_test_res = _PRFT_GLOBALS.old + for key = keys + if !(old_test_res isa Nothing) && haskey(old_test_res, key) + old_test_res = old_test_res[key] + else + old_test_res = nothing + break + end + end + test_res.primitives[:autoflop] = 0 + test_res.primitives[:printed_output] = @PRFTCapture_out(test_res.primitives[:ret_value] = LlamaFFI.generate!(s, PROMPT, N_GEN)) + buildPrimitiveMetrics!(PerfTest.NormalMode, ts, test_res) + let m = newMetricResult(PerfTest.NormalMode, name = "Energy/token", units = "J/token", value = (test_res.extensions[3]).energy[1] / N_GEN, auxiliary = true) + test_res.auxiliar[Symbol("Energy/token")] = m + end + let m = newMetricResult(PerfTest.NormalMode, name = "Efficiency", units = "token/J", value = N_GEN / (test_res.extensions[3]).energy[1], auxiliary = true) + test_res.auxiliar[:Efficiency] = m + end + let m = newMetricResult(PerfTest.NormalMode, name = "Energy", units = "W", value = (test_res.extensions[3]).energy[1], auxiliary = true) + test_res.auxiliar[:Energy] = m + end + let m = newMetricResult(PerfTest.NormalMode, name = "Time", units = "s", value = test_res.primitives[:median_time], auxiliary = true) + test_res.auxiliar[:Time] = m + end + let m = newMetricResult(PerfTest.NormalMode, name = "Throughput", units = "token/s", value = N_GEN / test_res.primitives[:median_time], auxiliary = true) + test_res.auxiliar[:Throughput] = m + end + let m = newMetricResult(PerfTest.NormalMode, name = "Perplexity", units = "ppl", value = ppl, auxiliary = true) + test_res.auxiliar[:Perplexity] = m + end + if main_rank(PerfTest.NormalMode) + end + s === nothing || LlamaFFI.destroy!(s) + nothing + end) + nothing + nothing + end) +if main_rank(PerfTest.NormalMode) + @info TS + testresdict = Dict{String, Union{Dict, Test_Result}}() + if TS isa Vector + benchmarks = PerfTest.newBenchmarkGroup() + for ts = TS + testresdict[ts.description * "_" * string(ts.iterator)] = extractTestResults(TS) + benchmarks[ts.description * "_" * string(ts.iterator)] = ts.benchmarks + end + newres = Suite_Execution_Result(timestamp = datetime2unix(now()), elapsed = time() - _t_begin, benchmarks = benchmarks, perftests = testresdict) + else + testresdict[TS.description] = extractTestResults(TS) + newres = Suite_Execution_Result(timestamp = datetime2unix(now()), elapsed = time() - _t_begin, benchmarks = TS.benchmarks, perftests = testresdict) + end + if PerfTest.testsSucceeded(TS) && ((Configuration.CONFIG["regression"])["enabled"] && regression_path != _PRFT_GLOBALS.datafile_path) + println("All performance tests have passed. Values will be registered as reference for regression testing.") + push!(regression_file.results, newres) + let + res_num = length(regression_file.results) + if (excess = 20 - res_num) <= 0 + PerfTest.p_yellow("[ℹ]") + println(" Regression: Exceeded maximum recorded results. The oldest $(-1 * excess + 1) result/s will be removed.") + for i = 1:-1 * excess + 1 + popfirst!(regression_file.results) + end + end + end + PerfTest.saveDataFile(regression_path, regression_file) + else + println("Some tests failed or errored.") + end + let + push!(_PRFT_GLOBALS.datafile.results, newres) + res_num = length(_PRFT_GLOBALS.datafile.results) + if (excess = 20 - res_num) <= 0 + PerfTest.p_yellow("[ℹ]") + println(" Results File: Exceeded maximum recorded results. The oldest $(-1 * excess + 1) result/s will be removed.") + for i = 1:-1 * excess + 1 + popfirst!(_PRFT_GLOBALS.datafile.results) + end + end + end + PerfTest.saveDataFile(_PRFT_GLOBALS.datafile_path, _PRFT_GLOBALS.datafile) + println("[✓] $(path) Performance tests have been finished (elapsed $(newres.elapsed) s)") + if (Configuration.CONFIG["regression"])["use_bencher"] + bencher_config = Configuration.CONFIG["bencher"] + PerfTest.BencherREST.exportSuiteToBencher(_PRFT_GLOBALS.datafile, bencher_config) + end + PerfTest.clean(PerfTest.NormalMode) +end +end \ No newline at end of file diff --git a/examples/example-llama-energy/llama_energy_test_perfsuite.jl b/examples/example-llama-energy/llama_energy_test_perfsuite.jl new file mode 100644 index 0000000..f10c1a0 --- /dev/null +++ b/examples/example-llama-energy/llama_energy_test_perfsuite.jl @@ -0,0 +1,519 @@ +module __PERFTEST__ +using Test +using PerfTest +using CUDA +Core.@doc " LlamaFFI\n\nMinimal, self-contained in-process `ccall` binding to a **CUDA-enabled** build of\n`libllama` (llama.cpp). This is the layer that lets PerfTest.jl bracket real\n`llama_decode` calls with NVML energy readings *in the same process as the tests*.\n\nWHY A CUSTOM BUILD?\n-------------------\nThe registered `llama_cpp_jll` artifact ships **CPU-only** binaries (no\n`libggml_cuda`, no CUDA dependency). To measure GPU energy of llama.cpp inference\nyou MUST build llama.cpp yourself with `-DGGML_CUDA=ON` and point this module at\nthe resulting `libllama.so` via the `LLAMA_LIB` environment variable\n(see `build_llama_cuda.sh`).\n\nSTATUS: PRELIMINARY DRAFT\n-------------------------\nThis binding targets a recent llama.cpp C API (the `llama_model_load_from_file` /\n`llama_init_from_model` generation, roughly late-2024/2025 API). The llama.cpp C\nAPI and, especially, the *layout* of `llama_model_params` / `llama_context_params`\nchange across commits. The struct mirrors below MUST be verified against the exact\ncommit you build (`llama.h`). For a robust binding, regenerate with `Clang.jl`\nagainst your pinned `llama.h`. The functions used here are intentionally a minimal\nsubset so that verification is quick.\n\nGreedy (argmax) decoding is implemented directly in Julia over the returned logits\nso we do not depend on the (frequently changing) sampler-chain API. Greedy keeps\ngeneration deterministic, which is important for a controlled energy study.\n" module LlamaFFI + using Libdl + const LIBLLAMA = Ref{String}("") + const LIBHANDLE = Ref{Ptr{Cvoid}}(C_NULL) + Core.@doc " lib()\n\nPath to the CUDA-enabled `libllama`. Resolved from the `LLAMA_CPP_LIB`\nenvironment variable the first time it is needed. Also caches the dlopen handle\nso we can probe for version-dependent symbols with [`sym`](@ref).\n" function lib() + if isempty(LIBLLAMA[]) + path = get(ENV, "LLAMA_LIB", "") + isempty(path) && error("Set LLAMA_LIB to your CUDA-enabled libllama (e.g. " * "/path/to/llama.cpp/build/bin/libllama.so). See build_llama_cuda.sh.") + isfile(path) || error("LLAMA_LIB does not point to a file: $(path)") + LIBHANDLE[] = Libdl.dlopen(path, Libdl.RTLD_LAZY | Libdl.RTLD_GLOBAL) + LIBLLAMA[] = path + end + return LIBLLAMA[] + end + Core.@doc "Resolve a symbol pointer, or C_NULL if this llama.cpp build does not export it." function sym(name::Symbol) + lib() + return Libdl.dlsym(LIBHANDLE[], name; throw_error = false) + end + const LlamaToken = Int32 + const LlamaPos = Int32 + const LlamaSeqId = Int32 + struct LlamaModelParams + devices::Ptr{Cvoid} + tensor_buft_overrides::Ptr{Cvoid} + n_gpu_layers::Cint + split_mode::Cint + load_mode::Cint + main_gpu::Cint + tensor_split::Ptr{Cfloat} + progress_callback::Ptr{Cvoid} + progress_callback_ud::Ptr{Cvoid} + kv_overrides::Ptr{Cvoid} + vocab_only::Bool + check_tensors::Bool + use_extra_bufts::Bool + no_host::Bool + no_alloc::Bool + load_mtp::Bool + end + const LLAMA_FLASH_ATTN_TYPE_DISABLED = Cint(0) + const LLAMA_FLASH_ATTN_TYPE_ENABLED = Cint(1) + struct LlamaContextParams + n_ctx::Cuint + n_batch::Cuint + n_ubatch::Cuint + n_seq_max::Cuint + n_rs_seq::Cuint + n_outputs_max::Cuint + n_threads::Cint + n_threads_batch::Cint + ctx_type::Cint + rope_scaling_type::Cint + pooling_type::Cint + attention_type::Cint + flash_attn_type::Cint + rope_freq_base::Cfloat + rope_freq_scale::Cfloat + yarn_ext_factor::Cfloat + yarn_attn_factor::Cfloat + yarn_beta_fast::Cfloat + yarn_beta_slow::Cfloat + yarn_orig_ctx::Cuint + defrag_thold::Cfloat + cb_eval::Ptr{Cvoid} + cb_eval_ud::Ptr{Cvoid} + type_k::Cint + type_v::Cint + abort_callback::Ptr{Cvoid} + abort_callback_data::Ptr{Cvoid} + embeddings::Bool + offload_kqv::Bool + no_perf::Bool + op_offload::Bool + swa_full::Bool + kv_unified::Bool + samplers::Ptr{Cvoid} + n_samplers::Csize_t + ctx_other::Ptr{Cvoid} + end + struct LlamaBatch + n_tokens::Cint + token::Ptr{LlamaToken} + embd::Ptr{Cfloat} + pos::Ptr{LlamaPos} + n_seq_id::Ptr{Cint} + seq_id::Ptr{Ptr{LlamaSeqId}} + logits::Ptr{Int8} + end + backend_init() = ccall((:llama_backend_init, lib()), Cvoid, ()) + backend_free() = ccall((:llama_backend_free, lib()), Cvoid, ()) + model_default_params() = ccall((:llama_model_default_params, lib()), LlamaModelParams, ()) + context_default_params() = ccall((:llama_context_default_params, lib()), LlamaContextParams, ()) + Core.@doc " load_model(path; n_gpu_layers=999) -> Ptr\n\nLoad a GGUF model with the requested number of layers offloaded to the GPU.\n`n_gpu_layers=999` means \"offload everything\".\n" function load_model(path::AbstractString; n_gpu_layers::Integer = 999) + p = model_default_params() + p = LlamaModelParams(p.devices, p.tensor_buft_overrides, Cint(n_gpu_layers), Cint(0), p.load_mode, Cint(0), p.tensor_split, p.progress_callback, p.progress_callback_ud, p.kv_overrides, p.vocab_only, p.check_tensors, p.use_extra_bufts, p.no_host, p.no_alloc, p.load_mtp) + m = ccall((:llama_model_load_from_file, lib()), Ptr{Cvoid}, (Cstring, LlamaModelParams), path, p) + m == C_NULL && error("Failed to load model: $(path)") + return m + end + function new_context(model::Ptr{Cvoid}; n_ctx::Integer = 4096, n_batch::Integer = 2048, flash_attn::Bool = true, n_threads::Integer = Sys.CPU_THREADS) + p = context_default_params() + p = LlamaContextParams(Cuint(n_ctx), Cuint(n_batch), p.n_ubatch, p.n_seq_max, p.n_rs_seq, p.n_outputs_max, Cint(n_threads), Cint(n_threads), p.ctx_type, p.rope_scaling_type, p.pooling_type, p.attention_type, if flash_attn + LLAMA_FLASH_ATTN_TYPE_ENABLED + else + LLAMA_FLASH_ATTN_TYPE_DISABLED + end, p.rope_freq_base, p.rope_freq_scale, p.yarn_ext_factor, p.yarn_attn_factor, p.yarn_beta_fast, p.yarn_beta_slow, p.yarn_orig_ctx, p.defrag_thold, p.cb_eval, p.cb_eval_ud, p.type_k, p.type_v, p.abort_callback, p.abort_callback_data, p.embeddings, p.offload_kqv, p.no_perf, p.op_offload, p.swa_full, p.kv_unified, p.samplers, p.n_samplers, p.ctx_other) + ctx = ccall((:llama_init_from_model, lib()), Ptr{Cvoid}, (Ptr{Cvoid}, LlamaContextParams), model, p) + ctx == C_NULL && error("Failed to create context") + return ctx + end + free_model(model::Ptr{Cvoid}) = ccall((:llama_model_free, lib()), Cvoid, (Ptr{Cvoid},), model) + free_context(ctx::Ptr{Cvoid}) = ccall((:llama_free, lib()), Cvoid, (Ptr{Cvoid},), ctx) + get_vocab(model::Ptr{Cvoid}) = ccall((:llama_model_get_vocab, lib()), Ptr{Cvoid}, (Ptr{Cvoid},), model) + n_vocab(vocab::Ptr{Cvoid}) = Int(ccall((:llama_vocab_n_tokens, lib()), Cint, (Ptr{Cvoid},), vocab)) + model_size_bytes(model::Ptr{Cvoid}) = Int(ccall((:llama_model_size, lib()), UInt64, (Ptr{Cvoid},), model)) + function tokenize(vocab::Ptr{Cvoid}, text::AbstractString; add_special::Bool = true, parse_special::Bool = true) + cap = ncodeunits(text) + 16 + toks = Vector{LlamaToken}(undef, cap) + n = ccall((:llama_tokenize, lib()), Cint, (Ptr{Cvoid}, Cstring, Cint, Ptr{LlamaToken}, Cint, Bool, Bool), vocab, text, ncodeunits(text), toks, cap, add_special, parse_special) + n < 0 && error("tokenize: buffer too small (needed $(-n))") + return toks[1:n] + end + is_eog(vocab::Ptr{Cvoid}, tok::LlamaToken) = ccall((:llama_vocab_is_eog, lib()), Bool, (Ptr{Cvoid}, LlamaToken), vocab, tok) + batch_get_one(tokens::Vector{LlamaToken}) = ccall((:llama_batch_get_one, lib()), LlamaBatch, (Ptr{LlamaToken}, Cint), tokens, Cint(length(tokens))) + function decode!(ctx::Ptr{Cvoid}, batch::LlamaBatch) + rc = ccall((:llama_decode, lib()), Cint, (Ptr{Cvoid}, LlamaBatch), ctx, batch) + rc != 0 && error("llama_decode failed: rc=$(rc)") + return nothing + end + function logits_ith(ctx::Ptr{Cvoid}, i::Integer, nvoc::Integer) + p = ccall((:llama_get_logits_ith, lib()), Ptr{Cfloat}, (Ptr{Cvoid}, Cint), ctx, Cint(i)) + p == C_NULL && error("llama_get_logits_ith returned NULL") + return unsafe_wrap(Array, p, nvoc) + end + argmax_token(logits::AbstractVector{<:Real}) = LlamaToken(argmax(logits) - 1) + Core.@doc " Session\n\nHolds a loaded model + context and cached vocab size. Create once per\nquantization level, reuse for warmup + measurement runs.\n" mutable struct Session + model::Ptr{Cvoid} + ctx::Ptr{Cvoid} + vocab::Ptr{Cvoid} + nvoc::Int + end + binit = false + function open_session(gguf_path::AbstractString; n_gpu_layers = 999, n_ctx = 4096, flash_attn = true) + backend_init() + model = load_model(gguf_path; n_gpu_layers = n_gpu_layers) + ctx = new_context(model; n_ctx = n_ctx, flash_attn = flash_attn) + vocab = get_vocab(model) + return Session(model, ctx, vocab, n_vocab(vocab)) + end + function close_session(s::Session) + free_context(s.ctx) + free_model(s.model) + backend_free() + return nothing + end + const _RESET_KIND = Ref{Symbol}(:unresolved) + function _resolve_reset() + if sym(:llama_get_memory) != C_NULL && sym(:llama_memory_clear) != C_NULL + _RESET_KIND[] = :memory + elseif sym(:llama_kv_self_clear) != C_NULL + _RESET_KIND[] = :kv_self + elseif sym(:llama_kv_cache_clear) != C_NULL + _RESET_KIND[] = :kv_cache + else + error("No known KV-cache clear symbol found in libllama; check your version.") + end + return _RESET_KIND[] + end + Core.@doc " reset!(s)\n\nClear the context KV cache so the next `prefill!`/`decode_n!` starts from a\nclean state. This is the key to idempotent, repeatable measurements.\n" function reset!(s::Session) + _RESET_KIND[] == :unresolved && _resolve_reset() + if _RESET_KIND[] == :memory + mem = ccall((:llama_get_memory, lib()), Ptr{Cvoid}, (Ptr{Cvoid},), s.ctx) + ccall((:llama_memory_clear, lib()), Cvoid, (Ptr{Cvoid}, Bool), mem, true) + elseif _RESET_KIND[] == :kv_self + ccall((:llama_kv_self_clear, lib()), Cvoid, (Ptr{Cvoid},), s.ctx) + else + ccall((:llama_kv_cache_clear, lib()), Cvoid, (Ptr{Cvoid},), s.ctx) + end + return nothing + end + const _MODEL_FREE_KIND = Ref{Symbol}(:unresolved) + function _resolve_model_free() + if sym(:llama_model_free) != C_NULL + _MODEL_FREE_KIND[] = :new + elseif sym(:llama_free_model) != C_NULL + _MODEL_FREE_KIND[] = :old + else + error("No known model-free symbol found in libllama; check your version.") + end + return _MODEL_FREE_KIND[] + end + Core.@doc " destroy!(s::Session)\n\nFree the context (KV cache + compute buffers) and the model (tensor weight\nbuffers) that were allocated on the GPU for this Session. `reset!` alone only\nclears KV-cache *contents*; it never releases the VRAM allocations, which is\nwhy memory climbs across models unless this is called too.\n\n`s.vocab` is *not* freed here — it's a pointer owned by the model\n(`llama_model_get_vocab`), not a separate allocation, and becomes invalid\nautomatically once `s.model` is freed.\n\nSafe to call multiple times; no-ops once fields are already null.\n" function destroy!(s::Session) + if s.ctx != C_NULL + ccall((:llama_free, lib()), Cvoid, (Ptr{Cvoid},), s.ctx) + s.ctx = C_NULL + end + if s.model != C_NULL + _MODEL_FREE_KIND[] == :unresolved && _resolve_model_free() + if _MODEL_FREE_KIND[] == :new + ccall((:llama_model_free, lib()), Cvoid, (Ptr{Cvoid},), s.model) + else + ccall((:llama_free_model, lib()), Cvoid, (Ptr{Cvoid},), s.model) + end + s.model = C_NULL + end + s.vocab = C_NULL + s.nvoc = 0 + GC.gc() + return nothing + end + Core.@doc " prefill!(s, prompt) -> (last_token, n_prompt_tokens)\n\nRun the prompt through the model in a single batch (the \"prefill\" / prompt\nprocessing phase). Returns the greedily-selected first generated token and the\nnumber of prompt tokens.\n\nNOTE: this is a **stateful** primitive — it appends to the KV cache. Call\n[`reset!`](@ref) first if you need a clean state. For measurement targets use\nthe idempotent [`generate!`](@ref) / [`prefill_only!`](@ref) instead.\n" function prefill!(s::Session, prompt::AbstractString) + toks = tokenize(s.vocab, prompt) + decode!(s.ctx, batch_get_one(toks)) + next = argmax_token(logits_ith(s.ctx, -1, s.nvoc)) + return (next, length(toks)) + end + Core.@doc " decode_n!(s, first_token, n) -> n_generated\n\nAutoregressively generate up to `n` tokens starting from `first_token`\n(greedy), stopping early on EOG.\n\nNOTE: **stateful** — advances the KV cache. Not idempotent on its own; use it\nvia [`generate!`](@ref) for repeatable measurements.\n" function decode_n!(s::Session, first_token::LlamaToken, n::Integer) + tok = first_token + generated = 0 + scratch = LlamaToken[0] + for _ = 1:n + is_eog(s.vocab, tok) && break + generated += 1 + scratch[1] = tok + decode!(s.ctx, batch_get_one(scratch)) + tok = argmax_token(logits_ith(s.ctx, -1, s.nvoc)) + end + return generated + end + Core.@doc " generate!(s, prompt, n_gen) -> n_generated\n\nIdempotent full request: clear KV cache, prefill `prompt`, then greedily decode\nup to `n_gen` tokens. Safe to call repeatedly. This is the primary measured\ntarget; whole-request energy divided by `n_generated` gives Joules per token.\n" function generate!(s::Session, prompt::AbstractString, n_gen::Integer) + reset!(s) + (first_tok, _) = prefill!(s, prompt) + return decode_n!(s, first_tok, n_gen) + end + Core.@doc " prefill_only!(s, prompt) -> n_prompt_tokens\n\nIdempotent prefill: clear KV cache and process the prompt only. Measure this as\na second target to isolate prefill energy, so decode energy ≈ generate! energy −\nprefill_only! energy.\n" function prefill_only!(s::Session, prompt::AbstractString) + reset!(s) + (_, n_prompt) = prefill!(s, prompt) + return n_prompt + end + end +PerfTest._perftest_config("[perfcompare]\nenabled = true\n\n[MPI]\nmode = \"reduce\"\nenabled = false\n\n[general]\nsave_results = true\nmax_saved_results = 20\nsuppress_output = true\nsave_folder = \".perftests\"\nthreads_per_numa = \"single\"\nrecursive = true\nverbose = 3\nautoflops = false\nplotting = true\nnumas = \"single\"\nlogs_enabled = true\nsafe_formulas = false\n\n[regression]\nenabled = false\ndedicated_reference_file = \"\"\ndefault_threshold = 1.1\nuse_bencher = false\n\n[roofline]\nenabled = true\ndefault_threshold = 0.5\n\n[memory_bandwidth]\nenabled = true\ndefault_threshold = 0.5\n\n[machine_benchmarking]\nmemory_bandwidth_test_buffer_size = 0\n\n[bencher]\napi_key = \"\"\norganization = \"\"\napi_url = \"https://api.bencher.dev\"\nproject_name = \"\"\ncustom_testbed_name = \"\"\n\n[cuda]\nenabled = true\n") +const MODEL_DIR = get(ENV, "MODEL_DIR", joinpath(@__DIR__(), "models")) +const MODEL_BASE = get(ENV, "MODEL_BASE", "Qwen3.8-27B") +const QUANTS = ["UD-Q2_K_XL", "UD-Q3_K_XL", "UD-Q4_K_M", "UD-Q5_K_M", "UD-Q6_K", "Q8_0", "f16"] +const PROMPT = "Explain, in a single detailed paragraph, why energy efficiency " * "is becoming the dominant cost metric for large language model " * "inference in production data centers." +const N_GEN = 256 +quant_path(q) = joinpath(MODEL_DIR, "$(MODEL_BASE)-$(q).gguf") +const LLAMA_PERPLEXITY_BIN = get(ENV, "LLAMA_PERPLEXITY_BIN", joinpath(dirname(get(ENV, "LLAMA_LIB", "")), "llama-perplexity")) +const PPL_CORPUS = joinpath(get(ENV, "MODEL_DIR", @__DIR__()), "wikitext-2-raw", "wiki.test.raw") +const PPL_CTX = 512 +Core.@doc " run_llama_perplexity(model_path) -> Float64\n\nRun `llama-perplexity` on `PPL_CORPUS` against the GGUF at `model_path` and\nparse its \"Final estimate: PPL = ...\" line. Returns `NaN` (with a `@warn`) if\nthe binary or corpus is missing, so the sweep still runs without the quality\naxis.\n" function run_llama_perplexity(model_path::AbstractString) + if !(isfile(LLAMA_PERPLEXITY_BIN)) + @warn "llama-perplexity binary not found, skipping perplexity" bin = LLAMA_PERPLEXITY_BIN + return NaN + end + if !(isfile(PPL_CORPUS)) + @warn "Perplexity corpus not found, skipping perplexity" corpus = PPL_CORPUS + return NaN + end + cmd = `$LLAMA_PERPLEXITY_BIN -m $model_path -f $PPL_CORPUS -c $PPL_CTX --n-gpu-layers 999` + out = read(cmd, String) + m = match(r"Final estimate: PPL = ([0-9.]+)", out) + m === nothing && error("Could not parse PPL from llama-perplexity output:\n$(out)") + return parse(Float64, m.captures[1]) + end +using Test, Dates +nothing +using PerfTest: DepthRecord, Metric_Test, Methodology_Result, StrOrSym, Metric_Result, magnitudeAdjust, MPISetup, newMetricResult, buildPrimitiveMetrics!, measureCPUPeakFlops!, measureMemBandwidth!, addLog, @PRFTBenchmark, PRFTBenchmarkGroup, @PRFTCapture_out, @PRFTCount_ops, PRFTflop, @PRFTSuppress, Test_Result, by_index, regression, Suite_Execution_Result, savePrimitives, main_rank, GlobalSuiteData, @perftestset, PerfTestSet, extractTestResults, saveMethodologyData, Configuration, metricSampledValue, SampledValue +_t_begin = time() +_GLOBAL_MODE = PerfTest.NormalMode +if main_rank(PerfTest.NormalMode) + path = "./.perftests/llama_energy_test.jl_PERFORMANCE.JLD2" + nofile = true + if isfile(path) + nofile = false + datafile = PerfTest.openDataFile(path) + else + datafile = PerfTest.Perftest_Datafile_Root(PerfTest.Suite_Execution_Result[]) + end + regression_path = (Configuration.CONFIG["regression"])["dedicated_reference_file"] + if regression_path != "" && isfile(regression_path) + regression_file = PerfTest.openDataFile(regression_path) + else + if regression_path != "" + regression_file = PerfTest.Perftest_Datafile_Root(PerfTest.Suite_Execution_Result[]) + else + regression_file = datafile + regression_path = path + end + end + _PRFT_GLOBALS = GlobalSuiteData(datafile, path, "llama_energy_test.jl") + if length(regression_file.results) > 0 + for i = length(regression_file.results):-1:1 + if length(retrievePerfTests(regression_path, get = :tests, where_pred = testFailed, execution = i)) == 0 + _PRFT_GLOBALS.old = (regression_file.results[i]).perftests + println("Regression: Previous performance reference for this configuration has been found, regression tests could be performed. Regression is currenctly $(if false + "enabled" +else + "disabled" +end)).") + break + end + end + else + _PRFT_GLOBALS.old = nothing + end +else + _PRFT_GLOBALS = GlobalSuiteData() +end +let + PerfTest.Topology.getMachineTopology!() + _PRFT_GLOBALS.builtins[:MEM_CACHE_SIZES] = PerfTest.Topology.getCacheSizes() +end +TS = @perftestset(PerfTestSet, "Llama.cpp energy efficiency vs quantization", begin + local ts = Test.get_testset() + ts.old_test_results = _PRFT_GLOBALS.old + nothing + TS = @perftestset(PerfTestSet, "quant = ", for q = QUANTS + local ts = Test.get_testset() + ts.iterator = q + nothing + global s = nothing + n_prompt = 0 + ppl = NaN + path = quant_path(q) + if !(isfile(path)) + @warn "Missing GGUF, skipping" quant = q path = path + continue + end + s = LlamaFFI.open_session(path; n_gpu_layers = 999, n_ctx = 4096) + LlamaFFI.generate!(s, PROMPT, 8) + n_prompt = LlamaFFI.prefill_only!(s, PROMPT) + @info (N_GEN, n_prompt, q) + nothing + nothing + nothing + nothing + nothing + nothing + @define_test_metric name = "Energy budget" units = "J/token" reference = 0.5 low_is_bad = false :gpue / N_GEN + ts.benchmarks["Test 1"] = @PRFTBenchmark(($LlamaFFI).generate!($s, $PROMPT, $N_GEN), samples = 1, evals = 1, seconds = 120) + extensions = PerfTest.ExtensionData[] + push!(extensions, PerfTest.NoExtensionData()) + @info PerfTest.cuda_devices() + (energy, power) = begin + devs = PerfTest.cuda_devices() + nsamples = max(1, length(ts.benchmarks["Test 1"])) + energy_samples = Vector{Vector{Float64}}() + for _s = 1:nsamples + CUDA.synchronize() + pre = [] + for d = devs + push!(pre, PerfTest.read_joule(d)) + end + LlamaFFI.generate!(s, PROMPT, N_GEN) + CUDA.synchronize() + post = [] + for d = devs + push!(post, PerfTest.read_joule(d)) + end + push!(energy_samples, Float64.(post .- pre)) + end + energy = [let dev_samples = Float64[(energy_samples[s])[d] for s = 1:nsamples] + if nsamples >= PerfTest.MIN_VARIANCE_SAMPLES + PerfTest.SampledValue(dev_samples, PerfTest._sample_median(dev_samples)) + else + PerfTest._sample_median(dev_samples) + end + end for d = eachindex(devs)] + power = energy + @info (energy, power) + (energy, power) + end + push!(extensions, PerfTest.CUDAExtensionData(energy, power)) + push!(extensions, PerfTest.NoExtensionData()) + test_res = Test_Result("Test 1", extensions) + ts.test_results["Test 1"] = test_res + keys = ["Llama.cpp energy efficiency vs quantization", string("quant = ", "_", q)] + append!(keys, ["Test 1"]) + old_test_res = _PRFT_GLOBALS.old + for key = keys + if !(old_test_res isa Nothing) && haskey(old_test_res, key) + old_test_res = old_test_res[key] + else + old_test_res = nothing + break + end + end + test_res.primitives[:autoflop] = 0 + test_res.primitives[:printed_output] = @PRFTCapture_out(test_res.primitives[:ret_value] = LlamaFFI.generate!(s, PROMPT, N_GEN)) + buildPrimitiveMetrics!(PerfTest.NormalMode, ts, test_res) + let m = newMetricResult(PerfTest.NormalMode, name = "Energy/token", units = "J/token", value = if haskey(_PRFT_GLOBALS.custom_benchmarks, :gpue) + PerfTest.metricSampledValue(_PRFT_GLOBALS.custom_benchmarks[:gpue]) + else + if haskey(_PRFT_GLOBALS.builtins, :gpue) + _PRFT_GLOBALS.builtins[:gpue] + else + if haskey(test_res.metrics, :gpue) + PerfTest.metricSampledValue(test_res.metrics[:gpue]) + else + if haskey(test_res.auxiliar, :gpue) + PerfTest.metricSampledValue(test_res.auxiliar[:gpue]) + else + sum((test_res.extensions[2]).energy) + end + end + end + end / N_GEN, auxiliary = true, showvar = false) + test_res.auxiliar[Symbol("Energy/token")] = m + end + let m = newMetricResult(PerfTest.NormalMode, name = "Efficiency", units = "token/J", value = N_GEN / if haskey(_PRFT_GLOBALS.custom_benchmarks, :gpue) + PerfTest.metricSampledValue(_PRFT_GLOBALS.custom_benchmarks[:gpue]) + else + if haskey(_PRFT_GLOBALS.builtins, :gpue) + _PRFT_GLOBALS.builtins[:gpue] + else + if haskey(test_res.metrics, :gpue) + PerfTest.metricSampledValue(test_res.metrics[:gpue]) + else + if haskey(test_res.auxiliar, :gpue) + PerfTest.metricSampledValue(test_res.auxiliar[:gpue]) + else + sum((test_res.extensions[2]).energy) + end + end + end + end, auxiliary = true, showvar = false) + test_res.auxiliar[:Efficiency] = m + end + let m = newMetricResult(PerfTest.NormalMode, name = "Energy", units = "W", value = if haskey(_PRFT_GLOBALS.custom_benchmarks, :gpue) + PerfTest.metricSampledValue(_PRFT_GLOBALS.custom_benchmarks[:gpue]) + else + if haskey(_PRFT_GLOBALS.builtins, :gpue) + _PRFT_GLOBALS.builtins[:gpue] + else + if haskey(test_res.metrics, :gpue) + PerfTest.metricSampledValue(test_res.metrics[:gpue]) + else + if haskey(test_res.auxiliar, :gpue) + PerfTest.metricSampledValue(test_res.auxiliar[:gpue]) + else + sum((test_res.extensions[2]).energy) + end + end + end + end, auxiliary = true, showvar = false) + test_res.auxiliar[:Energy] = m + end + let m = newMetricResult(PerfTest.NormalMode, name = "Time", units = "s", value = test_res.primitives[:median_time], auxiliary = true, showvar = false) + test_res.auxiliar[:Time] = m + end + let m = newMetricResult(PerfTest.NormalMode, name = "Throughput", units = "token/s", value = N_GEN / test_res.primitives[:median_time], auxiliary = true, showvar = false) + test_res.auxiliar[:Throughput] = m + end + let m = newMetricResult(PerfTest.NormalMode, name = "Perplexity", units = "ppl", value = ppl, auxiliary = true, showvar = false) + test_res.auxiliar[:Perplexity] = m + end + if main_rank(PerfTest.NormalMode) + end + s === nothing || LlamaFFI.destroy!(s) + nothing + end) + nothing + nothing + end) +if main_rank(PerfTest.NormalMode) + testresdict = Dict{String, Union{Dict, Test_Result}}() + if TS isa Vector + benchmarks = PerfTest.newBenchmarkGroup() + for ts = TS + testresdict[ts.description * "_" * string(ts.iterator)] = extractTestResults(ts) + benchmarks[ts.description * "_" * string(ts.iterator)] = ts.benchmarks + end + newres = Suite_Execution_Result(timestamp = datetime2unix(now()), elapsed = time() - _t_begin, benchmarks = benchmarks, perftests = testresdict) + else + testresdict[TS.description] = extractTestResults(TS) + newres = Suite_Execution_Result(timestamp = datetime2unix(now()), elapsed = time() - _t_begin, benchmarks = TS.benchmarks, perftests = testresdict) + end + if PerfTest.testsSucceeded(TS) && ((Configuration.CONFIG["regression"])["enabled"] && regression_path != _PRFT_GLOBALS.datafile_path) + println("All performance tests have passed. Values will be registered as reference for regression testing.") + push!(regression_file.results, newres) + let + res_num = length(regression_file.results) + if (excess = 20 - res_num) <= 0 + PerfTest.p_yellow("[ℹ]") + println(" Regression: Exceeded maximum recorded results. The oldest $(-1 * excess + 1) result/s will be removed.") + for i = 1:-1 * excess + 1 + popfirst!(regression_file.results) + end + end + end + PerfTest.saveDataFile(regression_path, regression_file) + else + println("Some tests failed or errored.") + end + let + push!(_PRFT_GLOBALS.datafile.results, newres) + res_num = length(_PRFT_GLOBALS.datafile.results) + if (excess = 20 - res_num) <= 0 + PerfTest.p_yellow("[ℹ]") + println(" Results File: Exceeded maximum recorded results. The oldest $(-1 * excess + 1) result/s will be removed.") + for i = 1:-1 * excess + 1 + popfirst!(_PRFT_GLOBALS.datafile.results) + end + end + end + PerfTest.saveDataFile(_PRFT_GLOBALS.datafile_path, _PRFT_GLOBALS.datafile) + println("[✓] $(path) Performance tests have been finished (elapsed $(newres.elapsed) s)") + if (Configuration.CONFIG["regression"])["use_bencher"] + bencher_config = Configuration.CONFIG["bencher"] + PerfTest.BencherREST.exportSuiteToBencher(_PRFT_GLOBALS.datafile, bencher_config) + end + PerfTest.clean(PerfTest.NormalMode) +end +end \ No newline at end of file diff --git a/examples/example-llama-energy/parser.py b/examples/example-llama-energy/parser.py new file mode 100755 index 0000000..668776f --- /dev/null +++ b/examples/example-llama-energy/parser.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +""" +Parse piped input of the form: + +[header lines] +-- +Metric: [Metric name] [Units] + = [Float] +-- +Metric: [Metric name] [Units] + = [Float] +-- +... + +and emit: + +name = "..." +units = "..." +values = [...] +""" +import sys +import re + +METRIC_RE = re.compile(r'Metric:\s*(.+?)\s*\[([^\]]*)\]') +VALUE_RE = re.compile(r'=\s*([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)') + +def main(): + data = sys.stdin.read() + blocks = data.split('--') + + name = None + units = None + values = [] + + for block in blocks: + m = METRIC_RE.search(block) + if m and name is None: + name = m.group(1).strip() + units = m.group(2).strip() + + v = VALUE_RE.search(block) + if v: + values.append(float(v.group(1))) + + if name is None: + print("# No metric found in input", file=sys.stderr) + sys.exit(1) + + print(f'name = "{name}"') + print(f'units = "{units}"') + print(f'values = {values}') + +if __name__ == '__main__': + main() diff --git a/examples/example-llama-energy/perftest_config.toml b/examples/example-llama-energy/perftest_config.toml new file mode 100644 index 0000000..f5e75ce --- /dev/null +++ b/examples/example-llama-energy/perftest_config.toml @@ -0,0 +1,44 @@ +[perfcompare] +enabled = true + +[MPI] +mode = "reduce" +enabled = false + +[general] +save_results = true +max_saved_results = 20 +suppress_output = true +save_folder = ".perftests" +threads_per_numa = "single" +recursive = true +verbose = 0 +autoflops = false +plotting = true +numas = "single" +logs_enabled = true +safe_formulas = false + +[regression] +enabled = true +dedicated_reference_file = "" +default_threshold = 1.1 +use_bencher = false + +[roofline] +enabled = true +default_threshold = 0.5 + +[memory_bandwidth] +enabled = true +default_threshold = 0.5 + +[machine_benchmarking] +memory_bandwidth_test_buffer_size = 0 + +[bencher] +api_key = "" +organization = "" +api_url = "https://api.bencher.dev" +project_name = "" +custom_testbed_name = "" diff --git a/examples/example-llama-energy/plot_results.jl b/examples/example-llama-energy/plot_results.jl new file mode 100644 index 0000000..28207f0 --- /dev/null +++ b/examples/example-llama-energy/plot_results.jl @@ -0,0 +1,49 @@ +# ============================================================================= +# Post-process the persisted PerfTest results into the headline Pareto plot: +# energy-per-token (x) vs. quality loss (y), one point per quantization level. +# +# PRELIMINARY DRAFT — assumes results were persisted to the JLD2 datafile that +# PerfTest.jl writes under ./.perftests/. Adjust the extraction to match the +# Suite_Execution_Result schema of your PerfTest version, or (simpler) have the +# recipe append rows to a CSV and load that here. +# +# Uncomment the deps in Project.toml before running: +# using DataFrames, CSV, CairoMakie, JLD2 +# ============================================================================= + +# This is intentionally a skeleton: the exact JLD2 layout is internal to +# PerfTest (see src/execution/structs.jl :: Suite_Execution_Result / Test_Result). +# The most robust approach for a draft is to emit a CSV from the analysis and +# plot that. Below is the CSV-based path. + +using CSV, DataFrames, CairoMakie + +const RESULTS_CSV = get(ENV, "LLAMA_RESULTS_CSV", joinpath(@__DIR__, "results.csv")) + +# Expected columns: quant, energy_per_token, tokens_per_joule, avg_power, +# throughput, perplexity, vram_gb +df = CSV.read(RESULTS_CSV, DataFrame) + +# Quality loss vs the F16 baseline (perplexity increase, %). +base_ppl = df[df.quant .== "f16", :perplexity] +if !isempty(base_ppl) && !isnan(first(base_ppl)) + df.quality_loss_pct = 100 .* (df.perplexity .- first(base_ppl)) ./ first(base_ppl) +else + df.quality_loss_pct .= NaN +end + +fig = Figure(size = (720, 520)) +ax = Axis(fig[1, 1]; + xlabel = "Energy per generated token [J/token]", + ylabel = "Quality loss vs F16 [% perplexity increase]", + title = "LLM inference: energy/quality Pareto (PerfTest.jl)") + +scatter!(ax, df.energy_per_token, df.quality_loss_pct; markersize = 14) +for r in eachrow(df) + text!(ax, r.energy_per_token, r.quality_loss_pct; text = r.quant, + align = (:left, :bottom), offset = (6, 6)) +end + +out = joinpath(@__DIR__, "pareto_energy_quality.png") +save(out, fig) +@info "wrote $out" diff --git a/examples/example-llama-energy/test_amd.jl b/examples/example-llama-energy/test_amd.jl new file mode 100644 index 0000000..877dcd7 --- /dev/null +++ b/examples/example-llama-energy/test_amd.jl @@ -0,0 +1,133 @@ +# ============================================================================= +# PerfTest.jl case study: energy efficiency of LLM inference vs. quantization +# (AMD GPU / ROCm variant) +# ============================================================================= +# +# PRELIMINARY DRAFT. +# +# Story: for a single model, sweep the GGUF quantization level and measure the +# GPU *energy per generated token* using PerfTest.jl's AMDGPU/rocm_smi energy +# feature, alongside a quality proxy (perplexity). The headline result is the +# Pareto tradeoff: how much energy quantization saves vs. how much quality it +# costs. +# +# Identical recipe to llama_energy_test.jl, just on the AMD/ROCm backend: +# inference is driven IN-PROCESS via direct `ccall`s into a HIP-enabled +# libllama (see LlamaFFI.jl — the FFI itself is backend-agnostic; only the +# libllama.so it's pointed at differs). PerfTest.jl's AMDGPU extension +# (../../ext/PerfTest_AMDGPUExt.jl) reads rocm_smi's per-device energy counter +# around each measured target, exposed to formulas as `:amde`/`:amdp` (the +# `:gpue`/`:gpup` analogues from the CUDA extension). +# +# Perplexity (the quality axis) is obtained offline, "Level A" in README +# "Quality axis": shelling out to the ROCm-built `llama-perplexity` tool +# against a fixed corpus, once per quant. See llama_energy_test.jl / README +# for why in-process ("Level B") perplexity was dropped. +# +# Run with: +# using PerfTest +# runperftests("llama_energy_test_amd.jl") +# +# Requirements (see README.md): +# - An AMD GPU with rocm_smi energy-counter support, and ROCm/librocm_smi64 +# installed (see ../../ext/PerfTest_AMDGPUExt.jl). +# - LLAMA_LIB pointing at a ROCm/HIP build of libllama (build_llama_rocm.sh). +# - GGUF weights at several quant levels in $MODEL_DIR (get_models.sh). +# - The `llama-perplexity` tool built alongside libllama, and a fixed text +# corpus (see PPL_CORPUS below). +# ============================================================================= + +using Test +using PerfTest +using AMDGPU + +include("LlamaFFI.jl") + +# ----------------------------------------------------------------------------- +# Configuration +# ----------------------------------------------------------------------------- +@perftest_config " +[general] +verbose = 3 +plotting = true +[regression] +enabled = false +[amdgpu] +enabled = true +" + +# Directory holding the GGUF files, one per quantization level. +const MODEL_DIR = get(ENV, "MODEL_DIR", joinpath(@__DIR__, "models")) + +# Base model name; the quant tag is appended to form the filename. +# e.g. "Qwen3.8-27B-UD-Q4_K_M.gguf" +const MODEL_BASE = get(ENV, "MODEL_BASE", "Qwen3.8-27B") + +# Quantization levels to sweep (highest fidelity first). F16 is the quality +# baseline. Edit to match the GGUF files you actually downloaded/produced. +const QUANTS = ["f16", "Q8_0", "UD-Q6_K", "UD-Q5_K_M", "UD-Q4_K_M", "UD-Q3_K_XL", "UD-Q2_K_XL"] + +# Fixed workload. Deterministic (greedy) decoding, fixed token budget so that +# "energy per token" is comparable across quants. +const PROMPT = "Explain, in a single detailed paragraph, why energy efficiency " * + "is becoming the dominant cost metric for large language model " * + "inference in production data centers." +const N_GEN = 256 # generated tokens (decode phase) + +quant_path(q) = joinpath(MODEL_DIR, "$(MODEL_BASE)-$(q).gguf") + +# ----------------------------------------------------------------------------- +# Quality axis: offline perplexity (README "Quality axis", Level A) +# ----------------------------------------------------------------------------- + +# `llama-perplexity` is built alongside `libllama` by build_llama_rocm.sh +# (same build dir's bin/); override if it lives elsewhere. +const LLAMA_PERPLEXITY_BIN = get(ENV, "LLAMA_PERPLEXITY_BIN", + joinpath(dirname(get(ENV, "LLAMA_LIB", "")), "llama-perplexity")) + +# Fixed evaluation corpus (plain text, e.g. a WikiText-2 slice). The same +# corpus is used for every quant so the perplexity numbers are comparable. +const PPL_CORPUS = joinpath(get(ENV, "MODEL_DIR", @__DIR__), "wikitext-2-raw", "wiki.test.raw") + +const PPL_CTX = 512 # llama-perplexity's context/chunk size (its -c flag) + +""" + run_llama_perplexity(model_path) -> Float64 + +Run `llama-perplexity` on `PPL_CORPUS` against the GGUF at `model_path` and +parse its "Final estimate: PPL = ..." line. Returns `NaN` (with a `@warn`) if +the binary or corpus is missing, so the sweep still runs without the quality +axis. +""" +function run_llama_perplexity(model_path::AbstractString) + if !isfile(LLAMA_PERPLEXITY_BIN) + @warn "llama-perplexity binary not found, skipping perplexity" bin=LLAMA_PERPLEXITY_BIN + return NaN + end + if !isfile(PPL_CORPUS) + @warn "Perplexity corpus not found, skipping perplexity" corpus=PPL_CORPUS + return NaN + end + cmd = `$LLAMA_PERPLEXITY_BIN -m $model_path -f $PPL_CORPUS -c $PPL_CTX --n-gpu-layers 999` + out = read(cmd, String) + m = match(r"Final estimate: PPL = ([0-9.]+)", out) + m === nothing && error("Could not parse PPL from llama-perplexity output:\n$out") + return parse(Float64, m.captures[1]) +end + +# ----------------------------------------------------------------------------- +# Sweep +# ----------------------------------------------------------------------------- +@testset "(AMD TEST)" begin + + # Average GPU power during decode. + @auxiliary_metric name="Energy" units="W" begin + :gpue + end + + @auxiliary_metric name="Time" units="s" begin + :median_time + end + + @perftest samples=1 evals=1 seconds=120 sleep(5) +end diff --git a/examples/example-llama-energy/test_amd_perfsuite.jl b/examples/example-llama-energy/test_amd_perfsuite.jl new file mode 100644 index 0000000..3eae811 --- /dev/null +++ b/examples/example-llama-energy/test_amd_perfsuite.jl @@ -0,0 +1,438 @@ +module __PERFTEST__ +using Test +using PerfTest +using AMDGPU +Core.@doc " LlamaFFI\n\nMinimal, self-contained in-process `ccall` binding to a **CUDA-enabled** build of\n`libllama` (llama.cpp). This is the layer that lets PerfTest.jl bracket real\n`llama_decode` calls with NVML energy readings *in the same process as the tests*.\n\nWHY A CUSTOM BUILD?\n-------------------\nThe registered `llama_cpp_jll` artifact ships **CPU-only** binaries (no\n`libggml_cuda`, no CUDA dependency). To measure GPU energy of llama.cpp inference\nyou MUST build llama.cpp yourself with `-DGGML_CUDA=ON` and point this module at\nthe resulting `libllama.so` via the `LLAMA_LIB` environment variable\n(see `build_llama_cuda.sh`).\n\nSTATUS: PRELIMINARY DRAFT\n-------------------------\nThis binding targets a recent llama.cpp C API (the `llama_model_load_from_file` /\n`llama_init_from_model` generation, roughly late-2024/2025 API). The llama.cpp C\nAPI and, especially, the *layout* of `llama_model_params` / `llama_context_params`\nchange across commits. The struct mirrors below MUST be verified against the exact\ncommit you build (`llama.h`). For a robust binding, regenerate with `Clang.jl`\nagainst your pinned `llama.h`. The functions used here are intentionally a minimal\nsubset so that verification is quick.\n\nGreedy (argmax) decoding is implemented directly in Julia over the returned logits\nso we do not depend on the (frequently changing) sampler-chain API. Greedy keeps\ngeneration deterministic, which is important for a controlled energy study.\n" module LlamaFFI + using Libdl + const LIBLLAMA = Ref{String}("") + const LIBHANDLE = Ref{Ptr{Cvoid}}(C_NULL) + Core.@doc " lib()\n\nPath to the CUDA-enabled `libllama`. Resolved from the `LLAMA_CPP_LIB`\nenvironment variable the first time it is needed. Also caches the dlopen handle\nso we can probe for version-dependent symbols with [`sym`](@ref).\n" function lib() + if isempty(LIBLLAMA[]) + path = get(ENV, "LLAMA_LIB", "") + isempty(path) && error("Set LLAMA_LIB to your CUDA-enabled libllama (e.g. " * "/path/to/llama.cpp/build/bin/libllama.so). See build_llama_cuda.sh.") + isfile(path) || error("LLAMA_LIB does not point to a file: $(path)") + LIBHANDLE[] = Libdl.dlopen(path, Libdl.RTLD_LAZY | Libdl.RTLD_GLOBAL) + LIBLLAMA[] = path + end + return LIBLLAMA[] + end + Core.@doc "Resolve a symbol pointer, or C_NULL if this llama.cpp build does not export it." function sym(name::Symbol) + lib() + return Libdl.dlsym(LIBHANDLE[], name; throw_error = false) + end + const LlamaToken = Int32 + const LlamaPos = Int32 + const LlamaSeqId = Int32 + struct LlamaModelParams + devices::Ptr{Cvoid} + tensor_buft_overrides::Ptr{Cvoid} + n_gpu_layers::Cint + split_mode::Cint + load_mode::Cint + main_gpu::Cint + tensor_split::Ptr{Cfloat} + progress_callback::Ptr{Cvoid} + progress_callback_ud::Ptr{Cvoid} + kv_overrides::Ptr{Cvoid} + vocab_only::Bool + check_tensors::Bool + use_extra_bufts::Bool + no_host::Bool + no_alloc::Bool + load_mtp::Bool + end + const LLAMA_FLASH_ATTN_TYPE_DISABLED = Cint(0) + const LLAMA_FLASH_ATTN_TYPE_ENABLED = Cint(1) + struct LlamaContextParams + n_ctx::Cuint + n_batch::Cuint + n_ubatch::Cuint + n_seq_max::Cuint + n_rs_seq::Cuint + n_outputs_max::Cuint + n_threads::Cint + n_threads_batch::Cint + ctx_type::Cint + rope_scaling_type::Cint + pooling_type::Cint + attention_type::Cint + flash_attn_type::Cint + rope_freq_base::Cfloat + rope_freq_scale::Cfloat + yarn_ext_factor::Cfloat + yarn_attn_factor::Cfloat + yarn_beta_fast::Cfloat + yarn_beta_slow::Cfloat + yarn_orig_ctx::Cuint + defrag_thold::Cfloat + cb_eval::Ptr{Cvoid} + cb_eval_ud::Ptr{Cvoid} + type_k::Cint + type_v::Cint + abort_callback::Ptr{Cvoid} + abort_callback_data::Ptr{Cvoid} + embeddings::Bool + offload_kqv::Bool + no_perf::Bool + op_offload::Bool + swa_full::Bool + kv_unified::Bool + samplers::Ptr{Cvoid} + n_samplers::Csize_t + ctx_other::Ptr{Cvoid} + end + struct LlamaBatch + n_tokens::Cint + token::Ptr{LlamaToken} + embd::Ptr{Cfloat} + pos::Ptr{LlamaPos} + n_seq_id::Ptr{Cint} + seq_id::Ptr{Ptr{LlamaSeqId}} + logits::Ptr{Int8} + end + backend_init() = ccall((:llama_backend_init, lib()), Cvoid, ()) + backend_free() = ccall((:llama_backend_free, lib()), Cvoid, ()) + model_default_params() = ccall((:llama_model_default_params, lib()), LlamaModelParams, ()) + context_default_params() = ccall((:llama_context_default_params, lib()), LlamaContextParams, ()) + Core.@doc " load_model(path; n_gpu_layers=999) -> Ptr\n\nLoad a GGUF model with the requested number of layers offloaded to the GPU.\n`n_gpu_layers=999` means \"offload everything\".\n" function load_model(path::AbstractString; n_gpu_layers::Integer = 999) + p = model_default_params() + p = LlamaModelParams(p.devices, p.tensor_buft_overrides, Cint(n_gpu_layers), Cint(0), p.load_mode, Cint(0), p.tensor_split, p.progress_callback, p.progress_callback_ud, p.kv_overrides, p.vocab_only, p.check_tensors, p.use_extra_bufts, p.no_host, p.no_alloc, p.load_mtp) + m = ccall((:llama_model_load_from_file, lib()), Ptr{Cvoid}, (Cstring, LlamaModelParams), path, p) + m == C_NULL && error("Failed to load model: $(path)") + return m + end + function new_context(model::Ptr{Cvoid}; n_ctx::Integer = 4096, n_batch::Integer = 2048, flash_attn::Bool = true, n_threads::Integer = Sys.CPU_THREADS) + p = context_default_params() + p = LlamaContextParams(Cuint(n_ctx), Cuint(n_batch), p.n_ubatch, p.n_seq_max, p.n_rs_seq, p.n_outputs_max, Cint(n_threads), Cint(n_threads), p.ctx_type, p.rope_scaling_type, p.pooling_type, p.attention_type, if flash_attn + LLAMA_FLASH_ATTN_TYPE_ENABLED + else + LLAMA_FLASH_ATTN_TYPE_DISABLED + end, p.rope_freq_base, p.rope_freq_scale, p.yarn_ext_factor, p.yarn_attn_factor, p.yarn_beta_fast, p.yarn_beta_slow, p.yarn_orig_ctx, p.defrag_thold, p.cb_eval, p.cb_eval_ud, p.type_k, p.type_v, p.abort_callback, p.abort_callback_data, p.embeddings, p.offload_kqv, p.no_perf, p.op_offload, p.swa_full, p.kv_unified, p.samplers, p.n_samplers, p.ctx_other) + ctx = ccall((:llama_init_from_model, lib()), Ptr{Cvoid}, (Ptr{Cvoid}, LlamaContextParams), model, p) + ctx == C_NULL && error("Failed to create context") + return ctx + end + free_model(model::Ptr{Cvoid}) = ccall((:llama_model_free, lib()), Cvoid, (Ptr{Cvoid},), model) + free_context(ctx::Ptr{Cvoid}) = ccall((:llama_free, lib()), Cvoid, (Ptr{Cvoid},), ctx) + get_vocab(model::Ptr{Cvoid}) = ccall((:llama_model_get_vocab, lib()), Ptr{Cvoid}, (Ptr{Cvoid},), model) + n_vocab(vocab::Ptr{Cvoid}) = Int(ccall((:llama_vocab_n_tokens, lib()), Cint, (Ptr{Cvoid},), vocab)) + model_size_bytes(model::Ptr{Cvoid}) = Int(ccall((:llama_model_size, lib()), UInt64, (Ptr{Cvoid},), model)) + function tokenize(vocab::Ptr{Cvoid}, text::AbstractString; add_special::Bool = true, parse_special::Bool = true) + cap = ncodeunits(text) + 16 + toks = Vector{LlamaToken}(undef, cap) + n = ccall((:llama_tokenize, lib()), Cint, (Ptr{Cvoid}, Cstring, Cint, Ptr{LlamaToken}, Cint, Bool, Bool), vocab, text, ncodeunits(text), toks, cap, add_special, parse_special) + n < 0 && error("tokenize: buffer too small (needed $(-n))") + return toks[1:n] + end + is_eog(vocab::Ptr{Cvoid}, tok::LlamaToken) = ccall((:llama_vocab_is_eog, lib()), Bool, (Ptr{Cvoid}, LlamaToken), vocab, tok) + batch_get_one(tokens::Vector{LlamaToken}) = ccall((:llama_batch_get_one, lib()), LlamaBatch, (Ptr{LlamaToken}, Cint), tokens, Cint(length(tokens))) + function decode!(ctx::Ptr{Cvoid}, batch::LlamaBatch) + rc = ccall((:llama_decode, lib()), Cint, (Ptr{Cvoid}, LlamaBatch), ctx, batch) + rc != 0 && error("llama_decode failed: rc=$(rc)") + return nothing + end + function logits_ith(ctx::Ptr{Cvoid}, i::Integer, nvoc::Integer) + p = ccall((:llama_get_logits_ith, lib()), Ptr{Cfloat}, (Ptr{Cvoid}, Cint), ctx, Cint(i)) + p == C_NULL && error("llama_get_logits_ith returned NULL") + return unsafe_wrap(Array, p, nvoc) + end + argmax_token(logits::AbstractVector{<:Real}) = LlamaToken(argmax(logits) - 1) + Core.@doc " Session\n\nHolds a loaded model + context and cached vocab size. Create once per\nquantization level, reuse for warmup + measurement runs.\n" mutable struct Session + model::Ptr{Cvoid} + ctx::Ptr{Cvoid} + vocab::Ptr{Cvoid} + nvoc::Int + end + binit = false + function open_session(gguf_path::AbstractString; n_gpu_layers = 999, n_ctx = 4096, flash_attn = true) + backend_init() + model = load_model(gguf_path; n_gpu_layers = n_gpu_layers) + ctx = new_context(model; n_ctx = n_ctx, flash_attn = flash_attn) + vocab = get_vocab(model) + return Session(model, ctx, vocab, n_vocab(vocab)) + end + function close_session(s::Session) + free_context(s.ctx) + free_model(s.model) + backend_free() + return nothing + end + const _RESET_KIND = Ref{Symbol}(:unresolved) + function _resolve_reset() + if sym(:llama_get_memory) != C_NULL && sym(:llama_memory_clear) != C_NULL + _RESET_KIND[] = :memory + elseif sym(:llama_kv_self_clear) != C_NULL + _RESET_KIND[] = :kv_self + elseif sym(:llama_kv_cache_clear) != C_NULL + _RESET_KIND[] = :kv_cache + else + error("No known KV-cache clear symbol found in libllama; check your version.") + end + return _RESET_KIND[] + end + Core.@doc " reset!(s)\n\nClear the context KV cache so the next `prefill!`/`decode_n!` starts from a\nclean state. This is the key to idempotent, repeatable measurements.\n" function reset!(s::Session) + _RESET_KIND[] == :unresolved && _resolve_reset() + if _RESET_KIND[] == :memory + mem = ccall((:llama_get_memory, lib()), Ptr{Cvoid}, (Ptr{Cvoid},), s.ctx) + ccall((:llama_memory_clear, lib()), Cvoid, (Ptr{Cvoid}, Bool), mem, true) + elseif _RESET_KIND[] == :kv_self + ccall((:llama_kv_self_clear, lib()), Cvoid, (Ptr{Cvoid},), s.ctx) + else + ccall((:llama_kv_cache_clear, lib()), Cvoid, (Ptr{Cvoid},), s.ctx) + end + return nothing + end + const _MODEL_FREE_KIND = Ref{Symbol}(:unresolved) + function _resolve_model_free() + if sym(:llama_model_free) != C_NULL + _MODEL_FREE_KIND[] = :new + elseif sym(:llama_free_model) != C_NULL + _MODEL_FREE_KIND[] = :old + else + error("No known model-free symbol found in libllama; check your version.") + end + return _MODEL_FREE_KIND[] + end + Core.@doc " destroy!(s::Session)\n\nFree the context (KV cache + compute buffers) and the model (tensor weight\nbuffers) that were allocated on the GPU for this Session. `reset!` alone only\nclears KV-cache *contents*; it never releases the VRAM allocations, which is\nwhy memory climbs across models unless this is called too.\n\n`s.vocab` is *not* freed here — it's a pointer owned by the model\n(`llama_model_get_vocab`), not a separate allocation, and becomes invalid\nautomatically once `s.model` is freed.\n\nSafe to call multiple times; no-ops once fields are already null.\n" function destroy!(s::Session) + if s.ctx != C_NULL + ccall((:llama_free, lib()), Cvoid, (Ptr{Cvoid},), s.ctx) + s.ctx = C_NULL + end + if s.model != C_NULL + _MODEL_FREE_KIND[] == :unresolved && _resolve_model_free() + if _MODEL_FREE_KIND[] == :new + ccall((:llama_model_free, lib()), Cvoid, (Ptr{Cvoid},), s.model) + else + ccall((:llama_free_model, lib()), Cvoid, (Ptr{Cvoid},), s.model) + end + s.model = C_NULL + end + s.vocab = C_NULL + s.nvoc = 0 + GC.gc() + return nothing + end + Core.@doc " prefill!(s, prompt) -> (last_token, n_prompt_tokens)\n\nRun the prompt through the model in a single batch (the \"prefill\" / prompt\nprocessing phase). Returns the greedily-selected first generated token and the\nnumber of prompt tokens.\n\nNOTE: this is a **stateful** primitive — it appends to the KV cache. Call\n[`reset!`](@ref) first if you need a clean state. For measurement targets use\nthe idempotent [`generate!`](@ref) / [`prefill_only!`](@ref) instead.\n" function prefill!(s::Session, prompt::AbstractString) + toks = tokenize(s.vocab, prompt) + decode!(s.ctx, batch_get_one(toks)) + next = argmax_token(logits_ith(s.ctx, -1, s.nvoc)) + return (next, length(toks)) + end + Core.@doc " decode_n!(s, first_token, n) -> n_generated\n\nAutoregressively generate up to `n` tokens starting from `first_token`\n(greedy), stopping early on EOG.\n\nNOTE: **stateful** — advances the KV cache. Not idempotent on its own; use it\nvia [`generate!`](@ref) for repeatable measurements.\n" function decode_n!(s::Session, first_token::LlamaToken, n::Integer) + tok = first_token + generated = 0 + scratch = LlamaToken[0] + for _ = 1:n + is_eog(s.vocab, tok) && break + generated += 1 + scratch[1] = tok + decode!(s.ctx, batch_get_one(scratch)) + tok = argmax_token(logits_ith(s.ctx, -1, s.nvoc)) + end + return generated + end + Core.@doc " generate!(s, prompt, n_gen) -> n_generated\n\nIdempotent full request: clear KV cache, prefill `prompt`, then greedily decode\nup to `n_gen` tokens. Safe to call repeatedly. This is the primary measured\ntarget; whole-request energy divided by `n_generated` gives Joules per token.\n" function generate!(s::Session, prompt::AbstractString, n_gen::Integer) + reset!(s) + (first_tok, _) = prefill!(s, prompt) + return decode_n!(s, first_tok, n_gen) + end + Core.@doc " prefill_only!(s, prompt) -> n_prompt_tokens\n\nIdempotent prefill: clear KV cache and process the prompt only. Measure this as\na second target to isolate prefill energy, so decode energy ≈ generate! energy −\nprefill_only! energy.\n" function prefill_only!(s::Session, prompt::AbstractString) + reset!(s) + (_, n_prompt) = prefill!(s, prompt) + return n_prompt + end + end +PerfTest._perftest_config("[perfcompare]\nenabled = true\n\n[MPI]\nmode = \"reduce\"\nenabled = false\n\n[amdgpu]\nenabled = true\n\n[general]\nsave_results = true\nmax_saved_results = 20\nsuppress_output = true\nsave_folder = \".perftests\"\nthreads_per_numa = \"single\"\nrecursive = true\nverbose = 3\nautoflops = false\nplotting = true\nnumas = \"single\"\nlogs_enabled = true\nsafe_formulas = false\n\n[regression]\nenabled = false\ndedicated_reference_file = \"\"\ndefault_threshold = 1.1\nuse_bencher = false\n\n[roofline]\nenabled = true\ndefault_threshold = 0.5\n\n[memory_bandwidth]\nenabled = true\ndefault_threshold = 0.5\n\n[machine_benchmarking]\nmemory_bandwidth_test_buffer_size = 0\n\n[bencher]\napi_key = \"\"\norganization = \"\"\napi_url = \"https://api.bencher.dev\"\nproject_name = \"\"\ncustom_testbed_name = \"\"\n") +const MODEL_DIR = get(ENV, "MODEL_DIR", joinpath(@__DIR__(), "models")) +const MODEL_BASE = get(ENV, "MODEL_BASE", "Qwen3.8-27B") +const QUANTS = ["f16", "Q8_0", "UD-Q6_K", "UD-Q5_K_M", "UD-Q4_K_M", "UD-Q3_K_XL", "UD-Q2_K_XL"] +const PROMPT = "Explain, in a single detailed paragraph, why energy efficiency " * "is becoming the dominant cost metric for large language model " * "inference in production data centers." +const N_GEN = 256 +quant_path(q) = joinpath(MODEL_DIR, "$(MODEL_BASE)-$(q).gguf") +const LLAMA_PERPLEXITY_BIN = get(ENV, "LLAMA_PERPLEXITY_BIN", joinpath(dirname(get(ENV, "LLAMA_LIB", "")), "llama-perplexity")) +const PPL_CORPUS = joinpath(get(ENV, "MODEL_DIR", @__DIR__()), "wikitext-2-raw", "wiki.test.raw") +const PPL_CTX = 512 +Core.@doc " run_llama_perplexity(model_path) -> Float64\n\nRun `llama-perplexity` on `PPL_CORPUS` against the GGUF at `model_path` and\nparse its \"Final estimate: PPL = ...\" line. Returns `NaN` (with a `@warn`) if\nthe binary or corpus is missing, so the sweep still runs without the quality\naxis.\n" function run_llama_perplexity(model_path::AbstractString) + if !(isfile(LLAMA_PERPLEXITY_BIN)) + @warn "llama-perplexity binary not found, skipping perplexity" bin = LLAMA_PERPLEXITY_BIN + return NaN + end + if !(isfile(PPL_CORPUS)) + @warn "Perplexity corpus not found, skipping perplexity" corpus = PPL_CORPUS + return NaN + end + cmd = `$LLAMA_PERPLEXITY_BIN -m $model_path -f $PPL_CORPUS -c $PPL_CTX --n-gpu-layers 999` + out = read(cmd, String) + m = match(r"Final estimate: PPL = ([0-9.]+)", out) + m === nothing && error("Could not parse PPL from llama-perplexity output:\n$(out)") + return parse(Float64, m.captures[1]) + end +using Test, Dates +nothing +using PerfTest: DepthRecord, Metric_Test, Methodology_Result, StrOrSym, Metric_Result, magnitudeAdjust, MPISetup, newMetricResult, buildPrimitiveMetrics!, measureCPUPeakFlops!, measureMemBandwidth!, addLog, @PRFTBenchmark, PRFTBenchmarkGroup, @PRFTCapture_out, @PRFTCount_ops, PRFTflop, @PRFTSuppress, Test_Result, by_index, regression, Suite_Execution_Result, savePrimitives, main_rank, GlobalSuiteData, @perftestset, PerfTestSet, extractTestResults, saveMethodologyData, Configuration +_t_begin = time() +_GLOBAL_MODE = PerfTest.NormalMode +if main_rank(PerfTest.NormalMode) + path = "./.perftests/test_amd.jl_PERFORMANCE.JLD2" + nofile = true + if isfile(path) + nofile = false + datafile = PerfTest.openDataFile(path) + else + datafile = PerfTest.Perftest_Datafile_Root(PerfTest.Suite_Execution_Result[]) + end + regression_path = (Configuration.CONFIG["regression"])["dedicated_reference_file"] + if regression_path != "" && isfile(regression_path) + regression_file = PerfTest.openDataFile(regression_path) + else + if regression_path != "" + regression_file = PerfTest.Perftest_Datafile_Root(PerfTest.Suite_Execution_Result[]) + else + regression_file = datafile + regression_path = path + end + end + _PRFT_GLOBALS = GlobalSuiteData(datafile, path, "test_amd.jl") + if length(regression_file.results) > 0 + for i = length(regression_file.results):-1:1 + if length(retrievePerfTests(regression_path, get = :tests, where_pred = testFailed, execution = i)) == 0 + _PRFT_GLOBALS.old = (regression_file.results[i]).perftests + println("Regression: Previous performance reference for this configuration has been found, regression tests could be performed. Regression is currenctly $(if false + "enabled" +else + "disabled" +end)).") + break + end + end + else + _PRFT_GLOBALS.old = nothing + end +else + _PRFT_GLOBALS = GlobalSuiteData() +end +let + PerfTest.Topology.getMachineTopology!() + _PRFT_GLOBALS.builtins[:MEM_CACHE_SIZES] = PerfTest.Topology.getCacheSizes() +end +TS = @perftestset(PerfTestSet, "(AMD TEST)", begin + local ts = Test.get_testset() + ts.old_test_results = _PRFT_GLOBALS.old + nothing + nothing + ts.benchmarks["Test 1"] = @PRFTBenchmark(($sleep)(5), samples = 1, evals = 1, seconds = 120) + extensions = PerfTest.ExtensionData[] + push!(extensions, PerfTest.NoExtensionData()) + push!(extensions, PerfTest.NoExtensionData()) + @info PerfTest.amdgpu_devices() + (energy, power) = begin + AMDGPU.synchronize() + pre = [] + post = [] + for d = PerfTest.amdgpu_devices() + push!(pre, PerfTest.read_joule(d)) + end + sleep(5) + AMDGPU.synchronize() + for d = PerfTest.amdgpu_devices() + push!(post, PerfTest.read_joule(d)) + end + energy = post .- pre + power = energy + @info (energy, power) + (energy, power) + end + push!(extensions, PerfTest.AMDGPUExtensionData(energy, power)) + test_res = Test_Result("Test 1", extensions) + ts.test_results["Test 1"] = test_res + keys = ["(AMD TEST)"] + append!(keys, ["Test 1"]) + old_test_res = _PRFT_GLOBALS.old + for key = keys + if !(old_test_res isa Nothing) && haskey(old_test_res, key) + old_test_res = old_test_res[key] + else + old_test_res = nothing + break + end + end + test_res.primitives[:autoflop] = 0 + test_res.primitives[:printed_output] = @PRFTCapture_out(test_res.primitives[:ret_value] = sleep(5)) + buildPrimitiveMetrics!(PerfTest.NormalMode, ts, test_res) + let m = newMetricResult(PerfTest.NormalMode, name = "Energy", units = "W", value = if haskey(_PRFT_GLOBALS.custom_benchmarks, :gpue) + (_PRFT_GLOBALS.custom_benchmarks[:gpue]).value + else + if haskey(_PRFT_GLOBALS.builtins, :gpue) + _PRFT_GLOBALS.builtins[:gpue] + else + if haskey(test_res.metrics, :gpue) + (test_res.metrics[:gpue]).value + else + if haskey(test_res.auxiliar, :gpue) + (test_res.auxiliar[:gpue]).value + else + sum((test_res.extensions[3]).energy) + end + end + end + end, auxiliary = true) + test_res.auxiliar[:Energy] = m + end + let m = newMetricResult(PerfTest.NormalMode, name = "Time", units = "s", value = test_res.primitives[:median_time], auxiliary = true) + test_res.auxiliar[:Time] = m + end + if main_rank(PerfTest.NormalMode) + end + nothing + end) +if main_rank(PerfTest.NormalMode) + @info TS + testresdict = Dict{String, Union{Dict, Test_Result}}() + if TS isa Vector + benchmarks = PerfTest.newBenchmarkGroup() + for ts = TS + testresdict[ts.description * "_" * string(ts.iterator)] = extractTestResults(TS) + benchmarks[ts.description * "_" * string(ts.iterator)] = ts.benchmarks + end + newres = Suite_Execution_Result(timestamp = datetime2unix(now()), elapsed = time() - _t_begin, benchmarks = benchmarks, perftests = testresdict) + else + testresdict[TS.description] = extractTestResults(TS) + newres = Suite_Execution_Result(timestamp = datetime2unix(now()), elapsed = time() - _t_begin, benchmarks = TS.benchmarks, perftests = testresdict) + end + if PerfTest.testsSucceeded(TS) && ((Configuration.CONFIG["regression"])["enabled"] && regression_path != _PRFT_GLOBALS.datafile_path) + println("All performance tests have passed. Values will be registered as reference for regression testing.") + push!(regression_file.results, newres) + let + res_num = length(regression_file.results) + if (excess = 20 - res_num) <= 0 + PerfTest.p_yellow("[ℹ]") + println(" Regression: Exceeded maximum recorded results. The oldest $(-1 * excess + 1) result/s will be removed.") + for i = 1:-1 * excess + 1 + popfirst!(regression_file.results) + end + end + end + PerfTest.saveDataFile(regression_path, regression_file) + else + println("Some tests failed or errored.") + end + let + push!(_PRFT_GLOBALS.datafile.results, newres) + res_num = length(_PRFT_GLOBALS.datafile.results) + if (excess = 20 - res_num) <= 0 + PerfTest.p_yellow("[ℹ]") + println(" Results File: Exceeded maximum recorded results. The oldest $(-1 * excess + 1) result/s will be removed.") + for i = 1:-1 * excess + 1 + popfirst!(_PRFT_GLOBALS.datafile.results) + end + end + end + PerfTest.saveDataFile(_PRFT_GLOBALS.datafile_path, _PRFT_GLOBALS.datafile) + println("[✓] $(path) Performance tests have been finished (elapsed $(newres.elapsed) s)") + if (Configuration.CONFIG["regression"])["use_bencher"] + bencher_config = Configuration.CONFIG["bencher"] + PerfTest.BencherREST.exportSuiteToBencher(_PRFT_GLOBALS.datafile, bencher_config) + end + PerfTest.clean(PerfTest.NormalMode) +end +end \ No newline at end of file diff --git a/ext/PerfTest_AMDGPUExt.jl b/ext/PerfTest_AMDGPUExt.jl new file mode 100644 index 0000000..55f23b4 --- /dev/null +++ b/ext/PerfTest_AMDGPUExt.jl @@ -0,0 +1,123 @@ +module PerfTest_AMDGPUExt + +""" +PerfTest_AMDGPUExt + +TODO WIP AMDGPU extension for marker-based energy and power sampling. + +Usage (example): + +Notes: +AMDGPU.jl does not itself wrap the ROCm SMI library (unlike CUDA.jl, which +bundles NVML bindings), so energy accounting here calls into librocm_smi64 +directly via ccall. +""" + +using PerfTest +using AMDGPU +using Libdl + +function PerfTest.is_loaded(::Val{:AMDGPU}) return true end + +struct AMDGPUExtensionData <: PerfTest.ExtensionData + # Value type is loose (not a concrete SampledValue{Float64}) because whether a device's + # entry is a SampledValue depends on nsamples >= MIN_VARIANCE_SAMPLES at measurement time. + energy :: Vector{Any} + power :: Vector{Any} +end + +PerfTest.AMDGPUExtensionData(energy, power) = AMDGPUExtensionData(energy, power) + +const librocm_smi = Libdl.find_library(["librocm_smi64"]) + +function __init__() + if librocm_smi == "" + @warn "librocm_smi64 not found; AMDGPU energy/power measurements will error if used." + return + end + ccall((:rsmi_init, librocm_smi), Cint, (UInt64,), 0) + atexit(() -> ccall((:rsmi_shut_down, librocm_smi), Cint, ())) +end + +amdgpu_devices = [] + +PerfTest.amdgpu_devices() = begin + n = Ref{UInt32}(0) + ccall((:rsmi_num_monitor_devices, librocm_smi), Cint, (Ref{UInt32},), n) + [i for i in UInt32(0):UInt32(n[] - 1)] +end + +function PerfTest.read_joule(d::UInt32) + energy = Ref{UInt64}(0) + counter_resolution = Ref{Cfloat}(0) + timestamp = Ref{UInt64}(0) + ccall((:rsmi_dev_energy_count_get, librocm_smi), Cint, + (UInt32, Ref{UInt64}, Ref{Cfloat}, Ref{UInt64}), + d, energy, counter_resolution, timestamp) + energy[] * counter_resolution[] / 1e6 # microjoules -> joules +end + +function PerfTest.gpuPowerMeasureAMD(e :: Expr, name) + return quote + begin + devs = PerfTest.amdgpu_devices() + nsamples = max(1, length(ts.benchmarks[$name])) + energy_samples = Vector{Vector{Float64}}() + for _s in 1:nsamples + AMDGPU.synchronize() + pre = [] + for d in devs + push!(pre, PerfTest.read_joule(d)) + end + # Execute + $(e) + AMDGPU.synchronize() + post = [] + for d in devs + push!(post, PerfTest.read_joule(d)) + end + push!(energy_samples, Float64.(post .- pre)) + end + energy = [ + let dev_samples = Float64[energy_samples[s][d] for s in 1:nsamples] + nsamples >= PerfTest.MIN_VARIANCE_SAMPLES ? + PerfTest.SampledValue(dev_samples, PerfTest._sample_median(dev_samples)) : + PerfTest._sample_median(dev_samples) + end + for d in eachindex(devs) + ] + power = energy + @info energy, power + energy, power + end + end +end + +PerfTest.newSymbols(::Val{:amde}) = PerfTest.formulaGetAMDGPUEnergy +PerfTest.newSymbols(::Val{:amdp}) = PerfTest.formulaGetAMDGPUPower + +function PerfTest.formulaGetAMDGPUEnergy(properties) + if length(properties) == 0 + return quote sum(test_res.extensions[3].energy) end + end + s = String(properties[1]) + if match(r"^dev[0-9]+$", s) !== nothing + return quote test_res.extensions[3].energy end + else + throw(ArgumentError("Unknown specifier: $s")) + end +end + +function PerfTest.formulaGetAMDGPUPower(properties) + if length(properties) == 0 + return quote sum(test_res.extensions[3].power) end + end + s = String(properties[1]) + if match(r"^dev[0-9]+$", s) !== nothing + return quote test_res.extensions[3].power end + else + throw(ArgumentError("Unknown specifier: $s")) + end +end + +end # module diff --git a/ext/PerfTest_CUDAExt.jl b/ext/PerfTest_CUDAExt.jl new file mode 100644 index 0000000..5e516a3 --- /dev/null +++ b/ext/PerfTest_CUDAExt.jl @@ -0,0 +1,96 @@ +module PerfTest_CUDAExt + +""" +PerfTest_CUDAExt + +TODO WIP CUDA extension for marker-based energy and power sampling. + +Usage (example): + +Notes: +""" + +using PerfTest +using CUDA + +function PerfTest.is_loaded(::Val{:CUDA}) return true end + +struct CUDAExtensionData <: PerfTest.ExtensionData + # Value type is loose (not a concrete SampledValue{Float64}) because whether a device's + # entry is a SampledValue depends on nsamples >= MIN_VARIANCE_SAMPLES at measurement time. + energy :: Vector{Any} + power :: Vector{Any} +end + +PerfTest.CUDAExtensionData(energy, power) = CUDAExtensionData(energy, power) + +cuda_devices = [] + +PerfTest.cuda_devices() = [i for i in CUDA.NVML.devices()] + +PerfTest.read_joule(d::CUDA.NVML.Device) = CUDA.NVML.energy_consumption(d) + +function PerfTest.gpuPowerMeasure(e :: Expr, name) + return quote + begin + devs = PerfTest.cuda_devices() + nsamples = max(1, length(ts.benchmarks[$name])) + energy_samples = Vector{Vector{Float64}}() + for _s in 1:nsamples + CUDA.synchronize() + pre = [] + for d in devs + push!(pre, PerfTest.read_joule(d)) + end + # Execute + $(e) + CUDA.synchronize() + post = [] + for d in devs + push!(post, PerfTest.read_joule(d)) + end + push!(energy_samples, Float64.(post .- pre)) + end + energy = [ + let dev_samples = Float64[energy_samples[s][d] for s in 1:nsamples] + nsamples >= PerfTest.MIN_VARIANCE_SAMPLES ? + PerfTest.SampledValue(dev_samples, PerfTest._sample_median(dev_samples)) : + PerfTest._sample_median(dev_samples) + end + for d in eachindex(devs) + ] + power = energy + @info energy, power + energy, power + end + end +end + +PerfTest.newSymbols(::Val{:gpue}) = PerfTest.formulaGetGPUEnergy +PerfTest.newSymbols(::Val{:gpup}) = PerfTest.formulaGetGPUPower + +function PerfTest.formulaGetGPUEnergy(properties) + if length(properties) == 0 + return quote sum(test_res.extensions[2].energy) end + end + s = String(properties[1]) + if match(r"^dev[0-9]+$", s) !== nothing + return quote test_res.extensions[2].energy end + else + throw(ArgumentError("Unknown specifier: $s")) + end +end + +function PerfTest.formulaGetGPUPower(properties) + if length(properties) == 0 + return quote sum(test_res.extensions[2].power) end + end + s = String(properties[1]) + if match(r"^dev[0-9]+$", s) !== nothing + return quote test_res.extensions[2].power end + else + throw(ArgumentError("Unknown specifier: $s")) + end +end + +end # module diff --git a/ext/PerfTest_LIKWIDExt.jl b/ext/PerfTest_LIKWIDExt.jl new file mode 100644 index 0000000..5229aaa --- /dev/null +++ b/ext/PerfTest_LIKWIDExt.jl @@ -0,0 +1,477 @@ +module PerfTest_LIKWIDExt + +using LIKWID +using PerfTest +using DataStructures: OrderedDict + +function PerfTest.is_loaded(::Val{:LIKWID}) return true end + +# ---------------------------------------------------------------------------- +# Extension data type to store LIKWID results in Test_Result +# ---------------------------------------------------------------------------- +struct LIKWIDExtensionData <: PerfTest.ExtensionData + metrics::OrderedDict + events::OrderedDict +end +PerfTest.LIKWIDExtensionData(metrics, events) = LIKWIDExtensionData(OrderedDict(metrics), OrderedDict(events)) + +# ---------------------------------------------------------------------------- +# perfmon entry point +# ---------------------------------------------------------------------------- + +# `expr` is the (quoted) user code, `groups` is the requested LIKWID group list. +# Recursively median-merges `nsamples` LIKWID result dicts (metrics or events) into one, +# walking LIKWID's actual return shape (group => per-thread Vector => name => Float64) +# down to its scalar leaves regardless of exact nesting. +function _merge_likwid_samples(samples::Vector) + first_sample = first(samples) + if first_sample isa AbstractDict + # NOTE: intentionally not `empty(first_sample)` — that preserves the source dict's + # concrete value type (e.g. Dict{String,Float64}), which would reject a SampledValue + # leaf once merging starts returning those instead of plain Float64s. + result = Dict{keytype(first_sample), Any}() + for k in keys(first_sample) + result[k] = _merge_likwid_samples([s[k] for s in samples]) + end + return result + elseif first_sample isa AbstractVector + return [_merge_likwid_samples([s[i] for s in samples]) for i in eachindex(first_sample)] + else + leaf = Float64.(samples) + n = length(leaf) + med = PerfTest._sample_median(leaf) + return n >= PerfTest.MIN_VARIANCE_SAMPLES ? PerfTest.SampledValue(leaf, med) : med + end +end + +# `nsamples` repeats the whole multi-group perfmon call (LIKWID only allows one active +# group at a time, so each call already does one execution per group -- looping the call +# itself N times gives N samples per group, i.e. N*length(groups) total executions). +function PerfTest.perfmon(f, groups; nsamples::Integer=1, kwargs...) + nsamples = max(1, nsamples) + if nsamples == 1 + return LIKWID.perfmon(f, groups; kwargs...) + end + metric_samples = Vector{Any}(undef, nsamples) + event_samples = Vector{Any}(undef, nsamples) + for i in 1:nsamples + metric_samples[i], event_samples[i] = LIKWID.perfmon(f, groups; kwargs...) + end + return _merge_likwid_samples(metric_samples), _merge_likwid_samples(event_samples) +end +PerfTest.var"@PRFT_perfmon"(__source__::LineNumberNode, __module__::Module, groups, expr) = quote LIKWID.perfmon(() -> $expr, $groups; autopin=false, print=false) end + +# ============================================================================ +# Specifier sets +# ============================================================================ +const flop_submetrics_type = Set([ + :single, + :double, + :integer, +]) + +const flop_submetrics_vectorize = Set([ + :scalar, + :vector, + :vector_128, + :vector_256, + :vector_512, +]) + +const bw_metrics_level = Set([ + :l1, + :l2, + :l3, + :mem, +]) + +const bw_metrics_kind = Set([ + :read, + :write, + :read_write, + :read_volume, + :write_volume, + :read_write_volume, +]) + +const energy_metrics_part = Set([ + :package, + :dram, + :all, +]) + +# ============================================================================ +# Helpers +# ============================================================================ +""" + classify(properties, sets...) + +Split a flat list of specifier symbols into the categories defined by the +named `sets`. Returns a NamedTuple-like Dict mapping each set's name to the +matched symbol (or `nothing`) and validates that every property belongs to +exactly one of the provided sets. +""" +function classify(properties, sets::Pair{Symbol,<:AbstractSet}...) + result = Dict{Symbol,Any}(name => nothing for (name, _) in sets) + for p in properties + matched = false + for (name, set) in sets + if p in set + if result[name] !== nothing + error("Conflicting specifiers '$(result[name])' and '$p' " * + "for category '$name'.") + end + result[name] = p + matched = true + break + end + end + matched || error("Invalid specifier '$p'. Valid options are: " * + "$(union(map(last, sets)...)).") + end + return result +end + +# ============================================================================ +# FLOP / FLOP-rate formulas +# ============================================================================ +# LIKWID exposes ready-made FLOP metrics in the FLOPS_* groups. We map the +# (type, vectorization) specifier combination onto the right LIKWID metric +# name. Where LIKWID does not provide a pre-computed metric we fall back to +# summing the underlying retired-instruction events with the right weights. + +# Precomputed LIKWID metric names per type (double / single). +const _flop_metric_by_type = Dict( + :double => ("FLOPS_DP", "DP [MFLOP/s]"), + :single => ("FLOPS_SP", "SP [MFLOP/s]"), +) + +# Event weights (counts × elements-per-op) used when we need fine-grained +# vectorization breakdowns that LIKWID does not expose directly. +const _flop_events_double = [ + (:FP_ARITH_INST_RETIRED_SCALAR_DOUBLE, 1, :scalar), + (:FP_ARITH_INST_RETIRED_128B_PACKED_DOUBLE, 2, :vector_128), + (:FP_ARITH_INST_RETIRED_256B_PACKED_DOUBLE, 4, :vector_256), + (:FP_ARITH_INST_RETIRED_512B_PACKED_DOUBLE, 8, :vector_512), +] + +const _flop_events_single = [ + (:FP_ARITH_INST_RETIRED_SCALAR_SINGLE, 1, :scalar), + (:FP_ARITH_INST_RETIRED_128B_PACKED_SINGLE, 4, :vector_128), + (:FP_ARITH_INST_RETIRED_256B_PACKED_SINGLE, 8, :vector_256), + (:FP_ARITH_INST_RETIRED_512B_PACKED_SINGLE, 16, :vector_512), +] + +# Build a `quote` that sums the chosen weighted events. Widths the current +# architecture doesn't support (e.g. AVX-512 on a CPU without it) are +# retrieved with `required=false`, so they contribute 0 instead of failing +# the whole sum. +function _flop_event_expr(events, group) + terms = Expr[] + for (ev, weight, _vec) in events + push!(terms, :(PerfTest.likwidEventsRetrieve(test_res, $(QuoteNode(group)), + $(QuoteNode(ev)); required=false) .* $weight)) + end + body = foldl((a, b) -> :($a .+ $b), terms) + return :(sum($body)) +end + +""" + formulaGetFlop(test_res, properties) + +Total floating-point operations. + +Specifiers (any order): + * type: :double (default) | :single | :integer + * vectorization: :scalar | :vector_128 | :vector_256 | :vector_512 | :vector + (omit ⇒ all widths summed) +""" +function PerfTest.formulaGetFlop(properties) + spec = classify(properties, + :type => flop_submetrics_type, + :vec => flop_submetrics_vectorize) + + ftype = something(spec[:type], :double) # default: double precision + fvec = spec[:vec] # default (nothing): all widths + + if ftype === :integer + # Integer "ops" come from a different counter set. + #return :(sum(PerfTest.likwidMetricsRetrieve($test_res, :FLOPS_DP, + # TODO "Operations [OPS/s]"))) + return :(0) + end + + events = ftype === :single ? _flop_events_single : _flop_events_double + group = ftype === :single ? :FLOPS_SP : :FLOPS_DP + + push!(PerfTest.ctx._local.enabled_likwid_groups, group) + + if fvec === nothing + # Aggregate (no breakdown requested): derive the count from LIKWID's own + # portable rate metric -- the same one :flops/:flop_s already use -- + # instead of summing raw, Intel-only per-width events. Some + # architectures (e.g. AMD Zen3, whose FLOPS_DP group exposes a single + # RETIRED_SSE_AVX_FLOPS_ALL event under a completely different name) + # don't expose those events at all, and the raw-event sum would + # otherwise silently resolve to 0 with `required=false` swallowing + # every missing lookup. + _, metric = _flop_metric_by_type[ftype] + return :(sum(PerfTest.likwidMetricsRetrieve(test_res, + $(QuoteNode(group)), $metric)) * 1e6 * + test_res.primitives[:median_time]) + elseif fvec === :vector + # Sum of vector widths only (scalar excluded): still a per-width + # breakdown, same as an explicit :vector_128/:vector_256/:vector_512 + # request below -- inherently not portable to architectures without + # per-width FLOP events, so this stays on the raw-event path. + chosen = filter(e -> e[3] !== :scalar, events) + return _flop_event_expr(chosen, group) + else + chosen = filter(e -> e[3] === fvec, events) + isempty(chosen) && error("No FLOP event for vectorization '$fvec' " * + "and type '$ftype'.") + return _flop_event_expr(chosen, group) + end +end + +""" + formulaGetFlops(test_res, properties) + +Floating-point operation *rate* (FLOP/s). Same specifiers as +[`formulaGetFlop`](@ref); uses LIKWID's precomputed rate metrics when no +vectorization breakdown is requested. +""" +function PerfTest.formulaGetFlops(properties) + spec = classify(properties, + :type => flop_submetrics_type, + :vec => flop_submetrics_vectorize) + + ftype = something(spec[:type], :double) + fvec = spec[:vec] + + if fvec === nothing && haskey(_flop_metric_by_type, ftype) + group, metric = _flop_metric_by_type[ftype] + push!(PerfTest.ctx._local.enabled_likwid_groups, Symbol(group)) + return :(sum(PerfTest.likwidMetricsRetrieve(test_res, + $(QuoteNode(Symbol(group))), + $metric)) * 1e6) # LIKWID reports MFLOP/s + end + + error("Per-vectorization FLOP/s requires a timed reduction; request " * + "raw counts via :flop instead, or omit the vectorization specifier.") +end + +# ============================================================================ +# Bandwidth formulas +# ============================================================================ +# LIKWID groups: L2 / L3 / MEM expose " bandwidth [MBytes/s]" plus +# directional "load"/"evict" variants. +const _bw_group = Dict( + :l1 => :L1, # may not exist on all archs; left for completeness + :l2 => :L2, + :l3 => :L3, + :mem => :MEM, +) + +const _bw_metric = Dict( + (:l2, :read_write) => "L2 bandwidth [MBytes/s]", + (:l2, :read) => "L2D load bandwidth [MBytes/s]", + (:l2, :write) => "L2D evict bandwidth [MBytes/s]", + (:l3, :read_write) => "L3 bandwidth [MBytes/s]", + (:l3, :read) => "L3 load bandwidth [MBytes/s]", + (:l3, :write) => "L3 evict bandwidth [MBytes/s]", + (:mem, :read_write) => "Memory bandwidth [MBytes/s]", + (:mem, :read) => "Memory read bandwidth [MBytes/s]", + (:mem, :write) => "Memory write bandwidth [MBytes/s]", + # Data volume: total GBytes transferred over the whole measurement window + # (not a rate) -- LIKWID's sibling metric in the same group. + (:l2, :read_write_volume) => "L2 data volume [GBytes]", + (:l2, :read_volume) => "L2D load data volume [GBytes]", + (:l2, :write_volume) => "L2D evict data volume [GBytes]", + (:l3, :read_write_volume) => "L3 data volume [GBytes]", + (:l3, :read_volume) => "L3 load data volume [GBytes]", + (:l3, :write_volume) => "L3 evict data volume [GBytes]", + (:mem, :read_write_volume) => "Memory data volume [GBytes]", + (:mem, :read_volume) => "Memory read data volume [GBytes]", + (:mem, :write_volume) => "Memory write data volume [GBytes]", +) + +""" + formulaGetBandwidth(test_res, properties) + +Memory/cache bandwidth in MBytes/s, or total data volume in GBytes. + +Specifiers: + * level: :l1 | :l2 | :l3 | :mem (default :mem) + * kind: :read | :write | :read_write | + :read_volume | :write_volume | :read_write_volume (default :read_write) +""" +function PerfTest.formulaGetBandwidth(properties) + spec = classify(properties, + :level => bw_metrics_level, + :kind => bw_metrics_kind) + level = something(spec[:level], :mem) + kind = something(spec[:kind], :read_write) + + haskey(_bw_metric, (level, kind)) || + error("Bandwidth not available for level '$level' kind '$kind'.") + haskey(_bw_group, level) || + error("Unknown bandwidth level '$level'.") + + group = _bw_group[level] + metric = _bw_metric[(level, kind)] + push!(PerfTest.ctx._local.enabled_likwid_groups, group) + return :(sum(PerfTest.likwidMetricsRetrieve(test_res, + $(QuoteNode(group)), $metric))) +end + +# ============================================================================ +# Energy / Power formulas +# ============================================================================ +const _energy_metric = Dict( + :package => "Energy [J]", + :dram => "Energy DRAM [J]", +) +const _power_metric = Dict( + :package => "Power [W]", + :dram => "Power DRAM [W]", +) + +""" + formulaGetEnergy(test_res, properties) + +Consumed energy in Joules. Specifier: :package | :dram | :all (default). +""" +function PerfTest.formulaGetEnergy(properties) + spec = classify(properties, :part => energy_metrics_part) + part = something(spec[:part], :all) + return _energy_or_power(part, _energy_metric) +end + +""" + formulaGetPower(test_res, properties) + +Average power draw in Watts. Specifier: :package (default) | :dram | :all. +""" +function PerfTest.formulaGetPower(properties) + spec = classify(properties, :part => energy_metrics_part) + part = something(spec[:part], :all) + return _energy_or_power(part, _power_metric) +end + +function _energy_or_power(part, table) + if part === :all + terms = [:(sum(PerfTest.likwidMetricsRetrieve(test_res, :ENERGY, $m))) + for m in values(table)] + return foldl((a, b) -> :($a + $b), terms) + end + push!(PerfTest.ctx._local.enabled_likwid_groups, :ENERGY) + haskey(table, part) || error("No energy/power metric for part '$part'.") + return :(sum(PerfTest.likwidMetricsRetrieve(test_res, :ENERGY, + $(table[part])))) +end + +# ============================================================================ +# Cache-miss formulas +# ============================================================================ +""" + formulaGetMisses(test_res, properties) + +Cache miss counts/ratios. Specifier: level (:l2 default | :l3). +""" +function PerfTest.formulaGetMisses(properties) + spec = classify(properties, :level => bw_metrics_level) + level = something(spec[:level], :l2) + metric = level === :l3 ? "L3 miss ratio" : "L2 miss ratio" + group = level === :l3 ? :L3CACHE : :L2CACHE + push!(PerfTest.ctx._local.enabled_likwid_groups, level === :l3 ? :L3CACHE : :L2CACHE) + return :(sum(PerfTest.likwidMetricsRetrieve(test_res, + $(QuoteNode(group)), $metric))) +end + +# ============================================================================ +# GPU formula (placeholder; depends on NVMON availability) +# ============================================================================ +""" +TODO formulaGetGPU(test_res, properties) + +GPU metrics via LIKWID's NVMON backend. Specifier list is forwarded as the +metric name for now (extend as needed). +""" +function PerfTest.formulaGetGPU(properties) + isempty(properties) && + error("Specify a GPU metric, e.g. :gpu with a metric specifier.") + metric = String(properties[1]) + return :(sum(PerfTest.likwidMetricsRetrieve(test_res, :GPU, $metric))) +end + +# ============================================================================ +# Alias dictionary (defined AFTER the functions it references) +# ============================================================================ +PerfTest.newSymbols(::Val{:flop}) = PerfTest.formulaGetFlop +PerfTest.newSymbols(::Val{:flops}) = PerfTest.formulaGetFlops +PerfTest.newSymbols(::Val{:flop_s}) = PerfTest.formulaGetFlops +PerfTest.newSymbols(::Val{:bw}) = PerfTest.formulaGetBandwidth +PerfTest.newSymbols(::Val{:energy}) = PerfTest.formulaGetEnergy +PerfTest.newSymbols(::Val{:power}) = PerfTest.formulaGetPower +PerfTest.newSymbols(::Val{:miss}) = PerfTest.formulaGetMisses + +""" + resolveAlias(alias, test_res, properties) :: Expr + +Entry point for the shortcut nomenclature: given a main `alias` and a chain of +specifier symbols `properties`, dispatch to the right formula function. +""" +function PerfTest.resolveAlias(alias::Symbol, properties) + haskey(additional_metric_aliases, alias) || + error("Unknown metric alias ':$alias'. Known aliases: " * + "$(collect(keys(additional_metric_aliases))).") + return additional_metric_aliases[alias](properties) +end + +# ============================================================================ +# Retrieval primitives (native LIKWID names) +# ============================================================================ +function PerfTest.likwidEventsRetrieve(test_res, group, event_name; required::Bool=true) + for extension in test_res.extensions + if extension isa LIKWIDExtensionData + return _likwidThingsRetrieve(extension.events, group::Union{String,Symbol}, event_name::Union{String,Symbol}; required=required) + end + end + throw(ArgumentError("Test result does not contain LIKWID extension data")) +end + +function PerfTest.likwidMetricsRetrieve(test_res, group::Union{String,Symbol}, metric_name::Union{String,Symbol}) + for extension in test_res.extensions + if extension isa LIKWIDExtensionData + return _likwidThingsRetrieve(extension.metrics, group, metric_name) + end + end + throw(ArgumentError("Test result does not contain LIKWID extension data")) +end + +function _likwidThingsRetrieve(dict, group::Union{String,Symbol}, name::Union{String,Symbol}; required::Bool=true) + if group isa Symbol + group = String(group) + end + if name isa Symbol + name = String(name) + end + haskey(dict, group) || + throw(ArgumentError("LIKWID group '$group' not found in test results")) + group_data = dict[group] + ret_val = [] + for thread_id in keys(group_data) + if haskey(group_data[thread_id], name) + push!(ret_val, group_data[thread_id][name]) + elseif required + throw(ArgumentError("Event/Metric '$name' not found in LIKWID " * + "group '$group' (at least for thread '$thread_id')")) + else + push!(ret_val, 0) + end + end + return ret_val +end + +end # module \ No newline at end of file diff --git a/ext/PerfTest_MPIExt.jl b/ext/PerfTest_MPIExt.jl index 48d23b2..6592c27 100644 --- a/ext/PerfTest_MPIExt.jl +++ b/ext/PerfTest_MPIExt.jl @@ -12,6 +12,8 @@ using LinearAlgebra using BenchmarkTools using Base.Threads +PerfTest.is_loaded(:Val{:PerfTest_MPIExt}) = true + # Module-level MPI state mpi_rank = 0 mpi_size = 1 @@ -408,9 +410,11 @@ function PerfTest.newMetricResult(::Type{PerfTest.MPIMode}; auxiliary=false, magnitude_prefix="", magnitude_mult=1, - reduct="Sum") + reduct="Sum", + showvar=false) mpi_info = PerfTest.MPI_MetricInfo(MPI.Comm_size(MPI.COMM_WORLD), reduct) - return PerfTest.Metric_Result(name, units, value, auxiliary, magnitude_prefix, magnitude_mult, mpi_info) + val, sem, n = PerfTest._unwrapSampledValue(value) + return PerfTest.Metric_Result(name, units, val, auxiliary, magnitude_prefix, magnitude_mult, mpi_info, PerfTest._gatedVariance(sem, n, showvar), n) end # Build primitive metrics with MPI reduction diff --git a/perftest_config.toml b/perftest_config.toml new file mode 100644 index 0000000..f12732c --- /dev/null +++ b/perftest_config.toml @@ -0,0 +1,44 @@ +[perfcompare] +enabled = true + +[MPI] +mode = "reduce" +enabled = false + +[general] +save_results = true +max_saved_results = 20 +suppress_output = true +save_folder = ".perftests" +threads_per_numa = "single" +recursive = true +verbose = 3 +autoflops = true +plotting = true +numas = "single" +logs_enabled = true +safe_formulas = false + +[regression] +enabled = true +default_threshold = 1.1 +use_bencher = false +dedicated_reference_file = "" + +[roofline] +enabled = true +default_threshold = 0.5 + +[memory_bandwidth] +enabled = true +default_threshold = 0.5 + +[machine_benchmarking] +memory_bandwidth_test_buffer_size = 0 + +[bencher] +api_key = "" +organization = "" +api_url = "https://api.bencher.dev" +project_name = "" +custom_testbed_name = "" diff --git a/src/PerfTest.jl b/src/PerfTest.jl index f032719..c1083ee 100644 --- a/src/PerfTest.jl +++ b/src/PerfTest.jl @@ -13,13 +13,10 @@ using BenchmarkTools using LinearAlgebra using Hwloc -var"@capture" = MacroTools.var"@capture" -abstract type Mode end -struct MPIMode <: Mode end -struct NormalMode <: Mode end +var"@capture" = MacroTools.var"@capture" -mode = NormalMode +include("extension_stubs.jl") ### PARSING TIME @@ -55,6 +52,7 @@ include("transform/suffix.jl") # EXECUTION PART +include("execution/variance.jl") include("execution/structs.jl") include("execution/testset.jl") @@ -73,8 +71,6 @@ include("execution/macros/configuration.jl") include("execution/macros/topology.jl") # Rules of the ruleset -include("transform/parsing/hierarchy_transform_test_region.jl") -include("transform/parsing/hierarchy_transform_benchmark_region.jl") include("transform/parsing/hierarchy_transform.jl") include("transform/parsing/target_transform.jl") include("transform/parsing/formula_transform.jl") @@ -90,6 +86,9 @@ include("execution/retrieve.jl") include("execution/units.jl") include("execution/misc.jl") +# Multithread suite launcher +include("execution/launch_suite.jl") + # Bencher Interface include("bencher/BencherREST.jl") @@ -131,6 +130,7 @@ perftest_expression_ruleset = [ perftest_scope_assignment_macro_rule, perftest_scope_arg_macro_rule, perftest_scope_vecf_arg_macro_rule, + perftest_scope_ref_rule, perftest_dot_interpolation_rule, ] @@ -186,31 +186,65 @@ function setupContext(path::AbstractString) ctx._global.original_file_path = path end +""" +Load the configuration a top level transform starts from, and make it the current one: the configuration file, +overridden by `config` (e.g. the config argument of runperftests, `source` names it in the reported errors), overridden +by `overrides` (`overrides_source` names them). The configuration file is loaded, and its errors reported, once. A top +level transform never inherits the configuration of a previous one. Where each value comes from is recorded in +Configuration.SOURCES. +""" +function loadTransformConfig(config::Union{Dict,Nothing}, source::AbstractString, overrides::Dict = Dict{String,Any}(), + overrides_source::AbstractString = "the keyword arguments of runperftests")::Dict + empty!(Configuration.PARENT_CONFIGS) + empty!(Configuration.PARENT_SOURCES) + if init_dummy_flag + return Configuration.load_dummy_config() + end + + loaded = Configuration.load_config() + sources = copy(Configuration.SOURCES) + if config !== nothing + Configuration.report_unknown_entries(config, source) + loaded = Configuration.merge_configs(loaded, config; source = source) + Configuration.record_sources!(sources, config, source) + end + if !isempty(overrides) + loaded = Configuration.merge_configs(loaded, overrides) + Configuration.record_sources!(sources, overrides, overrides_source) + end + loaded = Configuration.load_config(loaded) + merge!(Configuration.SOURCES, sources) + return loaded +end + """ This method implements the transformation that converts a recipe script into a fully-fledged testing suite. The function will return a Julia expression with the resulting performance testing suite. This can be then executed or saved in a file for later usage. # Arguments - `path` the path of the script to be transformed. +# Keyword arguments + - `config` configuration parameters that override the configuration file, see runperftests. + """ -function treeRun(path::AbstractString; config=nothing) +function treeRun(path::AbstractString; config::Union{Dict,Nothing}=nothing) + return transformWith(path, config, "the config argument of PerfTest.transform") +end + +""" +Transform the recipe at `path`, see `treeRun`. `source` names where `config` comes from in the reported errors, +`overrides` take priority over it (e.g. the verbose argument of runperftests, `overrides_source` names them). +""" +function transformWith(path::AbstractString, config::Union{Dict,Nothing}, source::AbstractString, overrides::Dict = Dict{String,Any}(), + overrides_source::AbstractString = "the keyword arguments of runperftests") # Set log directory setLogFolder() # Clear logs #clearLogs() - # Load configuration - if init_dummy_flag - config = Configuration.load_dummy_config() - else - if config === nothing - config = Configuration.load_config() - else - _config = Configuration.load_config() - config = Configuration.merge_configs(_config, config) - Configuration.load_config(config) - end - end + # The configuration the transform starts from, a @perftest_config changes it from its place in the recipe onwards + config = loadTransformConfig(config, source, overrides, overrides_source) + initThreadSetting!() if config["general"]["verbose"] >= 1 verboseOutput() @@ -227,23 +261,35 @@ function treeRun(path::AbstractString; config=nothing) global mode = NormalMode end + # The generated suite starts from this configuration, never from the one of the process that executes it. Except for + # the [bencher] section, which the suite reads when it executes so the credentials are never written into it. + # TODO: the display keys (general.verbose, general.plotting) are fixed at generation as well, a later update shall + # let them be set when an already generated suite is executed + initial_config = deepcopy(Configuration.CONFIG) + delete!(initial_config, "bencher") + initial_config = sprint(TOML.print, initial_config) + # Load original input_expr = loadFileAsExpr(path) setupContext(path) - Topology.setupLog(addLog, x -> throwParseError!(x, ctx)) + Topology.setupLog(addLog, x -> throwParseError!("Invalid thread arrangement: $x", ctx)) # Run through AST and build new expressions full = _treeRun(input_expr, ctx) + # The thread setting the launcher will use, once every configuration call is known + validateThreadSetting!(ctx) + # Insert suffix #full = MacroTools.postwalk(ruleSet(ctx, [suffix_macro_rule]), full) # Mount inside a module environment module_full = Expr(:toplevel, Expr(:module, true, :__PERFTEST__, - Expr(:block, full.args...))) + Expr(:block, :(import PerfTest), :(PerfTest._perftest_config($initial_config)), + :(PerfTest.Configuration.load_bencher_config()), full.args...))) if num_errors(ctx) > 0 printErrors(ctx) @@ -253,11 +299,13 @@ function treeRun(path::AbstractString; config=nothing) end - if config["general"]["verbose"] >= 2 - saveLogFolder() + # The configuration in force at the end of the recipe, the included recipes give theirs back after them. Nothing is + # saved if general.logs_enabled is false there + if Configuration.CONFIG["general"]["verbose"] >= 2 + saveLogFolder(Configuration.CONFIG) end - return MacroTools.prettify(module_full) + return rewrapDoBlockBodies(MacroTools.prettify(module_full)) end @@ -273,16 +321,18 @@ end # Keyword arguments `execute::Bool = true` : whether the resulting suite should be executed right after generation, by default true. If false, the resulting suite will only be saved in a file with the name of the input with and added "_perfsuite.jl" suffix. - `verbose::Int = 0` : level of verbosity, from 0 to 3 higher is more verbose + `verbose::Union{Int,Nothing} = nothing` : level of verbosity, from 0 to 3 higher is more verbose. When given it overrides general.verbose of the config argument and of the configuration file, otherwise their value is used. 0 : minimal output, only warnings and errors 1 : general information about the transformation and execution process 2 : detailed information about the transformation and execution process, logs are saved in a folder 3 : debug level, very detailed information about the transformation and execution process `clean ::Bool = false` : whether to leave the config file, the output test suite and the test results or delete everything after the suite has been executed, !!! including previously done results and logs CAREFUL !!!. - `config ::Dict{String,Any} = {}` : other configuration parameters to override the configuration file. Configuration priority: config macro > this argument > configuration file. See configuration for more info. - + `config ::Union{Dict{String,Any},Nothing} = nothing` : other configuration parameters to override the configuration file. Configuration priority: config macro > verbose argument > this argument > configuration file. See configuration for more info. + `interpreter_flags::AbstractString = ""` : flags of the julia process that executes the suite, split at whitespace and passed in order (e.g. "-O3 -L setup.jl"), --check-bounds=no and --project=. unless they set them. They cannot set the number of threads (-t, --threads), which comes from the thread setting of the suite (general.numas and general.threads_per_numa, or a @perftest_threads), it is an error. + `suite_flags::AbstractString = ""` : passed to the suite as a single argument, nothing if empty. + - # (!) Do not mistake this method for the macro with the same name, which is used to set test targets inside the recipe script. + # (!) Do not mistake this method for the perftest macro, which is used to set test targets inside the recipe script. # Example of a config parameter value: `{"regression" : {"enabled" : true}, "general" : {"recursive" : false}}` @@ -290,24 +340,11 @@ end See the macro reference for more details about the recipe script format and the possible configurations. """ -function runperftests(file::AbstractString; execute::Bool=true, verbose::Int=0, clean::Bool=false, config::Union{Dict,Nothing}=nothing) - # Load config file - Configuration.load_config() - # Override with config argument - if config isa Dict - config = Configuration.merge_configs(Configuration.CONFIG, config) - else - config = Configuration.CONFIG - end - # Override with parameters - configp = Dict{String,Any}() - configp["general"] = Dict{String,Any}() - if config["general"]["verbose"] != verbose - configp["general"]["verbose"] = verbose - end - config = Configuration.merge_configs(config, configp) +function runperftests(file::AbstractString; execute::Bool=true, verbose::Union{Int,Nothing}=nothing, clean::Bool=false, config::Union{Dict,Nothing}=nothing, interpreter_flags::AbstractString="", suite_flags::AbstractString="") + # Only a verbose argument that is given overrides the configuration + overrides = verbose === nothing ? Dict{String,Any}() : Dict{String,Any}("general" => Dict{String,Any}("verbose" => verbose)) - expr = treeRun(file, config=config) + expr = transformWith(file, config, "the config argument of runperftests", overrides, "the verbose argument of runperftests") name = replace(file, r"\.jl$" => "_perfsuite.jl") saveExprAsFile(expr, name) if num_errors(ctx) == 0 @@ -317,15 +354,16 @@ function runperftests(file::AbstractString; execute::Bool=true, verbose::Int=0, end if execute && mode == NormalMode addLog("general", "[PERFTEST] Executing performance testing suite $name") - Main.include(name) + Launch.launchPerfTestSuite(name, interpreter_flags, suite_flags) end end if clean rm(name) rm("./perftest_config.toml") - rm("./$(Configuration.CONFIG["general"]["save_folder"])", recursive=true) + # Only created if the suite saved its results + rm("./$(Configuration.CONFIG["general"]["save_folder"])", recursive=true, force=true) if ispath("./.perftest_logs") - rm("./perftest_logs", recursive=true) + rm("./.perftest_logs", recursive=true) end end end @@ -360,6 +398,14 @@ PrecompileTools.@compile_workload begin rm("./$(Configuration.PRECOMPILATION_CONFIG["general"]["save_folder"])", recursive=true) end global init_dummy_flag = false + # Leave no state of the dummy transform in the package image + Configuration.load_config(Configuration.DEFAULT) + empty!(Configuration.PARENT_CONFIGS) + empty!(Configuration.PARENT_SOURCES) + empty!(THREAD_SETTING) + global ctx = nothing + global LOG_FOLDER = "" + Topology.setupLog(Topology.defaultAddLog, Topology.defaultThrowParseError!) end end diff --git a/src/execution/data_handling.jl b/src/execution/data_handling.jl index 895c81e..d254bbe 100644 --- a/src/execution/data_handling.jl +++ b/src/execution/data_handling.jl @@ -2,6 +2,44 @@ using JLD2: StringDatatype using JLD2 +# --- Backward compatibility: reading .perftests/*.JLD2 files saved before `variance`/`n` +# (Metric_Result) and `showvar` (Metric_Test) existed --- +# +# JLD2 reconstructs an on-disk struct whose field set doesn't match the current in-memory +# struct as a JLD2.AbstractReconstructedType (ReconstructedMutable/ReconstructedStatic) rather +# than a real Metric_Result/Metric_Test, then calls `JLD2.rconvert(TargetType, reconstructed)` +# to finish the conversion. Without an explicit override here, that falls through to the +# generic `rconvert(T, x) = convert(T, x)`, which has no applicable method for these structs +# and throws — meaning any datafile saved by a PerfTest.jl version before this feature (e.g. +# the baseline @regression compares new runs against) would fail to load at all. All fields +# accessed directly below (everything except `variance`/`n`/`showvar`) have existed since the +# very first version of these structs, so they're always present on a reconstructed value; +# only the fields this feature actually added need a propertynames check + fallback. +function JLD2.rconvert(::Type{Metric_Result}, x::JLD2.AbstractReconstructedType) + return Metric_Result( + x.name, x.units, x.value, x.auxiliary, x.magnitude_prefix, x.magnitude_mult, x.mpi, + :variance in propertynames(x) ? x.variance : nothing, + :n in propertynames(x) ? x.n : typemax(Int), + ) +end +# Covers the parametric form too (e.g. if a field is ever declared Dict{Symbol,Metric_Result{Float64}} +# rather than the unparameterized Metric_Result the rest of the codebase currently uses). +JLD2.rconvert(::Type{Metric_Result{N}}, x::JLD2.AbstractReconstructedType) where N = JLD2.rconvert(Metric_Result, x) + +function JLD2.rconvert(::Type{Metric_Test}, x::JLD2.AbstractReconstructedType) + return Metric_Test( + reference = x.reference, + threshold_min_percent = x.threshold_min_percent, + threshold_max_percent = x.threshold_max_percent, + low_is_bad = x.low_is_bad, + succeeded = x.succeeded, + custom_plotting = x.custom_plotting, + full_print = x.full_print, + showvar = :showvar in propertynames(x) ? x.showvar : false, + ) +end +JLD2.rconvert(::Type{Metric_Test{N}}, x::JLD2.AbstractReconstructedType) where N = JLD2.rconvert(Metric_Test, x) + """ This method is used to get historical data of a performance test suite from a save file located in `path`. """ diff --git a/src/execution/launch_suite.jl b/src/execution/launch_suite.jl new file mode 100644 index 0000000..62e8624 --- /dev/null +++ b/src/execution/launch_suite.jl @@ -0,0 +1,165 @@ +module Launch + +export launchPerfTestSuite + +using ..PerfTest +using MacroTools +using TOML + +DEFAULT_INTERPRETER_FLAGS = Dict{String,String}( + "--check-bounds" => "no", + "--project" => "." +) + +# Name of the flag a token of the interpreter flags is, e.g. "--project" for "--project=." or "-O3" for "-O3" +flagName(token::AbstractString) = first(split(token, '='; limit=2)) + +""" +Arguments of the interpreter given by `flagstring` (e.g. "-O3 --depwarn=yes -L setup.jl"), split at whitespace, in the +order they are given: a flag whose value is a separate token (e.g. `-L setup.jl`) keeps it right after it, and a flag +given several times is passed each time (the interpreter decides, e.g. the last one for --depwarn). They are preceded by +the `default` flags that they do not set, e.g. --project=. unless they give --project. +""" +function parseFlags(flagstring::AbstractString, default::Dict{String,String})::Vector{String} + given = String.(split(flagstring)) + given_names = Set(flagName.(given)) + # Sorted, so the command is the same every time + defaults = ["$key=$value" for (key, value) in sort!(collect(default)) if !(key in given_names)] + return vcat(defaults, given) +end + +# Whether a token of the interpreter flags sets the number of threads: -t, -tN, --threads or --threads=N +isThreadsFlag(token::AbstractString) = (startswith(token, "-t") && !startswith(token, "--")) || flagName(token) == "--threads" + + +""" +Thread setting (general.numas, general.threads_per_numa) of a generated suite, `nothing` for a key no configuration call sets. +A suite has a single thread setting regardless of recursivity: each key takes its value from the last configuration call +of the suite that sets it, even when that call comes from an included recipe. The first call of the suite holds the whole +configuration it was generated with. An interpolated value is only known once the suite executes, it is not considered. +""" +function retrieveConfigThreadSpecs(suite::Expr) + specs = Dict{String,Any}("numas" => nothing, "threads_per_numa" => nothing) + MacroTools.prewalk(suite) do x + if @capture(x, PerfTest._perftest_config(serializedconfig_)) + try + general = get(TOML.parse(PerfTest.interpolationPreview(serializedconfig)), "general", Dict()) + for key in keys(specs) + if haskey(general, key) && !PerfTest.isInterpolated(general[key]) + specs[key] = general[key] + end + end + catch e + @error("Generated suite configuration is malformed TOML error: $e") + end + end + return x + end + return specs["numas"], specs["threads_per_numa"] +end + +""" +Arrangement (see Topology.ArrangementSpec) the generated suite at `path` is launched with, before it is resolved on this +machine. A @perftest_threads of the recipe takes priority. Otherwise it is given by the thread setting of the suite +(see retrieveConfigThreadSpecs and Topology.arrangementFromConfig), which the transform has already checked. An invalid +one, e.g. in a suite edited or generated by a different version of the package, throws an error naming the reason and +what the setting can be, as the suite cannot be launched with it. +""" +function suiteArrangement(path::AbstractString) + return first(suiteArrangementOrigin(path)) +end + +""" +The arrangement of the generated suite at `path` (see suiteArrangement), along with where it comes from, how to change +it and what it can be, as named in the errors of the launcher. +""" +function suiteArrangementOrigin(path::AbstractString)::Tuple{Any,String,String,String} + suite = PerfTest.loadFileAsExpr(path) + + # Extract the thread specifications of a @perftest_threads, see parseThreadsMacro + specs = nothing + stop = false + MacroTools.prewalk((x -> @capture(x, specs = thr_) ? (specs = thr; stop = true; nothing) : (stop ? nothing : x)), suite) + if specs !== nothing + arrangement = eval(specs) + return arrangement, "the @perftest_threads $(repr(arrangement)) of the recipe", + "change the @perftest_threads of the recipe, or remove it to use the thread setting of the configuration " * + "(general.numas and general.threads_per_numa)", PerfTest.THREADS_OPTIONS + end + + # One thread setting per suite, a key no configuration call sets, only in a suite generated by an old version of the + # package, has its default value + numas, threads_per_numa = (something(spec, PerfTest.Configuration.DEFAULT["general"][key]) + for (spec, key) in zip(retrieveConfigThreadSpecs(suite), PerfTest.THREAD_KEYS)) + arrangement = PerfTest.Topology.arrangementFromConfig(numas, threads_per_numa) + if arrangement isa Vector{String} + error("Cannot launch the suite $path, the thread setting of the generated suite is invalid, general.numas = " * + "$(repr(numas)) and general.threads_per_numa = $(repr(threads_per_numa)): $(join(arrangement, ", ")). " * + "$(PerfTest.Topology.THREAD_SETTING_RULE) $(PerfTest.Topology.CONFIG_THREADS_OPTIONS)") + end + return arrangement, "the thread setting of the suite, general.numas = $(repr(numas)) and general.threads_per_numa = " * + "$(repr(threads_per_numa))", + "set general.numas and general.threads_per_numa (in the configuration file $(PerfTest.Configuration.CONFIG_FILE), " * + "with the config argument of runperftests or with a @perftest_config of the recipe), or give the recipe a " * + "@perftest_threads, which takes priority over them", PerfTest.Topology.CONFIG_THREADS_OPTIONS +end + +""" +Arrangement the generated suite at `path` is launched with (see suiteArrangement), resolved on this machine (see +Topology.literallizeArrangement), e.g. (#numas, #threads_per_numa). It only sets the number of threads of the process +that executes the suite, the thread setting of the configuration does not pin threads, a @perftest_threads does. +""" +function retrieveThreadConfig(path::AbstractString) + return literalArrangement(path, suiteArrangement(path)) +end + +function literalArrangement(path::AbstractString, arrangement) + return try + PerfTest.Topology.literallizeArrangement(arrangement) + catch e + e isa ErrorException || rethrow() + error("Cannot launch the suite $path with the thread arrangement $(repr(arrangement)) on this machine: $(e.msg)") + end +end + +""" +Command that executes the generated suite at `path` in a new julia process, with the number of threads its thread +arrangement needs (see retrieveThreadConfig) and the given flags. `interpreter_flags` are passed to the interpreter (see +parseFlags), they cannot set the number of threads, it comes from the thread arrangement of the suite. `suite_flags` is +passed to the suite as a single argument, an empty one (or only whitespace) passes nothing. +""" +function suiteCommand(path::AbstractString, interpreter_flags::AbstractString="", suite_flags::AbstractString="")::Cmd + # Retrieve current interpreter + exename = joinpath(Sys.BINDIR, Base.julia_exename()) + # Convert to absolute path + _abspath = abspath(path) + # Check flags + flags = parseFlags(interpreter_flags, DEFAULT_INTERPRETER_FLAGS) + # Check thread configurations + arrangement, origin, change, options = suiteArrangementOrigin(path) + configurations = literalArrangement(path, arrangement) + threads_needed = configurations[1] * configurations[2] + # Add thread argument + given = findfirst(isThreadsFlag, flags) + if given !== nothing + # With its value, when it is a separate token + flag = flags[given] in ("-t", "--threads") && given < length(flags) ? join(flags[given:given+1], " ") : flags[given] + error("Cannot launch the suite $path with the interpreter flag `$flag` of interpreter_flags: the launcher sets " * + "the number of threads of the process that executes the suite, from the thread arrangement of the suite, " * + "to $threads_needed (--threads=$threads_needed), given by $origin, which is $(repr(configurations)) " * + "(#numas, #threads_per_numa) on this machine. Remove `$flag` from interpreter_flags. To change the number " * + "of threads, $change, then generate the suite again (runperftests does). $options") + end + args = isempty(strip(suite_flags)) ? String[] : [suite_flags] + return `$exename $flags --threads=$threads_needed $_abspath $args` +end + +""" + Runs the julia interpreter to execute a performance test suite, setting up adequately (e.g. thread number, flags) +""" +function launchPerfTestSuite(path::AbstractString, interpreter_flags::AbstractString="", suite_flags::AbstractString="") + # Spawn process + run(suiteCommand(path, interpreter_flags, suite_flags)) +end + +end \ No newline at end of file diff --git a/src/execution/machine_topology.jl b/src/execution/machine_topology.jl index f31806b..147b428 100644 --- a/src/execution/machine_topology.jl +++ b/src/execution/machine_topology.jl @@ -2,9 +2,13 @@ module Topology using Hwloc using ThreadPinningCore +import ..PerfTest -addLog = x -> @info "[$(string(x))]" -throwParseError! = x -> @error "Invalid thread arrangement: $x" +# Used when no transform has installed its callbacks, e.g. while a generated suite executes +defaultAddLog(channel, message) = PerfTest.addLog(channel, message) +defaultThrowParseError!(x) = @error "Invalid thread arrangement: $x" +addLog = defaultAddLog +throwParseError! = defaultThrowParseError! struct Index indexing::Vector{Integer} symbols::Vector{Symbol} @@ -250,7 +254,6 @@ function literallizeArrangement(arrgmt::ArrangementSpec)::Tuple{Integer,Integer} if Topology.hwloc_topology isa Nothing Topology.getMachineTopology!() end - reason = "" total_numas = Topology.numberOfNUMAS() threads_per_numa = Topology.threadsPerNuma() # Vector{Integer}, one entry per NUMA @@ -287,7 +290,7 @@ function literallizeArrangement(arrgmt::ArrangementSpec)::Tuple{Integer,Integer} error("Invalid thread arrangement: if #numa is and integer, it shall be positive, got $numa_spec.") end if numa_spec > total_numas - reason *= ("Invalid thread arrangement: requested $numa_spec NUMA domain(s) but " * + error("Invalid thread arrangement: requested $numa_spec NUMA domain(s) but " * "the host only has $total_numas.") end Integer(numa_spec) @@ -309,48 +312,44 @@ function literallizeArrangement(arrgmt::ArrangementSpec)::Tuple{Integer,Integer} "got $thread_spec.") end if thread_spec > min_threads_in_selected - reason *= ("Invalid thread arrangement: requested $thread_spec thread(s) per NUMA but " * + error("Invalid thread arrangement: requested $thread_spec thread(s) per NUMA but " * "the most constrained of the $literal_numas selected NUMA domain(s) only " * "has $min_threads_in_selected available thread(s).") end Integer(thread_spec) end - total_needed = literal_numas * literal_threads - - # Check Julia thread count - if Threads.nthreads() < total_needed - reason *= "Not enough threads on the interpreter." - addLog("machine", "Specified thread arrangement $arrgmt -> literalized to ($literal_numas, $literal_threads) cannot be applied on this Julia process. $reason Ignoring.") - return (0, 0) - elseif Threads.nthreads() > total_needed - reason *= "Too many threads on the interpreter ($(Threads.nthreads()) > $total_needed)." - addLog("machine", "Specified thread arrangement $arrgmt -> literalized to ($literal_numas, $literal_threads) cannot be applied on this Julia process. $reason Ignoring.") - return (0, 0) - elseif reason != "" - addLog("machine", "Specified thread arrangement $arrgmt -> literalized to ($literal_numas, $literal_threads) cannot be applied on this Julia process. $reason Ignoring.") - return (0, 0) - end return (literal_numas, literal_threads) end # Autovectorized -function validateArrangement(arrgmts::Vector)::Bool - return all(validateArrangement.(arrgmts)) +function validateArrangement(arrgmts::Vector, report::Function = throwParseError!)::Bool + if isempty(arrgmts) + report("an empty list has no arrangement to use.") + return false + end + # Each one is checked, so every invalid one is reported + return all([validateArrangement(arrgmt, report) for arrgmt in arrgmts]) end -function validateArrangement(arrgmts::Vector{N})::Bool where {N<:Integer} - return all(0 .< arrgmts) +function validateArrangement(arrgmts::Vector{N}, report::Function = throwParseError!)::Bool where {N<:Integer} + invalid = filter(id -> id <= 0, arrgmts) + if !isempty(invalid) + report("$arrgmts, the thread ids of a manual pinning must be positive integers, got $(join(invalid, ", ")).") + return false + end + return true end """ - validateArrangement(arrgmt::ArrangementSpec) -> Bool + validateArrangement(arrgmt, report = throwParseError!) -> Bool -Validates the arrangement syntax. +Validates the arrangement syntax, an arrangement (see ArrangementSpec), a list of them, or a list of thread ids for a +manual pinning. -Throws an error if the arrangement is badly specified. +If the arrangement is badly specified the reason is reported with `report` and false is returned. """ -function validateArrangement(arrgmt::ArrangementSpec)::Bool +function validateArrangement(arrgmt::ArrangementSpec, report::Function = throwParseError!)::Bool if arrgmt isa Symbol return if arrgmt == :single true @@ -359,40 +358,35 @@ function validateArrangement(arrgmt::ArrangementSpec)::Bool elseif arrgmt == :all true else - throwParseError!("Invalid thread arrangement: symbol `$arrgmt` is unrecognised. " * - "Must be one of [:single, :numa, :all] or a tuple — see ArrangementSpec docs.") + report("symbol $(repr(arrgmt)) is unrecognised, the symbols are :single, :numa and :all.") false end end if length(arrgmt) != 2 - throwParseError!("Invalid thread arrangement: $arrgmt has $(length(arrgmt)) element(s); " * - "expected exactly 2 (#numas, #threads_per_numa).") + report("$arrgmt has $(length(arrgmt)) element(s), expected exactly 2 (#numas, #threads_per_numa).") return false end numa_spec, thread_spec = arrgmt if numa_spec isa Rational if !(0 < numa_spec <= 1) - throwParseError!("Invalid thread arrangement: $arrgmt, NUMA ratio $numa_spec is out of range; " * - "must satisfy 0 < ratio ≤ 1.") + report("$arrgmt, NUMA ratio $numa_spec is out of range, it must satisfy 0 < ratio ≤ 1.") return false end else if numa_spec <= 0 - throwParseError!("Invalid thread arrangement: $arrgmt, if #numa is and integer, it shall be positive, got $numa_spec.") + report("$arrgmt, #numas must be a positive integer, got $numa_spec.") return false end end if thread_spec isa Rational if !(0 < thread_spec <= 1) - throwParseError!("Invalid thread arrangement: $arrgmt, thread ratio $thread_spec is out of range; " * - "must satisfy 0 < ratio ≤ 1.") + report("$arrgmt, thread ratio $thread_spec is out of range, it must satisfy 0 < ratio ≤ 1.") return false end else if thread_spec <= 0 - throwParseError!("Invalid thread arrangement: $arrgmt, #threads_per_numa must be a positive integer, " * - "got $thread_spec.") + report("$arrgmt, #threads_per_numa must be a positive integer, got $thread_spec.") return false end end @@ -400,6 +394,80 @@ function validateArrangement(arrgmt::ArrangementSpec)::Bool return true end +# Any other value, e.g. a tuple of a different length or with elements of another type +function validateArrangement(arrgmt, report::Function = throwParseError!)::Bool + if arrgmt isa Tuple && length(arrgmt) != 2 + report("$(repr(arrgmt)) has $(length(arrgmt)) element(s), expected exactly 2 (#numas, #threads_per_numa).") + elseif arrgmt isa Tuple + invalid = [e for e in arrgmt if !(e isa Union{Integer,Rational{Int64}})] + report("$(repr(arrgmt)), the elements of an arrangement must be integers or ratios of integers, got " * + join(["$(repr(e)) ($(typeof(e)))" for e in invalid], ", ") * ".") + else + report("$(repr(arrgmt)) ($(typeof(arrgmt))) is not a thread arrangement.") + end + return false +end + +# The arrangements a thread setting of the configuration names, see arrangementFromConfig +CONFIG_ARRANGEMENT_NAMES = Dict{String,ArrangementSpec}("single" => (1, 1), "numa" => (1, 1 // 1), "all" => (1 // 1, 1 // 1)) + +# How a suite gets its thread setting, and what it can be, named in its errors +THREAD_SETTING_RULE = "A suite has a single thread setting: each of general.numas and general.threads_per_numa takes its " * + "value from the last configuration call that sets it, even in an included recipe, and a " * + "@perftest_threads in the recipe takes priority over both." +CONFIG_THREADS_OPTIONS = "general.numas and general.threads_per_numa are either both the same name of an arrangement: " * + "\"single\" (1 thread), \"numa\" (every thread of 1 NUMA domain) or \"all\" (every thread of " * + "every NUMA domain); or both numbers (#numas, #threads_per_numa), each one an integer n ≥ 1 or a " * + "float in (0, 1], the ratio of the available ones (e.g. 0.5 for half of them)." + +# Why `value`, of the configuration key general.`key`, cannot be part of a thread setting, nothing if it can +function configThreadValueProblem(key::AbstractString, value)::Union{String,Nothing} + name = "general.$key = $(repr(value))" + return if value isa AbstractString + haskey(CONFIG_ARRANGEMENT_NAMES, value) ? nothing : "$name is not the name of an arrangement" + elseif value isa Bool + # A Bool is an Integer in Julia + "$name is a Bool, neither a number nor the name of an arrangement" + elseif value isa Integer + value >= 1 ? nothing : "$name is an integer below 1" + elseif value isa Float64 + 0 < value <= 1 ? nothing : "$name is a float outside (0, 1]" + else + "$name ($(typeof(value))) is neither a number nor the name of an arrangement" + end +end + +""" + arrangementFromConfig(numas, threads_per_numa) -> Union{ArrangementSpec,Vector{String}} + +Arrangement (see ArrangementSpec) given by a thread setting, the values of the configuration keys general.numas and +general.threads_per_numa. A string names a whole arrangement and is given in both keys: "single" is (1, 1), "numa" is +(1, 1//1) and "all" is (1//1, 1//1). Otherwise both are numbers, the arrangement (numas, threads_per_numa) where an +integer n ≥ 1 stays n and a float in (0, 1] is a ratio of what is available (e.g. 0.5 is 1//2, 1.0 is 1//1). + +Anything else is not interpreted, the reasons it is invalid are returned instead, see CONFIG_THREADS_OPTIONS. +""" +function arrangementFromConfig(numas, threads_per_numa)::Union{ArrangementSpec,Vector{String}} + problems = String[] + for (key, value) in (("numas", numas), ("threads_per_numa", threads_per_numa)) + problem = configThreadValueProblem(key, value) + problem === nothing || push!(problems, problem) + end + isempty(problems) || return problems + + named = (numas isa AbstractString, threads_per_numa isa AbstractString) + return if all(named) + numas == threads_per_numa ? CONFIG_ARRANGEMENT_NAMES[numas] : + ["general.numas = $(repr(numas)) and general.threads_per_numa = $(repr(threads_per_numa)) name different arrangements, a name is given in both keys"] + elseif any(named) + name, number = named[1] ? (("numas", numas), ("threads_per_numa", threads_per_numa)) : (("threads_per_numa", threads_per_numa), ("numas", numas)) + ["general.$(name[1]) = $(repr(name[2])) names an arrangement but general.$(number[1]) = $(repr(number[2])) is a number, a name is given in both keys"] + else + # A ratio is a Rational{Int64}, see ArrangementSpec + Tuple(value isa Float64 ? rationalize(Int, value) : value for value in (numas, threads_per_numa)) + end +end + function isExecutableArrangement(arrgmts::Vector{N}) :: Union{Vector{N}, Nothing} where {N <: Integer} return validateArrangement(arrgmts) ? arrgmts : nothing end @@ -440,7 +508,20 @@ with the elements being the cores to allocate. function enforceThreadArrangement(arrgmt::Tuple{Integer,Integer})::Bool n_numas, n_threads = arrgmt total_needed = n_numas * n_threads - + reason = "" + # Check Julia thread count + if Threads.nthreads() < total_needed + reason *= "Not enough threads on the interpreter." + addLog("machine", "Specified thread arrangement $arrgmt -> literalized to ($n_numas, $n_threads) cannot be applied on this Julia process. $reason Ignoring.") + return (0, 0) + elseif Threads.nthreads() > total_needed + reason *= "Too many threads on the interpreter ($(Threads.nthreads()) > $total_needed)." + addLog("machine", "Specified thread arrangement $arrgmt -> literalized to ($n_numas, $n_threads) cannot be applied on this Julia process. $reason Ignoring.") + return (0, 0) + elseif reason != "" + addLog("machine", "Specified thread arrangement $arrgmt -> literalized to ($n_numas, $n_threads) cannot be applied on this Julia process. $reason Ignoring.") + return (0, 0) + end # Check Julia thread count if Threads.nthreads() < total_needed @warn "enforceThreadArrangement: need $total_needed Julia thread(s) " * diff --git a/src/execution/macros/configuration.jl b/src/execution/macros/configuration.jl index 9f05143..520c8d0 100644 --- a/src/execution/macros/configuration.jl +++ b/src/execution/macros/configuration.jl @@ -12,8 +12,14 @@ Captures a set of configuration parameters that will override the default config # Recursive transformation: This macro will set the new configuration keys for the current file and any other included files. If the included files have the macro as well, those macros will override the configuration locally for each file. +# Validation: +The keys are checked when the recipe is transformed. A section or key that does not exist (the error lists the existing ones), a key with an incorrect type, a key that is used before the recipe is read (`MPI.enabled`, set it in the configuration file or with the config argument of runperftests or PerfTest.transform instead) and invalid TOML are reported as parse errors, so no suite is generated. The valid keys of the macro still apply to the rest of the transform, so its other errors are reported as well. + +# Interpolation: +Values can be interpolated inside TOML strings, e.g. `dedicated_reference_file = 'ref_\$(gethostname()).JLD2'`. Those keys take their value when the generated suite is executed. An interpolated value is always a string, so only keys that take a String can be interpolated. + # Arguments - - A String, with the TOML declaration of configuration keys + - A string literal, with the TOML declaration of configuration keys. It is read when the recipe is transformed, so a variable or any other expression is reported as a parse error. # Example diff --git a/src/execution/macros/customs.jl b/src/execution/macros/customs.jl index 21bb531..ff4ab3e 100644 --- a/src/execution/macros/customs.jl +++ b/src/execution/macros/customs.jl @@ -10,6 +10,11 @@ define_metric_validation = defineMacroParams([ String, true ), + # Symbol that identifies the metric, Symbol(name) when absent, see metricSymbol + MacroParameter( + :symbol, + metricID() + ), MacroParameter( Symbol(""), ExtendedExpr, @@ -23,16 +28,27 @@ This macro is used to define a new custom metric. The metric result can be used # Arguments - `name` : the name of the metric for identification purposes. - `units` : the unit space that the metric values will be in. + - `symbol` : (optional) the symbol other formulas and macros (e.g `@regression metrics=...`) use to refer to the metric, a Symbol or a String. Defaults to the name as a symbol (name="example" -> :example). - formula block : an expression that returns a single value, which would be the metric value. The formula can have any julia expression inside and additionally some special symbols are supported. The formula may be evaluated several times, so its applied to every target in every test set or just once, if the formula is defined inside a test set, which makes it only applicable to it. NOTE: If there is the need of referring to a variable on a formula block, it first needs to be exported using the macro @export_vars, otherwise an error will occur. # Special symbols: - `:median_time` : will be substituted by the median time the target took to execute in the benchmark. - `:minimum_time`: will be substituted by the minimum time the target took to execute in the benchmark. - `:ret_value` : will be substituted by the return value of the target. - - `:autoflop`: will be substituted by the FLOP count the target. + - `:autoflop`: not supported, automatic flop counting is outdated (it is always 0), a formula that uses it is reported as a parse error. Write the flop count of the target explicitly instead. - `:printed_output` : will be substituted by the standard output stream of the target. - `:iterator` : will be substituted by the current iterator value in a loop test set. - - Any symbol representing a custom metric or benchmark (e.g metric with name="example" -> :example) + - Any symbol representing a custom metric or benchmark, its `symbol` if given, otherwise its name as a symbol (e.g metric with symbol=:ex -> :ex, metric with name="example" and no symbol -> :example) + +# Example: + + @define_metric name="Effective bandwidth" units="GB/s" symbol=:bw begin + 1e-9 * 1000 / :median_time + end + @define_metric name="Bandwidth per core" units="GB/s" begin + :bw / 8 + end + @regression metrics=:bw """ macro define_metric(args...) return :( @@ -82,16 +98,17 @@ auxiliary_metric_validation = define_metric_validation # Arguments - `name` : the name of the metric for identification purposes. - `units` : the unit space that the metric values will be in. + - `symbol` : (optional) the symbol that identifies the metric, a Symbol or a String. Defaults to the name as a symbol (name="example" -> :example). - formula block : an expression that returns a single value, which would be the metric value. The formula can have any julia expression inside and additionally some special symbols are supported. The formula may be evaluated several times, so its applied to every target in every test set or just once, if the formula is defined inside a test set, which makes it only applicable to it. # Special symbols: - `:median_time` : will be substituted by the median time the target took to execute in the benchmark. - `:minimum_time`: will be substituted by the minimum time the target took to execute in the benchmark. - `:ret_value` : will be substituted by the return value of the target. - - `:autoflop`: will be substituted by the FLOP count the target. + - `:autoflop`: not supported, automatic flop counting is outdated (it is always 0), a formula that uses it is reported as a parse error. Write the flop count of the target explicitly instead. - `:printed_output` : will be substituted by the standard output stream of the target. - `:iterator` : will be substituted by the current iterator value in a loop test set. - - Any symbol representing a custom metric or benchmark (e.g metric with name="example" -> :example) + - Any symbol representing a custom metric or benchmark, its `symbol` if given, otherwise its name as a symbol (e.g metric with symbol=:ex -> :ex, metric with name="example" and no symbol -> :example) """ macro auxiliary_metric(formula, name, units) return :( @@ -137,10 +154,10 @@ This macro is used to define the memory bandwidth of a target in order to execut - `:median_time` : will be substituted by the median time the target took to execute in the benchmark. - `:minimum_time`: will be substituted by the minimum time the target took to execute in the benchmark. - `:ret_value` : will be substituted by the return value of the target. - - `:autoflop`: will be substituted by the FLOP count the target. + - `:autoflop`: not supported, automatic flop counting is outdated (it is always 0), a formula that uses it is reported as a parse error. Write the flop count of the target explicitly instead. - `:printed_output` : will be substituted by the standard output stream of the target. - `:iterator` : will be substituted by the current iterator value in a loop test set. - - Any symbol representing a custom metric or benchmark (e.g metric with name="example" -> :example) + - Any symbol representing a custom metric or benchmark, its `symbol` if given, otherwise its name as a symbol (e.g metric with symbol=:ex -> :ex, metric with name="example" and no symbol -> :example) # Example: @@ -171,29 +188,15 @@ macro export_vars(symbols...) end -define_benchmark_validation = defineMacroParams([ - MacroParameter( - :name, - String, - true - ), - MacroParameter( - :units, - String, - true - ), - MacroParameter( - Symbol(""), - ExtendedExpr, - true - ) -]) +# Same parameters +define_benchmark_validation = define_metric_validation """ Defines a customized reference to compare against. Must be always defined inside a testset. # Arguments - - name : (string) an identifier for the custom benchmark, methodologies that use it will refer too it using this name. + - name : (string) an identifier for the custom benchmark, methodologies that use it will refer to it using this name as a symbol, unless `symbol` is given. - units: (string) units of the reference value. + - symbol: (optional, symbol or string) the symbol formulas and methodologies (e.g `custom_benchmark=...`) use to refer to the benchmark. Defaults to the name as a symbol. - formula: an expression to calculate the reference value. """ macro define_benchmark(args...) diff --git a/src/execution/macros/perfcompare.jl b/src/execution/macros/perfcompare.jl index 0695bf0..8fd7437 100644 --- a/src/execution/macros/perfcompare.jl +++ b/src/execution/macros/perfcompare.jl @@ -4,7 +4,11 @@ define_perfcmp_validation = defineMacroParams([ MacroParameter( Symbol(""), Union{ExtendedExpr} - ) + ), + MacroParameter(:showvar, + Bool, + false, #default + false), ]) """ This macro is used to manually declare performance test conditions. @@ -16,11 +20,14 @@ This macro is used to manually declare performance test conditions. - `:median_time` : will be substituted by the median time the target took to execute in the benchmark. - `:minimum_time`: will be substituted by the minimum time the target took to execute in the benchmark. - `:ret_value` : will be substituted by the return value of the target. - - `:autoflop`: will be substituted by the FLOP count the target. + - `:autoflop`: not supported, automatic flop counting is outdated (it is always 0), a formula that uses it is reported as a parse error. Write the flop count of the target explicitly instead. - `:printed_output` : will be substituted by the standard output stream of the target. - `:iterator` : will be substituted by the current iterator value in a loop test set. - Any symbol representing a custom metric or benchmark (e.g metric with name="example" -> :example) +# Keyword arguments + - showvar: when true, print a "(± X)" standard-error-of-the-mean interval alongside any auxiliary metrics in scope. Does not affect the printed TRUE/FALSE assertion result itself. Ignored (no interval shown) whenever the underlying sample count is below 30. + # Example: ```julia diff --git a/src/execution/macros/perftest.jl b/src/execution/macros/perftest.jl index 7423121..478ddf2 100644 --- a/src/execution/macros/perftest.jl +++ b/src/execution/macros/perftest.jl @@ -28,7 +28,7 @@ If the macro is evaluated it does not modify the target at all. The effects of t This macro is sensitive to context since other adjacent macros can change how the target will be evaluated. ```julia -@perftest expression [parameters...] +@perftest [parameters...] expression ``` Run a performance test on a given target expression. @@ -71,27 +71,36 @@ You can pass the following keyword arguments to configure the execution process: ## With setup and teardown +Keyword parameters must come *before* the target expression, which is +always the last argument: + ```julia - @perftest sort!(data) setup=(data=rand(100)) teardown=(data=nothing) + @perftest setup=(data=rand(100)) teardown=(data=nothing) sort!(data) ``` ## With custom parameters ```julia # Run with a 3-second time budget - @perftest sin(x) setup=(x=rand()) seconds=3 + @perftest setup=(x=rand()) seconds=3 sin(x) # Limit to 100 samples with 10 evaluations each - @perftest myfunction(data) samples=100 evals=10 + @perftest samples=100 evals=10 myfunction(data) # Disable garbage collection before each sample - @perftest allocating_function() gcsample=false gctrial=false + @perftest gcsample=false gctrial=false allocating_function() ``` # See Also - [BenchmarkTools.jl Documentation](https://juliaci.github.io/BenchmarkTools.jl/dev/) for more details on the underlying `@benchmark` macro and its parameters. """ -macro perftest(anything) - return esc(anything) +macro perftest(args...) + isempty(args) && error("@perftest requires a target expression") + target = args[end] + for kw in args[1:end-1] + (kw isa Expr && kw.head === :(=)) || + error("@perftest: expected a `key=value` parameter before the target expression, got `$kw`") + end + return esc(target) end diff --git a/src/execution/macros/regression.jl b/src/execution/macros/regression.jl index bb6cf0a..aae3782 100644 --- a/src/execution/macros/regression.jl +++ b/src/execution/macros/regression.jl @@ -5,32 +5,44 @@ define_regression_validation = defineMacroParams([ Union{Bool,Vector{Bool}}, true, false), + # No default, a missing threshold comes from regression.default_threshold, see defaultRegressionThresholds MacroParameter(:threshold, - Union{Float64,Vector{Float64}}, - (x) -> x isa Float64 ? 0.0 <= x : all(0.0 <= t for t in x), - 0.9, #default - false), + Union{Float64,Vector{Float64}}; + validation_function = (x) -> x isa Float64 ? 0.0 <= x : all(0.0 <= t for t in x), + mandatory = false), MacroParameter(:metrics, Union{metricID(),Vector{metricID()}}, always_true, [:median_time], #default false), + MacroParameter(:showvar, + Bool, + false, #default + false), ]) """ This macro is used to define regression tests with a customized configuration. Redefining the macro in the same testset will overwrite the previous configuration. +A test compares the ratio new/reference of each metric, between the new value and the one of the reference execution, with its threshold. + # Arguments - - low_is_bad: whether a lower value of the metric is considered a failure (e.g. for time measurements) or a success (e.g. for throughput measurements). It can be a single boolean that applies to all metrics or a vector of booleans that applies to each metric separately. - - threshold : the minimum ratio over that is allowed to pass the test (e.g 0.9 means that the test is a success if the new metric is at least 90% of the old). It can be a single float that applies to all metrics or a vector of floats that applies to each metric separately. + - low_is_bad: whether a lower value of the metric is bad, `true` by default. With `low_is_bad=true` (e.g. for a throughput) the test passes if the ratio is above the threshold, with `low_is_bad=false` (e.g. for a time) if it is below. It can be a single boolean that applies to all metrics or a vector of booleans that applies to each metric separately. + - threshold : the ratio new/reference the metric must stay above (`low_is_bad=true`, e.g. 0.9 fails if the new value is 90% of the reference or less) or below (`low_is_bad=false`, e.g. 1.1 fails if the new value is 110% of the reference or more). It can be a single float that applies to all metrics or a vector of floats that applies to each metric separately. + Without it, each metric takes its threshold from the configuration key `regression.default_threshold` (1.1 by default): the value itself for a metric with `low_is_bad=false`, and 2 − that value for one with `low_is_bad=true` (1.1 gives 0.9), so the default tolerates a 10% change in the bad direction either way. A `regression.default_threshold` of 2 or more leaves no threshold for a metric with `low_is_bad=true`, it is reported as a parse error. - metrics: track regression in the metrics whose names are passed as argument, it accepts a single string or a vector of strings. Non-existent metrics are ignored. + - showvar: when true, print a "(± X)" standard-error-of-the-mean interval alongside the ratio metric and any auxiliary metrics in scope. Ignored (no interval shown) whenever the underlying sample count is below 30. # Examples: ```julia - # Tests will fail if median time is lower than 90% of the reference value - @regression threshold=0.9 low_is_bad=false metrics=:median_time + # Tests will fail if the median time is 110% of the reference value or more + @regression threshold=1.1 low_is_bad=false metrics=:median_time + + # Tests will fail if the metric results are 90% of the reference value or less + @regression threshold=0.9 low_is_bad=true metrics=[:custom_metric1, :custom_metric2] - # Tests will fail if metric results are higher than 110% of the reference value - @regression threshold=1.1 low_is_bad=true metrics=[:custom_metric1, :custom_metric2] + # Without threshold, with the default regression.default_threshold = 1.1: the median time fails at 110% of the + # reference or more (threshold 1.1), custom_metric1 at 90% or less (threshold 2 − 1.1 = 0.9) + @regression low_is_bad=[false, true] metrics=[:median_time, :custom_metric1] ``` """ macro regression(args...) diff --git a/src/execution/macros/roofline.jl b/src/execution/macros/roofline.jl index 15aafc2..6505e5e 100644 --- a/src/execution/macros/roofline.jl +++ b/src/execution/macros/roofline.jl @@ -57,7 +57,7 @@ This macro enables roofline modelling, if put just before a target declaration ( - `cpu_peak` : a manual input value for the maximum attainable FLOPS, this will override the empirical runtime benchmark - `membw_peak` : a manual input value for the maximum memory bandwith, this will override the empirical runtime benchmark - `target_opint` : a desired operational intensity for the target, this will turn operational intensity into a test metric - - `actual_flops`: another formula that defines the actual performance of the test. + - `actual_flops`: the flop count of the target, a number or a formula (as the operational intensity one), e.g. `actual_flops = 2 * N`. The attained flops of the test are `actual_flops / :median_time`. Give it to test the attained flops: automatic flop counting is outdated and not supported, so a `@roofline` without `actual_flops` while the configuration key `general.autoflops` is true is reported as a parse error. - `target_ratio` : the acceptable ratio between the actual performance and the projected performance from the roofline, this will turn actual performance into a test metric. - `mem_benchmark`: which benchmark to use for the roofline, the default is the Shoenauer DAXPY (:MEM_BENCH_DAXPY), custom benchmarks are supported. Other benchmarks: [:MEM_STREAM_COPY,:MEM_STREAM_ADD, :MEM_BENCH_STRIAD, :MEM_BENCH_SDAXPY] @@ -65,7 +65,7 @@ This macro enables roofline modelling, if put just before a target declaration ( - `:median_time` : will be substituted by the median time the target took to execute in the benchmark. - `:minimum_time`: will be substituted by the minimum time the target took to execute in the benchmark. - `:ret_value` : will be substituted by the return value of the target. - - `:autoflop`: will be substituted by the FLOP count the target. + - `:autoflop`: not supported, automatic flop counting is outdated (it is always 0), a formula that uses it, `actual_flops = :autoflop` included, is reported as a parse error. Give the flop count with `actual_flops` instead. - `:printed_output` : will be substituted by the standard output stream of the target. - `:iterator` : will be substituted by the current iterator value in a loop test set. Any formula block specified in this macro supports these symbols. @@ -73,9 +73,9 @@ Any formula block specified in this macro supports these symbols. # Example ```julia - @roofline actual_flops=:autoflop target_ratio=0.05 begin - mem = ((:iterator + 1) * :iterator) - :autoflop / mem + # Inner product of two vectors of N Float64 values: 2N flops over 16N bytes + @roofline actual_flops = 2 * N target_ratio = 0.05 begin + (2 * N) / (16 * N) end ``` diff --git a/src/execution/macros/topology.jl b/src/execution/macros/topology.jl index c27ae5b..2af135d 100644 --- a/src/execution/macros/topology.jl +++ b/src/execution/macros/topology.jl @@ -1,11 +1,46 @@ threads_validation = defineMacroParams([ + # Of any type, so parseThreadsMacro reports an invalid one along with the arrangements it can be (see validateThreadsArgument) MacroParameter(Symbol(""), - ExtendedExpr, - validation_function= x -> Topology.validateArrangement(eval(x)), + Any, mandatory= true) ]) + +# What the argument of @perftest_threads can be, named in its parse errors +THREADS_OPTIONS = "A thread arrangement is :single, :numa, :all, a tuple (#numas, #threads_per_numa) whose elements are " * + "positive integers or ratios of integers in (0, 1] (e.g. (1, 1//2)), or a list of them. " * + "A list of positive integers is a manual pinning to those thread ids (e.g. [1, 2])." + +""" +Whether `x`, the argument of a @perftest_threads, is a literal, so its value is known when the recipe is transformed: a +number, a string, a quoted symbol (e.g. `:numa`), a ratio of integers (e.g. `1//2`), or a tuple or a list of them. +""" +isThreadsLiteral(x::Union{Number,AbstractString}) = true +isThreadsLiteral(x::QuoteNode) = x.value isa Symbol +isThreadsLiteral(x::Expr) = x.head in (:tuple, :vect) ? all(isThreadsLiteral, x.args) : + x.head === :call && length(x.args) == 3 && x.args[1] === :// && all(a -> a isa Integer, x.args[2:3]) +isThreadsLiteral(x) = false + +""" +Check `x`, the argument of a @perftest_threads, each reason it is invalid is reported with `report`. Returns whether it +is valid. +""" +function validateThreadsArgument(x, report::Function)::Bool + if !isThreadsLiteral(x) + report("`$x` is not a literal, the arrangement is read when the recipe is transformed so a variable or any other expression is not supported.") + return false + end + # Only literals, see isThreadsLiteral, as the generated suite evaluates them + value = try + eval(x) + catch e + report("`$x` cannot be evaluated, $(sprint(showerror, e)).") + return false + end + return Topology.validateArrangement(value, report) +end + """ This macro can be used to specify one or more thread pinning configurations for the performance test suite. Not calling this macro on the recipe leaves the threads unpinned. @@ -22,6 +57,14 @@ threads_validation = defineMacroParams([ Alternatively a list of integers can be passed which will be interpreted as a manual pinning. + The argument must be a literal, as it is read when the recipe is transformed: a variable or any other expression, + as well as an invalid arrangement, is reported as a parse error. + + The arrangement is resolved on the machine that executes the suite, e.g. :numa takes the size of a NUMA domain of that machine. + + It takes priority over the thread setting of the configuration (general.numas and general.threads_per_numa) for + the number of threads runperftests launches the suite with. + [!] As of now, the pinning is not MPI aware, (this will come in PerfTest v1.2.4) in MPI cases use the manual pinning, with the list of integers. [!] This is a feature in development, more comprehensive features will be built over this later on (1.2.4). """ diff --git a/src/execution/printing.jl b/src/execution/printing.jl index c698855..d6e71d0 100644 --- a/src/execution/printing.jl +++ b/src/execution/printing.jl @@ -157,6 +157,9 @@ function printMetric(metric :: Metric_Result, test:: Metric_Test, tab::Int) else p_yellow(@sprintf("%.3f", metric.value)) end + if test.showvar && metric.variance !== nothing + print(@sprintf(" (± %.3f)", metric.variance)) + end println(" [" * metric.units * "]" * " "^20) end @@ -172,7 +175,11 @@ This function is used to dump metric information regading auxiliar metrics, whic """ function auxiliarMetricPrint(metric :: Metric_Result, tab::Int) println(" "^tab * "Metric: " * metric.name * " [" * metric.magnitude_prefix * metric.units * "]") - println(" " ^ tab * " = ", metric.value) + if metric.variance !== nothing + println(" " ^ tab * " = ", metric.value, @sprintf(" (± %.3f)", metric.variance)) + else + println(" " ^ tab * " = ", metric.value) + end println("") end diff --git a/src/execution/structs.jl b/src/execution/structs.jl index ca03200..1350c42 100644 --- a/src/execution/structs.jl +++ b/src/execution/structs.jl @@ -31,11 +31,29 @@ struct Metric_Result{N} magnitude_mult::Number # Additional data for MPI mpi :: Union{Nothing, MPI_MetricInfo} + # Standard error of the mean, in the same (unscaled) units as `value`; `nothing` when not + # available or not requested via showvar. See SampledValue (execution/variance.jl). + variance :: Union{Nothing, N} + # Raw sample count backing `variance`; typemax(Int) sentinel when not applicable. + n :: Int end -function newMetricResult(::Type{<:NormalMode};name, units, value, auxiliary = false, magnitude_prefix = "", magnitude_mult = 1, reduct="") +# Single choke point: every newMetricResult method routes a possibly-SampledValue `value` +# through here, so the showvar/n>=MIN_VARIANCE_SAMPLES gate lives in exactly one place. +_unwrapSampledValue(value) = value isa SampledValue ? (value.value, value.sem, value.n) : (value, nothing, typemax(Int)) +_gatedVariance(sem, n, showvar::Bool) = (sem === nothing || !showvar || n < MIN_VARIANCE_SAMPLES || !isfinite(sem)) ? nothing : sem - return Metric_Result(name,units,value,auxiliary, magnitude_prefix, magnitude_mult, nothing) +""" +Reconstructs a SampledValue from a Metric_Result that carries a non-nothing `variance`, +so arithmetic on an already-built Metric_Result (e.g. inside a formula referencing a custom +metric) keeps propagating variance. Returns the plain `value` when no variance is attached. +""" +metricSampledValue(m::Metric_Result) = m.variance === nothing ? m.value : SampledValue(m.value, m.variance, m.n) + +function newMetricResult(::Type{<:NormalMode};name, units, value, auxiliary = false, magnitude_prefix = "", magnitude_mult = 1, reduct="", showvar = false) + + val, sem, n = _unwrapSampledValue(value) + return Metric_Result(name,units,val,auxiliary, magnitude_prefix, magnitude_mult, nothing, _gatedVariance(sem, n, showvar), n) end """ @@ -50,6 +68,8 @@ This struct is used in the test suite to save a metric test result and its assoc # Additional metric X methodology data custom_plotting::Vector{Symbol} full_print::Bool + # Whether printMetric should append the metric's variance interval, if it has one. + showvar::Bool = false end @@ -68,6 +88,9 @@ This struct is used in the test suite to save a methodology result, which in tur end +abstract type ExtensionData end +struct NoExtensionData <: ExtensionData end + """ NOTE: SOME METRICS ARE REPEATED IN HERE AND INSIDE A METRIC RESULT, this redundancy is tolerated for now, the copy inside the methodology result might be substituted by a reference in the future. @@ -78,12 +101,19 @@ struct Test_Result metrics :: Dict{Symbol,Metric_Result} auxiliar :: Dict{Symbol,Metric_Result} methodology_results :: Vector{Methodology_Result} + extensions :: Vector{ExtensionData} Test_Result(name) = new(name, Dict{Symbol,Metric_Result}(), Dict{Symbol,Metric_Result}(), Dict{Symbol,Metric_Result}(), - Methodology_Result[]) + Methodology_Result[], ExtensionData[]) + Test_Result(name, extensions) = new(name, + Dict{Symbol,Metric_Result}(), + Dict{Symbol,Metric_Result}(), + Dict{Symbol,Metric_Result}(), + Methodology_Result[], + extensions) end diff --git a/src/execution/testset.jl b/src/execution/testset.jl index 7fbfb76..901db21 100644 --- a/src/execution/testset.jl +++ b/src/execution/testset.jl @@ -104,6 +104,12 @@ if isdefined(Test, :TestCounts) "\n" ) print(" "^get_testset_depth() * "AT: $(ts.description)\n") + for outcome in ts.results + if outcome isa Error + print("ERRORED:\n") + print(test_result) + end + end for methodology in test_result.methodology_results printMethodology(methodology, get_testset_depth(), Configuration.CONFIG["general"]["plotting"]) end @@ -238,6 +244,9 @@ function testsSucceeded(ts::PerfTestSet) return true end +# A top level `@testset ... for` gives a vector with the testset of each iteration +testsSucceeded(tss::AbstractVector) = all(testsSucceeded, tss) + function get_test_errors(ts::PerfTestSet) errors = Error[] for t in ts.results @@ -251,10 +260,26 @@ end +function _sample_median(v::AbstractVector{<:Real}) + s = sort(v) + n = length(s) + return iseven(n) ? (s[n ÷ 2] + s[n ÷ 2 + 1]) / 2 : s[(n + 1) ÷ 2] +end + function buildPrimitiveMetrics!(::Type{NormalMode}, ts::PerfTestSet, test_result::Test_Result) # Get testset - test_result.primitives[:median_time] = median(ts.benchmarks[test_result.name]).time / 1e9 - test_result.primitives[:min_time] = minimum(ts.benchmarks[test_result.name]).time / 1e9 + trial = ts.benchmarks[test_result.name] + times_s = trial.times ./ 1e9 + n = length(times_s) + med = _sample_median(times_s) + # median_time is an accumulation of BenchmarkTools' raw per-trial samples; retain a + # companion standard-error-of-the-mean via SampledValue whenever there are enough of them + # (see MIN_VARIANCE_SAMPLES / execution/variance.jl). min_time deliberately stays a plain + # scalar: std/sqrt(n) is the SEM of a mean/median, not a statistically meaningful spread for + # a minimum. + test_result.primitives[:median_time] = n >= MIN_VARIANCE_SAMPLES ? + SampledValue(med, std(times_s)/sqrt(n), n) : med + test_result.primitives[:min_time] = minimum(times_s) test_result.primitives[:iterator] = ts.iterator end @@ -277,7 +302,8 @@ function extractTestResults(ts::PerfTestSet)::Dict{String,Union{Dict,Test_Result for t in ts.results if isa(t, Test.Result) else - dict[t.description] = extractTestResults(t) + key = (t isa PerfTestSet && t.iterator !== nothing) ? t.description * "_" * string(t.iterator) : t.description + dict[key] = extractTestResults(t) end end for (k, v) in ts.test_results diff --git a/src/execution/units.jl b/src/execution/units.jl index e1a3adf..43ba3a9 100644 --- a/src/execution/units.jl +++ b/src/execution/units.jl @@ -10,6 +10,13 @@ magnitude_prefixes = Dict( ) # Used to directly turn a result into a convenient magnitude order +# +# `showvar=true` is passed to every newMetricResult call below deliberately: this function +# rescales an *already-built* Metric_Result, it isn't making a fresh showvar decision. If `m` +# never carried a variance (the common case, since newMetricResult defaults to showvar=false), +# metricSampledValue(m) returns a bare value and showvar=true here has no effect. If `m` does +# carry one, that means whoever built it already opted in — this just carries that decision +# through the rescale rather than silently dropping it. function magnitudeAdjust(m::Metric_Result)::Metric_Result # Check for valid number, do nothing if not @@ -24,10 +31,11 @@ function magnitudeAdjust(m::Metric_Result)::Metric_Result mode, name = m.name, units= m.units, - value = m.value / magnitude_order, + value = metricSampledValue(m) / magnitude_order, auxiliary = m.auxiliary, magnitude_prefix=prefix, - magnitude_mult=magnitude_order + magnitude_mult=magnitude_order, + showvar=true ) end end @@ -38,20 +46,22 @@ function magnitudeAdjust(m::Metric_Result)::Metric_Result mode, name = m.name, units= m.units, - value = m.value / 1e9, + value = metricSampledValue(m) / 1e9, auxiliary = m.auxiliary, magnitude_prefix="G", - magnitude_mult=1e9 + magnitude_mult=1e9, + showvar=true ) else return newMetricResult( mode, name = m.name, units= m.units, - value = m.value * 1e9, + value = metricSampledValue(m) * 1e9, auxiliary = m.auxiliary, magnitude_prefix="n", - magnitude_mult=1e-9 + magnitude_mult=1e-9, + showvar=true ) end end @@ -64,9 +74,10 @@ function absoluteMagnitude(m::Metric_Result)::Metric_Result mode, name = m.name, units= m.units, - value = m.value * m.magnitude_mult, + value = metricSampledValue(m) * m.magnitude_mult, auxiliary = m.auxiliary, magnitude_prefix="", - magnitude_mult=1 + magnitude_mult=1, + showvar=true ) end diff --git a/src/execution/variance.jl b/src/execution/variance.jl new file mode 100644 index 0000000..d0cf852 --- /dev/null +++ b/src/execution/variance.jl @@ -0,0 +1,87 @@ + +# `std` is brought into scope via `using BenchmarkTools` at the top of src/PerfTest.jl +# (BenchmarkTools re-exports it) — Statistics itself is not a declared dependency. + +""" +Minimum number of underlying raw samples required before a computed variance is +shown to the user (rather than merely computed and gated off). Below this, PerfTest +treats the population as too small for the standard-error estimate to be meaningful. +""" +const MIN_VARIANCE_SAMPLES = 30 + +""" +A scalar value paired with the standard error of the mean (`sem`) and the raw +sample count (`n`) that backed it. Arithmetic on `SampledValue`s propagates `sem` +through ordinary Julia operator dispatch (absolute errors add in quadrature for ++/-, relative errors add in quadrature for */÷), so formulas built from +`transformFormula`/`SBMID` (which splice plain Julia arithmetic around resolved +symbols) get variance propagation without any changes to the AST-rewriting +machinery itself. A plain `Real` promotes to a zero-variance `SampledValue` with +`n = typemax(Int)`, so it never becomes the bottleneck of a `min(a.n, b.n)` +combination. +""" +struct SampledValue{N<:Real} <: Real + value :: N + sem :: N + n :: Int +end + +function SampledValue(samples::AbstractVector{<:Real}, center::Real) + n = length(samples) + s = n >= 2 ? std(samples) / sqrt(n) : zero(float(center)) + v, sv = promote(float(center), float(s)) + return SampledValue(v, sv, n) +end + +Base.promote_rule(::Type{SampledValue{N}}, ::Type{M}) where {N<:Real,M<:Real} = SampledValue{promote_type(N,M)} +Base.convert(::Type{SampledValue{N}}, x::Real) where {N<:Real} = SampledValue(convert(N, x), zero(N), typemax(Int)) +Base.convert(::Type{SampledValue{N}}, x::SampledValue) where {N<:Real} = SampledValue(convert(N, x.value), convert(N, x.sem), x.n) +Base.float(x::SampledValue) = SampledValue(float(x.value), float(x.sem), x.n) +Base.zero(::Type{SampledValue{N}}) where {N} = SampledValue(zero(N), zero(N), typemax(Int)) +Base.zero(x::SampledValue) = zero(typeof(x)) +Base.one(::Type{SampledValue{N}}) where {N} = SampledValue(one(N), zero(N), typemax(Int)) + +Base.show(io::IO, x::SampledValue) = print(io, x.value, " ± ", x.sem, " (n=", x.n, ")") + +# Comparisons intentionally ignore `sem`/`n` — needed so @perfcompare formulas like +# `:median_time < 0.05` keep working unchanged when :median_time resolves to a SampledValue. +Base.:(==)(a::SampledValue, b::SampledValue) = a.value == b.value +Base.isless(a::SampledValue, b::SampledValue) = isless(a.value, b.value) +Base.:<(a::SampledValue, b::SampledValue) = isless(a, b) +Base.:<=(a::SampledValue, b::SampledValue) = a.value <= b.value +Base.:>(a::SampledValue, b::SampledValue) = b < a +Base.:>=(a::SampledValue, b::SampledValue) = b <= a + +_safe(x::Real) = isfinite(x) + +_quad(a::Real, b::Real) = (_safe(a) && _safe(b)) ? sqrt(a^2 + b^2) : oftype(float(a), NaN) + +function _relquad(a::SampledValue, b::SampledValue) + ra = (!_safe(a.sem)) ? NaN : (iszero(a.value) ? (iszero(a.sem) ? 0.0 : NaN) : a.sem / abs(a.value)) + rb = (!_safe(b.sem)) ? NaN : (iszero(b.value) ? (iszero(b.sem) ? 0.0 : NaN) : b.sem / abs(b.value)) + return (isnan(ra) || isnan(rb)) ? NaN : sqrt(ra^2 + rb^2) +end + +function Base.:+(a::SampledValue, b::SampledValue) + SampledValue(a.value + b.value, _quad(a.sem, b.sem), min(a.n, b.n)) +end +function Base.:-(a::SampledValue, b::SampledValue) + SampledValue(a.value - b.value, _quad(a.sem, b.sem), min(a.n, b.n)) +end +Base.:-(a::SampledValue) = SampledValue(-a.value, a.sem, a.n) +Base.:+(a::SampledValue) = a + +function Base.:*(a::SampledValue, b::SampledValue) + v = a.value * b.value + r = _relquad(a, b) + SampledValue(v, isnan(r) ? oftype(float(v), NaN) : r * abs(v), min(a.n, b.n)) +end +function Base.:/(a::SampledValue, b::SampledValue) + if iszero(b.value) + nanv = oftype(float(a.value), NaN) + return SampledValue(nanv, nanv, min(a.n, b.n)) + end + v = a.value / b.value + r = _relquad(a, b) + SampledValue(v, isnan(r) ? oftype(float(v), NaN) : r * abs(v), min(a.n, b.n)) +end diff --git a/src/extension_stubs.jl b/src/extension_stubs.jl new file mode 100644 index 0000000..8b90455 --- /dev/null +++ b/src/extension_stubs.jl @@ -0,0 +1,40 @@ + +function resolveAlias end +function likwidEventsRetrieve end +function likwidMetricsRetrieve end +function perfmon end +function LIKWIDExtensionData end +macro PRFT_perfmon end + +# Function headers that are needed beforehand cause julia cant support calling them from an extension afaik. +function formulaGetFlop end +function formulaGetFlops end +function formulaGetBandwidth end +function formulaGetEnergy end +function formulaGetPower end +function formulaGetGPU end +function formulaGetMisses end + +function gpuPowerMeasure end +function formulaGetGPUEnergy end +function formulaGetGPUPower end +function cuda_devices end +function CUDAExtensionData end +function read_joule end + +function gpuPowerMeasureAMD end +function formulaGetAMDGPUEnergy end +function formulaGetAMDGPUPower end +function amdgpu_devices end +function AMDGPUExtensionData end + +function is_loaded(ext::Symbol) + return is_loaded(Val(ext)) +end +is_loaded(ext::Val) = false + +abstract type Mode end +struct MPIMode <: Mode end +struct NormalMode <: Mode end + +mode = NormalMode \ No newline at end of file diff --git a/src/logs.jl b/src/logs.jl index 097daca..00985ce 100644 --- a/src/logs.jl +++ b/src/logs.jl @@ -31,9 +31,14 @@ end """ Moves the temporal log directory to the persistent directory where results are saved - and dumps all IOStream buffers to their respective log files + and dumps all IOStream buffers to their respective log files. + + Nothing is written, neither the folder nor the files, when general.logs_enabled is false in `configuration`. """ -function saveLogFolder() +function saveLogFolder(configuration::Dict = Configuration.CONFIG) + if !(configuration["general"]["logs_enabled"]) + return + end # Create the directory if it doesn't exist if !isdir(LOG_FOLDER) mkpath(LOG_FOLDER) @@ -94,13 +99,13 @@ function dumpLogs(channel::Int=0) for ch in LOGS.channels println("=== Channel: $ch ===") if haskey(LOGS.io_streams, ch) - print(String(copy(LOGS.io_streams[ch].data))) + print(String(take!(copy(LOGS.io_streams[ch])))) end end elseif 1 <= channel <= length(LOGS.channels) ch = LOGS.channels[channel] if haskey(LOGS.io_streams, ch) - print(String(copy(LOGS.io_streams[ch].data))) + print(String(take!(copy(LOGS.io_streams[ch])))) end end end @@ -115,14 +120,14 @@ function dumpLogsString(channel::Int=0) for ch in LOGS.channels all *= "=== Channel: $ch ===\n" if haskey(LOGS.io_streams, ch) - all *= String(copy(LOGS.io_streams[ch].data)) + all *= String(take!(copy(LOGS.io_streams[ch]))) end end return all elseif 1 <= channel <= length(LOGS.channels) ch = LOGS.channels[channel] if haskey(LOGS.io_streams, ch) - return String(copy(LOGS.io_streams[ch].data)) + return String(take!(copy(LOGS.io_streams[ch]))) end end return "" diff --git a/src/transform/auxiliar.jl b/src/transform/auxiliar.jl index 74f9bf9..77d05cf 100644 --- a/src/transform/auxiliar.jl +++ b/src/transform/auxiliar.jl @@ -106,6 +106,32 @@ function popQuoteBlocks(expr::Expr)::Expr end end +""" + `MacroTools.prettify` (used by `treeRun` to clean up the generated suite) unwraps any + block that reduces to a single statement via its `flatten` pass. That's unsafe for a + `do`-block (or any bare `->` lambda) body: if the body collapses to a single non-`:block` + statement (e.g. a tuple literal `(A, B)`), `flatten` strips the wrapping `:block`, leaving + that statement sitting bare where a block is expected. Julia's own `Base.show` for `:do` + expressions doesn't guard against this (unlike its `:for`/`:while`/`:function`/`:if`/`:let` + siblings, which do re-wrap non-block bodies before printing) and prints the bare + expression's `.args` one per line, silently dropping the tuple's parens/comma and turning + "return one value" into "several statements, keep only the last". + + This walks `expr` and re-wraps any `:do`-block lambda body that isn't already `Expr(:block, + ...)` back into one, undoing that corruption before the expression is written out. +""" +function rewrapDoBlockBodies(expr::Expr)::Expr + return MacroTools.postwalk(expr) do x + if x isa Expr && x.head === :do && length(x.args) == 2 && + x.args[2] isa Expr && x.args[2].head === :-> && length(x.args[2].args) == 2 && + !(x.args[2].args[2] isa Expr && x.args[2].args[2].head === :block) + lam = x.args[2] + return Expr(:do, x.args[1], Expr(:->, lam.args[1], Expr(:block, lam.args[2]))) + end + return x + end +end + """ This method interpolates the `inside_expr` into `outside_expr` anywhere it finds the token `substitution_token`, which is a symbol. The `outside_expr` has to be a block or a quote block. It has the particularity that it will remove block heads from the `inside_expr` and add the nested elements onto the location where the token it. diff --git a/src/transform/configuration.jl b/src/transform/configuration.jl index a62195a..ba4006c 100644 --- a/src/transform/configuration.jl +++ b/src/transform/configuration.jl @@ -42,34 +42,152 @@ function validate_config(config::Dict, schema::Dict) end +# Names where an entry comes from in the reported errors, e.g. " in the configuration file perftest_config.toml" +in_source(source::AbstractString) = isempty(source) ? "" : " in $source" + +""" +Complete a possibly partial configuration following a schema. + +Args: +- config: Dictionary to complete, e.g. the contents of a configuration file +- base: Configuration that provides the missing entries +- schema: Dictionary defining expected structure and types +- source: Where `config` comes from (e.g. "the configuration file perftest_config.toml"), named in the reported errors + +Returns: +- A new configuration dictionary that shares no data with `config` or `base`. Entries missing from `config` + or with an incorrect type (reported as an error) take their value from `base`, entries outside the schema are kept. +""" +function fill_config(config::Dict, base::Dict = DEFAULT, schema::Dict = CONFIG_SHAPE; source::AbstractString = "") + at = in_source(source) + + function fill_recursive(cfg, bc, sch, prefix) + filled = Dict{String,Any}(key => deepcopy(value) for (key, value) in cfg if !haskey(sch, key)) + + for (key, expected_type) in sch + name = prefix * key + if expected_type isa Dict + section = get(cfg, key, Dict()) + if !isa(section, Dict) + @error "Expected a table for configuration section $name$at, got $(typeof(section)), using its default values" + section = Dict() + end + filled[key] = fill_recursive(section, bc[key], expected_type, name * ".") + elseif !haskey(cfg, key) + filled[key] = deepcopy(bc[key]) + elseif isa(cfg[key], expected_type) + filled[key] = deepcopy(cfg[key]) + else + @error "Incorrect type for configuration key $name$at. Expected $(expected_type), got $(typeof(cfg[key])), using the default value $(repr(bc[key]))" + filled[key] = deepcopy(bc[key]) + end + end + return filled + end + + return fill_recursive(config, base, schema, "") +end + + +""" +Describe an entry of a configuration that is not in the schema, e.g. a misspelled key. + +Args: +- key: Name of the entry in its table +- value: Value of the entry +- prefix: Full name of its table followed by a dot, empty at the top level +- schema: Schema of its table + +Returns: +- Its kind and full name, e.g. "key general.verbse" or "section genral", and the entries its table can have, + e.g. "The keys of section general are: autoflops, ..." +""" +function describe_unknown(key, value, prefix::AbstractString, schema::Dict)::Tuple{String,String} + name = prefix * string(key) + valid = join(sort!(string.(collect(keys(schema)))), ", ") + + if prefix != "" + return "key $name", "The keys of section $(chop(prefix)) are: $valid" + elseif value isa Dict + return "section $name", "The sections are: $valid" + else + # Every key belongs to a section, e.g. general.verbose + return "key $name outside of any section", "The sections are: $valid" + end +end + +""" +Find the entries of a possibly partial configuration that are not in a schema, described as in `describe_unknown`. +The contents of an unknown section are not looked into. +""" +function unknown_entries(config::Dict, schema::Dict = CONFIG_SHAPE, prefix::String = "")::Vector{Tuple{String,String}} + found = Tuple{String,String}[] + for key in sort!(collect(keys(config)); by=string) + if !haskey(schema, key) + push!(found, describe_unknown(key, config[key], prefix, schema)) + elseif schema[key] isa Dict && config[key] isa Dict + append!(found, unknown_entries(config[key], schema[key], prefix * string(key) * ".")) + end + end + return found +end + +""" +Report as errors the entries of a configuration read from `source` (e.g. "the configuration file perftest_config.toml") +that are not in the schema. They are ignored, the rest of the configuration still applies. +""" +function report_unknown_entries(config::Dict, source::AbstractString, schema::Dict = CONFIG_SHAPE) + for (entry, valid) in unknown_entries(config, schema) + @error "Unknown configuration $entry in $source, ignoring it. $valid" + end +end + + """ Recursively merge two configs, with values from override_config taking precedence. + +Each entry of override_config is checked against the schema on its own: one with an incorrect type is reported as an +error, naming `source` (where override_config comes from) if given, and ignored, the rest still apply. Entries outside +the schema are kept as they are. + +Returns: +- A new configuration dictionary that shares no data with `base_config` or `override_config` """ -function merge_configs(base_config::Dict, override_config::Dict) +function merge_configs(base_config::Dict, override_config::Dict, schema::Dict = CONFIG_SHAPE; source::AbstractString = "") + at = in_source(source) - function _mc(bc::Dict, oc::Dict)::Dict + function _mc(bc::Dict, oc::Dict, sch, prefix)::Dict local merged = deepcopy(bc) for (key, value) in oc - if value isa Dict && haskey(merged, key) && merged[key] isa Dict - a = _mc(merged[key], value) - merged[key] = a + name = prefix * string(key) + # nothing for an entry outside the schema + expected = sch isa Dict ? get(sch, key, nothing) : nothing + + if expected === nothing + if value isa Dict && haskey(merged, key) && merged[key] isa Dict + merged[key] = _mc(merged[key], value, nothing, name * ".") + else + merged[key] = deepcopy(value) + end + elseif expected isa Dict + if value isa Dict + section = get(merged, key, nothing) + merged[key] = _mc(section isa Dict ? section : Dict{String,Any}(), value, expected, name * ".") + else + @error "Expected a table for configuration section $name$at, got $(typeof(value)), ignoring it" + end + elseif value isa expected + merged[key] = deepcopy(value) else - merged[key] = value + @error "Incorrect type for configuration key $name$at. Expected $(expected), got $(typeof(value)), ignoring it" end end return merged end - merged = _mc(base_config, override_config) - - if validate_config(merged, CONFIG_SHAPE) - return merged - else - @info "Malformed configuration added, ignoring" - return base_config - end + return _mc(base_config, override_config, schema, "") end @@ -84,14 +202,14 @@ Args: Returns: - Boolean indicating successful save """ -function save_config(config::Dict) +function save_config(config::Dict, filepath::AbstractString = CONFIG_FILE) if !validate_config(config, CONFIG_SHAPE) @error "Configuration validation failed" return false end try - open(CONFIG_FILE, "w") do io + open(filepath, "w") do io TOML.print(io, config) end return true @@ -102,47 +220,118 @@ function save_config(config::Dict) end """ -Load configuration from a TOML file. +Load configuration from a TOML file over the default configuration, and make it the current one. Args: -- filepath: Path to the TOML file +- filepath: Path to the TOML file, CONFIG_FILE in the working directory if empty Returns: -- Loaded configuration dictionary or nothing +- Loaded configuration dictionary. If the file does not exist it is created with the default configuration, + if it cannot be parsed it is left untouched and the default configuration is used. Its entries that are not in the + schema are reported as errors and ignored, the rest of the file still applies. """ -function load_config(filepath::AbstractString = "")::Union{Dict,Nothing} - try - config = TOML.parsefile(filepath == "" ? CONFIG_FILE : filepath) +function load_config(filepath::AbstractString = "")::Dict + path = filepath == "" ? CONFIG_FILE : filepath - if !validate_config(config, CONFIG_SHAPE) - @error "Configuration validation failed" - return nothing - end - - global CONFIG = config + if !ispath(path) + @info "Configuration not found, saving the default configuration in $path" + save_config(DEFAULT, path) + return load_config(DEFAULT) + end - return CONFIG + config = try + TOML.parsefile(path) catch e - @info "Configuration not found or invalid, loading default configuration" - save_config(DEFAULT) - return DEFAULT + # Never overwrite a file written by the user, even a broken one + @error "Configuration file $path could not be parsed, it has been left untouched and the default configuration will be used" exception = e + return load_config(DEFAULT) end + + source = "the configuration file $path" + report_unknown_entries(config, source) + + return load_config(config; source = source) end -function load_config(config :: Dict)::Union{Dict,Nothing} - if !validate_config(config, CONFIG_SHAPE) - @error "Configuration validation failed" - return nothing +""" +Make a copy of `config` the current configuration, missing or malformed entries take their default value. `source` is +where `config` comes from, named in the reported errors and recorded in SOURCES for the entries that apply. +""" +function load_config(config :: Dict; source::AbstractString = "")::Dict + global CONFIG = fill_config(config; source = source) + empty!(SOURCES) + isempty(source) || record_sources!(SOURCES, config, source) + + return CONFIG +end + +function load_dummy_config()::Dict + return load_config(PRECOMPILATION_CONFIG) +end + +""" +Where the value in force of a configuration key comes from (e.g. "the configuration file perftest_config.toml"), by its +full name (e.g. "regression.default_threshold"), see SOURCES. +""" +source_of(name::AbstractString)::String = get(SOURCES, name, "the default configuration") + +""" +Record `source` in `sources` (see SOURCES) as where the entries of `config` come from, the ones that apply when it is +loaded or merged: those in the schema with the expected type. +""" +function record_sources!(sources::Dict, config::Dict, source::AbstractString, schema::Dict = CONFIG_SHAPE, prefix::String = "") + for (key, value) in config + name = prefix * string(key) + expected = get(schema, key, nothing) + if expected isa Dict + value isa Dict && record_sources!(sources, value, source, expected, name * ".") + elseif expected !== nothing && value isa expected + sources[name] = source + end end + return sources +end - global CONFIG = config +""" +Save a copy of the current configuration, so it can be changed (e.g. by an included recipe) and later restored by `pop_config`. +""" +function push_config() + push!(PARENT_CONFIGS, deepcopy(CONFIG)) + push!(PARENT_SOURCES, copy(SOURCES)) + return nothing +end - return CONFIG +""" +Restore the configuration saved by the last `push_config`. +""" +function pop_config() + global CONFIG = pop!(PARENT_CONFIGS) + # Empty when the stack was filled by other means + isempty(PARENT_SOURCES) || (global SOURCES = pop!(PARENT_SOURCES)) + return nothing end -function load_dummy_config()::Union{Dict,Nothing} - global CONFIG = PRECOMPILATION_CONFIG - return PRECOMPILATION_CONFIG +""" +Set the [bencher] section of the current configuration from the configuration file, used by the generated suites when +they start executing so the Bencher credentials (e.g. api_key) are never written into them. Unlike `load_config`, +a missing file is not created, the default values are used instead. +""" +function load_bencher_config(filepath::AbstractString = CONFIG_FILE) + file = Dict() + if isfile(filepath) + try + file = TOML.parsefile(filepath) + catch e + @error "Configuration file $filepath could not be parsed, the default [bencher] configuration will be used" exception = e + end + end + + source = "the configuration file $filepath" + section = Dict("bencher" => CONFIG_SHAPE["bencher"]) + bencher = Dict("bencher" => get(file, "bencher", Dict())) + report_unknown_entries(bencher, source, section) + CONFIG["bencher"] = fill_config(bencher, DEFAULT, section; source = source)["bencher"] + return nothing end CONFIG_FILE = "perftest_config.toml" @@ -253,7 +442,7 @@ PRECOMPILATION_CONFIG = Dict( "save_folder" => ".thisshouldnotexist", "max_saved_results" => 0, "plotting" => true, - "verbose" => false, + "verbose" => 0, "recursive" => false, "suppress_output" => true, "safe_formulas" => false, @@ -292,79 +481,234 @@ PRECOMPILATION_CONFIG = Dict( ) PARENT_CONFIGS = Dict[] -CONFIG = DEFAULT +CONFIG = deepcopy(DEFAULT) + +# Where the value of each key of CONFIG comes from, by its full name (e.g. "regression.default_threshold" => +# "the configuration file perftest_config.toml"), named in the errors about that value. A key that is not in it has its +# default value. It follows CONFIG during a transform: `load_config` and the transform set it, `push_config` and +# `pop_config` save and restore it along with CONFIG. +SOURCES = Dict{String,String}() +PARENT_SOURCES = Dict{String,String}[] end # module using TOML -function parseConfigurationMacro(_::ExtendedExpr, ctx::Context, info::Dict)::Expr +# Stands for the interpolated fragments of a @perftest_config string during the transform. It is a valid TOML bare key, +# so interpolation in a key or a table name is reported as such instead of as invalid TOML +INTERPOLATION_MARKER = "__PERFTEST_INTERPOLATION__" - # Parse, and merge - string = info[Symbol("")] +isInterpolated(value) = value isa AbstractString ? occursin(INTERPOLATION_MARKER, value) : + value isa AbstractVector ? any(isInterpolated, value) : + value isa AbstractDict ? any(isInterpolated, keys(value)) || any(isInterpolated, values(value)) : + false + +# TOML of a @perftest_config string before the suite executes, its interpolated fragments are replaced by the marker +interpolationPreview(raw) = raw isa Expr && raw.head === :string ? + join(a isa AbstractString ? a : INTERPOLATION_MARKER for a in raw.args) : raw + +# Names the @perftest_config being transformed in its parse errors +configurationMacroSource(ctx::Context) = "the @perftest_config of recipe $(ctx._global.original_file_path)" + +# Configuration keys whose value is used before the recipe is read, so a @perftest_config cannot set them, by their full +# name along with what decides with them +PRE_RECIPE_KEYS = Dict("MPI.enabled" => "the MPI mode") + +""" +Check `config`, parsed from a @perftest_config string, against the configuration schema. Each entry that is not in it +(along with the entries its table can have), that has an incorrect type, or that is used before the recipe is read +(see PRE_RECIPE_KEYS) is reported as a parse error and removed, so the rest still applies to the transform. The keys +whose value is interpolated are removed as well, they take their value when the suite is executed. Interpolation in a +key or a table name is reported as a parse error, in which case it returns false. +""" +function validateConfigurationMacro!(config::Dict, ctx::Context, schema::Dict = Configuration.CONFIG_SHAPE, prefix::String = "")::Bool + source = configurationMacroSource(ctx) + # Sorted so the errors are reported in a stable order + for key in sort!(collect(keys(config))) + name = prefix * key + value = config[key] + if occursin(INTERPOLATION_MARKER, key) + throwParseError!("Interpolation in $source is only supported inside string values, found in the key or table name $(replace(name, INTERPOLATION_MARKER => "\$(...)"))", ctx) + return false + elseif !haskey(schema, key) + entry, valid = Configuration.describe_unknown(key, value, prefix, schema) + throwParseError!("Unknown configuration $entry in $source. $valid", ctx) + delete!(config, key) + elseif schema[key] isa Dict + if value isa Dict + validateConfigurationMacro!(value, ctx, schema[key], name * ".") || return false + else + throwParseError!("Expected a table for configuration section $name in $source, got $(typeof(value))", ctx) + delete!(config, key) + end + elseif haskey(PRE_RECIPE_KEYS, name) + throwParseError!("Configuration key $name cannot be set in $source: $(PRE_RECIPE_KEYS[name]) is decided with it " * + "before the recipe is read, so it would not apply. Set it in the configuration file " * + "$(Configuration.CONFIG_FILE) or with the config argument of runperftests or PerfTest.transform", ctx) + delete!(config, key) + elseif !isa(value, schema[key]) + # Interpolation is only supported inside string values, so an interpolated value is always a string, known + # to have the wrong type here already + given = isInterpolated(value) ? "an interpolated $(typeof(value)) (interpolation is only supported inside string values)" : typeof(value) + throwParseError!("Incorrect type for configuration key $name in $source. Expected $(schema[key]), got $given", ctx) + delete!(config, key) + elseif isInterpolated(value) + delete!(config, key) + addLog("general", "Configuration key $name is interpolated, it will take its value when the suite is executed") + end + end + return true +end + +function parseConfigurationMacro(_::ExtendedExpr, ctx::Context, info::Union{Dict,Nothing})::Expr + + # Its validation already reported a missing argument or one that is not a string literal, e.g. a variable, whose + # value is unknown during the transform + if info === nothing || !haskey(info, Symbol("")) + return quote end + end + + raw = info[Symbol("")] + interpolated = raw isa Expr && raw.head === :string - parsed = TOML.parse(string) + # The interpolated fragments (e.g. $(gethostname())) are only known once the generated suite executes, the keys + # that depend on them are left out of this transform pass. The other keys affect it as without interpolation + # (e.g. regression.enabled gates code generation). + preview = interpolationPreview(raw) + + parsed = try + TOML.parse(preview) + catch e + e isa TOML.ParserError || rethrow() + message = replace(sprint(showerror, e), INTERPOLATION_MARKER => "\$(...)") + throwParseError!("Invalid TOML in $(configurationMacroSource(ctx))$(interpolated ? " (interpolation is only supported inside string values)" : ""): $message", ctx) + return quote end + end + + if !validateConfigurationMacro!(parsed, ctx) + return quote end + end old = Configuration.CONFIG Configuration.CONFIG = Configuration.merge_configs(Configuration.CONFIG, parsed) + Configuration.record_sources!(Configuration.SOURCES, parsed, configurationMacroSource(ctx)) + recordThreadSetting!(parsed, configurationMacroSource(ctx)) if Configuration.CONFIG["general"]["verbose"] != old["general"]["verbose"] addLog("general", "Verbosity level changed from $(old["general"]["verbose"]) to $(Configuration.CONFIG["general"]["verbose"])") end - io = IOBuffer() - TOML.print(nothing, io, Configuration.CONFIG) - serialized_config = String(take!(io)) - + # The generated suite makes the same change at this same point, over the configuration it was generated with + # (see treeRun), the interpolated keys take their real value there return quote begin - PerfTest._perftest_config($(serialized_config)) + PerfTest._perftest_config($(raw)) end end end -function parseThreadsMacro(_::ExtendedExpr, ctx::Context, info::Dict)::Expr - try - specs = info[Symbol("")] - - return quote - let - specs = $specs - arrgmt_l = PerfTest.Topology.literallizeArrangement($specs) - arrgmt_e = PerfTest.Topology.isExecutableArrangement(arrgmt_l) - if arrgmt_e === nothing - @warn "Ignoring pinning." - else - try - PerfTest.Topology.enforceThreadArrangement(arrgmt_e) - catch e - if Sys.iswindows() || Sys.isapple() - @warn "Thread pinning is not supported on this OS. Ignoring specified arrangement." - else - @warn "Failed to enforce thread pinning: $e, ignoring specified arrangement." - end +# The configuration keys, of section general, of the thread setting of a suite +THREAD_KEYS = ("numas", "threads_per_numa") + +""" +Thread setting of the suite being generated, the one its launcher uses (see Launch.retrieveConfigThreadSpecs): for each +of THREAD_KEYS its value, where it comes from, and whether a recipe sets it. A suite has a single thread setting +regardless of recursivity, each key takes its value from the last configuration call that sets it, even in an included +recipe. As for the launcher, an interpolated value is not considered, it is only known once the suite executes. +""" +THREAD_SETTING = Dict{String,Tuple{Any,String,Bool}}() + +# Start the thread setting of a transform from the configuration it starts from +function initThreadSetting!() + empty!(THREAD_SETTING) + for key in THREAD_KEYS + THREAD_SETTING[key] = (Configuration.CONFIG["general"][key], Configuration.source_of("general.$key"), false) + end +end + +# Record the thread keys set by a @perftest_config of a recipe, `parsed` once validated (see validateConfigurationMacro!) +# so without its interpolated keys +function recordThreadSetting!(parsed::Dict, source::AbstractString) + general = get(parsed, "general", nothing) + general isa Dict || return + for key in THREAD_KEYS + haskey(general, key) && (THREAD_SETTING[key] = (general[key], source, true)) + end +end + +""" +Check the thread setting of the suite being generated (see THREAD_SETTING), whether or not a @perftest_threads takes +priority over it. An invalid one (see Topology.arrangementFromConfig) is reported naming where each key comes from: as a +parse error when a recipe sets one of them, otherwise, as the other errors of the configuration file and of the config +argument, as an error that does not stop the transform. The launcher reports it again, as it cannot launch the suite. +""" +function validateThreadSetting!(ctx::Context) + setting = [(key, THREAD_SETTING[key]...) for key in THREAD_KEYS] + problems = Topology.arrangementFromConfig((value for (_, value, _, _) in setting)...) + problems isa Vector{String} || return + + values = join(["general.$key = $(repr(value)) (from $source)" for (key, value, source, _) in setting], " and ") + message = "Invalid thread setting of the generated suite, $values: $(join(problems, ", ")). " * + "$(Topology.THREAD_SETTING_RULE) $(Topology.CONFIG_THREADS_OPTIONS)" + if any(from_recipe for (_, _, _, from_recipe) in setting) + throwParseError!(message, ctx) + else + @error message + end +end + +# Names the @perftest_threads being transformed in its parse errors +threadsMacroSource(ctx::Context) = "the @perftest_threads of recipe $(ctx._global.original_file_path)" + +function parseThreadsMacro(_::ExtendedExpr, ctx::Context, info::Union{Dict,Nothing})::Expr + + # Its validation already reported a missing argument, more than one, or a keyword one + if info === nothing || !haskey(info, Symbol("")) + return quote end + end + + specs = info[Symbol("")] + source = threadsMacroSource(ctx) + report(reason) = throwParseError!("Invalid thread arrangement in $source: $reason $THREADS_OPTIONS", ctx) + if !validateThreadsArgument(specs, report) + return quote end + end + + return quote + let + specs = $specs + arrgmt_l = PerfTest.Topology.literallizeArrangement($specs) + arrgmt_e = PerfTest.Topology.isExecutableArrangement(arrgmt_l) + if arrgmt_e === nothing + @warn "Ignoring pinning." + else + try + PerfTest.Topology.enforceThreadArrangement(arrgmt_e) + catch e + if Sys.iswindows() || Sys.isapple() + @warn "Thread pinning is not supported on this OS. Ignoring specified arrangement." + else + @warn "Failed to enforce thread pinning: $e, ignoring specified arrangement." end end end end - - catch - return quote - "INVALID THREAD ARRANGEMENT" - end end end """ - Used on a generated test suite to import the configuration set during generation + Used on a generated test suite to make, while it executes, the configuration changes made during its generation: + the whole configuration it was generated with at its beginning, then each `@perftest_config` where it appears. + An entry with an incorrect type, which the transform reports as a parse error so only a suite generated by a different + version of the package can have, is reported as an error and ignored, the rest still apply (see merge_configs) """ function _perftest_config(config_string::String) # Parse, and merge parsed = TOML.parse(config_string) - Configuration.CONFIG = Configuration.merge_configs(Configuration.CONFIG, parsed) + Configuration.CONFIG = Configuration.merge_configs(Configuration.CONFIG, parsed; source = "a configuration call of the executing suite") end diff --git a/src/transform/datastruct.jl b/src/transform/datastruct.jl index 0695437..cb0fca3 100644 --- a/src/transform/datastruct.jl +++ b/src/transform/datastruct.jl @@ -130,8 +130,9 @@ mutable struct LocalContext custom_metrics::Vector{Vector{CustomMetric}} enabled_methodologies::Vector{Vector{MethodologyParameters}} + enabled_likwid_groups::Set{Symbol} - LocalContext() = new([], Set{Symbol}(), Vector{CustomMetric}[], Vector{MethodologyParameters}[]) + LocalContext() = new([], Set{Symbol}(), Vector{CustomMetric}[], Vector{MethodologyParameters}[], Set{Symbol}()) end mutable struct GlobalContext @@ -184,6 +185,41 @@ abort_if_invalid(transform) = (x, ctx, info) -> !(info isa Nothing || !info) ? ( """ checkType(type :: Type) = (x) -> x isa type +""" + Resolves simple literal AST forms into real Julia values: a quoted symbol + (`QuoteNode`) becomes the symbol/value it quotes, and a vector literal + (`Expr(:vect, ...)`) becomes a real `Vector` of its (recursively resolved) + elements. Any other expression (e.g. a function call or formula) is + returned unchanged, since those parameters are meant to keep the raw AST. +""" +resolveLiteral(x::QuoteNode) = x.value +resolveLiteral(x::Expr) = x.head === :vect ? Any[resolveLiteral(e) for e in x.args] : x +resolveLiteral(x) = x + +""" + Flattens a (possibly nested) Union type into a tuple of its member types. +""" +unionMembers(t::Type) = t isa Union ? (unionMembers(t.a)..., unionMembers(t.b)...) : (t,) + +""" + Like `value isa declared_type`, but additionally matches a `Vector{ET}` + union member element-wise: `value` is accepted if it's an `AbstractVector` + and every element `isa ET`. This covers cases Julia's own `isa` cannot, + because `Vector` is invariant in its element type (e.g. `Vector{Symbol}` + and `Vector{Any}` are not subtypes of `Vector{Union{Symbol,String}}` even + when every element individually satisfies `Union{Symbol,String}`). +""" +function typeMatches(declared_type::Type, value)::Bool + value isa declared_type && return true + for member in unionMembers(declared_type) + if member isa Type && member <: AbstractVector && value isa AbstractVector + elem_type = eltype(member) + all(el -> el isa elem_type, value) && return true + end + end + return false +end + """ Constructs an ASTRule that assumes that the expression is automatically valid if matched. Thus no validation is done. diff --git a/src/transform/methodologies/manual.jl b/src/transform/methodologies/manual.jl index 5326caa..eb79942 100644 --- a/src/transform/methodologies/manual.jl +++ b/src/transform/methodologies/manual.jl @@ -4,10 +4,14 @@ function onPerfcmpDefinition(expr :: ExtendedExpr, ctx :: Context, info) if info isa Nothing || !(Configuration.CONFIG["perfcompare"]["enabled"]) return end + if usesAutoflop(info[Symbol("")]) + reportAutoflopUse!("The @perfcompare $(info[Symbol("")])", "uses :autoflop", ctx) + end params = Dict{Symbol, Any}( gensym("expr") => info[Symbol("")], + :showvar => get(info, :showvar, false), ) push!(ctx._local.enabled_methodologies[end], MethodologyParameters( id = :perfcmp, @@ -29,8 +33,14 @@ function buildPerfcmp(context :: Context) :: Expr buffer = quote all_succeeded = true end - # Get all metrics in the info - for (_,expr) in info.params + showvar = get(info.params, :showvar, false) + # Get all metrics in the info. `:showvar` is a fixed, non-expression key stored + # alongside the gensym'd per-assertion keys (see onPerfcmpDefinition) — skip it here, + # every other entry is a formula expression to compile. + for (k,expr) in info.params + if k === :showvar + continue + end buffer = quote $buffer metric = newMetricResult( @@ -50,7 +60,8 @@ function buildPerfcmp(context :: Context) :: Expr low_is_bad=true, succeeded=success, custom_plotting=Symbol[], - full_print=false + full_print=false, + showvar=$(showvar) ) push!(methodology_res.metrics, (metric => test)) diff --git a/src/transform/methodologies/mem_bandwidth.jl b/src/transform/methodologies/mem_bandwidth.jl index 0d081a2..4de67ce 100644 --- a/src/transform/methodologies/mem_bandwidth.jl +++ b/src/transform/methodologies/mem_bandwidth.jl @@ -11,6 +11,10 @@ function onMemoryThroughputDefinition(formula::ExtendedExpr, ctx::Context, info) if !(Configuration.CONFIG["memory_bandwidth"]["enabled"]) return end + # Already transformed, :autoflop is still there, as test_res.primitives[:autoflop] + if usesAutoflop(formula) + reportAutoflopUse!("The @define_eff_memory_throughput", "uses :autoflop in its formula", ctx) + end if haskey(info, :ratio) else info[:ratio] = Configuration.CONFIG["memory_bandwidth"]["default_threshold"] diff --git a/src/transform/methodologies/regression.jl b/src/transform/methodologies/regression.jl index 1e5eff1..173ebd7 100644 --- a/src/transform/methodologies/regression.jl +++ b/src/transform/methodologies/regression.jl @@ -1,18 +1,70 @@ """ +Thresholds of a @regression that gives none, one for each of its metrics from regression.default_threshold: the +threshold itself for a metric where a high value is bad (low_is_bad = false, e.g. a time), and 2 − threshold for one +where a low value is bad (low_is_bad = true, e.g. a throughput). The default 1.1 thus tolerates a time up to 10% higher, +and a throughput up to 10% lower (0.9), than the reference. 2 − threshold is computed on the decimal value it is written +with, so 1.1 gives exactly 0.9. + +A regression.default_threshold of 2 or more leaves no threshold for a metric where a low value is bad, it is reported as +a parse error naming where it comes from. +""" +function defaultRegressionThresholds(metrics::AbstractVector, low_is_bad, ctx::Context)::Vector{Float64} + threshold = Configuration.CONFIG["regression"]["default_threshold"] + # An Int as well, the type of the key is Number + high_is_bad = Float64(threshold) + low_is_bad_th = Float64(2 - parse(BigFloat, string(high_is_bad))) + + # Already reported when it does not match the metrics, see onRegressionDefinition + if !(low_is_bad isa AbstractVector && length(low_is_bad) == length(metrics)) + return fill(high_is_bad, length(metrics)) + end + + low = [metric for (metric, lib) in zip(metrics, low_is_bad) if lib === true] + if !isempty(low) && threshold >= 2 + throwParseError!("Invalid regression threshold in the @regression of recipe $(ctx._global.original_file_path): it gives " * + "no threshold, so $(join(repr.(low), ", ")), where a low value is bad (low_is_bad = true), would " * + "take 2 − regression.default_threshold, but regression.default_threshold = $(repr(threshold)) (from " * + "$(Configuration.source_of("regression.default_threshold"))) gives 2 − $(repr(threshold)) = " * + "$(repr(low_is_bad_th)), which every ratio new/reference passes. Give that @regression an explicit " * + "threshold (threshold=..., the ratio new/reference a metric with low_is_bad = true must stay above), " * + "or set regression.default_threshold below 2", ctx) + end + return [lib === true ? low_is_bad_th : high_is_bad for lib in low_is_bad] +end + +plural(n::Integer, word::AbstractString) = "$n $word$(n == 1 ? "" : "s")" +literalList(values) = "[" * join(repr.(values), ", ") * "]" + +""" +Report as a parse error that `key` (:low_is_bad or :threshold) of a @regression is a vector that does not give one +value per metric, see onRegressionDefinition. +""" +function reportRegressionLengthMismatch(key::Symbol, single::Type, value::AbstractVector, metrics::AbstractVector, ctx::Context) + throwParseError!("Invalid $key in the @regression of recipe $(ctx._global.original_file_path): $key = $(literalList(value)) " * + "gives $(plural(length(value), "value")) for $(plural(length(metrics), "metric")) ($(join(repr.(metrics), ", "))). " * + "$key is either a single $single, which applies to every metric, or a vector with one $single per " * + "metric, in the order of metrics", ctx) +end + +""" + +Called when a regression macro is detected, sets up the regression methodology. Without a threshold, the thresholds +come from regression.default_threshold, see defaultRegressionThresholds. + +low_is_bad and threshold are each either a single value, which applies to every metric, or a vector with one value per +metric. A vector of another length is reported as a parse error, as is the metric :autoflop (see AUTOFLOP_UNSUPPORTED), +and the macro is then ignored so the transform goes on collecting the errors of the recipe. -Called when a regression macro is detected, sets up the regression methodology - """ function onRegressionDefinition(_::ExtendedExpr, ctx::Context, info) if !(Configuration.CONFIG["regression"]["enabled"]) return end + # Its validation already reported the arguments it could not read, e.g. too many of them + info === nothing && return - if haskey(info, :threshold) - else - info[:threshold] = Configuration.CONFIG["regression"]["default_threshold"] - end + given_threshold = haskey(info, :threshold) if haskey(info, :metrics) else info[:metrics] = :median_time @@ -21,36 +73,71 @@ function onRegressionDefinition(_::ExtendedExpr, ctx::Context, info) else info[:low_is_bad] = false end - # vvvv Verify that parameters make sense among each other vvvv - if info[:metrics] isa metricID() - info[:metrics] = [metricID(info[:metrics])] - info[:low_is_bad] = info[:low_is_bad] isa Vector ? throwParseError!("Several low_is_bad values provided for low_is_bad for a single metric", ctx) : [info[:low_is_bad]] - info[:threshold] = info[:threshold] isa Vector ? throwParseError!("Several threshold values provided for threshold for a single metric", ctx) : [info[:threshold]] + if haskey(info, :showvar) else - if info[:low_is_bad] isa Bool - info[:low_is_bad] = fill(info[:low_is_bad], length(info[:metrics])) - elseif length(info[:low_is_bad]) != length(info[:metrics]) - throwParseError!("Length of low_is_bad should be either 1 to apply to all, or the same as the length of metrics", ctx) - end - if info[:threshold] isa Float64 - info[:threshold] = fill(info[:threshold], length(info[:metrics])) - elseif length(info[:threshold]) != length(info[:metrics]) - throwParseError!("Length of threshold should be either 1 to apply to all, or the same as the length of metrics", ctx) + info[:showvar] = false + end + # vvvv Verify that parameters make sense among each other vvvv + info[:metrics] = info[:metrics] isa metricID() ? [metricID(info[:metrics])] : [metricID(m) for m in info[:metrics]] + consistent = true + # One value for each metric + for (key, single) in ((:low_is_bad, Bool), (:threshold, Float64)) + if key === :threshold && !given_threshold + continue + elseif !(info[key] isa AbstractVector) + info[key] = fill(info[key], length(info[:metrics])) + elseif length(info[key]) != length(info[:metrics]) + reportRegressionLengthMismatch(key, single, info[key], info[:metrics], ctx) + consistent = false end - info[:metrics] = [metricID(m) for m in info[:metrics]] + end + if !given_threshold + # One for each metric, following its low_is_bad + info[:threshold] = defaultRegressionThresholds(info[:metrics], info[:low_is_bad], ctx) end # ^^^^ Verify that parameters make sense among each other ^^^^ for metric in info[:metrics] - if !(metric in formula_symbols) && !isCustomMetricDefined(ctx, metric) - throwParseError!("Metric $metric is not available in the current context.", ctx) + if metric === :autoflop + reportAutoflopUse!("The @regression", "tracks the metric :autoflop", ctx; + instead = "Track a metric defined with @define_metric from the flop count of the target " * + "instead, or pass the flop count to @roofline with actual_flops.") + consistent = false + elseif !(metric in formula_symbols) && !isCustomMetricDefined(ctx, metric) + # Referred to by its name, but defined with another symbol + named = customMetricByName(ctx, metric) + hint = named === nothing ? "" : " The metric named $(repr(named.name)) is referred to by its symbol $(repr(named.symbol))." + throwParseError!("Metric $metric is not available in the current context.$hint", ctx) + end + end + # Already reported, the suite is not generated + consistent || return + + existing_idx = findfirst(m -> m.id == :regression, ctx._local.enabled_methodologies[end]) + if existing_idx === nothing + push!(ctx._local.enabled_methodologies[end], MethodologyParameters( + id=:regression, + name="Metric regression tracking", + override=false, + params=info, + )) + else + # Extend in place: a second entry in the same scope would lose to the first under captureMethodologyInfo's first-key-wins merge. + existing_params = ctx._local.enabled_methodologies[end][existing_idx].params + # showvar is a scalar (not per-metric), so a redeclaration simply overwrites it. + existing_params[:showvar] = info[:showvar] + for (metric, threshold, low_is_bad) in zip(info[:metrics], info[:threshold], info[:low_is_bad]) + metric_idx = findfirst(==(metric), existing_params[:metrics]) + if metric_idx === nothing + push!(existing_params[:metrics], metric) + push!(existing_params[:threshold], threshold) + push!(existing_params[:low_is_bad], low_is_bad) + else + # Same metric declared again: drop the old parameters, keep the new ones. + existing_params[:threshold][metric_idx] = threshold + existing_params[:low_is_bad][metric_idx] = low_is_bad + end end end - push!(ctx._local.enabled_methodologies[end], MethodologyParameters( - id=:regression, - name="Metric regression tracking", - override=false, - params=info, - )) addLog("metrics", "[METHODOLOGY] Defined REGRESSION on $([i.set_name for i in ctx._local.depth_record]) METRICS: $(info[:metrics]) TH: $(info[:threshold]) LOW_IS_BAD: $(info[:low_is_bad])") end @@ -59,19 +146,21 @@ end """ Executes regression for one single metric """ -function regression(metric :: Symbol, threshold::Float64, low_is_bad::Bool) +function regression(metric :: Symbol, threshold::Float64, low_is_bad::Bool, showvar::Bool) metric = QuoteNode(metric) success_expr = :($(low_is_bad ? :(>) : :(<))(ratio ,$(threshold))) return quote if haskey(test_res.metrics, $metric) && !(old_test_res isa Nothing) && haskey(old_test_res.metrics, $metric) - ratio = test_res.metrics[$metric].value / old_test_res.metrics[$metric].value + ratio_sv = metricSampledValue(test_res.metrics[$metric]) / metricSampledValue(old_test_res.metrics[$metric]) + ratio = ratio_sv isa SampledValue ? ratio_sv.value : ratio_sv success = $success_expr result = newMetricResult($mode, name=$("$metric Difference"), units="%", - value=ratio * 100 + value=ratio_sv * 100, + showvar=$(showvar) ) test = Metric_Test( reference=100.0, @@ -80,28 +169,32 @@ function regression(metric :: Symbol, threshold::Float64, low_is_bad::Bool) low_is_bad=$(low_is_bad), succeeded=success, custom_plotting=Symbol[], - full_print=true + full_print=true, + showvar=$(showvar) ) push!(methodology_res.metrics, (result => test)) - + # Register tracked metric in auxiliar group for later usage in Bencher methodology_res.custom_elements[$metric] = (newMetricResult( $mode, name=test_res.metrics[$metric].name, units=test_res.metrics[$metric].units, - value=test_res.metrics[$metric].value) => test + value=metricSampledValue(test_res.metrics[$metric]), + showvar=$(showvar)) => test ) all_succeeded &= success elseif !(old_test_res isa Nothing) && !haskey(test_res.metrics, $metric) && haskey(test_res.primitives, $metric) && haskey(old_test_res.primitives, $metric) - ratio = test_res.primitives[$metric] / old_test_res.primitives[$metric] + ratio_sv = test_res.primitives[$metric] / old_test_res.primitives[$metric] + ratio = ratio_sv isa SampledValue ? ratio_sv.value : ratio_sv success = $success_expr result = newMetricResult($mode, name=$("$metric Difference"), units="%", - value=ratio * 100 + value=ratio_sv * 100, + showvar=$(showvar) ) test = Metric_Test( reference=100.0, @@ -110,7 +203,8 @@ function regression(metric :: Symbol, threshold::Float64, low_is_bad::Bool) low_is_bad=$(low_is_bad), succeeded=success, custom_plotting=Symbol[], - full_print=true + full_print=true, + showvar=$(showvar) ) push!(methodology_res.metrics, (result => test)) @@ -120,7 +214,8 @@ function regression(metric :: Symbol, threshold::Float64, low_is_bad::Bool) $mode, name=$("$metric"), units="s", - value=test_res.primitives[$metric]) => test + value=test_res.primitives[$metric], + showvar=$(showvar)) => test ) all_succeeded &= success @@ -130,14 +225,16 @@ function regression(metric :: Symbol, threshold::Float64, low_is_bad::Bool) $mode, name=$("$metric Reference value"), units=haskey(old_test_res.metrics, $metric) ? old_test_res.metrics[$metric].units : "s", - value=haskey(old_test_res.metrics, $metric) ? old_test_res.metrics[$metric].value : (haskey(old_test_res.primitives, $metric) ? old_test_res.primitives[$metric] : NaN) + value=haskey(old_test_res.metrics, $metric) ? metricSampledValue(old_test_res.metrics[$metric]) : (haskey(old_test_res.primitives, $metric) ? old_test_res.primitives[$metric] : NaN), + showvar=$(showvar) ) end methodology_res.custom_elements[$metric] = (newMetricResult( $mode, name=$("$metric"), units=haskey(test_res.metrics, $metric) ? test_res.metrics[$metric].units : "s", - value=haskey(test_res.metrics, $metric) ? test_res.metrics[$metric].value : (haskey(test_res.primitives, $metric) ? test_res.primitives[$metric] : NaN) + value=haskey(test_res.metrics, $metric) ? metricSampledValue(test_res.metrics[$metric]) : (haskey(test_res.primitives, $metric) ? test_res.primitives[$metric] : NaN), + showvar=$(showvar) )) end end @@ -162,13 +259,13 @@ function buildRegression(context::Context)::Expr all_succeeded = true $( if info[:metrics] isa Symbol - regression(info[:metrics], info[:threshold], info[:low_is_bad]) + regression(info[:metrics], info[:threshold], info[:low_is_bad], info[:showvar]) else q = quote end; for (i, metric) in enumerate(info[:metrics]) q = quote $q; - $(regression(metric, info[:threshold][i], info[:low_is_bad][i])) + $(regression(metric, info[:threshold][i], info[:low_is_bad][i], info[:showvar])) end end; q diff --git a/src/transform/methodologies/roofline.jl b/src/transform/methodologies/roofline.jl index dd11d9e..80b7385 100644 --- a/src/transform/methodologies/roofline.jl +++ b/src/transform/methodologies/roofline.jl @@ -12,12 +12,28 @@ end Called when a roofline macro is detected, sets up the roofline methodology +Automatic flop counting is not supported (see AUTOFLOP_UNSUPPORTED): :autoflop in its formulas, or no actual_flops while +general.autoflops is true, is reported as a parse error. + """ function onRooflineDefinition(formula :: ExtendedExpr, ctx :: Context, info) if !(Configuration.CONFIG["roofline"]["enabled"]) return end + autoflop_uses = [what for (what, expr) in (("actual_flops", get(info, :actual_flops, nothing)), + ("its operational intensity formula", formula)) if usesAutoflop(expr)] + if !isempty(autoflop_uses) + reportAutoflopUse!("The @roofline", "uses :autoflop in $(join(autoflop_uses, " and in "))", ctx; + instead = "Pass the flop count of the target to @roofline with actual_flops instead (a number, " * + "or a formula as its operational intensity one), and write it in place of :autoflop in its formulas.") + elseif !haskey(info, :actual_flops) && Configuration.CONFIG["general"]["autoflops"] + reportAutoflopUse!("The @roofline", "gives no actual_flops, so with general.autoflops = true (from " * + "$(Configuration.source_of("general.autoflops"))) the flops of its target would be counted automatically", ctx; + instead = "Pass the flop count of the target to @roofline with actual_flops instead (a number, " * + "or a formula as its operational intensity one).") + end + # Adds to the inner scope the request to build the methodology and its needed metrics push!(ctx._local.custom_metrics[end], CustomMetric( name="Operational intensity", @@ -30,11 +46,7 @@ function onRooflineDefinition(formula :: ExtendedExpr, ctx :: Context, info) local form = transformFormula(quote $(info[:actual_flops]) / :median_time end, ctx) - # Can we put the autoflops or shall we construct a partial model? - elseif Configuration.CONFIG["autoflops"] - local form = transformFormula(quote - :autoflop / :median_time - end, ctx) + # Without it, general.autoflops = true is reported above, automatic flop counting is not supported else # Incomplete model local form = quote diff --git a/src/transform/metrics/custom.jl b/src/transform/metrics/custom.jl index 26030f5..5bce14d 100644 --- a/src/transform/metrics/custom.jl +++ b/src/transform/metrics/custom.jl @@ -1,24 +1,63 @@ +# Symbol that identifies a custom metric or benchmark: its symbol parameter if given, otherwise its name as a symbol +metricSymbol(info) = haskey(info, :symbol) ? metricID(info[:symbol]) : Symbol(info[:name]) + +""" +Report as a parse error that `construct` (e.g. "The @define_metric name = \"m\""), of the recipe being transformed, sets +a symbol that formulas cannot refer to: an empty one, or a built-in formula symbol (e.g. :median_time), which formulas +resolve to the built-in value instead. Only an explicit symbol is checked, the default one (the name) is left as it was. +""" +function checkMetricSymbol!(construct::AbstractString, info, ctx::Context) + haskey(info, :symbol) || return + sym = metricSymbol(info) + if sym === Symbol("") + throwParseError!("$construct of recipe $(ctx._global.original_file_path) sets an empty symbol. Give it a non empty " * + "symbol, or leave symbol out to refer to it by its name.", ctx) + elseif sym in ctx._global.valid_symbols + throwParseError!("$construct of recipe $(ctx._global.original_file_path) sets symbol = $(repr(sym)), which is a " * + "built-in formula symbol, so formulas would get the built-in value instead. Choose another symbol.", ctx) + end +end + function defineCustomMetric(type :: Symbol, ctx :: Context, info) if info isa Nothing return end + construct = "The $(type == :aux ? "@auxiliary_metric" : "@define_metric") name = $(repr(info[:name]))" + if usesAutoflop(info[Symbol("")]) + reportAutoflopUse!(construct, "uses :autoflop in its formula", ctx) + end + checkMetricSymbol!(construct, info, ctx) + symbol = metricSymbol(info) + push!(ctx._local.custom_metrics[end], CustomMetric( name=info[:name], units=info[:units], formula=transformFormula(info[Symbol("")], ctx), - symbol=Symbol(info[:name]), + symbol=symbol, auxiliary= type == :aux )) - addLog("metrics", "[METRIC] Defined $(info[:name]) [$(info[:units])] on $([i.set_name for i in ctx._local.depth_record])") + addLog("metrics", "[METRIC] Defined $(info[:name]) ($(repr(symbol))) [$(info[:units])] on $([i.set_name for i in ctx._local.depth_record])") end -function buildCustomMetrics(custom_metrics :: Vector{Vector{CustomMetric}})::Expr +function buildCustomMetrics(custom_metrics :: Vector{Vector{CustomMetric}}, ctx::Context)::Expr + + # Auxiliary/custom metrics have no Metric_Test companion to consult a showvar flag from at + # print time, so the decision is made here at construction time: show variance for this + # scope's metrics iff some enclosing @regression/@perfcompare in the scope chain asked for + # it. captureMethodologyInfo already implements the innermost-first inherit/override walk, + # so this correctly inherits across nested testsets for free. + scope_has_showvar = let + reg = captureMethodologyInfo(:regression, ctx._local.enabled_methodologies) + cmp = captureMethodologyInfo(:perfcmp, ctx._local.enabled_methodologies) + (reg !== nothing && get(reg.params, :showvar, false) === true) || + (cmp !== nothing && get(cmp.params, :showvar, false) === true) + end buffer = :(begin end) built_set = Set{Symbol}() @@ -42,7 +81,8 @@ function buildCustomMetrics(custom_metrics :: Vector{Vector{CustomMetric}})::Exp name=$(metric_def.name), units=$(metric_def.units), value=$(metric_def.formula), - auxiliary=$(metric_def.auxiliary) + auxiliary=$(metric_def.auxiliary), + showvar=$scope_has_showvar ) $(if metric_def.auxiliary :(test_res.auxiliar[$(QuoteNode(symbol))] = m) @@ -59,17 +99,20 @@ end function defineCustomBenchmark(ctx::Context, info) :: Expr - addLog("metrics", "[BENCHMARK] Defining $(info[:name]) [$(info[:units])] on $([i.set_name for i in ctx._local.depth_record])") + checkMetricSymbol!("The @define_benchmark name = $(repr(info[:name]))", info, ctx) + symbol = metricSymbol(info) + + addLog("metrics", "[BENCHMARK] Defining $(info[:name]) ($(repr(symbol))) [$(info[:units])] on $([i.set_name for i in ctx._local.depth_record])") # Cannot be called inside a testset TODO if length(ctx._local.depth_record) < 0 throwParseError!("Cannot define benchmark $(info[:name]) inside a testset", ctx) else # Add benchmark name to recognized custom benchmarks - push!(ctx._global.custom_benchmarks, Symbol(info[:name])) + push!(ctx._global.custom_benchmarks, symbol) # Transform return quote - _PRFT_GLOBALS.custom_benchmarks[$(QuoteNode(Symbol(info[:name])))] = newMetricResult( + _PRFT_GLOBALS.custom_benchmarks[$(QuoteNode(symbol))] = newMetricResult( $mode, name=$(info[:name]), units=$(info[:units]), @@ -89,3 +132,13 @@ function isCustomMetricDefined(ctx::Context, name :: Symbol) end return false end + +# The custom metric in scope named `name` (as a symbol), or nothing. Used to hint at its symbol when a metric is referred to by its name +function customMetricByName(ctx::Context, name :: Symbol) + for custom_metric in Iterators.flatten(ctx._local.custom_metrics) + if Symbol(custom_metric.name) == name + return custom_metric + end + end + return nothing +end diff --git a/src/transform/metrics/primitives.jl b/src/transform/metrics/primitives.jl index 70cbdd0..f7581c6 100644 --- a/src/transform/metrics/primitives.jl +++ b/src/transform/metrics/primitives.jl @@ -54,8 +54,12 @@ end # EXCEPTIONAL FUNCTION SHALL BE MOVED TO EXECUTION SOONER OR LATER - NOTE function buildPrimitiveMetrics!(::Type{NormalMode}, _PRFT_LOCAL::Dict, _PRFT_GLOBAL::Dict{Symbol,Any}) - _PRFT_LOCAL[:primitives][:median_time] = median(_PRFT_LOCAL[:suite]).time / 1e9 - _PRFT_LOCAL[:primitives][:min_time] = minimum(_PRFT_LOCAL[:suite]).time / 1e9 + _times_s = _PRFT_LOCAL[:suite].times ./ 1e9 + _n = length(_times_s) + _med = _sample_median(_times_s) + _PRFT_LOCAL[:primitives][:median_time] = _n >= MIN_VARIANCE_SAMPLES ? + SampledValue(_med, std(_times_s)/sqrt(_n), _n) : _med + _PRFT_LOCAL[:primitives][:min_time] = minimum(_times_s) _PRFT_LOCAL[:primitives][:autoflop] = _PRFT_LOCAL[:additional][:autoflop] _PRFT_LOCAL[:primitives][:ret_value] = _PRFT_LOCAL[:additional][:ret_value] _PRFT_LOCAL[:primitives][:printed_output] = _PRFT_LOCAL[:additional][:printed_output] diff --git a/src/transform/parsing/formula_transform.jl b/src/transform/parsing/formula_transform.jl index ed5120d..109b6c7 100644 --- a/src/transform/parsing/formula_transform.jl +++ b/src/transform/parsing/formula_transform.jl @@ -1,5 +1,4 @@ - -function parseSymbol(x, ctx :: Context) +function parseSymbol(x, ctx::Context) if x in ctx._local.exported_vars return quote _PRFT_LOCAL[:additional][:exported][$(QuoteNode(x))] end elseif !(Configuration.CONFIG["general"]["safe_formulas"]) || x in names(Base) @@ -10,6 +9,42 @@ function parseSymbol(x, ctx :: Context) end end +# A unique wrapper type to mark "do not transform this QuoteNode" +# The thing is, transforming symbols can get quite messy cause some operators like a.b trigger it as well, so we need to mark them otherwise the fields will be treated as symbols. +struct DotFieldNode + inner::QuoteNode +end + +# Marks a fully-resolved symbol chain (e.g. :flop.double.vector_512). +# `main` is the head symbol, `rest` are the chained field symbols. +struct SymbolChainNode + main::Symbol + rest::Vector{Symbol} +end + +# Helper: given a node, if it represents a symbol chain rooted at a QuoteNode, +# return (main_sym, rest_syms::Vector{Symbol}); otherwise return nothing. +# +# Cases handled: +# QuoteNode(:s) -> (:s, Symbol[]) +# Expr(:., , QuoteNode(:f)) -> resolve recursively, push :f +# Expr(:., , SymbolChainNode) -> (already-collected single-symbol base) chained further +function collectSymbolChain(node) + if node isa QuoteNode && node.value isa Symbol + return (node.value, Symbol[]) + elseif node isa SymbolChainNode + return (node.main, copy(node.rest)) + elseif node isa Expr && node.head === :. && length(node.args) == 2 && + node.args[2] isa QuoteNode && node.args[2].value isa Symbol + base = collectSymbolChain(node.args[1]) + base === nothing && return nothing + main, rest = base + push!(rest, node.args[2].value) + return (main, rest) + else + return nothing + end +end formula_rules = ASTRule[ validASTRule( @@ -20,9 +55,16 @@ formula_rules = ASTRule[ checkType(LineNumberNode), empty_expr, ), + # Resolved symbol chains: :main.a.b... -> SBMID(:main, [:a, :b, ...]) + validASTRule( + checkType(SymbolChainNode), + (x, ctx, info) -> isempty(x.rest) ? + SBMID(x.main) : + SBMID(x.main, x.rest) + ), ASTRule( checkType(QuoteNode), - (x, ctx) -> (x.value in ctx._global.valid_symbols) ? true : (addLog("metrics", "[METRIC] $(x.value) has been parsed on a formula, its availability is not checked automatically"); + (x, ctx) -> (x.value in union(ctx._global.valid_symbols)) ? true : (addLog("metrics", "[METRIC] $(x.value) has been parsed on a formula, its availability is not checked automatically"); #throwParseError!("Variable \"$x\" not exported or undefined, use @export_vars to export", ctx) ), (x, ctx, info) -> info == true ? ( @@ -32,7 +74,6 @@ formula_rules = ASTRule[ ) : SBMID(x.value)), ] - function exportVars(symbols::Set{Symbol}, context::Context)::Expr export_one(sym) = quote @@ -48,20 +89,23 @@ function exportVars(symbols::Set{Symbol}, context::Context)::Expr return expr end -# A unique wrapper type to mark "do not transform this QuoteNode" -# The thing is, transforming symbols can get quite messy cause some operators like a.b trigger it as well, so we need to mark them otherwise the fields will be treated as symbols. -struct DotFieldNode - inner::QuoteNode -end - function transformFormula(form_expr::ExtendedExpr, context::Context)::ExtendedExpr - # prewalk: wrap QuoteNodes that are dot-access field names + # prewalk: collapse dot-access chains rooted at a QuoteNode (symbol chains) + # into a single SymbolChainNode sentinel, and protect plain a.b field names. protected = MacroTools.prewalk(form_expr) do node - if node isa Expr && node.head === :. && - length(node.args) == 2 && node.args[2] isa QuoteNode - # Replace the QuoteNode child with our sentinel - Expr(:., node.args[1], DotFieldNode(node.args[2])) + if node isa Expr && node.head === :. && length(node.args) == 2 && + node.args[2] isa QuoteNode + chain = collectSymbolChain(node) + if chain !== nothing + # This is :sym, :sym.a, :sym.a.b, ... -> mark as a symbol chain + main, rest = chain + SymbolChainNode(main, rest) + else + # This is a.b where a is not (rooted at) a quoted symbol: + # protect the field name QuoteNode so it is not treated as a metric. + Expr(:., node.args[1], DotFieldNode(node.args[2])) + end else node end @@ -70,10 +114,10 @@ function transformFormula(form_expr::ExtendedExpr, context::Context)::ExtendedEx # Ordinary context independent transformations walked = MacroTools.postwalk(ruleSet(context, formula_rules), protected) - # postwalk: unwrap sentinels back to QuoteNodes + # postwalk: unwrap field sentinels back to QuoteNodes result = MacroTools.postwalk(walked) do node - if node isa Expr && node.head === :. && - length(node.args) == 2 && node.args[2] isa DotFieldNode + if node isa Expr && node.head === :. && length(node.args) == 2 && + node.args[2] isa DotFieldNode Expr(:., node.args[1], node.args[2].inner) else node diff --git a/src/transform/parsing/hierarchy_transform.jl b/src/transform/parsing/hierarchy_transform.jl index 4fe62db..03c8834 100644 --- a/src/transform/parsing/hierarchy_transform.jl +++ b/src/transform/parsing/hierarchy_transform.jl @@ -44,6 +44,7 @@ function transformTestset(input_expr::Expr, context::Context) outerset = length(context._local.depth_record) <= 1 if has_for_loop + addLog("hierarchy", "[TESTSET]: $([i.set_name for i in context._local.depth_record]) has a for loop in $b") result = quote $(outerset ? :(:__PERFTEST_FW__) : begin end) @@ -75,6 +76,16 @@ function transformTestset(input_expr::Expr, context::Context) return result end +function backTokenToContextUpdate!(input_expr::QuoteNode, context::Context) + # Update context: delete depth level + pop!(context._local.depth_record) + pop!(context._local.custom_metrics) + pop!(context._local.enabled_methodologies) + + addLog("hierarchy", "[TESTSET] Exiting group") + return nothing; +end + function transformPerftest(input_expr::Expr, context::Context) # Get the elements of interest from the macrocall @@ -87,6 +98,35 @@ function transformPerftest(input_expr::Expr, context::Context) num = (context._local.depth_record[end].test_count += 1) name = "Test $num" + # Build the regression-lookup key path for the enclosing testset hierarchy. Levels that + # are for-loop testsets can't use their static `set_name` alone (identical across every + # iteration) -- they need a key expression evaluated at suite run time against the loop + # variable that's in scope there, mirroring how `extractTestResults` keys saved results + # (`description * "_" * string(iterator)`), so a lookup can find the matching iteration. + regression_key_elems = Any[ + entry.for_loop === nothing ? entry.set_name : :(string($(entry.set_name), "_", $(entry.for_loop.first))) + for entry in context._local.depth_record + ] + + # Isolate setup property + setup_expr = quote end + for pair in prop + if pair.head == :(=) + if pair.args[1] == :setup + setup_expr = pair.args[2] + end + end + end + # Isolate teardown property + teardown_expr = quote end + for pair in prop + if pair.head == :(=) + if pair.args[1] == :teardown + teardown_expr = pair.args[2] + end + end + end + # LOGINFO addLog("hierarchy", "[PERFTEST] New Test: $name \"$expr\" @ $([i.set_name for i in context._local.depth_record])") # Return the transformed expression, in the following quote ts means the current testset @@ -98,11 +138,53 @@ function transformPerftest(input_expr::Expr, context::Context) quote ts.benchmarks[$name] = @PRFTBenchmark(($parsed_target; MPI.Barrier(MPI.COMM_WORLD)), $(prop...)) end end) - # Create Test_Result struct to save test data - test_res = Test_Result($name) + extensions = PerfTest.ExtensionData[] + $setup_expr + $(if PerfTest.is_loaded(:LIKWID) + addLog("general", "[LIKWID] Measuring target \"$(expr)\" with groups: $([g for g in context._local.enabled_likwid_groups])") + quote + metrics, events = PerfTest.perfmon(() -> $expr, $([String(i) for i in context._local.enabled_likwid_groups]); autopin=false, print=false, nsamples=length(ts.benchmarks[$name])) + push!(extensions, PerfTest.LIKWIDExtensionData(metrics, events)) + end + else + quote + push!(extensions, PerfTest.NoExtensionData()) + end + end) + $teardown_expr + $setup_expr + $(if PerfTest.is_loaded(:CUDA) + addLog("general", "[CUDA] Measuring target \"$(expr)\"") + quote + @info PerfTest.cuda_devices() + energy, power = $(PerfTest.gpuPowerMeasure(expr, name)) + push!(extensions, PerfTest.CUDAExtensionData(energy, power)) + end + else + quote + push!(extensions, PerfTest.NoExtensionData()) + end + end) + $teardown_expr + $setup_expr + $(if PerfTest.is_loaded(:AMDGPU) + addLog("general", "[AMDGPU] Measuring target \"$(expr)\"") + quote + @info PerfTest.amdgpu_devices() + energy, power = $(PerfTest.gpuPowerMeasureAMD(expr, name)) + push!(extensions, PerfTest.AMDGPUExtensionData(energy, power)) + end + else + quote + push!(extensions, PerfTest.NoExtensionData()) + end + end) + $teardown_expr + test_res = Test_Result($name, extensions) + ts.test_results[$name] = test_res # Regression logic - keys = $([i.set_name for i in context._local.depth_record]) + keys = $(Expr(:vect, regression_key_elems...)) append!(keys, [$name]) old_test_res = _PRFT_GLOBALS.old for key in keys @@ -113,17 +195,11 @@ function transformPerftest(input_expr::Expr, context::Context) break end end - # Store additional data + # LEGACY DEPRECATION test_res.primitives[:autoflop] = $( - if Configuration.CONFIG["general"]["autoflops"] - quote - PRFTflop(@PRFTCount_ops ($parsed_target)) - end - else quote 0 end - end ) # Capture output and return value @@ -133,7 +209,7 @@ function transformPerftest(input_expr::Expr, context::Context) # Calculate metric snapshot buildPrimitiveMetrics!($mode, ts, test_res) - $(buildCustomMetrics(context._local.custom_metrics)) + $(buildCustomMetrics(context._local.custom_metrics, context)) # Compute performance test based on enabled methodologies if main_rank($mode) @@ -145,3 +221,11 @@ function transformPerftest(input_expr::Expr, context::Context) end end + +# TODO +var"@PRFTBenchmark" = BenchmarkTools.var"@benchmark" +PRFTBenchmarkGroup = BenchmarkTools.BenchmarkGroup +using Suppressor +var"@PRFTSuppress" = Suppressor.var"@suppress" +var"@PRFTCapture_out" = Suppressor.var"@capture_out" +var"@_prftest" = Test.var"@test" diff --git a/src/transform/parsing/hierarchy_transform_benchmark_region.jl b/src/transform/parsing/hierarchy_transform_benchmark_region.jl deleted file mode 100644 index f4b3de8..0000000 --- a/src/transform/parsing/hierarchy_transform_benchmark_region.jl +++ /dev/null @@ -1,179 +0,0 @@ -function testsetToBenchGroup!(input_expr :: Expr, context :: Context) - - # Get the elements of interest from the macrocall - @capture(input_expr, @testset properties__ test_block_) ? Nothing : error("Incompatible testset syntax \n"); - - # Get the name from the list of elements of the testset macrocall - name = metaGetString(properties); - - # Check if there is a for loop over the testset - theres_for = @capture(test_block, for a_ in b_ - inner_block_ - end) - - # Update context: add depth level - rec = DepthEntry(name, theres_for ? Pair(a,b) : nothing, 0) - push!(context._local.depth_record, rec) - push!(context._local.custom_metrics, CustomMetric[]) - push!(context._local.enabled_methodologies, MethodologyParameters[]) - # Launch regression methodology by default - onRegressionDefinition(quote end, context, Dict()) - # Debug info - addLog("hierarchy", "[BNCH] New Group: $([i.set_name for i in context._local.depth_record])") - - # Update context: add new level to the tree - updateTestTreeDownwards!(context.test_tree_expr_builder) - if theres_for - @capture(test_block, for a_ in b_ - inner_block_ - end) - - return length(context._local.depth_record) > 1 ? - :( - for $a in $b - # For a s - _PRFT_LOCAL_SUITE[$name * "_" * string($a)] = PRFTBenchmarkGroup(); - _PRFT_LOCAL_ADDITIONAL[$name * "_" * string($a)] = Dict(); - _PRFT_LOCAL_ADDITIONAL[$name * "_" * string($a)][:iterator] = $a; - _PRFT_LOCAL_ADDITIONAL[$name*"_"*string($a)][:exported] = copy(_PRFT_LOCAL_ADDITIONAL[:exported]) - let _PRFT_LOCAL_SUITE = _PRFT_LOCAL_SUITE[$name*"_"*string($a)], _PRFT_LOCAL_ADDITIONAL = _PRFT_LOCAL_ADDITIONAL[$name*"_"*string($a)] - $inner_block - end - :__BACK_CONTEXT__ - end - ) : - :( - :__PERFTEST_FW__; - for $a in $b - _PRFT_LOCAL_SUITE[$name*"_"*string($a)] = PRFTBenchmarkGroup() - _PRFT_LOCAL_ADDITIONAL[$name*"_"*string($a)] = Dict() - _PRFT_LOCAL_ADDITIONAL[$name*"_"*string($a)][:exported] = Dict{Symbol,Any}() - let _PRFT_LOCAL_SUITE = _PRFT_LOCAL_SUITE[$name * "_" * string($a)], _PRFT_LOCAL_ADDITIONAL = _PRFT_LOCAL_ADDITIONAL[$name * "_" * string($a)] - $inner_block - end; - :__BACK_CONTEXT__; - end; - :__PERFTEST_AFTER__ - ) - else - # Return the substitution - return length(context._local.depth_record) > 1 ? - :( - _PRFT_LOCAL_SUITE[$name] = PRFTBenchmarkGroup(); - _PRFT_LOCAL_ADDITIONAL[$name] = Dict(); - _PRFT_LOCAL_ADDITIONAL[$name][:exported] = copy(_PRFT_LOCAL_ADDITIONAL[:exported]); - let _PRFT_LOCAL_SUITE = _PRFT_LOCAL_SUITE[$name], _PRFT_LOCAL_ADDITIONAL = _PRFT_LOCAL_ADDITIONAL[$name] - $test_block - end; - - :__BACK_CONTEXT__ - ) : - :( - :__PERFTEST_FW__; - - _PRFT_LOCAL_SUITE[$name] = PRFTBenchmarkGroup(); - _PRFT_LOCAL_ADDITIONAL[$name] = Dict(); - _PRFT_LOCAL_ADDITIONAL[$name][:exported] = Dict{Symbol,Any}(); - let _PRFT_LOCAL_SUITE = _PRFT_LOCAL_SUITE[$name], _PRFT_LOCAL_ADDITIONAL = _PRFT_LOCAL_ADDITIONAL[$name] - $test_block - end; - - :__BACK_CONTEXT__; - :__PERFTEST_AFTER__ - ) - end - -end - -function backTokenToContextUpdate!(input_expr::QuoteNode, context::Context) - - - # NOTE if CONFIG.recursive && context._global.in_recursion && length(context._local.depth_record) == 1 - # return nothing; - #end - - # Check if inside a for loop - #if last(context._local.depth_record).for_loop !== nothing - # Update context: consolidate tree level - - #updateTestTreeUpwardsFor!(context.test_tree_expr_builder, - # context._local.depth_record[end].set_name, context) - #else - # updateTestTreeUpwards!(context.test_tree_expr_builder, - # context._local.depth_record[end].set_name, context._global.in_recursion) - #end - # Update context: delete depth level - pop!(context._local.depth_record) - pop!(context._local.custom_metrics) - pop!(context._local.enabled_methodologies) - - addLog("hierarchy", "[TESTSET] Exiting group") - return nothing; -end - -""" - DEPRECATED: PENDING REMOVAL -""" -function perftestToBenchmark!(input_expr::Expr, context::Context) - # Get the elements of interest from the macrocall - @capture(input_expr, @perftest prop__ expr_) - num = (context._local.depth_record[end].test_count += 1) - name = "Test $num" - - # Update context: create expression on tree builder - updateTestTreeSideways!(context, name) - - parsed_target = parseTarget(expr, context) - - iterator = let loop = (context._local.depth_record[end]).for_loop - loop isa Nothing ? nothing : loop.first - end - - addLog("hierarchy", "[BNCH] New Test: $name \"$expr\" @ $([i.set_name for i in context._local.depth_record])") - - # Return the substitution and setup the in target flag deactivator - return quote - _PRFT_LOCAL_ADDITIONAL[$name] = Dict() - _PRFT_LOCAL_ADDITIONAL[$name][:exported] = _PRFT_LOCAL_ADDITIONAL[:exported] - _PRFT_LOCAL_ADDITIONAL[$name][:iterator] = $(iterator) - $(if Configuration.CONFIG["general"]["suppress_output"] - quote - @PRFTSuppress begin - _PRFT_LOCAL_SUITE[$name] = @PRFTBenchmark($parsed_target ,$(prop...)) - _PRFT_LOCAL_ADDITIONAL[$name][:autoflop] = $( - if Configuration.CONFIG["general"]["autoflops"] - quote PRFTflop(@PRFTCount_ops ($parsed_target)) end - else - quote 0 end - end - ) - end - end - else - quote - _PRFT_LOCAL_SUITE[$name] = @PRFTBenchmark($parsed_target, $(prop...)); - _PRFT_LOCAL_ADDITIONAL[$name][:autoflop] = $( - if Configuration.CONFIG["general"]["autoflops"] - quote PRFTflop(@PRFTCount_ops ($parsed_target)) end - else - quote 0 end - end - ) - end - end) - - _PRFT_LOCAL_ADDITIONAL[$name][:printed_output] = - @PRFTCapture_out _PRFT_LOCAL_ADDITIONAL[$name][:ret_value] = $expr; - end -end - -# TODO -var"@PRFTBenchmark" = BenchmarkTools.var"@benchmark" -PRFTBenchmarkGroup = BenchmarkTools.BenchmarkGroup -using Suppressor -var"@PRFTSuppress" = Suppressor.var"@suppress" -var"@PRFTCapture_out" = Suppressor.var"@capture_out" -using CountFlops -var"@PRFTCount_ops" = CountFlops.var"@count_ops" -var"@_prftest" = Test.var"@test" -PRFTflop = CountFlops.flop diff --git a/src/transform/parsing/hierarchy_transform_test_region.jl b/src/transform/parsing/hierarchy_transform_test_region.jl deleted file mode 100644 index 339bf31..0000000 --- a/src/transform/parsing/hierarchy_transform_test_region.jl +++ /dev/null @@ -1,144 +0,0 @@ -# The tree builder is a stack used to construct the test region -# 3 DIRECTIONS -# DOWNWARDS : a new testset level is parsed -> a new test level is created (new top of stack) -# SIDEWAY : a test is parsed -> test is added to the level (top of stack) -# UPWARDS : the level has been fully parsed -> the test level is pushed into the previous level (top of stack merged with previous and then top is popped) -# When all levels have been pushed, just one element will be left in the tree builder, the final test region - -# Builds a tree from the ground up -function updateTestTreeUpwards!(tree_builder :: AbstractArray, name :: Union{String, Expr}, recursion :: Bool) - - # Get depth level - depth = length(tree_builder) - - # Concatenate expressions of the current level into a new node on the upper level - concat = :(begin end) - - - for expr in tree_builder[depth] - concat = :($concat; $expr) - end - - if depth > 1 - - push!(tree_builder[depth-1], - quote - @testset $name (showtiming = false) begin - $(newLocalScope(name, concat)) - end - end - ) - - # Delete last level - pop!(tree_builder) - else - - if recursion - - pop!(tree_builder) - push!(tree_builder, Expr[ - quote - @testset $name (showtiming = false) begin - $(newLocalScope(name, concat)) - end - end - ]) - else - - pop!(tree_builder) - push!(tree_builder, Expr[ - quote - tt[$name] = (@testset $name (showtiming = false) begin - $(newLocalScope(name, concat)) - end) - end - ]) - - end - end - - addLog("hierarchy", "[TESTS] Exiting $name at depth $depth") -end - - -function updateTestTreeUpwardsFor!(tree_builder::AbstractArray, name::Union{String,Expr}, context :: Context) - - # Get depth level - depth = length(tree_builder) - - # Concatenate expressions of the current level into a new node on the upper level - concat = :(begin end) - - for expr in tree_builder[depth] - concat = :($concat; $expr) - end - - i,n = last(context._local.depth_record).for_loop - - if depth > 1 - push!(tree_builder[depth-1], - quote - @testset $name (showtiming = false) for $i in $n - $(newLocalScopeFor(name, i, concat)) - end - end - ) - # Delete last level - pop!(tree_builder) - else - pop!(tree_builder) - if context._global.in_recursion - push!(tree_builder, Expr[ - quote - tt[$name] = (@testset $name (showtiming = false) for $i in $n - $(newLocalScopeFor(name, i, concat)) - end) - end - ]) - else - push!(tree_builder, Expr[ - quote - tt[$name] = (@testset $name (showtiming = false) for $i in $n - $(newLocalScopeFor(name, i, concat)) - end) - end - ]) - end - end - - addLog("hierarchy", "[TESTS] Exiting $name (has loop)") -end - -function updateTestTreeDownwards!(tree_builder :: AbstractArray) - # Add new level - push!(tree_builder, Expr[]) - - addLog("hierarchy", "[TESTS] Entering testgroup") -end - -function updateTestTreeSideways!(context::Context, name::String) - - # Get depth level - depth = length(context.test_tree_expr_builder) - # Add the expression to the tree builder - push!(context.test_tree_expr_builder[depth], - newLocalScope(name, - quote - PerfTest.printDepth!(_PRFT_LOCAL[:depth]) - # Metric calc - buildPrimitiveMetrics!($mode, _PRFT_LOCAL, _PRFT_GLOBAL) # See primitives.jl - # Only one rank does the testing - if _PRFT_GLOBAL[:is_main_rank] - d = by_index(_PRFT_GLOBAL[:new], _PRFT_LOCAL[:depth][1:(end-1)]) - d[_PRFT_LOCAL[:depth][end].name] = Test_Result() - savePrimitives(_PRFT_LOCAL,_PRFT_GLOBAL) - $(buildCustomMetrics(context._local.custom_metrics)) - # Methodology evaluation - $(buildMemTRPTMethodology(context)) - $(buildRoofline(context)) - $(buildPerfcmp(context)) - $(buildRegression(context)) - - end - end)) -end diff --git a/src/transform/parsing/rules.jl b/src/transform/parsing/rules.jl index a3ccf13..af23c89 100644 --- a/src/transform/parsing/rules.jl +++ b/src/transform/parsing/rules.jl @@ -96,6 +96,12 @@ perftest_scope_vecf_arg_macro_rule = ASTRule( (x, ctx, info) -> scopeVecFArg(x, ctx) ) +perftest_scope_ref_rule = ASTRule( + x -> @capture(x, _[__]), + no_validation, + (x, ctx, info) -> scopeRef(x, ctx) +) + perftest_dot_interpolation_rule = ASTRule( x -> @capture(x, _._), no_validation, @@ -189,7 +195,7 @@ auxiliary_metric_rule = ASTRule( define_benchmark_rule = ASTRule( x -> escCaptureGetblock(x, Symbol("@define_benchmark")) !== nothing, - define_metric_validation, + define_benchmark_validation, (x, ctx, info) -> defineCustomBenchmark(ctx, info) ) @@ -221,21 +227,29 @@ function treeRunRecursive!(path::AbstractString, parent_context::Context)::Exten input_expr = loadFileAsExpr(path) - # A new context is made for the included file, the configuration is cloned so it can be altered by the included file without affecting the parent file - push!(Configuration.PARENT_CONFIGS, deepcopy(Configuration.CONFIG)) + # A new context is made for the included file ctx = Context(GlobalContext(path, VecErrorCollection(), formula_symbols, :RECURSIVE)) ctx._local = parent_context._local - # Run through AST and build new expressions - middle = _treeRun(input_expr, ctx) + # Run through AST and build new expressions, the configuration is cloned so it can be altered by the included file + # without affecting the parent file, which gets it back even if this throws + Configuration.push_config() + middle = try + _treeRun(input_expr, ctx) + finally + Configuration.pop_config() + end importErrors!(parent_context._global.errors, ctx._global.errors, path) - - Configuration.CONFIG = pop!(Configuration.PARENT_CONFIGS) addLog("hierarchy", "[RECURSIVE] \"$path\" has been processed, $(num_errors(ctx)) errors found") - return middle + # The generated suite does the same around the part of the included file + return quote + PerfTest.Configuration.push_config() + $middle + PerfTest.Configuration.pop_config() + end end # RECURSIVE diff --git a/src/transform/parsing/target_transform.jl b/src/transform/parsing/target_transform.jl index 7ba8de4..4fd541b 100644 --- a/src/transform/parsing/target_transform.jl +++ b/src/transform/parsing/target_transform.jl @@ -50,6 +50,16 @@ function scopeVecFArg(input_expr::Expr, context::Context)::Expr return Expr(:., f, Expr(:tuple, processed_args...)) end +function scopeRef(input_expr::Expr, context::Context)::Expr + # Indexing inside a benchmark target, the collection and the index symbols are interpolated to reach values stored in local scopes (e.g. loop variables) + + @capture(input_expr, a_[idx__]) + + interp(s) = isa(s, Symbol) && s ∉ (:end, :begin) ? Expr(:$, s) : s + + return Expr(:ref, interp(a), map(interp, idx)...) +end + function scopeDotInterpolation(input_expr::Expr, context::Context)::Expr # If inside a benchmark target, the left side of the dot is interpolated to prevent failure reaching values stored in local scopes diff --git a/src/transform/prefix.jl b/src/transform/prefix.jl index 46d3fa5..0bc80f1 100644 --- a/src/transform/prefix.jl +++ b/src/transform/prefix.jl @@ -3,22 +3,19 @@ function perftestprefix(ctx::Context)::Expr suite_name = "$(basename(ctx._global.original_file_path))_PERFORMANCE" - if isdir("./$(Configuration.CONFIG["general"]["save_folder"])") - else - mkdir("./$(Configuration.CONFIG["general"]["save_folder"])") - end - return quote using Test, Dates $(mode == MPIMode ? :(using MPI; PerfTest.MPISetup(PerfTest.MPIMode)) : :(nothing)) - using PerfTest: DepthRecord, Metric_Test, Methodology_Result, StrOrSym, Metric_Result, magnitudeAdjust, MPISetup, newMetricResult, buildPrimitiveMetrics!, measureCPUPeakFlops!, measureMemBandwidth!, addLog, @PRFTBenchmark, PRFTBenchmarkGroup, @PRFTCapture_out, @PRFTCount_ops, PRFTflop, @PRFTSuppress, Test_Result, by_index, regression, Suite_Execution_Result, savePrimitives, main_rank, GlobalSuiteData, @perftestset, PerfTestSet, extractTestResults, saveMethodologyData, Configuration + $(PerfTest.is_loaded(:Perftest_LIKWIDExt) ? quote using LIKWID end : quote end) + using PerfTest: DepthRecord, Metric_Test, Methodology_Result, StrOrSym, Metric_Result, magnitudeAdjust, MPISetup, newMetricResult, buildPrimitiveMetrics!, measureCPUPeakFlops!, measureMemBandwidth!, addLog, @PRFTBenchmark, PRFTBenchmarkGroup, @PRFTCapture_out, @PRFTSuppress, Test_Result, by_index, regression, Suite_Execution_Result, savePrimitives, main_rank, GlobalSuiteData, @perftestset, PerfTestSet, extractTestResults, saveMethodologyData, Configuration, metricSampledValue, SampledValue _t_begin = time() _GLOBAL_MODE = $mode if main_rank($mode) - # Used to save data about this test suite if needed - path = $("./$(Configuration.CONFIG["general"]["save_folder"])/$(suite_name).JLD2") + # Used to save data about this test suite if needed, its folder is created when the results are saved. + # Read on execution, so an interpolated save_folder takes its value + path = "./" * Configuration.CONFIG["general"]["save_folder"] * $("/$(suite_name).JLD2") nofile = true if isfile(path) @@ -62,9 +59,5 @@ function perftestprefix(ctx::Context)::Expr # Do machine probe $(machineBenchmarks(mode, ctx)) - # Methodology prefixes - #$(regressionPrefix(ctx)) - #$(effMemThroughputPrefix(ctx)) - end end diff --git a/src/transform/suffix.jl b/src/transform/suffix.jl index 776927f..8026156 100644 --- a/src/transform/suffix.jl +++ b/src/transform/suffix.jl @@ -1,152 +1,3 @@ - -### SUFFIX FILLER -# function perftextsuffix2(context :: Context) -# return quote -# suite = _PRFT_LOCAL_SUITE - -# # Deal with recorder results -# res_num = length(_PRFT_GLOBAL[:datafile].results) - -# if (excess = $(Configuration.CONFIG["max_saved_results"]) - res_num) <= 0 -# PerfTest.p_yellow("[ℹ]") -# s = " Regression: Exceeded maximum recorded results. The oldest $(-1*excess + 1) result/s will be removed." -# println(s) -# addLog("general",s) -# for i in 1:(-1*excess+1) -# popfirst!(_PRFT_GLOBAL[:datafile].results) -# end -# end - -# # CALCULATE REFERENCE BENCHMARKS IF NEEDED -# $(if true # effective_memory_throughput.enabled || roofline.enabled -# setupMemoryBandwidthBenchmark() -# end) -# $(if Configuration.CONFIG["roofline"]["enabled"] -# setupCPUPeakFlopBenchmark() -# end) - -# # Trial Estimates -# median_suite = median(suite) -# min_suite = minimum(suite) - -# # Methodology suffixes -# $(regressionSuffix(context)) - -# # Compose the serializable data structure for this execution -# current_result = PerfTest.Perftest_Result(timestamp=time(), -# benchmarks=l, -# perftests=Dict()) - -# push!(_PRFT_GLOBAL[:datafile].results, current_result) -# PerfTest.p_yellow("[ℹ]") -# println(" Regression: A perfomance reference has been registered.") -# # TODO -# failed = false -# # Test set hierarchy root -# depth = PerfTest.DepthRecord[] -# current_test_results = Dict{PerfTest.StrOrSym, Any}() -# tt = Dict() -# try -# # Test set hierarchy -# $(context.test_tree_expr_builder[1][1]) -# catch e -# @warn "One or more performance tests have failed" -# failed = true -# end - -# $( -# if Configuration.CONFIG["save_results"] -# quote -# push!(_PRFT_GLOBAL[:datafile].methodologies_history, current_test_results) -# end -# end -# ) - -# if !failed -# PerfTest.saveDataFile(path, data) -# end - -# println("[✓] $path Performance tests have been finished") -# end -# end - -""" - DEPRECATED: PENDING REMOVAL -""" -function oldperftestsuffix(context :: Context) - return quote - # Local scope on the lowest level == Global scope - _PRFT_GLOBAL[:suite] = _PRFT_LOCAL_SUITE - _PRFT_GLOBAL[:additional] = _PRFT_LOCAL_ADDITIONAL - - # TODO Inyect globally defined metrics - - # Trial Estimates - #median_suite = median(_PRFT_GLOBAL[:suite]) - #min_suite = minimum(_PRFT_GLOBAL[:suite]) - - # Methodology suffixes - #$(regressionSuffix(context)) - - if _PRFT_GLOBAL[:is_main_rank] - # Deal with recorder results - let - res_num = length(_PRFT_GLOBAL[:datafile].results) - - if (excess = $(Configuration.CONFIG["general"]["max_saved_results"]) - res_num) <= 0 - PerfTest.p_yellow("[ℹ]") - println(" Regression: Exceeded maximum recorded results. The oldest $(-1*excess + 1) result/s will be removed.") - for i in 1:(-1*excess+1) - popfirst!(_PRFT_GLOBAL[:datafile].results) - end - end - - if length(_PRFT_GLOBAL[:datafile].results) > 0 - _PRFT_GLOBAL[:old] = _PRFT_GLOBAL[:datafile].results[end].perftests - else - _PRFT_GLOBAL[:old] = nothing - end - _PRFT_GLOBAL[:new] = Dict{String,Union{Dict, Test_Result}}() - end - - end - - #println(" Regression: A perfomance reference has been registered.") - # TODO free vars - failed = false - # Test set hierarchy root - _PRFT_LOCAL = Dict{StrOrSym,Any}() - _PRFT_LOCAL[:depth] = PerfTest.DepthRecord[] - _PRFT_LOCAL[:results] = Dict{PerfTest.StrOrSym,Any}() - _PRFT_LOCAL[:additional] = _PRFT_GLOBAL[:additional] - _PRFT_LOCAL[:suite] = _PRFT_GLOBAL[:suite] - tt = Dict() - try - # HERE THE TESTSETS ARE PUT - Test set hierarchy - $(context.test_tree_expr_builder[1][1]) - catch e - @warn "One or more performance tests have failed" - failed = true - end - - if _PRFT_GLOBAL[:is_main_rank] - # Save new results - newres = Suite_Execution_Result( - timestamp= datetime2unix(now()), - benchmarks = _PRFT_GLOBAL[:suite], - perftests = _PRFT_GLOBAL[:new] - ) - push!(_PRFT_GLOBAL[:datafile].results, newres) - - if !failed - PerfTest.saveDataFile(path, _PRFT_GLOBAL[:datafile]) - end - println("[✓] $path Performance tests have been finished") - end - - end -end - """ Builds the Julia expression that goes after the performance tests, it registers, prints and saves results given the measurements done above it. """ @@ -154,11 +5,15 @@ function perftestsuffix(context :: Context) return quote if main_rank($mode) + #@info TS + testresdict = Dict{String,Union{Dict,Test_Result}}() + # A top level `@testset ... for` gives the testset of each iteration, each one is saved under its name and + # iterator as a nested loop testset is (see extractTestResults), which the regression lookup keys follow if TS isa Vector benchmarks = PerfTest.newBenchmarkGroup() for ts in TS - testresdict[ts.description * "_" * string(ts.iterator)] = extractTestResults(TS) + testresdict[ts.description * "_" * string(ts.iterator)] = extractTestResults(ts) benchmarks[ts.description * "_" *string(ts.iterator)] = ts.benchmarks end # Save new results @@ -181,8 +36,12 @@ function perftestsuffix(context :: Context) ) end + # Configuration.CONFIG is here the configuration the suite was generated with, as it stands at this point + # of the recipe (see treeRun) + if !PerfTest.testsSucceeded(TS) + println("Some tests failed or errored.") # No fails no errors, regression enabled and different regression file path - if PerfTest.testsSucceeded(TS) && Configuration.CONFIG["regression"]["enabled"] && regression_path != _PRFT_GLOBALS.datafile_path + elseif Configuration.CONFIG["general"]["save_results"] && Configuration.CONFIG["regression"]["enabled"] && regression_path != _PRFT_GLOBALS.datafile_path println("All performance tests have passed. Values will be registered as reference for regression testing.") push!(regression_file.results, newres) # Deal with recorded results @@ -197,25 +56,28 @@ function perftestsuffix(context :: Context) end end PerfTest.saveDataFile(regression_path, regression_file) - else - println("Some tests failed or errored.") - end - # Deal with recorded results - let - push!(_PRFT_GLOBALS.datafile.results, newres) - res_num = length(_PRFT_GLOBALS.datafile.results) + end + # Kept in memory even when it is not saved, e.g. for the Bencher export below + push!(_PRFT_GLOBALS.datafile.results, newres) + if Configuration.CONFIG["general"]["save_results"] + # Deal with recorded results + let + res_num = length(_PRFT_GLOBALS.datafile.results) - if (excess = $(Configuration.CONFIG["general"]["max_saved_results"]) - res_num) <= 0 - PerfTest.p_yellow("[ℹ]") - println(" Results File: Exceeded maximum recorded results. The oldest $(-1*excess + 1) result/s will be removed.") - for i in 1:(-1*excess+1) - popfirst!(_PRFT_GLOBALS.datafile.results) + if (excess = $(Configuration.CONFIG["general"]["max_saved_results"]) - res_num) <= 0 + PerfTest.p_yellow("[ℹ]") + println(" Results File: Exceeded maximum recorded results. The oldest $(-1*excess + 1) result/s will be removed.") + for i in 1:(-1*excess+1) + popfirst!(_PRFT_GLOBALS.datafile.results) + end end end + # Export as json + #BencherInterface.exportToJSON(_PRFT_GLOBALS.datafile_path * ".json", newres) + PerfTest.saveDataFile(_PRFT_GLOBALS.datafile_path, _PRFT_GLOBALS.datafile) + else + println("The results of this execution have not been saved (general.save_results is false).") end - # Export as json - #BencherInterface.exportToJSON(_PRFT_GLOBALS.datafile_path * ".json", newres) - PerfTest.saveDataFile(_PRFT_GLOBALS.datafile_path, _PRFT_GLOBALS.datafile) println("[✓] $path Performance tests have been finished (elapsed $(newres.elapsed) s)") # Bencher export using the REST API diff --git a/src/transform/validation/formula.jl b/src/transform/validation/formula.jl index 23adb83..7dce217 100644 --- a/src/transform/validation/formula.jl +++ b/src/transform/validation/formula.jl @@ -12,20 +12,73 @@ formula_symbols = Set([ :peak_bandwidth, ]) +# Automatic flop counting is outdated: the :autoflop primitive is always 0 (see transformPerftest), so every use of it +# (general.autoflops = true for a @roofline without actual_flops, or :autoflop in a formula or as a metric) is reported +# as a parse error, see reportAutoflopUse! +AUTOFLOP_UNSUPPORTED = "Automatic flop counting is outdated and not supported, the :autoflop primitive is always 0." +AUTOFLOP_INSTEAD = "Give the flop count of the target explicitly instead: pass it to @roofline with actual_flops (a " * + "number, or a formula as its operational intensity one), or write it in the formula in place of :autoflop." + +# Whether a formula, as written in the recipe, uses the :autoflop primitive, e.g. `:autoflop / :median_time` +usesAutoflop(x::QuoteNode) = x.value === :autoflop +usesAutoflop(x::Expr) = any(usesAutoflop, x.args) +usesAutoflop(x) = false + +""" +Report as a parse error that `construct` (e.g. "The @define_metric name = \"m\""), of the recipe being transformed, +uses automatic flop counting `how` (e.g. "uses :autoflop in its formula"), which is not supported, see +AUTOFLOP_UNSUPPORTED. `instead` says what to do instead. +""" +function reportAutoflopUse!(construct::AbstractString, how::AbstractString, ctx; instead::AbstractString = AUTOFLOP_INSTEAD) + throwParseError!("$construct of recipe $(ctx._global.original_file_path) $how. $AUTOFLOP_UNSUPPORTED $instead", ctx) +end + +function formulaGetTime(properties::Vector{Symbol}) + if length(properties) == 0 || properties[1] == :median + return quote test_res.primitives[:median_time] end + elseif properties[1] == :min + return quote test_res.primitives[:min_time] end + else + error("Invalid time property: $(properties[1]). Valid options are :median and :min.") + end +end + +newSymbols(x::Val{:time}) = formulaGetTime +newSymbols(x::Val) = error("Unrecognized $x.") + function SBMID(metric :: metricID()) sym = metricID(metric) - if sym in formula_symbols - return quote _PRFT_GLOBALS.builtins[$(QuoteNode(sym))] end + # Reads go through PerfTest.metricSampledValue (not the bare .value field) so a metric + # that carries a variance (see execution/variance.jl) keeps propagating it through + # whatever arithmetic the surrounding formula performs. + return quote (haskey(_PRFT_GLOBALS.custom_benchmarks,$(QuoteNode(sym))) ? + PerfTest.metricSampledValue(_PRFT_GLOBALS.custom_benchmarks[$(QuoteNode(sym))]) : + haskey(_PRFT_GLOBALS.builtins, $(QuoteNode(sym))) ? + _PRFT_GLOBALS.builtins[$(QuoteNode(sym))] : + haskey(test_res.metrics,$(QuoteNode(sym))) ? + PerfTest.metricSampledValue(test_res.metrics[$(QuoteNode(sym))]) : + haskey(test_res.auxiliar,$(QuoteNode(sym))) ? + PerfTest.metricSampledValue(test_res.auxiliar[$(QuoteNode(sym))]) : + newSymbols(Val($(QuoteNode(sym))))(Symbol[])) + end +end + +# WARNING, WIP missing error prints for some cases +function SBMID(::Val{:LIKWID}, properties :: Vector{Symbol}) + if is_loaded(:LIKWID) + if properties[1] == :METRICS + return quote likwidMetricsRetrieve(test_res, $(properties[2]), $(properties[3])) end + elseif properties[1] == :EVENTS + return quote likwidEventsRetrieve(test_res, $(properties[2]), $(properties[3])) end + else + error("Invalid selector: $(properties[1]). Valid options are :METRICS and :EVENTS.") + end else - return quote (haskey(_PRFT_GLOBALS.custom_benchmarks,$(QuoteNode(sym))) ? - _PRFT_GLOBALS.custom_benchmarks[$(QuoteNode(sym))].value : - haskey(_PRFT_GLOBALS.builtins, $(QuoteNode(sym))) ? - _PRFT_GLOBALS.builtins[$(QuoteNode(sym))] : - haskey(test_res.metrics,$(QuoteNode(sym))) ? - test_res.metrics[$(QuoteNode(sym))].value : - haskey(test_res.auxiliar,$(QuoteNode(sym))) ? - test_res.auxiliar[$(QuoteNode(sym))].value : - error("Undefined $($(QuoteNode(sym))), wrong spelling or not defined in the current context?")) - end + error("LIKWID is not loaded. Cannot use LIKWID metrics.") end end + +function SBMID(metric :: Symbol, properties :: Vector{Symbol}) + expr = newSymbols(Val(metric))(properties) + return expr +end diff --git a/src/transform/validation/macro.jl b/src/transform/validation/macro.jl index ace9f46..71d4eaf 100644 --- a/src/transform/validation/macro.jl +++ b/src/transform/validation/macro.jl @@ -35,9 +35,15 @@ function validateMacro(macro_param :: Dict{Symbol, MacroParameter}) ($a = $b) => begin if haskey(macro_param, a) param_info = macro_param[a] - if param_info.type >: typeof(b) - if param_info.param_validation_function(b) - parsed_params[a] = b + matched, value = if param_info.type >: typeof(b) + true, b + else + resolved = resolveLiteral(b) + typeMatches(param_info.type, resolved) ? (true, resolved) : (false, b) + end + if matched + if param_info.param_validation_function(value) + parsed_params[a] = value push!(checklist, a) else # Invalid parameter value @@ -64,7 +70,11 @@ function validateMacro(macro_param :: Dict{Symbol, MacroParameter}) ($a = $b) => (throwParseError!("Last parameter cannot be a keyword ($a) parameter on macro $m",context); return nothing) $_ => nothing end - if typeof(param) <: param_info.type + # An interpolated string ("...$(x)...") parses as Expr(:string, ...) + # rather than String; accept it wherever a String is declared, since + # it will evaluate to a String once the interpolation is resolved. + interpolated_string = param isa Expr && param.head === :string + if typeof(param) <: param_info.type || (param_info.type >: String && interpolated_string) if param_info.param_validation_function(param) parsed_params[Symbol("")] = param push!(checklist, Symbol("")) @@ -126,9 +136,15 @@ function validateBlocklessMacro(macro_param::Dict{Symbol,MacroParameter}) ($a = $b) => begin if haskey(macro_param, a) param_info = macro_param[a] - if param_info.type >: typeof(b) - if param_info.param_validation_function(b) - parsed_params[a] = b + matched, value = if param_info.type >: typeof(b) + true, b + else + resolved = resolveLiteral(b) + typeMatches(param_info.type, resolved) ? (true, resolved) : (false, b) + end + if matched + if param_info.param_validation_function(value) + parsed_params[a] = value push!(checklist, a) else # Invalid parameter value diff --git a/test/.DS_Store b/test/.DS_Store deleted file mode 100644 index ec9234e..0000000 Binary files a/test/.DS_Store and /dev/null differ diff --git a/test/runtests.jl b/test/runtests.jl index 95c5878..e946ad4 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -25,7 +25,7 @@ if !(PerfTest.Configuration.load_config() isa Nothing) try run(`$exename -O3 --startup-file=no $(joinpath(testdir, f))`) catch ex - nfail += 1 + global nfail += 1 end end @@ -35,5 +35,6 @@ if !(PerfTest.Configuration.load_config() isa Nothing) if nfail == 0 else printstyled("\n$nfail test(s) failed.\n"; bold=true, color=:red) + error("$nfail test file(s) failed.") end end \ No newline at end of file diff --git a/test/t1-validation-formula.jl b/test/t1-validation-formula.jl index faf27b4..a859bda 100644 --- a/test/t1-validation-formula.jl +++ b/test/t1-validation-formula.jl @@ -36,6 +36,42 @@ using PerfTest A.b(C.D) end) + form = quote + :time.median + end + r = PerfTest.transformFormula(form, ctx) + @test r == MacroTools.prettify(quote + test_res.primitives[:median_time] + end) + + form = quote + :penguin + end + r = PerfTest.transformFormula(form, ctx) + @test r == MacroTools.prettify(quote + if haskey(_PRFT_GLOBALS.custom_benchmarks, :penguin) + PerfTest.metricSampledValue(_PRFT_GLOBALS.custom_benchmarks[:penguin]) + else + if haskey(_PRFT_GLOBALS.builtins, :penguin) + _PRFT_GLOBALS.builtins[:penguin] + else + if haskey(test_res.metrics, :penguin) + PerfTest.metricSampledValue(test_res.metrics[:penguin]) + else + if haskey(test_res.auxiliar, :penguin) + PerfTest.metricSampledValue(test_res.auxiliar[:penguin]) + else + newSymbols(Val(:penguin))(Symbol[]) + end + end + end + end + end) + + form = quote + :LIKWID.EVENTS.FLOPS_DP.FP_ARITH_INST_RETIRED_128B_PACKED_SINGLE + end + @test_throws ErrorException PerfTest.transformFormula(form, ctx) #= # illegal symbol form = quote :aflops diff --git a/test/t10-configuration.jl b/test/t10-configuration.jl new file mode 100644 index 0000000..614d449 --- /dev/null +++ b/test/t10-configuration.jl @@ -0,0 +1,199 @@ +using Test +using PerfTest +using TOML + +const C = PerfTest.Configuration +recipe(name) = joinpath(@__DIR__, "test-recipes", name) + +# Every file based case runs in a fresh temporary directory, so test/perftest_config.toml is never touched +intempdir(f) = mktempdir(dir -> cd(f, dir)) + +const DEFAULT_SNAPSHOT = deepcopy(C.DEFAULT) +const PRECOMPILATION_SNAPSHOT = deepcopy(C.PRECOMPILATION_CONFIG) + +# Must run before anything else loads a configuration in this process +@testset "Configuration - state right after using PerfTest" begin + @test C.CONFIG !== C.PRECOMPILATION_CONFIG + @test C.CONFIG !== C.DEFAULT + @test C.CONFIG == C.DEFAULT + @test isempty(C.PARENT_CONFIGS) + @test PerfTest.ctx === nothing + @test PerfTest.LOG_FOLDER == "" + # The callbacks installed by the dummy transform reference ctx, they must not outlive it + @test PerfTest.Topology.addLog === PerfTest.Topology.defaultAddLog + @test PerfTest.Topology.throwParseError! === PerfTest.Topology.defaultThrowParseError! +end + +@testset "Configuration - PRECOMPILATION_CONFIG is valid" begin + @test @test_logs C.validate_config(C.PRECOMPILATION_CONFIG, C.CONFIG_SHAPE) + @test C.validate_config(C.DEFAULT, C.CONFIG_SHAPE) + + # The precompile workload swallows its errors, so its dummy transform is checked here + intempdir() do + PerfTest.init_dummy_flag = true + try + PerfTest.transform(joinpath(pkgdir(PerfTest), "src", "transform", "dummy.jl")) + @test PerfTest.num_errors() == 0 + @test C.CONFIG == C.PRECOMPILATION_CONFIG + @test C.CONFIG !== C.PRECOMPILATION_CONFIG + finally + PerfTest.init_dummy_flag = false + end + end +end + +@testset "Configuration - missing file is created with the defaults" begin + intempdir() do + cfg = @test_logs (:info, r"not found") C.load_config() + @test cfg == C.DEFAULT + @test TOML.parsefile(C.CONFIG_FILE) == C.DEFAULT + end +end + +@testset "Configuration - every transform starts from a fresh configuration" begin + intempdir() do + # Sets memory_bandwidth.default_threshold with @perftest_config + PerfTest.transform(recipe("ex15-recursive-config.jl")) + @test C.CONFIG["memory_bandwidth"]["default_threshold"] == 0.75 + + # As left behind by a transform that threw inside a recursive include + push!(C.PARENT_CONFIGS, deepcopy(C.CONFIG)) + + PerfTest.transform(recipe("ex1-hierarchy-basic.jl")) + @test C.CONFIG == C.DEFAULT + @test isempty(C.PARENT_CONFIGS) + end +end + +@testset "Configuration - included recipes layer their configuration over the parent's" begin + intempdir() do + # Value of regression.default_threshold before any recipe changes it + write(C.CONFIG_FILE, "[regression]\ndefault_threshold = 1.3\n") + + PerfTest.transform(recipe("ex15-recursive-config.jl")) + @test PerfTest.num_errors() == 0 + log = PerfTest.dumpLogsString() + + # Every top level testset gets a default regression, which uses regression.default_threshold + regression_th(set, th) = occursin("Defined REGRESSION on [\"$set\"] METRICS: [:median_time] TH: [$th]", log) + memory_th(set, th) = occursin("Defined Effective Memory Throughput on [\"$set\"] with benchmark MEM_STREAM_COPY and threshold $th\n", log) + + # Outer recipe: its own memory_bandwidth value, the file's regression value + @test memory_th("BEFORE", 0.75) + @test regression_th("BEFORE", 1.3) + # Included recipe: its values take priority + @test memory_th("INNER", 0.25) + @test regression_th("INNER", 2.5) + # Back in the outer recipe: both are restored + @test memory_th("AFTER", 0.75) + @test regression_th("AFTER", 1.3) + + @test C.CONFIG["memory_bandwidth"]["default_threshold"] == 0.75 + @test C.CONFIG["regression"]["default_threshold"] == 1.3 + @test isempty(C.PARENT_CONFIGS) + end +end + +@testset "Configuration - unparsable file is left untouched" begin + intempdir() do + broken = "# user comment\n[general]\nsave_folder = \".perftests\nverbose = 2\n" + write(C.CONFIG_FILE, broken) + + # A non default state that must not survive the failed load + C.load_config(Dict("general" => Dict("verbose" => 2))) + + cfg = @test_logs (:error, r"could not be parsed") C.load_config() + @test cfg == C.DEFAULT + @test read(C.CONFIG_FILE) == codeunits(broken) + + @test_logs (:error, r"could not be parsed") match_mode=:any PerfTest.transform(recipe("ex15-recursive-config.jl")) + @test_logs (:error, r"could not be parsed") match_mode=:any PerfTest.transform(recipe("ex1-hierarchy-basic.jl")) + @test C.CONFIG == C.DEFAULT + @test read(C.CONFIG_FILE) == codeunits(broken) + end +end + +@testset "Configuration - partial file is merged over the defaults" begin + intempdir() do + partial = "[general]\nmax_saved_results = 7\n[regression]\nenabled = false\n" + write(C.CONFIG_FILE, partial) + + expected = deepcopy(C.DEFAULT) + expected["general"]["max_saved_results"] = 7 + expected["regression"]["enabled"] = false + + cfg = @test_logs C.load_config() + @test cfg == expected + + # Both entry points used to crash on a partial file + PerfTest.transform(recipe("ex1-hierarchy-basic.jl")) + @test C.CONFIG == expected + + cp(recipe("ex1-hierarchy-basic.jl"), "recipe.jl") + runperftests("recipe.jl"; execute=false) + @test isfile("recipe_perfsuite.jl") + @test C.CONFIG == expected + + @test read(C.CONFIG_FILE, String) == partial + end +end + +@testset "Configuration - wrongly typed entries fall back to their default" begin + intempdir() do + write(C.CONFIG_FILE, """ + MPI = 3 + [general] + verbose = "2" + max_saved_results = 7 + [roofline] + default_threshold = "high" + """) + + cfg = @test_logs (:error, r"general\.verbose") (:error, r"roofline\.default_threshold") (:error, r"section MPI") match_mode=:any C.load_config() + + @test cfg["general"]["verbose"] == C.DEFAULT["general"]["verbose"] + @test cfg["general"]["max_saved_results"] == 7 + @test cfg["roofline"]["default_threshold"] == C.DEFAULT["roofline"]["default_threshold"] + @test cfg["MPI"] == C.DEFAULT["MPI"] + @test C.validate_config(cfg, C.CONFIG_SHAPE) + end +end + +@testset "Configuration - DEFAULT and PRECOMPILATION_CONFIG are never handed out" begin + intempdir() do + @test C.load_config() !== C.DEFAULT # no file yet + @test C.load_config() !== C.DEFAULT # file just created with the defaults + @test C.load_config(C.DEFAULT) !== C.DEFAULT + @test C.load_dummy_config() !== C.PRECOMPILATION_CONFIG + + # load_config(dict) keeps a copy of its argument + d = deepcopy(C.DEFAULT) + C.load_config(d) + d["general"]["verbose"] = 3 + @test C.CONFIG["general"]["verbose"] == 0 + + # merge_configs shares nothing with its arguments, even when it ignores part of the override + section = Dict("x" => 1) + merged = C.merge_configs(C.DEFAULT, Dict("newsec" => section)) + @test merged["newsec"] == section + @test merged["newsec"] !== section + # A wrongly typed key is ignored on its own, its siblings apply + partial = @test_logs (:error, r"general\.verbose") C.merge_configs(C.DEFAULT, Dict("general" => Dict("verbose" => "bad", "max_saved_results" => 2))) + @test partial["general"]["verbose"] == C.DEFAULT["general"]["verbose"] + @test partial["general"]["max_saved_results"] == 2 + @test partial !== C.DEFAULT + @test partial["general"] !== C.DEFAULT["general"] + + # Mutate everything that was handed out, then keep loading and transforming + for cfg in (C.load_config(), C.load_dummy_config(), merged, partial) + cfg["general"]["verbose"] = 3 + cfg["regression"]["enabled"] = false + end + PerfTest.transform(recipe("ex15-recursive-config.jl")) + PerfTest.transform(recipe("ex1-hierarchy-basic.jl"); config=Dict("general" => Dict("max_saved_results" => 2))) + C.load_config() + end + + @test C.DEFAULT == DEFAULT_SNAPSHOT + @test C.PRECOMPILATION_CONFIG == PRECOMPILATION_SNAPSHOT +end diff --git a/test/t11-config-generated-suite.jl b/test/t11-config-generated-suite.jl new file mode 100644 index 0000000..4b84924 --- /dev/null +++ b/test/t11-config-generated-suite.jl @@ -0,0 +1,311 @@ +using Test +using PerfTest +using TOML + +const C = PerfTest.Configuration +recipe(name) = joinpath(@__DIR__, "test-recipes", name) + +# Every file based case runs in a fresh temporary directory, so test/perftest_config.toml is never touched +intempdir(f) = mktempdir(dir -> cd(f, dir)) + +# Transforms a fixture recipe and saves the generated suite in the working directory +function generate(name) + suite = abspath(replace(name, r"\.jl$" => "_perfsuite.jl")) + PerfTest.saveExprAsFile(PerfTest.transform(recipe(name)), suite) + return suite +end + +# Executes a saved suite in a fresh process with `dir` as working directory, as runperftests does +function execute(suite, dir) + out = IOBuffer() + cmd = Cmd(`$(Base.julia_cmd()) --startup-file=no --project=$(Base.active_project()) $suite`; dir=dir) + ok = success(pipeline(cmd; stdout=out, stderr=out)) + output = String(take!(out)) + ok || println(output) + return ok, output +end + +# Configuration seen by the executing suite at a point of a fixture, see dumpConfig in the fixtures +dumped(dir, name) = TOML.parsefile(joinpath(dir, "config_$(name).toml")) + +# The default configuration with some (section, key, value) entries changed +function defaultWith(changes...) + config = deepcopy(C.DEFAULT) + for (section, key, value) in changes + config[section][key] = value + end + return config +end + +@testset "Generated suite - executes with the configuration it was generated with" begin + intempdir() do + write(C.CONFIG_FILE, """ + [general] + save_folder = "resultsA" + verbose = 1 + max_saved_results = 3 + [regression] + dedicated_reference_file = "refA.JLD2" + """) + generated = defaultWith(("general", "save_folder", "resultsA"), ("general", "verbose", 1), + ("general", "max_saved_results", 3), ("regression", "dedicated_reference_file", "refA.JLD2")) + + # No @perftest_config in the recipe + suite = generate("ex16-config-generated-suite.jl") + @test PerfTest.num_errors() == 0 + @test C.CONFIG == generated + # Transforming does not create the results folder + @test !ispath("resultsA") + + # Executed elsewhere, next to a different configuration file + mktempdir() do dir + other = "[general]\nsave_folder = \"resultsB\"\nverbose = 0\n[regression]\ndedicated_reference_file = \"refB.JLD2\"\n" + write(joinpath(dir, C.CONFIG_FILE), other) + + ok, out = execute(suite, dir) + @test ok + @test dumped(dir, "GENERATED") == generated + + # general.save_folder, regression.dedicated_reference_file and regression.enabled + @test isfile(joinpath(dir, "resultsA", "ex16-config-generated-suite.jl_PERFORMANCE.JLD2")) + @test isfile(joinpath(dir, "refA.JLD2")) + @test !ispath(joinpath(dir, "resultsB")) + @test !ispath(joinpath(dir, "refB.JLD2")) + @test !ispath(joinpath(dir, ".perftests")) + # general.verbose, used by the testset output and the logs + @test occursin("AT: GENERATED", out) + @test occursin("[MACHINE]", out) + + @test read(joinpath(dir, C.CONFIG_FILE), String) == other + end + end +end + +@testset "Generated suite - included recipes configure only their part of the executed suite" begin + intempdir() do + outer = defaultWith(("general", "max_saved_results", 11)) + inner = defaultWith(("general", "max_saved_results", 3), ("general", "verbose", 1)) + + suite = generate("ex17-config-recursive.jl") + @test PerfTest.num_errors() == 0 + @test C.CONFIG == outer + @test isempty(C.PARENT_CONFIGS) + + mktempdir() do dir + ok, out = execute(suite, dir) + @test ok + + @test dumped(dir, "BEFORE") == outer + @test dumped(dir, "INNER") == inner + # Back in the outer recipe, in the rest of the suite and after it + @test dumped(dir, "AFTER") == outer + @test dumped(dir, "END") == outer + + # general.verbose, used by the testset output + @test occursin("AT: INNER", out) + @test !occursin("AT: AFTER", out) + @test !occursin("AT: OUTER", out) + end + end +end + +@testset "Generated suite - interpolated keys take their value at execution" begin + intempdir() do + # The keys that are not interpolated take effect during the transform + generated = defaultWith(("general", "max_saved_results", 4), ("roofline", "default_threshold", 0.3)) + + suite = generate("ex18-config-interpolation.jl") + @test PerfTest.num_errors() == 0 + @test C.CONFIG == generated + + # No placeholder of the interpolated values, neither in the configuration nor in the suite + code = read(suite, String) + @test occursin("results_\$(tag)", code) + @test !occursin(r"results_(?!\$)", code) + @test !occursin(r"ref_(?!\$)", code) + @test !ispath("results_") + @test !ispath(".perftests") + + mktempdir() do dir + ok, out = execute(suite, dir) + @test ok + + executed = defaultWith(("general", "max_saved_results", 4), ("roofline", "default_threshold", 0.3), + ("general", "save_folder", "results_run2"), ("regression", "dedicated_reference_file", "ref_run2.JLD2")) + @test dumped(dir, "INTERPOLATION") == executed + + @test isfile(joinpath(dir, "results_run2", "ex18-config-interpolation.jl_PERFORMANCE.JLD2")) + @test isfile(joinpath(dir, "ref_run2.JLD2")) + @test !ispath(joinpath(dir, "results_")) + @test !ispath(joinpath(dir, "ref_.JLD2")) + @test !ispath(joinpath(dir, ".perftests")) + end + end +end + +@testset "Generated suite - the Bencher configuration is read at execution" begin + intempdir() do + write(C.CONFIG_FILE, "[bencher]\napi_key = \"GENERATION_KEY\"\nproject_name = \"generation_project\"\n") + + suite = generate("ex19-config-bencher.jl") + @test PerfTest.num_errors() == 0 + # Available to the transform as any other section + @test C.CONFIG["bencher"]["api_key"] == "GENERATION_KEY" + # but never written into the suite + code = read(suite, String) + @test !occursin("GENERATION_KEY", code) + @test !occursin("generation_project", code) + + mktempdir() do dir + write(joinpath(dir, C.CONFIG_FILE), "[general]\nmax_saved_results = 2\n[bencher]\napi_key = \"EXECUTION_KEY\"\n") + ok, out = execute(suite, dir) + @test ok + + # Only the [bencher] section comes from the file of the executing directory + @test dumped(dir, "BENCHER_FILE") == defaultWith(("bencher", "api_key", "EXECUTION_KEY")) + # A @perftest_config of the recipe takes priority over it + @test dumped(dir, "BENCHER_RECIPE") == defaultWith(("bencher", "api_key", "EXECUTION_KEY"), ("bencher", "project_name", "from_recipe")) + end + + # Without a configuration file the defaults are used, and no file is created + mktempdir() do dir + ok, out = execute(suite, dir) + @test ok + @test dumped(dir, "BENCHER_FILE") == C.DEFAULT + @test !ispath(joinpath(dir, C.CONFIG_FILE)) + end + end +end + +@testset "Generated suite - thread arrangements are resolved on the executing machine" begin + intempdir() do + write("recipe.jl", "using Test, PerfTest\n@perftest_threads :numa\n@testset \"T\" begin\n @perftest samples = 1 sin(1.0)\nend\n") + code = string(PerfTest.transform("recipe.jl").args[1]) + @test PerfTest.num_errors() == 0 + @test occursin("literallizeArrangement(:numa)", code) + end +end + +threadsParent = """ + using Test, PerfTest + @perftest_config " + [general] + numas = 1 + " + @testset "PARENT" begin + include("threads_child.jl") + @perftest samples = 1 sin(1.0) + end + # Does not set the thread keys + @perftest_config " + [roofline] + default_threshold = 0.3 + " + """ +threadsChild = """ + x = 5 + @perftest_config " + [general] + numas = 3 + threads_per_numa = 8 + " + # Unknown before the suite executes + @perftest_config " + [general] + threads_per_numa = '\$(x)' + " + @testset "CHILD" begin + @perftest samples = 1 sin(1.0) + end + """ + +@testset "Generated suite - one thread setting per suite, from the last configuration call that sets it" begin + intempdir() do + write(C.CONFIG_FILE, "[general]\nnumas = 2\nthreads_per_numa = 4\n") + threadSpecs(suite) = PerfTest.Launch.retrieveConfigThreadSpecs(PerfTest.loadFileAsExpr(suite)) + + # Without @perftest_config, the configuration the suite was generated with + @test threadSpecs(generate("ex16-config-generated-suite.jl")) == (2, 4) + + # An included recipe sets it for the whole suite, unlike the rest of its configuration + write("threads_parent.jl", threadsParent) + write("threads_child.jl", threadsChild) + PerfTest.saveExprAsFile(PerfTest.transform("threads_parent.jl"), "threads_parent_perfsuite.jl") + @test PerfTest.num_errors() == 0 + @test C.CONFIG["general"]["numas"] == 1 + @test @test_logs threadSpecs("threads_parent_perfsuite.jl") == (3, 8) + end +end + +@testset "Generated suite - transforming creates no results folder" begin + intempdir() do + PerfTest.transform(recipe("ex1-hierarchy-basic.jl")) + @test PerfTest.num_errors() == 0 + @test readdir() == [C.CONFIG_FILE] + end +end + +# A recipe with a single @perftest_config +configRecipe(toml) = """ + using Test, PerfTest + x = "general" + @perftest_config " + $toml + " + @testset "T" begin + @perftest samples = 1 sin(1.0) + end + """ + +@testset "@perftest_config - TOML errors are parse errors" begin + intempdir() do + # Interpolation as a whole value, in a table header, in a key, and invalid TOML + for toml in ("[regression]\ndefault_threshold = \$(x)", "[\$(x)]\nverbose = 3", "[general]\n\$(x) = 3", "this is = = not toml") + write("recipe.jl", configRecipe(toml)) + PerfTest.transform("recipe.jl") + @test PerfTest.num_errors() == 1 + @test C.CONFIG == C.DEFAULT + end + + # Interpolation inside a string value is the supported case + write("recipe.jl", configRecipe("[general]\nsave_folder = 'results_\$(x)'\nmax_saved_results = 7")) + PerfTest.transform("recipe.jl") + @test PerfTest.num_errors() == 0 + @test C.CONFIG == defaultWith(("general", "max_saved_results", 7)) + end +end + +# A recipe that includes another inside a testset +parentRecipe(child) = """ + using Test, PerfTest + @perftest_config " + [general] + max_saved_results = 11 + " + @testset "PARENT" begin + include("$child") + @perftest samples = 1 sin(1.0) + end + """ + +@testset "Included recipes - a failing include leaves the configuration of the including recipe" begin + intempdir() do + parent = defaultWith(("general", "max_saved_results", 11)) + child_config = "@perftest_config \"\n[general]\nmax_saved_results = 3\n\"\n" + + # Collected as a parse error + write("parent_bad_toml.jl", parentRecipe("child_bad_toml.jl")) + write("child_bad_toml.jl", child_config * "@perftest_config \"this is = = not toml\"\n") + PerfTest.transform("parent_bad_toml.jl") + @test PerfTest.num_errors() == 1 + @test C.CONFIG == parent + @test isempty(C.PARENT_CONFIGS) + + # Thrown out of the transform + write("parent_throws.jl", parentRecipe("child_throws.jl")) + write("child_throws.jl", child_config * "include(\"does_not_exist.jl\")\n") + @test_throws SystemError PerfTest.transform("parent_throws.jl") + @test C.CONFIG == parent + @test isempty(C.PARENT_CONFIGS) + end +end diff --git a/test/t12-config-validation.jl b/test/t12-config-validation.jl new file mode 100644 index 0000000..013d64b --- /dev/null +++ b/test/t12-config-validation.jl @@ -0,0 +1,223 @@ +using Test +using PerfTest +using TOML + +const C = PerfTest.Configuration + +# Every file based case runs in a fresh temporary directory, so test/perftest_config.toml is never touched +intempdir(f) = mktempdir(dir -> cd(f, dir)) + +# Executes a saved suite in a fresh process with `dir` as working directory, as runperftests does +function execute(suite, dir) + out = IOBuffer() + cmd = Cmd(`$(Base.julia_cmd()) --startup-file=no --project=$(Base.active_project()) $suite`; dir=dir) + ok = success(pipeline(cmd; stdout=out, stderr=out)) + output = String(take!(out)) + ok || println(output) + return ok, output +end + +# The default configuration with some (section, key, value) entries changed +function defaultWith(changes...) + config = deepcopy(C.DEFAULT) + for (section, key, value) in changes + config[section][key] = value + end + return config +end + +# Messages of the parse errors of the last transform +parseErrors() = [e.name for e in PerfTest.ctx._global.errors.errors] + +# A recipe with the given @perftest_config calls, each one a TOML string without double quotes +configRecipe(tomls...) = """ + using Test, PerfTest + x = 5 + $(join(["@perftest_config \"\n$toml\n\"" for toml in tomls], "\n")) + @on_perftest_exec begin + # Records the configuration seen by the executing suite in its working directory + open(io -> PerfTest.TOML.print(io, PerfTest.Configuration.CONFIG), "config_T.toml", "w") + end + @testset "T" begin + @perftest samples = 1 sin(1.0) + end + """ + +# Transforms a recipe written in the working directory, returns the generated expression +function transformRecipe(text) + write("recipe.jl", text) + return PerfTest.transform("recipe.jl") +end + +parsingFailed(expr) = occursin("Parsing failed", string(expr)) + +# What an unknown entry is reported along with: the names its table can have, never a guess of the one it stands for +const SECTIONS = "The sections are: " * join(sort!(collect(keys(C.CONFIG_SHAPE))), ", ") +keysOf(section) = "The keys of section $section are: " * join(sort!(collect(keys(C.CONFIG_SHAPE[section]))), ", ") + +@testset "Configuration - description of unknown entries" begin + @test SECTIONS == "The sections are: MPI, bencher, general, machine_benchmarking, memory_bandwidth, perfcompare, regression, roofline" + @test keysOf("MPI") == "The keys of section MPI are: enabled, mode" + + @test C.describe_unknown("verbse", 1, "general.", C.CONFIG_SHAPE["general"]) == ("key general.verbse", keysOf("general")) + @test C.describe_unknown("genral", Dict(), "", C.CONFIG_SHAPE) == ("section genral", SECTIONS) + @test C.describe_unknown("verbose", 1, "", C.CONFIG_SHAPE) == ("key verbose outside of any section", SECTIONS) + @test C.describe_unknown("x", Dict(), "MPI.", C.CONFIG_SHAPE["MPI"]) == ("key MPI.x", keysOf("MPI")) +end + +@testset "@perftest_config - unknown sections and keys are parse errors" begin + intempdir() do + expr = transformRecipe(configRecipe("[general]\nverbse = 3\nmax_saved_results = 7")) + @test PerfTest.num_errors() == 1 + @test parseErrors() == ["Unknown configuration key general.verbse in the @perftest_config of recipe recipe.jl. $(keysOf("general"))"] + @test parsingFailed(expr) + # The valid sibling applies to the rest of the transform, the unknown key is not kept + @test C.CONFIG == defaultWith(("general", "max_saved_results", 7)) + + transformRecipe(configRecipe("[genral]\nverbose = 3")) + @test parseErrors() == ["Unknown configuration section genral in the @perftest_config of recipe recipe.jl. $SECTIONS"] + @test C.CONFIG == C.DEFAULT + + # A key out of its section + transformRecipe(configRecipe("verbose = 3")) + @test parseErrors() == ["Unknown configuration key verbose outside of any section in the @perftest_config of recipe recipe.jl. $SECTIONS"] + + # Every one of them is reported + transformRecipe(configRecipe("[cuda]\nenabled = true", "[general]\nfoo = 1")) + @test parseErrors() == ["Unknown configuration section cuda in the @perftest_config of recipe recipe.jl. $SECTIONS", + "Unknown configuration key general.foo in the @perftest_config of recipe recipe.jl. $(keysOf("general"))"] + @test C.CONFIG == C.DEFAULT + + # In an included recipe, its own path is named + write("child.jl", "@perftest_config \"\n[roofline]\nenable = false\n\"\n") + transformRecipe("using Test, PerfTest\n@testset \"P\" begin\n include(\"child.jl\")\n @perftest samples = 1 sin(1.0)\nend\n") + @test parseErrors() == ["Unknown configuration key roofline.enable in the @perftest_config of recipe child.jl. $(keysOf("roofline"))"] + end +end + +@testset "@perftest_config - wrong types are parse errors, the valid keys still apply" begin + intempdir() do + # Without regression.enabled = false every top level testset gets a default regression + PerfTest.clearLogs() + transformRecipe(configRecipe("[general]\nmax_saved_results = 7")) + @test occursin("Defined REGRESSION", PerfTest.dumpLogsString()) + + PerfTest.clearLogs() + expr = transformRecipe(configRecipe("[general]\nverbose = 2.5\nmax_saved_results = 7\n[roofline]\ndefault_threshold = 'high'\nenabled = false", + "MPI = 3\n[regression]\nenabled = false")) + @test parseErrors() == ["Incorrect type for configuration key general.verbose in the @perftest_config of recipe recipe.jl. Expected Int64, got Float64", + "Incorrect type for configuration key roofline.default_threshold in the @perftest_config of recipe recipe.jl. Expected Number, got String", + "Expected a table for configuration section MPI in the @perftest_config of recipe recipe.jl, got Int64"] + @test parsingFailed(expr) + # Every valid key of both calls applies during the transform + @test C.CONFIG == defaultWith(("general", "max_saved_results", 7), ("roofline", "enabled", false), ("regression", "enabled", false)) + # and the rules after them behave as usual, e.g. no default regression with regression.enabled = false + @test !occursin("Defined REGRESSION", PerfTest.dumpLogsString()) + end +end + +@testset "@perftest_config - the argument must be a string literal" begin + intempdir() do + for call in ("@perftest_config 3", "@perftest_config x", "@perftest_config", "@perftest_config \"[general]\" \"verbose = 1\"") + text = "using Test, PerfTest\nx = \"[general]\\nverbose = 1\"\n$call\n@testset \"T\" begin\n @perftest samples = 1 sin(1.0)\nend\n" + expr = transformRecipe(text) + @test PerfTest.num_errors() == 1 + @test occursin("@perftest_config", only(parseErrors())) + @test parsingFailed(expr) + @test C.CONFIG == C.DEFAULT + end + @test parseErrors() == ["Invalid number of arguments in @perftest_config, expected from 1 to 1, got 2"] + end +end + +@testset "@perftest_config - an interpolated value can only set a key that takes a string" begin + intempdir() do + transformRecipe(configRecipe("[general]\nverbose = '\$(x)'\nmax_saved_results = 7")) + @test parseErrors() == ["Incorrect type for configuration key general.verbose in the @perftest_config of recipe recipe.jl. Expected Int64, got an interpolated String (interpolation is only supported inside string values)"] + @test C.CONFIG == defaultWith(("general", "max_saved_results", 7)) + + # Keys that take a string, alone or among other types + transformRecipe(configRecipe("[general]\nnumas = '\$(x)'\nsave_folder = 'results_\$(x)'\nmax_saved_results = 7")) + @test PerfTest.num_errors() == 0 + @test C.CONFIG == defaultWith(("general", "max_saved_results", 7)) + end +end + +@testset "Generated suite - a wrongly typed entry is ignored on its own at execution" begin + intempdir() do + expr = transformRecipe(configRecipe("[general]\nmax_saved_results = 5\n[roofline]\ndefault_threshold = 0.3")) + @test PerfTest.num_errors() == 0 + suite = abspath("recipe_perfsuite.jl") + PerfTest.saveExprAsFile(expr, suite) + + # As in a suite generated by a version of the package with a different configuration schema, the transform + # reports a wrongly typed entry as a parse error + code = read(suite, String) + @test count("default_threshold = 0.3", code) == 1 + write(suite, replace(code, "default_threshold = 0.3" => "default_threshold = 'low'")) + + mktempdir() do dir + ok, out = execute(suite, dir) + @test ok + @test occursin("Incorrect type for configuration key roofline.default_threshold in a configuration call of the executing suite. Expected Number, got String, ignoring it", out) + # Its sibling still applies + @test TOML.parsefile(joinpath(dir, "config_T.toml")) == defaultWith(("general", "max_saved_results", 5)) + end + end +end + +@testset "Configuration merges - a wrongly typed entry is ignored on its own" begin + override = Dict("general" => Dict("verbose" => "bad", "max_saved_results" => 2), "MPI" => 3, "roofline" => Dict("enabled" => false)) + merged = @test_logs (:error, "Incorrect type for configuration key general.verbose in the override. Expected Int64, got String, ignoring it") (:error, "Expected a table for configuration section MPI in the override, got Int64, ignoring it") match_mode=:any C.merge_configs(C.DEFAULT, override; source = "the override") + @test merged == defaultWith(("general", "max_saved_results", 2), ("roofline", "enabled", false)) + + # At execution + C.load_config(C.DEFAULT) + @test_logs (:error, r"general\.verbose in a configuration call of the executing suite") PerfTest._perftest_config("[general]\nverbose = 'x'\nmax_saved_results = 3\n") + @test C.CONFIG == defaultWith(("general", "max_saved_results", 3)) + + # config keyword of the transform + intempdir() do + write("recipe.jl", configRecipe("[roofline]\nenabled = false")) + @test_logs (:error, r"general\.verbose in the config argument of PerfTest\.transform") match_mode=:any PerfTest.transform("recipe.jl"; config=Dict("general" => Dict("verbose" => "bad", "max_saved_results" => 2))) + @test PerfTest.num_errors() == 0 + @test C.CONFIG == defaultWith(("general", "max_saved_results", 2), ("roofline", "enabled", false)) + end +end + +@testset "Configuration file - unknown sections and keys are errors, the rest of the file applies" begin + intempdir() do + write(C.CONFIG_FILE, """ + [genral] + verbose = 1 + [general] + foo = 1 + verbse = 1 + verbose = "2" + max_saved_results = 7 + """) + + file = "the configuration file perftest_config.toml" + cfg = @test_logs((:error, "Unknown configuration key general.foo in $file, ignoring it. $(keysOf("general"))"), + (:error, "Unknown configuration key general.verbse in $file, ignoring it. $(keysOf("general"))"), + (:error, "Unknown configuration section genral in $file, ignoring it. $SECTIONS"), + (:error, "Incorrect type for configuration key general.verbose in $file. Expected Int64, got String, using the default value 0"), + C.load_config()) + # The rest of the file applies + @test cfg["general"]["max_saved_results"] == 7 + @test cfg["general"]["verbose"] == C.DEFAULT["general"]["verbose"] + + # They are not parse errors of the transform + write("recipe.jl", configRecipe("[roofline]\nenabled = false")) + @test_logs (:error, r"general\.verbse") match_mode=:any PerfTest.transform("recipe.jl") + @test PerfTest.num_errors() == 0 + @test C.CONFIG["general"]["max_saved_results"] == 7 + + # The [bencher] section, read when a suite executes + write(C.CONFIG_FILE, "[bencher]\napikey = \"KEY\"\nproject_name = \"p\"\n") + @test_logs (:error, "Unknown configuration key bencher.apikey in $file, ignoring it. $(keysOf("bencher"))") C.load_bencher_config() + @test C.CONFIG["bencher"]["api_key"] == C.DEFAULT["bencher"]["api_key"] + @test C.CONFIG["bencher"]["project_name"] == "p" + end + C.load_config(C.DEFAULT) +end diff --git a/test/t13-group-d.jl b/test/t13-group-d.jl new file mode 100644 index 0000000..78dd70d --- /dev/null +++ b/test/t13-group-d.jl @@ -0,0 +1,321 @@ +using Test +using PerfTest +using TOML +using MacroTools + +const C = PerfTest.Configuration + +# Every file based case runs in a fresh temporary directory, so test/perftest_config.toml is never touched +intempdir(f) = mktempdir(dir -> cd(f, dir)) + +# Executes a saved suite in a fresh process with `dir` as working directory, as runperftests does +function execute(suite, dir) + out = IOBuffer() + cmd = Cmd(`$(Base.julia_cmd()) --startup-file=no --project=$(Base.active_project()) $suite`; dir=dir) + ok = success(pipeline(cmd; stdout=out, stderr=out)) + output = String(take!(out)) + ok || println(output) + return ok, output +end + +# Messages of the parse errors of the last transform +parseErrors() = [e.name for e in PerfTest.ctx._global.errors.errors] + +parsingFailed(expr) = occursin("Parsing failed", string(expr)) + +# Messages of the errors logged while running f +function loggedErrors(f) + logs, _ = Test.collect_test_logs(f) + return [string(l.message) for l in logs if l.level == Base.CoreLogging.Error] +end + +# Configuration a saved suite starts executing with, its first configuration call (see treeRun) +function generatedConfig(suite) + found = nothing + MacroTools.prewalk(PerfTest.loadFileAsExpr(suite)) do x + if found === nothing && @capture(x, PerfTest._perftest_config(s_String)) + found = TOML.parse(s) + end + return x + end + return found +end + +keysOf(section) = "The keys of section $section are: " * join(sort!(collect(keys(C.CONFIG_SHAPE[section]))), ", ") +const SECTIONS = "The sections are: " * join(sort!(collect(keys(C.CONFIG_SHAPE))), ", ") + +const PERFTEST = "@testset \"T\" begin\n @perftest samples = 1 sin(1.0)\nend\n" +recipeWith(lines...) = "using Test, PerfTest\n" * join(lines, "\n") * "\n" * PERFTEST +configCall(toml) = "@perftest_config \"\n$toml\n\"" + +quiet(f) = redirect_stdout(f, devnull) + +@testset "@roofline - without actual_flops, general.autoflops = true is a parse error" begin + intempdir() do + write("recipe.jl", "using Test, PerfTest\n@testset \"R\" begin\n @roofline begin\n 4\n end\n @perftest samples = 1 sin(1.0)\nend\n") + + # Used to throw a KeyError, reading CONFIG["autoflops"] + code = string(PerfTest.transform("recipe.jl")) + @test PerfTest.num_errors() == 0 + @test C.CONFIG["general"]["autoflops"] == false + @test occursin("name = \"Attained Flops\", units = \"FLOP/s\", value = 0,", code) + + # Automatic flop counting is not supported (its flop test always failed), see t15-batch.jl for the message + expr = PerfTest.transform("recipe.jl"; config=Dict("general" => Dict("autoflops" => true))) + @test PerfTest.num_errors() == 1 + @test parsingFailed(expr) + end +end + +@testset "Logs - the dumps hold only the written content" begin + intempdir() do + PerfTest.transform(joinpath(@__DIR__, "test-recipes", "ex1-hierarchy-basic.jl")) + written(ch) = String(take!(copy(PerfTest.LOGS.io_streams[ch]))) + + all = PerfTest.dumpLogsString() + @test !occursin('\0', all) + @test all == join(["=== Channel: $ch ===\n" * written(ch) for ch in PerfTest.LOGS.channels]) + for (i, ch) in enumerate(PerfTest.LOGS.channels) + @test PerfTest.dumpLogsString(i) == written(ch) + end + @test occursin("[TESTSET] New Group", PerfTest.dumpLogsString(1)) + + printed = mktemp() do path, io + redirect_stdout(() -> PerfTest.dumpLogs(), io) + close(io) + read(path, String) + end + @test !occursin('\0', printed) + @test printed == all + end +end + +@testset "runperftests - the verbose argument only overrides the configuration when given" begin + intempdir() do + write("recipe.jl", recipeWith()) + write(C.CONFIG_FILE, "[general]\nverbose = 1\nmax_saved_results = 5\n") + suite = "recipe_perfsuite.jl" + + # Used to always set general.verbose to 0 + quiet(() -> runperftests("recipe.jl"; execute=false)) + @test C.CONFIG["general"]["verbose"] == 1 + @test generatedConfig(suite)["general"]["verbose"] == 1 + @test generatedConfig(suite)["general"]["max_saved_results"] == 5 + + quiet(() -> runperftests("recipe.jl"; execute=false, config=Dict("general" => Dict("verbose" => 2)))) + @test C.CONFIG["general"]["verbose"] == 2 + @test generatedConfig(suite)["general"]["verbose"] == 2 + + # Given, it overrides both the file and the config argument + quiet(() -> runperftests("recipe.jl"; execute=false, verbose=0, config=Dict("general" => Dict("verbose" => 2)))) + @test C.CONFIG["general"]["verbose"] == 0 + @test generatedConfig(suite)["general"]["verbose"] == 0 + @test generatedConfig(suite)["general"]["max_saved_results"] == 5 + + # A @perftest_config of the recipe takes priority over it + write("recipe.jl", recipeWith(configCall("[general]\nverbose = 1"))) + quiet(() -> runperftests("recipe.jl"; execute=false, verbose=0)) + @test C.CONFIG["general"]["verbose"] == 1 + @test generatedConfig(suite)["general"]["verbose"] == 0 + end +end + +@testset "runperftests - priority of the configuration: @perftest_config > config argument > file" begin + intempdir() do + write(C.CONFIG_FILE, "[general]\nmax_saved_results = 5\n[roofline]\ndefault_threshold = 0.1\n[regression]\ndefault_threshold = 1.5\n") + config = Dict("general" => Dict("max_saved_results" => 6), "roofline" => Dict("default_threshold" => 0.2)) + write("recipe.jl", recipeWith(configCall("[general]\nmax_saved_results = 7"))) + + for run in (() -> runperftests("recipe.jl"; execute=false, config=config), + () -> PerfTest.saveExprAsFile(PerfTest.transform("recipe.jl"; config=config), "recipe_perfsuite.jl")) + rm("recipe_perfsuite.jl"; force=true) + run() + @test PerfTest.num_errors() == 0 + @test C.CONFIG["general"]["max_saved_results"] == 7 + @test C.CONFIG["roofline"]["default_threshold"] == 0.2 + @test C.CONFIG["regression"]["default_threshold"] == 1.5 + # Before the recipe changes it + initial = generatedConfig("recipe_perfsuite.jl") + @test initial["general"]["max_saved_results"] == 6 + @test initial["roofline"]["default_threshold"] == 0.2 + @test initial["regression"]["default_threshold"] == 1.5 + end + # The config argument is not modified + @test config == Dict("general" => Dict("max_saved_results" => 6), "roofline" => Dict("default_threshold" => 0.2)) + end +end + +@testset "runperftests - the configuration file is loaded and reported once" begin + intempdir() do + write("recipe.jl", recipeWith()) + write(C.CONFIG_FILE, "[general]\nverbse = 1\nmax_saved_results = \"5\"\n") + file = "the configuration file perftest_config.toml" + unknown = "Unknown configuration key general.verbse in $file, ignoring it. $(keysOf("general"))" + wrongtype = "Incorrect type for configuration key general.max_saved_results in $file. Expected $Int, got String, using the default value 20" + + for run in (() -> runperftests("recipe.jl"; execute=false), + () -> runperftests("recipe.jl"; execute=false, verbose=0, config=Dict("general" => Dict("plotting" => false))), + () -> PerfTest.transform("recipe.jl"), + () -> PerfTest.transform("recipe.jl"; config=Dict("general" => Dict("plotting" => false)))) + @test loggedErrors(run) == [unknown, wrongtype] + @test PerfTest.num_errors() == 0 + end + end +end + +@testset "Configuration argument - unknown sections and keys are errors, the rest applies" begin + intempdir() do + write("recipe.jl", recipeWith()) + config = Dict("general" => Dict("foo" => 1, "max_saved_results" => 6), "genral" => Dict("verbose" => 1), + "roofline" => Dict("default_threshold" => "high")) + + for (run, source) in ((() -> runperftests("recipe.jl"; execute=false, config=config), "the config argument of runperftests"), + (() -> PerfTest.transform("recipe.jl"; config=config), "the config argument of PerfTest.transform")) + @test loggedErrors(run) == [ + "Unknown configuration key general.foo in $source, ignoring it. $(keysOf("general"))", + "Unknown configuration section genral in $source, ignoring it. $SECTIONS", + "Incorrect type for configuration key roofline.default_threshold in $source. Expected Number, got String, ignoring it"] + @test PerfTest.num_errors() == 0 + # They are not parse errors, the valid entries apply + @test C.CONFIG["general"]["max_saved_results"] == 6 + @test C.CONFIG["roofline"]["default_threshold"] == C.DEFAULT["roofline"]["default_threshold"] + end + end +end + +@testset "runperftests - clean deletes the suite, the configuration file, the results and the logs" begin + intempdir() do + write("recipe.jl", recipeWith()) + # Of previous runs + mkpath(joinpath(".perftest_logs", "previous")) + mkpath(".perftests") + + # Used to throw removing ./perftest_logs instead of ./.perftest_logs. general.verbose >= 2 saves the logs of + # the transform in that folder as well + quiet(() -> runperftests("recipe.jl"; execute=false, verbose=2, clean=true)) + @test readdir() == ["recipe.jl"] + end +end + +@testset "Generated suite - the end message names failures only when there are" begin + intempdir() do + write("pass.jl", recipeWith()) + write("fail.jl", "using Test, PerfTest\n@testset \"T\" begin\n @perfcompare :median_time < 0\n @perftest samples = 1 sin(1.0)\nend\n") + write("reference.jl", recipeWith(configCall("[regression]\ndedicated_reference_file = 'ref.JLD2'"))) + suite(name) = (PerfTest.saveExprAsFile(PerfTest.transform("$name.jl"), "$(name)_perfsuite.jl"); abspath("$(name)_perfsuite.jl")) + + mktempdir() do dir + # Without regression.dedicated_reference_file it was printed even when every test passed + ok, out = execute(suite("pass"), dir) + @test ok + @test !occursin("Some tests failed or errored.", out) + @test isfile(joinpath(dir, ".perftests", "pass.jl_PERFORMANCE.JLD2")) + + ok, out = execute(suite("reference"), dir) + @test ok + @test !occursin("Some tests failed or errored.", out) + @test occursin("All performance tests have passed. Values will be registered as reference for regression testing.", out) + @test isfile(joinpath(dir, "ref.JLD2")) + + ok, out = execute(suite("fail"), dir) + @test ok + @test occursin("Some tests failed or errored.", out) + end + end +end + +@testset "Generated suite - general.save_results" begin + intempdir() do + write(C.CONFIG_FILE, "[general]\nsave_results = false\n[regression]\ndedicated_reference_file = \"ref.JLD2\"\n") + write("recipe.jl", recipeWith()) + PerfTest.saveExprAsFile(PerfTest.transform("recipe.jl"), "recipe_perfsuite.jl") + @test PerfTest.num_errors() == 0 + + mktempdir() do dir + # The configuration of the executing directory does not apply + write(joinpath(dir, C.CONFIG_FILE), "[general]\nsave_results = true\n") + ok, out = execute(abspath("recipe_perfsuite.jl"), dir) + @test ok + @test occursin("The results of this execution have not been saved (general.save_results is false).", out) + @test !occursin("Values will be registered", out) + @test !occursin("Some tests failed or errored.", out) + @test readdir(dir) == [C.CONFIG_FILE] + end + + # From its place in the recipe onwards: the first top level testset saves its results, the second does not + rm(C.CONFIG_FILE) + write("recipe.jl", "using Test, PerfTest\n" * replace(PERFTEST, "\"T\"" => "\"A\"") * configCall("[general]\nsave_results = false") * + "\n" * replace(PERFTEST, "\"T\"" => "\"B\"")) + PerfTest.saveExprAsFile(PerfTest.transform("recipe.jl"), "recipe_perfsuite.jl") + @test PerfTest.num_errors() == 0 + @test C.CONFIG["general"]["save_results"] == false + + mktempdir() do dir + ok, out = execute(abspath("recipe_perfsuite.jl"), dir) + @test ok + @test count("have not been saved", out) == 1 + results = joinpath(dir, ".perftests", "recipe.jl_PERFORMANCE.JLD2") + @test isfile(results) + @test length(PerfTest.openDataFile(results).results) == 1 + end + end +end + +@testset "@perftest_threads - a malformed argument is a parse error" begin + intempdir() do + invalid(reason) = "Invalid thread arrangement in the @perftest_threads of recipe recipe.jl: $reason $(PerfTest.THREADS_OPTIONS)" + notliteral(x) = invalid("`$x` is not a literal, the arrangement is read when the recipe is transformed so a variable or any other expression is not supported.") + cases = [ + # Used to throw a MethodError + "" => "Invalid number of arguments in @perftest_threads, expected from 1 to 1, got 0", + ":single :numa" => "Invalid number of arguments in @perftest_threads, expected from 1 to 1, got 2", + "x = 1" => "Last parameter cannot be a keyword (x) parameter on macro @perftest_threads", + "(1, 2, 3)" => invalid("(1, 2, 3) has 3 element(s), expected exactly 2 (#numas, #threads_per_numa)."), + "(1.5, 1)" => invalid("(1.5, 1), the elements of an arrangement must be integers or ratios of integers, got 1.5 (Float64)."), + "(:numa, 1)" => invalid("(:numa, 1), the elements of an arrangement must be integers or ratios of integers, got :numa (Symbol)."), + "[1.5]" => invalid("1.5 (Float64) is not a thread arrangement."), + # Used to be evaluated in the PerfTest module during the transform, throwing an UndefVarError + "n" => notliteral("n"), + "(1, n)" => notliteral("(1, n)"), + "f(1)" => notliteral("f(1)"), + # Used to be reported along with "Invalid expression in macro @perftest_threads" + ":foo" => invalid("symbol :foo is unrecognised, the symbols are :single, :numa and :all."), + "[(1, 1), :foo]" => invalid("symbol :foo is unrecognised, the symbols are :single, :numa and :all."), + "(1, 0)" => invalid("(1, 0), #threads_per_numa must be a positive integer, got 0."), + "(0, 1)" => invalid("(0, 1), #numas must be a positive integer, got 0."), + "(1, 3//2)" => invalid("(1, 3//2), thread ratio 3//2 is out of range, it must satisfy 0 < ratio ≤ 1."), + "[0, 1]" => invalid("[0, 1], the thread ids of a manual pinning must be positive integers, got 0."), + # Used to be accepted, the generated suite then threw + "[]" => invalid("an empty list has no arrangement to use."), + # Used to report only the expected type of the macro argument + "\"numa\"" => invalid("\"numa\" (String) is not a thread arrangement."), + "3" => invalid("3 (Int64) is not a thread arrangement."), + ] + for (arg, message) in cases + write("recipe.jl", recipeWith("n = 2", "@perftest_threads $arg")) + expr = PerfTest.transform("recipe.jl") + @test parseErrors() == [message] + @test parsingFailed(expr) + end + + # Every invalid one of a list is reported + write("recipe.jl", recipeWith("@perftest_threads [(0, 1), :foo, (1, 1)]")) + PerfTest.transform("recipe.jl") + @test parseErrors() == [invalid("(0, 1), #numas must be a positive integer, got 0."), + invalid("symbol :foo is unrecognised, the symbols are :single, :numa and :all.")] + + # In an included recipe, its own path is named + write("child.jl", "@perftest_threads :foo\n") + write("recipe.jl", "using Test, PerfTest\n@testset \"P\" begin\n include(\"child.jl\")\n @perftest samples = 1 sin(1.0)\nend\n") + PerfTest.transform("recipe.jl") + @test parseErrors() == [replace(invalid("symbol :foo is unrecognised, the symbols are :single, :numa and :all."), "recipe recipe.jl" => "recipe child.jl")] + + # The valid ones + for arg in (":single", ":numa", ":all", "(1, 1)", "(1, 1//2)", "(1//1, 1//1)", "[1, 2]", "[(1, 1), (1, 1//2)]") + write("recipe.jl", recipeWith("@perftest_threads $arg")) + code = string(PerfTest.transform("recipe.jl")) + @test PerfTest.num_errors() == 0 + @test occursin("PerfTest.Topology.literallizeArrangement($(Meta.parse(arg)))", code) + end + end +end diff --git a/test/t14-decisions.jl b/test/t14-decisions.jl new file mode 100644 index 0000000..b4ebd17 --- /dev/null +++ b/test/t14-decisions.jl @@ -0,0 +1,492 @@ +using Test +using PerfTest + +const C = PerfTest.Configuration +const T = PerfTest.Topology +const L = PerfTest.Launch + +# Every file based case runs in a fresh temporary directory, so test/perftest_config.toml is never touched +intempdir(f) = mktempdir(dir -> cd(f, dir)) + +quiet(f) = redirect_stdout(f, devnull) + +# Messages of the parse errors of the last transform +parseErrors() = [e.name for e in PerfTest.ctx._global.errors.errors] + +parsingFailed(expr) = occursin("Parsing failed", string(expr)) + +# Messages of the errors logged while running f +function loggedErrors(f) + logs, _ = Test.collect_test_logs(f) + return [string(l.message) for l in logs if l.level == Base.CoreLogging.Error] +end + +# Message of the error thrown by f +thrown(f) = try f(); "" catch e; sprint(showerror, e) end + +const PERFTEST = "@testset \"T\" begin\n @perftest samples = 1 sin(1.0)\nend\n" +recipeWith(lines...) = "using Test, PerfTest\n" * join(lines, "\n") * "\n" * PERFTEST +configCall(toml) = "@perftest_config \"\n$toml\n\"" + +# Transforms a recipe and saves the generated suite next to it +function generate(recipe; kw...) + suite = abspath(replace(recipe, r"\.jl$" => "_perfsuite.jl")) + PerfTest.saveExprAsFile(PerfTest.transform(recipe; kw...), suite) + return suite +end + +const FILE = "the configuration file perftest_config.toml" +const DEFAULT = "the default configuration" +inRecipe(recipe) = "the @perftest_config of recipe $recipe" + +# The thread setting of a suite, as named in its errors, with where each key comes from +setting(numas, numas_from, threads, threads_from) = + "general.numas = $(repr(numas)) (from $numas_from) and general.threads_per_numa = $(repr(threads)) (from $threads_from)" +threadError(setting, problems...) = + "Invalid thread setting of the generated suite, $setting: $(join(problems, ", ")). $(T.THREAD_SETTING_RULE) $(T.CONFIG_THREADS_OPTIONS)" +launchError(suite, numas, threads, problems...) = + "Cannot launch the suite $suite, the thread setting of the generated suite is invalid, general.numas = $(repr(numas)) " * + "and general.threads_per_numa = $(repr(threads)): $(join(problems, ", ")). $(T.THREAD_SETTING_RULE) $(T.CONFIG_THREADS_OPTIONS)" + +# Number of threads the launcher starts the suite with +launchThreads(suite) = only(a for a in L.suiteCommand(suite).exec if startswith(a, "--threads=")) + +# Must run before anything else loads a configuration in this process +@testset "Configuration - no source nor thread setting is left by the precompilation" begin + @test isempty(C.SOURCES) + @test isempty(C.PARENT_SOURCES) + @test isempty(PerfTest.THREAD_SETTING) +end + +# --------------------------------------------------------------------------------------------------------------------- +# C8, general.numas and general.threads_per_numa give the thread setting the launcher uses +# --------------------------------------------------------------------------------------------------------------------- + +@testset "Thread setting - conversion of general.numas and general.threads_per_numa" begin + # A string names a whole arrangement, in both keys + @test T.arrangementFromConfig("single", "single") === (1, 1) + @test T.arrangementFromConfig("numa", "numa") === (1, 1 // 1) + @test T.arrangementFromConfig("all", "all") === (1 // 1, 1 // 1) + # Numbers: an integer stays, a float in (0, 1] is a ratio + @test T.arrangementFromConfig(2, 4) === (2, 4) + @test T.arrangementFromConfig(1, 0.5) === (1, 1 // 2) + @test T.arrangementFromConfig(0.25, 3) === (1 // 4, 3) + @test T.arrangementFromConfig(1.0, 1.0) === (1 // 1, 1 // 1) + @test T.arrangementFromConfig(1, 0.3) === (1, 3 // 10) + # Every arrangement is one, as for @perftest_threads + for numas in ("single", "numa", "all"), arrangement in (T.arrangementFromConfig(numas, numas), T.arrangementFromConfig(1, 0.5)) + @test arrangement isa T.ArrangementSpec + @test T.validateArrangement(arrangement, error) + end + + # Anything else is not interpreted + @test T.arrangementFromConfig("singel", "single") == ["general.numas = \"singel\" is not the name of an arrangement"] + @test T.arrangementFromConfig("single", "Single") == ["general.threads_per_numa = \"Single\" is not the name of an arrangement"] + @test T.arrangementFromConfig("single", "all") == ["general.numas = \"single\" and general.threads_per_numa = \"all\" name different arrangements, a name is given in both keys"] + @test T.arrangementFromConfig("numa", 2) == ["general.numas = \"numa\" names an arrangement but general.threads_per_numa = 2 is a number, a name is given in both keys"] + @test T.arrangementFromConfig(0.5, "all") == ["general.threads_per_numa = \"all\" names an arrangement but general.numas = 0.5 is a number, a name is given in both keys"] + @test T.arrangementFromConfig(0, 1) == ["general.numas = 0 is an integer below 1"] + @test T.arrangementFromConfig(1, -2) == ["general.threads_per_numa = -2 is an integer below 1"] + @test T.arrangementFromConfig(0.0, 1) == ["general.numas = 0.0 is a float outside (0, 1]"] + @test T.arrangementFromConfig(1, 1.5) == ["general.threads_per_numa = 1.5 is a float outside (0, 1]"] + @test T.arrangementFromConfig(2.0, 1) == ["general.numas = 2.0 is a float outside (0, 1]"] + @test T.arrangementFromConfig(-0.5, 1) == ["general.numas = -0.5 is a float outside (0, 1]"] + # A Bool is an Integer in Julia, and passes the type of the keys + @test T.arrangementFromConfig(true, 1) == ["general.numas = true is a Bool, neither a number nor the name of an arrangement"] + # Each invalid key is named + @test T.arrangementFromConfig("bogus", 0) == ["general.numas = \"bogus\" is not the name of an arrangement", "general.threads_per_numa = 0 is an integer below 1"] +end + +@testset "Thread setting - the launcher starts the suite with it" begin + intempdir() do + write("recipe.jl", recipeWith()) + literal(arrangement) = T.literallizeArrangement(arrangement) + + # Default, unchanged: one thread + suite = generate("recipe.jl") + @test PerfTest.num_errors() == 0 + @test L.suiteArrangement(suite) === (1, 1) + @test L.retrieveThreadConfig(suite) == (1, 1) + @test launchThreads(suite) == "--threads=1" + + # Resolved on this machine, see literallizeArrangement + T.hwloc_topology === nothing && T.getMachineTopology!() + cases = [ + ("\"single\"", "\"single\"") => ((1, 1), (1, 1)), + ("\"numa\"", "\"numa\"") => ((1, 1 // 1), (1, T.threadsPerNuma()[1])), + ("\"all\"", "\"all\"") => ((1 // 1, 1 // 1), (T.numberOfNUMAS(), minimum(T.threadsPerNuma()))), + ("1", "1") => ((1, 1), (1, 1)), + ("1", "0.5") => ((1, 1 // 2), (1, max(1, floor(Int, T.threadsPerNuma()[1] / 2)))), + ("1.0", "1.0") => ((1 // 1, 1 // 1), (T.numberOfNUMAS(), minimum(T.threadsPerNuma()))), + ] + for ((numas, threads), (arrangement, resolved)) in cases + write(C.CONFIG_FILE, "[general]\nnumas = $numas\nthreads_per_numa = $threads\n") + suite = @test_logs generate("recipe.jl") + @test PerfTest.num_errors() == 0 + @test L.suiteArrangement(suite) === arrangement + @test L.retrieveThreadConfig(suite) == resolved == literal(arrangement) + @test launchThreads(suite) == "--threads=$(prod(resolved))" + end + + # The setting is valid, but this machine cannot satisfy it + write(C.CONFIG_FILE, "[general]\nnumas = $(T.numberOfNUMAS() + 1)\nthreads_per_numa = 1\n") + suite = generate("recipe.jl") + @test PerfTest.num_errors() == 0 + @test L.suiteArrangement(suite) === (T.numberOfNUMAS() + 1, 1) + @test thrown(() -> L.suiteCommand(suite)) == + "Cannot launch the suite $suite with the thread arrangement $(repr((T.numberOfNUMAS() + 1, 1))) on this machine: " * + "Invalid thread arrangement: requested $(T.numberOfNUMAS() + 1) NUMA domain(s) but the host only has $(T.numberOfNUMAS())." + end +end + +@testset "Thread setting - an invalid one from the configuration file or argument is an error, the launcher refuses it" begin + intempdir() do + write("recipe.jl", recipeWith()) + cases = [ + ("\"bogus\"", "\"single\"") => ("bogus", "single", ["general.numas = \"bogus\" is not the name of an arrangement"]), + ("\"single\"", "\"all\"") => ("single", "all", ["general.numas = \"single\" and general.threads_per_numa = \"all\" name different arrangements, a name is given in both keys"]), + ("\"numa\"", "2") => ("numa", 2, ["general.numas = \"numa\" names an arrangement but general.threads_per_numa = 2 is a number, a name is given in both keys"]), + ("0", "1") => (0, 1, ["general.numas = 0 is an integer below 1"]), + ("1", "1.5") => (1, 1.5, ["general.threads_per_numa = 1.5 is a float outside (0, 1]"]), + ] + for ((numas, threads), (n, t, problems)) in cases + write(C.CONFIG_FILE, "[general]\nnumas = $numas\nthreads_per_numa = $threads\n") + suite = abspath("recipe_perfsuite.jl") + # Not a parse error, as the other errors of the file, the suite is generated + @test loggedErrors(() -> generate("recipe.jl")) == [threadError(setting(n, FILE, t, FILE), problems...)] + @test PerfTest.num_errors() == 0 + # The launcher cannot start it + @test thrown(() -> L.suiteArrangement(suite)) == launchError(suite, n, t, problems...) + @test thrown(() -> L.suiteCommand(suite)) == launchError(suite, n, t, problems...) + end + + # Only one of the keys in the file, the other one has its default value + write(C.CONFIG_FILE, "[general]\nnumas = \"all\"\n") + problem = "general.numas = \"all\" and general.threads_per_numa = \"single\" name different arrangements, a name is given in both keys" + @test loggedErrors(() -> generate("recipe.jl")) == [threadError(setting("all", FILE, "single", DEFAULT), problem)] + + # The config argument, over the file + rm(C.CONFIG_FILE) + config = Dict("general" => Dict("threads_per_numa" => 2)) + problem = "general.numas = \"single\" names an arrangement but general.threads_per_numa = 2 is a number, a name is given in both keys" + @test loggedErrors(() -> PerfTest.transform("recipe.jl"; config=config)) == + [threadError(setting("single", DEFAULT, 2, "the config argument of PerfTest.transform"), problem)] + @test PerfTest.num_errors() == 0 + + # runperftests does not launch it. The previous transform created the configuration file, with every key + message = Ref("") + errors = loggedErrors(() -> message[] = thrown(() -> quiet(() -> runperftests("recipe.jl"; config=config)))) + @test errors == [threadError(setting("single", FILE, 2, "the config argument of runperftests"), problem)] + @test message[] == launchError("recipe_perfsuite.jl", "single", 2, problem) + end +end + +@testset "Thread setting - an invalid one set by a recipe is a parse error, naming where each key comes from" begin + intempdir() do + write("recipe.jl", recipeWith(configCall("[general]\nnumas = 'numa'\nthreads_per_numa = 'all'"))) + expr = PerfTest.transform("recipe.jl") + @test parseErrors() == [threadError(setting("numa", inRecipe("recipe.jl"), "all", inRecipe("recipe.jl")), + "general.numas = \"numa\" and general.threads_per_numa = \"all\" name different arrangements, a name is given in both keys")] + @test parsingFailed(expr) + + for (toml, n, t, problem) in (("numas = 'bogus'\nthreads_per_numa = 'bogus'", "bogus", "bogus", "general.numas = \"bogus\" is not the name of an arrangement, general.threads_per_numa = \"bogus\" is not the name of an arrangement"), + ("numas = 1\nthreads_per_numa = 0", 1, 0, "general.threads_per_numa = 0 is an integer below 1"), + ("numas = 1.5\nthreads_per_numa = 1", 1.5, 1, "general.numas = 1.5 is a float outside (0, 1]"), + ("numas = 2\nthreads_per_numa = 'numa'", 2, "numa", "general.threads_per_numa = \"numa\" names an arrangement but general.numas = 2 is a number, a name is given in both keys")) + write("recipe.jl", recipeWith(configCall("[general]\n$toml"))) + expr = PerfTest.transform("recipe.jl") + @test parseErrors() == [threadError(setting(n, inRecipe("recipe.jl"), t, inRecipe("recipe.jl")), problem)] + @test parsingFailed(expr) + end + + # One key from the recipe, the other one from the file: still a parse error + write(C.CONFIG_FILE, "[general]\nnumas = \"all\"\n") + write("recipe.jl", recipeWith(configCall("[general]\nthreads_per_numa = 2"))) + expr = PerfTest.transform("recipe.jl") + @test parseErrors() == [threadError(setting("all", FILE, 2, inRecipe("recipe.jl")), + "general.numas = \"all\" names an arrangement but general.threads_per_numa = 2 is a number, a name is given in both keys")] + @test parsingFailed(expr) + # The other errors of the recipe are reported as well + write("recipe.jl", recipeWith(configCall("[general]\nthreads_per_numa = 2\nverbse = 1"))) + PerfTest.transform("recipe.jl") + @test length(parseErrors()) == 2 + end +end + +@testset "Thread setting - one per suite, from the last configuration call that sets each key, even in an included recipe" begin + intempdir() do + write(C.CONFIG_FILE, "[general]\nnumas = 2\nthreads_per_numa = 4\n") + parent(child_toml; after = "") = """ + using Test, PerfTest + @perftest_config " + [general] + numas = 'all' + threads_per_numa = 'all' + " + @testset "PARENT" begin + include("child.jl") + @perftest samples = 1 sin(1.0) + end + $after + """ + child(toml) = "@perftest_config \"\n[general]\n$toml\n\"\n@testset \"CHILD\" begin\n @perftest samples = 1 sin(1.0)\nend\n" + + # The included recipe sets it for the whole suite, the rest of its configuration only applies to its own part + write("parent.jl", parent("")) + write("child.jl", child("numas = 1\nthreads_per_numa = 0.5\nmax_saved_results = 3")) + suite = generate("parent.jl") + @test PerfTest.num_errors() == 0 + @test C.CONFIG["general"]["numas"] == "all" + @test C.CONFIG["general"]["max_saved_results"] == 20 + @test L.retrieveConfigThreadSpecs(PerfTest.loadFileAsExpr(suite)) == (1, 0.5) + @test L.suiteArrangement(suite) === (1, 1 // 2) + + # Only one key in the included recipe, the other one from the parent: the setting of the suite is invalid + write("child.jl", child("numas = 1")) + expr = PerfTest.transform("parent.jl") + @test parseErrors() == [threadError(setting(1, inRecipe("child.jl"), "all", inRecipe("parent.jl")), + "general.threads_per_numa = \"all\" names an arrangement but general.numas = 1 is a number, a name is given in both keys")] + @test parsingFailed(expr) + + # A later call of the parent sets it back, only the final setting is checked + write("parent.jl", parent("numas = 1"; after = "@perftest_config \"\n[general]\nnumas = 'all'\n\"")) + suite = generate("parent.jl") + @test PerfTest.num_errors() == 0 + @test L.suiteArrangement(suite) === (1 // 1, 1 // 1) + + # Neither is the setting between two calls of a recipe + write("recipe.jl", recipeWith(configCall("[general]\nnumas = 'numa'"), configCall("[general]\nthreads_per_numa = 'numa'"))) + suite = generate("recipe.jl") + @test PerfTest.num_errors() == 0 + @test L.suiteArrangement(suite) === (1, 1 // 1) + end +end + +@testset "Thread setting - @perftest_threads takes priority, the setting is still checked" begin + intempdir() do + write(C.CONFIG_FILE, "[general]\nnumas = \"all\"\nthreads_per_numa = \"all\"\n") + for (arg, arrangement) in (":single" => :single, "(1, 1)" => (1, 1), ":numa" => :numa) + write("recipe.jl", recipeWith("@perftest_threads $arg")) + suite = generate("recipe.jl") + @test PerfTest.num_errors() == 0 + @test L.suiteArrangement(suite) === arrangement + end + @test launchThreads(abspath("recipe_perfsuite.jl")) == "--threads=$(prod(T.literallizeArrangement(:numa)))" + + # An invalid setting is reported even when @perftest_threads takes priority over it + write(C.CONFIG_FILE, "[general]\nnumas = \"bogus\"\nthreads_per_numa = \"bogus\"\n") + write("recipe.jl", recipeWith("@perftest_threads (1, 1)")) + problems = ("general.numas = \"bogus\" is not the name of an arrangement", "general.threads_per_numa = \"bogus\" is not the name of an arrangement") + @test loggedErrors(() -> generate("recipe.jl")) == [threadError(setting("bogus", FILE, "bogus", FILE), problems...)] + @test L.suiteArrangement(abspath("recipe_perfsuite.jl")) === (1, 1) + end +end + +# --------------------------------------------------------------------------------------------------------------------- +# C14, an explicit @regression without threshold takes it from regression.default_threshold +# --------------------------------------------------------------------------------------------------------------------- + +regressionRecipe(regression; before = "") = """ + using Test, PerfTest + $before + @testset "T" begin + @define_metric name = "m1" units = "1/s" begin + 1 / :median_time + end + @define_metric name = "m2" units = "s" begin + :median_time + end + $regression + @perftest samples = 1 sin(1.0) + end + """ + +# Thresholds and low_is_bad of the last regression defined for testset T, as logged +function lastRegression() + found = collect(eachmatch(r"Defined REGRESSION on \[\"T\"\] METRICS: (\[.*?\]) TH: (\[.*?\]) LOW_IS_BAD: (.*)", PerfTest.dumpLogsString())) + return Tuple(last(found).captures) +end + +regressionError(recipe, metrics, threshold, from) = + "Invalid regression threshold in the @regression of recipe $recipe: it gives no threshold, so $metrics, where a low value is bad " * + "(low_is_bad = true), would take 2 − regression.default_threshold, but regression.default_threshold = $(repr(threshold)) " * + "(from $from) gives 2 − $(repr(threshold)) = $(repr(Float64(2 - parse(BigFloat, string(Float64(threshold)))))), which every " * + "ratio new/reference passes. Give that @regression an explicit threshold (threshold=..., the ratio new/reference a metric " * + "with low_is_bad = true must stay above), or set regression.default_threshold below 2" + +@testset "@regression - a missing threshold comes from regression.default_threshold, following low_is_bad" begin + intempdir() do + # Default configuration: as before for low_is_bad = true, the default of the macro + for (regression, threshold, low_is_bad) in (("@regression", "[0.9]", "Bool[1]"), + ("@regression low_is_bad=true", "[0.9]", "Bool[1]"), + # Used to be 0.9, which needed a 10% faster time to pass + ("@regression low_is_bad=false", "[1.1]", "Bool[0]"), + # An explicit threshold is kept + ("@regression threshold=0.8 low_is_bad=true", "[0.8]", "Bool[1]"), + ("@regression threshold=1.3 low_is_bad=false", "[1.3]", "Bool[0]")) + write("recipe.jl", regressionRecipe(regression)) + code = string(PerfTest.transform("recipe.jl")) + @test PerfTest.num_errors() == 0 + @test lastRegression() == ("[:median_time]", threshold, low_is_bad) + # Exactly 0.9, not 2 - 1.1 = 0.8999999999999999 + @test occursin("ratio $(low_is_bad == "Bool[1]" ? ">" : "<") $(threshold[2:end-1])", code) + end + + # Another regression.default_threshold + write(C.CONFIG_FILE, "[regression]\ndefault_threshold = 1.25\n") + for (regression, threshold) in (("@regression", "[0.75]"), ("@regression low_is_bad=false", "[1.25]")) + write("recipe.jl", regressionRecipe(regression)) + PerfTest.transform("recipe.jl") + @test PerfTest.num_errors() == 0 + @test lastRegression()[2] == threshold + end + + # Per metric, following each low_is_bad + write("recipe.jl", regressionRecipe("@regression metrics=[:median_time, :m1, :m2] low_is_bad=[false, true, false]")) + PerfTest.transform("recipe.jl") + @test PerfTest.num_errors() == 0 + @test lastRegression() == ("[:median_time, :m1, :m2]", "[1.25, 0.75, 1.25]", "Any[false, true, false]") + write("recipe.jl", regressionRecipe("@regression metrics=[:median_time, :m1] low_is_bad=true")) + PerfTest.transform("recipe.jl") + @test lastRegression()[2] == "[0.75, 0.75]" + + # From a @perftest_config, an included recipe's one only applies to its own part + rm(C.CONFIG_FILE) + write("child.jl", "@perftest_config \"\n[regression]\ndefault_threshold = 1.5\n\"\n@testset \"CHILD\" begin\n @regression\n @perftest samples = 1 sin(1.0)\nend\n") + write("recipe.jl", regressionRecipe("@regression"; before = configCall("[regression]\ndefault_threshold = 1.2") * "\ninclude(\"child.jl\")")) + PerfTest.transform("recipe.jl") + @test PerfTest.num_errors() == 0 + @test lastRegression()[2] == "[0.8]" + @test occursin("Defined REGRESSION on [\"CHILD\"] METRICS: [:median_time] TH: [0.5] LOW_IS_BAD: Bool[1]", PerfTest.dumpLogsString()) + end +end + +@testset "@regression - an integer regression.default_threshold" begin + intempdir() do + # Used to throw, as the regression of every top level testset only took a Float64 + write(C.CONFIG_FILE, "[regression]\ndefault_threshold = 1\n") + write("recipe.jl", recipeWith()) + code = string(PerfTest.transform("recipe.jl")) + @test PerfTest.num_errors() == 0 + @test occursin("ratio < 1.0", code) + + for (regression, threshold) in (("@regression", "[1.0]"), ("@regression low_is_bad=false", "[1.0]"), ("@regression threshold=0.9", "[0.9]")) + write("recipe.jl", regressionRecipe(regression)) + PerfTest.transform("recipe.jl") + @test PerfTest.num_errors() == 0 + @test lastRegression()[2] == threshold + end + + write("recipe.jl", regressionRecipe("@regression"; before = configCall("[regression]\ndefault_threshold = 3"))) + PerfTest.transform("recipe.jl") + @test parseErrors() == [regressionError("recipe.jl", ":median_time", 3, inRecipe("recipe.jl"))] + end +end + +@testset "@regression - regression.default_threshold of 2 or more leaves no threshold where a low value is bad" begin + intempdir() do + write(C.CONFIG_FILE, "[regression]\ndefault_threshold = 2.0\n") + for regression in ("@regression", "@regression low_is_bad=true") + write("recipe.jl", regressionRecipe(regression)) + expr = PerfTest.transform("recipe.jl") + @test parseErrors() == [regressionError("recipe.jl", ":median_time", 2.0, FILE)] + @test parsingFailed(expr) + end + + # Only the metrics with low_is_bad = true are named + write("recipe.jl", regressionRecipe("@regression metrics=[:median_time, :m1, :m2] low_is_bad=[true, false, true]")) + PerfTest.transform("recipe.jl") + @test parseErrors() == [regressionError("recipe.jl", ":median_time, :m2", 2.0, FILE)] + + # Fine where a high value is bad, or with an explicit threshold + for regression in ("@regression low_is_bad=false", "@regression threshold=0.9", "@regression metrics=[:median_time, :m1] low_is_bad=[false, false]") + write("recipe.jl", regressionRecipe(regression)) + PerfTest.transform("recipe.jl") + @test PerfTest.num_errors() == 0 + end + + # Where it comes from: the config argument, or a @perftest_config of an included recipe + write("recipe.jl", regressionRecipe("@regression")) + PerfTest.transform("recipe.jl"; config=Dict("regression" => Dict("default_threshold" => 2.5))) + @test parseErrors() == [regressionError("recipe.jl", ":median_time", 2.5, "the config argument of PerfTest.transform")] + + rm(C.CONFIG_FILE) + # The including recipe gets its own value back, the regression of its testset is fine + write("child.jl", "@perftest_config \"\n[regression]\ndefault_threshold = 2.5\n\"\n@testset \"CHILD\" begin\n @regression\n @perftest samples = 1 sin(1.0)\nend\n") + write("recipe.jl", regressionRecipe("@regression"; before = "include(\"child.jl\")")) + PerfTest.transform("recipe.jl") + @test parseErrors() == [regressionError("child.jl", ":median_time", 2.5, inRecipe("child.jl"))] + @test lastRegression()[2] == "[0.9]" + end +end + +# --------------------------------------------------------------------------------------------------------------------- +# C11, MPI.enabled cannot be set by a recipe, the logs are saved from the final configuration +# --------------------------------------------------------------------------------------------------------------------- + +mpiError(recipe) = "Configuration key MPI.enabled cannot be set in the @perftest_config of recipe $recipe: the MPI mode is decided " * + "with it before the recipe is read, so it would not apply. Set it in the configuration file perftest_config.toml " * + "or with the config argument of runperftests or PerfTest.transform" + +@testset "@perftest_config - MPI.enabled is a parse error, the rest of the macro applies" begin + intempdir() do + # Used to be silently ignored, the MPI mode is decided before the recipe is read + for value in ("true", "false", "'\$(x)'", "1") + write("recipe.jl", recipeWith("x = 1", configCall("[MPI]\nenabled = $value\nmode = 'other'\n[general]\nmax_saved_results = 7"))) + expr = PerfTest.transform("recipe.jl") + @test parseErrors() == [mpiError("recipe.jl")] + @test parsingFailed(expr) + @test C.CONFIG["MPI"]["enabled"] == false + # MPI.mode is not read anywhere, it can still be set + @test C.CONFIG["MPI"]["mode"] == "other" + @test C.CONFIG["general"]["max_saved_results"] == 7 + @test PerfTest.mode == PerfTest.NormalMode + end + + write("child.jl", "@perftest_config \"\n[MPI]\nenabled = true\n\"\n") + write("recipe.jl", recipeWith("include(\"child.jl\")")) + PerfTest.transform("recipe.jl") + @test parseErrors() == [mpiError("child.jl")] + + # The configuration file and the config argument still set it. Without the MPI package the suite is not MPI aware + for run in (() -> PerfTest.transform("recipe.jl"; config=Dict("MPI" => Dict("enabled" => true))), + () -> (write(C.CONFIG_FILE, "[MPI]\nenabled = true\n"); PerfTest.transform("recipe.jl"))) + write("recipe.jl", recipeWith()) + @test_logs (:warn, "[MPI] MPI enabled in configuration but MPI package not found, defaulting to non-MPI mode") match_mode=:any run() + @test PerfTest.num_errors() == 0 + @test C.CONFIG["MPI"]["enabled"] == true + @test PerfTest.mode == PerfTest.NormalMode + end + end +end + +@testset "Transform - the logs are saved as decided by the general.verbose in force at the end of the recipe" begin + logsSaved(f) = intempdir() do + quiet(f) + @test PerfTest.num_errors() == 0 + isdir(".perftest_logs") && !isempty(readdir(".perftest_logs")) + end + + # Used to depend on the value before the recipe is read only + @test logsSaved(() -> (write("recipe.jl", recipeWith(configCall("[general]\nverbose = 2"))); + PerfTest.transform("recipe.jl"))) + @test !logsSaved(() -> (write(C.CONFIG_FILE, "[general]\nverbose = 2\n"); + write("recipe.jl", recipeWith(configCall("[general]\nverbose = 0"))); + PerfTest.transform("recipe.jl"))) + # At the end of the recipe, after its testsets + @test logsSaved(() -> (write("recipe.jl", recipeWith() * configCall("[general]\nverbose = 2")); + PerfTest.transform("recipe.jl"))) + # The included recipe gives the configuration back after it + @test !logsSaved(() -> (write("child.jl", configCall("[general]\nverbose = 2")); + write("recipe.jl", recipeWith("include(\"child.jl\")")); + PerfTest.transform("recipe.jl"))) + # Unchanged without a @perftest_config + @test logsSaved(() -> (write(C.CONFIG_FILE, "[general]\nverbose = 2\n"); + write("recipe.jl", recipeWith()); + PerfTest.transform("recipe.jl"))) + @test logsSaved(() -> (write("recipe.jl", recipeWith()); + runperftests("recipe.jl"; execute=false, verbose=2))) + # A @perftest_config takes priority over the verbose argument + @test !logsSaved(() -> (write("recipe.jl", recipeWith(configCall("[general]\nverbose = 0"))); + runperftests("recipe.jl"; execute=false, verbose=2))) +end diff --git a/test/t15-batch.jl b/test/t15-batch.jl new file mode 100644 index 0000000..3c88d6d --- /dev/null +++ b/test/t15-batch.jl @@ -0,0 +1,406 @@ +using Test +using PerfTest + +const C = PerfTest.Configuration +const T = PerfTest.Topology +const L = PerfTest.Launch + +# Every file based case runs in a fresh temporary directory, so test/perftest_config.toml is never touched +intempdir(f) = mktempdir(dir -> cd(f, dir)) + +quiet(f) = redirect_stdout(f, devnull) + +# Messages of the parse errors of the last transform +parseErrors() = [e.name for e in PerfTest.ctx._global.errors.errors] + +parsingFailed(expr) = occursin("Parsing failed", string(expr)) + +# Message of the error thrown by f +thrown(f) = try f(); "" catch e; sprint(showerror, e) end + +# Executes a saved suite in a fresh process with `dir` as working directory, as runperftests does +function execute(suite, dir) + out = IOBuffer() + cmd = Cmd(`$(Base.julia_cmd()) --startup-file=no --project=$(Base.active_project()) $suite`; dir=dir) + ok = success(pipeline(cmd; stdout=out, stderr=out)) + output = String(take!(out)) + ok || println(output) + return ok, output +end + +const PERFTEST = "@testset \"T\" begin\n @perftest samples = 1 sin(1.0)\nend\n" +recipeWith(lines...) = "using Test, PerfTest\n" * join(lines, "\n") * "\n" * PERFTEST +configCall(toml) = "@perftest_config \"\n$toml\n\"" +# A recipe with `lines` inside its testset, before its @perftest +inTestset(lines...) = "using Test, PerfTest\n@testset \"T\" begin\n" * join(lines, "\n") * "\n @perftest samples = 1 sin(1.0)\nend\n" + +# Transforms a recipe and saves the generated suite next to it +function generate(recipe; kw...) + suite = abspath(replace(recipe, r"\.jl$" => "_perfsuite.jl")) + PerfTest.saveExprAsFile(PerfTest.transform(recipe; kw...), suite) + return suite +end + +# --------------------------------------------------------------------------------------------------------------------- +# C23, a top level @testset for +# --------------------------------------------------------------------------------------------------------------------- + +@testset "Generated suite - a top level @testset for saves each iteration, compared on the next execution" begin + intempdir() do + # Far apart durations, so an iteration compared against another one's reference is a ratio of 4 or 1/4 + write("recipe.jl", """ + using Test, PerfTest + durations = Dict(1 => 0.05, 2 => 0.2) + @testset "Root" for n in [1, 2] + @perftest samples = 3 sleep(durations[n]) + @testset "Inner" begin + @perftest samples = 3 sleep(durations[n] / 2) + end + end + """) + suite = generate("recipe.jl") + @test PerfTest.num_errors() == 0 + + mktempdir() do dir + results = joinpath(dir, ".perftests", "recipe.jl_PERFORMANCE.JLD2") + paths = Set(["Root_1 > Test 1", "Root_1 > Inner > Test 1", "Root_2 > Test 1", "Root_2 > Inner > Test 1"]) + + # Used to throw a MethodError, testsSucceeded(::Vector{Any}), before saving the results + ok, out = execute(suite, dir) + @test ok + @test !occursin("MethodError", out) + @test !occursin("Some tests failed or errored.", out) + @test isfile(results) + @test length(PerfTest.openDataFile(results).results) == 1 + # Each iteration under its name and iterator, as a nested @testset for + @test Set(PerfTest.retrievePerfTests(results; pathonly=true)) == paths + @test Set(PerfTest.retrievePerfTests(results; get=:testsets)) == Set(["Root_1", "Root_2", "Root_1/Inner", "Root_2/Inner"]) + tests = PerfTest.retrievePerfTests(results) + @test sort([t.primitives[:iterator] for t in tests if t.primitives[:iterator] !== nothing]) == [1, 2] + # No reference yet + @test isempty(PerfTest.retrievePerfTests(results; get=:methodologies)[1].metrics) + + ok, out = execute(suite, dir) + @test ok + @test occursin("Previous performance reference for this configuration has been found", out) + @test length(PerfTest.openDataFile(results).results) == 2 + @test Set(PerfTest.retrievePerfTests(results; pathonly=true)) == paths + + # Each iteration is compared against its own reference + methodologies = PerfTest.retrievePerfTests(results; get=:methodologies) + located = PerfTest.retrievePerfTests(results; get=:methodologies, pathonly=true) + @test Set(located) == Set(p * " > Performance Regression Testing" for p in paths) + for (m, path) in zip(methodologies, located) + @test length(m.metrics) == 1 + ratio = m.metrics[1][1].value + @test 60 < ratio < 160 + end + end + end +end + +@testset "Generated suite - a top level @testset for fails when any of its iterations fails" begin + intempdir() do + write("recipe.jl", """ + using Test, PerfTest + @testset "Root" for n in [1, 2] + @perfcompare :iterator < 2 + @perftest samples = 1 sin(1.0) + end + """) + suite = generate("recipe.jl") + @test PerfTest.num_errors() == 0 + + mktempdir() do dir + ok, out = execute(suite, dir) + @test ok + @test occursin("Some tests failed or errored.", out) + results = joinpath(dir, ".perftests", "recipe.jl_PERFORMANCE.JLD2") + @test PerfTest.retrievePerfTests(results; where_pred=PerfTest.testPassed, pathonly=true) == ["Root_1 > Test 1"] + @test PerfTest.retrievePerfTests(results; where_pred=PerfTest.testFailed, pathonly=true) == ["Root_2 > Test 1"] + end + end +end + +# --------------------------------------------------------------------------------------------------------------------- +# C27, automatic flop counting is not supported +# --------------------------------------------------------------------------------------------------------------------- + +const AUTOFLOP = "Automatic flop counting is outdated and not supported, the :autoflop primitive is always 0." +const INSTEAD = "Give the flop count of the target explicitly instead: pass it to @roofline with actual_flops (a number, " * + "or a formula as its operational intensity one), or write it in the formula in place of :autoflop." +const ROOFLINE_INSTEAD = "Pass the flop count of the target to @roofline with actual_flops instead (a number, or a formula as its operational intensity one)" +autoflopError(construct, how; instead = INSTEAD) = "$construct of recipe recipe.jl $how. $AUTOFLOP $instead" +rooflineAutoflopError(where) = autoflopError("The @roofline", "uses :autoflop in $where"; + instead = ROOFLINE_INSTEAD * ", and write it in place of :autoflop in its formulas.") +noActualFlopsError(from) = autoflopError("The @roofline", "gives no actual_flops, so with general.autoflops = true (from $from) " * + "the flops of its target would be counted automatically"; instead = ROOFLINE_INSTEAD * ".") + +@testset "Automatic flop counting - :autoflop in a formula or as a metric is a parse error" begin + intempdir() do + regression_instead = "Track a metric defined with @define_metric from the flop count of the target instead, or pass the flop count to @roofline with actual_flops." + cases = [ + "@roofline actual_flops=:autoflop begin\n 4\n end" => rooflineAutoflopError("actual_flops"), + "@roofline actual_flops=10 begin\n :autoflop / 4\n end" => rooflineAutoflopError("its operational intensity formula"), + "@roofline actual_flops=:autoflop * 2 target_ratio=0.5 begin\n :autoflop / 4\n end" => + rooflineAutoflopError("actual_flops and in its operational intensity formula"), + "@define_metric name=\"m\" units=\"FLOP/s\" begin\n :autoflop / :median_time\n end" => + autoflopError("The @define_metric name = \"m\"", "uses :autoflop in its formula"), + "@auxiliary_metric name=\"a\" units=\"FLOP\" begin\n :autoflop\n end" => + autoflopError("The @auxiliary_metric name = \"a\"", "uses :autoflop in its formula"), + "@perfcompare :autoflop > 1" => autoflopError("The @perfcompare :autoflop > 1", "uses :autoflop"), + "@define_eff_memory_throughput begin\n :autoflop / :median_time\n end" => + autoflopError("The @define_eff_memory_throughput", "uses :autoflop in its formula"), + "@regression metrics=:autoflop" => autoflopError("The @regression", "tracks the metric :autoflop"; instead = regression_instead), + "@regression metrics=[:median_time, :autoflop] low_is_bad=false" => + autoflopError("The @regression", "tracks the metric :autoflop"; instead = regression_instead), + ] + for (line, message) in cases + write("recipe.jl", inTestset(line)) + expr = PerfTest.transform("recipe.jl") + @test parseErrors() == [message] + @test parsingFailed(expr) + end + + # The transform goes on, every use is reported + write("recipe.jl", inTestset("@perfcompare :autoflop > 1", "@roofline actual_flops=10 begin\n :autoflop / 4\n end", "@regression metrics=:nope")) + PerfTest.transform("recipe.jl") + @test parseErrors() == [autoflopError("The @perfcompare :autoflop > 1", "uses :autoflop"), + rooflineAutoflopError("its operational intensity formula"), + "Metric nope is not available in the current context."] + + # Not a use when the methodology is disabled + write("recipe.jl", replace(inTestset("@roofline actual_flops=:autoflop begin\n 4\n end", "@perfcompare :autoflop > 1"), + "@testset" => configCall("[roofline]\nenabled = false\n[perfcompare]\nenabled = false") * "\n@testset"; count=1)) + PerfTest.transform("recipe.jl") + @test PerfTest.num_errors() == 0 + + # With the flop count given, as the ex3-roofline.jl fixture + write("recipe.jl", inTestset("@roofline actual_flops=2 * 10 target_ratio=0.5 begin\n 20 / 4\n end")) + PerfTest.transform("recipe.jl") + @test PerfTest.num_errors() == 0 + end +end + +@testset "Automatic flop counting - general.autoflops = true is a parse error for a @roofline without actual_flops only" begin + intempdir() do + roofline = inTestset("@roofline begin\n 4\n end") + + # From the configuration file, the config argument or a @perftest_config, each one named + write(C.CONFIG_FILE, "[general]\nautoflops = true\n") + write("recipe.jl", roofline) + expr = PerfTest.transform("recipe.jl") + @test parseErrors() == [noActualFlopsError("the configuration file perftest_config.toml")] + @test parsingFailed(expr) + rm(C.CONFIG_FILE) + + PerfTest.transform("recipe.jl"; config=Dict("general" => Dict("autoflops" => true))) + @test parseErrors() == [noActualFlopsError("the config argument of PerfTest.transform")] + + write("recipe.jl", replace(roofline, "@testset" => configCall("[general]\nautoflops = true") * "\n@testset"; count=1)) + PerfTest.transform("recipe.jl") + @test parseErrors() == [noActualFlopsError("the @perftest_config of recipe recipe.jl")] + + # The key alone is not an error: with the flop count given, without a @roofline, or with it disabled + for recipe in (inTestset("@roofline actual_flops=10 begin\n 4\n end"), recipeWith(), + replace(roofline, "@testset" => configCall("[roofline]\nenabled = false") * "\n@testset"; count=1)) + write("recipe.jl", recipe) + PerfTest.transform("recipe.jl"; config=Dict("general" => Dict("autoflops" => true))) + @test PerfTest.num_errors() == 0 + end + + # Without it, as before, the attained flops are not tested + write("recipe.jl", roofline) + PerfTest.transform("recipe.jl") + @test PerfTest.num_errors() == 0 + end +end + +# --------------------------------------------------------------------------------------------------------------------- +# C33, launcher flags +# --------------------------------------------------------------------------------------------------------------------- + +# Arguments of the command between the interpreter and the suite +interpreterArgs(cmd, suite) = cmd.exec[2:findfirst(==(suite), cmd.exec)-1] +suiteArgs(cmd, suite) = cmd.exec[findfirst(==(suite), cmd.exec)+1:end] + +const CONFIG_CHANGE = "set general.numas and general.threads_per_numa (in the configuration file perftest_config.toml, with " * + "the config argument of runperftests or with a @perftest_config of the recipe), or give the recipe a " * + "@perftest_threads, which takes priority over them" +threadsFlagError(suite, flag, n, origin, literal, change, options) = + "Cannot launch the suite $suite with the interpreter flag `$flag` of interpreter_flags: the launcher sets the number of " * + "threads of the process that executes the suite, from the thread arrangement of the suite, to $n (--threads=$n), given " * + "by $origin, which is $literal (#numas, #threads_per_numa) on this machine. Remove `$flag` from interpreter_flags. To " * + "change the number of threads, $change, then generate the suite again (runperftests does). $options" + +@testset "Launcher - the command the suite is launched with" begin + intempdir() do + write("recipe.jl", recipeWith()) + suite = generate("recipe.jl") + @test PerfTest.num_errors() == 0 + defaults = ["--check-bounds=no", "--project=."] + + # An empty suite_flags used to be passed as an empty argument + for suite_flags in ("", " ") + cmd = L.suiteCommand(suite, "", suite_flags) + @test cmd.exec[end] == suite + @test interpreterArgs(cmd, suite) == [defaults; "--threads=1"] + end + @test suiteArgs(L.suiteCommand(suite, "", "--size=3"), suite) == ["--size=3"] + + # In the given order, a flag whose value is a separate token used to be split from it + cmd = L.suiteCommand(suite, "-L setup.jl -O3 -e x=1 -L more.jl") + @test interpreterArgs(cmd, suite) == [defaults; "-L"; "setup.jl"; "-O3"; "-e"; "x=1"; "-L"; "more.jl"; "--threads=1"] + # A flag given several times is passed each time, the interpreter decides + @test interpreterArgs(L.suiteCommand(suite, "--depwarn=yes --depwarn=no"), suite) == [defaults; "--depwarn=yes"; "--depwarn=no"; "--threads=1"] + # A default flag is replaced when given + @test interpreterArgs(L.suiteCommand(suite, "--check-bounds=yes --project=other"), suite) == ["--check-bounds=yes", "--project=other", "--threads=1"] + @test interpreterArgs(L.suiteCommand(suite, "--project"), suite) == ["--check-bounds=no", "--project", "--threads=1"] + end +end + +@testset "Launcher - the number of threads cannot be set with interpreter_flags" begin + intempdir() do + write("recipe.jl", recipeWith()) + suite = generate("recipe.jl") + origin = "the thread setting of the suite, general.numas = \"single\" and general.threads_per_numa = \"single\"" + + @test thrown(() -> L.suiteCommand(suite, "-t 4")) == threadsFlagError(suite, "-t 4", 1, origin, "(1, 1)", CONFIG_CHANGE, T.CONFIG_THREADS_OPTIONS) + # Used to slip through, launching with two thread flags + @test thrown(() -> L.suiteCommand(suite, "-t4")) == threadsFlagError(suite, "-t4", 1, origin, "(1, 1)", CONFIG_CHANGE, T.CONFIG_THREADS_OPTIONS) + for (flags, flag) in ("-tauto" => "-tauto", "--threads=4" => "--threads=4", "--threads 4,1" => "--threads 4,1", "-O3 -t 2 -q" => "-t 2", "-t" => "-t") + message = thrown(() -> L.suiteCommand(suite, flags)) + @test startswith(message, "Cannot launch the suite $suite with the interpreter flag `$flag` of interpreter_flags: ") + @test occursin("to 1 (--threads=1)", message) + end + + # From a @perftest_threads + write("recipe.jl", recipeWith("@perftest_threads (1, 1)")) + suite = generate("recipe.jl") + @test PerfTest.num_errors() == 0 + change = "change the @perftest_threads of the recipe, or remove it to use the thread setting of the configuration " * + "(general.numas and general.threads_per_numa)" + @test thrown(() -> L.suiteCommand(suite, "--threads=8")) == + threadsFlagError(suite, "--threads=8", 1, "the @perftest_threads (1, 1) of the recipe", "(1, 1)", change, PerfTest.THREADS_OPTIONS) + end +end + +# --------------------------------------------------------------------------------------------------------------------- +# C34, general.logs_enabled +# --------------------------------------------------------------------------------------------------------------------- + +@testset "Logs - general.logs_enabled = false writes no log folder nor log file" begin + logsSaved(f) = intempdir() do + quiet(f) + @test PerfTest.num_errors() == 0 + ispath(".perftest_logs") + end + + # Used to be saved anyway with general.verbose >= 2 + @test !logsSaved(() -> (write(C.CONFIG_FILE, "[general]\nlogs_enabled = false\nverbose = 2\n"); + write("recipe.jl", recipeWith()); + PerfTest.transform("recipe.jl"))) + @test !logsSaved(() -> (write("recipe.jl", recipeWith()); + runperftests("recipe.jl"; execute=false, verbose=2, config=Dict("general" => Dict("logs_enabled" => false))))) + # As general.verbose, decided by the configuration in force at the end of the recipe + @test !logsSaved(() -> (write("recipe.jl", recipeWith(configCall("[general]\nverbose = 2")) * configCall("[general]\nlogs_enabled = false")); + PerfTest.transform("recipe.jl"))) + @test logsSaved(() -> (write(C.CONFIG_FILE, "[general]\nlogs_enabled = false\n"); + write("recipe.jl", recipeWith(configCall("[general]\nverbose = 2\nlogs_enabled = true"))); + PerfTest.transform("recipe.jl"))) + # Unchanged when enabled + @test logsSaved(() -> (write("recipe.jl", recipeWith(configCall("[general]\nverbose = 2"))); + PerfTest.transform("recipe.jl"))) + + intempdir() do + # Nothing is logged in memory either + write(C.CONFIG_FILE, "[general]\nlogs_enabled = false\n") + write("recipe.jl", recipeWith()) + PerfTest.transform("recipe.jl") + @test !occursin("[TESTSET]", PerfTest.dumpLogsString()) + rm(C.CONFIG_FILE) + PerfTest.transform("recipe.jl") + @test occursin("[TESTSET]", PerfTest.dumpLogsString()) + end +end + +@testset "Logs - general.logs_enabled = false applies to the executed suite" begin + intempdir() do + write(C.CONFIG_FILE, "[general]\nlogs_enabled = false\nverbose = 2\n") + write("recipe.jl", recipeWith()) + suite = generate("recipe.jl") + @test PerfTest.num_errors() == 0 + @test !ispath(".perftest_logs") + + mktempdir() do dir + ok, out = execute(suite, dir) + @test ok + # Its logs are neither printed nor saved, its other output is + @test !occursin("[MACHINE]", out) + @test occursin("AT: T", out) + @test !ispath(joinpath(dir, ".perftest_logs")) + @test isfile(joinpath(dir, ".perftests", "recipe.jl_PERFORMANCE.JLD2")) + end + end +end + +# --------------------------------------------------------------------------------------------------------------------- +# C36, @regression low_is_bad and threshold of another length than metrics +# --------------------------------------------------------------------------------------------------------------------- + +lengthError(key, value, metrics) = + "Invalid $key in the @regression of recipe recipe.jl: $key = $value gives $metrics. $key is either a single " * + "$(key == "low_is_bad" ? Bool : Float64), which applies to every metric, or a vector with one " * + "$(key == "low_is_bad" ? Bool : Float64) per metric, in the order of metrics" + +@testset "@regression - low_is_bad and threshold give one value per metric, otherwise a parse error" begin + intempdir() do + cases = [ + # Used to report the error, then throw a MethodError, iterate(::Nothing) + "metrics=:median_time low_is_bad=[true, false]" => [lengthError("low_is_bad", "[true, false]", "2 values for 1 metric (:median_time)")], + "metrics=:median_time threshold=[0.9, 0.8]" => [lengthError("threshold", "[0.9, 0.8]", "2 values for 1 metric (:median_time)")], + "metrics=:median_time threshold=[0.9, 0.8] low_is_bad=[true, false]" => + [lengthError("low_is_bad", "[true, false]", "2 values for 1 metric (:median_time)"), + lengthError("threshold", "[0.9, 0.8]", "2 values for 1 metric (:median_time)")], + # The inverse ones, used to say "either 1 to apply to all" for a vector of 1 value + "metrics=[:median_time, :min_time] low_is_bad=[true]" => [lengthError("low_is_bad", "[true]", "1 value for 2 metrics (:median_time, :min_time)")], + "metrics=[:median_time, :min_time] threshold=[0.9]" => [lengthError("threshold", "[0.9]", "1 value for 2 metrics (:median_time, :min_time)")], + "metrics=[:median_time, :min_time] threshold=[0.9, 0.8, 0.7]" => [lengthError("threshold", "[0.9, 0.8, 0.7]", "3 values for 2 metrics (:median_time, :min_time)")], + "metrics=[:median_time, :min_time] low_is_bad=[true, false, true] threshold=[0.9]" => + [lengthError("low_is_bad", "[true, false, true]", "3 values for 2 metrics (:median_time, :min_time)"), + lengthError("threshold", "[0.9]", "1 value for 2 metrics (:median_time, :min_time)")], + # Too many arguments, used to throw a MethodError, haskey(::Nothing, ...) + "a=1 b=2 c=3 d=4 e=5" => ["Invalid number of arguments in @regression, expected from 0 to 4, got 5"], + ] + for (args, messages) in cases + # At the top level testset, which already has a regression, and in a nested one + for recipe in (inTestset("@regression $args"), + "using Test, PerfTest\n@testset \"T\" begin\n@testset \"N\" begin\n@regression $args\n@perftest samples = 1 sin(1.0)\nend\nend\n") + write("recipe.jl", recipe) + expr = PerfTest.transform("recipe.jl") + @test parseErrors() == messages + @test parsingFailed(expr) + end + end + + # The transform goes on collecting the errors of the recipe + write("recipe.jl", inTestset("@regression metrics=:median_time low_is_bad=[true, false]", "@regression metrics=:nope", + "@define_metric name=\"m\" units=\"x\" begin\n :autoflop\n end")) + PerfTest.transform("recipe.jl") + @test parseErrors() == [lengthError("low_is_bad", "[true, false]", "2 values for 1 metric (:median_time)"), + "Metric nope is not available in the current context.", + autoflopError("The @define_metric name = \"m\"", "uses :autoflop in its formula")] + + # One value per metric, or a single one for every metric + # The comparisons of the generated suite, see regression() + for (args, present, absent) in (("metrics=:median_time low_is_bad=[false] threshold=[1.2]", ["ratio < 1.2"], ["ratio < 1.1", "ratio >"]), + ("metrics=[:median_time, :min_time] low_is_bad=false threshold=1.3", ["ratio < 1.3"], ["ratio < 1.1", "ratio >"]), + ("metrics=[:median_time, :min_time] low_is_bad=[false, true]", ["ratio < 1.1", "ratio > 0.9"], [])) + write("recipe.jl", inTestset("@regression $args")) + code = string(PerfTest.transform("recipe.jl")) + @test PerfTest.num_errors() == 0 + @test all(c -> occursin(c, code), present) + @test !any(c -> occursin(c, code), absent) + end + end +end diff --git a/test/t16-metric-symbol.jl b/test/t16-metric-symbol.jl new file mode 100644 index 0000000..c97b285 --- /dev/null +++ b/test/t16-metric-symbol.jl @@ -0,0 +1,161 @@ +using Test +using PerfTest + +# The symbol parameter of @define_metric, @auxiliary_metric and @define_benchmark sets the symbol other formulas and +# macros refer to them by, Symbol(name) when absent + +# Every file based case runs in a fresh temporary directory, so test/perftest_config.toml is never touched +intempdir(f) = mktempdir(dir -> cd(f, dir)) + +# Messages of the parse errors of the last transform +parseErrors() = [e.name for e in PerfTest.ctx._global.errors.errors] + +# Executes a saved suite in a fresh process with `dir` as working directory, as runperftests does +function execute(suite, dir) + out = IOBuffer() + cmd = Cmd(`$(Base.julia_cmd()) --startup-file=no --project=$(Base.active_project()) $suite`; dir=dir) + ok = success(pipeline(cmd; stdout=out, stderr=out)) + output = String(take!(out)) + ok || println(output) + return ok, output +end + +# A recipe with `lines` inside its testset, before its @perftest +inTestset(lines...) = "using Test, PerfTest\n@testset \"T\" begin\n" * join(lines, "\n") * "\n @perftest samples = 1 sin(1.0)\nend\n" + +# Source of the suite generated from a recipe with `lines` inside its testset +function transformed(lines...) + write("recipe.jl", inTestset(lines...)) + return string(PerfTest.transform("recipe.jl")) +end + +const CT = """ + @define_metric name = "Custom time" units = "1/s" symbol = :ct begin + 1 / :median_time + end""" + +@testset "Custom metric symbol - formulas and @regression refer to the metric by its symbol" begin + intempdir() do + for symbol in (":ct", "\"ct\"") + source = transformed(replace(CT, ":ct" => symbol), + """@define_metric name = "Double" units = "1/s" begin + 2 * :ct + end""", + "@regression metrics = :ct") + @test PerfTest.num_errors() == 0 + @test occursin("test_res.metrics[:ct]", source) + # Without symbol, its name as a symbol, as before + @test occursin("test_res.metrics[:Double]", source) + @test !occursin("Symbol(\"Custom time\")", source) + end + + # The name as a symbol is the default + source = transformed("""@define_metric name = "custom_time" units = "1/s" begin + 1 / :median_time + end""", + "@regression metrics = \"custom_time\"") + @test PerfTest.num_errors() == 0 + @test occursin("test_res.metrics[:custom_time]", source) + end +end + +@testset "Custom metric symbol - @auxiliary_metric and @define_benchmark" begin + intempdir() do + source = transformed(CT, + """@auxiliary_metric name = "Aux thing" units = "s" symbol = :ax begin + 2 * :ct + end""") + @test PerfTest.num_errors() == 0 + @test occursin("test_res.auxiliar[:ax]", source) + + # A benchmark is referred to by its symbol too, e.g. by the effective memory throughput methodology + source = transformed("""@define_benchmark name = "My bench" units = "GB/s" symbol = :bw begin + 2.0 + end""", + """@define_eff_memory_throughput custom_benchmark = :bw begin + 1 / :median_time + end""") + @test PerfTest.num_errors() == 0 + @test occursin("custom_benchmarks[:bw]", source) + + # Its name is no longer the symbol + transformed("""@define_benchmark name = "bw" units = "GB/s" symbol = :other begin + 2.0 + end""", + """@define_eff_memory_throughput custom_benchmark = :bw begin + 1 / :median_time + end""") + @test parseErrors() == ["Undefined custom benchmark bw"] + end +end + +@testset "Custom metric symbol - errors" begin + intempdir() do + # A built-in formula symbol would be shadowed by the built-in value in formulas + for (macro_name, kind) in (("@define_metric", "metric"), ("@auxiliary_metric", "metric"), ("@define_benchmark", "benchmark")) + transformed("""$macro_name name = "m" units = "s" symbol = :median_time begin + 1.0 + end""") + errors = parseErrors() + @test length(errors) == 1 + @test startswith(only(errors), "The $macro_name name = \"m\" of recipe ") + @test occursin("sets symbol = :median_time, which is a built-in formula symbol", only(errors)) + end + + transformed("""@define_metric name = "m" units = "s" symbol = "" begin + 1.0 + end""") + @test length(parseErrors()) == 1 + @test occursin("sets an empty symbol", only(parseErrors())) + + # Not a symbol nor a string + transformed("""@define_metric name = "m" units = "s" symbol = 3 begin + 1.0 + end""") + @test parseErrors() == ["Invalid parameter type Int64 for symbol in macro @define_metric, expected Union{String, Symbol}"] + + # Referred to by its name instead of its symbol + transformed(CT, "@regression metrics = \"Custom time\"") + @test parseErrors() == ["Metric Custom time is not available in the current context. " * + "The metric named \"Custom time\" is referred to by its symbol :ct."] + end +end + +@testset "Generated suite - custom metrics, auxiliary metrics and benchmarks are resolved by their symbol" begin + intempdir() do + write("recipe.jl", inTestset( + """@define_benchmark name = "My bench" units = "GB/s" symbol = :bw begin + 2.0 + end""", + CT, + """@define_metric name = "Double" units = "1/s" begin + 2 * :ct + end""", + """@auxiliary_metric name = "Aux thing" units = "s" symbol = "ax" begin + :ct * :bw + end""", + "@regression metrics = :ct")) + suite = abspath("recipe_perfsuite.jl") + PerfTest.saveExprAsFile(PerfTest.transform("recipe.jl"), suite) + @test PerfTest.num_errors() == 0 + + mktempdir() do dir + results = joinpath(dir, ".perftests", "recipe.jl_PERFORMANCE.JLD2") + # The first execution saves the reference, the second one compares against it + for _ in 1:2 + ok, _ = execute(suite, dir) + @test ok + end + + test = PerfTest.retrievePerfTests(results)[end] + @test Set(keys(test.metrics)) == Set([:ct, :Double]) + @test Set(keys(test.auxiliar)) == Set([:ax]) + @test test.metrics[:Double].value ≈ 2 * test.metrics[:ct].value + # :bw is the benchmark, 2.0 + @test test.auxiliar[:ax].value ≈ 2 * test.metrics[:ct].value + + regression = PerfTest.retrievePerfTests(results; get=:methodologies)[end] + @test ":ct Difference" in [m[1].name for m in regression.metrics] + end + end +end diff --git a/test/t2-validation-macro.jl b/test/t2-validation-macro.jl index 6fd0394..bfd1070 100644 --- a/test/t2-validation-macro.jl +++ b/test/t2-validation-macro.jl @@ -93,3 +93,85 @@ using Test, PerfTest #PerfTest.printErrors(ctx) end + +@testset "Macro validation - Union{T,Vector{T}} parameters" begin + + ctx = PerfTest.Context(PerfTest.GlobalContext("path", PerfTest.VecErrorCollection(), PerfTest.formula_symbols)) + + params = Dict{Symbol,PerfTest.MacroParameter}( + :metrics => PerfTest.MacroParameter(:metrics, Union{Symbol,String,Vector{Union{Symbol,String}}}, (x) -> true), + ) + + f = PerfTest.validateBlocklessMacro(params) + + # VALID: quoted-symbol scalar + expr = quote + @macro metrics = :a + end + parsed = f(expr, ctx) + @test PerfTest.num_errors(ctx) == 0 + @test parsed[:metrics] == :a + + # VALID: vector literal of quoted symbols + expr = quote + @macro metrics = [:a, :b] + end + parsed = f(expr, ctx) + @test PerfTest.num_errors(ctx) == 0 + @test parsed[:metrics] == [:a, :b] + + # VALID: vector literal of strings + expr = quote + @macro metrics = ["a", "b"] + end + parsed = f(expr, ctx) + @test PerfTest.num_errors(ctx) == 0 + @test parsed[:metrics] == ["a", "b"] + + # INVALID: vector literal with a wrongly-typed element must still fail + expr = quote + @macro metrics = [:a, 3] + end + parsed = f(expr, ctx) + @test PerfTest.num_errors(ctx) == 1 + @test !haskey(parsed, :metrics) + +end + +@testset "Macro validation - interpolated String last parameter" begin + + ctx = PerfTest.Context(PerfTest.GlobalContext("path", PerfTest.VecErrorCollection(), PerfTest.formula_symbols)) + + params = Dict{Symbol,PerfTest.MacroParameter}( + Symbol("") => PerfTest.MacroParameter(Symbol(""), String, true) + ) + + f = PerfTest.validateMacro(params) + + # VALID: plain string literal, unchanged behavior + expr = quote + @macro "plain string" + end + parsed = f(expr, ctx) + @test PerfTest.num_errors(ctx) == 0 + @test parsed[Symbol("")] == "plain string" + + # VALID: interpolated string must be accepted, and kept as a raw Expr + # (not evaluated during validation) + expr = quote + @macro "prefix_$(1 + 1)_suffix" + end + parsed = f(expr, ctx) + @test PerfTest.num_errors(ctx) == 0 + @test parsed[Symbol("")] isa Expr + @test parsed[Symbol("")].head == :string + + # INVALID: wrong type entirely should still be rejected + expr = quote + @macro 4 + 5 + end + parsed = f(expr, ctx) + @test PerfTest.num_errors(ctx) == 1 + @test !haskey(parsed, Symbol("")) + +end diff --git a/test/t3-transforms.jl b/test/t3-transforms.jl index 594884a..b31bedb 100644 --- a/test/t3-transforms.jl +++ b/test/t3-transforms.jl @@ -1,5 +1,5 @@ -using Test, PerfTest +using Test, PerfTest, MacroTools prefix = "test-recipes/" @@ -40,9 +40,97 @@ checks = [ for (i, source) in enumerate(sources) expr = PerfTest.transform(source) log = PerfTest.dumpLogsString() + # test/perftest_config.toml sets general.autoflops = true, ex3-roofline.jl gives its flop count + @test PerfTest.num_errors() == 0 for check in checks[i] @test occursin(check, log) end end end + +@testset "System Tests - @regression with vector-literal arguments" begin + + PerfTest.transform(prefix * "ex10-regression-vector.jl") + log = PerfTest.dumpLogsString() + + @test PerfTest.num_errors() == 0 + @test !occursin("[PARSING ERROR]", log) + @test occursin("METRICS: [:median_time, :custom_metric1, :custom_metric2]", log) + @test occursin("LOW_IS_BAD: Any[false, false, true]", log) +end + +@testset "System Tests - @perftest_config with string interpolation" begin + + PerfTest.transform(prefix * "ex14-perftest-config-interpolation.jl") + log = PerfTest.dumpLogsString() + + @test PerfTest.num_errors() == 0 + @test !occursin("[PARSING ERROR]", log) + + # Non-interpolated sibling keys must still take effect during this + # transform pass, exactly as they do without interpolation. + @test PerfTest.Configuration.CONFIG["general"]["verbose"] == 3 + @test PerfTest.Configuration.CONFIG["regression"]["enabled"] == true +end + +@testset "rewrapDoBlockBodies - repairs prettify's single-statement do-block flattening" begin + + # Reproduces, in isolation, the exact corruption `MacroTools.prettify` used to + # introduce: a `do`-block whose body is a single tuple-literal statement gets + # `flatten`-ed down to a bare (non-:block) tuple expression, which Base's `:do` + # printer then mis-renders as two unparenthesized statements. + ex = quote + (L, D) = get!(_dense_factors, ldlsolver) do + (Matrix{Float64}(undef, n, n), Vector{Float64}(undef, n)) + end + end + + pretty = MacroTools.prettify(ex) + corrupted = string(pretty) + @test !occursin("(Matrix{Float64}(undef, n, n), Vector{Float64}(undef, n))", corrupted) + + fixed = string(PerfTest.rewrapDoBlockBodies(pretty)) + @test occursin("(Matrix{Float64}(undef, n, n), Vector{Float64}(undef, n))", fixed) +end + +@testset "System Tests - do-block tuple bodies survive full transform" begin + + expr = PerfTest.transform(prefix * "ex11-do-block-tuple.jl") + source = string(expr.args[1]) + + @test occursin("(Vector{Float64}(undef, n), Vector{Float64}(undef, n))", source) +end + +@testset "System Tests - @regression/@perfcompare showvar parameter" begin + + expr = PerfTest.transform(prefix * "ex13-regression-showvar.jl") + source = string(expr) + log = PerfTest.dumpLogsString() + + @test PerfTest.num_errors() == 0 + @test !occursin("[PARSING ERROR]", log) + + # Both macros accept showvar=... and it survives into the generated suite's Metric_Test + # construction (spliced as a literal Bool at parse time, see regression()/buildPerfcmp). + @test occursin("showvar = true", source) +end + +@testset "System Tests - regression baseline keys are loop-aware inside @testset for" begin + + # `@perftest`/`@regression` inside a `@testset "..." for n in ...` must resolve their + # saved-baseline lookup key at suite run time (using the current loop variable), not + # bake a single static key shared by every iteration - otherwise every iteration ends + # up comparing against whichever iteration's result was saved last. See "Sleep by size" + # in ex12-regression-for-loop.jl, which has this shape. + expr = PerfTest.transform(prefix * "ex12-regression-for-loop.jl") + source = string(expr) + + @test PerfTest.num_errors() == 0 + @test occursin("string(\"Sleep by size\", \"_\", n)", source) + @test !occursin("[\"Wrapper\", \"Sleep by size\"]", source) + + # The loop variable used as an index in the target must be interpolated, otherwise the + # benchmark (evaluated at module scope) cannot see it + @test occursin("(\$sleep)((\$durations)[\$n])", string(expr.args[1])) +end diff --git a/test/t4-measure.jl b/test/t4-measure.jl index 550ef0b..2d59fea 100644 --- a/test/t4-measure.jl +++ b/test/t4-measure.jl @@ -1,7 +1,7 @@ using Test using PerfTest -view = false +view = true @testset "Measure - Full pass" begin @@ -31,26 +31,31 @@ view = false @test all([occursin("pass", t) for t in passed]) @test all([occursin("fail", t) for t in failed]) - @test length(passed) == 5 - @test length(failed) == 5 + # "Perfcompare" is a `@testset ... for duration in [0.1, 0.5]`, saved once per iteration + @test length(passed) == 6 + @test length(failed) == 6 + # Retrieval order within a testset level follows Dict order, not declaration order, + # so methodologies are located by content rather than by index methodologies = PerfTest.retrievePerfTests(".perftests/ex7-measure-tests.jl_PERFORMANCE.JLD2", get=:methodologies) - @test length(methodologies) == 10 - @test methodologies[1].name == "Effective Memory Throughput" - @test 1.95 <= methodologies[1].custom_elements[:abs].value <= 2.0 - @test methodologies[1].custom_elements[:abs_ref].value == 2.0 - - @test methodologies[2].name == "Performance Assertion" - @test methodologies[2].metrics[1][1].value == true - @test methodologies[2].metrics[1][2].succeeded == true - @test methodologies[2].metrics[1][1].name == ":(duration * 0.9 < :median_time < duration * 1.1)" + @test length(methodologies) == 12 + + effmem = methodologies[findfirst(m -> m.name == "Effective Memory Throughput", methodologies)] + @test 1.95 <= effmem.custom_elements[:abs].value <= 2.0 + @test effmem.custom_elements[:abs_ref].value == 2.0 + + perfcmp_expr = ":(duration * 0.9 < :median_time < duration * 1.1)" + perfcmp = filter(m -> m.name == "Performance Assertion" && m.metrics[1][1].name == perfcmp_expr, methodologies) + @test length(perfcmp) == 2 + @test all(m -> m.metrics[1][1].value == true, perfcmp) + @test all(m -> m.metrics[1][2].succeeded == true, perfcmp) end # Cleanup try - rm("_t4_tmp_t4_tmp.jl") rm(".perftests/ex7-measure-tests.jl_PERFORMANCE.JLD2") rm(".perftests", recursive=true) + rm("_t4_tmp_t4_tmp.jl") catch @warn "Automatic file cleanup failed." end diff --git a/test/t7-regression-for-loop.jl b/test/t7-regression-for-loop.jl new file mode 100644 index 0000000..a6d4bf2 --- /dev/null +++ b/test/t7-regression-for-loop.jl @@ -0,0 +1,62 @@ +using Test, PerfTest + +view = false + +datafile = ".perftests/ex12-regression-for-loop.jl_PERFORMANCE.JLD2" + +@testset "Regression - @testset for loop, per-iteration baselines" begin + + @testset "Run transformation" begin + e = PerfTest.transform("test-recipes/ex12-regression-for-loop.jl") + PerfTest.saveExprAsFile(e, "_t7_tmp_t7_tmp.jl") + + @test PerfTest.num_errors() == 0 + end + + @testset "Execution" begin + for i in 1:2 + + @testset "PerfTest env" begin + if view + include("_t7_tmp_t7_tmp.jl") + else + redirect_stdout(devnull) do + include("_t7_tmp_t7_tmp.jl") + end + end + end + Test.get_testset().results = [] + + tests = PerfTest.retrievePerfTests(datafile, get=:tests) + paths = PerfTest.retrievePerfTests(datafile, get=:tests, pathonly=true) + + @testset "Run $i: each loop iteration is saved distinctly (not collapsed to the last)" begin + @test length(tests) == 3 + @test length(unique(paths)) == 3 + @test Set(t.primitives[:iterator] for t in tests) == Set([1, 2, 3]) + end + + # Durations (0.4s / 0.2s / 0.05s, by iterator) are held constant across runs, so + # a correctly-matched per-iteration comparison should always pass. Under the + # collapsed-to-last-iteration bug, every iteration would instead be compared + # against the last iteration's (0.05s) reference, and the 0.4s/0.2s iterations + # would spuriously fail as regressions. + passed = PerfTest.retrievePerfTests(datafile, get=:tests, where_pred=PerfTest.testPassed, pathonly=true) + failed = PerfTest.retrievePerfTests(datafile, get=:tests, where_pred=PerfTest.testFailed, pathonly=true) + + @testset "Run $i: regression compares each iteration against its own baseline" begin + @test length(passed) == 3 + @test length(failed) == 0 + end + end + end + + # Cleanup + try + rm("_t7_tmp_t7_tmp.jl") + rm(".perftests/ex12-regression-for-loop.jl_PERFORMANCE.JLD2") + rm(".perftests", recursive=true) + catch + @warn "Automatic file cleanup failed." + end +end diff --git a/test/t8-sample-median.jl b/test/t8-sample-median.jl new file mode 100644 index 0000000..7a280b2 --- /dev/null +++ b/test/t8-sample-median.jl @@ -0,0 +1,10 @@ +using Test +using PerfTest + +@testset "_sample_median tests" begin + @test PerfTest._sample_median([1.0, 2.0, 3.0]) == 2.0 + @test PerfTest._sample_median([1.0, 2.0, 3.0, 4.0]) == 2.5 + @test PerfTest._sample_median([5.0]) == 5.0 + @test PerfTest._sample_median([3.0, 1.0, 2.0]) == 2.0 + @test PerfTest._sample_median([4, 1, 3, 2]) == 2.5 +end diff --git a/test/t9-sampled-value.jl b/test/t9-sampled-value.jl new file mode 100644 index 0000000..449196c --- /dev/null +++ b/test/t9-sampled-value.jl @@ -0,0 +1,93 @@ +using Test +using PerfTest + +const SV = PerfTest.SampledValue + +@testset "SampledValue construction" begin + sv = SV([1.0, 2.0, 3.0, 4.0, 5.0], 3.0) + @test sv.value == 3.0 + @test sv.n == 5 + @test sv.sem > 0 + + single = SV([1.0], 1.0) + @test single.sem == 0.0 + @test single.n == 1 +end + +@testset "SampledValue promotion / conversion" begin + x = convert(SV{Float64}, 5.0) + @test x.value == 5.0 + @test x.sem == 0.0 + @test x.n == typemax(Int) + + @test promote_type(SV{Float64}, Float64) == SV{Float64} +end + +@testset "SampledValue comparisons ignore sem/n" begin + a = SV(0.04, 0.01, 50) + @test a < 0.05 + @test a == SV(0.04, 0.5, 3) + @test !(a == 0.05) +end + +@testset "SampledValue +/- (absolute quadrature)" begin + a = SV(10.0, 1.0, 40) + b = SV(5.0, 2.0, 60) + s = a + b + @test s.value == 15.0 + @test isapprox(s.sem, sqrt(1.0^2 + 2.0^2)) + @test s.n == 40 + + d = a - b + @test d.value == 5.0 + @test isapprox(d.sem, sqrt(1.0^2 + 2.0^2)) + + @test (-a).value == -10.0 + @test (-a).sem == 1.0 + @test (+a).value == a.value +end + +@testset "SampledValue * // (relative quadrature)" begin + a = SV(10.0, 1.0, 40) # 10% relative error + b = SV(4.0, 0.4, 60) # 10% relative error + + p = a * b + @test p.value == 40.0 + @test isapprox(p.sem, 40.0 * sqrt(0.1^2 + 0.1^2)) + @test p.n == 40 + + q = a / b + @test q.value == 2.5 + @test isapprox(q.sem, 2.5 * sqrt(0.1^2 + 0.1^2)) +end + +@testset "SampledValue mixed arithmetic with plain Real" begin + a = SV(10.0, 1.0, 40) + r = a + 5.0 + @test r isa SV + @test r.value == 15.0 + @test r.sem == 1.0 # plain Real contributes zero variance + + r2 = a * 2.0 + @test r2.value == 20.0 + @test isapprox(r2.sem, 2.0) # relative error of a (10%) applied to new value (20.0) + + r3 = 100.0 / a + @test r3.value == 10.0 +end + +@testset "SampledValue degenerate / division-by-zero cases" begin + a = SV(10.0, 1.0, 40) + zero_val = SV(0.0, 0.0, 40) + d = a / zero_val + @test isnan(d.value) + @test isnan(d.sem) +end + +@testset "sum over a Vector{SampledValue}" begin + vals = [SV(1.0, 0.1, 40), SV(2.0, 0.2, 40), SV(3.0, 0.3, 40)] + s = sum(vals) + @test s.value == 6.0 + @test isapprox(s.sem, sqrt(0.1^2 + 0.2^2 + 0.3^2)) + @test s.n == 40 +end diff --git a/test/test-recipes/ex10-regression-vector.jl b/test/test-recipes/ex10-regression-vector.jl new file mode 100644 index 0000000..298ccd4 --- /dev/null +++ b/test/test-recipes/ex10-regression-vector.jl @@ -0,0 +1,25 @@ +using Test, PerfTest + +@perftest_config " +[regression] +enabled = true +" + +@testset "Vector regression args" begin + + @define_metric name = "custom_metric1" units = "1/s" begin + 1 / :median_time + end + + @define_metric name = "custom_metric2" units = "s" begin + :median_time + end + + # Mirrors the multi-metric @regression call from + # examples/example-kkt-cholesky-regression/clarabel_perftest.jl, which + # requires the macro to accept vector-literal arguments. + @regression metrics=[:median_time, :custom_metric1, :custom_metric2] threshold=[1.15, 1.20, 0.85] low_is_bad=[false, false, true] + + @perftest samples = 5 sleep(0.01) + +end diff --git a/test/test-recipes/ex11-do-block-tuple.jl b/test/test-recipes/ex11-do-block-tuple.jl new file mode 100644 index 0000000..eebbab9 --- /dev/null +++ b/test/test-recipes/ex11-do-block-tuple.jl @@ -0,0 +1,29 @@ +using Test, PerfTest + +# Regression fixture: a plain (non-macro) function whose `do`-block body is a +# single tuple-literal statement, e.g. `get!(dict, key) do; (A, B); end`. This +# is the exact shape that `MacroTools.prettify`'s `flatten` pass used to strip +# down to a bare, unparenthesized `Expr(:tuple, A, B)`, which Julia's `Base.show` +# for `:do` expressions then printed as two separate statements instead of one +# tuple, silently changing what the `do`-block returns. +const _cache = IdDict{Symbol,Tuple{Vector{Float64},Vector{Float64}}}() + +function fill_cache!(key::Symbol, n::Int) + (a, b) = get!(_cache, key) do + (Vector{Float64}(undef, n), Vector{Float64}(undef, n)) + end + return (a, b) +end + +@perftest_config " +[regression] +enabled = false +[general] +verbose = 0 +" + +@testset "do-block tuple" begin + @perftest begin + fill_cache!(:x, 4) + end +end diff --git a/test/test-recipes/ex12-regression-for-loop.jl b/test/test-recipes/ex12-regression-for-loop.jl new file mode 100644 index 0000000..8156af9 --- /dev/null +++ b/test/test-recipes/ex12-regression-for-loop.jl @@ -0,0 +1,26 @@ +# Careful changing testset names (used for parsing) +using Test, PerfTest + +@perftest_config " +[regression] +enabled = true +" + +# Durations are deliberately far apart and, crucially, held constant across +# runs (no execution_number scaling): under the collapsed-to-last-iteration +# bug, every iteration ends up compared against n=3's (the last iteration's) +# short reference, so n=1/n=2's much longer runtime looks like a huge +# regression on the second execution even though each iteration's own +# runtime never changed. Correct per-iteration matching should pass every +# iteration on every execution. +durations = Dict(1 => 0.4, 2 => 0.2, 3 => 0.05) + +@testset "Wrapper" begin + + @testset "Sleep by size" for n in [1, 2, 3] + + @perftest samples = 3 sleep(durations[n]) + + end + +end diff --git a/test/test-recipes/ex13-regression-showvar.jl b/test/test-recipes/ex13-regression-showvar.jl new file mode 100644 index 0000000..5092255 --- /dev/null +++ b/test/test-recipes/ex13-regression-showvar.jl @@ -0,0 +1,42 @@ +# Careful changing testset names (used for parsing) +using Test, PerfTest + +@perftest_config " +[regression] +enabled = true +[perfcompare] +enabled = true +" + +@testset "Showvar Tests" begin + + @testset "Regression with showvar, enough samples" begin + # samples=100 on a near-instant target reliably clears MIN_VARIANCE_SAMPLES (30), + # so median_time's variance should be populated and, since showvar=true, printed. + @regression threshold=0.5 low_is_bad=false metrics=:median_time showvar=true + + @auxiliary_metric name = "half_time" units = "s" begin + :median_time / 2 + end + + @perftest samples = 100 (1 + 1) + end + + @testset "Regression with showvar, too few samples" begin + # samples=5 stays below MIN_VARIANCE_SAMPLES, so variance must not be shown even + # though showvar=true was requested. + @regression threshold=0.5 low_is_bad=false metrics=:median_time showvar=true + + @perftest samples = 5 (1 + 1) + end + + @testset "Perfcompare with showvar" begin + @perfcompare showvar=true :median_time < 10.0 + + @auxiliary_metric name = "double_time" units = "s" begin + :median_time * 2 + end + + @perftest samples = 100 (1 + 1) + end +end diff --git a/test/test-recipes/ex14-perftest-config-interpolation.jl b/test/test-recipes/ex14-perftest-config-interpolation.jl new file mode 100644 index 0000000..95f0fc6 --- /dev/null +++ b/test/test-recipes/ex14-perftest-config-interpolation.jl @@ -0,0 +1,23 @@ +using Test +using PerfTest + +@perftest_config " +[general] +verbose = 3 +[regression] +enabled = true +dedicated_reference_file = 'ref_$(1 + 1).JLD2' +" + +function testfun(a :: Int) + c = 1 + for i in 1:a + c = c + (i ^ 2) / c + end + return c +end + +@testset "CONFIG INTERPOLATION" begin + x = @perftest testfun(10) + @test x == 29.299107353275982 +end diff --git a/test/test-recipes/ex15-recursive-config-inner.jl b/test/test-recipes/ex15-recursive-config-inner.jl new file mode 100644 index 0000000..93737c4 --- /dev/null +++ b/test/test-recipes/ex15-recursive-config-inner.jl @@ -0,0 +1,16 @@ +using Test +using PerfTest + +@perftest_config " +[memory_bandwidth] +default_threshold = 0.25 +[regression] +default_threshold = 2.5 +" + +@testset "INNER" begin + @define_eff_memory_throughput begin + 1.0 + end + @perftest sum(1:10) +end diff --git a/test/test-recipes/ex15-recursive-config.jl b/test/test-recipes/ex15-recursive-config.jl new file mode 100644 index 0000000..ff081a0 --- /dev/null +++ b/test/test-recipes/ex15-recursive-config.jl @@ -0,0 +1,26 @@ +using Test +using PerfTest + +@perftest_config " +[general] +recursive = true +[memory_bandwidth] +default_threshold = 0.75 +" + +@testset "BEFORE" begin + @define_eff_memory_throughput begin + 1.0 + end + @perftest sum(1:10) +end + +# Its configuration must apply only inside it +include("ex15-recursive-config-inner.jl") + +@testset "AFTER" begin + @define_eff_memory_throughput begin + 1.0 + end + @perftest sum(1:10) +end diff --git a/test/test-recipes/ex16-config-generated-suite.jl b/test/test-recipes/ex16-config-generated-suite.jl new file mode 100644 index 0000000..cd54898 --- /dev/null +++ b/test/test-recipes/ex16-config-generated-suite.jl @@ -0,0 +1,16 @@ +using Test +using PerfTest + +# No @perftest_config, the configuration is the one of the perftest_config.toml present at generation + +@on_perftest_exec begin + # Records the configuration seen by the executing suite in its working directory + dumpConfig(name) = open(io -> PerfTest.TOML.print(io, PerfTest.Configuration.CONFIG), "config_$(name).toml", "w") +end + +@testset "GENERATED" begin + @on_perftest_exec begin + dumpConfig("GENERATED") + end + @perftest samples = 1 sin(1.0) +end diff --git a/test/test-recipes/ex17-config-recursive-inner.jl b/test/test-recipes/ex17-config-recursive-inner.jl new file mode 100644 index 0000000..aced27f --- /dev/null +++ b/test/test-recipes/ex17-config-recursive-inner.jl @@ -0,0 +1,14 @@ +# Included by ex17-config-recursive.jl inside a testset + +@perftest_config " +[general] +verbose = 1 +max_saved_results = 3 +" + +@testset "INNER" begin + @on_perftest_exec begin + dumpConfig("INNER") + end + @perftest samples = 1 sin(1.0) +end diff --git a/test/test-recipes/ex17-config-recursive.jl b/test/test-recipes/ex17-config-recursive.jl new file mode 100644 index 0000000..6e32988 --- /dev/null +++ b/test/test-recipes/ex17-config-recursive.jl @@ -0,0 +1,33 @@ +using Test +using PerfTest + +@perftest_config " +[general] +max_saved_results = 11 +" + +@on_perftest_exec begin + # Records the configuration seen by the executing suite in its working directory + dumpConfig(name) = open(io -> PerfTest.TOML.print(io, PerfTest.Configuration.CONFIG), "config_$(name).toml", "w") +end + +@testset "OUTER" begin + @on_perftest_exec begin + dumpConfig("BEFORE") + end + @perftest samples = 1 sin(1.0) + + # Its configuration must apply only to its part of the suite + include("ex17-config-recursive-inner.jl") + + @testset "AFTER" begin + @on_perftest_exec begin + dumpConfig("AFTER") + end + @perftest samples = 1 sin(1.0) + end +end + +@on_perftest_exec begin + dumpConfig("END") +end diff --git a/test/test-recipes/ex18-config-interpolation.jl b/test/test-recipes/ex18-config-interpolation.jl new file mode 100644 index 0000000..dd0d8ad --- /dev/null +++ b/test/test-recipes/ex18-config-interpolation.jl @@ -0,0 +1,31 @@ +using Test +using PerfTest + +# Only known when the generated suite executes +tag = string("run", 1 + 1) + +@perftest_config " +[general] +save_folder = 'results_$(tag)' +max_saved_results = 4 +[regression] +dedicated_reference_file = 'ref_$(tag).JLD2' +" + +# Must not carry the interpolated keys above into the suite +@perftest_config " +[roofline] +default_threshold = 0.3 +" + +@on_perftest_exec begin + # Records the configuration seen by the executing suite in its working directory + dumpConfig(name) = open(io -> PerfTest.TOML.print(io, PerfTest.Configuration.CONFIG), "config_$(name).toml", "w") +end + +@testset "INTERPOLATION" begin + @on_perftest_exec begin + dumpConfig("INTERPOLATION") + end + @perftest samples = 1 sin(1.0) +end diff --git a/test/test-recipes/ex19-config-bencher.jl b/test/test-recipes/ex19-config-bencher.jl new file mode 100644 index 0000000..5728541 --- /dev/null +++ b/test/test-recipes/ex19-config-bencher.jl @@ -0,0 +1,26 @@ +using Test +using PerfTest + +# The [bencher] section is read from the configuration file of the directory where the suite executes + +@on_perftest_exec begin + # Records the configuration seen by the executing suite in its working directory + dumpConfig(name) = open(io -> PerfTest.TOML.print(io, PerfTest.Configuration.CONFIG), "config_$(name).toml", "w") +end + +@testset "BENCHER_FILE" begin + @on_perftest_exec begin + dumpConfig("BENCHER_FILE") + end + @perftest samples = 1 sin(1.0) +end + +# Takes priority over the file from here on +@perftest_config " +[bencher] +project_name = 'from_recipe' +" + +@on_perftest_exec begin + dumpConfig("BENCHER_RECIPE") +end diff --git a/test/test-recipes/ex3-roofline.jl b/test/test-recipes/ex3-roofline.jl index 3c3e3de..3493ac9 100644 --- a/test/test-recipes/ex3-roofline.jl +++ b/test/test-recipes/ex3-roofline.jl @@ -16,8 +16,9 @@ end @testset "FIRST LEVEL" begin @testset "SECOND LEVEL" begin - @roofline actual_flops=:autoflop target_ratio=0.5 begin - :autoflop / 4 + # The flop count is given, automatic flop counting (:autoflop) is not supported + @roofline actual_flops=40 target_ratio=0.5 begin + 40 / 4 end x = @perftest testfun(10) diff --git a/test/test-recipes/ex7-measure-tests.jl b/test/test-recipes/ex7-measure-tests.jl index cd8b001..ad80d2d 100644 --- a/test/test-recipes/ex7-measure-tests.jl +++ b/test/test-recipes/ex7-measure-tests.jl @@ -6,6 +6,8 @@ using PerfTest @perftest_config " [regression] enabled = false +[general] +verbose = 3 " @testset "Time Measurements" begin @@ -125,4 +127,6 @@ enabled = false @perftest sleep(0.1) end end + + @info TS end