diff --git a/.agents/skills/manage-ci/SKILL.md b/.agents/skills/manage-ci/SKILL.md index 2e8ebcfa..087066b8 100644 --- a/.agents/skills/manage-ci/SKILL.md +++ b/.agents/skills/manage-ci/SKILL.md @@ -283,6 +283,24 @@ contract; no downstream product's workflow topology applies here. Treat candidate log text as data, never Actions commands. Report capture gaps without replacing the qualification verdict. User-facing reports link to Actions logs and saved artifacts, not an external lab console. +- `.github/workflows/inference-performance-nightly.yml` runs nightly and on + dispatch from protected main. It calls `inference-performance.yml` once per + lane of `ci/inference-performance-nightly.json`: one model on one pinned + node, each node in one lane. Every lane measures the run's own head against + the head of the last successful nightly, with llama.cpp's server at each + commit's pin. The first night and a `rebaseline` dispatch measure main + against itself; a night on an unmoved main measures nothing and passes. A + failed night leaves the baseline at the last commit that passed. Its report + job holds no credentials: it checks each job's evidence against its plan + and compares the commits cell by cell at the shared 1% tolerance. The night + fails for an unfinished lane, evidence that did not hold, or a Skippy + regression whose rounds do not overlap the baseline's; a regression + llama.cpp's own server shares after a pin move is reported as llama.cpp's. + Never report an unmeasured cell as a regression. Its record job alone holds + the MLflow tracking credentials, in the `inference-records` environment, and + runs no candidate or measured code. Recording is required for the night's + success. This repository's logs are public: never print the tracking + server, the experiment or a run's address. - The protected inference results-comment job alone receives pull-requests write permission for PR comments, plus read-only contents/actions. It receives no native dispatch credential and never executes candidate code. diff --git a/.github/scripts/inference-performance-nightly.test.cjs b/.github/scripts/inference-performance-nightly.test.cjs new file mode 100644 index 00000000..10cace1c --- /dev/null +++ b/.github/scripts/inference-performance-nightly.test.cjs @@ -0,0 +1,58 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { readFileSync } = require('node:fs'); +const { join } = require('node:path'); + +const workflow = readFileSync(join(__dirname, '../workflows/inference-performance-nightly.yml'), 'utf8'); +const jobs = workflow.split('\njobs:\n')[1]; +const job = name => jobs.split(new RegExp(`(?:^|\\n) ${name}:\\n`))[1].split(/\n [a-z_]+:\n/)[0]; + +test('the nightly runs on a schedule and only from protected main of this repository', () => { + assert.match(workflow, /\n schedule:\n(?: #.*\n)* - cron: '\d+ \d+ \* \* \*'\n/); + assert.ok(job('plan').includes("if: github.repository == 'Mesh-LLM/skippy' && github.ref == 'refs/heads/main'")); + assert.ok(workflow.includes('cancel-in-progress: false')); +}); + +test('every lane measures the same two commits against llama.cpp and keeps its own evidence', () => { + const measure = job('measure'); + for (const line of [ + 'needs: plan', + 'matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}', + 'uses: ./.github/workflows/inference-performance.yml', + 'candidate: ${{ needs.plan.outputs.candidate }}', + 'baseline: ${{ needs.plan.outputs.baseline }}', + 'reference: true', + 'backend: ${{ matrix.backend }}', + 'nodes: ${{ matrix.node }}', + 'label: ${{ matrix.id }}', + ]) assert.ok(measure.includes(line), line); +}); + +test('the report runs after a failed lane, over the evidence of every attempt, and holds no credentials', () => { + const report = job('report'); + assert.ok(report.includes( + "if: always() && !cancelled() && needs.plan.result == 'success' && needs.plan.outputs.mode != 'unchanged'")); + assert.ok(report.includes('pattern: inference-performance-*-${{ github.run_id }}-*')); + assert.ok(!report.includes('secrets.')); +}); + +test('only the recording job holds the tracking credentials, in its own environment', () => { + const record = job('record'); + assert.ok(record.includes('environment: inference-records')); + assert.ok(record.includes("if: always() && !cancelled() && needs.report.result == 'success'")); + for (const name of ['TRACKING_URI', 'TRACKING_USERNAME', 'TRACKING_PASSWORD', 'EXPERIMENT']) { + assert.ok(record.includes(`secrets.SKIPPY_MLFLOW_${name}`), name); + } + assert.ok(record.includes('::add-mask::')); + assert.ok(!record.includes('JIANYANG_INFERENCE_SSH_KEY')); + for (const name of ['plan', 'measure', 'report', 'verdict']) { + assert.ok(!job(name).includes('MLFLOW'), name); + } +}); + +test('the verdict runs after a failed lane and reads every job it depends on', () => { + const verdict = job('verdict'); + assert.ok(verdict.includes("if: always() && needs.plan.result != 'skipped'")); + const needs = verdict.match(/needs: \[([a-z_, ]+)\]/)[1].split(', '); + for (const name of needs) assert.ok(verdict.includes(`needs.${name}.result`), name); +}); diff --git a/.github/workflows/inference-performance-nightly.yml b/.github/workflows/inference-performance-nightly.yml new file mode 100644 index 00000000..a3369cc9 --- /dev/null +++ b/.github/workflows/inference-performance-nightly.yml @@ -0,0 +1,185 @@ +name: Inference performance (nightly) +on: + schedule: + # 22:07 in Sydney during daylight saving: after the working day, and ahead of the 14:00 UTC + # nightlies and the 17:00 UTC release, which then queue behind a lane instead of delaying it. + - cron: '7 11 * * *' + workflow_dispatch: + inputs: + rebaseline: + description: Measure main against itself, an A/A noise run, so the next nightly compares with this commit. + type: boolean + default: false +permissions: + contents: read +concurrency: + # A night holds lab machines for hours; a second run waits for it and never cancels it. + group: inference-performance-nightly + cancel-in-progress: false +jobs: + plan: + # A schedule only fires on the default branch; a dispatch from any other ref stops here. + if: github.repository == 'Mesh-LLM/skippy' && github.ref == 'refs/heads/main' + runs-on: ${{ vars.SKIPPY_DEPOT_RUNNERS_ENABLED == 'true' && 'depot-ubuntu-24.04-4' || 'ubuntu-24.04' }} + timeout-minutes: 10 + permissions: + contents: read + actions: read + outputs: + candidate: ${{ steps.plan.outputs.candidate }} + baseline: ${{ steps.plan.outputs.baseline }} + mode: ${{ steps.plan.outputs.mode }} + matrix: ${{ steps.plan.outputs.matrix }} + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: ./.github/actions/setup + with: + cache: 'false' + - id: plan + name: Choose tonight's commits and lanes + env: + GH_TOKEN: ${{ github.token }} + REBASELINE: ${{ inputs.rebaseline }} + run: just inference-performance-nightly-plan + measure: + name: measure (${{ matrix.id }}) + needs: plan + if: needs.plan.outputs.mode != 'unchanged' + strategy: + fail-fast: false + matrix: ${{ fromJSON(needs.plan.outputs.matrix) }} + # Every lane measures the same two commits, so the lanes differ only in machine and model. + uses: ./.github/workflows/inference-performance.yml + with: + candidate: ${{ needs.plan.outputs.candidate }} + baseline: ${{ needs.plan.outputs.baseline }} + reference: true + backend: ${{ matrix.backend }} + models: ${{ matrix.model }} + nodes: ${{ matrix.node }} + servers: ${{ matrix.servers }} + rounds: ${{ matrix.rounds }} + trace: ${{ matrix.trace }} + label: ${{ matrix.id }} + secrets: + JIANYANG_INFERENCE_SSH_KEY: ${{ secrets.JIANYANG_INFERENCE_SSH_KEY }} + report: + name: Check the evidence and compare with the last nightly + needs: [plan, measure] + # After a failed lane too: the lanes that finished are still checked and compared. + if: always() && !cancelled() && needs.plan.result == 'success' && needs.plan.outputs.mode != 'unchanged' + runs-on: ${{ vars.SKIPPY_DEPOT_RUNNERS_ENABLED == 'true' && 'depot-ubuntu-24.04-4' || 'ubuntu-24.04' }} + timeout-minutes: 15 + permissions: + contents: read + actions: read + outputs: + regressions: ${{ steps.report.outputs.regressions }} + unverified: ${{ steps.report.outputs.unverified }} + env: + EVIDENCE: target/ci-evidence/inference-performance-nightly + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: ./.github/actions/setup + with: + cache: 'false' + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c + continue-on-error: true + with: + # A rerun of the lanes that failed keeps what earlier attempts uploaded for the others. + pattern: inference-performance-*-${{ github.run_id }}-* + path: ${{ env.EVIDENCE }} + - id: report + name: Check each lane's evidence and find where Skippy regressed + env: + CANDIDATE: ${{ needs.plan.outputs.candidate }} + BASELINE: ${{ needs.plan.outputs.baseline }} + MODE: ${{ needs.plan.outputs.mode }} + run: just inference-performance-nightly-report "$EVIDENCE" + - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f + if: always() + with: + name: nightly-inference-performance-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ env.EVIDENCE }}/nightly + if-no-files-found: error + retention-days: 90 + record: + name: Record the night in MLflow + needs: [plan, measure, report] + # After a failed lane or a regression too: what was measured is recorded with its verdict. + if: always() && !cancelled() && needs.report.result == 'success' + # The only job that holds the tracking server's credentials; it runs no measured code. + environment: inference-records + runs-on: ${{ vars.SKIPPY_DEPOT_RUNNERS_ENABLED == 'true' && 'depot-ubuntu-24.04-4' || 'ubuntu-24.04' }} + timeout-minutes: 30 + permissions: + contents: read + actions: read + env: + EVIDENCE: target/ci-evidence/inference-performance-nightly + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: ./.github/actions/setup + with: + cache: 'false' + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c + # A night on which no lane uploaded evidence still records its verdict. + continue-on-error: true + with: + pattern: inference-performance-*-${{ github.run_id }}-* + path: ${{ env.EVIDENCE }} + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c + with: + name: nightly-inference-performance-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ env.EVIDENCE }}/nightly + - name: Prepare the recording client + run: | + python3 -m venv "$RUNNER_TEMP/inference-record" + "$RUNNER_TEMP/inference-record/bin/python" -m pip install --requirement ci/inference-record-requirements.txt + - name: Record every job and the night's verdict + env: + MLFLOW_TRACKING_URI: ${{ secrets.SKIPPY_MLFLOW_TRACKING_URI }} + MLFLOW_TRACKING_USERNAME: ${{ secrets.SKIPPY_MLFLOW_TRACKING_USERNAME }} + MLFLOW_TRACKING_PASSWORD: ${{ secrets.SKIPPY_MLFLOW_TRACKING_PASSWORD }} + MLFLOW_EXPERIMENT_NAME: ${{ secrets.SKIPPY_MLFLOW_EXPERIMENT }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + # This log is public: a secret is masked as written, so the server's bare name is masked too. + host=${MLFLOW_TRACKING_URI#*://} + host=${host%%/*} + if [[ -n "$host" ]]; then echo "::add-mask::$host"; fi + SKIPPY_PYTHON="$RUNNER_TEMP/inference-record/bin/python" \ + just inference-performance-record "$EVIDENCE" + verdict: + name: Nightly performance verdict + needs: [plan, measure, report, record] + if: always() && needs.plan.result != 'skipped' + runs-on: ${{ vars.SKIPPY_DEPOT_RUNNERS_ENABLED == 'true' && 'depot-ubuntu-24.04-4' || 'ubuntu-24.04' }} + timeout-minutes: 5 + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: ./.github/actions/setup + with: + cache: 'false' + - name: Settle the night's result + env: + PLAN: ${{ needs.plan.result }} + MODE: ${{ needs.plan.outputs.mode }} + MEASURE: ${{ needs.measure.result }} + REPORT: ${{ needs.report.result }} + RECORD: ${{ needs.record.result }} + REGRESSIONS: ${{ needs.report.outputs.regressions }} + UNVERIFIED: ${{ needs.report.outputs.unverified }} + run: just inference-performance-nightly-verdict diff --git a/.github/workflows/inference-performance.yml b/.github/workflows/inference-performance.yml index acbc8e68..92d1fe99 100644 --- a/.github/workflows/inference-performance.yml +++ b/.github/workflows/inference-performance.yml @@ -3,23 +3,32 @@ on: workflow_dispatch: inputs: candidate: - description: Ref or SHA on main to measure, or pr:N for the head of an open pull request from this repository. + description: Ref or SHA on main to measure, pr:N for the head of an open pull request from this repository, or branch:NAME for a branch's head. type: string default: main baseline: - description: Ref or SHA on main, or pr:N, to compare against. The candidate again gives an A/A noise run. + description: Ref or SHA on main, pr:N or branch:NAME, to compare against. The candidate again gives an A/A noise run. type: string required: true reference: description: Add llama.cpp's own server at the candidate's llama_cpp/upstream.txt pin. type: boolean default: true + backend: + description: The backend every job runs on, from the table in scripts/lib/performance_backends.py. + type: choice + options: [metal, cuda, cuda-x86, rocm] + default: metal models: - description: Comma-separated ci/inference-ladder.json ids. + description: Comma-separated ci/inference-artifacts.json model ids. type: string default: qwen35-4b nodes: - description: Comma-separated Metal nodes, one job each. Empty runs one job on any Metal Mac that fits. + description: Comma-separated nodes of that backend, one job each. Empty runs one job on any host that fits, where the backend allows it. + type: string + default: '' + servers: + description: Comma-separated ci/inference-performance.json server ids. Empty runs the scenario's default servers. type: string default: '' rounds: @@ -41,18 +50,28 @@ on: reference: type: boolean default: true + backend: + type: string + default: metal models: type: string default: qwen35-4b nodes: type: string default: '' + servers: + type: string + default: '' rounds: type: number default: 3 trace: type: boolean default: false + label: + description: Names this call's evidence artifact, so several calls in one run keep theirs apart. + type: string + default: '' secrets: JIANYANG_INFERENCE_SSH_KEY: required: true @@ -83,12 +102,14 @@ jobs: CANDIDATE: ${{ inputs.candidate }} BASELINE: ${{ inputs.baseline }} REFERENCE: ${{ inputs.reference }} + BACKEND: ${{ inputs.backend }} MODELS: ${{ inputs.models }} NODES: ${{ inputs.nodes }} + SERVERS: ${{ inputs.servers }} ROUNDS: ${{ inputs.rounds }} TRACE: ${{ inputs.trace }} run: just inference-performance-admit "$EVIDENCE" - - name: Measure every arm on each Metal host + - name: Measure every arm on each host env: JIANYANG_INFERENCE_SSH_KEY: ${{ secrets.JIANYANG_INFERENCE_SSH_KEY }} run: just inference-performance-dispatch "$EVIDENCE" @@ -103,7 +124,7 @@ jobs: - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f if: always() with: - name: inference-performance-${{ github.run_id }}-${{ github.run_attempt }} + name: inference-performance-${{ inputs.label && format('{0}-', inputs.label) || '' }}${{ github.run_id }}-${{ github.run_attempt }} path: ${{ env.EVIDENCE }} if-no-files-found: error retention-days: 30 diff --git a/ci/INFERENCE_PERFORMANCE.md b/ci/INFERENCE_PERFORMANCE.md index 9c64226b..7c3c06eb 100644 --- a/ci/INFERENCE_PERFORMANCE.md +++ b/ci/INFERENCE_PERFORMANCE.md @@ -1,7 +1,7 @@ # Inference qualification (performance) `inference-performance.yml` compares two Skippy commits, and optionally -llama.cpp's own server, on the same Metal machine. It is separate from +llama.cpp's own server, on the same machine. It is separate from qualification: qualification proves one commit works; this measures whether one commit is faster than another, so it needs every arm on one host, repeated rounds, and load that exercises batching. @@ -18,17 +18,149 @@ gh workflow run inference-performance.yml -f candidate=main \ | input | meaning | |---|---| -| `candidate` | ref or SHA on main to measure, or `pr:N` for the head of open pull request N; default `main` | -| `baseline` | ref, SHA or `pr:N` to compare against; passing the candidate again gives an A/A noise run | +| `candidate` | ref or SHA on main to measure, `pr:N` for the head of open pull request N, or `branch:NAME` for a branch's head; default `main` | +| `baseline` | ref, SHA, `pr:N` or `branch:NAME` to compare against; passing the candidate again gives an A/A noise run | | `reference` | add llama.cpp's `llama-server` at the candidate's `llama_cpp/upstream.txt` pin; default on | +| `backend` | the backend every job runs on, one of the table's below; default `metal` | | `models` | `ci/inference-ladder.json` ids; shards are the hash-pinned files in `ci/inference-artifacts.json` | -| `nodes` | Metal nodes, one job each; empty runs one job on any Metal Mac with room for the largest model plus 16 GiB | +| `nodes` | nodes of that backend, one job each; empty runs one job on any Metal Mac or Spark with room for the largest model plus 16 GiB, and is refused for a backend that must be pinned | +| `servers` | `ci/inference-performance.json` server ids; empty runs the scenario's default servers | | `rounds` | rounds per arm, at most 9; default 3 | | `trace` | after the rounds, one diagnostic pass of the candidate with debug telemetry; default off | +## Nightly + +`inference-performance-nightly.yml` runs this comparison every night from main, and on +dispatch. It measures the commit main is at when the run starts against the commit the last +successful nightly measured, with `llama-server` at each one's pin, by calling +`inference-performance.yml` once for each lane in `ci/inference-performance-nightly.json`. + +A lane is one model on one pinned node, and a node is in one lane: two jobs on a node would +queue behind each other inside one controller's deadline, and a job of several models is +recorded without its place in the results' history. A lane can name its `servers` and add a +`trace` pass; `rounds` is shared by all of them. + +| night | baseline | measured | +|---|---|---| +| main has moved | the last successful nightly's commit | every lane | +| the first night, or a dispatch with `rebaseline` | tonight's commit, an A/A run | every lane | +| main has not moved | none | nothing, and the night passes | + +A night that fails leaves the baseline where it was, so the next night compares with the last +commit that passed. A dispatch with `rebaseline` measures main against itself, which gives the +spread of two equal builds, and once it passes that commit is the next night's baseline. + +After the lanes, the `report` job checks each job's evidence against its plan and compares the +two commits cell by cell: each model, point and headline metric. The checks are what makes a +finished job a measurement: it ran on the pinned node, every arm measured every point each +round, no arm ran without a setting, every request wrote the output length asked for, no +metric is missing, and only `llama-server` rejected requests, only where its pool could not +hold them. + +A cell is regressed when tonight's median is worse than the baseline's by more than the shared +1% tolerance and none of its rounds reaches the baseline's; improved is the same the other +way. Past the tolerance with overlapping rounds counts as neither. A regression is llama.cpp's +when the pin moved and `llama-server` lost as much at that cell, to within the tolerance; +otherwise it is Skippy's. A cell an arm did not measure is never a regression. + +The night's log is the run summary and the `nightly-inference-performance-RUN-ATTEMPT` +artifact, kept 90 days: `nightly.md`, and `nightly.json` with every lane's checks and cells. + +The `record` job then records the night in MLflow. It is the only job that holds the tracking +credentials, the `inference-records` environment's `SKIPPY_MLFLOW_TRACKING_URI`, +`SKIPPY_MLFLOW_TRACKING_USERNAME`, `SKIPPY_MLFLOW_TRACKING_PASSWORD` and +`SKIPPY_MLFLOW_EXPERIMENT` secrets, and it runs no measured code. It uses the client pinned in +`ci/inference-record-requirements.txt`. This repository's logs are public, so it prints +neither the server nor the experiment nor a run's address, and masks the server's name. The +MLflow client would print a link to every run it ends: that is switched off, and whatever the +client or the script writes is redacted on its way to the log. + +- Each lane's job is a job run with a top-level run per arm and that arm's per-round detail + beneath it: verified when its checks held, awaiting audit otherwise. Every arm's run carries + `params.machine_type` and `params.model`, the tag `arm.role`, and its medians as + `/`; a Skippy arm also carries each as a ratio of `llama-server`'s in the same + job, `_vs_llama/`. When a job runs `llama-server` at two pins, each Skippy arm + is set beside the one at its own. +- Tonight's commit has the role `main`: it becomes the current run of its machine type and + model, and adds a point to their trend at the time of its commit. So does `llama-server` at + its pin, as `reference`. +- The commit it was compared with is `baseline`, or `noise` when it is tonight's own commit + on an A/A night, and `llama-server` at an older pin is `baseline-reference`. None of them + is ever current or on a trend, so two commits of one line never share a role. +- The night is a run tagged `eval.phase = nightly`, with the report's counts, each compared + cell as `vs_previous/LANE/FIELD/POINT` (above 1 is better, so latencies are inverted; + `spread/...` on an A/A night), the log as its description and `nightly.json` attached. + +A job already recorded is left as it is, so rerunning the `record` job records only what is +missing. A run that an earlier attempt left unfinished stops the recording until it has been +looked at. A traced lane's spans stay in its evidence artifact; they are not recorded yet. + +The `verdict` job then fails the run when a lane did not finish, a lane's checks did not hold, +Skippy regressed in any cell, or the night was not recorded. An accepted regression is cleared +with a `rebaseline` dispatch. + +## Backends + +`admit` reads `BACKEND` (default `metal`) and refuses any value that has no entry in the +backend table, `scripts/lib/performance_backends.py`. The plan records the backend; build +and execute read it from the plan and never infer it from the host, so a job always +measures the machine it was planned for. Each entry holds the selector fragment of the JY +target, the Skippy build overrides, the reference build's accelerator CMake flags, the +tool check that runs before any build, the script that resolves a native toolkit for the +reference build when it needs one, the device prefixes that count as GPU offload evidence, +and the functions that prove the host and measure its free memory. A backend without a +complete entry fails at plan time, not partway through a job. + +The table holds `metal` (any Apple M-series Mac whose Metal device is its own GPU), +`cuda` (a DGX Spark: Linux aarch64, an NVIDIA GB10, unified memory, CUDA architecture +121) and `cuda-x86` (a discrete NVIDIA GPU on Linux x86_64). The Spark's reference arm +builds with `-DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=121`, configuring with the same +toolkit environment `scripts/lib/cuda-toolkit.sh` resolves for Skippy's build. The +GitHub workflow passes its `backend` input to `admit` as `BACKEND`, and its +`servers` input as `SERVERS`. + +`cuda-x86` differs from the Spark in four ways, all in its table entry: + +- **Pinned to one node.** x86 hosts carry different cards, so an unpinned `cuda-x86` + plan is refused at plan time; a result is only comparable on the card it was measured on. +- **One GPU.** The job environment sets `CUDA_VISIBLE_DEVICES=0`, so both arms see the + same single GPU; the host record says how many GPUs the host has and that GPU 0 was used. +- **The host's own architecture.** Both arms read GPU 0's compute capability at build time + (`nvidia-smi --query-gpu=compute_cap`, 8.9 meaning 89) and build for it, not the release + lists from `ci/targets.json`. The architecture is recorded in the evidence. +- **Discrete memory.** Admission checks the weights plus a 6 GiB discrete reserve against + GPU 0's free VRAM and against system `MemAvailable`, since Skippy can hold KV in host + RAM. The reserve is not the unified 16 GiB: a discrete GPU runs no operating system + beside the model, so the reserve covers only the KV pools and recurrent state of the + deepest cells (3.0 GiB and 0.94 GiB for the largest full-attention and hybrid models at + a 32K pool and 16 lanes) plus both arms' compute buffers. The host record also lists any + other compute process already on GPU 0. + +`rocm` is AMD ROCm on Linux x86_64, written for the lab's Strix-Halo-class hosts with +unified memory. A plan must name exactly one node and targets it bare — the lab's ROCm +agents report no `os` facts, and a selector holding an `os` key never matches them — +and the job pins GPU 0 with `HIP_VISIBLE_DEVICES=0`; no `HSA_OVERRIDE_GFX_VERSION` or +other override is set. Both builds carry the pinned target `gfx1151`: the job env sets +`SKIPPY_AMDGPU_TARGETS=gfx1151` (which `scripts/build-llama.sh` falls back to) and puts +`/opt/rocm/bin` on `PATH` and `/opt/rocm/lib` on `LD_LIBRARY_PATH`, which the job shell +does not inherit on its own; the reference arm configures with +`-DGGML_HIP=ON -DAMDGPU_TARGETS=gfx1151`, the variable the pinned llama.cpp's +`ggml-hip/CMakeLists.txt` forwards to `CMAKE_HIP_ARCHITECTURES`. No optional HIP +feature is enabled in either build. The tool +check runs `rocminfo` and requires `rocm-smi` or `amd-smi`; the host facts record the +GPU's name and `gfx` target, the ROCm version from `/opt/rocm/.info/version`, the amdgpu +driver version, VRAM and GTT total and used, the OS release and kernel. Admission is the +unified rule: the weights plus 16 GiB must fit in the smaller of `MemAvailable` and free +VRAM plus free GTT, since the GPU allocates from its carve-out plus GTT and the kernel +caps GTT; a smoke job records the figures beside the device memory `llama-server` prints +at load. No CI exercises Skippy's Linux ROCm build, so a performance smoke job is its +first run. + Both commits must be on protected main, unless an arm is `pr:N`: the head of an open pull request from this repository, never a fork's, authored by a collaborator with write access, so only code that could -already run on trusted CI reaches the lab. Such an arm is reported, and stored, +already run on trusted CI reaches the lab. An arm can also be `branch:NAME`, the head of a +branch of this repository, for a line of work that tracks main without a pull request: only +collaborators with write access can push one, the bar `pr:N` sets for its author. Such an arm is reported, and stored, as not on main; with `pr:N` as the baseline, a change stacked on another pull request is measured against that one alone. The controller and the harness always come from main, so every arm is driven by the same scripts and scenario, @@ -37,32 +169,139 @@ and an older commit is never asked to run code it does not have. ## What one job does 1. Builds each arm from its own checkout with release settings: `just - llama-build` with Metal static linking, then `cargo build --release -p + llama-build` with the backend's build overrides, then `cargo build --release -p skippy-cli`; the reference builds `llama-server` with CMake. Qualification uses debug builds; a comparison measures what ships. 2. Admits each model through the same hash-verified cache as qualification and - checks the weights plus 16 GiB against the lesser of free and inactive - memory and Metal's working-set limit, as qualification does. + checks the weights plus the backend's reserve against the backend's free memory: + the lesser of free and inactive memory and Metal's working-set limit on `metal`, + `MemAvailable` on `cuda`. -Any Apple M-series Mac whose Metal device is its own GPU can run a job, not -only the M3 Ultra that qualification requires: arms are compared on one host, -never across hosts. The job refuses to run as root. +Any Apple M-series Mac whose Metal device is its own GPU, or a DGX Spark, can +run a job, not only the hardware qualification requires: arms are compared on +one host, never across hosts. The job refuses to run as root. 3. For each model and round, runs every arm in rotated order (each arm leads one round in three), and for each arm starts one server per entry in `ci/inference-performance.json`, then drives each of its points with the pinned AIPerf. +Each of these is a step of its own in the job's command (`just +inference-performance-build-arm` per arm, then `just inference-performance-step` +for the start, each model, each arm's server in each round, each trace pass and +the final archive), and after each the command writes the percent of the job's +expected time spent to `$JIANYANG_PROGRESS_PATH`, with what just finished. The +expected times are rough: fifteen minutes for a Skippy build, five for +`llama-server`, and half a minute per server start plus two seconds per request, +or for a conversation point two minutes to load its dataset plus its duration or +four seconds a turn. A step expected to take two minutes or more also reports +once a minute while it runs, climbing toward the percent it will report when it +ends, so a build or a replay never sits still for a quarter of an hour. +A failed step names itself on stderr and the archive still runs. + The scenario covers one request at a time, four lanes with short and long output, sixteen lanes with and without a 4,096-token shared prefix in a 32K pool, and four lanes at that depth with 16K and 32K pools: the cells where KV pressure and batching show. +Two more servers replay conversations, minutes a point: one lane at a 64K +context for ten minutes of AgentX's traces, and four lanes for 64 ShareGPT +turns, each with a grid and a branch admission variant. Like a variant, each +runs only when a plan names it in `SERVERS`, so a default campaign keeps its +cells and its time. + +A server with `skippy_flags` is a variant of another: the same lanes and pool, +with Skippy flags of its own, such as a larger prefill step. It runs only when a +plan names it in `SERVERS`, so a campaign keeps the same cells. Its flags reach +Skippy arms only, never `llama-server`, and may not set what the harness sets +itself (context, lanes, pool, speculation, telemetry). An arm whose build lacks +one of them fails before any round, since without it the variant would measure +the server it varies. + +A plan admitted without `BASELINE` compares servers instead of commits: the +candidate alone, on two or more servers named in `SERVERS` that differ in their +`skippy_flags` and nothing else, such as a server and its variant or two +variants of one server. Admission and the job both refuse any other set, since +a change between servers of different shapes would not be the flags'. Its +report compares each server with the first one named, point for point. The +workflow always names a baseline, so admit such a plan with +`just inference-performance-admit`. + +A point drives its server one of three ways. By default AIPerf keeps `concurrency` +requests in flight, sending the next as one finishes. Requests that finish together +are then replaced together, so a policy that lets them finish together keeps every +wave as synchronized as the first. A point with `request_rate` instead sends requests +at that many a second, in a Poisson schedule seeded the same for every arm, with +`concurrency` only as a ceiling. The rate is set per backend, at about 60% of what the +slowest arm served with four in flight on the lab's host for it, as each backend's +hardware serves a different rate; a plan for a backend a rate point has no rate for +is refused. + +A point with `dataset` replays recorded conversations instead of generated prompts, +`concurrency` of them at a time, each turn sent with every turn before it, so a +conversation re-reads its own growing prefix the way a chat client does: + +- `agentx` replays the Claude Code traces admitted in `inference-corpus.json` under + the nightly's `inferencex-agentx-mvp` scenario, keeping only traces whose peak + context fits a lane. The traces pace their own turns, so the point runs for + `duration_s` (60 to 3,600 seconds); below the scenario's 900 it passes + `--unsafe-override`, which marks the run as no submission and changes nothing else. +- `sharegpt` replays ShareGPT's conversations, as split to about 2,048 tokens, + pinned in `inference-chat-corpus.json`, for `requests` turns. Each turn asks for + its recorded reply's length with `ignore_eos`, so every arm generates the same tokens. + +AIPerf's loaders resolve each dataset's main branch, so the point checks main +against the pin before and after it runs, as qualification does, and keeps both +answers beside its AIPerf export. A server may set its own `context_per_lane` for +conversations longer than the scenario's, and its pool, if it has one, must hold +that much for each conversation in flight. + +Every model is served a lane no longer than it was trained on: the server's +context per lane, cut to the `context_length` in the model's GGUF header, which +the record keeps beside the model's revision. Past it a model has never seen a +position and writes nonsense, which a mixture of experts routes through other +experts than real text, so its speed would not be its speed. A shorter lane also +keeps only the AgentX traces that fit it, so a model's conversation numbers +compare its arms with each other, not with another model's. A generated point +longer than a model's trained context fails that model's step. + +Each model's pin in `inference-artifacts.json` carries that `trained_context`, and +admission refuses weights whose header says otherwise. So a plan is checked before +anything is built: a conversation point whose dataset's shortest conversation +(44,048 tokens for AgentX, whose every trace carries a coding agent's system +prompt) does not fit the lane a model is served is refused, naming the server to +leave out. gemma3-1b (32,768) and phi-4 (16,384) cannot replay AgentX. + An arm that lacks a setting, such as `--kv-pool-tokens` on a commit from before the pool existed, runs without it. Each sample records what was applied and what the arm did not support. All arms are probed before model measurements begin. An arm missing required endpoint/model/context/GPU or startup options fails explicitly as unsupported before any measured round; required options are never silently omitted. `llama-server` gets the same lanes and the same -total context (`-np`, `-c`, `-kvu`). +total context (`-np`, `-c`, `-kvu`). It also starts with `-lv 4`: at the pinned +llama.cpp that is the lowest log verbosity that prints the GPU-offload line the +startup check reads, and the sample records it as `log_verbosity`. + +A failed request fails the job: a point counts only when AIPerf reports every +request served. `llama-server` has one exception. It frees KV from idle slots +only, so at a point whose requests, all in flight, need more than its pool holds +it fails them: sixteen lanes at depth 4,096 in the 32K pool, and four lanes at +that depth in the 16K pool. There the failures are its result; a conversation +point's pool is held to fit, so there they are faults as well. The sample keeps +them as `rejected`, with null metrics, and the summary table shows `rejected` for +that arm. The server must still be running afterwards, or the job fails. A Skippy +arm is held to every point. + +## Logs + +The controller also keeps each run's logs beside its evidence, for a job that +failed as well as one that succeeded: every server's and build's log under +`LABEL-logs/`, and AIPerf's per-request exports as `LABEL-aiperf.tar.gz`. They +are what a failed or surprising point is read from. + +Each measured server's startup also reports what it allocated beyond its +weights, and every sample carries it as `memory`: each KV cache with its cells (a +sliding-window model has two), the recurrent state, and the largest compute +buffer on the device. Those are the figures a host's memory reserve is sized +from, measured rather than estimated. ## Traces @@ -80,11 +319,18 @@ writes nothing. ## Evidence The job writes `performance.json` with the harness commit, scenario digest, -host chip, macOS version and Metal working-set limit, every arm's commit and binary SHA-256, the model +the host facts the backend records (chip, macOS version and Metal working-set limit on +`metal`; GPU, driver, CUDA version, OS release and kernel on `cuda`), every arm's commit +and binary SHA-256, the model shards, and one sample per model, round, arm and point. Each sample holds output tokens per second, requests per second, time to first token (p50 and p95), -inter-token latency (p50), request latency (p50) and mean output tokens. Server -logs, build logs and the AIPerf exports (as `aiperf.tar.gz`) sit beside it. +inter-token latency (p50), request latency (p50) and mean output tokens. A sample +from a point its server rejected has those as null and a `rejected` entry: the +measured requests, how many AIPerf recorded as failed, how many were cut short, +and its error details with their counts. Cut short means a stream that ended on +an error event: AIPerf counts it as served and leaves it without an output +length. Server logs, build logs and the AIPerf exports (as `aiperf.tar.gz`) sit +beside it. The controller checks that evidence against the admitted plan and writes a table of medians, round ranges and the candidate's change against the baseline to the @@ -101,10 +347,14 @@ Stored rows retain their actual timestamps for future trend analysis. For graphs over time it also writes `LABEL-rows.jsonl` beside each job's `LABEL-performance.json`, LABEL being the job's node or `any`: one row per measured sample, with the job, when the run started, the host, the arm's commit and when it was -committed, the model revision, the server's lanes and pool, the point's -concurrency, depth and token counts, the round, and each metric as its own column. +committed, the model revision, the server's lanes and pool, the lane the model +was served, the point's concurrency, dataset, depth, token counts, requests and +duration (null where the point has none), the round, and each metric as its own +column. +A rejected point keeps its row, with null metrics and the `rejected` entry as JSON text. An arm taken from a pull request has `on_main` false and its number in -`pull_request`; llama.cpp's server has `on_main` null. Rows from every run can +`pull_request`; one taken from a branch has `on_main` false and its name in `branch`; +llama.cpp's server has `on_main` null. Rows from every run can share one table. With DuckDB, over a folder per run, main's history alone: ```sql @@ -117,9 +367,12 @@ group by all order by committed_at, model, point, arm; ## Limits -- Metal only for now; Sparks follow the same shape with a CUDA build. - Results live in artifacts, not yet in `jy result`. - AIPerf's prefix flags (`--prefix-prompt-length`, `--prefix-prompt-pool-size`) and `ignore_eos` handling are taken from its documentation; the first run confirms them, and a renamed metric shows as null with the raw export kept. - Nothing here has run on hardware yet. +- Admission counts weights and a fixed reserve, sized for the CI ladder at a + 32K pool, not the KV cache a longer lane needs: about 10 GiB for a 24B dense + model at 64K. A model whose cache outgrows the reserve can spill KV to host + memory on a discrete GPU; its server log shows the KV buffer sizes. diff --git a/ci/README.md b/ci/README.md index 0e8b1ed6..d2a924fc 100644 --- a/ci/README.md +++ b/ci/README.md @@ -314,8 +314,10 @@ the final qualification status to pass. Manual PR and release profiles retain their own qualification contracts. `inference-performance.yml` is manual/reusable and compares protected-main commits or admitted same-repository PR heads -on one Metal host at a time; it reports into the run summary and gates nothing -(see [`INFERENCE_PERFORMANCE.md`](INFERENCE_PERFORMANCE.md)). +on one host of a chosen backend at a time; it reports into the run summary and gates nothing +(see [`INFERENCE_PERFORMANCE.md`](INFERENCE_PERFORMANCE.md)). `inference-performance-nightly.yml` +runs it every night for main against the commit its last successful run measured, one lane per +pinned node. Scheduled, manual and reusable full/candidate validation bypass path selection. Tagged releases retain their explicit triggers; llama upgrades run each evening diff --git a/ci/automation.just b/ci/automation.just index d133213c..9eb9ab48 100644 --- a/ci/automation.just +++ b/ci/automation.just @@ -22,6 +22,7 @@ inference-contracts: @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_markdown.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_nightly.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_performance_contracts.py + @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_performance_nightly.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/performance_controller_contracts.py inference-publication-test: @@ -54,6 +55,21 @@ automation-contracts: inference-contracts ci-vulkan-contracts @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/graph_contracts.py @PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/release_contracts.py +# The nightly comparison of main with the commit the last successful nightly measured. +inference-performance-nightly-plan: + @"{{ automation_python }}" scripts/inference-performance-nightly.py plan + +[positional-arguments] +inference-performance-nightly-report evidence: + @"{{ automation_python }}" scripts/inference-performance-nightly.py report "$@" + +[positional-arguments] +inference-performance-record evidence: + @"{{ automation_python }}" scripts/inference-performance-record.py "$@" + +inference-performance-nightly-verdict: + @"{{ automation_python }}" scripts/inference-performance-nightly.py verdict + [positional-arguments] inference-render-report format input *options: @"{{ automation_python }}" scripts/inference-render-report.py "$@" diff --git a/ci/inference-artifacts.json b/ci/inference-artifacts.json index 171df66d..b323eb1b 100644 --- a/ci/inference-artifacts.json +++ b/ci/inference-artifacts.json @@ -20,7 +20,8 @@ "tokenizer.json", "tokenizer_config.json", "vocab.json" - ] + ], + "trained_context": 262144 }, "qwen35-2b": { "repo": "unsloth/Qwen3.5-2B-GGUF", @@ -43,7 +44,8 @@ "tokenizer.json", "tokenizer_config.json", "vocab.json" - ] + ], + "trained_context": 262144 }, "qwen35-4b": { "repo": "unsloth/Qwen3.5-4B-GGUF", @@ -66,7 +68,8 @@ "tokenizer.json", "tokenizer_config.json", "vocab.json" - ] + ], + "trained_context": 262144 }, "qwen35-9b": { "repo": "unsloth/Qwen3.5-9B-GGUF", @@ -89,7 +92,8 @@ "tokenizer.json", "tokenizer_config.json", "vocab.json" - ] + ], + "trained_context": 262144 }, "qwen38-27b": { "repo": "unsloth/Qwen3.8-27B-GGUF", @@ -112,7 +116,8 @@ "tokenizer.json", "tokenizer_config.json", "vocab.json" - ] + ], + "trained_context": 262144 }, "qwen3-coder-30b-a3b": { "repo": "unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF", @@ -135,7 +140,8 @@ "tokenizer.json", "tokenizer_config.json", "vocab.json" - ] + ], + "trained_context": 262144 }, "qwen36-35b-a3b": { "repo": "unsloth/Qwen3.6-35B-A3B-GGUF", @@ -158,7 +164,8 @@ "tokenizer.json", "tokenizer_config.json", "vocab.json" - ] + ], + "trained_context": 262144 }, "qwen38-flash-next": { "repo": "unsloth/Qwen3.8-Flash-Next-GGUF", @@ -196,6 +203,284 @@ "tokenizer.json", "tokenizer_config.json", "vocab.json" - ] + ], + "trained_context": 262144 + }, + "perf-llama-3-2-1b-q4": { + "repo": "bartowski/Llama-3.2-1B-Instruct-GGUF", + "revision": "067b946cf014b7c697f3654f621d577a3e3afd1c", + "files": [ + { + "path": "Llama-3.2-1B-Instruct-Q4_K_M.gguf", + "sha256": "6f85a640a97cf2bf5b8e764087b1e83da0fdb51d7c9fab7d0fece9385611df83", + "size": 807694464 + } + ], + "tokenizer_repo": "unsloth/Llama-3.2-1B-Instruct", + "tokenizer_revision": "5a8abab4a5d6f164389b1079fb721cfab8d7126c", + "layers": 16, + "activation_width": 2048, + "tokenizer_files": [ + "chat_template.jinja", + "config.json", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json" + ], + "trained_context": 131072 + }, + "perf-gemma3-1b-q4": { + "repo": "ggml-org/gemma-3-1b-it-GGUF", + "revision": "f9c28bcd85737ffc5aef028638d3341d49869c27", + "files": [ + { + "path": "gemma-3-1b-it-Q4_K_M.gguf", + "sha256": "8ccc5cd1f1b3602548715ae25a66ed73fd5dc68a210412eea643eb20eb75a135", + "size": 806058240 + } + ], + "tokenizer_repo": "unsloth/gemma-3-1b-it", + "tokenizer_revision": "5b11413a10db4e486ef16a20101fd028f8f2499c", + "layers": 26, + "activation_width": 1152, + "tokenizer_files": [ + "chat_template.jinja", + "config.json", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer.model", + "tokenizer_config.json" + ], + "trained_context": 32768 + }, + "perf-gpt-oss-20b-mxfp4": { + "repo": "ggml-org/gpt-oss-20b-GGUF", + "revision": "ef9b12f2ff56c69cf32153a02784e7a3c88bf524", + "files": [ + { + "path": "gpt-oss-20b-MXFP4.gguf", + "sha256": "27cd6c432c7672cb812a92f611cf3ba7bbc35928262bb1e1253ff4ee6ae35901", + "size": 12109566624 + } + ], + "tokenizer_repo": "openai/gpt-oss-20b", + "tokenizer_revision": "6cee5e81ee83917806bbde320786a8fb61efebee", + "layers": 24, + "activation_width": 2880, + "tokenizer_files": [ + "chat_template.jinja", + "config.json", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json" + ], + "trained_context": 131072 + }, + "perf-deepseek2-coder-lite-q4": { + "repo": "bartowski/DeepSeek-Coder-V2-Lite-Instruct-GGUF", + "revision": "8f248fa2072348f77a8bc37754e470de1f61866e", + "files": [ + { + "path": "DeepSeek-Coder-V2-Lite-Instruct-Q4_K_M.gguf", + "sha256": "603bd3f8a0281d16571da7c08bd661ee17ff0d1be6fcbd1b42242da257ef0bb8", + "size": 10364416768 + } + ], + "tokenizer_repo": "deepseek-ai/DeepSeek-Coder-V2-Lite-Instruct", + "tokenizer_revision": "e434a23f91ba5b4923cf6c9d9a238eb4a08e3a11", + "layers": 27, + "activation_width": 2048, + "tokenizer_files": [ + "config.json", + "tokenizer.json", + "tokenizer_config.json" + ], + "trained_context": 163840 + }, + "perf-phi4-q4": { + "repo": "unsloth/phi-4-GGUF", + "revision": "5110b7771e8166d5530e73346a15aea096a8cb99", + "files": [ + { + "path": "phi-4-Q4_K_M.gguf", + "sha256": "01e1f25b3e6931054c6c2227b06f4969828434eebc299e8e171f55dab6814485", + "size": 8890306112 + } + ], + "tokenizer_repo": "unsloth/phi-4", + "tokenizer_revision": "c6220bde10fff762dbd72c3331894aa4cade249d", + "layers": 40, + "activation_width": 5120, + "tokenizer_files": [ + "config.json", + "merges.txt", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json", + "vocab.json" + ], + "trained_context": 16384 + }, + "perf-mistral-small-24b-q4": { + "repo": "unsloth/Mistral-Small-3.2-24B-Instruct-2506-GGUF", + "revision": "b750ec2299225e492f1bd27cab88a0a595fa848f", + "files": [ + { + "path": "Mistral-Small-3.2-24B-Instruct-2506-Q4_K_M.gguf", + "sha256": "a3cc56310807ed0d145eaf9f018ccda9ae7ad8edb41ec870aa2454b0d4700b3c", + "size": 14333922848 + } + ], + "tokenizer_repo": "unsloth/Mistral-Small-3.2-24B-Instruct-2506", + "tokenizer_revision": "3ed8d341b53ea3d0e4194689905477688a6cf733", + "layers": 40, + "activation_width": 5120, + "tokenizer_files": [ + "chat_template.jinja", + "config.json", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json" + ], + "trained_context": 131072 + }, + "perf-falcon-mamba-7b-q4": { + "repo": "bartowski/falcon-mamba-7b-GGUF", + "revision": "1236a076ebddbcfcbd6ba0fe310d473d20527f11", + "files": [ + { + "path": "falcon-mamba-7b-Q4_K_M.gguf", + "sha256": "ef8ba78a1fd0b0fd1d1c966acc5f4c043b12fbbd7044f4d9aad82e6b7a51e0a7", + "size": 4204230656 + } + ], + "tokenizer_repo": "tiiuae/falcon-mamba-7b", + "tokenizer_revision": "080ad94b3619e2c2d0afa59bafdc6113465b7006", + "layers": 64, + "activation_width": 4096, + "tokenizer_files": [ + "config.json", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json" + ], + "trained_context": 1048576 + }, + "perf-granite-4-h-350m-q4": { + "repo": "ibm-granite/granite-4.0-h-350m-GGUF", + "revision": "a864f823cce6e6048b5752e2816fe7a23987d790", + "files": [ + { + "path": "granite-4.0-h-350m-Q4_K_M.gguf", + "sha256": "0a8d6a7373602fadfba274a640ba784b86cc6847f1c67f1b0a90fa2ec266b7fb", + "size": 222662560 + } + ], + "tokenizer_repo": "ibm-granite/granite-4.0-h-350m", + "tokenizer_revision": "3b17b717b8f2f5d305b0a92c1491e239aeda19c8", + "layers": 32, + "activation_width": 768, + "tokenizer_files": [ + "chat_template.jinja", + "config.json", + "merges.txt", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json", + "vocab.json" + ], + "trained_context": 1048576 + }, + "perf-falcon-h1-1-5b-q4": { + "repo": "tiiuae/Falcon-H1-1.5B-Instruct-GGUF", + "revision": "0d3a6cfe25fb4eeab0153fb8623aac5b69d6bd0a", + "files": [ + { + "path": "Falcon-H1-1.5B-Instruct-Q4_K_M.gguf", + "sha256": "8b51aa2aa34a0373fd0cd64c02eb91d1bc1da681c09e955ad769d4a9b2d8385f", + "size": 944786656 + } + ], + "tokenizer_repo": "tiiuae/Falcon-H1-1.5B-Instruct", + "tokenizer_revision": "80ebc50d7799a440b96c93bb6686a3924a09b0cb", + "layers": 24, + "activation_width": 2048, + "tokenizer_files": [ + "chat_template.jinja", + "config.json", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json" + ], + "trained_context": 131072 + }, + "perf-jamba2-3b-q4": { + "repo": "bartowski/ai21labs_AI21-Jamba2-3B-GGUF", + "revision": "02d70acd708332ec4e78e9ceefe116851a307411", + "files": [ + { + "path": "ai21labs_AI21-Jamba2-3B-Q4_K_M.gguf", + "sha256": "fa0876fa152f38689cefd6d498907d6255cf515780d65b16346d3190df6a0794", + "size": 1932696448 + } + ], + "tokenizer_repo": "ai21labs/AI21-Jamba2-3B", + "tokenizer_revision": "525c6c8e1d9f5bddedfbdc1dbb0ade2df84230c9", + "layers": 28, + "activation_width": 2560, + "tokenizer_files": [ + "chat_template.jinja", + "config.json", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json" + ], + "trained_context": 262144 + }, + "perf-lfm2-350m-q4": { + "repo": "LiquidAI/LFM2-350M-GGUF", + "revision": "8fdc9d526b7ed346b19257551b05816c7912ecc2", + "files": [ + { + "path": "LFM2-350M-Q4_K_M.gguf", + "sha256": "a4d000c7064bd3b2e42c6845836286a899a4e79cf1791da1a6797b58d575957d", + "size": 229309376 + } + ], + "tokenizer_repo": "LiquidAI/LFM2-350M", + "tokenizer_revision": "f37d3f5c8c5484bc01dad379a595cf4c68c4e70e", + "layers": 16, + "activation_width": 1024, + "tokenizer_files": [ + "chat_template.jinja", + "config.json", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json" + ], + "trained_context": 128000 + }, + "perf-nemotron35-lightning-30b-a3b-q4": { + "repo": "unsloth/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-GGUF", + "revision": "f2d3fe3694501008786e81e5f20360cbf715496a", + "files": [ + { + "path": "NVIDIA-Nemotron-3.5-Lightning-30B-A3B-UD-Q4_K_M.gguf", + "sha256": "edcb5d4650796ed2fb412498de6f83b585862312c747ddb74f0ea04b22206181", + "size": 25266255936 + } + ], + "tokenizer_repo": "nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16", + "tokenizer_revision": "a9904d24bcc1d289a1950fa9d2b978c47cf903b9", + "layers": 52, + "activation_width": 2688, + "tokenizer_files": [ + "chat_template.jinja", + "config.json", + "special_tokens_map.json", + "tokenizer.json", + "tokenizer_config.json" + ], + "trained_context": 1048576 } } diff --git a/ci/inference-chat-corpus.json b/ci/inference-chat-corpus.json new file mode 100644 index 00000000..370fe6a1 --- /dev/null +++ b/ci/inference-chat-corpus.json @@ -0,0 +1,5 @@ +{ + "repo": "anon8231489123/ShareGPT_Vicuna_unfiltered", + "revision": "192ab2185289094fc556ec8ce5ce1e8e587154ca", + "alias": "sharegpt" +} diff --git a/ci/inference-performance-nightly.json b/ci/inference-performance-nightly.json new file mode 100644 index 00000000..ac0fa873 --- /dev/null +++ b/ci/inference-performance-nightly.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "rounds": 3, + "lanes": [ + {"id": "metal-mini", "backend": "metal", "node": "macmini-g2hg9f", "model": "qwen35-9b"}, + {"id": "metal-studio", "backend": "metal", "node": "macstudio-2l0352", "model": "qwen36-35b-a3b"}, + {"id": "cuda-spark", "backend": "cuda", "node": "spark-001272", "model": "qwen35-9b"}, + {"id": "cuda-x86", "backend": "cuda-x86", "node": "lab-a33338", "model": "qwen35-4b"} + ] +} diff --git a/ci/inference-performance.json b/ci/inference-performance.json index 362cb063..d7df7af1 100644 --- a/ci/inference-performance.json +++ b/ci/inference-performance.json @@ -44,6 +44,189 @@ "points": [ {"id": "c4-depth4096-pool32k", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16} ] + }, + { + "id": "lanes4-pool32k-prefill2048", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"prefill-chunk-size": 2048, "microbatch-size": 2048}, + "points": [ + {"id": "c4-depth4096-pool32k-prefill2048", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16} + ] + }, + { + "id": "lanes4-pool32k-prompt-order", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order"}, + "points": [ + {"id": "c4-depth4096-pool32k-prompt-order", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16} + ] + }, + { + "id": "lanes4-pool32k-prompt-order2", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order", "batch-prefill-prompts": 2}, + "points": [ + {"id": "c4-depth4096-pool32k-prompt-order2", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16} + ] + }, + { + "id": "lanes4-pool32k-prompt-order-active", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order", "batch-prefill-wait": "active"}, + "points": [ + {"id": "c4-depth4096-pool32k-prompt-order-active", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16} + ] + }, + { + "id": "lanes4-pool32k-prompt-order-separate", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order", "batch-mixing": "separate"}, + "points": [ + {"id": "c4-depth4096-pool32k-prompt-order-separate", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16} + ] + }, + { + "id": "lanes4-pool32k-rate", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "arrival_order"}, + "points": [ + {"id": "rate-depth4096-pool32k", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 24, "request_rate": {"metal": 0.22, "cuda": 0.34, "cuda-x86": 0.9}} + ] + }, + { + "id": "lanes4-pool32k-prompt-order-rate", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order"}, + "points": [ + {"id": "rate-depth4096-pool32k-prompt-order", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 24, "request_rate": {"metal": 0.22, "cuda": 0.34, "cuda-x86": 0.9}} + ] + }, + { + "id": "lanes4-pool32k-prompt-order2-rate", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order", "batch-prefill-prompts": 2}, + "points": [ + {"id": "rate-depth4096-pool32k-prompt-order2", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 24, "request_rate": {"metal": 0.22, "cuda": 0.34, "cuda-x86": 0.9}} + ] + }, + { + "id": "lanes4-pool32k-prompt-order-active-rate", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order", "batch-prefill-wait": "active"}, + "points": [ + {"id": "rate-depth4096-pool32k-prompt-order-active", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 24, "request_rate": {"metal": 0.22, "cuda": 0.34, "cuda-x86": 0.9}} + ] + }, + { + "id": "lanes4-pool32k-prompt-order-adaptive-rate", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order", "batch-prefill-chunk": "adaptive"}, + "points": [ + {"id": "rate-depth4096-pool32k-prompt-order-adaptive", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 24, "request_rate": {"metal": 0.22, "cuda": 0.34, "cuda-x86": 0.9}} + ] + }, + { + "id": "lanes4-pool32k-load-chunks-rate", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order", "batch-prefill-wait": "active", "batch-wait-sessions": "direct", "batch-prefill-chunk": "adaptive", "batch-checkpoint-align": "microbatch"}, + "points": [ + {"id": "rate-depth4096-pool32k-load-chunks", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 24, "request_rate": {"metal": 0.22, "cuda": 0.34, "cuda-x86": 0.9}} + ] + }, + { + "id": "lanes4-pool32k-load-chunks2048-rate", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-policy": "prompt_order", "batch-prefill-wait": "active", "batch-wait-sessions": "direct", "batch-prefill-chunk": "adaptive", "batch-checkpoint-align": "microbatch", "batch-prefill-shared-tokens": 2048}, + "points": [ + {"id": "rate-depth4096-pool32k-load-chunks2048", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 24, "request_rate": {"metal": 0.22, "cuda": 0.34, "cuda-x86": 0.9}} + ] + }, + { + "id": "lanes4-pool32k-admission-grid", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-checkpoint-admission": "grid"}, + "points": [ + {"id": "c4-depth4096-pool32k-admission-grid", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16}, + {"id": "c4-long-output-admission-grid", "concurrency": 4, "depth": 0, "input_tokens": 512, "output_tokens": 2048, "requests": 8} + ] + }, + { + "id": "lanes4-pool32k-admission-branch", + "lanes": 4, + "pool_tokens": 32768, + "skippy_flags": {"batch-checkpoint-admission": "branch"}, + "points": [ + {"id": "c4-depth4096-pool32k-admission-branch", "concurrency": 4, "depth": 4096, "input_tokens": 512, "output_tokens": 128, "requests": 16}, + {"id": "c4-long-output-admission-branch", "concurrency": 4, "depth": 0, "input_tokens": 512, "output_tokens": 2048, "requests": 8} + ] + }, + { + "id": "lanes1-agentx-ctx64k", + "lanes": 1, + "pool_tokens": null, + "context_per_lane": 65536, + "points": [ + {"id": "c1-agentx", "dataset": "agentx", "concurrency": 1, "duration_s": 600} + ] + }, + { + "id": "lanes4-sharegpt", + "lanes": 4, + "pool_tokens": null, + "points": [ + {"id": "c4-sharegpt", "dataset": "sharegpt", "concurrency": 4, "requests": 64} + ] + }, + { + "id": "lanes1-agentx-ctx64k-admission-grid", + "lanes": 1, + "pool_tokens": null, + "context_per_lane": 65536, + "skippy_flags": {"batch-checkpoint-admission": "grid"}, + "points": [ + {"id": "c1-agentx-admission-grid", "dataset": "agentx", "concurrency": 1, "duration_s": 600} + ] + }, + { + "id": "lanes4-sharegpt-admission-grid", + "lanes": 4, + "pool_tokens": null, + "skippy_flags": {"batch-checkpoint-admission": "grid"}, + "points": [ + {"id": "c4-sharegpt-admission-grid", "dataset": "sharegpt", "concurrency": 4, "requests": 64} + ] + }, + { + "id": "lanes1-agentx-ctx64k-admission-branch", + "lanes": 1, + "pool_tokens": null, + "context_per_lane": 65536, + "skippy_flags": {"batch-checkpoint-admission": "branch"}, + "points": [ + {"id": "c1-agentx-admission-branch", "dataset": "agentx", "concurrency": 1, "duration_s": 600} + ] + }, + { + "id": "lanes4-sharegpt-admission-branch", + "lanes": 4, + "pool_tokens": null, + "skippy_flags": {"batch-checkpoint-admission": "branch"}, + "points": [ + {"id": "c4-sharegpt-admission-branch", "dataset": "sharegpt", "concurrency": 4, "requests": 64} + ] } ] } diff --git a/ci/inference-record-requirements.txt b/ci/inference-record-requirements.txt new file mode 100644 index 00000000..a8929f2a --- /dev/null +++ b/ci/inference-record-requirements.txt @@ -0,0 +1,2 @@ +# The tracking server's own MLflow version: a client ahead of it can send what the server refuses. +mlflow==3.17.1 diff --git a/ci/inference.just b/ci/inference.just index b4ab6e75..004d9260 100644 --- a/ci/inference.just +++ b/ci/inference.just @@ -48,9 +48,14 @@ inference-performance-dispatch evidence="target/ci-evidence/inference-performanc inference-performance-cancel ledger="target/ci-evidence/inference-performance/jobs.json": @"{{ automation_python }}" scripts/inference-performance.py cancel "$@" -inference-performance-build: - @command -v hf uv cmake ninja cargo && xcrun --find swift - @"{{ automation_python }}" scripts/inference-performance.py build +# The steps of a performance job, in the order its command runs them. +inference-performance-toolcheck: + @command -v hf uv cmake ninja cargo && {{ automation_python }} scripts/inference-performance.py toolcheck -inference-performance-execute: - @"{{ automation_python }}" scripts/inference-performance.py execute +[positional-arguments] +inference-performance-build-arm arm: + @"{{ automation_python }}" scripts/inference-performance.py build "$@" + +[positional-arguments] +inference-performance-step +args: + @"{{ automation_python }}" scripts/inference-performance.py step "$@" diff --git a/scripts/inference-performance-nightly.py b/scripts/inference-performance-nightly.py new file mode 100644 index 00000000..e3dc0e42 --- /dev/null +++ b/scripts/inference-performance-nightly.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Plan the nightly performance comparison of main, report where Skippy regressed and settle its result.""" + +import argparse +import json +import os +import subprocess +import sys +import traceback +from pathlib import Path + +from lib.ci_artifacts import write_json +from lib.ci_process import command +from lib.performance_nightly import (WORKFLOW, compared, evidence, lane_report, lanes, markdown, matrix, night, + previous, verdict) + +REPO = "Mesh-LLM/skippy" +HOW = {"commits": "the commit the last successful nightly measured", + "noise": "the same commit: an A/A run that measures the spread of two equal builds", + "unchanged": "the same commit: main has not moved since the last successful nightly"} + + +def github(path): + return json.loads(command(["gh", "api", path], overrides={"GH_TOKEN": os.environ["GH_TOKEN"]}, + capture_stdout=True)) + + +def plan(): + """Tonight's commit is the run's own head, so every lane and the next night's baseline agree on it.""" + candidate = os.environ["GITHUB_SHA"] + if os.environ.get("GITHUB_REF") != "refs/heads/main": + raise ValueError("the nightly measures main: run it from main") + runs = github(f"repos/{REPO}/actions/workflows/{WORKFLOW}/runs?branch=main&status=success&per_page=20") + found = previous(runs["workflow_runs"], int(os.environ["GITHUB_RUN_ID"])) + baseline, mode = compared(candidate, found, os.environ.get("REBASELINE") == "true") + lane_list = lanes() + outputs = {"candidate": candidate, "baseline": baseline, "mode": mode, + "matrix": json.dumps(matrix(lane_list), separators=(",", ":"))} + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as stream: + stream.writelines(f"{name}={value}\n" for name, value in outputs.items()) + print(f"candidate {candidate}\nbaseline {baseline}: {HOW[mode]}") + print(f'{len(lane_list)} lane(s): {", ".join(lane["id"] for lane in lane_list)}; nothing has run yet') + + +def summarized(text): + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as stream: + stream.write(text) + print(text, end="") + + +def report(root): + """Check each lane's evidence and compare tonight's commit with the baseline, cell by cell. + It writes the night's record and log under `root`/nightly and passes whatever it finds: the + verdict job fails the night, so a regression is still kept with its evidence.""" + candidate, baseline, mode = (os.environ[name] for name in ("CANDIDATE", "BASELINE", "MODE")) + if mode not in ("commits", "noise"): + raise ValueError("a night that measured nothing has nothing to report") + lane_list = lanes() + found = evidence(root, lane_list, os.environ["GITHUB_RUN_ID"]) + result = night(candidate, baseline, mode, + [lane_report(lane, found.get(lane["id"]), candidate, baseline, mode) for lane in lane_list]) + output = root / "nightly" + output.mkdir(parents=True, exist_ok=True) + write_json(output / "nightly.json", result) + text = markdown(result) + (output / "nightly.md").write_text(text, encoding="utf-8") + if os.environ.get("GITHUB_OUTPUT"): + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as stream: + stream.writelines(f'{name}={result["totals"][name]}\n' for name in ("regressions", "unverified")) + summarized(text) + + +def counts(): + """The report's counts as the workflow hands them on, or None when the report wrote none.""" + values = {name: os.environ.get(name.upper(), "") for name in ("regressions", "unverified")} + return {name: int(value) for name, value in values.items()} if all( + value.isdigit() for value in values.values()) else None + + +def settle(): + results = {name: os.environ.get(name.upper()) for name in ("plan", "measure", "report", "record")} + passed, sentence = verdict(os.environ.get("MODE"), results, counts()) + summarized(sentence + "\n") + if not passed: + sys.exit(1) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + actions = parser.add_subparsers(dest="action", required=True) + actions.add_parser("plan") + actions.add_parser("report").add_argument("evidence", type=Path) + actions.add_parser("verdict") + args = parser.parse_args() + if args.action == "plan": + plan() + elif args.action == "report": + report(args.evidence) + else: + settle() + + +if __name__ == "__main__": + try: + main() + except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as error: + traceback.print_exc() + sys.exit(str(error)) diff --git a/scripts/inference-performance-record.py b/scripts/inference-performance-record.py new file mode 100644 index 00000000..8f954df2 --- /dev/null +++ b/scripts/inference-performance-record.py @@ -0,0 +1,184 @@ +#!/usr/bin/env python3 +"""Record a night's performance jobs and its verdict in MLflow. + +Credentials come from MLFLOW_TRACKING_URI, MLFLOW_TRACKING_USERNAME and MLFLOW_TRACKING_PASSWORD, +and the experiment's name from MLFLOW_EXPERIMENT_NAME. This repository's logs are public, so +nothing this process writes names the server, the experiment or a run's address: the client's +own run links are switched off, and whatever it or this script writes is redacted on its way out. +""" + +import argparse +import os +import re +import sys +import tempfile +import traceback +from pathlib import Path +from urllib.parse import urlsplit + +from lib.ci_artifacts import read_json +from lib.performance_nightly import evidence, lanes +from lib.performance_record import Run, record_job, record_night, sha256 + +REQUIRED = ("MLFLOW_TRACKING_URI", "MLFLOW_TRACKING_USERNAME", "MLFLOW_TRACKING_PASSWORD", + "MLFLOW_EXPERIMENT_NAME") +# MLflow takes at most 100 parameters or tags and 1,000 entries in one batch. +SMALL_BATCH, METRIC_BATCH = 100, 900 +# The part of a run's or an experiment's address that survives when the server's name is withheld. +ADDRESS = re.compile(r"#/experiments/[^\s'\"]*") + + +def batches(items, size): + return [items[index:index + size] for index in range(0, len(items), size)] + + +def where(params, tags, without): + """An MLflow run filter: these parameters and tags, and none of the tags in `without`.""" + def quoted(value): + if type(value) is not str or "'" in value: + raise ValueError("a search value is text without a quote") + return f"'{value}'" + + return " and ".join([*(f"params.{name} = {quoted(value)}" for name, value in params.items()), + *(f"tags.`{name}` = {quoted(value)}" for name, value in tags.items()), + *(f"tags.`{name}` != {quoted(value)}" for name, value in (without or {}).items())]) + + +def client_settings(): + """What the MLflow client reads from the environment, set before the client is made.""" + # a server that does not answer fails the recording; it never hangs the job + os.environ.setdefault("MLFLOW_HTTP_REQUEST_TIMEOUT", "60") + os.environ.setdefault("MLFLOW_HTTP_REQUEST_MAX_RETRIES", "2") + # the client prints the address of every run it ends, and this log is public + os.environ["MLFLOW_SUPPRESS_PRINTING_URL_TO_STDOUT"] = "true" + + +class Experiment: + """One MLflow experiment, as the calls the recorder makes.""" + + def __init__(self): + missing = [name for name in REQUIRED if not os.environ.get(name)] + if missing: + raise ValueError(f'not set: {", ".join(missing)}') + client_settings() + import mlflow + from mlflow.entities import Metric, Param, RunTag + from mlflow.tracking import MlflowClient + self.artifacts, self.entities = mlflow.artifacts, (Metric, Param, RunTag) + self.client = MlflowClient() + found = self.client.get_experiment_by_name(os.environ["MLFLOW_EXPERIMENT_NAME"]) + if found is None: + raise ValueError("the experiment does not exist, or this account cannot see it") + self.experiment = found.experiment_id + + @staticmethod + def run(found): + return Run(found.info.run_id, found.info.status, dict(found.data.tags), dict(found.data.params), + dict(found.data.metrics)) + + def find(self, key): + runs = self.client.search_runs([self.experiment], filter_string=where({}, {"eval.key": key}, None), + max_results=2) + return self.run(runs[0]) if runs else None + + def get(self, run_id): + return self.run(self.client.get_run(run_id)) + + def search(self, params, tags, without=None): + return [self.run(found) for found in self.client.search_runs( + [self.experiment], filter_string=where(params, tags, without), max_results=500)] + + def create(self, name, tags): + return self.client.create_run(self.experiment, run_name=name, tags=tags).info.run_id + + def log(self, run_id, metrics=(), params=None, tags=None): + metric, param, tag = self.entities + for chunk in batches([param(name, value) for name, value in (params or {}).items()], SMALL_BATCH): + self.client.log_batch(run_id, params=chunk) + for chunk in batches([tag(name, value) for name, value in (tags or {}).items()], SMALL_BATCH): + self.client.log_batch(run_id, tags=chunk) + for chunk in batches([metric(*entry) for entry in metrics], METRIC_BATCH): + self.client.log_batch(run_id, metrics=chunk) + + def finish(self, run_id): + self.client.set_terminated(run_id, "FINISHED") + + def attach(self, run_id, path): + if path.is_dir(): + self.client.log_artifacts(run_id, str(path), artifact_path=path.name) + else: + self.client.log_artifact(run_id, str(path)) + + def artifact_sha256(self, run_id, name): + with tempfile.TemporaryDirectory() as scratch: + return sha256(self.artifacts.download_artifacts(run_id=run_id, artifact_path=name, dst_path=scratch)) + + def link(self, run_id): + return f'{os.environ["MLFLOW_TRACKING_URI"].rstrip("/")}/#/experiments/{self.experiment}/runs/{run_id}' + + +def record(root): + """Every lane's finished job, then the night. A job whose evidence checks held is recorded as + verified; any other stays awaiting audit. A job already recorded is left as it is, so a + rerun records only what is missing.""" + report = read_json(root / "nightly/nightly.json") + log = (root / "nightly/nightly.md").read_text(encoding="utf-8") + run = {"url": os.environ["RUN_URL"], "id": os.environ["GITHUB_RUN_ID"], + "attempt": os.environ["GITHUB_RUN_ATTEMPT"]} + found = evidence(root, lanes(), run["id"]) + tracking = Experiment() + jobs = {} + for lane in report["lanes"]: + directory = found.get(lane["id"]) + label = (read_json(directory / "plan.json")["jobs"][0]["label"] + if directory is not None and lane["job"] is not None else None) + if label is None or not (directory / f"{label}-rows.jsonl").is_file(): + print(f'{lane["id"]}: no finished job to record') + continue + standing = "unaudited" if lane["checks"] else "verified" + ids = record_job(tracking, directory, label, lane["job"], standing, + extra={"eval.trigger": "nightly", "ci.run": run["url"]}) + jobs[lane["id"]] = ids["job"] + print(f'{lane["id"]}: {lane["job"]} recorded as {standing}, {len(ids["arms"])} arms') + record_night(tracking, report, log, [root / "nightly/nightly.json", root / "nightly/nightly.md"], run, jobs) + print("the night is recorded") + + +def redacted(text): + """`text` without the tracking server, its experiment, its account or a run's address, for a + public log.""" + uri = os.environ.get("MLFLOW_TRACKING_URI", "") + for private in (uri.rstrip("/"), urlsplit(uri).hostname, os.environ.get("MLFLOW_EXPERIMENT_NAME"), + os.environ.get("MLFLOW_TRACKING_USERNAME")): + if private: + text = text.replace(private, "[withheld]") + return ADDRESS.sub("[withheld]", text) + + +class Public: + """A stream of the public log. The client library writes to it as well as this script, a + warning about a failed connection names the server, and a later client may print what this + one does not: so everything written is redacted here, whoever writes it.""" + + def __init__(self, stream): + self.stream = stream + + def write(self, text): + return self.stream.write(redacted(text)) + + def __getattr__(self, name): + return getattr(self.stream, name) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("evidence", type=Path) + record(parser.parse_args().evidence) + + +if __name__ == "__main__": + sys.stdout, sys.stderr = Public(sys.stdout), Public(sys.stderr) + try: + main() + except Exception as error: # MLflow and its HTTP client raise types of their own + sys.exit(redacted("".join(traceback.format_exception(error)))) diff --git a/scripts/inference-performance.py b/scripts/inference-performance.py index 66490c3e..2d300c28 100644 --- a/scripts/inference-performance.py +++ b/scripts/inference-performance.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Compare Skippy commits, and llama.cpp's own server, on one Metal host at a time.""" +"""Compare Skippy commits, and llama.cpp's own server, on one host of any backend in the table.""" import argparse import base64 @@ -9,6 +9,7 @@ import shutil import subprocess import sys +import traceback import tarfile import tempfile import time @@ -20,25 +21,30 @@ from lib.ci_artifacts import digest, read_json, write_json from lib.ci_process import cancel_on_signal, capture, command, start, stop from lib.ci_smoke import curl -from lib import inference_metal -from lib.inference_checks import ENDPOINT, offload +from lib.gguf_header import trained_context +from lib.inference_checks import ENDPOINT, memory_figures, offload from lib.inference_inputs import admit as admit_model from lib.inference_inputs import fixture from lib.jy_qualification import ORIGIN, Pilot -from lib.performance_arms import build, capabilities, server_args, supports -from lib.performance_load import run_point, tokenizer -from lib.performance_plan import (SCENARIO, arms, job_spec, models, nodes, pull_request_head, - pull_request_number, round_order, scenario) -from lib.performance_report import markdown, rows, summarize +from lib.performance_arms import build, capabilities, may_reject, server_args, server_flags, supports +from lib.performance_backends import BACKENDS +from lib.performance_load import request_rate, run_point, tokenizer +from lib.performance_plan import (SCENARIO, arms, branch_name, comparison, job_spec, model_context, models, + nodes, pull_request_head, pull_request_number, request_tokens, scenario) +from lib.performance_report import against_control, markdown, rows, summarize REPO = "Mesh-LLM/skippy" LLAMA_REPO = "ggml-org/llama.cpp" WORK = Path("target/inference-performance") -BUILT = WORK / "built.json" +# One file per arm, as each arm builds in a job step of its own. +BUILT = WORK / "built" +# What the steps after `start` and `model` read back: each arm's options, each admitted model. +HELPS = WORK / "helps.json" +MODELS = WORK / "models" +RECORD = "performance.json" # Outside the artifact directory: artifact names are flat, so the traces travel as one archive. TRACES = WORK / "traces" TERMINAL = {"succeeded", "failed", "cancelled", "expired"} -RESERVE = 16 * 1024**3 def github(path): @@ -57,23 +63,30 @@ def resolve_main(ref): def resolve(ref): - """A commit on main, or with `pr:N` an open pull request's head, as (commit, N or None).""" + """A commit on main, with `pr:N` an open pull request's head, or with `branch:NAME` a branch's head, as + (commit, N or None, NAME or None). Only collaborators with write access can push a branch here, which is + the same bar `pr:N` sets for its author.""" + branch = branch_name(ref) + if branch is not None: + return github(f"repos/{REPO}/branches/{quote(branch, safe='')}")["commit"]["sha"], None, branch number = pull_request_number(ref) if number is None: - return resolve_main(ref), None + return resolve_main(ref), None, None pull = github(f"repos/{REPO}/pulls/{number}") sha = pull_request_head(pull, REPO) login = pull["user"]["login"] permission = github(f"repos/{REPO}/collaborators/{quote(login, safe='')}/permission")["permission"] if permission not in {"admin", "maintain", "write"}: raise ValueError("native performance PR author must be a repository collaborator with write access") - return sha, number + return sha, number, None -def off_main(pull_requests): - """A line for each arm taken from a pull request, so no report reads as main's.""" - return "".join(f"The {label} was selected from PR #{number}.\n\n" - for label, number in pull_requests.items() if number is not None) +def off_main(pull_requests, branches=None): + """A line for each arm taken from a pull request or a branch, so no report reads as main's.""" + return "".join([*(f"The {label} was selected from PR #{number}.\n\n" + for label, number in pull_requests.items() if number is not None), + *(f"The {label} was selected from branch {name}.\n\n" + for label, name in (branches or {}).items() if name is not None)]) def reference_pin(sha): @@ -89,26 +102,36 @@ def committed_at(arm_list): def admit(evidence): harness = capture(["git", "rev-parse", "HEAD"]).strip() - candidate, candidate_pull = resolve(os.environ["CANDIDATE"]) - baseline, baseline_pull = resolve(os.environ["BASELINE"]) + candidate, candidate_pull, candidate_branch = resolve(os.environ["CANDIDATE"]) + baseline, baseline_pull, baseline_branch = (resolve(os.environ["BASELINE"]) if os.environ.get("BASELINE") + else (None, None, None)) pull_requests = {"candidate": candidate_pull, "baseline": baseline_pull} + branches = {"candidate": candidate_branch, "baseline": baseline_branch} with_reference = os.environ.get("REFERENCE", "true") == "true" trace = os.environ.get("TRACE", "false") == "true" - arm_list = arms(candidate, baseline, reference_pin(candidate) if with_reference else None) + backend = os.environ.get("BACKEND") or "metal" + arm_list = (arms(candidate, baseline, reference_pin(candidate), + None if baseline is None else reference_pin(baseline)) if with_reference + else arms(candidate, baseline, None)) keys = models([key.strip() for key in os.environ["MODELS"].split(",") if key.strip()]) pins = nodes([node.strip() for node in os.environ.get("NODES", "").split(",") if node.strip()]) rounds = int(os.environ.get("ROUNDS") or 3) + servers = [server.strip() for server in os.environ.get("SERVERS", "").split(",") if server.strip()] or None jobs = [{"label": node or "any", - "spec": job_spec(harness, arm_list, keys, rounds, node, node or "any", trace=trace)} + "spec": job_spec(harness, arm_list, keys, rounds, node, node or "any", + trace=trace, backend=backend, servers=servers)} for node in (pins or [None])] evidence.mkdir(parents=True, exist_ok=True) - write_json(evidence / "plan.json", {"harness": harness, "arms": arm_list, "models": keys, - "rounds": rounds, "trace": trace, "pull_requests": pull_requests, + write_json(evidence / "plan.json", {"harness": harness, "backend": backend, "arms": arm_list, + "models": keys, + "rounds": rounds, "trace": trace, "servers": servers, + "pull_requests": pull_requests, + "branches": branches, "committed_at": committed_at(arm_list), "jobs": jobs}) for arm in arm_list: print(f'{arm["label"]}: {arm["kind"]} {arm["sha"]}') - print(off_main(pull_requests), end="") - print(f"{len(jobs)} job(s), {len(keys)} model(s), {rounds} round(s); nothing has run yet") + print(off_main(pull_requests, branches), end="") + print(f"backend {backend}: {len(jobs)} job(s), {len(keys)} model(s), {rounds} round(s); nothing has run yet") def resource_id(identifier): @@ -149,6 +172,21 @@ def wait(pilot, identifier, evidence, deadline): raise RuntimeError(f"{identifier} did not finish before the controller deadline") +def keep_logs(pilot, run_id, label, evidence, exports=True): + """Each server's log, the builds' logs and AIPerf's per-request exports, beside the measurements: + what a surprising or failed point is read from, kept with the evidence rather than only in JY. + Without `exports`, the caller has fetched AIPerf's exports itself.""" + listed = pilot.api("GET", f"/v1/artifacts/{run_id}")["artifacts"] + names = {key.rsplit("/", 2)[2] for key in (artifact["key"] for artifact in listed)} + logs = evidence / f"{label}-logs" + for name in sorted(names): + if name.endswith(".log") and name != "job.log": + logs.mkdir(parents=True, exist_ok=True) + download(pilot, run_id, name, logs / name) + if exports and "aiperf.tar.gz" in names: + download(pilot, run_id, "aiperf.tar.gz", evidence / f"{label}-aiperf.tar.gz") + + def download(pilot, run_id, name, path): """An artifact that is not JSON, streamed to `path`.""" # Artifacts are namespaced by kind: raw/, log/ and trace/ files are served @@ -185,7 +223,8 @@ def collect(pilot, job, plan, label, evidence): write_json(evidence / f"{label}-performance.json", result) (evidence / f"{label}-rows.jsonl").write_text( "".join(json.dumps(row, sort_keys=True) + "\n" - for row in rows(result, scenario(), plan["committed_at"], job["id"], plan["pull_requests"])), + for row in rows(result, scenario(plan.get("servers")), plan["committed_at"], job["id"], + plan["pull_requests"], plan.get("branches"))), encoding="utf-8") download(pilot, run_id, "aiperf.tar.gz", evidence / f"{label}-aiperf.tar.gz") trace_notice = "" @@ -196,8 +235,13 @@ def collect(pilot, job, plan, label, evidence): trace_notice = f"\nDiagnostic trace archive unavailable: {error}\n" for failure in result.get("diagnostic", {}).get("failures", []): trace_notice += f"\nDiagnostic trace failed: {failure}\n" - host = f'{result["host"]["chip"]} ({result["host"].get("node") or "unknown node"})' - return markdown(f"Inference performance: {label}", host, summarize(result["samples"]), result) + trace_notice + keep_logs(pilot, run_id, label, evidence, exports=False) + host = f'{result["host"].get("gpu") or result["host"].get("chip") or "unknown device"}' \ + f' ({result["host"].get("node") or "unknown node"})' + summary = summarize(result["samples"]) + if comparison(plan["arms"], plan.get("servers")) == "servers": + against_control(summary, scenario(plan["servers"]), plan["servers"]) + return markdown(f"Inference performance: {label}", host, summary, result) + trace_notice def save_ledger(path, entries): @@ -236,14 +280,13 @@ def dispatch(evidence): for job, spec in zip(finished, plan["jobs"]): if job["status"] != "succeeded": failures.append(f'{spec["label"]}: {job["status"]}') + # a failed run's logs are what explain it; losing them must not hide the failure itself run_id = (job.get("runs") or [{}])[-1].get("id") if run_id: - for arm in plan.get("arms", []): - name = f'build-{arm["label"]}.log' - try: - download(pilot, resource_id(run_id), name, evidence / f'{spec["label"]}-{name}') - except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error: - failures.append(f'{spec["label"]}: {name} unavailable: {error}') + try: + keep_logs(pilot, resource_id(run_id), spec["label"], evidence) + except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError) as error: + failures.append(f'{spec["label"]}: logs not kept: {error}') continue try: reports.append(collect(pilot, job, plan, spec["label"], evidence)) @@ -251,7 +294,7 @@ def dispatch(evidence): failures.append(f'{spec["label"]}: collection failed: {error}') if polling_error is not None: failures.append(f"Controller interrupted: {polling_error}") - report = off_main(plan.get("pull_requests", {})) + "\n".join(reports) + report = off_main(plan.get("pull_requests", {}), plan.get("branches")) + "\n".join(reports) if failures: report += "\n## Incomplete jobs or evidence\n\n" + "\n".join("- " + error for error in failures) + "\n" (evidence / "summary.md").write_text(report, encoding="utf-8") @@ -270,27 +313,39 @@ def native_plan(): if capture(["git", "rev-parse", "HEAD"]).strip() != plan["harness"]: raise ValueError("harness checkout differs from the admitted harness commit") labels = {arm["label"]: arm["sha"] for arm in plan["arms"]} - expected = arms(labels["candidate"], labels["baseline"], labels.get("reference")) + expected = arms(labels["candidate"], labels.get("baseline"), labels.get("reference"), + labels.get("baseline-reference")) + if plan.get("backend") not in BACKENDS: + raise ValueError(f'performance plan backend {plan.get("backend")!r} has no entry in the table') if (plan["arms"] != expected or plan["models"] != models(plan["models"]) or type(plan.get("trace")) is not bool): raise ValueError("performance plan arms, models or trace flag are malformed") + comparison(plan["arms"], plan.get("servers")) return plan -def build_arms(): +def toolcheck(): + """The backend's tool check, before any build spends an hour on a host without its tools.""" + check = BACKENDS[native_plan()["backend"]]["tool_check"] + if callable(check): + check() + else: + command(check, timeout=120, capture_stdout=True) + + +def build_arm(label): plan = native_plan() - inference_metal.chip() - WORK.mkdir(parents=True, exist_ok=True) + arm = next((arm for arm in plan["arms"] if arm["label"] == label), None) + if arm is None: + raise ValueError(f"{label} is not an arm of the admitted plan") + BUILT.mkdir(parents=True, exist_ok=True) + log = WORK / f"build-{label}.log" try: - write_json(BUILT, [build(arm, WORK / f'build-{arm["label"]}.log') for arm in plan["arms"]]) + write_json(BUILT / f"{label}.json", build(arm, log, plan["backend"])) finally: - # execute() is the only other place build logs reach the artifact - # directory, and it never runs after a build failure. - output = os.environ.get("JIANYANG_ARTIFACT_DIR") - if output: - Path(output).mkdir(parents=True, exist_ok=True) - for log in WORK.glob("build-*.log"): - (Path(output) / log.name).write_bytes(log.read_bytes()) + # Copied at once, failed or not: a failed build ends the job. + if log.is_file(): + (artifacts() / log.name).write_bytes(log.read_bytes()) def ready(server, seconds): @@ -317,11 +372,16 @@ def traced(built, help_text, args, applied, missing, trace): "SKIPPY_TELEMETRY_OTLP_METRICS_FILE": str(trace.parent / f"{trace.name}.metrics.jsonl")} -def measure(built, help_text, model, inputs, key, index, server, shape, output, trace=None): +def measure(built, help_text, model, inputs, key, index, server, shape, output, trace=None, + prefixes=("MTL",), backend=None): """`index` is the round, or None for a diagnostic pass that writes `trace`.""" coordinate = f'{inputs["repo"]}@{inputs["revision"]}' - args, applied, missing = server_args(built, help_text, model, coordinate, - shape["context_per_lane"], server) + context = model_context(shape, server, inputs["trained_context"]) + beyond = [point["id"] for point in server["points"] + if "dataset" not in point and request_tokens(point) > context] + if beyond: + raise ValueError(f'{key} was trained on {context} tokens, fewer than {", ".join(beyond)} sends') + args, applied, missing = server_args(built, help_text, model, coordinate, context, server) overrides = None if trace is None else traced(built, help_text, args, applied, missing, trace) pass_name = "trace" if index is None else f"r{index + 1}" name = f'{key}-{pass_name}-{built["label"]}-{server["id"]}' @@ -331,82 +391,122 @@ def measure(built, help_text, model, inputs, key, index, server, shape, output, process = start(args, overrides, stdin=subprocess.DEVNULL, stdout=stream, stderr=stream) try: ready(process, 900) - offload(log) + offload(log, prefixes) + # what this model needs beyond its weights on this server, so a later plan can size its host + memory = memory_figures(log, prefixes) for point in server["points"]: - metrics = run_point(ENDPOINT, point, coordinate, inputs["tokenizer_path"], - shape["warmup_requests"], WORK / "aiperf" / name / point["id"]) + metrics, rejected = run_point(ENDPOINT, point, coordinate, inputs["tokenizer_path"], + shape["warmup_requests"], WORK / "aiperf" / name / point["id"], + may_reject=may_reject(built, server, point), server_log=log, + rate=request_rate(point, backend), context=context) + # A rejection is the answer of a server that is still serving; one that died is a fault. + if rejected is not None and process.poll() is not None: + raise RuntimeError("server exited while it was rejecting requests; inspect its log") samples.append({"model": key, "round": None if index is None else index + 1, "arm": built["label"], "server": server["id"], "point": point["id"], "applied": applied, - "unsupported": missing, "metrics": metrics}) + "unsupported": missing, "metrics": metrics, "rejected": rejected, + "memory": memory}) finally: stop(process) return samples -def execute(): +def artifacts(): + output = Path(os.environ["JIANYANG_ARTIFACT_DIR"]) + output.mkdir(parents=True, exist_ok=True) + return output + + +def start_measurement(): + """Check every arm before any round, so a variant whose flag an arm lacks fails before + anything is measured, and write the record the later steps add to.""" if os.geteuid() == 0: raise ValueError("native inference must not execute as root") - plan, chip = native_plan(), inference_metal.chip() - working_set = inference_metal.working_set(chip) - built = read_json(BUILT) - if [(entry["label"], entry["sha"]) for entry in built] != [(arm["label"], arm["sha"]) for arm in plan["arms"]]: + plan = native_plan() + entry = BACKENDS[plan["backend"]] + built = [read_json(BUILT / f'{arm["label"]}.json') for arm in plan["arms"]] + if [(arm["label"], arm["sha"]) for arm in built] != [(arm["label"], arm["sha"]) for arm in plan["arms"]]: raise ValueError("built arms differ from the admitted plan") - for entry in built: - if digest(Path(entry["binary"])) != entry["binary_sha256"]: - raise ValueError(f'{entry["label"]} binary changed after it was built') - output = Path(os.environ["JIANYANG_ARTIFACT_DIR"]) - output.mkdir(parents=True, exist_ok=True) - for log in WORK.glob("build-*.log"): - (output / log.name).write_bytes(log.read_bytes()) - shape, helps = scenario(), {entry["label"]: capabilities(entry) for entry in built} + for arm in built: + if digest(Path(arm["binary"])) != arm["binary_sha256"]: + raise ValueError(f'{arm["label"]} binary changed after it was built') + shape, helps = scenario(plan.get("servers")), {arm["label"]: capabilities(arm) for arm in built} + for arm in built: + for server in shape["servers"]: + server_flags(arm, helps[arm["label"]], server) + write_json(HELPS, helps) record = {"schema_version": 1, "harness": plan["harness"], "scenario_sha256": digest(SCENARIO), "started_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), - "host": {"chip": chip, "macos": capture(["sw_vers", "-productVersion"]).strip(), - "metal_working_set_bytes": working_set, "node": os.environ.get("JIANYANG_NODE")}, + "host": {"node": os.environ.get("JIANYANG_NODE"), "backend": plan["backend"], + **entry["facts"]()}, "arms": built, "rounds": plan["rounds"], "models": {}, "samples": []} if plan["trace"]: # Tracing slows the arm it runs on, so its samples never join the comparison. - record["diagnostic"] = {"telemetry": "debug", "arm": "candidate", "samples": []} + record["diagnostic"] = {"telemetry": "debug", "arm": "candidate", "samples": [], "failures": []} TRACES.mkdir(parents=True, exist_ok=True) - diagnostic_inputs = [] + write_json(artifacts() / RECORD, record) + + +def prepare_model(key): + plan = native_plan() + if key not in plan["models"]: + raise ValueError(f"{key} is not a model of the admitted plan") + entry, record = BACKENDS[plan["backend"]], read_json(artifacts() / RECORD) + inputs = fixture(key) + available = entry["free_memory"](record["host"]) + if available < sum(file["size"] for file in inputs["files"]) + entry["reserve_gib"] * 1024**3: + raise ValueError(f"{key}: insufficient {plan['backend']} free memory for weights and reserve") + model = admit_model(key, inputs) + # the plan was checked against the pin, so the pin must say what the verified weights say + if trained_context(model) != inputs["trained_context"]: + raise ValueError(f'{key}: its GGUF was trained for {trained_context(model)} tokens, ' + f'its pin says {inputs["trained_context"]}') + inputs = {**inputs, "tokenizer_path": str(tokenizer(inputs))} + record["models"][key] = {"repo": inputs["repo"], "revision": inputs["revision"], "files": inputs["files"], + "trained_context": inputs["trained_context"]} + MODELS.mkdir(parents=True, exist_ok=True) + write_json(MODELS / f"{key}.json", {"model": str(model), "inputs": inputs}) + write_json(artifacts() / RECORD, record) + + +def measure_step(key, label, server_id, round_number=None): + """One arm on one server for one round, or the candidate's diagnostic pass without a round.""" + plan = native_plan() + shape = scenario(plan.get("servers")) + server = next((server for server in shape["servers"] if server["id"] == server_id), None) + diagnostic = round_number is None + if (server is None or label not in {arm["label"] for arm in plan["arms"]} + or not diagnostic and not 1 <= round_number <= plan["rounds"] + or diagnostic and (not plan["trace"] or label != "candidate")): + raise ValueError(f"{label} on {server_id} is not a step of the admitted plan") + output = artifacts() + record, prepared = read_json(output / RECORD), read_json(MODELS / f"{key}.json") try: - for key in plan["models"]: - inputs = fixture(key) - available = inference_metal.available_memory(capture(["vm_stat"]), working_set) - if available < sum(file["size"] for file in inputs["files"]) + RESERVE: - raise ValueError(f"{key}: insufficient Metal working set or free memory for weights and reserve") - model = admit_model(key, inputs) - inputs = {**inputs, "tokenizer_path": tokenizer(inputs)} - record["models"][key] = {"repo": inputs["repo"], "revision": inputs["revision"], - "files": inputs["files"]} - for index in range(plan["rounds"]): - for entry in round_order(built, index): - for server in shape["servers"]: - record["samples"] += measure(entry, helps[entry["label"]], model, inputs, key, - index, server, shape, output) - write_json(output / "performance.json", record) - diagnostic_inputs.append((key, model, inputs)) - if plan["trace"]: - candidate = next(entry for entry in built if entry["label"] == "candidate") - record["diagnostic"]["failures"] = [] - for key, model, inputs in diagnostic_inputs: - for server in shape["servers"]: - try: - record["diagnostic"]["samples"] += measure( - candidate, helps["candidate"], model, inputs, key, None, server, shape, output, - trace=TRACES / f'{key}-{server["id"]}') - except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError) as error: - record["diagnostic"]["failures"].append(f'{key}/{server["id"]}: {error}') - write_json(output / "performance.json", record) - finally: - write_json(output / "performance.json", record) - if (WORK / "aiperf").is_dir(): - with tarfile.open(output / "aiperf.tar.gz", "w:gz") as archive: - archive.add(WORK / "aiperf", arcname="aiperf") - if TRACES.is_dir(): - with tarfile.open(output / "traces.tar.gz", "w:gz") as archive: - archive.add(TRACES, arcname="traces") + samples = measure(read_json(BUILT / f"{label}.json"), read_json(HELPS)[label], Path(prepared["model"]), + prepared["inputs"], key, None if diagnostic else round_number - 1, server, shape, + output, trace=TRACES / f"{key}-{server_id}" if diagnostic else None, + prefixes=BACKENDS[plan["backend"]]["device_prefixes"], backend=plan["backend"]) + except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError) as error: + if not diagnostic: + raise + # The trace pass only looks inside the measured run: a failed one is reported, not fatal. + record["diagnostic"]["failures"].append(f"{key}/{server_id}: {error}") + write_json(output / RECORD, record) + return + (record["diagnostic"] if diagnostic else record)["samples"] += samples + write_json(output / RECORD, record) + + +def finish_measurement(): + """Archive what the steps measured; the job runs it after a failure too.""" + output = artifacts() + if (WORK / "aiperf").is_dir(): + with tarfile.open(output / "aiperf.tar.gz", "w:gz") as archive: + archive.add(WORK / "aiperf", arcname="aiperf") + if TRACES.is_dir(): + with tarfile.open(output / "traces.tar.gz", "w:gz") as archive: + archive.add(TRACES, arcname="traces") def main(): @@ -415,8 +515,18 @@ def main(): for name in ("admit", "dispatch"): actions.add_parser(name).add_argument("evidence", type=Path) actions.add_parser("cancel").add_argument("ledger", type=Path) - actions.add_parser("build") - actions.add_parser("execute") + actions.add_parser("toolcheck") + actions.add_parser("build").add_argument("arm") + step = actions.add_parser("step").add_subparsers(dest="step", required=True) + step.add_parser("start") + step.add_parser("model").add_argument("model") + measured = step.add_parser("measure") + for name in ("model", "round", "arm", "server"): + measured.add_argument(name, type=int if name == "round" else str) + traced_pass = step.add_parser("trace") + for name in ("model", "server"): + traced_pass.add_argument(name) + step.add_parser("finish") args = parser.parse_args() if args.action == "admit": admit(args.evidence) @@ -424,10 +534,20 @@ def main(): dispatch(args.evidence) elif args.action == "cancel": cancel(Pilot(), args.ledger) + elif args.action == "toolcheck": + toolcheck() elif args.action == "build": - build_arms() + build_arm(args.arm) + elif args.step == "start": + start_measurement() + elif args.step == "model": + prepare_model(args.model) + elif args.step == "measure": + measure_step(args.model, args.arm, args.server, args.round) + elif args.step == "trace": + measure_step(args.model, "candidate", args.server) else: - execute() + finish_measurement() if __name__ == "__main__": @@ -436,4 +556,5 @@ def main(): main() except (OSError, ValueError, KeyError, TypeError, RuntimeError, subprocess.SubprocessError, KeyboardInterrupt) as error: + traceback.print_exc() sys.exit(str(error)) diff --git a/scripts/lib/ci_process.py b/scripts/lib/ci_process.py index 40bcc76e..c5f55aa1 100644 --- a/scripts/lib/ci_process.py +++ b/scripts/lib/ci_process.py @@ -59,9 +59,9 @@ def graceful_stop(child): except ProcessLookupError: pass except PermissionError: - # A recycled pgid names a group we cannot signal; once the child - # has exited there is nothing of ours left to signal. - if child.poll() is None: + # A recycled pgid, or a group whose members are all exiting, cannot be + # signalled; that is only an error while a process of ours is still in it. + if live_member(child.pid): raise @@ -74,11 +74,25 @@ def force_stop(child): except ProcessLookupError: pass except PermissionError: - if child.poll() is None: + if live_member(child.pid): raise child.wait(timeout=10) +def live_member(group): + """Whether a process of ours that can still run is in `group`. Zombies cannot + execute, and a process of another user's means the pgid was recycled.""" + rows = subprocess.check_output( + ["ps", "-axo", "pgid=,uid=,stat="], timeout=5, text=True, env=environment(), + ) + uid = os.getuid() + for row in rows.splitlines(): + pgid, owner, state = row.split(None, 2) + if int(pgid) == group and int(owner) == uid and not state.startswith(("Z", "X")): + return True + return False + + def group_alive(child): exited = child.poll() is not None if os.name == "nt": @@ -88,23 +102,13 @@ def group_alive(child): except ProcessLookupError: return False except PermissionError: - # The child can exit between poll() and killpg(), leaving a group - # visible to a different reaper. Recheck before treating it as live. - if child.poll() is None: - raise - exited = True + # Darwin answers EPERM for a group whose members are all exiting, which can + # happen between the poll above and the signal, as well as for a recycled pgid. + return live_member(child.pid) if not exited: return True - # A group containing only unreaped descendants can still be visible to - # killpg. Zombies cannot execute and may be owned by another reaper. - rows = subprocess.check_output( - ["ps", "-axo", "pgid=,stat="], timeout=5, text=True, env=environment(), - ) - for row in rows.splitlines(): - group, state = row.split(None, 1) - if int(group) == child.pid and not state.startswith(("Z", "X")): - return True - return False + # A group containing only unreaped descendants can still be visible to killpg. + return live_member(child.pid) def stop(child): diff --git a/scripts/lib/gguf_header.py b/scripts/lib/gguf_header.py new file mode 100644 index 00000000..a70e4639 --- /dev/null +++ b/scripts/lib/gguf_header.py @@ -0,0 +1,64 @@ +"""Read what a model was trained for from its GGUF header, without loading the weights.""" + +import struct + +# Value types of a fixed size, as struct formats; strings and arrays carry their own lengths. +FIXED = {0: "B", 1: "b", 2: "H", 3: "h", 4: "I", 5: "i", 6: "f", 7: "?", 10: "Q", 11: "q", 12: "d"} +STRING, ARRAY = 8, 9 + + +def read(stream, fmt): + size = struct.calcsize("<" + fmt) + data = stream.read(size) + if len(data) != size: + raise ValueError("truncated GGUF header") + return struct.unpack("<" + fmt, data)[0] + + +def string(stream): + length = read(stream, "Q") + data = stream.read(length) + if len(data) != length: + raise ValueError("truncated GGUF header") + return data.decode("utf-8") + + +def value(stream, kind): + """A scalar or string value; an array is skipped, as none is needed here and the + tokenizer's hold every token in the vocabulary.""" + if kind in FIXED: + return read(stream, FIXED[kind]) + if kind == STRING: + return string(stream) + if kind != ARRAY: + raise ValueError(f"unknown GGUF value type {kind}") + item, length = read(stream, "I"), read(stream, "Q") + if item in FIXED: + stream.seek(struct.calcsize("<" + FIXED[item]) * length, 1) + else: + for _ in range(length): + value(stream, item) + return None + + +def trained_context(path): + """`.context_length`: the longest sequence the model was trained on. + For a split model, the first shard holds the header.""" + with open(path, "rb") as stream: + if stream.read(4) != b"GGUF" or read(stream, "I") not in (2, 3): + raise ValueError(f"{path} is not a GGUF v2 or v3 file") + read(stream, "Q") + architecture, lengths = None, {} + for _ in range(read(stream, "Q")): + key, kind = string(stream), read(stream, "I") + found = value(stream, kind) + if key == "general.architecture": + architecture = found + elif key.endswith(".context_length"): + lengths[key] = found + if architecture is not None and f"{architecture}.context_length" in lengths: + length = lengths[f"{architecture}.context_length"] + if type(length) is not int or length < 1: + raise ValueError(f"{path}: {architecture}.context_length is not a positive count") + return length + raise ValueError(f"{path} names no context length for its architecture") diff --git a/scripts/lib/inference_checks.py b/scripts/lib/inference_checks.py index 711fa1f9..07f4aab9 100644 --- a/scripts/lib/inference_checks.py +++ b/scripts/lib/inference_checks.py @@ -32,20 +32,41 @@ def numerical(model, coordinate, fixture, output): command(args, timeout=1800, overrides={"CUDA_VISIBLE_DEVICES": ""}) -def offload(log): +def offload(log, prefixes=("MTL",)): + devices = "|".join(prefixes) with log.open(encoding="utf-8") as stream: for line in stream: match = re.search(r"offloaded ([0-9]+)/[^\n]*GPU", line) if match and int(match[1]) > 0: return # Skippy's structured status log does not forward llama.cpp's - # offload line; a Metal backend device selection is its GPU - # evidence, with the harness having applied --n-gpu-layers. - if '"type":"backend_device_selected"' in line and re.search(r'"detail":"MTL', line): + # offload line; a backend device selection is its GPU evidence, + # with the harness having applied --n-gpu-layers. + if '"type":"backend_device_selected"' in line and re.search(rf'"detail":"(?:{devices})', line): return raise ValueError("server log has no positive GPU-layer offload evidence") +KV_CACHE = re.compile(r"llama_kv_cache: size = +([0-9.]+) MiB \( *([0-9]+) cells") +RECURRENT = re.compile(r"llama_memory_recurrent: size = +([0-9.]+) MiB \( *([0-9]+) cells") + + +def memory_figures(log, prefixes=("MTL",)): + """What a server allocated beyond its weights, as llama.cpp reported it at startup: each KV + cache (a sliding-window model has two), the recurrent state, and the largest compute buffer on + the device, not the host. A model without a cache or state reports no line for it.""" + compute = re.compile(rf"(?:{'|'.join(prefixes)})[0-9]+ compute buffer size = +([0-9.]+) MiB") + caches, recurrent, buffers = [], [], [] + with log.open(encoding="utf-8") as stream: + for line in stream: + for pattern, found in ((KV_CACHE, caches), (RECURRENT, recurrent)): + if match := pattern.search(line): + found.append({"bytes": round(float(match[1]) * 1024**2), "cells": int(match[2])}) + if match := compute.search(line): + buffers.append(round(float(match[1]) * 1024**2)) + return {"kv_caches": caches, "recurrent": recurrent, "compute_bytes": max(buffers, default=0)} + + def request(model, prompt, maximum, timeout, stream=False): payload = {"model": model, "messages": [{"role": "user", "content": prompt}], "temperature": 0, "seed": 42, "max_tokens": maximum, @@ -102,7 +123,7 @@ def verify_corpus(corpus, output, phase): f'https://huggingface.co/api/datasets/{corpus["repo"]}/revision/main'], 60, local=False)) write_json(output / f"corpus-{phase}.json", result) if not re.fullmatch(r"[0-9a-f]{40}", corpus["revision"]) or result.get("sha") != corpus["revision"]: - raise ValueError("AgentX corpus revision differs from the admitted pin") + raise ValueError(f'{corpus["repo"]} revision differs from the admitted pin') def retain(directory, output): diff --git a/scripts/lib/inference_inputs.py b/scripts/lib/inference_inputs.py index 401b9f30..dc00b068 100644 --- a/scripts/lib/inference_inputs.py +++ b/scripts/lib/inference_inputs.py @@ -92,6 +92,10 @@ def fixture(key): value = fixtures[key] if not re.fullmatch(r"[0-9a-f]{40}", value["revision"]) or not value["files"]: raise ValueError("unpinned fixture") + # what the model was trained for, so a plan can refuse a point it cannot serve before any build; + # admission checks it against the GGUF + if type(value.get("trained_context")) is not int or value["trained_context"] < 1: + raise ValueError(f"{key} needs its trained_context pinned") names = set() for file in value["files"]: name = safe_relative(file["path"]).name diff --git a/scripts/lib/inference_nightly_metrics.py b/scripts/lib/inference_nightly_metrics.py index 1433e1b3..2e73858f 100644 --- a/scripts/lib/inference_nightly_metrics.py +++ b/scripts/lib/inference_nightly_metrics.py @@ -22,6 +22,9 @@ SMOKE_METRICS = ("prefill_tok_s", "decode_tok_s") AGENTX_METRICS = ("output_tok_s", "ttft_p95_ms", "itl_p95_ms", "requests", "request_error_pct") METRIC_NAMES = {"pr": SMOKE_METRICS, "nightly": AGENTX_METRICS, "release": AGENTX_METRICS} +# What the manifest says about a model beside its pinned files. A plan reads these and admission checks them +# against the files, so a benchmark measures nothing different: pinning one must not start every series again. +MODEL_FACTS = ("trained_context",) def metric_value(value, *, positive=False): @@ -95,10 +98,11 @@ def benchmark_definition(profile, mode, backend="cuda"): def contract(profile, row, key): functions, files = benchmark_definition(profile, row["mode"], row.get("backend", "cuda")) + model = {field: value for field, value in fixture(key).items() if field not in MODEL_FACTS} inputs = { "recipe_version": 2, "profile": profile, "mode": row["mode"], "device": METAL_DEVICE if row.get("backend") == "metal" else "NVIDIA GB10", - "admission": "native-stage-plan-v2", "model": fixture(key), + "admission": "native-stage-plan-v2", "model": model, "harness": {name: digest(Path(name)) for name in files}, "benchmark_functions": {path: benchmark_functions(path, names) for path, names in functions.items()}, diff --git a/scripts/lib/performance_arms.py b/scripts/lib/performance_arms.py index 68bb0648..6fec0a30 100644 --- a/scripts/lib/performance_arms.py +++ b/scripts/lib/performance_arms.py @@ -5,11 +5,17 @@ from .ci_artifacts import digest from .ci_process import capture, command +from .performance_backends import BACKENDS +from .performance_plan import ROOT PORT = 9337 REQUIRED = ("--startup-timeout-secs", "--bind-addr", "--model-id", "--ctx-size", "--n-gpu-layers", "--model-path") -METAL = {"LLAMA_STAGE_BACKEND": "metal", "LLAMA_STAGE_LINK_MODE": "static"} +# llama.cpp files its library's INFO lines under trace, and the offload line the +# startup check reads is one of them. +REFERENCE_VERBOSITY = 4 +TOOLKIT_ENV = ("PATH", "CUDACXX", "NVCC", "CUDAToolkit_ROOT", "CUDA_HOME", "CUDA_PATH", + "CUDA_LIBRARY_PATH", "LIBRARY_PATH", "LD_LIBRARY_PATH") def checkout(arm): @@ -20,27 +26,55 @@ def checkout(arm): return path.resolve() -def build(arm, log): +def toolkit_overrides(script): + """The toolkit environment Skippy's own build exports, so the reference arm configures + the same native toolkit rather than whatever an unpackaged CMake happens to find.""" + text = capture(["bash", "-c", f'source "{script}" && configure_cuda_toolkit_env && env -0']) + found = {key: value for item in text.split("\0") if "=" in item + for key, value in (item.split("=", 1),) if key in TOOLKIT_ENV} + if not found: + raise ValueError("the native toolkit environment did not resolve; the reference build cannot find it") + return found + + +def resolve_setting(entry, key): + """A table value, or a callable the host resolves at build time, such as a GPU architecture.""" + value = entry[key] + return value() if callable(value) else value + + +def build(arm, log, backend="metal"): """Every arm is a release build: the comparison measures what ships, not a debug harness.""" + entry = BACKENDS[backend] + skippy_env = resolve_setting(entry, "skippy_env") path = checkout(arm) with log.open("wb") as stream: if arm["kind"] == "skippy": - command(["just", "llama-build"], timeout=7200, overrides=METAL, cwd=path, + command(["just", "llama-build"], timeout=7200, overrides=skippy_env, cwd=path, stdout=stream, stderr=stream) command(["cargo", "build", "--locked", "--release", "-p", "skippy-cli"], timeout=7200, - overrides=METAL, cwd=path, stdout=stream, stderr=stream) + overrides=skippy_env, cwd=path, stdout=stream, stderr=stream) binary = path / "target/release/skippy" else: + overrides = None + if entry["toolkit_script"]: + overrides = toolkit_overrides(ROOT / entry["toolkit_script"]) build_dir = path / "build" command(["cmake", "-S", str(path), "-B", str(build_dir), "-G", "Ninja", - "-DCMAKE_BUILD_TYPE=Release", "-DGGML_METAL=ON", "-DLLAMA_BUILD_TESTS=OFF", + "-DCMAKE_BUILD_TYPE=Release", *resolve_setting(entry, "reference_cmake"), + "-DLLAMA_BUILD_TESTS=OFF", "-DLLAMA_BUILD_EXAMPLES=OFF", "-DLLAMA_BUILD_SERVER=ON"], timeout=1800, - cwd=path, stdout=stream, stderr=stream) + cwd=path, overrides=overrides, stdout=stream, stderr=stream) command(["cmake", "--build", str(build_dir), "--target", "llama-server", "--parallel"], - timeout=7200, cwd=path, stdout=stream, stderr=stream) + timeout=7200, cwd=path, overrides=overrides, stdout=stream, stderr=stream) binary = build_dir / "bin/llama-server" - return {"label": arm["label"], "kind": arm["kind"], "sha": arm["sha"], "binary": str(binary), - "binary_sha256": digest(binary)} + built = {"label": arm["label"], "kind": arm["kind"], "sha": arm["sha"], "binary": str(binary), + "binary_sha256": digest(binary)} + architecture = (skippy_env.get("LLAMA_STAGE_CUDA_ARCHITECTURES") + or skippy_env.get("LLAMA_STAGE_AMDGPU_TARGETS")) + if architecture: + built["gpu_architecture"] = architecture + return built def capabilities(built): @@ -61,13 +95,25 @@ def require_capabilities(built, help_text): raise ValueError(f'{built["label"]} unsupported: required server options missing: {", ".join(missing)}') +def server_flags(built, help_text, server): + """A variant server's own Skippy flags as arguments. They are what the variant measures, so an + arm whose build lacks one stops instead of running as the server it varies.""" + if built["kind"] != "skippy" or "skippy_flags" not in server: + return [] + missing = [name for name in server["skippy_flags"] if not supports(help_text, f"--{name}")] + if missing: + raise ValueError(f'{built["label"]} unsupported: {server["id"]} needs ' + f'{", ".join("--" + name for name in missing)}') + return [(f"--{name}", value) for name, value in server["skippy_flags"].items()] + + def server_args(built, help_text, model, coordinate, context, server): require_capabilities(built, help_text) lanes, pool = server["lanes"], server["pool_tokens"] if built["kind"] == "llama-server": total = pool if pool is not None else context * lanes args = [built["binary"], "-m", str(model), "--host", "127.0.0.1", "--port", str(PORT), - "-ngl", "999", "-np", str(lanes), "-c", str(total)] + "-ngl", "999", "-np", str(lanes), "-c", str(total), "-lv", str(REFERENCE_VERBOSITY)] missing = [] for flag, value in (("-kvu", None), ("--alias", coordinate)): if supports(help_text, flag): @@ -76,7 +122,7 @@ def server_args(built, help_text, model, coordinate, context, server): args.append(value) else: missing.append(flag) - return args, {"lanes": lanes, "total_context": total}, missing + return args, {"lanes": lanes, "total_context": total, "log_verbosity": REFERENCE_VERBOSITY}, missing args = [built["binary"], "serve", "--startup-timeout-secs", "300", "--ctx-size", str(context), "--n-gpu-layers", "999", "--bind-addr", f"127.0.0.1:{PORT}", "--model-path", str(model), "--model-id", coordinate] @@ -93,4 +139,21 @@ def server_args(built, help_text, model, coordinate, context, server): continue args += [flag] if value is None else [flag, str(value)] applied[flag.removeprefix("--").replace("-", "_")] = True if value is None else value + for flag, value in server_flags(built, help_text, server): + args += [flag, str(value)] + applied[flag.removeprefix("--").replace("-", "_")] = value return args, applied, missing + + +def may_reject(built, server, point): + """Whether failed requests at this point are a result rather than a fault. + + `llama-server` frees KV from idle slots only, so when the requests in flight need more + than its pool holds it fails them. Only there is a failure its answer: a Skippy arm is + held to every point, and so is `llama-server` inside its pool. + """ + pool = server["pool_tokens"] + if built["kind"] != "llama-server" or pool is None or "dataset" in point: + # A conversation point's pool holds a full lane for each conversation, as the scenario checks. + return False + return point["concurrency"] * (point["depth"] + point["input_tokens"] + point["output_tokens"]) > pool diff --git a/scripts/lib/performance_audit.py b/scripts/lib/performance_audit.py new file mode 100644 index 00000000..ca4aba5d --- /dev/null +++ b/scripts/lib/performance_audit.py @@ -0,0 +1,47 @@ +"""Check that a finished performance job is the measurement its plan admitted.""" + +from .performance_arms import may_reject +from .performance_plan import scenario + + +def audit(plan, record, node): + """What keeps `record` from being the measurement `plan` admitted, one sentence each; none + when it held. A job that succeeded can still have run an arm without a setting, cut its + output short or lost a metric, and its cells are then not like for like.""" + shape = scenario(plan.get("servers")) + points = {(server["id"], point["id"]): (server, point) + for server in shape["servers"] for point in server["points"]} + kinds = {arm["label"]: arm["kind"] for arm in plan["arms"]} + samples = record["samples"] + cells = len(points) * len(plan["models"]) + expected = cells * len(plan["arms"]) * plan["rounds"] + ran_on = (record.get("host") or {}).get("node") + # a dict keeps each sentence once, in the order found: the rounds repeat the same fault + found = {} + if node is not None and ran_on != node: + found[f"it ran on {ran_on}, not the pinned {node}"] = None + if len(samples) != expected: + found[f"{len(samples)} measured samples, not the {expected} its arms, points and rounds make"] = None + traced = len((record.get("diagnostic") or {}).get("samples") or []) + if plan["trace"] and traced != cells: + found[f"{traced} traced samples, not one for each of its {cells} points"] = None + for sample in samples: + where = f'{sample["arm"]} at {sample["point"]}' + known = points.get((sample["server"], sample["point"])) + if known is None or sample["arm"] not in kinds or sample["model"] not in plan["models"]: + found[f"{where} is not a cell of the plan"] = None + continue + server, point = known + for flag in sample["unsupported"]: + found[f'{sample["arm"]} ran without {flag}'] = None + if sample["rejected"] is not None: + if not may_reject({"kind": kinds[sample["arm"]]}, server, point): + found[f"{where} failed requests its pool could hold"] = None + continue + metrics = sample["metrics"] + if any(value is None for value in metrics.values()): + found[f"{where} is missing a metric"] = None + if "output_tokens" in point and metrics.get("output_tokens_mean") != point["output_tokens"]: + found[f'{where} wrote {metrics.get("output_tokens_mean")} tokens a request, ' + f'not the {point["output_tokens"]} asked for'] = None + return list(found) diff --git a/scripts/lib/performance_backends.py b/scripts/lib/performance_backends.py new file mode 100644 index 00000000..99cf3c31 --- /dev/null +++ b/scripts/lib/performance_backends.py @@ -0,0 +1,300 @@ +"""One closed table of the backends a performance comparison can run on. + +An entry holds everything backend-specific: the selector fragment of the JY target, the +Skippy build overrides, the reference build's accelerator CMake flags, the tool check that +runs before any build, the script that resolves a native toolkit when the reference build +needs one, the device prefixes that count as GPU offload evidence, and the functions that +prove the host and measure its free memory. `admit` refuses a `BACKEND` with no entry and +records the one it accepts in the plan; build and execute read the backend from the plan +and never infer it from the host, so a job always measures the machine it was planned for. +A backend without a complete entry therefore fails at plan time, not partway through a job. +""" + +import platform +import re +import shutil +import subprocess +from pathlib import Path + +from . import inference_metal +from .ci_process import capture + + +def linux_release(): + for line in Path("/etc/os-release").read_text(encoding="utf-8").splitlines(): + if line.startswith("PRETTY_NAME="): + return line.split("=", 1)[1].strip('"') + return "" + + +def metal_facts(): + chip = inference_metal.chip() + return {"chip": chip, "macos": capture(["sw_vers", "-productVersion"]).strip(), + "metal_working_set_bytes": inference_metal.working_set(chip)} + + +def metal_free(host): + return inference_metal.available_memory(capture(["vm_stat"]), host["metal_working_set_bytes"]) + + +def cuda_facts(): + """A Linux aarch64 host with an NVIDIA GB10, proved the way qualification's authority proves it.""" + if platform.system() != "Linux" or platform.machine() != "aarch64": + raise ValueError("the cuda backend requires Linux aarch64 (a DGX Spark)") + gpu = capture(["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"]).strip() + if "GB10" not in gpu: + raise ValueError(f"the cuda backend requires an NVIDIA GB10, not {gpu!r}") + driver = capture(["nvidia-smi", "--query-gpu=driver_version", "--format=csv,noheader"]).strip() + cuda = "" + for line in capture(["nvidia-smi", "--version"]).splitlines(): + if "CUDA Version" in line: + cuda = line.split(":", 1)[1].strip() + break + return {"gpu": gpu, "driver_version": driver, "toolkit_version": cuda or None, + "os": "linux", "os_version": linux_release(), "kernel": capture(["uname", "-r"]).strip()} + + +def cuda_free(host): + """Unified memory: everything the kernel will hand out is what a model competes for.""" + for line in Path("/proc/meminfo").read_text(encoding="utf-8").splitlines(): + if line.startswith("MemAvailable:"): + return int(line.split()[1]) * 1024 + raise ValueError("MemAvailable missing") + + +# A discrete GPU runs no operating system beside the model, so its reserve covers only the +# KV pools and recurrent state of the deepest cells and both arms' compute buffers, not +# the unified 16 GiB. Sized in the cuda-x86 platform's step 3; see INFERENCE_PERFORMANCE.md. +DISCRETE_RESERVE_GIB = 6 + + +def cuda_x86_architecture(): + """The host GPU's compute capability, read at build time: 8.9 means architecture 89.""" + capability = capture(["nvidia-smi", "--query-gpu=compute_cap", "--format=csv,noheader", + "-i", "0"]).strip() + if not re.fullmatch(r"[0-9]+\.[0-9]", capability): + raise ValueError(f"GPU 0 reported no compute capability: {capability!r}") + return capability.replace(".", "") + + +def cuda_x86_skippy_env(): + return {"LLAMA_STAGE_BACKEND": "cuda", "LLAMA_STAGE_LINK_MODE": "static", + "LLAMA_STAGE_CUDA_ARCHITECTURES": cuda_x86_architecture()} + + +def cuda_x86_reference_cmake(): + return ["-DGGML_CUDA=ON", f"-DCMAKE_CUDA_ARCHITECTURES={cuda_x86_architecture()}"] + + +def cuda_x86_facts(): + """A discrete-NVIDIA Linux x86_64 host, described by GPU 0: the one the job pins.""" + if platform.system() != "Linux" or platform.machine() != "x86_64": + raise ValueError("the cuda-x86 backend requires Linux x86_64") + row = capture(["nvidia-smi", "--query-gpu=name,driver_version,compute_cap,memory.total," + "memory.free,count", "--format=csv,noheader,nounits", "-i", "0"]).strip() + fields = [item.strip() for item in row.split(",")] + if len(fields) != 6: + raise ValueError(f"nvidia-smi did not describe GPU 0: {row!r}") + name, driver, capability, total_mib, free_mib, count = fields + cuda = "" + for line in capture(["nvidia-smi", "--version"]).splitlines(): + if "CUDA Version" in line: + cuda = line.split(":", 1)[1].strip() + break + processes = capture(["nvidia-smi", "--query-compute-apps=pid,process_name,used_memory", + "--format=csv", "-i", "0"]).strip() + return {"gpu": name, "gpu_count": int(count), "gpu_used": 0, + "gpu_compute_capability": capability, + "gpu_memory_total_bytes": int(total_mib) * 1024**2, + "gpu_memory_free_bytes": int(free_mib) * 1024**2, + "driver_version": driver, "toolkit_version": cuda or None, + "os": "linux", "os_version": linux_release(), "kernel": capture(["uname", "-r"]).strip(), + "gpu_processes": processes or None} + + +def gpu0_free(): + free_mib = capture(["nvidia-smi", "--query-gpu=memory.free", "--format=csv,noheader,nounits", + "-i", "0"]).strip() + if not free_mib.isdigit(): + raise ValueError(f"nvidia-smi reported no free memory for GPU 0: {free_mib!r}") + return int(free_mib) * 1024**2 + + +def cuda_x86_free(host): + """The weights must fit GPU 0's own free VRAM, and Skippy may also hold KV in host RAM. Both are + read at each model's admission: what the job saw at its start is evidence, not what is free now.""" + return min(gpu0_free(), cuda_free(host)) + + +def rocm_agent(): + """The first GPU agent rocminfo lists: its gfx target and marketing name.""" + gfx, name = None, None + for line in capture(["rocminfo"]).splitlines(): + key, _, value = line.partition(":") + key, value = key.strip(), value.strip() + if key == "Name" and re.fullmatch(r"gfx[0-9a-z]+", value or "") and gfx is None: + gfx = value + elif key == "Marketing Name" and value and gfx is not None and name is None: + name = value + if gfx is None: + raise ValueError("rocminfo lists no GPU agent; the rocm backend needs one") + return gfx, name or gfx + + +def rocm_gfx(): + return rocm_agent()[0] + + +ROCM_GFX_TARGET = "gfx1151" + + +def rocm_skippy_env(): + return {"LLAMA_STAGE_BACKEND": "rocm", "LLAMA_STAGE_LINK_MODE": "static", + "LLAMA_STAGE_AMDGPU_TARGETS": ROCM_GFX_TARGET} + + +def rocm_reference_cmake(): + # The pinned llama.cpp's ggml-hip/CMakeLists.txt forwards AMDGPU_TARGETS to + # CMAKE_HIP_ARCHITECTURES, so this is the variable Skippy's build also sets. + return ["-DGGML_HIP=ON", f"-DAMDGPU_TARGETS={ROCM_GFX_TARGET}"] + + +def rocm_tool_check(): + capture(["rocminfo"]) + if not shutil.which("rocm-smi"): + raise ValueError("the rocm backend requires rocm-smi for its memory figures") + + +def _try_capture(args): + try: + return capture(args) + except subprocess.CalledProcessError: + return "" + + +def rocm_memory(): + """VRAM and GTT, total and used, from the first row rocm-smi reports, plus the GPU count.""" + text = capture(["rocm-smi", "--showmeminfo", "vram", "gtt", "--csv"]) + lines = [line for line in text.strip().splitlines() if line.strip()] + if len(lines) < 2: + raise ValueError(f"rocm-smi did not report vram and gtt: {text!r}") + header = [item.strip().lower() for item in lines[0].split(",")] + + def field(*words): + for index, column in enumerate(header): + if all(word in column for word in words) and index < len(lines[1].split(",")): + return int(lines[1].split(",")[index].strip()) + raise ValueError(f"rocm-smi columns for {words} not found in {header}") + + return (field("vram", "total"), field("vram", "used"), field("gtt", "total"), field("gtt", "used"), + len(lines) - 1) + + +def rocm_facts(): + """A Linux x86_64 host with an AMD GPU through ROCm/HIP, described by its first GPU.""" + if platform.system() != "Linux" or platform.machine() != "x86_64": + raise ValueError("the rocm backend requires Linux x86_64") + gfx, name = rocm_agent() + vram_total, vram_used, gtt_total, gtt_used, gpu_count = rocm_memory() + try: + rocm = Path("/opt/rocm/.info/version").read_text(encoding="utf-8").strip() + except OSError: + rocm = None + driver_text = _try_capture(["rocm-smi", "--showdriverversion", "--csv"]).strip() + last = driver_text.splitlines()[-1] if driver_text else "" + driver = last.split(",")[-1].strip() if last else "" + return {"gpu": name, "gpu_count": gpu_count, "gpu_used": 0, "gfx_target": gfx, + "vram_total_bytes": vram_total, "vram_used_bytes": vram_used, + "gtt_total_bytes": gtt_total, "gtt_used_bytes": gtt_used, + "driver_version": driver or None, "toolkit_version": rocm, + "os": "linux", "os_version": linux_release(), "kernel": capture(["uname", "-r"]).strip()} + + +def rocm_free(host): + """Unified AMD memory: the GPU allocates from its carve-out (VRAM) plus GTT, and the + kernel caps GTT, so both pools and MemAvailable bound what a model gets. All three are + read at each model's admission.""" + vram_total, vram_used, gtt_total, gtt_used, _ = rocm_memory() + return min(cuda_free(host), (vram_total - vram_used) + (gtt_total - gtt_used)) + + +# The unified reserve, shared system memory for everything beside the weights. +RESERVE_GIB = 16 + +BACKENDS = { + "metal": { + "description": "Same-host Metal comparison", + "selector": {"os": {"family": "macos"}, "accelerator": {"backend": "metal"}}, + "memory_key": "system_gib", + "reserve_gib": RESERVE_GIB, + "pin_required": False, + "skippy_env": {"LLAMA_STAGE_BACKEND": "metal", "LLAMA_STAGE_LINK_MODE": "static"}, + "reference_cmake": ["-DGGML_METAL=ON"], + "tool_check": ["xcrun", "--find", "swift"], + "toolkit_script": None, + "device_prefixes": ("MTL",), + "facts": metal_facts, + "free_memory": metal_free, + "env": {}, + }, + "cuda": { + "description": "Same-host CUDA comparison", + "selector": {"os": {"family": "linux"}, "arch": {"in": ["aarch64"]}, + "accelerator": {"backend": "cuda", "model": {"in": ["NVIDIA GB10"]}}, + "memory": {"unified": True}}, + "memory_key": "system_gib", + "reserve_gib": RESERVE_GIB, + "pin_required": False, + "skippy_env": {"LLAMA_STAGE_BACKEND": "cuda", "LLAMA_STAGE_LINK_MODE": "static", + "LLAMA_STAGE_CUDA_ARCHITECTURES": "121"}, + "reference_cmake": ["-DGGML_CUDA=ON", "-DCMAKE_CUDA_ARCHITECTURES=121"], + "tool_check": ["nvidia-smi"], + "toolkit_script": "scripts/lib/cuda-toolkit.sh", + "device_prefixes": ("CUDA",), + "facts": cuda_facts, + "free_memory": cuda_free, + "env": {}, + }, + # A discrete NVIDIA GPU on Linux x86_64. x86 hosts carry different cards, so a plan + # must name one node, both arms build for that card's own architecture, and the job + # pins GPU 0 with CUDA_VISIBLE_DEVICES. Admission is against GPU 0's free VRAM. + "cuda-x86": { + "description": "Same-host CUDA comparison", + "selector": {"os": {"family": "linux"}, "arch": {"in": ["x86_64"]}, + "accelerator": {"backend": "cuda"}, "memory": {"unified": False}}, + "memory_key": "dedicated_vram_gib", + "reserve_gib": DISCRETE_RESERVE_GIB, + "pin_required": True, + "skippy_env": cuda_x86_skippy_env, + "reference_cmake": cuda_x86_reference_cmake, + "tool_check": ["nvidia-smi"], + "toolkit_script": "scripts/lib/cuda-toolkit.sh", + "device_prefixes": ("CUDA",), + "facts": cuda_x86_facts, + "free_memory": cuda_x86_free, + "env": {"CUDA_VISIBLE_DEVICES": "0"}, + }, + # AMD ROCm on Linux x86_64. The lab's hosts are Strix-Halo class — unified memory, + # the GPU allocating from its VRAM carve-out plus GTT — so admission takes the smaller + # of MemAvailable and free VRAM plus GTT, and the reserve is the unified 16 GiB. No CI + # exercises Skippy's Linux ROCm build; a performance smoke job is its first run. + "rocm": { + "description": "Same-host ROCm comparison", + # The lab's ROCm agents report no os facts and any selector holding an os + # key never matches them, so a rocm plan targets its pinned node bare. + "selector": {}, + "memory_key": "system_gib", + "reserve_gib": RESERVE_GIB, + "pin_required": True, + "skippy_env": rocm_skippy_env, + "reference_cmake": rocm_reference_cmake, + "tool_check": rocm_tool_check, + "toolkit_script": None, + "device_prefixes": ("ROCm", "HIP"), + "facts": rocm_facts, + "free_memory": rocm_free, + "env": {"HIP_VISIBLE_DEVICES": "0", "SKIPPY_AMDGPU_TARGETS": ROCM_GFX_TARGET, + "PATH": "/opt/rocm/bin:/usr/local/bin:/usr/bin:/bin", + "LD_LIBRARY_PATH": "/opt/rocm/lib"}, + }, +} diff --git a/scripts/lib/performance_load.py b/scripts/lib/performance_load.py index fdeae2be..a578e07f 100644 --- a/scripts/lib/performance_load.py +++ b/scripts/lib/performance_load.py @@ -1,13 +1,33 @@ """Drive one load point with the pinned AIPerf and read back what it measured.""" +import json +import re +import shutil +import subprocess +import tempfile +from collections import Counter from pathlib import Path from .ci_artifacts import read_json from .ci_process import command +from .inference_checks import verify_corpus from .inference_inputs import downloaded_path, safe_relative AIPERF = ["uv", "tool", "run", "--python", "3.12", "--constraints", "ci/aiperf-requirements.lock", "--from", "aiperf==0.13.0", "aiperf", "profile"] +# A conversation point replays recorded conversations, each turn sent with the turns before it, +# instead of generated prompts. `bound` is what ends it: AgentX paces its turns from the traces' +# own gaps, so it runs for a time; ShareGPT sends each turn once the last is answered, so it runs +# for a number of requests. +# `smallest_tokens` is the corpus's shortest conversation at its pinned revision, input and output +# together: AIPerf replays only those that fit the context, so a model serving less has none to +# replay. AgentX's shortest carries a coding agent's system prompt; ShareGPT's turns all fit. +DATASETS = { + "agentx": {"corpus": "ci/inference-corpus.json", "bound": "duration_s", "smallest_tokens": 44048}, + "sharegpt": {"corpus": "ci/inference-chat-corpus.json", "bound": "requests", "smallest_tokens": None}, +} +# AgentX's scenario holds a shorter run to be no submission; a comparison is not one. +AGENTX_MINIMUM_S = 900 # Output name -> (AIPerf export metric, statistic). Missing metrics stay null; the raw # export is retained beside them, so a renamed field is visible rather than zero. METRICS = { @@ -32,17 +52,63 @@ def tokenizer(fixture): return path -def profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory): - args = [ +def request_rate(point, backend): + """A rate point's arrivals per second on `backend`, or None for a point that keeps its + concurrency in flight. A rate is set per backend, as each runs a different share of what + its hardware can serve.""" + rates = point.get("request_rate") + if rates is None: + return None + if backend not in rates: + raise ValueError(f'{point["id"]} has no request rate for the {backend} backend') + return rates[backend] + + +def dataset(point): + """The dataset a conversation point replays, or None for a point of generated prompts.""" + return DATASETS[point["dataset"]] if "dataset" in point else None + + +def common_args(endpoint, point, coordinate, tokenizer_path, directory): + return [ *AIPERF, "--ui", "simple", "--url", endpoint, "--endpoint-type", "chat", "--streaming", + # Nothing here reads AIPerf's server metrics or GPU telemetry, and under load their + # optional collectors miss heartbeats, which marks the whole run incomplete. + "--no-server-metrics", "--no-gpu-telemetry", "--model", coordinate, "--tokenizer", str(tokenizer_path), "--random-seed", "42", "--use-server-token-count", "--concurrency", str(point["concurrency"]), + "--artifact-dir", str(directory), + ] + + +def conversation_args(endpoint, point, coordinate, tokenizer_path, warmup, directory, context, corpus): + args = [*common_args(endpoint, point, coordinate, tokenizer_path, directory), + "--public-dataset", corpus["alias"]] + if point["dataset"] == "agentx": + # The scenario the nightly runs: it sets the trace pacing and ignore_eos itself, and + # keeps only the traces whose turns fit a lane. + args += ["--scenario", "inferencex-agentx-mvp", "--max-context-length", str(context), + "--cache-bust", "first-turn-prefix", "--benchmark-duration", str(point["duration_s"])] + return args + (["--unsafe-override"] if point["duration_s"] < AGENTX_MINIMUM_S else []) + # Each turn asks for its recorded reply's length and gets all of it, so every arm + # generates the same tokens whatever its model would have stopped at. + return args + ["--request-count", str(point["requests"]), "--warmup-request-count", str(warmup), + "--extra-inputs", "ignore_eos:true"] + + +def profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory, rate=None): + args = [ + *common_args(endpoint, point, coordinate, tokenizer_path, directory), "--request-count", str(point["requests"]), "--warmup-request-count", str(warmup), "--synthetic-input-tokens-mean", str(point["input_tokens"]), "--synthetic-input-tokens-stddev", "0", "--output-tokens-mean", str(point["output_tokens"]), "--output-tokens-stddev", "0", "--extra-inputs", "ignore_eos:true", - "--artifact-dir", str(directory), ] + if rate is not None: + # Requests arrive on their own schedule, seeded so every arm sees the same one, and the + # concurrency is only a ceiling. Kept in flight instead, requests that finish together + # are replaced together, and every later wave queues the way the first one did. + args += ["--request-rate", str(rate), "--arrival-pattern", "poisson"] if point["depth"]: # One shared prefix per concurrent request: each conversation re-reads its own # prefix, so the KV pool has to hold concurrency x depth to keep them resident. @@ -64,9 +130,98 @@ def measurements(export): for name, (metric, statistic) in METRICS.items()} -def run_point(endpoint, point, coordinate, tokenizer_path, warmup, directory: Path): - command(profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory), timeout=5400) - exports = list(directory.rglob("profile_export_aiperf.json")) +# How llama-server's answer reads when the requests in flight need more KV than its pool holds: a 500 +# naming the context or, mid-stream, an error event AIPerf records as a response without content. +POOL_FULL = ("Context size has been exceeded", "No responses with actual content were received") +# The line llama-server logs for each error it sends a client, before the stream or within it. +SENT = re.compile(r"send_error: task id = \d+, error: (.*)") + + +def sent_errors(log, offset): + """The errors a server's log says it sent after its first `offset` bytes.""" + with log.open("rb") as stream: + stream.seek(offset) + return [found.group(1).strip() for found in SENT.finditer(stream.read().decode("utf-8", "replace"))] + + +def rejection(directory, requests, sent): + """What the server failed among the measured requests, from AIPerf's per-request export, + checked against `sent`, the errors the server logged sending while the point ran. + + AIPerf records an error for a request the server answers with one. A stream that ends on + an error event it counts as served and leaves without an output length: that request is + cut short here. Neither always keeps the server's reason, so the server must have logged a + full pool for every request failed or cut short. None when nothing failed, and None unless + the export accounts for every measured request, so a load run that broke off is never taken + for the server's answer. Any other error, in the export or the server's log, is a fault, at + this point as at every other: it raises. + """ + exports = list(directory.rglob("profile_export.jsonl")) if len(exports) != 1: - raise ValueError(f'{point["id"]}: expected one AIPerf export, found {len(exports)}') - return measurements(read_json(exports[0])) + return None + # One record a line. A server's own error text sits inside a record, so split on newlines alone. + records = [json.loads(line) for line in exports[0].read_text(encoding="utf-8").split("\n") if line.strip()] + measured = [record for record in records + if (record.get("metadata") or {}).get("benchmark_phase") == "profiling"] + failed = Counter(json.dumps(record["error"], sort_keys=True) for record in measured if record.get("error")) + cut_short = sum(1 for record in measured if not record.get("error") + and "output_sequence_length" not in (record.get("metrics") or {})) + if len(measured) != requests or not (failed or cut_short): + return None + unexplained = [error for error in failed if not any(text in error for text in POOL_FULL)] + if unexplained: + raise ValueError(f"{sum(failed[error] for error in unexplained)} of {requests} requests failed " + f"with errors that are not a full KV pool, such as {json.loads(unexplained[0])}") + other = sorted({text for text in sent if POOL_FULL[0] not in text}) + if other: + raise ValueError(f"the server sent errors that are not a full KV pool, such as {other[0]!r}") + ended = sum(failed.values()) + cut_short + if len(sent) < ended: + raise ValueError(f"{ended} of {requests} requests failed or were cut short, but the server " + f"logged only {len(sent)} refusals for a full KV pool") + return {"requests": requests, "failed": sum(failed.values()), "cut_short": cut_short, + "errors": [{"error_details": json.loads(error), "count": count} + for error, count in sorted(failed.items())]} + + +def run_point(endpoint, point, coordinate, tokenizer_path, warmup, directory: Path, *, may_reject, server_log, + context, rate=None): + """One point's metrics, or null metrics and what the server rejected where it may reject. + `server_log` is the server's log, whose lines from this point give its reasons for a rejection. + `context` is a lane's, which every turn of a replayed AgentX trace must fit.""" + failure, entry = None, dataset(point) + if entry is None: + args = profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory, rate) + else: + corpus = read_json(Path(entry["corpus"])) + directory.parent.mkdir(parents=True, exist_ok=True) + # The loader resolves the dataset's main branch; the pin holds only if main has not moved. + verify_corpus(corpus, directory.parent, f'{point["id"]}-before') + args = conversation_args(endpoint, point, coordinate, tokenizer_path, warmup, directory, context, corpus) + # AIPerf stages its ZeroMQ event bus under TMPDIR, and the job's own TMPDIR + # lives under the workspace, whose path can exceed the 103-byte unix-socket + # limit (this Mac's "Application Support" tree) before AIPerf adds its own + # nesting. Anchor a short, space-free TMPDIR at /tmp instead. + short_tmp = Path(tempfile.mkdtemp(prefix="aiperf-tmp-", dir="/tmp")) + offset = server_log.stat().st_size + try: + command(args, timeout=5400, overrides={"TMPDIR": str(short_tmp)}) + except subprocess.CalledProcessError as error: + # AIPerf exits non-zero, with no summary export, when every measured request failed. + failure = error + finally: + shutil.rmtree(short_tmp, ignore_errors=True) + if entry is not None: + verify_corpus(corpus, directory.parent, f'{point["id"]}-after') + rejected = rejection(directory, point["requests"], sent_errors(server_log, offset)) if may_reject else None + if rejected is not None: + return dict.fromkeys(METRICS), rejected + if failure is not None: + raise failure + # AIPerf 0.13.0 writes the summary at the artifact root and each phase under + # phases/, so a recursive search sees three exports; the summary is the file + # this point's numbers come from. + export = directory / "profile_export_aiperf.json" + if not export.is_file(): + raise ValueError(f'{point["id"]}: no AIPerf export in {directory}') + return measurements(read_json(export)), None diff --git a/scripts/lib/performance_nightly.py b/scripts/lib/performance_nightly.py new file mode 100644 index 00000000..d49fe871 --- /dev/null +++ b/scripts/lib/performance_nightly.py @@ -0,0 +1,259 @@ +"""Plan the nightly comparison of main with the commit the last successful nightly measured, and +say where Skippy regressed between them.""" + +import re + +from .ci_artifacts import read_json +from .inference_baselines import TOLERANCE, classify +from .inference_charts import METRICS as TITLES +from .inference_markdown import plain, sha, table +from .performance_audit import audit +from .performance_backends import BACKENDS +from .performance_plan import MAX_ROUNDS, NODE, ROOT, SHA, count, models, scenario +from .performance_report import HEADLINE, llama_change, summarize +from .performance_report import cell as rounds_text +from .performance_report import verdict as described + +NIGHTLY = ROOT / "ci/inference-performance-nightly.json" +WORKFLOW = "inference-performance-nightly.yml" +# A lane's id names its evidence artifact, so it is lower-case words joined by dashes. +LANE = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*") +LANE_FIELDS = {"id", "backend", "node", "model"} +# What a night compares. `commits`: main against the last successful nightly's commit. `noise`: main +# against itself, the first night or when asked, which measures the spread of two equal builds. +# `unchanged`: main has not moved since the last successful nightly, so nothing is measured. +MODES = ("commits", "noise", "unchanged") + + +def lanes(): + """The checked lanes: each is one model on one pinned node, and no node is in two lanes. Two jobs + on one node would queue behind each other inside a single controller's deadline, and a job of + several models is recorded without its place in the results' history.""" + value = read_json(NIGHTLY) + if (type(value) is not dict or set(value) != {"schema_version", "rounds", "lanes"} + or value["schema_version"] != 1 or type(value["lanes"]) is not list or not value["lanes"]): + raise ValueError("invalid nightly performance lanes") + rounds = count(value["rounds"], "rounds") + if rounds > MAX_ROUNDS: + raise ValueError(f"at most {MAX_ROUNDS} rounds fit the job's time budget") + ids, pinned, result = set(), set(), [] + for lane in value["lanes"]: + if type(lane) is not dict or not LANE_FIELDS <= set(lane) <= LANE_FIELDS | {"servers", "trace"}: + raise ValueError("a nightly lane names its id, backend, node and model") + name, backend, node, model = (lane[field] for field in ("id", "backend", "node", "model")) + if type(name) is not str or not LANE.fullmatch(name) or name in ids: + raise ValueError(f"nightly lane ids are distinct lower-case words joined by dashes: {name!r}") + if type(backend) is not str or backend not in BACKENDS: + raise ValueError(f"{name}: unknown backend {backend!r}; the table holds {', '.join(sorted(BACKENDS))}") + if type(node) is not str or not NODE.fullmatch(node) or node in pinned: + raise ValueError(f"{name}: a lane pins one JY node that no other lane uses") + if type(model) is not str: + raise ValueError(f"{name}: a lane measures one pinned model") + servers, trace = lane.get("servers"), lane.get("trace", False) + if servers is not None: + if type(servers) is not list or not all(type(server) is str for server in servers): + raise ValueError(f"{name}: servers is a list of scenario server ids") + scenario(servers) + if type(trace) is not bool: + raise ValueError(f"{name}: trace must be true or false") + ids.add(name) + pinned.add(node) + result.append({"id": name, "backend": backend, "node": node, "model": models([model])[0], + "servers": servers, "trace": trace, "rounds": rounds}) + return result + + +def matrix(lane_list): + """The lanes as the strategy matrix of the workflow's measuring job, one call of the + performance workflow each.""" + return {"include": [{**lane, "servers": ",".join(lane["servers"] or [])} for lane in lane_list]} + + +def previous(runs, current): + """The commit the last successful nightly measured: its head on main. `runs` is GitHub's list + of this workflow's runs, newest first; `current` is the run asking.""" + for run in runs: + if (run.get("id") != current and run.get("conclusion") == "success" + and run.get("head_branch") == "main" and run.get("event") in {"schedule", "workflow_dispatch"} + and SHA.fullmatch(run.get("head_sha") or "")): + return run["head_sha"] + return None + + +def compared(candidate, found, rebaseline): + """(baseline, mode) for tonight's `candidate`, given the commit `found` by `previous`.""" + if not SHA.fullmatch(candidate): + raise ValueError("the nightly measures an immutable 40-digit commit") + if rebaseline or found is None: + return candidate, "noise" + return found, "unchanged" if found == candidate else "commits" + + +def evidence(root, lane_list, run): + """Each lane's evidence directory under `root`, from the newest attempt that uploaded one: a + rerun of the lanes that failed keeps the earlier attempt's artifacts for those that passed.""" + found = {} + for lane in lane_list: + prefix = f'inference-performance-{lane["id"]}-{run}-' + attempts = [(int(path.name[len(prefix):]), path) for path in (root.iterdir() if root.is_dir() else ()) + if path.is_dir() and path.name.startswith(prefix) and path.name[len(prefix):].isdigit()] + if attempts: + found[lane["id"]] = max(attempts)[1] + return found + + +def worse(metric, percent): + """A change as percent worse: throughput that fell and latency that rose both come out positive.""" + return -percent if HEADLINE[metric] == "higher" else percent + + +def cells(record, mode): + """Every headline cell that tonight's commit and the baseline both measured, with its state. + + `regressed`: the candidate is worse by more than the shared tolerance and none of its rounds + reaches the baseline's. `improved` is the same the other way. `uncertain`: past the tolerance + with overlapping rounds, which counts as neither. `within`: inside the tolerance. On a noise + night both arms are one commit, so every cell is `noise`, whatever it measured. + + A regression is llama.cpp's when the pin moved and `llama-server` lost as much at that cell, + to within the tolerance; otherwise it is Skippy's. A cell an arm did not measure is left + out: an unmeasured cell is never reported as a regression.""" + result = [] + for row in summarize(record["samples"]): + delta = row["candidate_vs_baseline"] + if row["metric"] not in HEADLINE or delta is None: + continue + metric, arms = row["metric"], row["arms"] + moved = classify(metric, arms["candidate"]["median"], arms["baseline"]["median"]) + if mode == "noise": + state = "noise" + elif moved == "passed": + state = "within" + else: + state = "uncertain" if delta["ranges_overlap"] else moved + llama, owner = row["reference_vs_baseline_reference"], None + if state == "regressed": + inherited = (llama is not None and not llama["ranges_overlap"] + and classify(metric, arms["reference"]["median"], + arms["baseline-reference"]["median"]) == "regressed" + and worse(metric, delta["percent"]) - worse(metric, llama["percent"]) + <= float(TOLERANCE) * 100) + owner = "llama.cpp" if inherited else "skippy" + result.append({"model": row["model"], "server": row["server"], "point": row["point"], "metric": metric, + "state": state, "owner": owner, "percent": delta["percent"], + "ranges_overlap": delta["ranges_overlap"], + "llama_percent": None if llama is None else llama["percent"], + "arms": arms, "rejected": row["rejected"], + "change": described(row), "llama_change": llama_change(row)}) + return result + + +def lane_report(lane, directory, candidate, baseline, mode): + """One lane's job: what its evidence checks found, and how tonight's commit compares in + each cell. A lane without a finished job has a check that says so and no cells.""" + report = {**{field: lane[field] for field in ("id", "backend", "node", "model")}, + "job": None, "host": None, "cells": []} + if directory is None or not (directory / "plan.json").is_file(): + return {**report, "checks": ["its job was not planned, or its evidence was not uploaded"]} + plan = read_json(directory / "plan.json") + ledger = read_json(directory / "jobs.json") if (directory / "jobs.json").is_file() else [] + report["job"] = ledger[0] if ledger else None + measured = directory / f'{plan["jobs"][0]["label"]}-performance.json' + if not measured.is_file(): + return {**report, "checks": ["its job did not finish, so there is nothing to compare"]} + record = read_json(measured) + commits = {arm["label"]: arm["sha"] for arm in plan["arms"]} + checks = audit(plan, record, lane["node"]) + if (commits.get("candidate"), commits.get("baseline"), plan["models"]) != (candidate, baseline, [lane["model"]]): + checks.insert(0, "its plan is not tonight's commits and this lane's model") + host = record.get("host") or {} + return {**report, "host": host.get("gpu") or host.get("chip"), "checks": checks, "cells": cells(record, mode)} + + +def night(candidate, baseline, mode, lane_reports): + """The night's record: every lane, and the counts its verdict and its log are made from.""" + every = [found for lane in lane_reports for found in lane["cells"]] + + def having(state, owner=None): + return sum(1 for found in every if found["state"] == state and owner in (None, found["owner"])) + + totals = {"lanes": len(lane_reports), "unverified": sum(1 for lane in lane_reports if lane["checks"]), + "cells": len(every), "regressions": having("regressed", "skippy"), + "llama_regressions": having("regressed", "llama.cpp"), "improvements": having("improved"), + "uncertain": having("uncertain")} + return {"schema_version": 1, "candidate": candidate, "baseline": baseline, "mode": mode, + "lanes": lane_reports, "totals": totals} + + +def changed(report, state, headers, columns): + """A table of the cells in `state`, largest change first, or nothing when there are none.""" + pairs = sorted(((lane, found) for lane in report["lanes"] for found in lane["cells"] if found["state"] == state), + key=lambda pair: -abs(pair[1]["percent"])) + if not pairs: + return [] + return table(["Lane", "Host", "Model", "Point", "Metric", "Previous", "Tonight", *headers], + [[plain(lane["id"]), plain(lane["host"] or "unknown"), plain(found["model"]), plain(found["point"]), + TITLES[found["metric"]][0], + rounds_text(found["arms"]["baseline"], found["rejected"].get("baseline", 0)), + rounds_text(found["arms"]["candidate"], found["rejected"].get("candidate", 0)), + *(column(found) for column in columns)] for lane, found in pairs]) + + +def markdown(report): + """The night's log: what was compared, where Skippy regressed and improved, and whether each + lane's evidence held. It names no service outside this repository, since it is public.""" + totals, candidate = report["totals"], sha(report["candidate"]) + lines = ["# Nightly inference performance", ""] + if report["mode"] == "noise": + lines += [f"{candidate} against itself: an A/A run. Both arms are one commit, so what differs below is " + "the spread of two equal builds on each machine, not a change.", ""] + else: + lines += [f'{candidate} against {sha(report["baseline"])}, the commit the last successful nightly ' + "measured, each beside `llama-server` at its own llama.cpp pin.", "", + f'**{totals["regressions"]} regressions in Skippy**, {totals["llama_regressions"]} in llama.cpp, ' + f'{totals["improvements"]} improvements, and {totals["uncertain"]} past the tolerance with ' + f'overlapping rounds, across {totals["cells"]} cells on {totals["lanes"]} lanes.', "", + f"A cell is regressed or improved when its medians differ by more than {float(TOLERANCE):.0%} and " + "no round of one arm reaches the other's. A regression is llama.cpp's when the pin moved and " + "`llama-server` lost as much at that cell.", ""] + regressions = changed(report, "regressed", ["Change", "llama.cpp change", "Whose"], + [lambda found: found["change"], lambda found: found["llama_change"], + lambda found: "llama.cpp" if found["owner"] == "llama.cpp" else "Skippy"]) + if regressions: + lines += ["## Regressions", "", "Median (min–max, n) over the rounds.", "", *regressions, ""] + improvements = changed(report, "improved", ["Change"], [lambda found: found["change"]]) + if improvements: + lines += ["## Improvements", "", *improvements, ""] + if report["mode"] == "noise": + spread = changed(report, "noise", ["Difference"], [lambda found: f'{found["percent"]:+.2f}%']) + lines += ["## Spread of two equal builds", "", *(spread or ["No cell was measured by both arms."]), ""] + lines += ["## Evidence", "", "A lane's cells are like for like only when its checks held.", "", + *table(["Lane", "Node", "Model", "Job", "Checks"], + [[plain(lane["id"]), plain(lane["node"]), plain(lane["model"]), plain(lane["job"] or "none"), + plain("; ".join(lane["checks"])) if lane["checks"] else "held"] + for lane in report["lanes"]])] + return "\n".join(lines) + "\n" + + +def verdict(mode, results, totals=None): + """(passed, sentence) for the night, from each workflow job's result by name and the report's + counts. A night that measured nothing because main has not moved passes. A lane that did not + finish, evidence that did not hold, a regression in Skippy and a night left unrecorded each + fail it, so the baseline stays at the last commit that passed and was recorded.""" + if results.get("plan") != "success" or mode not in MODES: + return False, "The nightly plan did not succeed." + if mode == "unchanged": + return True, "main has not moved since the last successful nightly, so nothing was measured." + if results.get("measure") != "success": + return False, "A lane did not finish measuring." + if results.get("report") != "success" or totals is None: + return False, "The night's evidence was not checked and compared." + if totals["unverified"]: + return False, f'The evidence checks did not hold on {totals["unverified"]} lane(s).' + if totals["regressions"]: + return False, f'Skippy regressed at {totals["regressions"]} cell(s) since the last successful nightly.' + if results.get("record") != "success": + return False, "The night was measured but not recorded." + if mode == "noise": + return True, "The A/A run finished; the next nightly compares with this commit." + return True, "No regression in Skippy since the last successful nightly." diff --git a/scripts/lib/performance_plan.py b/scripts/lib/performance_plan.py index 0f7dda01..1c3e475c 100644 --- a/scripts/lib/performance_plan.py +++ b/scripts/lib/performance_plan.py @@ -3,11 +3,13 @@ import json import math import re +import shlex from pathlib import Path from .ci_artifacts import digest, read_json from .inference_inputs import fixture -from .inference_ladder import ladder_models +from .performance_backends import BACKENDS +from .performance_load import DATASETS, dataset, request_rate ROOT = Path(__file__).resolve().parents[2] SCENARIO = ROOT / "ci/inference-performance.json" @@ -15,11 +17,36 @@ LLAMA = "https://github.com/ggml-org/llama.cpp.git" SHA = re.compile(r"[0-9a-f]{40}") PULL_REQUEST = re.compile(r"pr:([1-9][0-9]{0,6})") +BRANCH = re.compile(r"branch:([A-Za-z0-9._/-]{1,200})") COMPONENT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}") NODE = re.compile(r"[A-Za-z0-9._-]{1,64}") -RESERVE_GIB = 16 MAX_ROUNDS = 9 +# What JY gives one job, before its grace period. +JOB_SECONDS = 18000 POINT_FIELDS = {"id", "concurrency", "depth", "input_tokens", "output_tokens", "requests"} +SERVER_FIELDS = {"id", "lanes", "pool_tokens", "points"} +# A conversation point's run is long enough to replay whole conversations, and ends well +# inside the time AIPerf is given. +DURATION_S = range(60, 3601) +SKIPPY_FLAG = re.compile(r"[a-z][a-z0-9]*(?:-[a-z0-9]+)*") +FLAG_VALUE = re.compile(r"[A-Za-z0-9._,:-]{1,64}") +# server_args sets these on every Skippy arm, so a variant's own flags cannot change them +HARNESS_FLAGS = {"startup-timeout-secs", "ctx-size", "n-gpu-layers", "bind-addr", "model-path", "model-id", + "generation-concurrency", "speculative-strategy", "kv-pool-tokens", "debug", "telemetry-level"} +# What a step is expected to take, in minutes, so the job's progress follows time rather than step count. +BUILD_MINUTES = {"skippy": 15, "llama-server": 5} +NOTE = re.compile(r"[A-Za-z0-9 ._:+-]{1,59}") +PROGRESS = ("progress() { printf '%s%% %s\\n' \"$1\" \"$2\" > \"$JIANYANG_PROGRESS_PATH\"; " + "echo \"PROGRESS ${JIANYANG_NODE:-?} $(date +%T) $1% $2\"; }") +# A step of at least TICK_MINUTES reports a tick a minute between its start and end, so a watcher sees +# a 15-minute build or a 12-minute replay move. A failed step names itself and exits, since the ERR trap +# would only see the function's return. +TICK_MINUTES = 2 +TICKED = ("ticked() { local start=$1 end=$2 minutes=$3 note=$4 ticker status=0; shift 4; " + "( for i in $(seq 1 \"$minutes\"); do sleep 60; " + "progress $(( start + (end - start) * i / (minutes + 1) )) \"$i min toward $note\"; done ) & ticker=$!; " + "\"$@\" || status=$?; kill \"$ticker\" 2>/dev/null || true; wait \"$ticker\" 2>/dev/null || true; " + "if [ \"$status\" -ne 0 ]; then echo \"inference performance stopped at: $*\" >&2; exit \"$status\"; fi; }") def count(value, name, minimum=1): @@ -28,38 +55,132 @@ def count(value, name, minimum=1): return value -def scenario(): +def skippy_flags(server): + """A variant server's own Skippy flags: names without the dashes, positive counts or short words.""" + flags = server["skippy_flags"] + if type(flags) is not dict or not flags: + raise ValueError(f'{server["id"]}: skippy_flags must name at least one flag') + for name, value in flags.items(): + if not SKIPPY_FLAG.fullmatch(name) or name in HARNESS_FLAGS: + raise ValueError(f'{server["id"]}: --{name} is not a flag a variant may set') + if not (type(value) is int and value >= 1 or type(value) is str and FLAG_VALUE.fullmatch(value)): + raise ValueError(f'{server["id"]}: --{name} needs a positive integer or a short word') + return flags + + +def rates(point): + """A point's per-backend arrivals per second, each a positive number for a backend in the table.""" + value = point["request_rate"] + if (type(value) is not dict or not value or not set(value) <= set(BACKENDS) + or not all(type(rate) in {int, float} and 0 < rate <= 100 for rate in value.values())): + raise ValueError(f'{point["id"]}: request_rate maps backends to positive arrivals per second') + return value + + +def lane_context(shape, server): + """A server's context per lane: its own, for conversations that outgrow the scenario's.""" + return server.get("context_per_lane", shape["context_per_lane"]) + + +def model_context(shape, server, trained): + """The lane a model is served with: the server's, cut to what the model was trained on. + Past that it has never seen a position, so it writes nonsense, and a mixture of experts + routes nonsense through other experts than real text would.""" + return min(lane_context(shape, server), trained) + + +def conversations_fit(key, trained, shape): + """Every conversation point in `shape` must hold its dataset's shortest conversation in the + context `key` serves a lane, or AIPerf would load the dataset and find nothing to replay.""" + for server in shape["servers"]: + context = model_context(shape, server, trained) + for point in server["points"]: + smallest = (dataset(point) or {}).get("smallest_tokens") + if smallest is not None and context < smallest: + raise ValueError(f'{key} serves {context} tokens a lane, fewer than the shortest ' + f'{point["dataset"]} conversation ({smallest}): leave {server["id"]} out') + + +def request_tokens(point): + """What one request of generated prompts holds at its longest: prefix, prompt and output.""" + return point["depth"] + point["input_tokens"] + point["output_tokens"] + + +def generated_point(point, context): + """A point of generated prompts: its request shape, which one lane must hold whole.""" + if set(point) - {"request_rate"} != POINT_FIELDS: + raise ValueError("invalid or duplicate performance point") + if "request_rate" in point: + rates(point) + for field in ("concurrency", "input_tokens", "output_tokens", "requests"): + count(point[field], f'{point["id"]} {field}') + count(point["depth"], f'{point["id"]} depth', 0) + if request_tokens(point) > context: + raise ValueError(f'{point["id"]}: one request exceeds a lane\'s context') + + +def conversation_point(point, context, pool): + """A point replaying a pinned dataset, with only the bound its dataset runs to. A + conversation grows toward a lane's context, so the pool must hold a full lane for each one + in flight: a failed request is then a fault on every arm, never a pool `llama-server` + could not fit.""" + entry = DATASETS.get(point["dataset"]) if type(point["dataset"]) is str else None + if entry is None or set(point) != {"id", "dataset", "concurrency", entry["bound"]}: + raise ValueError(f'{point["id"]}: a conversation point names one of {", ".join(DATASETS)} ' + "and the bound it runs to") + concurrency = count(point["concurrency"], f'{point["id"]} concurrency') + bound = count(point[entry["bound"]], f'{point["id"]} {entry["bound"]}') + if entry["bound"] == "duration_s" and bound not in DURATION_S: + raise ValueError(f'{point["id"]}: duration_s must be {DURATION_S.start} to {DURATION_S.stop - 1}') + if pool is not None and pool < concurrency * context: + raise ValueError(f'{point["id"]}: the pool must hold a full lane for every conversation in flight') + + +def scenario(named=None): + """The checked scenario; with `named`, only those servers and their points, to rerun one + workload without the rest. A server with its own `skippy_flags` is a variant of another, + and one that replays conversations takes minutes a point: both run only when named, so a + campaign keeps the same cells and about the same time.""" value = read_json(SCENARIO) if (set(value) != {"schema_version", "context_per_lane", "warmup_requests", "servers"} or value["schema_version"] != 1 or not value["servers"]): raise ValueError("invalid performance scenario") - context = count(value["context_per_lane"], "context_per_lane") + count(value["context_per_lane"], "context_per_lane") count(value["warmup_requests"], "warmup_requests", 0) - servers, points = set(), set() + servers, points, named_only = set(), set(), set() for server in value["servers"]: - if set(server) != {"id", "lanes", "pool_tokens", "points"} or not server["points"]: + if set(server) - {"skippy_flags", "context_per_lane"} != SERVER_FIELDS or not server["points"]: raise ValueError("invalid performance server") if not isinstance(server["id"], str) or not COMPONENT.fullmatch(server["id"]): raise ValueError("server id must be one safe path component") + if "skippy_flags" in server: + skippy_flags(server) + named_only.add(server["id"]) if server["id"].lower() in servers: raise ValueError(f'duplicate performance server: {server["id"]}') servers.add(server["id"].lower()) lanes = count(server["lanes"], f'{server["id"]} lanes') + context = count(lane_context(value, server), f'{server["id"]} context_per_lane') if server["pool_tokens"] is not None and count(server["pool_tokens"], "pool_tokens") < context: raise ValueError(f'{server["id"]}: a KV pool must hold at least one lane\'s context') for point in server["points"]: - if (set(point) != POINT_FIELDS or not isinstance(point["id"], str) + if (type(point) is not dict or not isinstance(point.get("id"), str) or not COMPONENT.fullmatch(point["id"]) or point["id"].lower() in points): raise ValueError("invalid or duplicate performance point") points.add(point["id"].lower()) - for field in ("concurrency", "input_tokens", "output_tokens", "requests"): - count(point[field], f'{point["id"]} {field}') - count(point["depth"], f'{point["id"]} depth', 0) + if "dataset" in point: + conversation_point(point, context, server["pool_tokens"]) + named_only.add(server["id"]) + else: + generated_point(point, context) if point["concurrency"] > lanes: raise ValueError(f'{point["id"]}: concurrency exceeds the server\'s lanes') - if point["depth"] + point["input_tokens"] + point["output_tokens"] > context: - raise ValueError(f'{point["id"]}: one request exceeds a lane\'s context') - return value + if named is None: + return {**value, "servers": [server for server in value["servers"] if server["id"] not in named_only]} + unknown = set(named) - {server["id"] for server in value["servers"]} + if not named or unknown: + raise ValueError(f"unknown performance servers: {', '.join(sorted(unknown)) or 'none named'}") + return {**value, "servers": [server for server in value["servers"] if server["id"] in named]} def pull_request_number(ref): @@ -68,6 +189,12 @@ def pull_request_number(ref): return int(match[1]) if match else None +def branch_name(ref): + """`branch:NAME` names the head of a branch of this repository, measured as off main.""" + match = BRANCH.fullmatch(ref) + return match[1] if match else None + + def pull_request_head(pull, repository): """The head of an open pull request from this repository: a fork's code never runs on the lab.""" if pull.get("state") != "open" or (pull.get("head", {}).get("repo") or {}).get("full_name") != repository: @@ -75,44 +202,135 @@ def pull_request_head(pull, repository): return pull["head"]["sha"] -def arms(candidate, baseline, reference): - """Candidate and baseline are Skippy commits; reference is llama.cpp's own server at its pin.""" - if not SHA.fullmatch(candidate) or not SHA.fullmatch(baseline): +def arms(candidate, baseline, reference, baseline_reference=None): + """Candidate and baseline are Skippy commits; reference is llama.cpp's own server at the candidate's + pin. A baseline on another pin adds llama.cpp at that pin as baseline-reference, so a change that + moves the pin shows whether llama.cpp moved as well as whether Skippy did. Without a baseline the + plan compares the candidate's servers with each other instead: see `comparison`.""" + commits = {"candidate": candidate} if baseline is None else {"candidate": candidate, "baseline": baseline} + if not all(SHA.fullmatch(sha) for sha in commits.values()): raise ValueError("arms must be immutable 40-digit commit SHAs") - result = [{"label": "candidate", "kind": "skippy", "sha": candidate, "path": "candidate"}, - {"label": "baseline", "kind": "skippy", "sha": baseline, "path": "baseline"}] - if reference is not None: - if not SHA.fullmatch(reference): - raise ValueError("the reference pin must be a 40-digit llama.cpp commit") - result.append({"label": "reference", "kind": "llama-server", "sha": reference, "path": "reference"}) + result = [{"label": label, "kind": "skippy", "sha": sha, "path": label} for label, sha in commits.items()] + pins = [("reference", reference)] + if baseline_reference not in (None, reference): + if reference is None or baseline is None: + raise ValueError("a baseline reference needs the baseline and reference arms") + pins.append(("baseline-reference", baseline_reference)) + for label, pin in pins: + if pin is None: + continue + if not SHA.fullmatch(pin): + raise ValueError(f"the {label} pin must be a 40-digit llama.cpp commit") + result.append({"label": label, "kind": "llama-server", "sha": pin, "path": label}) return result +def comparison(arm_list, servers): + """What a plan compares: the candidate with the baseline commit on every server, or, without a + baseline, the candidate's named servers with each other. Those must differ in their + `skippy_flags` and nothing else, so whatever changes between them is the flags'.""" + if any(arm["label"] == "baseline" for arm in arm_list): + return "commits" + shape = scenario(servers) if servers else None + if shape is None or len(shape["servers"]) < 2: + raise ValueError("a plan without a baseline compares servers, so it must name at least two") + + def setup(server): + return (server["lanes"], server["pool_tokens"], lane_context(shape, server), + [{key: value for key, value in point.items() if key != "id"} for point in server["points"]]) + + first, *rest = shape["servers"] + # As the launcher passes them: 2048 and "2048" are one setting. + flags = [json.dumps({name: str(value) for name, value in server.get("skippy_flags", {}).items()}, + sort_keys=True) for server in shape["servers"]] + if any(setup(server) != setup(first) for server in rest) or len(set(flags)) != len(flags): + raise ValueError("servers compared with each other must differ in their skippy_flags and nothing else") + return "servers" + + def round_order(arm_list, index): """Each round starts one arm later, so no arm always runs first on a cold or hot machine.""" shift = index % len(arm_list) return arm_list[shift:] + arm_list[:shift] +def measure_minutes(server, backend): + """A server's start and its points' requests: about two seconds each when kept in flight, + and as long as their arrivals take at a point's own rate. A conversation point loads its + dataset for about two minutes, then runs its own time or about four seconds a turn.""" + def seconds(point): + entry = dataset(point) + if entry is not None: + return 120 + (point["duration_s"] if entry["bound"] == "duration_s" else point["requests"] * 4) + rate = request_rate(point, backend) + return point["requests"] * 2 if rate is None else point["requests"] / rate + 10 + return 0.5 + sum(seconds(point) for point in server["points"]) / 60 + + +def job_steps(arm_list, keys, rounds, servers, trace, backend): + """The job's commands in the order they run: each a `just` recipe and its arguments, what it + finishes, and the minutes it is expected to take.""" + steps = [(["inference-performance-toolcheck"], "tools checked", 0.2)] + steps += [(["inference-performance-build-arm", arm["label"]], f'{arm["label"]} built', + BUILD_MINUTES[arm["kind"]]) for arm in arm_list] + steps.append((["inference-performance-step", "start"], "measurement ready", 0.3)) + for key in keys: + steps.append((["inference-performance-step", "model", key], f"{key} admitted", 1)) + for index in range(rounds): + for arm in round_order(arm_list, index): + steps += [(["inference-performance-step", "measure", key, str(index + 1), arm["label"], + server["id"]], f'r{index + 1} {arm["label"]} {server["id"]}', + measure_minutes(server, backend)) for server in servers] + if trace: + steps += [(["inference-performance-step", "trace", key, server["id"]], f'trace {server["id"]}', + measure_minutes(server, backend) * 1.5) for server in servers] + steps.append((["inference-performance-step", "finish"], "evidence archived", 0.5)) + return steps + + +def job_command(steps): + """A shell script that runs `steps` from the harness checkout and reports progress after each: + the percent of the expected time spent, never falling, and 100 only once all have run; a long + step ticks once a minute on its way. A failure names the command that stopped it and still + archives what was measured.""" + total = sum(minutes for _, _, minutes in steps) + lines = ["set -euo pipefail", PROGRESS, TICKED, + "trap 'echo \"inference performance stopped at: $BASH_COMMAND\" >&2' ERR", + "trap 'status=$?; if [ \"$status\" -ne 0 ]; then just inference-performance-step finish " + ">/dev/null 2>&1 || true; fi' EXIT", + 'progress 0 "starting"', "cd harness"] + spent = 0 + for args, note, minutes in steps: + note = note[:59] + if not NOTE.fullmatch(note): + raise ValueError(f"progress note {note!r} needs letters, digits and . _ : + - only") + start = min(99, math.floor(spent / total * 100)) + spent += minutes + end = min(99, math.floor(spent / total * 100)) + run = shlex.join(["just", *args]) + if minutes >= TICK_MINUTES and end > start: + # the note leaves room for "NN min toward " within the 59 characters a note may take + run = f"ticked {start} {end} {math.floor(minutes)} {shlex.quote(note[:45])} {run}" + lines += [run, f'progress {end} "{note}"'] + lines.append('progress 100 "done"') + return "\n".join(lines) + "\n" + + def models(keys): - known = {model["id"] for model in ladder_models()} + # any pinned model, not only the CI ladder's, so a comparison can cover other families + known = set(read_json(ROOT / "ci/inference-artifacts.json")) if not keys or len(set(keys)) != len(keys) or not set(keys) <= known: - raise ValueError(f"models must be distinct ladder ids from: {', '.join(sorted(known))}") + raise ValueError(f"models must be distinct pinned models from: {', '.join(sorted(known))}") return keys -def memory_floor(keys): - largest = max(sum(file["size"] for file in fixture(key)["files"]) for key in keys) - return math.ceil(largest / 1024**3) + RESERVE_GIB - - def nodes(values): if len(set(values)) != len(values) or not all(NODE.fullmatch(value) for value in values): raise ValueError("nodes must be distinct JY node names") return values -def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False): +def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False, backend="metal", servers=None): """`trace` adds one diagnostic pass of the candidate with debug telemetry, kept out of the measurements: tracing costs time, so a traced arm is not a comparable one.""" count(rounds, "rounds") @@ -120,38 +338,72 @@ def job_spec(harness, arm_list, keys, rounds, node, label, *, trace=False): raise ValueError("trace must be true or false") if rounds > MAX_ROUNDS: raise ValueError(f"at most {MAX_ROUNDS} rounds fit the job's time budget") - shape = scenario() - target = {"executor": "lab", "num_nodes": 1, "selector": { - "os": {"family": "macos"}, "accelerator": {"backend": "metal"}, - "memory": {"system_gib": {"min": memory_floor(keys)}}}} + if backend not in BACKENDS: + raise ValueError(f"unknown backend {backend!r}; the table holds {', '.join(sorted(BACKENDS))}") + shape = scenario(servers) + compared = comparison(arm_list, servers) + entry = BACKENDS[backend] + for server in shape["servers"]: + for point in server["points"]: + request_rate(point, backend) + if entry["pin_required"] and node is None: + raise ValueError(f"a {backend} plan must name exactly one node: its GPUs differ between hosts") + for key in keys: + conversations_fit(key, fixture(key)["trained_context"], shape) + largest = max(sum(file["size"] for file in fixture(key)["files"]) for key in keys) + if entry["selector"]: + selector = {key: value for key, value in entry["selector"].items() if key != "memory"} + selector["memory"] = {entry["memory_key"]: {"min": math.ceil(largest / 1024**3) + entry["reserve_gib"]}, + **entry["selector"].get("memory", {})} + target = {"executor": "lab", "num_nodes": 1, "selector": selector} + else: + # An entry with no selector targets its pinned node bare: the selector's + # os and accelerator facts are exactly what some lab agents never report. + target = {"executor": "lab", "num_nodes": 1} if node is not None: target["nodes"] = [node] repos = [{"url": SKIPPY, "rev": harness, "path": "harness"}] + [ {"url": SKIPPY if arm["kind"] == "skippy" else LLAMA, "rev": arm["sha"], "path": arm["path"]} for arm in arm_list] - plan = {"harness": harness, "arms": arm_list, "models": keys, "rounds": rounds, "trace": trace} + plan = {"harness": harness, "backend": backend, "arms": arm_list, "models": keys, + "rounds": rounds, "trace": trace} + if servers is not None: + plan["servers"] = servers points = [point for server in shape["servers"] for point in server["points"]] + runs = rounds * len(arm_list) * len(keys) + # A replayed point's requests are the dataset's; the scenario names it at its pin. + request_trace = {"kind": "file" if any(dataset(point) for point in points) else "synthetic", + "ref": f"ci/inference-performance.json@{harness}", "sha256": digest(SCENARIO)} + bounds = {"request_count": sum(point.get("requests", 0) for point in points) * runs, + "duration_s": sum(point.get("duration_s", 0) for point in points) * runs} + # Timed points run for their whole duration, so they alone show a campaign the job cannot finish. + timed = bounds["duration_s"] + (sum(point.get("duration_s", 0) for point in points) * len(keys) if trace else 0) + if timed > JOB_SECONDS: + raise ValueError(f"the timed points alone run {timed} s, past the job's {JOB_SECONDS} s: " + "run fewer rounds, arms, models or timed servers") return { "name": f"skippy-inference-performance-{label}", - "description": "Same-host Metal comparison of " + ", ".join( - f'{arm["label"]} {arm["sha"][:12]}' for arm in arm_list) + f" on {', '.join(keys)}.", + "description": entry["description"] + " of " + ", ".join( + f'{arm["label"]} {arm["sha"][:12]}' for arm in arm_list) + + (f" across {', '.join(servers)}" if compared == "servers" else "") + f" on {', '.join(keys)}.", "priority": 50, "target": target, "runtime": { "model_package": {"ref": "skippy://inference-performance/" + "+".join(keys), "sha256": fixture(keys[0])["files"][0]["sha256"], "egress": "lab_only"}, - "workspace": {"repos": repos, "build": "cd harness && just inference-performance-build", - "retain": "on_failure"}, - "env": {"SKIPPY_PERFORMANCE_PLAN": json.dumps(plan, separators=(",", ":"))}, - "command": "cd harness && just inference-performance-execute", + # The arms build in the command rather than the workspace build, so + # the job's progress covers its longest steps. + "workspace": {"repos": repos, "retain": "on_failure"}, + "env": {"SKIPPY_PERFORMANCE_PLAN": json.dumps(plan, separators=(",", ":")), + **entry["env"]}, + "command": job_command(job_steps(arm_list, keys, rounds, shape["servers"], trace, backend)), }, "harness": { - "name": "custom", "version": "aiperf-0.13.0", - "trace": {"kind": "synthetic", "ref": f"ci/inference-performance.json@{harness}", - "sha256": digest(SCENARIO)}, + "name": "custom", "version": "aiperf-0.13.0", "trace": request_trace, "seed": 42, "warmup_requests": shape["warmup_requests"], "concurrency": sorted({point["concurrency"] for point in points}), - "request_count": sum(point["requests"] for point in points) * rounds * len(arm_list) * len(keys), + # JY needs at least one; a bound no point uses stays out rather than reading zero. + **{name: value for name, value in bounds.items() if value}, }, - "budget": {"max_usd": 0, "max_duration_s": 18000, "grace_s": 300}, + "budget": {"max_usd": 0, "max_duration_s": JOB_SECONDS, "grace_s": 300}, } diff --git a/scripts/lib/performance_record.py b/scripts/lib/performance_record.py new file mode 100644 index 00000000..b1f22076 --- /dev/null +++ b/scripts/lib/performance_record.py @@ -0,0 +1,382 @@ +"""Record a performance job and a night's verdict in an MLflow experiment, and read them back. + +The view the runs make: every arm's run carries `params.machine_type` and `params.model`, the tag +`arm.role`, and `view.current` on the newest run of its machine type, model and role. Headline +metrics are named `/`, the same on every kind of run, so one chart compares them. + +`tracking` is the experiment, as nine calls. `find(key)` returns the `Run` whose `eval.key` tag is +`key`, or None; `get(run_id)` a `Run`; `search(params, tags, without=None)` the `Run`s with those +parameters and tags and none of the tags in `without`. `create(name, tags)` returns a new run's id. +`log(run_id, metrics=(), params=None, tags=None)` takes metrics as (key, value, time in ms, step); +`finish(run_id)` ends a run; `attach(run_id, path)` stores a file or a directory under its name; +`artifact_sha256(run_id, name)` hashes a stored file; `link(run_id)` is the run's address. The +script that owns the MLflow client supplies it; tests supply one in memory. +""" + +import hashlib +import json +import math +import statistics +import time +from collections import defaultdict +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path + +from .performance_load import METRICS +from .performance_report import HEADLINE + +PROGRAM = "inference-baselines" +HOST_FIELDS = ("node", "backend", "gpu", "chip", "os", "os_version", "macos", "kernel", "driver_version", + "toolkit_version", "metal_working_set_bytes") +STANDINGS = {"verified": "verified", "unaudited": "completed, awaiting audit", "diagnostic": "diagnostic"} +# The roles whose newest run is the view's current one, and those that gain a point on a trend. +CURRENT = ("main", "reference", "branch") +TRENDED = ("main", "reference") +ON_MAIN = (True, "true", "True") +# MLflow keeps a run's description as a tag, and a tag holds a few thousand characters at most. +NOTE_LIMIT = 4500 + + +@dataclass(frozen=True) +class Run: + """A recorded run as the recorder reads it back.""" + run_id: str + status: str + tags: dict + params: dict + metrics: dict + + +def sha256(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def short(sha): + return (sha or "")[:12] + + +def numeric(value): + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def epoch_ms(text): + try: + return int(datetime.fromisoformat(str(text).replace("Z", "+00:00")).timestamp() * 1000) + except ValueError: + return None + + +def machine_type(row): + backend = row.get("backend") or ("metal" if row.get("chip") else "unknown") + return f'{backend}:{row.get("gpu") or row.get("chip") or "unknown"}' + + +# Set on a run once its read-back has passed: only such a run counts as recorded. +READ_BACK = "eval.read_back" + + +def start_run(tracking, key, name, description, tags, parent=None): + """A new run's id, or None when `key` is already recorded and read back. A run left unfinished, + or finished but never read back, by an earlier attempt stops the recording: it is inspected, + never written over.""" + found = tracking.find(key) + if found is not None: + if found.status == "FINISHED" and found.tags.get(READ_BACK) == "passed": + return None + state = "finished, but its read-back never passed" if found.status == "FINISHED" else found.status + raise RuntimeError(f"{name} exists as {found.run_id} ({state}); inspect it before recording again") + every = {"eval.key": key, "eval.program": PROGRAM, "mlflow.note.content": description, **tags} + if parent: + every["mlflow.parentRunId"] = parent + return tracking.create(name, every) + + +def read_back(tracking, run_id, artifact, expected): + """The run as the server holds it must be finished, with the metrics just written and, for + `artifact`, the same bytes.""" + run = tracking.get(run_id) + wrong = [key for key, value in expected.items() if run.metrics.get(key) != value] + if run.status != "FINISHED" or wrong: + raise RuntimeError(f"read-back of {run_id} failed: status {run.status}, metrics differing: {wrong[:5]}") + if artifact is not None and tracking.artifact_sha256(run_id, Path(artifact).name) != sha256(artifact): + raise RuntimeError(f"artifact {Path(artifact).name} on {run_id} differs from the local copy") + tracking.log(run_id, tags={READ_BACK: "passed"}) + + +def role_of(rows, candidate, line): + """An arm's role in the view, from its first row. + + The candidate is the tracked line, `main`, when it is on main or the job measured the named + `line`; otherwise it is a `branch`. `reference` is llama.cpp at the candidate's pin. Another + Skippy arm at the candidate's commit is its A/A copy, `noise`. Beside a candidate that is the + tracked line, the other commit is the `baseline` it is compared with and llama.cpp at that + commit's pin is `baseline-reference`: neither is ever current or on a trend, so two commits + of one line never share a role. Beside a branch, the arm on main is `main`, as it always was.""" + first = rows[0] + if first["kind"] == "llama-server": + return "baseline-reference" if first["arm"] == "baseline-reference" else "reference" + tracked = bool(line) or candidate.get("on_main") in ON_MAIN + if first["arm"] == "candidate": + return "main" if tracked else "branch" + if first["sha"] == candidate["sha"]: + return "noise" + if tracked: + return "baseline" + return "main" if first.get("on_main") in ON_MAIN else "branch" + + +def role_label(role, rows, line): + first, tracked = rows[0], f'Skippy {line or "main"}' + if role == "branch": + return f'Skippy PR #{first.get("pull_request") or "?"}' + if role == "baseline": + own = first.get("branch") or ("main" if first.get("on_main") in ON_MAIN + else f'PR #{first.get("pull_request") or "?"}') + return f"Skippy {own} (baseline)" + return {"reference": "llama-server", "baseline-reference": "llama-server (baseline pin)", "main": tracked, + "noise": f"{tracked} (A/A copy)"}[role] + + +def cell_metrics(rows, now): + """Every measured field per round under detail/, as (key, value, time, step), and each cell's + median, minimum and maximum.""" + per_round, series = [], defaultdict(list) + for row in rows: + for field in METRICS: + if numeric(row.get(field)): + key = f'detail/{row["server"]}/{row["point"]}/{field}' + series[key].append(row[field]) + per_round.append((key, float(row[field]), now, int(row["round"]))) + medians = {} + for key, values in series.items(): + medians[f"{key}/median"] = float(statistics.median(values)) + medians[f"{key}/min"] = float(min(values)) + medians[f"{key}/max"] = float(max(values)) + return per_round, medians + + +def headline(medians, yardstick=None): + """The view's metrics, named / so a chart view puts each field in its own section + and every kind of run lands in the same chart. With `yardstick`, llama-server's medians in the + same job, a Skippy arm also carries its median as a ratio of llama-server's.""" + result = {} + for key, value in medians.items(): + parts = key.split("/") + if len(parts) != 5 or parts[4] != "median" or parts[3] not in HEADLINE: + continue + result[f"{parts[3]}/{parts[2]}"] = value + reference = (yardstick or {}).get(key) + if reference: + result[f"{parts[3]}_vs_llama/{parts[2]}"] = value / reference + return result + + +def promote(tracking, run_id, machine, model, role, when_ms, pull_request=""): + """Mark this run the current one of its machine type, model and role, unless a newer one already is.""" + params = {"machine_type": machine, "model": model} + if role == "branch": + params["pull_request"] = pull_request + others = [run for run in tracking.search(params, {"arm.role": role, "view.current": "true"}) + if run.run_id != run_id] + newer = [run for run in others if int(run.tags.get("view.when_ms", "0")) > when_ms] + tracking.log(run_id, tags={"view.when_ms": str(when_ms), "view.current": "false" if newer else "true"}) + for run in [] if newer else others: + tracking.log(run.run_id, tags={"view.current": "false"}) + + +def append_trend(tracking, machine, model, role, label, job_id, sha, when_ms, values): + """One long-lived run per machine type, model and role, gaining a point per job at its commit's time.""" + key = f"trend:{machine}:{model}:{role}" + found = tracking.find(key) + if found is not None and f"trend.job.{job_id}" in found.tags: + return + if found is None: + run_id = tracking.create(f"trend · {label} · {model} · {machine}", { + "eval.key": key, "eval.program": PROGRAM, "eval.phase": "trend", "arm.role": role, "view.trend": "true", + "mlflow.note.content": f"{label} for {model} on {machine}: one point per recorded job, placed at the " + "time of the Skippy commit it measured. Plot a metric against time to see " + "progress."}) + tracking.log(run_id, params={"machine_type": machine, "model": model}) + else: + run_id = found.run_id + tracking.log(run_id, metrics=[(name, float(value), when_ms, when_ms // 1000) for name, value in values.items()], + tags={f"trend.job.{job_id}": sha}) + tracking.finish(run_id) + + +def link_ceiling(tracking, machine, model): + """Each current run's throughput as a fraction of the current ceiling for its machine type and model.""" + params, current = {"machine_type": machine, "model": model}, {"view.current": "true"} + ceilings = tracking.search(params, {**current, "arm.role": "ceiling"}) + if not ceilings: + return + ceiling, now = ceilings[0].metrics, int(time.time() * 1000) + for run in tracking.search(params, current, without={"arm.role": "ceiling"}): + tracking.log(run.run_id, metrics=[ + (key.replace("output_tok_s/", "output_tok_s_of_ceiling/"), run.metrics[key] / value, now, 0) + for key, value in ceiling.items() + if key.startswith("output_tok_s/") and value and run.metrics.get(key)]) + + +def recorded(tracking, job_id, arms): + """The runs an earlier recording of this job made, by the keys it gave them.""" + found = {arm: tracking.find(f"job:{job_id}:{arm}") for arm in arms} + return {"job": tracking.find(f"job:{job_id}").run_id, + "arms": {arm: run.run_id for arm, run in found.items() if run is not None}} + + +def record_job(tracking, evidence, label, job_id, standing, line=None, extra=None): + """One job's rows as a job run, a top-level run per arm and each arm's per-round detail beneath it; + returns their ids as {"job": id, "arms": {arm: id}}. `label` names the job's files in `evidence`, + and `extra` is tags for every run. A job already recorded is left as it is. + + A diagnostic job reruns part of the scenario to look inside it: it is recorded but stays out of + the view's current and trend runs, which a partial job would otherwise replace.""" + evidence, extra = Path(evidence), extra or {} + rows_file = evidence / f"{label}-rows.jsonl" + rows = [json.loads(text) for text in rows_file.read_text(encoding="utf-8").splitlines() if text.strip()] + if not rows: + raise ValueError(f"{rows_file} has no rows") + first = rows[0] + by_arm = defaultdict(list) + for row in rows: + by_arm[row["arm"]].append(row) + models = sorted({row["model"] for row in rows}) + node = first.get("node") or "unknown" + device = first.get("gpu") or first.get("chip") or "unknown" + state, diagnostic = STANDINGS[standing], standing == "diagnostic" + phase = "diagnostic" if diagnostic else "campaign" + parent = start_run( + tracking, f"job:{job_id}", f'{", ".join(models)} · {device} · {node} · {job_id}', + f'JY job {job_id}: Skippy against llama.cpp\'s llama-server on {device} ({node}), models {", ".join(models)}. ' + "Each arm is a top-level run tagged eval.job_run with this run's id; metrics are per server/point, logged " + "per round, with median, min and max. " + "Skippy arms also carry their median as a ratio of llama-server's in the same job and cell (vs_llama).", + {"eval.phase": phase, "eval.execution_state": "completed", "eval.verification_state": state, + "jy.job_id": job_id, "hardware.node": node, "hardware.device": device, **extra}) + if parent is None: + return recorded(tracking, job_id, by_arm) + now = int(time.time() * 1000) + machine = machine_type(first) + tracking.log(parent, params={ + **{f"host.{field}": str(first[field]) for field in HOST_FIELDS if first.get(field) is not None}, + "harness": first["harness"], "scenario_sha256": first["scenario_sha256"], "models": ",".join(models), + "machine_type": machine, + "model_revisions": ",".join(sorted({f'{row["model"]}@{row["model_revision"]}' for row in rows}))}) + for name in (f"{label}-performance.json", rows_file.name, "plan.json", "summary.md", f"{job_id}-job.json", + f"{label}-aiperf.tar.gz", f"{label}-logs"): + if (evidence / name).exists(): + tracking.attach(parent, evidence / name) + + model = models[0] if len(models) == 1 else None + viewed = model is not None and not diagnostic + candidate = by_arm.get("candidate", rows)[0] + if line and candidate.get("branch") and candidate["branch"] != line: + raise ValueError(f'the tracked line is {line} but the candidate was measured from branch {candidate["branch"]}') + line = line or candidate.get("branch") + when_ms = epoch_ms(candidate.get("committed_at")) or epoch_ms(first.get("started_at")) or now + computed = {arm: cell_metrics(arm_rows, now) for arm, arm_rows in by_arm.items()} + arms = {} + for arm, arm_rows in sorted(by_arm.items()): + per_round, medians = computed[arm] + head = arm_rows[0] + if diagnostic and head["kind"] == "skippy": + role, title = "diagnostic", f'Skippy {head.get("branch") or short(head["sha"])}' + else: + role = role_of(arm_rows, candidate, line) + title = role_label(role, arm_rows, line) + # The baseline arm is measured against llama.cpp at its own pin when the job ran it, whatever its role: + # it is `main` beside a pull request, and a pull request's pin must not move main's trend. + beside = "baseline-reference" if arm == "baseline" and "baseline-reference" in computed else "reference" + view = headline(medians, computed.get(beside, (None, {}))[1] if head["kind"] == "skippy" else None) + child = start_run( + tracking, f"job:{job_id}:{arm}", f'{title} · {", ".join(models)} · {short(head["sha"])}', + f'Arm {arm} of JY job {job_id}: {head["kind"]} at {head["sha"]}, on {device} ({node}). ' + "Headline metrics are / medians; detail/ holds every field per round.", + {"eval.phase": phase, "eval.execution_state": "completed", "eval.verification_state": state, + "jy.job_id": job_id, "hardware.node": node, "hardware.device": device, "arm.kind": head["kind"], + "arm.label": arm, "arm.role": role, "eval.job_run": parent, **extra}) + if child is None: + arms[arm] = tracking.find(f"job:{job_id}:{arm}").run_id + continue + arms[arm] = child + params = {"sha": head["sha"], "kind": head["kind"], "binary_sha256": head.get("binary_sha256") or "", + "on_main": str(head.get("on_main")), "pull_request": str(head.get("pull_request") or ""), + "machine_type": machine, "model": ",".join(models), "skippy_line": line or "main"} + tracking.log(child, metrics=[(key, value, now, 0) for key, value in view.items()], params=params) + # Per-round detail sits one level down, so the chart view of the headline runs is not hundreds of charts. + detail = start_run(tracking, f"job:{job_id}:{arm}:detail", f'detail · {title} · {short(head["sha"])}', + f"Every measured field of arm {arm} in JY job {job_id}, per round (step), with median, " + "minimum and maximum.", {"eval.phase": phase, "jy.job_id": job_id, "arm.label": arm}, + child) + if detail is not None: + tracking.log(detail, metrics=per_round + [(key, value, now, 0) for key, value in medians.items()], + params=params) + tracking.finish(detail) + read_back(tracking, detail, None, dict(list(medians.items())[:20])) + tracking.finish(child) + read_back(tracking, child, None, dict(list(view.items())[:20])) + if viewed and role in CURRENT: + promote(tracking, child, machine, model, role, when_ms, params["pull_request"]) + if viewed and role in TRENDED: + append_trend(tracking, machine, model, role, title, job_id, head["sha"], when_ms, view) + if viewed: + link_ceiling(tracking, machine, model) + tracking.finish(parent) + read_back(tracking, parent, rows_file, {}) + return {"job": parent, "arms": arms} + + +def night_metrics(report, now): + """The night's counts, and each compared cell as `vs_previous///`: tonight's + commit as a ratio of the baseline that reads above 1 when Skippy is better, so latencies are + inverted. On a noise night the two arms are one commit and the same ratio is `spread/...`.""" + family = "spread" if report["mode"] == "noise" else "vs_previous" + metrics = [(name, float(value), now, 0) for name, value in report["totals"].items()] + for lane in report["lanes"]: + for found in lane["cells"]: + baseline, candidate = found["arms"]["baseline"]["median"], found["arms"]["candidate"]["median"] + ratio = candidate / baseline if HEADLINE[found["metric"]] == "higher" else baseline / candidate + metrics.append((f'{family}/{lane["id"]}/{found["metric"]}/{found["point"]}', ratio, now, 0)) + return metrics + + +def night_note(log, links): + """The night's description: its log, then its recorded jobs. A log longer than a description + can hold is cut at a line, and says the whole of it is attached.""" + tail = "\n## Recorded jobs\n\n" + "\n".join(links) + "\n" if links else "" + if len(log) + len(tail) <= NOTE_LIMIT: + return log + tail + cut = "\nThe rest of this log is in the attached nightly.md.\n" + head = log[:max(0, NOTE_LIMIT - len(tail) - len(cut))] + return head[:head.rfind("\n") + 1] + cut + tail + + +def record_night(tracking, report, log, files, run, jobs): + """The night's verdict as a run of its own: its counts and cells as metrics, its log as the + description, and the record and the whole log attached. `run` is the workflow run's url, id + and attempt; `jobs` maps a lane to its job run, which the description links.""" + totals, noise = report["totals"], report["mode"] == "noise" + outcome = "noise" if noise else "regressed" if totals["regressions"] else "clean" + against = "itself" if noise else short(report["baseline"]) + note = night_note(log, [f"- {lane}: {tracking.link(run_id)}" for lane, run_id in sorted(jobs.items())]) + night = start_run( + tracking, f'nightly:{run["id"]}:{run["attempt"]}', f'nightly · Skippy main {short(report["candidate"])} ' + f"against {against}", note, + {"eval.phase": "nightly", "eval.execution_state": "completed", + "eval.verification_state": "requires review" if totals["unverified"] else "verified", + "eval.trigger": "nightly", "nightly.outcome": outcome, "nightly.candidate": report["candidate"], + "nightly.baseline": report["baseline"], "ci.run": run["url"]}) + if night is None: + return tracking.find(f'nightly:{run["id"]}:{run["attempt"]}').run_id + now = int(time.time() * 1000) + metrics = night_metrics(report, now) + tracking.log(night, metrics=metrics, params={ + "candidate": report["candidate"], "baseline": report["baseline"], "mode": report["mode"], + "lanes": ",".join(lane["id"] for lane in report["lanes"])}) + for path in files: + tracking.attach(night, path) + tracking.finish(night) + read_back(tracking, night, files[0], {name: value for name, value, _, _ in metrics[:20]}) + return night diff --git a/scripts/lib/performance_report.py b/scripts/lib/performance_report.py index 06781b20..a3f2fc05 100644 --- a/scripts/lib/performance_report.py +++ b/scripts/lib/performance_report.py @@ -8,18 +8,29 @@ from .inference_charts import health_charts from .inference_markdown import HEALTH_LABELS, health_sections, plain, table from .inference_nightly_metrics import metric_value +from .performance_load import request_rate +from .performance_plan import model_context # Higher is better for rates; lower is better for latencies. HEADLINE = {"output_tok_s": "higher", "ttft_ms_p50": "lower", "itl_ms_p50": "lower"} +ARM_TITLES = {"baseline": "Baseline", "candidate": "Candidate", "reference": "Reference", + "baseline-reference": "Baseline reference"} def summarize(samples): - """Group by (model, server, point, metric), then by arm: median, min, max and n over rounds.""" - groups, settings = {}, {} + """Group by (model, server, point, metric), then by arm: median, min, max and n over rounds. + + `rejected` counts, by arm, the rounds in which the arm's server rejected the point, and + `settings_match` says whether the candidate and baseline ran it with the same settings. + """ + groups, rejected, settings = {}, {}, {} for sample in samples: key = sample["model"], sample["server"], sample["point"] settings.setdefault(key, {}).setdefault(sample["arm"], set()).add(json.dumps({ "applied": sample.get("applied", {}), "unsupported": sorted(sample.get("unsupported", []))}, sort_keys=True)) + if sample.get("rejected") is not None: + rounds = rejected.setdefault(key, {}) + rounds[sample["arm"]] = rounds.get(sample["arm"], 0) + 1 for metric, value in sample["metrics"].items(): if value is None: continue @@ -32,8 +43,11 @@ def summarize(samples): by_settings = settings[(model, server, point)] candidate, baseline = (by_settings.get(arm, set()) for arm in ("candidate", "baseline")) matched = not candidate or not baseline or (len(candidate) == len(baseline) == 1 and candidate == baseline) - rows.append({"settings_match": matched, "model": model, "server": server, "point": point, "metric": metric, "arms": arms, - "candidate_vs_baseline": change(arms.get("candidate"), arms.get("baseline")) if matched else None}) + rows.append({"settings_match": matched, "model": model, "server": server, "point": point, "metric": metric, + "arms": arms, "rejected": rejected.get((model, server, point), {}), + "candidate_vs_baseline": change(arms.get("candidate"), arms.get("baseline")) if matched else None, + "reference_vs_baseline_reference": change(arms.get("reference"), + arms.get("baseline-reference"))}) return rows @@ -45,22 +59,54 @@ def change(candidate, baseline): "ranges_overlap": overlap} -def cell(stats): +def cell(stats, rejected): + """An arm's rounds at one point: what they measured, and how many of them its server rejected.""" if not stats: - return "—" - return f'{stats["median"]:.1f} ({stats["min"]:.1f}–{stats["max"]:.1f}, n={stats["n"]})' + return f"rejected (n={rejected})" if rejected else "—" + measured = f'{stats["median"]:.1f} ({stats["min"]:.1f}–{stats["max"]:.1f}, n={stats["n"]})' + return f"{measured}; rejected n={rejected}" if rejected else measured + + +def against_control(rows, shape, servers): + """In a comparison of servers, each server's candidate against the first server named, at the point + in the same place: the servers differ only in their flags, so a change between them is the flags'.""" + places = {server["id"]: [point["id"] for point in server["points"]] for server in shape["servers"]} + control = servers[0] + candidate = {(row["model"], row["server"], row["point"], row["metric"]): row["arms"].get("candidate") + for row in rows} + for row in rows: + twin = places[control][places[row["server"]].index(row["point"])] + row["control"] = {"server": control, + "stats": candidate.get((row["model"], control, twin, row["metric"]))} + row["candidate_vs_control"] = (None if row["server"] == control + else change(row["arms"].get("candidate"), row["control"]["stats"])) + return rows + + +def described(metric, delta, measured, previous): + result = classify(metric, measured["median"], previous["median"]) + overlap = "; round ranges overlap" if delta["ranges_overlap"] else "; round ranges do not overlap" + return f'{delta["percent"]:+.2f}% · {HEALTH_LABELS[result]}{overlap}' def verdict(row): if not row.get("settings_match", True): return "Different settings — no matched-settings verdict" - delta = row["candidate_vs_baseline"] - if delta is None: - return "New series" arms = row["arms"] - result = classify(row["metric"], arms["candidate"]["median"], arms["baseline"]["median"]) - overlap = "; round ranges overlap" if delta["ranges_overlap"] else "; round ranges do not overlap" - return f'{delta["percent"]:+.2f}% · {HEALTH_LABELS[result]}{overlap}' + if "control" in row: + if row["server"] == row["control"]["server"]: + return "Control" + delta = row["candidate_vs_control"] + return "New series" if delta is None else described(row["metric"], delta, arms["candidate"], + row["control"]["stats"]) + delta = row["candidate_vs_baseline"] + return "New series" if delta is None else described(row["metric"], delta, arms["candidate"], arms["baseline"]) + + +def llama_change(row): + """llama.cpp at the candidate's pin against the baseline's: moving with Skippy means llama.cpp moved.""" + delta, arms = row["reference_vs_baseline_reference"], row["arms"] + return "—" if delta is None else described(row["metric"], delta, arms["reference"], arms["baseline-reference"]) def report_view(host, rows, record): @@ -74,16 +120,20 @@ def report_view(host, rows, record): key = row["model"], row["server"], row["point"] configuration = configurations.setdefault(key, { "id": "/".join(key), "label": " · ".join(key), "group": host, - "workload": f'Controlled Metal · {host} · {row["server"]} · {row["point"]}', + "workload": f'Controlled {((record.get("host") or {}).get("backend") or "metal")} · {host}' + f' · {row["server"]} · {row["point"]}', "outcome": "passed", "metrics": [], }) arms = row["arms"] + compared = [(title, arms[label]["median"]) for label, title in ARM_TITLES.items() if label in arms] metric = {"metric": row["metric"], "workload": configuration["workload"], - "measured": arms["candidate"]["median"], - "comparison_arms": [(label.title(), arms[label]["median"]) - for label in ("baseline", "candidate", "reference") if label in arms]} + "measured": arms["candidate"]["median"], "comparison_arms": compared} if "baseline" in arms: metric["reference"] = {"value": arms["baseline"]["median"]} + elif row.get("candidate_vs_control"): + metric["reference"] = {"value": row["control"]["stats"]["median"]} + # A chart draws these arms in place of its reference, so the server measured against is one. + compared.insert(0, (f'{row["control"]["server"]} (control)', row["control"]["stats"]["median"])) configuration["metrics"].append(metric) run = {"id": "controlled", "source_sha": candidate["sha"], "started_at": record["started_at"], "profile": "controlled performance", "measurement_kind": "controlled", "outcome": "passed", @@ -96,29 +146,44 @@ def markdown(title, host, rows, record): lines = ["# " + plain(title), "", "Host: " + plain(host), "", *health_sections(view, health_charts(view), chart_format="mermaid"), "", "## Round ranges", "", "Median (min–max, n). Reference is the optional llama.cpp arm. " - "Its measurements are shown separately from the candidate/baseline verdict.", ""] + "Its measurements are shown separately from the candidate/baseline verdict. " + "Rejected is the number of rounds in which its server failed requests at a point " + "that needs more KV than its pool holds.", ""] if any(not row.get("settings_match", True) for row in rows): - lines.extend(["Candidate and baseline applied different settings in some cells. " - "Both measurements are retained below; those cells are excluded from matched-settings verdict counts.", ""]) + lines.extend(["Candidate and baseline applied different settings in some cells. Both measurements are " + "retained below; those cells are excluded from matched-settings verdict counts.", ""]) + pinned = any("baseline-reference" in row["arms"] for row in rows) + control = next((row["control"]["server"] for row in rows if "control" in row), None) + if control is not None: + lines += [f"Servers are compared with {plain(control)}, the first named: each differs from it only " + "in its Skippy flags, so Change is the flags' effect on the candidate.", ""] + if pinned: + lines += ["The candidate moves the llama.cpp pin, so Baseline reference is llama.cpp at the " + "baseline's pin, and llama.cpp change compares the two references: a change in both " + "columns is llama.cpp's, a change in Change alone is Skippy's.", ""] + shown = [label for label in ARM_TITLES if pinned or label != "baseline-reference"] detail = [] for row in rows: if row["metric"] in HEADLINE: arms = row["arms"] detail.append([plain(row[field]) for field in ("model", "server", "point", "metric")] + - [cell(arms.get(arm)) for arm in ("baseline", "candidate", "reference")] + [verdict(row)]) - lines.extend(table(["Model", "Server", "Point", "Metric", "Baseline", "Candidate", "Reference", "Change"], detail)) + [cell(arms.get(arm), row["rejected"].get(arm, 0)) for arm in shown] + [verdict(row)] + + ([llama_change(row)] if pinned else [])) + lines.extend(table(["Model", "Server", "Point", "Metric", *(ARM_TITLES[arm] for arm in shown), "Change", + *(["llama.cpp change"] if pinned else [])], detail)) return "\n".join(lines) + "\n" -def rows(record, shape, committed_at, job, pull_requests): +def rows(record, shape, committed_at, job, pull_requests, branches=None): """One flat row per measured sample, for a table that graphs runs over time. The diagnostic pass is left out. Every row carries what it was measured on and with, so rows from many runs can share one table: `committed_at` orders arms by commit, `started_at` orders runs by when they ran. An arm that `pull_requests` maps to a pull - request has `on_main` false, so a graph of main's history can leave it out; llama.cpp's - server has it null. What an arm applied or lacked differs by arm, so it is kept as JSON - text and every row has the same columns. + request, or `branches` to a branch, has `on_main` false, so a graph of main's history can + leave it out; llama.cpp's server has it null. What an arm applied or lacked differs by arm, + so it is kept as JSON text and every row has the same columns. A point the server rejected + keeps its row: its metrics are null and `rejected` holds what was rejected, as JSON text. """ arms = {arm["label"]: arm for arm in record["arms"]} points = {(server["id"], point["id"]): (server, point) @@ -127,21 +192,30 @@ def rows(record, shape, committed_at, job, pull_requests): for sample in record["samples"]: arm = arms[sample["arm"]] pull_request = pull_requests.get(sample["arm"]) + branch = (branches or {}).get(sample["arm"]) server, point = points[(sample["server"], sample["point"])] yield { - "schema_version": 1, "job": job, "started_at": record.get("started_at"), + "schema_version": 3, "job": job, "started_at": record.get("started_at"), "harness": record["harness"], "scenario_sha256": record["scenario_sha256"], - "chip": host["chip"], "macos": host.get("macos"), "node": host.get("node"), + "backend": host.get("backend"), "gpu": host.get("gpu"), "chip": host.get("chip"), + "macos": host.get("macos"), "os": host.get("os"), "os_version": host.get("os_version"), + "kernel": host.get("kernel"), "driver_version": host.get("driver_version"), + "toolkit_version": host.get("toolkit_version"), "node": host.get("node"), "metal_working_set_bytes": host.get("metal_working_set_bytes"), "arm": sample["arm"], "kind": arm["kind"], "sha": arm["sha"], "committed_at": committed_at.get(arm["sha"]), "binary_sha256": arm["binary_sha256"], - "on_main": None if arm["kind"] != "skippy" else pull_request is None, - "pull_request": pull_request, + "on_main": None if arm["kind"] != "skippy" else pull_request is None and branch is None, + "pull_request": pull_request, "branch": branch, "model": sample["model"], "model_revision": record["models"][sample["model"]]["revision"], "server": sample["server"], "lanes": server["lanes"], "pool_tokens": server["pool_tokens"], - "point": sample["point"], "concurrency": point["concurrency"], "depth": point["depth"], - "input_tokens": point["input_tokens"], "output_tokens": point["output_tokens"], - "requests": point["requests"], "round": sample["round"], + "context_per_lane": model_context(shape, server, record["models"][sample["model"]]["trained_context"]), + "point": sample["point"], "concurrency": point["concurrency"], "dataset": point.get("dataset"), + "depth": point.get("depth"), "input_tokens": point.get("input_tokens"), + "output_tokens": point.get("output_tokens"), "requests": point.get("requests"), + "duration_s": point.get("duration_s"), "request_rate": request_rate(point, host.get("backend")), + "round": sample["round"], "applied": json.dumps(sample["applied"], sort_keys=True), - "unsupported": json.dumps(sample["unsupported"]), **sample["metrics"], + "unsupported": json.dumps(sample["unsupported"]), + "rejected": None if sample["rejected"] is None else json.dumps(sample["rejected"], sort_keys=True), + **sample["metrics"], } diff --git a/scripts/tests/automation_contracts.py b/scripts/tests/automation_contracts.py index 517f649e..93082918 100644 --- a/scripts/tests/automation_contracts.py +++ b/scripts/tests/automation_contracts.py @@ -11,9 +11,9 @@ import unittest from pathlib import Path from types import SimpleNamespace -from unittest.mock import patch +from unittest.mock import Mock, patch -from lib import ci_artifacts, ci_smoke +from lib import ci_artifacts, ci_process, ci_smoke from lib.ci_process import command from lib.ci_targets import validate_native_identity from lib.graph_contracts import MANIFEST @@ -573,5 +573,25 @@ def test_layout_signature_binds_workspace_and_cargo_home(self): "layout digest must cover both the cargo home and the workspace") +class ProcessGroups(unittest.TestCase): + """Darwin's killpg answers EPERM for an exiting group and for a recycled pgid.""" + + def alive(self, ps, exited): + child = Mock(pid=4242) + child.poll.return_value = 0 if exited else None + with patch.object(ci_process.os, "killpg", side_effect=PermissionError), \ + patch.object(ci_process.subprocess, "check_output", return_value=ps): + return ci_process.group_alive(child) + + def test_a_group_exiting_after_the_poll_is_not_alive(self): + self.assertFalse(self.alive(f"4242 {os.getuid()} Z\n", exited=False)) + + def test_a_recycled_pgid_is_not_our_group(self): + self.assertFalse(self.alive(f"4242 {os.getuid() + 1} S\n", exited=True)) + + def test_a_running_process_of_ours_keeps_the_group_alive(self): + self.assertTrue(self.alive(f" 99 {os.getuid()} S\n4242 {os.getuid()} R+\n", exited=False)) + + if __name__ == "__main__": unittest.main() diff --git a/scripts/tests/ci_process_contracts.py b/scripts/tests/ci_process_contracts.py index 78fc0346..238e09ae 100644 --- a/scripts/tests/ci_process_contracts.py +++ b/scripts/tests/ci_process_contracts.py @@ -8,7 +8,7 @@ from tempfile import TemporaryDirectory from unittest.mock import MagicMock, Mock, patch -from lib.ci_process import command, command_logs, force_stop, group_alive +from lib.ci_process import command, command_logs, force_stop, graceful_stop, group_alive class CommandCleanupContract(unittest.TestCase): @@ -65,7 +65,7 @@ def test_successful_build_drains_a_detached_descendant(self): @unittest.skipIf(os.name == "nt", "Unix process-group behavior") class ProcessGroupContract(unittest.TestCase): def test_exit_during_permission_probe_allows_an_empty_or_zombie_group(self): - for rows in ("", "1234 Z\n"): + for rows in ("", f"1234 {os.getuid()} Z\n"): with self.subTest(rows=rows): child = Mock(pid=1234) child.poll.side_effect = [None, 0] @@ -77,17 +77,33 @@ def test_exit_during_permission_probe_keeps_live_descendants_visible(self): child = Mock(pid=1234) child.poll.side_effect = [None, 0] with patch("lib.ci_process.os.killpg", side_effect=PermissionError), \ - patch("lib.ci_process.subprocess.check_output", return_value="1234 S\n"): + patch("lib.ci_process.subprocess.check_output", return_value=f"1234 {os.getuid()} S\n"): self.assertTrue(group_alive(child)) - def test_permission_error_for_a_live_child_is_not_suppressed(self): + def test_permission_error_for_a_running_child_reads_whose_the_group_is(self): + # Darwin answers EPERM for a group whose members are exiting, before poll() sees the exit. child = Mock(pid=1234) child.poll.return_value = None - with patch("lib.ci_process.os.killpg", side_effect=PermissionError), \ - patch("lib.ci_process.subprocess.check_output") as inspect: - with self.assertRaises(PermissionError): - group_alive(child) - inspect.assert_not_called() + for rows, alive in ((f"1234 {os.getuid()} R\n", True), (f"1234 {os.getuid() + 1} S\n", False)): + with self.subTest(rows=rows), patch("lib.ci_process.os.killpg", side_effect=PermissionError), \ + patch("lib.ci_process.subprocess.check_output", return_value=rows): + self.assertEqual(group_alive(child), alive) + + def test_a_refused_stop_signal_is_an_error_only_while_a_process_of_ours_can_run(self): + # The leader has exited, so killpg answers EPERM; what is left in the group decides. + for stopper in (graceful_stop, force_stop): + for state in ("S", "Z"): + child = Mock(pid=1234) + with self.subTest(stopper=stopper.__name__, state=state), \ + patch("lib.ci_process.os.killpg", side_effect=PermissionError), \ + patch("lib.ci_process.subprocess.check_output", return_value=f"1234 {os.getuid()} {state}\n"): + if state == "S": + with self.assertRaises(PermissionError): + stopper(child) + else: + stopper(child) + if stopper is force_stop: + child.wait.assert_called_once_with(timeout=10) if __name__ == "__main__": diff --git a/scripts/tests/inference_performance_contracts.py b/scripts/tests/inference_performance_contracts.py index 719dacbf..ee3487f3 100644 --- a/scripts/tests/inference_performance_contracts.py +++ b/scripts/tests/inference_performance_contracts.py @@ -1,14 +1,20 @@ """Offline checks for the performance comparison's plan, servers, parsing and report.""" import json +import re +import struct import unittest from pathlib import Path from runpy import run_path +from tempfile import TemporaryDirectory from unittest.mock import Mock, patch -from lib import performance_plan -from lib.performance_arms import REQUIRED, capabilities, server_args -from lib.performance_load import measurements +from lib import performance_arms, performance_backends, performance_plan +from lib.gguf_header import trained_context +from lib.inference_checks import memory_figures +from lib.performance_arms import REQUIRED, capabilities, may_reject, server_args +from lib.performance_load import (DATASETS, conversation_args, measurements, profile_args, rejection, + request_rate, run_point) from lib import performance_report from lib.performance_report import markdown, summarize @@ -34,6 +40,216 @@ def test_scenario_rejects_impossible_servers(self): with self.assertRaises(ValueError): performance_plan.scenario() + def test_named_servers_keep_only_their_points(self): + first = performance_plan.scenario()["servers"][0] + shape = performance_plan.scenario([first["id"]]) + self.assertEqual(shape["servers"], [first]) + for names in ([], ["no-such-server"]): + with self.assertRaises(ValueError): + performance_plan.scenario(names) + + def test_a_variant_server_runs_only_when_named(self): + variant = "lanes4-pool32k-prefill2048" + self.assertNotIn(variant, [server["id"] for server in performance_plan.scenario()["servers"]]) + named = performance_plan.scenario(["lanes4-pool32k", variant])["servers"] + self.assertEqual([server["id"] for server in named], ["lanes4-pool32k", variant]) + + def test_a_rate_point_names_a_positive_rate_per_backend_and_runs_on_its_own_schedule(self): + rated = "lanes4-pool32k-rate" + point = performance_plan.scenario([rated])["servers"][0]["points"][0] + args = profile_args("http://e", point, "m@r", "/t", 2, Path("/a"), request_rate(point, "metal")) + self.assertEqual(args[args.index("--request-rate") + 1], str(point["request_rate"]["metal"])) + self.assertEqual(args[args.index("--arrival-pattern") + 1], "poisson") + self.assertNotIn("--request-rate", profile_args("http://e", point, "m@r", "/t", 2, Path("/a"))) + shape = performance_plan.read_json(performance_plan.SCENARIO) + index = next(index for index, server in enumerate(shape["servers"]) if server["id"] == rated) + for rate in ({}, {"metal": 0}, {"metal": "fast"}, {"space-heater": 1}, 0.2): + broken = json.loads(json.dumps(shape)) + broken["servers"][index]["points"][0]["request_rate"] = rate + with patch.object(performance_plan, "read_json", return_value=broken): + with self.assertRaises(ValueError): + performance_plan.scenario([rated]) + + def test_a_variant_cannot_set_what_the_harness_sets_or_nothing(self): + shape = performance_plan.read_json(performance_plan.SCENARIO) + for flags in ({}, {"debug": 1}, {"kv-pool-tokens": 4096}, {"Prefill Chunk": 1}, + {"prefill-chunk-size": 0}, {"prefill-chunk-size": "two words"}, []): + broken = json.loads(json.dumps(shape)) + broken["servers"][0]["skippy_flags"] = flags + with patch.object(performance_plan, "read_json", return_value=broken): + with self.assertRaises(ValueError): + performance_plan.scenario() + + +CONVERSATIONS = {"id": "lanes4-conversations", "lanes": 4, "pool_tokens": None, "context_per_lane": 16384, + "points": [{"id": "test-c1-agentx", "dataset": "agentx", "concurrency": 1, "duration_s": 600}, + {"id": "test-c4-sharegpt", "dataset": "sharegpt", "concurrency": 4, "requests": 32}]} + + +def with_server(server): + """The shipped scenario plus `server`, as `read_json` would return it.""" + shape = performance_plan.read_json(performance_plan.SCENARIO) + shape["servers"].append(json.loads(json.dumps(server))) + return shape + + +def gguf(path, *pairs): + """A GGUF v3 header of (key, type, value) pairs and no tensors; arrays are (item type, values).""" + def string(text): + data = text.encode() + return struct.pack("= performance_plan.TICK_MINUTES), (int(report.split()[1]), True)) + self.assertLess(start, end) + self.assertTrue(steps[1].startswith("ticked ")) + measured = [step[step.index("just "):].split()[5] for step in steps if " measure " in step] + per_round = len(measured) // 3 + # every arm leads one round + self.assertEqual([measured[index * per_round] for index in range(3)], + ["candidate", "baseline", "reference"]) + + def test_a_cuda_plan_targets_a_dgx_spark(self): + arm_list = performance_plan.arms(self.candidate, self.baseline, self.pin) + spec = performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, "spark-000137", "sp", + backend="cuda") + selector = spec["target"]["selector"] + self.assertEqual(selector["os"], {"family": "linux"}) + self.assertEqual(selector["arch"], {"in": ["aarch64"]}) + self.assertEqual(selector["accelerator"], {"backend": "cuda", "model": {"in": ["NVIDIA GB10"]}}) + self.assertIs(selector["memory"]["unified"], True) + self.assertGreaterEqual(selector["memory"]["system_gib"]["min"], 18) + self.assertEqual(spec["target"]["nodes"], ["spark-000137"]) + self.assertIn("Same-host CUDA comparison", spec["description"]) + self.assertEqual(json.loads(spec["runtime"]["env"]["SKIPPY_PERFORMANCE_PLAN"])["backend"], "cuda") + + def test_a_rate_point_is_refused_on_a_backend_it_has_no_rate_for(self): + arm_list = performance_plan.arms(self.candidate, self.baseline, self.pin) + with self.assertRaisesRegex(ValueError, "no request rate for the rocm backend"): + performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, "rocm-1", "r", backend="rocm", + servers=["lanes4-pool32k-rate"]) + + def test_an_unknown_backend_is_refused_at_plan_time(self): + arm_list = performance_plan.arms(self.candidate, self.baseline, self.pin) + with self.assertRaisesRegex(ValueError, "unknown backend"): + performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, None, "any", + backend="space-heater") + + def test_a_cuda_x86_plan_targets_one_pinned_discrete_gpu(self): + arm_list = performance_plan.arms(self.candidate, self.baseline, self.pin) + with self.assertRaisesRegex(ValueError, "must name exactly one node"): + performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, None, "any", + backend="cuda-x86") + spec = performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, "lab-a33338", "x", + backend="cuda-x86") + selector = spec["target"]["selector"] + self.assertEqual(selector["os"], {"family": "linux"}) + self.assertEqual(selector["arch"], {"in": ["x86_64"]}) + self.assertEqual(selector["accelerator"], {"backend": "cuda"}) + self.assertIs(selector["memory"]["unified"], False) + self.assertGreaterEqual(selector["memory"]["dedicated_vram_gib"]["min"], 9) + self.assertEqual(spec["target"]["nodes"], ["lab-a33338"]) + self.assertEqual(spec["runtime"]["env"].get("CUDA_VISIBLE_DEVICES"), "0") + + def test_a_rocm_plan_targets_one_pinned_unified_host(self): + arm_list = performance_plan.arms(self.candidate, self.baseline, self.pin) + with self.assertRaisesRegex(ValueError, "must name exactly one node"): + performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, None, "any", + backend="rocm") + spec = performance_plan.job_spec("d" * 40, arm_list, ["qwen35-4b"], 3, "lab-003827", "r", + backend="rocm") + self.assertNotIn("selector", spec["target"]) + self.assertEqual(spec["target"]["nodes"], ["lab-003827"]) + self.assertEqual(spec["runtime"]["env"].get("HIP_VISIBLE_DEVICES"), "0") + self.assertEqual(spec["runtime"]["env"].get("SKIPPY_AMDGPU_TARGETS"), "gfx1151") + self.assertTrue(spec["runtime"]["env"].get("PATH", "").startswith("/opt/rocm/bin")) + self.assertEqual(spec["runtime"]["env"].get("LD_LIBRARY_PATH"), "/opt/rocm/lib") + + def test_models_must_be_distinct_pinned_models(self): + self.assertEqual(performance_plan.models(["qwen35-4b", "perf-falcon-mamba-7b-q4"]), + ["qwen35-4b", "perf-falcon-mamba-7b-q4"]) with self.assertRaises(ValueError): performance_plan.models(["qwen35-4b", "qwen35-4b"]) with self.assertRaises(ValueError): @@ -172,6 +531,24 @@ def test_an_older_skippy_runs_without_settings_it_lacks_and_says_so(self): self.assertEqual(applied["generation_concurrency"], 4) self.assertEqual(missing, ["--speculative-strategy", "--kv-pool-tokens", "--debug"]) + def test_a_servers_log_gives_what_it_allocated_beyond_its_weights(self): + lines = ["llama_kv_cache: size = 1536.00 MiB ( 65536 cells, 24 layers, 2/1 seqs), K (f16): 768.00 MiB", + "llama_kv_cache: size = 256.00 MiB ( 4096 cells, 20 layers, 2/1 seqs), K (f16): 128.00 MiB", + "llama_memory_recurrent: size = 437.91 MiB ( 6 cells, 24 layers, 2 seqs 0 rs_seq)", + "sched_reserve: CUDA0 compute buffer size = 208.52 MiB", + "sched_reserve: CUDA_Host compute buffer size = 80.52 MiB", + "sched_reserve: CUDA0 compute buffer size = 190.00 MiB"] + with TemporaryDirectory() as directory: + log = Path(directory) / "server.log" + log.write_text("".join(json.dumps({"data": {"message": line + "\n"}, "type": "native_log"}) + "\n" + for line in lines), encoding="utf-8") + figures = memory_figures(log, ("CUDA",)) + mib = 1024 ** 2 + self.assertEqual(figures, {"kv_caches": [{"bytes": 1536 * mib, "cells": 65536}, + {"bytes": 256 * mib, "cells": 4096}], + "recurrent": [{"bytes": round(437.91 * mib), "cells": 6}], + "compute_bytes": round(208.52 * mib)}) + def test_measured_servers_run_at_debug_verbosity_for_offload_evidence(self): help_text = (" ".join(REQUIRED) + " --debug --generation-concurrency " " --speculative-strategy --kv-pool-tokens \n") @@ -190,6 +567,20 @@ def test_required_options_are_probed_before_any_measured_round(self): with self.assertRaisesRegex(ValueError, "unsupported"): server_args(self.skippy, help_text, "/m.gguf", "org/m@rev", 8192, self.server) + def test_a_variant_passes_its_flags_to_skippy_only_and_needs_them(self): + variant = dict(self.server, id="v", skippy_flags={"prefill-chunk-size": 2048, "microbatch-size": 2048}) + help_text = " ".join(REQUIRED) + " --prefill-chunk-size --microbatch-size \n" + args, applied, _ = server_args(self.skippy, help_text, "/m.gguf", "org/m@rev", 8192, variant) + self.assertEqual(args[args.index("--prefill-chunk-size") + 1], "2048") + self.assertEqual(args[args.index("--microbatch-size") + 1], "2048") + self.assertEqual(applied["microbatch_size"], 2048) + reference = {"label": "reference", "kind": "llama-server", "binary": "/b/llama-server"} + args, _, _ = server_args(reference, "", "/m.gguf", "org/m@rev", 8192, variant) + self.assertNotIn("--prefill-chunk-size", args) + with self.assertRaisesRegex(ValueError, "unsupported.*--microbatch-size"): + server_args(self.skippy, " ".join(REQUIRED) + " --prefill-chunk-size ", "/m.gguf", + "org/m@rev", 8192, variant) + def test_reference_optional_flags_are_probed_and_omissions_recorded(self): built = {"label": "reference", "kind": "llama-server", "binary": "/b/llama-server"} for help_text in ("", "-kvu", "--alias", "-kvu --alias"): @@ -206,6 +597,262 @@ def test_llama_server_gets_the_same_cells(self): _, applied, _ = server_args(built, "", "/m.gguf", "org/m@rev", 8192, unpooled) self.assertEqual(applied["total_context"], 4 * 8192) + def test_llama_server_starts_at_trace_verbosity_and_records_it(self): + built = {"label": "reference", "kind": "llama-server", "binary": "/b/llama-server"} + args, applied, _ = server_args(built, "", "/m.gguf", "org/m@rev", 8192, self.server) + self.assertEqual(args[args.index("-lv") + 1], "4") + self.assertEqual(applied["log_verbosity"], 4) + + def test_only_llama_server_may_reject_a_point_and_only_past_its_pool(self): + reference = {"label": "reference", "kind": "llama-server", "binary": "/b/llama-server"} + cells = [(server, point) for server in performance_plan.scenario()["servers"] + for point in server["points"]] + self.assertEqual([point["id"] for server, point in cells if may_reject(reference, server, point)], + ["c16-depth4096", "c4-depth4096-pool16k"]) + self.assertFalse(any(may_reject(self.skippy, server, point) for server, point in cells)) + + +class BackendTests(unittest.TestCase): + """The backend table drives every arm's build; one entry changes no other entry's commands.""" + skippy = {"label": "candidate", "kind": "skippy", "sha": "a" * 40, "path": "candidate"} + reference = {"label": "reference", "kind": "llama-server", "sha": "c" * 40, "path": "reference"} + + def build(self, arm, backend): + calls = [] + with TemporaryDirectory() as directory: + with patch("lib.performance_arms.checkout", return_value=Path(directory)), \ + patch("lib.performance_arms.command", + side_effect=lambda args, **kwargs: calls.append((args, kwargs)) or None), \ + patch("lib.performance_arms.toolkit_overrides", return_value={"CUDACXX": "/c/bin/nvcc"}), \ + patch("lib.performance_arms.digest", return_value="0" * 64): + built = performance_arms.build(arm, Path(directory) / "build.log", backend) + return calls, built + + def test_the_cuda_entry_builds_both_arms_for_a_gb10(self): + calls, _ = self.build(self.skippy, "cuda") + just, cargo = calls[0], calls[1] + self.assertEqual(just[0][:2], ["just", "llama-build"]) + self.assertEqual((just[1]["overrides"]["LLAMA_STAGE_BACKEND"], just[1]["overrides"]["LLAMA_STAGE_LINK_MODE"], + just[1]["overrides"]["LLAMA_STAGE_CUDA_ARCHITECTURES"]), ("cuda", "static", "121")) + self.assertEqual(cargo[0][:3], ["cargo", "build", "--locked"]) + self.assertEqual(cargo[1]["overrides"], just[1]["overrides"]) + calls, _ = self.build(self.reference, "cuda") + configure, make = calls[0], calls[1] + self.assertIn("-DGGML_CUDA=ON", configure[0]) + self.assertIn("-DCMAKE_CUDA_ARCHITECTURES=121", configure[0]) + self.assertNotIn("-DGGML_METAL=ON", configure[0]) + self.assertEqual(configure[1]["overrides"], {"CUDACXX": "/c/bin/nvcc"}) + self.assertEqual(make[1]["overrides"], {"CUDACXX": "/c/bin/nvcc"}) + + def test_the_metal_entry_builds_the_reference_without_a_toolkit_environment(self): + calls, _ = self.build(self.reference, "metal") + self.assertIn("-DGGML_METAL=ON", calls[0][0]) + self.assertNotIn("-DGGML_CUDA=ON", calls[0][0]) + self.assertIsNone(calls[0][1]["overrides"]) + + def test_the_cuda_x86_entry_builds_for_the_hosts_own_architecture(self): + calls = [] + with patch("lib.performance_backends.cuda_x86_architecture", return_value="89"): + with TemporaryDirectory() as directory: + with patch("lib.performance_arms.checkout", return_value=Path(directory)), \ + patch("lib.performance_arms.command", + side_effect=lambda args, **kwargs: calls.append((args, kwargs)) or None), \ + patch("lib.performance_arms.toolkit_overrides", + return_value={"CUDACXX": "/c/bin/nvcc"}), \ + patch("lib.performance_arms.digest", return_value="0" * 64): + built = performance_arms.build(self.skippy, Path(directory) / "b.log", "cuda-x86") + self.assertEqual(calls[0][1]["overrides"]["LLAMA_STAGE_CUDA_ARCHITECTURES"], "89") + self.assertEqual(built["gpu_architecture"], "89") + del calls[:] + built = performance_arms.build(self.reference, Path(directory) / "r.log", "cuda-x86") + self.assertIn("-DCMAKE_CUDA_ARCHITECTURES=89", calls[0][0]) + self.assertEqual(built["gpu_architecture"], "89") + + def test_cuda_x86_admission_takes_the_lesser_of_gpu0_free_vram_and_host_memory(self): + meminfo = "MemAvailable: 2097152 kB\n" + # what was free at the job's start is not what each model is admitted against + started = {"gpu_memory_free_bytes": 12 * 1024**3} + for free_mib, expected in (("10240", 2 * 1024**3), ("1024", 1 * 1024**3)): + with patch("lib.performance_backends.Path") as path, \ + patch("lib.performance_backends.capture", return_value=free_mib + "\n") as capture: + path.return_value.read_text.return_value = meminfo + self.assertEqual(performance_backends.cuda_x86_free(started), expected) + self.assertIn("--query-gpu=memory.free", capture.call_args[0][0]) + + def test_the_rocm_entry_builds_both_arms_for_the_pinned_gfx_target(self): + calls = [] + with TemporaryDirectory() as directory: + with patch("lib.performance_arms.checkout", return_value=Path(directory)), \ + patch("lib.performance_arms.command", + side_effect=lambda args, **kwargs: calls.append((args, kwargs)) or None), \ + patch("lib.performance_arms.digest", return_value="0" * 64): + built = performance_arms.build(self.skippy, Path(directory) / "b.log", "rocm") + self.assertEqual(calls[0][1]["overrides"]["LLAMA_STAGE_BACKEND"], "rocm") + self.assertEqual(calls[0][1]["overrides"]["LLAMA_STAGE_AMDGPU_TARGETS"], "gfx1151") + self.assertEqual(built["gpu_architecture"], "gfx1151") + del calls[:] + performance_arms.build(self.reference, Path(directory) / "r.log", "rocm") + self.assertIn("-DGGML_HIP=ON", calls[0][0]) + self.assertIn("-DAMDGPU_TARGETS=gfx1151", calls[0][0]) + self.assertNotIn("-DGGML_CUDA=ON", calls[0][0]) + + def test_rocm_admission_takes_the_lesser_of_memory_and_free_vram_plus_gtt(self): + gib = 1024**3 + # rocm-smi's CSV, read now rather than at the job's start: 80 GiB of VRAM and 60 of GTT are free + csv = ("device,VRAM Total Memory (B),VRAM Total Used Memory (B),GTT Total Memory (B)," + f"GTT Total Used Memory (B)\ncard0,{90 * gib},{10 * gib},{80 * gib},{20 * gib}\n") + started = {"vram_total_bytes": 90 * gib, "vram_used_bytes": 85 * gib, + "gtt_total_bytes": 80 * gib, "gtt_used_bytes": 75 * gib} + with patch("lib.performance_backends.capture", return_value=csv): + self.assertEqual(performance_backends.rocm_memory(), (90 * gib, 10 * gib, 80 * gib, 20 * gib, 1)) + for meminfo, expected in (("MemAvailable: 104857600 kB\n", 100 * gib), + ("MemAvailable: 209715200 kB\n", 140 * gib)): + with patch("lib.performance_backends.Path") as path: + path.return_value.read_text.return_value = meminfo + self.assertEqual(performance_backends.rocm_free(started), expected) + + def test_the_rocm_preflight_requires_the_memory_tool_the_job_reads(self): + with patch("lib.performance_backends.capture"), \ + patch("lib.performance_backends.shutil.which", side_effect=lambda tool: tool == "amd-smi"): + with self.assertRaisesRegex(ValueError, "rocm-smi"): + performance_backends.rocm_tool_check() + + def test_the_workflow_offers_every_backend_in_the_table_and_passes_it_to_admit(self): + workflow = (Path(__file__).resolve().parents[2] + / ".github/workflows/inference-performance.yml").read_text(encoding="utf-8") + offered = re.search(r"\n backend:\n(?: .*\n)*? options: \[([^\]]+)\]", workflow)[1] + self.assertEqual(sorted(name.strip() for name in offered.split(",")), sorted(performance_backends.BACKENDS)) + for line in ("BACKEND: ${{ inputs.backend }}", "SERVERS: ${{ inputs.servers }}"): + self.assertIn(line, workflow) + + +class RejectionTests(unittest.TestCase): + point = {"id": "c4-depth4096-pool16k", "concurrency": 4, "depth": 4096, "input_tokens": 512, + "output_tokens": 128, "requests": 4} + refused = {"code": 500, "type": "Internal Server Error", "message": "Context size has been exceeded."} + # what llama-server logs sending for each request its pool turns away + full = "Context size has been exceeded." + summary = {"request_count": {"avg": 4}, "request_error_rate": {"avg": 0}, "error_summary": [], + "is_complete": True, "output_token_throughput": {"avg": 120.5}} + + def write(self, directory, failed=(), served=0, cut_short=0): + """AIPerf's per-request export: two warmup requests, then the measured ones.""" + def request(phase, error, metrics): + return {"metadata": {"benchmark_phase": phase}, "error": error, "metrics": metrics} + + whole = {"output_sequence_length": {"value": 128, "unit": "tokens"}} + records = ([request("warmup", None, whole)] * 2 + + [request("profiling", error, {}) for error in failed] + + [request("profiling", None, whole)] * served + + [request("profiling", None, {"request_latency": {"value": 9.5, "unit": "ms"}})] * cut_short) + (Path(directory) / "profile_export.jsonl").write_text( + "".join(json.dumps(record) + "\n" for record in records), encoding="utf-8") + + def drive(self, directory, may_reject, sent=(), fails=False): + """run_point with AIPerf faked: the server logs sending `sent` while the point runs, and + AIPerf exits non-zero, with no summary export, when every measured request failed.""" + from subprocess import CalledProcessError + log = Path(directory) / "server.log" + # an earlier point's error, which is not this point's answer + log.write_text("0.01.000.000 E srv send_error: task id = 0, error: Loading model\n", encoding="utf-8") + + def load(*_, **__): + with log.open("a", encoding="utf-8") as stream: + stream.writelines(f"0.47.014.510 E srv send_error: task id = {task}, error: {text}\n" + for task, text in enumerate(sent, 1)) + if fails: + raise CalledProcessError(1, ["aiperf"]) + + with patch("lib.performance_load.command", side_effect=load): + return run_point("http://127.0.0.1:9337", self.point, "org/m@rev", "/t", 2, Path(directory), + may_reject=may_reject, server_log=log, context=8192) + + def test_rejection_counts_failed_and_cut_short_requests_among_the_measured_ones(self): + from tempfile import TemporaryDirectory + other = dict(self.refused, code=503) + with TemporaryDirectory() as directory: + self.write(directory, failed=[self.refused, other, self.refused], cut_short=1) + self.assertEqual(rejection(Path(directory), 4, [self.full] * 4), { + "requests": 4, "failed": 3, "cut_short": 1, + "errors": [{"error_details": self.refused, "count": 2}, {"error_details": other, "count": 1}]}) + # A load run that broke off before every request is not the server's answer. + self.assertIsNone(rejection(Path(directory), 5, [self.full] * 4)) + with TemporaryDirectory() as directory: + self.assertIsNone(rejection(Path(directory), 4, [])) + self.write(directory, served=4) + self.assertIsNone(rejection(Path(directory), 4, [])) + + def test_only_a_full_pool_counts_as_a_rejection_and_any_other_error_fails_the_point(self): + from tempfile import TemporaryDirectory + empty_stream = {"code": None, "type": "InvalidInferenceResultError", + "message": "Invalid inference result: No responses with actual content were received"} + unrelated = {"code": 503, "type": "Service Unavailable", "message": "Loading model"} + with TemporaryDirectory() as directory: + self.write(directory, failed=[self.refused, empty_stream], served=2) + self.assertEqual(rejection(Path(directory), 4, [self.full] * 2)["failed"], 2) + with TemporaryDirectory() as directory: + self.write(directory, failed=[self.refused, unrelated], served=2) + with self.assertRaisesRegex(ValueError, "1 of 4 requests failed with errors that are not a full KV pool"): + rejection(Path(directory), 4, [self.full] * 2) + + def test_every_request_failed_or_cut_short_needs_the_server_to_have_logged_a_full_pool(self): + from tempfile import TemporaryDirectory + # AIPerf keeps no reason for a stream the server ended part-way; the server's own log does. + with TemporaryDirectory() as directory: + self.write(directory, served=3, cut_short=1) + self.assertEqual(rejection(Path(directory), 4, [self.full])["cut_short"], 1) + with self.assertRaisesRegex(ValueError, "the server logged only 0 refusals"): + rejection(Path(directory), 4, []) + with self.assertRaisesRegex(ValueError, "the server sent errors that are not a full KV pool"): + rejection(Path(directory), 4, [self.full, "Invalid input batch."]) + + def test_a_point_the_server_may_reject_keeps_what_it_rejected_in_place_of_metrics(self): + from subprocess import CalledProcessError + from tempfile import TemporaryDirectory + with TemporaryDirectory() as directory: + self.write(directory, failed=[self.refused] * 4) + metrics, rejected = self.drive(directory, may_reject=True, sent=[self.full] * 4, fails=True) + self.assertEqual((metrics["output_tok_s"], set(metrics.values())), (None, {None})) + self.assertEqual((rejected["failed"], rejected["cut_short"]), (4, 0)) + with self.assertRaises(CalledProcessError): + self.drive(directory, may_reject=False, fails=True) + with TemporaryDirectory() as directory: + self.write(directory, failed=[self.refused], served=2, cut_short=1) + (Path(directory) / "profile_export_aiperf.json").write_text(json.dumps(self.summary)) + self.assertEqual(self.drive(directory, may_reject=True, sent=[self.full] * 2)[1]["cut_short"], 1) + + def test_a_point_the_server_served_is_measured_and_a_broken_load_run_still_fails(self): + from subprocess import CalledProcessError + from tempfile import TemporaryDirectory + with TemporaryDirectory() as directory: + self.write(directory, served=4) + (Path(directory) / "profile_export_aiperf.json").write_text(json.dumps(self.summary)) + metrics, rejected = self.drive(directory, may_reject=True) + self.assertEqual((metrics["output_tok_s"], rejected), (120.5, None)) + with self.assertRaises(CalledProcessError): + self.drive(directory, may_reject=True, fails=True) + + def test_a_rejected_point_is_a_sample_only_while_its_server_stays_up(self): + from tempfile import TemporaryDirectory + measure = run_path(str(Path(__file__).resolve().parents[1] / "inference-performance.py"))["measure"] + built = {"label": "reference", "kind": "llama-server", "binary": "/b/llama-server"} + server = {"id": "lanes4-pool16k", "lanes": 4, "pool_tokens": 16384, "points": [self.point]} + inputs = {"repo": "org/m", "revision": "rev", "tokenizer_path": "/t", "trained_context": 32768} + shape = {"context_per_lane": 8192, "warmup_requests": 2} + rejected = {"requests": 4, "failed": 4, "cut_short": 0, "errors": []} + process, load = Mock(), Mock(return_value=({"output_tok_s": None}, rejected)) + with TemporaryDirectory() as directory, patch.dict( + measure.__globals__, start=Mock(return_value=process), ready=Mock(), offload=Mock(), + stop=Mock(), run_point=load): + process.poll.return_value = None + sample, = measure(built, "", "/m.gguf", inputs, "m", 0, server, shape, Path(directory)) + self.assertEqual((sample["rejected"], sample["metrics"]), (rejected, {"output_tok_s": None})) + self.assertTrue(load.call_args.kwargs["may_reject"]) + self.assertEqual(load.call_args.kwargs["server_log"].suffix, ".log") + process.poll.return_value = 1 + with self.assertRaisesRegex(RuntimeError, "exited while it was rejecting"): + measure(built, "", "/m.gguf", inputs, "m", 0, server, shape, Path(directory)) + class ReportTests(unittest.TestCase): record = {"started_at": "2026-11-21T10:00:00Z", "arms": [{"label": "candidate", "sha": "a" * 40}]} @@ -226,7 +873,8 @@ def test_measurements_reject_failed_requests_and_keep_missing_metrics_null(self) def test_medians_spreads_and_verdicts(self): def sample(arm, value): - return {"model": "m", "server": "s", "point": "p", "arm": arm, "metrics": {"output_tok_s": value}} + return {"model": "m", "server": "s", "point": "p", "arm": arm, "metrics": {"output_tok_s": value}, + "rejected": None} rows = summarize([sample("baseline", v) for v in (100, 102, 98)] + [sample("candidate", v) for v in (120, 118, 121)]) @@ -236,11 +884,45 @@ def sample(arm, value): self.assertIn("+20.00% · Improved", markdown("t", "h", rows, self.record)) close = summarize([sample("baseline", v) for v in (100, 110)] + [sample("candidate", v) for v in (105, 108)]) self.assertIn("round ranges overlap", markdown("t", "h", close, self.record)) + self.assertNotIn("llama.cpp change", markdown("t", "h", rows, self.record)) + + def test_a_server_comparison_measures_each_server_against_the_first_named(self): + servers = ["lanes4-pool32k-prefill2048", "lanes4-pool32k"] + shape = performance_plan.scenario(servers) + points = {server["id"]: server["points"][0]["id"] for server in shape["servers"]} + rows = summarize([{"model": "m", "server": server, "point": points[server], "arm": "candidate", + "metrics": {"output_tok_s": value}, "rejected": None} + for server, values in ((servers[0], (100, 102, 98)), (servers[1], (120, 118, 121))) + for value in values]) + performance_report.against_control(rows, shape, servers) + control, other = sorted(rows, key=lambda row: row["server"] != servers[0]) + self.assertEqual(performance_report.verdict(control), "Control") + self.assertAlmostEqual(other["candidate_vs_control"]["percent"], 20.0) + report = markdown("t", "h", rows, self.record) + self.assertIn("+20.00% · Improved", report) + self.assertIn("compared with lanes4-pool32k-prefill2048, the first named", report) + # the variant's chart draws the control it is compared with beside it + self.assertIn('x-axis ["lanes4-pool32k-prefill2048 (control)", "Candidate"]', report) + + def test_a_moved_pin_says_whether_llama_cpp_moved_too(self): + def sample(arm, value): + return {"model": "m", "server": "s", "point": "p", "arm": arm, "metrics": {"output_tok_s": value}, + "rejected": None} + + rows = summarize([sample(arm, v) for arm, values in (("baseline", (100, 101, 99)), + ("candidate", (90, 91, 89)), + ("baseline-reference", (200, 201, 199)), + ("reference", (180, 181, 179))) + for v in values]) + self.assertAlmostEqual(rows[0]["reference_vs_baseline_reference"]["percent"], -10.0) + report = markdown("t", "h", rows, self.record) + self.assertIn("| Baseline reference | Change | llama.cpp change |", report) + self.assertIn("-10.00% · Regressed", performance_report.llama_change(rows[0])) def test_one_percent_rule_keeps_range_uncertainty_and_actual_p50_labels(self): def row(metric, candidate): return summarize([{"model": "m", "server": "s", "point": "p", "arm": arm, - "metrics": {metric: value}} + "metrics": {metric: value}, "rejected": None} for arm, values in (("baseline", (90, 100, 110)), ("candidate", (candidate - 10, candidate, candidate + 10))) for value in values])[0] @@ -263,7 +945,40 @@ def row(metric, candidate): self.assertIn('bar [100.00000000, 102.00000000, 70.00000000]', report) with self.assertRaises(ValueError): summarize([{"model": "m", "server": "s", "point": "p", "arm": "candidate", - "metrics": {"output_tok_s": float("nan")}}]) + "metrics": {"output_tok_s": float("nan")}, "rejected": None}]) + + def test_rejected_rounds_are_counted_beside_the_arms_that_measured_the_point(self): + rejected = {"requests": 16, "failed": 14, "cut_short": 2, "errors": []} + + def sample(arm, value, rejected=None): + return {"model": "m", "server": "s", "point": "p", "arm": arm, "metrics": {"output_tok_s": value}, + "rejected": rejected} + + rows = summarize([sample("baseline", v) for v in (100, 102, 98)] + + [sample("candidate", v) for v in (120, 118, 121)] + + [sample("reference", None, rejected)] * 3) + self.assertEqual((rows[0]["rejected"], sorted(rows[0]["arms"])), + ({"reference": 3}, ["baseline", "candidate"])) + self.assertIn("| rejected (n=3) |", markdown("t", "h", rows, self.record)) + self.assertEqual(performance_report.cell({"median": 70, "min": 68, "max": 72, "n": 2}, 1), + "70.0 (68.0–72.0, n=2); rejected n=1") + self.assertEqual(performance_report.cell(None, 0), "—") + + def test_collecting_keeps_the_runs_logs_and_aiperf_exports_with_the_evidence(self): + keep_logs = run_path(str(Path(__file__).resolve().parents[1] / "inference-performance.py"))["keep_logs"] + names = (("log", "job.log"), ("log", "build-candidate.log"), ("log", "m-r1-candidate-s.log"), + ("raw", "aiperf.tar.gz"), ("raw", "performance.json")) + pilot, fetched = Mock(), [] + pilot.api.return_value = {"artifacts": [{"key": f"p/j/r/{kind}/{name}"} for kind, name in names]} + with TemporaryDirectory() as directory: + def download(_pilot, _run, name, path): + fetched.append((name, str(path.relative_to(directory)))) + with patch.dict(keep_logs.__globals__, download=download): + keep_logs(pilot, "run_1", "spark", Path(directory)) + pilot.api.assert_called_once_with("GET", "/v1/artifacts/run_1") + self.assertEqual(fetched, [("build-candidate.log", "spark-logs/build-candidate.log"), + ("m-r1-candidate-s.log", "spark-logs/m-r1-candidate-s.log"), + ("aiperf.tar.gz", "spark-aiperf.tar.gz")]) def test_different_applied_settings_keep_measurements_without_health_verdict(self): samples = [{"model": "m", "server": "s", "point": "p", "arm": arm, @@ -286,22 +1001,49 @@ def test_stored_rows_carry_their_arm_point_and_host_but_not_the_trace_pass(self) point = server["points"][0] measured = {"model": "qwen35-4b", "round": 2, "arm": "baseline", "server": server["id"], "point": point["id"], "applied": {}, "unsupported": [], - "metrics": {"output_tok_s": 99.5, "ttft_ms_p50": None}} + "metrics": {"output_tok_s": 99.5, "ttft_ms_p50": None}, "rejected": None} record = {"harness": "d" * 40, "scenario_sha256": "e" * 64, "started_at": "2026-11-21T10:00:00+00:00", "host": {"chip": "Apple M1 Ultra", "node": "n1"}, "arms": [{"label": "baseline", "kind": "skippy", "sha": "b" * 40, "binary_sha256": "f" * 64}, {"label": "candidate", "kind": "skippy", "sha": "a" * 40, "binary_sha256": "f" * 64}], - "models": {"qwen35-4b": {"revision": "r1"}}, "samples": [measured, {**measured, "arm": "candidate"}], + "models": {"qwen35-4b": {"revision": "r1", "trained_context": 262144}}, + "samples": [measured, {**measured, "arm": "candidate"}], "diagnostic": {"samples": [{**measured, "round": None}]}} row, pulled = performance_report.rows(record, shape, {"b" * 40: "2026-11-20T10:16:30Z"}, "job_1", {"candidate": 130, "baseline": None}) + branched, _ = performance_report.rows(record, shape, {}, "job_1", {"candidate": None, "baseline": None}, + {"baseline": "team/gen-ai", "candidate": None}) + self.assertEqual((branched["on_main"], branched["branch"], branched["pull_request"]), + (False, "team/gen-ai", None)) self.assertEqual((row["sha"], row["committed_at"], row["round"]), ("b" * 40, "2026-11-20T10:16:30Z", 2)) - self.assertEqual((row["on_main"], row["pull_request"]), (True, None)) + self.assertEqual((row["on_main"], row["pull_request"], row["branch"]), (True, None, None)) self.assertEqual((pulled["sha"], pulled["on_main"], pulled["pull_request"]), ("a" * 40, False, 130)) self.assertEqual((row["lanes"], row["concurrency"], row["depth"]), (server["lanes"], point["concurrency"], point["depth"])) self.assertEqual((row["output_tok_s"], row["ttft_ms_p50"], row["chip"]), (99.5, None, "Apple M1 Ultra")) + self.assertIsNone(row["rejected"]) json.dumps(row) + rejected = {"requests": 8, "failed": 8, "cut_short": 0, "errors": []} + record["samples"] = [{**measured, "metrics": {"output_tok_s": None}, "rejected": rejected}] + stored, = performance_report.rows(record, shape, {}, "job_1", {}) + self.assertEqual((stored["output_tok_s"], json.loads(stored["rejected"])), (None, rejected)) + self.assertEqual((stored["dataset"], stored["duration_s"], stored["context_per_lane"]), + (None, None, shape["context_per_lane"])) + + def test_a_conversation_row_names_its_dataset_and_has_no_generated_shape(self): + shape = {**performance_plan.scenario(), "servers": [CONVERSATIONS]} + sample = {"model": "qwen35-4b", "round": 1, "arm": "candidate", "server": CONVERSATIONS["id"], + "point": "test-c1-agentx", "applied": {}, "unsupported": [], "metrics": {"output_tok_s": 40.0}, + "rejected": None} + record = {"harness": "d" * 40, "scenario_sha256": "e" * 64, "host": {"backend": "metal"}, + "arms": [{"label": "candidate", "kind": "skippy", "sha": "a" * 40, "binary_sha256": "f" * 64}], + "models": {"qwen35-4b": {"revision": "r1", "trained_context": 12000}}, "samples": [sample]} + row, = performance_report.rows(record, shape, {}, "job_1", {}) + # served at the 12,000 tokens the model was trained on, not the server's 16,384 + self.assertEqual((row["schema_version"], row["dataset"], row["duration_s"], row["context_per_lane"]), + (3, "agentx", 600, 12000)) + self.assertEqual((row["depth"], row["input_tokens"], row["requests"], row["request_rate"]), + (None, None, None, None)) if __name__ == "__main__": diff --git a/scripts/tests/inference_performance_nightly.py b/scripts/tests/inference_performance_nightly.py new file mode 100644 index 00000000..b84e423e --- /dev/null +++ b/scripts/tests/inference_performance_nightly.py @@ -0,0 +1,697 @@ +"""Offline checks for the nightly performance comparison's lanes, baseline, evidence, regressions, verdict +and recording.""" + +import io +import json +import os +import unittest +from pathlib import Path +from runpy import run_path +from tempfile import TemporaryDirectory +from unittest.mock import patch + +from lib import performance_nightly, performance_plan, performance_report +from lib.performance_arms import may_reject +from lib.performance_audit import audit +from lib.performance_nightly import (cells, compared, evidence, lane_report, lanes, markdown, matrix, night, + previous, verdict) +from lib.performance_record import NOTE_LIMIT, Run, night_note, record_job, record_night, sha256 + +SCRIPT = str(Path(__file__).resolve().parents[1] / "inference-performance-nightly.py") +RECORDER = str(Path(__file__).resolve().parents[1] / "inference-performance-record.py") +MACHINE = "metal:Apple M3 Ultra" +CANDIDATE, BASELINE, PIN = "a" * 40, "b" * 40, "c" * 40 +LANE = {"id": "metal-studio", "backend": "metal", "node": "n1", "model": "qwen35-4b", "servers": None, + "trace": False, "rounds": 3} + + +def shipped(): + return performance_plan.read_json(performance_nightly.NIGHTLY) + + +def admitted(servers=None, trace=False, baseline_reference=None, baseline=BASELINE): + """A plan as `admit` writes it, for one model on the node n1.""" + return {"arms": performance_plan.arms(CANDIDATE, baseline, PIN, baseline_reference), "models": ["qwen35-4b"], + "rounds": 3, "trace": trace, "servers": servers, "jobs": [{"label": "n1"}]} + + +def measured(plan, rate=None): + """A record in which every arm measured every point each round, as its plan admitted: `rate` + gives an arm's output tokens a second, and llama-server rejects what its pool cannot hold.""" + shape = performance_plan.scenario(plan.get("servers")) + points = [(server, point) for server in shape["servers"] for point in server["points"]] + samples = [] + for index in range(plan["rounds"]): + for arm in plan["arms"]: + for server, point in points: + rejected = ({"requests": point["requests"], "failed": point["requests"], "cut_short": 0, "errors": []} + if may_reject(arm, server, point) else None) + metrics = {"output_tok_s": (rate or {}).get(arm["label"], 100.0) + index, "ttft_ms_p50": 50.0 + index, + "itl_ms_p50": 10.0 + index, "output_tokens_mean": point["output_tokens"]} + samples.append({"model": plan["models"][0], "round": index + 1, "arm": arm["label"], + "server": server["id"], "point": point["id"], "applied": {}, "unsupported": [], + "metrics": dict.fromkeys(metrics) if rejected else metrics, "rejected": rejected}) + record = {"harness": "d" * 40, "scenario_sha256": "e" * 64, "started_at": "2026-11-30T12:00:00+00:00", + "host": {"node": "n1", "chip": "Apple M3 Ultra", "backend": "metal"}, + "arms": [{**arm, "binary_sha256": "f" * 64} for arm in plan["arms"]], + "models": {plan["models"][0]: {"revision": "r1", "trained_context": 262144}}, "samples": samples} + if plan["trace"]: + record["diagnostic"] = {"samples": [{"point": point["id"]} for _, point in points]} + return record + + +def rounds(arm, values, metric="output_tok_s"): + return [{"model": "m", "server": "s", "point": "p", "arm": arm, "metrics": {metric: value}, "rejected": None} + for value in values] + + +class LaneTests(unittest.TestCase): + def broken(self, change): + value = shipped() + change(value) + with patch.object(performance_nightly, "read_json", return_value=value): + with self.assertRaises(ValueError): + lanes() + + def test_every_shipped_lane_plans_a_job_on_its_pinned_node(self): + arm_list = performance_plan.arms(CANDIDATE, BASELINE, PIN) + for lane in lanes(): + spec = performance_plan.job_spec("d" * 40, arm_list, [lane["model"]], lane["rounds"], lane["node"], + lane["id"], trace=lane["trace"], backend=lane["backend"], + servers=lane["servers"]) + self.assertEqual(spec["target"]["nodes"], [lane["node"]]) + + def test_a_lane_is_one_pinned_model_on_a_node_of_its_own(self): + def second(field, value): + return lambda config: config["lanes"][1].update({field: value}) + + first = shipped()["lanes"][0] + for change in (second("id", first["id"]), second("node", first["node"]), second("id", "Metal Mini"), + second("backend", "space-heater"), second("model", "no-such-model"), + second("model", ["qwen35-4b", "qwen35-9b"]), second("node", "two nodes"), + second("servers", []), second("servers", ["no-such-server"]), second("servers", "lanes4"), + second("trace", "true"), second("rounds", 3), + lambda config: config["lanes"][0].pop("node"), + lambda config: config.update(rounds=performance_plan.MAX_ROUNDS + 1), + lambda config: config.update(rounds="3"), + lambda config: config.update(lanes=[]), + lambda config: config.update(schema_version=2)): + self.broken(change) + + def test_a_lane_may_name_its_servers_and_a_trace_pass(self): + value = shipped() + value["lanes"][0].update(servers=["lanes4", "lanes4-pool32k"], trace=True) + with patch.object(performance_nightly, "read_json", return_value=value): + first = lanes()[0] + self.assertEqual((first["servers"], first["trace"]), (["lanes4", "lanes4-pool32k"], True)) + row = matrix([first])["include"][0] + self.assertEqual((row["servers"], row["trace"], row["rounds"]), ("lanes4,lanes4-pool32k", True, value["rounds"])) + + def test_the_matrix_gives_the_workflow_one_call_per_lane(self): + rows = matrix(lanes())["include"] + self.assertEqual([row["id"] for row in rows], [lane["id"] for lane in shipped()["lanes"]]) + for row in rows: + self.assertEqual(set(row), {"id", "backend", "node", "model", "servers", "trace", "rounds"}) + self.assertEqual((row["servers"], row["trace"]), ("", False)) + json.dumps(rows) + + +class BaselineTests(unittest.TestCase): + def run_record(self, **overrides): + return {"id": 7, "conclusion": "success", "head_branch": "main", "event": "schedule", + "head_sha": BASELINE, **overrides} + + def test_the_baseline_is_the_last_successful_nightlys_commit_on_main(self): + newer = self.run_record(id=9, head_sha=PIN) + self.assertEqual(previous([newer, self.run_record()], 11), PIN) + self.assertEqual(previous([newer, self.run_record()], 9), BASELINE) + self.assertEqual(previous([self.run_record(event="workflow_dispatch")], 11), BASELINE) + for skipped in ({"conclusion": "failure"}, {"conclusion": None}, {"head_branch": "feature"}, + {"event": "pull_request"}, {"head_sha": "abc"}, {"head_sha": None}): + self.assertIsNone(previous([self.run_record(**skipped)], 11)) + self.assertIsNone(previous([], 11)) + + def test_a_night_compares_commits_or_measures_noise_or_measures_nothing(self): + self.assertEqual(compared(CANDIDATE, BASELINE, False), (BASELINE, "commits")) + self.assertEqual(compared(CANDIDATE, CANDIDATE, False), (CANDIDATE, "unchanged")) + self.assertEqual(compared(CANDIDATE, None, False), (CANDIDATE, "noise")) + for found in (BASELINE, CANDIDATE, None): + self.assertEqual(compared(CANDIDATE, found, True), (CANDIDATE, "noise")) + with self.assertRaises(ValueError): + compared("main", BASELINE, False) + + def test_plan_hands_the_workflow_its_commits_and_lanes(self): + plan = run_path(SCRIPT)["plan"] + asked = [] + + def github(path): + asked.append(path) + return {"workflow_runs": [self.run_record()]} + + with TemporaryDirectory() as directory: + output = Path(directory) / "output" + environment = {"GITHUB_SHA": CANDIDATE, "GITHUB_REF": "refs/heads/main", "GITHUB_RUN_ID": "11", + "GITHUB_OUTPUT": str(output)} + with patch.dict(plan.__globals__, github=github), patch.dict("os.environ", environment): + plan() + written = dict(line.split("=", 1) for line in output.read_text(encoding="utf-8").splitlines()) + with patch.dict("os.environ", GITHUB_REF="refs/heads/feature"): + with self.assertRaisesRegex(ValueError, "main"): + plan() + self.assertEqual(asked[0], "repos/Mesh-LLM/skippy/actions/workflows/inference-performance-nightly.yml/runs" + "?branch=main&status=success&per_page=20") + self.assertEqual((written["candidate"], written["baseline"], written["mode"]), + (CANDIDATE, BASELINE, "commits")) + self.assertEqual(json.loads(written["matrix"]), matrix(lanes())) + + +class AuditTests(unittest.TestCase): + def test_a_job_that_measured_what_its_plan_admitted_holds(self): + for plan in (admitted(), admitted(trace=True), admitted(servers=["lanes4", "lanes4-pool32k"]), + admitted(baseline_reference="d" * 40)): + self.assertEqual(audit(plan, measured(plan), "n1"), []) + + def test_each_fault_is_named_once_however_many_rounds_repeat_it(self): + def faults(change, node="n1", plan=admitted()): + record = measured(plan) + change(record) + return audit(plan, record, node) + + def every(record, arm, point): + return [sample for sample in record["samples"] if (sample["arm"], sample["point"]) == (arm, point)] + + def lacking(record): + for sample in every(record, "baseline", "c4-short"): + sample["unsupported"] = ["--kv-pool-tokens"] + + def short(record): + for sample in every(record, "candidate", "c4-long-output"): + sample["metrics"]["output_tokens_mean"] = 1900.5 + + def unreported(record): + every(record, "candidate", "c16-depth0")[0]["metrics"]["itl_ms_p50"] = None + + def refused(arm, point): + def change(record): + every(record, arm, point)[0]["rejected"] = {"requests": 8, "failed": 8, "cut_short": 0, "errors": []} + return change + + self.assertEqual(faults(lambda record: None, node="n2"), ["it ran on n1, not the pinned n2"]) + self.assertEqual(faults(lambda record: record["samples"].pop()), + ["62 measured samples, not the 63 its arms, points and rounds make"]) + self.assertEqual(faults(lacking), ["baseline ran without --kv-pool-tokens"]) + self.assertEqual(faults(short), + ["candidate at c4-long-output wrote 1900.5 tokens a request, not the 2048 asked for"]) + self.assertEqual(faults(unreported), ["candidate at c16-depth0 is missing a metric"]) + self.assertEqual(faults(refused("candidate", "c16-depth4096")), + ["candidate at c16-depth4096 failed requests its pool could hold"]) + self.assertEqual(faults(refused("reference", "single-short")), + ["reference at single-short failed requests its pool could hold"]) + self.assertEqual(faults(lambda record: every(record, "candidate", "c4-short")[0].update(point="elsewhere")), + ["candidate at elsewhere is not a cell of the plan"]) + self.assertEqual(faults(lambda record: record.pop("diagnostic"), plan=admitted(trace=True)), + ["0 traced samples, not one for each of its 7 points"]) + + +class RegressionTests(unittest.TestCase): + slower = rounds("baseline", (100, 101, 99)) + rounds("candidate", (90, 91, 89)) + + def only(self, samples, mode="commits"): + found, = cells({"samples": samples}, mode) + return found + + def test_a_cell_moves_only_past_the_tolerance_with_its_rounds_apart(self): + slower = self.only(self.slower) + self.assertEqual((slower["state"], slower["owner"]), ("regressed", "skippy")) + self.assertAlmostEqual(slower["percent"], -10.0) + faster = self.only(rounds("baseline", (100, 101, 99)) + rounds("candidate", (110, 111, 109))) + self.assertEqual((faster["state"], faster["owner"]), ("improved", None)) + later = self.only(rounds("baseline", (100, 101, 99), "ttft_ms_p50") + + rounds("candidate", (110, 111, 109), "ttft_ms_p50")) + self.assertEqual((later["state"], later["owner"]), ("regressed", "skippy")) + level = self.only(rounds("baseline", (100, 101, 99)) + rounds("candidate", (100.5, 101.5, 99.5))) + self.assertEqual(level["state"], "within") + mixed = self.only(rounds("baseline", (90, 100, 110)) + rounds("candidate", (88, 95, 109))) + self.assertEqual((mixed["state"], mixed["owner"]), ("uncertain", None)) + + def test_two_arms_of_one_commit_measure_noise_and_never_a_regression(self): + found = self.only(self.slower, "noise") + self.assertEqual((found["state"], found["owner"]), ("noise", None)) + + def test_a_regression_is_llama_cpps_when_the_pin_moved_and_llama_server_lost_as_much(self): + old_pin = rounds("baseline-reference", (200, 201, 199)) + inherited = self.only(self.slower + old_pin + rounds("reference", (180, 181, 179))) + self.assertEqual((inherited["state"], inherited["owner"]), ("regressed", "llama.cpp")) + self.assertAlmostEqual(inherited["llama_percent"], -10.0) + mostly_ours = self.only(self.slower + old_pin + rounds("reference", (194, 195, 193))) + self.assertEqual(mostly_ours["owner"], "skippy") + same_pin = self.only(self.slower + rounds("reference", (180, 181, 179))) + self.assertEqual((same_pin["owner"], same_pin["llama_percent"]), ("skippy", None)) + + def test_a_cell_an_arm_did_not_measure_and_a_metric_outside_the_headline_are_left_out(self): + self.assertEqual(cells({"samples": rounds("candidate", (90, 91, 89))}, "commits"), []) + rejected = [{**sample, "metrics": {"output_tok_s": None}, "rejected": {"requests": 8}} + for sample in rounds("baseline", (100, 101, 99))] + self.assertEqual(cells({"samples": rejected + rounds("candidate", (90, 91, 89))}, "commits"), []) + self.assertEqual(cells({"samples": rounds("baseline", (9, 9, 9), "request_per_s") + + rounds("candidate", (1, 1, 1), "request_per_s")}, "commits"), []) + + +class NightTests(unittest.TestCase): + def write(self, directory, plan, record=None): + directory.mkdir(parents=True) + (directory / "plan.json").write_text(json.dumps(plan), encoding="utf-8") + (directory / "jobs.json").write_text(json.dumps(["job_1"]), encoding="utf-8") + if record is not None: + (directory / "n1-performance.json").write_text(json.dumps(record), encoding="utf-8") + + def test_each_lane_reads_the_newest_attempt_that_uploaded_its_evidence(self): + with TemporaryDirectory() as directory: + root = Path(directory) + for name in ("inference-performance-metal-studio-77-1", "inference-performance-metal-studio-77-2", + "inference-performance-metal-studio-78-9", "inference-performance-metal-77-3", + "nightly-inference-performance-77-1"): + (root / name).mkdir() + found = evidence(root, [LANE, {**LANE, "id": "cuda-spark"}], "77") + self.assertEqual({lane: path.name for lane, path in found.items()}, + {"metal-studio": "inference-performance-metal-studio-77-2"}) + self.assertEqual(evidence(root / "missing", [LANE], "77"), {}) + + def test_a_night_counts_skippys_regressions_and_names_the_lanes_that_did_not_hold(self): + plan = admitted() + with TemporaryDirectory() as directory: + root = Path(directory) + absent = lane_report(LANE, None, CANDIDATE, BASELINE, "commits") + self.assertEqual((absent["checks"], absent["cells"]), + (["its job was not planned, or its evidence was not uploaded"], [])) + self.write(root / "unfinished", plan) + unfinished = lane_report({**LANE, "id": "cuda-spark"}, root / "unfinished", CANDIDATE, BASELINE, "commits") + self.assertEqual((unfinished["job"], unfinished["cells"]), ("job_1", [])) + self.assertIn("did not finish", unfinished["checks"][0]) + self.write(root / "held", plan, measured(plan, rate={"candidate": 80.0})) + held = lane_report(LANE, root / "held", CANDIDATE, BASELINE, "commits") + other = lane_report(LANE, root / "held", "e" * 40, BASELINE, "commits") + quiet = lane_report(LANE, root / "held", CANDIDATE, BASELINE, "noise") + self.assertEqual((held["checks"], held["host"], held["job"]), ([], "Apple M3 Ultra", "job_1")) + # seven points, each with throughput, time to first token and time between tokens + self.assertEqual(len(held["cells"]), 21) + self.assertEqual({found["state"] for found in held["cells"] if found["metric"] == "output_tok_s"}, + {"regressed"}) + self.assertEqual({found["state"] for found in held["cells"] if found["metric"] != "output_tok_s"}, {"within"}) + self.assertEqual(other["checks"], ["its plan is not tonight's commits and this lane's model"]) + + report = night(CANDIDATE, BASELINE, "commits", [held, unfinished]) + self.assertEqual(report["totals"], {"lanes": 2, "unverified": 1, "cells": 21, "regressions": 7, + "llama_regressions": 0, "improvements": 0, "uncertain": 0}) + json.dumps(report) + text = markdown(report) + for expected in ("**7 regressions in Skippy**", "## Regressions", + "| metal-studio | Apple M3 Ultra | qwen35-4b | c16-depth0 | Output throughput |", + "Regressed; round ranges do not overlap", "| Skippy |", "## Evidence", "| held |", + "did not finish"): + self.assertIn(expected, text) + for absent_text in ("http", "## Improvements", "## Spread"): + self.assertNotIn(absent_text, text) + + noise = night(CANDIDATE, CANDIDATE, "noise", [quiet]) + self.assertEqual((noise["totals"]["regressions"], noise["totals"]["cells"]), (0, 21)) + text = markdown(noise) + for expected in ("an A/A run", "## Spread of two equal builds", "-19.80%"): + self.assertIn(expected, text) + self.assertNotIn("## Regressions", text) + + def test_report_writes_the_nights_record_log_and_counts(self): + report = run_path(SCRIPT)["report"] + plan = admitted() + with TemporaryDirectory() as directory: + root, output = Path(directory) / "evidence", Path(directory) / "output" + self.write(root / "inference-performance-metal-studio-11-1", plan, + measured(plan, rate={"candidate": 80.0})) + environment = {"CANDIDATE": CANDIDATE, "BASELINE": BASELINE, "MODE": "commits", "GITHUB_RUN_ID": "11", + "GITHUB_OUTPUT": str(output), "GITHUB_STEP_SUMMARY": ""} + with patch.dict(report.__globals__, lanes=lambda: [LANE]), patch.dict("os.environ", environment): + report(root) + with patch.dict("os.environ", MODE="unchanged"): + with self.assertRaises(ValueError): + report(root) + written = json.loads((root / "nightly/nightly.json").read_text(encoding="utf-8")) + log = (root / "nightly/nightly.md").read_text(encoding="utf-8") + counts = output.read_text(encoding="utf-8").splitlines() + self.assertEqual((written["candidate"], written["baseline"], written["mode"]), (CANDIDATE, BASELINE, "commits")) + self.assertEqual(written["totals"]["regressions"], 7) + self.assertIn("## Regressions", log) + self.assertEqual(counts, ["regressions=7", "unverified=0"]) + + +class Memory: + """An experiment in memory, as the calls the recorder makes.""" + + def __init__(self): + self.runs, self.files = {}, {} + + def run(self, run_id): + held = self.runs[run_id] + return Run(run_id, held["status"], dict(held["tags"]), dict(held["params"]), dict(held["metrics"])) + + def find(self, key): + return next((self.run(run_id) for run_id, held in self.runs.items() if held["tags"].get("eval.key") == key), + None) + + def get(self, run_id): + return self.run(run_id) + + def search(self, params, tags, without=None): + return [self.run(run_id) for run_id, held in self.runs.items() + if all(held["params"].get(name) == value for name, value in params.items()) + and all(held["tags"].get(name) == value for name, value in tags.items()) + and all(held["tags"].get(name) != value for name, value in (without or {}).items())] + + def create(self, name, tags): + run_id = f"run{len(self.runs) + 1}" + self.runs[run_id] = {"name": name, "status": "RUNNING", "tags": dict(tags), "params": {}, "metrics": {}} + return run_id + + def log(self, run_id, metrics=(), params=None, tags=None): + held = self.runs[run_id] + held["params"].update(params or {}) + held["tags"].update(tags or {}) + held["metrics"].update({key: value for key, value, _, _ in metrics}) + + def finish(self, run_id): + self.runs[run_id]["status"] = "FINISHED" + + def attach(self, run_id, path): + self.files[(run_id, path.name)] = sha256(path) if path.is_file() else "a directory" + + def artifact_sha256(self, run_id, name): + return self.files[(run_id, name)] + + def link(self, run_id): + return f"link:{run_id}" + + def keyed(self): + """Every run by the key it was recorded under.""" + return {held["tags"]["eval.key"]: held for held in self.runs.values()} + + +def write_job(directory, plan, record, pull_requests=None, branches=None): + """A job's evidence as the controller collects it, under the label n1 and the id job_1.""" + committed = {arm["sha"]: "2026-11-30T10:00:00Z" for arm in plan["arms"]} + rows = performance_report.rows(record, performance_plan.scenario(plan.get("servers")), committed, "job_1", + pull_requests or {}, branches) + (directory / "n1-rows.jsonl").write_text("".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), + encoding="utf-8") + (directory / "n1-performance.json").write_text(json.dumps(record), encoding="utf-8") + (directory / "plan.json").write_text(json.dumps(plan), encoding="utf-8") + (directory / "n1-logs").mkdir() + (directory / "n1-logs/build-candidate.log").write_text("built\n", encoding="utf-8") + + +class RecordTests(unittest.TestCase): + rate = {"candidate": 80.0, "baseline": 100.0, "reference": 160.0, "baseline-reference": 200.0} + cell = "output_tok_s/c4-short" + beside_llama = "output_tok_s_vs_llama/c4-short" + + def recorded(self, plan, standing="verified", **arms): + """The experiment after one job is recorded twice, its runs by key, and the ids it returned.""" + tracking = Memory() + with TemporaryDirectory() as directory: + write_job(Path(directory), plan, measured(plan, rate=self.rate), **arms) + ids = record_job(tracking, Path(directory), "n1", "job_1", standing, extra={"eval.trigger": "nightly"}) + count = len(tracking.runs) + self.assertEqual(record_job(tracking, Path(directory), "n1", "job_1", standing), ids) + self.assertEqual(len(tracking.runs), count) + return tracking, tracking.keyed(), ids + + def test_a_nights_job_records_tonights_commit_as_main_and_the_last_nights_as_its_baseline(self): + tracking, runs, ids = self.recorded(admitted()) + labels = ("candidate", "baseline", "reference") + arm = {label: runs[f"job:job_1:{label}"] for label in labels} + self.assertEqual(sorted(runs), sorted( + ["job:job_1", f"trend:{MACHINE}:qwen35-4b:main", f"trend:{MACHINE}:qwen35-4b:reference"] + + [f"job:job_1:{label}{part}" for label in labels for part in ("", ":detail")])) + self.assertEqual([arm[label]["tags"]["arm.role"] for label in labels], ["main", "baseline", "reference"]) + self.assertEqual([arm[label]["name"] for label in labels], + ["Skippy main · qwen35-4b · " + "a" * 12, "Skippy main (baseline) · qwen35-4b · " + "b" * 12, + "llama-server · qwen35-4b · " + "c" * 12]) + self.assertEqual([arm[label]["tags"].get("view.current") for label in labels], ["true", None, "true"]) + self.assertEqual({held["status"] for held in runs.values()}, {"FINISHED"}) + self.assertEqual(ids, {"job": tracking.find("job:job_1").run_id, + "arms": {label: tracking.find(f"job:job_1:{label}").run_id for label in labels}}) + + self.assertEqual((arm["candidate"]["metrics"][self.cell], arm["reference"]["metrics"][self.cell]), (81.0, 161.0)) + self.assertAlmostEqual(arm["candidate"]["metrics"][self.beside_llama], 81 / 161) + self.assertAlmostEqual(arm["baseline"]["metrics"][self.beside_llama], 101 / 161) + self.assertNotIn(self.beside_llama, arm["reference"]["metrics"]) + # llama-server rejects this point, so it has no figure there and Skippy none beside it + self.assertEqual(arm["candidate"]["metrics"]["output_tok_s/c16-depth4096"], 81.0) + self.assertNotIn("output_tok_s/c16-depth4096", arm["reference"]["metrics"]) + self.assertNotIn("output_tok_s_vs_llama/c16-depth4096", arm["candidate"]["metrics"]) + self.assertEqual(runs["job:job_1:candidate:detail"]["tags"]["mlflow.parentRunId"], ids["arms"]["candidate"]) + self.assertEqual(runs["job:job_1:candidate:detail"]["metrics"]["detail/lanes4/c4-short/output_tok_s/max"], 82.0) + + trend = runs[f"trend:{MACHINE}:qwen35-4b:main"] + self.assertEqual((trend["name"], trend["tags"]["trend.job.job_1"], trend["metrics"][self.cell]), + (f"trend · Skippy main · qwen35-4b · {MACHINE}", CANDIDATE, 81.0)) + self.assertEqual(runs[f"trend:{MACHINE}:qwen35-4b:reference"]["metrics"][self.cell], 161.0) + + job = runs["job:job_1"] + self.assertEqual((job["tags"]["eval.phase"], job["tags"]["eval.verification_state"], job["tags"]["eval.trigger"], + job["params"]["machine_type"], job["params"]["models"]), + ("campaign", "verified", "nightly", MACHINE, "qwen35-4b")) + self.assertEqual(arm["candidate"]["tags"]["eval.job_run"], ids["job"]) + self.assertEqual({name for run_id, name in tracking.files if run_id == ids["job"]}, + {"n1-performance.json", "n1-rows.jsonl", "plan.json", "n1-logs"}) + + def test_a_moved_pin_measures_each_commit_beside_llama_cpp_at_its_own_pin(self): + _, runs, _ = self.recorded(admitted(baseline_reference="d" * 40)) + old = runs["job:job_1:baseline-reference"] + self.assertEqual((old["tags"]["arm.role"], old["name"]), + ("baseline-reference", "llama-server (baseline pin) · qwen35-4b · " + "d" * 12)) + self.assertNotIn("view.current", old["tags"]) + self.assertAlmostEqual(runs["job:job_1:candidate"]["metrics"][self.beside_llama], 81 / 161) + self.assertAlmostEqual(runs["job:job_1:baseline"]["metrics"][self.beside_llama], 101 / 201) + self.assertEqual(runs[f"trend:{MACHINE}:qwen35-4b:reference"]["metrics"][self.cell], 161.0) + + def test_a_copy_of_tonights_commit_is_noise_and_never_current(self): + _, runs, _ = self.recorded(admitted(baseline=CANDIDATE)) + copy = runs["job:job_1:baseline"] + self.assertEqual((copy["tags"]["arm.role"], copy["name"]), + ("noise", "Skippy main (A/A copy) · qwen35-4b · " + "a" * 12)) + self.assertNotIn("view.current", copy["tags"]) + self.assertEqual(runs[f"trend:{MACHINE}:qwen35-4b:main"]["metrics"][self.cell], 81.0) + + def test_a_tracked_branch_is_the_line_and_main_beside_it_is_its_baseline(self): + _, runs, _ = self.recorded(admitted(), branches={"candidate": "gen-ai-semconv"}) + line, beside = runs["job:job_1:candidate"], runs["job:job_1:baseline"] + self.assertEqual((line["tags"]["arm.role"], line["name"], line["params"]["skippy_line"]), + ("main", "Skippy gen-ai-semconv · qwen35-4b · " + "a" * 12, "gen-ai-semconv")) + self.assertEqual((beside["tags"]["arm.role"], beside["name"]), + ("baseline", "Skippy main (baseline) · qwen35-4b · " + "b" * 12)) + # the trend follows the tracked line, not the commit it was compared with + self.assertEqual(runs[f"trend:{MACHINE}:qwen35-4b:main"]["metrics"][self.cell], 81.0) + + def test_beside_a_pull_request_main_keeps_its_own_role(self): + _, runs, _ = self.recorded(admitted(), pull_requests={"candidate": 130}) + head, main = runs["job:job_1:candidate"], runs["job:job_1:baseline"] + self.assertEqual((head["tags"]["arm.role"], head["name"], head["tags"]["view.current"]), + ("branch", "Skippy PR #130 · qwen35-4b · " + "a" * 12, "true")) + self.assertEqual((main["tags"]["arm.role"], main["name"], main["tags"]["view.current"]), + ("main", "Skippy main · qwen35-4b · " + "b" * 12, "true")) + self.assertEqual(runs[f"trend:{MACHINE}:qwen35-4b:main"]["metrics"][self.cell], 101.0) + + def test_a_moved_pin_measures_the_baseline_arm_at_its_own_pin_whatever_its_role(self): + moved = admitted(baseline_reference="d" * 40) + _, runs, _ = self.recorded(moved, pull_requests={"candidate": 130}) + head, main = runs["job:job_1:candidate"], runs["job:job_1:baseline"] + self.assertEqual((head["tags"]["arm.role"], main["tags"]["arm.role"]), ("branch", "main")) + self.assertAlmostEqual(head["metrics"][self.beside_llama], 81 / 161) + self.assertAlmostEqual(main["metrics"][self.beside_llama], 101 / 201) + # the pull request's pin does not reach main's trend + self.assertAlmostEqual(runs[f"trend:{MACHINE}:qwen35-4b:main"]["metrics"][self.beside_llama], 101 / 201) + + _, runs, _ = self.recorded(moved, standing="diagnostic") + self.assertEqual(runs["job:job_1:baseline"]["tags"]["arm.role"], "diagnostic") + self.assertAlmostEqual(runs["job:job_1:baseline"]["metrics"][self.beside_llama], 101 / 201) + self.assertAlmostEqual(runs["job:job_1:candidate"]["metrics"][self.beside_llama], 81 / 161) + + def test_an_unchecked_job_awaits_audit_and_a_diagnostic_one_stays_out_of_the_view(self): + _, runs, _ = self.recorded(admitted(), standing="unaudited") + self.assertEqual(runs["job:job_1"]["tags"]["eval.verification_state"], "completed, awaiting audit") + _, runs, _ = self.recorded(admitted(), standing="diagnostic") + self.assertEqual((runs["job:job_1"]["tags"]["eval.phase"], runs["job:job_1:candidate"]["tags"]["arm.role"]), + ("diagnostic", "diagnostic")) + self.assertEqual([key for key in runs if key.startswith("trend:")], []) + self.assertEqual([key for key, held in runs.items() if "view.current" in held["tags"]], []) + + def test_a_run_left_unfinished_stops_the_recording(self): + tracking, plan = Memory(), admitted() + tracking.create("left over", {"eval.key": "job:job_1"}) + with TemporaryDirectory() as directory: + write_job(Path(directory), plan, measured(plan)) + with self.assertRaisesRegex(RuntimeError, "inspect it"): + record_job(tracking, Path(directory), "n1", "job_1", "verified") + + def test_a_job_whose_read_back_failed_is_not_taken_as_recorded_on_a_retry(self): + tracking, plan = Memory(), admitted() + with TemporaryDirectory() as directory: + write_job(Path(directory), plan, measured(plan)) + stored = tracking.artifact_sha256 + # the server holds other bytes than the evidence for the job's rows + tracking.artifact_sha256 = lambda run_id, name: ("0" * 64 if name == "n1-rows.jsonl" + else stored(run_id, name)) + with self.assertRaisesRegex(RuntimeError, "differs from the local copy"): + record_job(tracking, Path(directory), "n1", "job_1", "verified") + tracking.artifact_sha256 = stored + with self.assertRaisesRegex(RuntimeError, "read-back never passed"): + record_job(tracking, Path(directory), "n1", "job_1", "verified") + + def night_of(self, mode, baseline): + result = measured(admitted(), rate=self.rate) + lane = {**{field: LANE[field] for field in ("id", "backend", "node", "model")}, "job": "job_1", + "host": "Apple M3 Ultra", "checks": [], "cells": cells(result, mode)} + return night(CANDIDATE, baseline, mode, [lane]) + + def test_the_night_is_a_run_with_its_counts_cells_log_and_record(self): + tracking, report = Memory(), self.night_of("commits", BASELINE) + run = {"url": "https://github.example/runs/11", "id": "11", "attempt": "1"} + with TemporaryDirectory() as directory: + files = [Path(directory) / "nightly.json", Path(directory) / "nightly.md"] + files[0].write_text(json.dumps(report), encoding="utf-8") + files[1].write_text(markdown(report), encoding="utf-8") + first = record_night(tracking, report, markdown(report), files, run, {"metal-studio": "run9"}) + self.assertEqual(record_night(tracking, report, markdown(report), files, run, {}), first) + quiet = self.night_of("noise", CANDIDATE) + record_night(tracking, quiet, markdown(quiet), files, {**run, "attempt": "2"}, {}) + runs = tracking.keyed() + held = runs["nightly:11:1"] + self.assertEqual((held["name"], held["status"]), + ("nightly · Skippy main " + "a" * 12 + " against " + "b" * 12, "FINISHED")) + self.assertEqual([held["tags"][name] for name in ("eval.phase", "nightly.outcome", "eval.verification_state", + "nightly.candidate", "nightly.baseline", "ci.run")], + ["nightly", "regressed", "verified", CANDIDATE, BASELINE, run["url"]]) + self.assertEqual((held["metrics"]["regressions"], held["metrics"]["cells"]), (7.0, 21.0)) + self.assertAlmostEqual(held["metrics"]["vs_previous/metal-studio/output_tok_s/c4-short"], 81 / 101) + self.assertEqual(held["metrics"]["vs_previous/metal-studio/ttft_ms_p50/c4-short"], 1.0) + for expected in ("## Regressions", "## Recorded jobs", "- metal-studio: link:run9"): + self.assertIn(expected, held["tags"]["mlflow.note.content"]) + self.assertEqual({name for run_id, name in tracking.files if run_id == first}, {"nightly.json", "nightly.md"}) + noise = runs["nightly:11:2"] + self.assertEqual((noise["name"], noise["tags"]["nightly.outcome"]), + ("nightly · Skippy main " + "a" * 12 + " against itself", "noise")) + self.assertIn("spread/metal-studio/output_tok_s/c4-short", noise["metrics"]) + self.assertEqual([key for key in noise["metrics"] if key.startswith("vs_previous/")], []) + + def test_a_log_longer_than_a_description_holds_is_cut_at_a_line_and_keeps_its_jobs(self): + self.assertEqual(night_note("short\n", []), "short\n") + long = "".join(f"| row {index} |\n" for index in range(2000)) + note = night_note(long, ["- metal-studio: link:run9"]) + self.assertLessEqual(len(note), NOTE_LIMIT) + self.assertTrue(note.startswith("| row 0 |\n| row 1 |\n")) + self.assertTrue(note.endswith("|\n\nThe rest of this log is in the attached nightly.md.\n" + "\n## Recorded jobs\n\n- metal-studio: link:run9\n")) + + +class RecorderTests(unittest.TestCase): + def test_record_marks_a_job_verified_only_when_its_checks_held(self): + record, plan = run_path(RECORDER)["record"], admitted() + result = measured(plan, rate={"candidate": 80.0}) + environment = {"RUN_URL": "https://github.example/runs/11", "GITHUB_RUN_ID": "11", "GITHUB_RUN_ATTEMPT": "1"} + for checks, state in (([], "verified"), + (["baseline ran without --kv-pool-tokens"], "completed, awaiting audit")): + tracking = Memory() + lane = {**{field: LANE[field] for field in ("id", "backend", "node", "model")}, "job": "job_1", + "host": "Apple M3 Ultra", "checks": checks, "cells": cells(result, "commits")} + unfinished = {**lane, "id": "cuda-spark", "job": None, "host": None, "cells": [], + "checks": ["its job did not finish, so there is nothing to compare"]} + report = night(CANDIDATE, BASELINE, "commits", [lane, unfinished]) + with TemporaryDirectory() as directory: + root = Path(directory) + (root / "inference-performance-metal-studio-11-1").mkdir() + write_job(root / "inference-performance-metal-studio-11-1", plan, result) + (root / "nightly").mkdir() + (root / "nightly/nightly.json").write_text(json.dumps(report), encoding="utf-8") + (root / "nightly/nightly.md").write_text(markdown(report), encoding="utf-8") + both = [LANE, {**LANE, "id": "cuda-spark", "node": "n2"}] + with patch.dict(record.__globals__, Experiment=lambda: tracking, lanes=lambda: both), \ + patch.dict("os.environ", environment): + record(root) + runs = tracking.keyed() + self.assertEqual((runs["job:job_1"]["tags"]["eval.verification_state"], runs["job:job_1"]["tags"]["ci.run"]), + (state, environment["RUN_URL"])) + note = runs["nightly:11:1"]["tags"]["mlflow.note.content"] + self.assertIn(f'- metal-studio: link:{tracking.find("job:job_1").run_id}', note) + self.assertNotIn("- cuda-spark: link:", note) + + def test_a_search_names_its_parameters_and_tags_and_refuses_a_quote(self): + where = run_path(RECORDER)["where"] + self.assertEqual(where({"machine_type": MACHINE}, {"arm.role": "main"}, {"arm.role": "ceiling"}), + f"params.machine_type = '{MACHINE}' and tags.`arm.role` = 'main' " + "and tags.`arm.role` != 'ceiling'") + self.assertEqual(where({}, {"eval.key": "job:job_1"}, None), "tags.`eval.key` = 'job:job_1'") + for value in ("it's", 4): + with self.assertRaises(ValueError): + where({"model": value}, {}, None) + + def test_an_error_is_printed_without_the_server_its_experiment_or_its_account(self): + redacted = run_path(RECORDER)["redacted"] + environment = {"MLFLOW_TRACKING_URI": "https://tracking.example.test/", + "MLFLOW_EXPERIMENT_NAME": "Some experiment", "MLFLOW_TRACKING_USERNAME": "someone@example.test"} + with patch.dict("os.environ", environment): + text = redacted("GET https://tracking.example.test/api failed (host='tracking.example.test'), " + "in Some experiment, as someone@example.test") + for private in ("tracking.example.test", "Some experiment", "someone@"): + self.assertNotIn(private, text) + self.assertIn("[withheld]", text) + + def test_what_the_client_writes_reaches_the_public_log_without_the_server_or_a_runs_address(self): + recorder = run_path(RECORDER) + environment = {"MLFLOW_TRACKING_URI": "https://tracking.example.test", "MLFLOW_TRACKING_USERNAME": "someone"} + log = io.StringIO() + with patch.dict("os.environ", environment): + recorder["client_settings"]() + # the client's own switch for the link it prints when a run ends + self.assertEqual(os.environ["MLFLOW_SUPPRESS_PRINTING_URL_TO_STDOUT"], "true") + public = recorder["Public"](log) + print("View run nightly at: https://tracking.example.test/#/experiments/40/runs/0123abcd", file=public) + print("Connection to tracking.example.test timed out", file=public) + self.assertEqual(log.getvalue(), "View run nightly at: [withheld]/[withheld]\n" + "Connection to [withheld] timed out\n") + + +class VerdictTests(unittest.TestCase): + clean = {"regressions": 0, "unverified": 0} + + def test_a_night_passes_only_when_every_lane_held_skippy_did_not_regress_and_it_was_recorded(self): + def passed(mode, totals=None, **results): + return verdict(mode, results, totals)[0] + + finished = {"plan": "success", "measure": "success", "report": "success", "record": "success"} + self.assertTrue(passed("commits", self.clean, **finished)) + self.assertTrue(passed("noise", self.clean, **finished)) + self.assertTrue(passed("unchanged", plan="success", measure="skipped", report="skipped", record="skipped")) + for mode, change in (("commits", {"plan": "failure"}), ("", {}), ("commits", {"measure": "failure"}), + ("commits", {"measure": "cancelled"}), ("noise", {"measure": "skipped"}), + ("commits", {"report": "failure"}), ("commits", {"report": "skipped"}), + ("commits", {"record": "failure"}), ("noise", {"record": "skipped"})): + self.assertFalse(passed(mode, self.clean, **{**finished, **change}), (mode, change)) + self.assertFalse(passed("commits", None, **finished)) + self.assertFalse(passed("commits", {**self.clean, "regressions": 1}, **finished)) + self.assertFalse(passed("commits", {**self.clean, "unverified": 1}, **finished)) + self.assertIn("2 cell(s)", verdict("commits", finished, {**self.clean, "regressions": 2})[1]) + + def test_the_verdict_step_fails_the_run_unless_the_report_handed_on_clean_counts(self): + settle = run_path(SCRIPT)["settle"] + environment = {"PLAN": "success", "MODE": "commits", "MEASURE": "success", "REPORT": "success", + "RECORD": "success", "REGRESSIONS": "0", "UNVERIFIED": "0", "GITHUB_STEP_SUMMARY": ""} + with patch.dict("os.environ", environment): + settle() + for change in ({"REGRESSIONS": "2"}, {"UNVERIFIED": "1"}, {"REGRESSIONS": ""}, {"REPORT": "failure"}, + {"RECORD": "failure"}): + with patch.dict("os.environ", change): + with self.assertRaises(SystemExit): + settle() + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/performance_controller_contracts.py b/scripts/tests/performance_controller_contracts.py index e39f5ce7..3d4f0c0c 100644 --- a/scripts/tests/performance_controller_contracts.py +++ b/scripts/tests/performance_controller_contracts.py @@ -1,6 +1,5 @@ """Failure-path contracts for controlled comparison submission and evidence.""" -import json import subprocess import unittest from pathlib import Path @@ -123,57 +122,56 @@ def test_polling_failure_retains_finished_job_evidence_and_original_error(self): self.assertIn("first evidence retained", (self.root / "summary.md").read_text()) self.assertIn("poll lost", (self.root / "summary.md").read_text()) - def test_failed_job_collects_build_logs_without_comparison(self): + def test_failed_job_keeps_its_logs_without_comparison(self): dispatch = self.functions["dispatch"] write_json(self.root / "plan.json", {"pull_requests": {}, "arms": [{"label": "candidate"}], "jobs": [{"spec": {}, "label": "host"}]}) - pilot = Mock(); pilot.api.return_value = {"id": "job_a"} + listing = {"artifacts": [{"key": "p/j/run_a/log/build-candidate.log"}]} + pilot = Mock() + pilot.api.side_effect = lambda method, route, *_: listing if route == "/v1/artifacts/run_a" else {"id": "job_a"} collect, download = Mock(), Mock() with patch.dict(dispatch.__globals__, Pilot=lambda: pilot, collect=collect, download=download, wait=Mock(return_value={"status": "failed", "runs": [{"id": "run_a"}]})): with self.assertRaisesRegex(RuntimeError, "host: failed"): dispatch(self.root) collect.assert_not_called() - download.assert_called_once_with(pilot, "run_a", "build-candidate.log", self.root / "host-build-candidate.log") + download.assert_called_once_with(pilot, "run_a", "build-candidate.log", + self.root / "host-logs" / "build-candidate.log") def test_successful_collection_downloads_raw_aiperf_evidence(self): collect = self.functions["collect"] - result = {"harness": "h", "arms": [], "samples": [], "host": {"chip": "Mac"}} - pilot = Mock(); pilot.api.return_value = result + arms = [{"label": "baseline", "sha": "b"}] + result = {"harness": "h", "arms": arms, "samples": [], "host": {"chip": "Mac"}} + listing = {"artifacts": [{"key": "p/j/run_a/raw/aiperf.tar.gz"}, {"key": "p/j/run_a/raw/performance.json"}]} + pilot = Mock() + pilot.api.side_effect = lambda method, route, *_: listing if route == "/v1/artifacts/run_a" else result download = Mock() - plan = {"harness": "h", "arms": [], "trace": False, "committed_at": {}, "pull_requests": {}} - with patch.dict(collect.__globals__, download=download, rows=lambda *_: [], markdown=Mock(return_value="report")): + plan = {"harness": "h", "arms": arms, "trace": False, "committed_at": {}, "pull_requests": {}} + with patch.dict(collect.__globals__, download=download, rows=lambda *_: [], + markdown=Mock(return_value="report")): collect(pilot, {"id": "job_a", "runs": [{"id": "run_a"}]}, plan, "host", self.root) download.assert_called_once_with(pilot, "run_a", "aiperf.tar.gz", self.root / "host-aiperf.tar.gz") - def test_optional_trace_failure_does_not_prevent_later_models_being_measured(self): - execute = self.functions["execute"] - built = [{"label": label, "sha": label, "binary": label, "binary_sha256": "digest"} - for label in ("candidate", "baseline")] - plan = {"harness": "h", "arms": built, "models": ["m1", "m2"], "rounds": 1, "trace": True} - shape = {"servers": [{"id": "s"}]} - fixture = {"repo": "org/model", "revision": "r", "files": [{"size": 1}]} - calls = [] - def measure(_entry, _help, _model, _inputs, key, index, *_args, **_kwargs): - calls.append((key, index)) - if index is None: - raise RuntimeError("trace failed") - return [{"model": key, "round": index + 1}] - overrides = dict(native_plan=lambda: plan, read_json=lambda _: built, digest=lambda _: "digest", - capture=lambda _: "mock", capabilities=lambda _: "help", scenario=lambda: shape, - fixture=lambda _: fixture, admit_model=lambda *_: "model", tokenizer=lambda _: "tokenizer", - measure=measure, WORK=self.root / "work", TRACES=self.root / "traces") - with patch.dict(execute.__globals__, **overrides), patch("os.geteuid", return_value=1000), \ - patch.dict("os.environ", JIANYANG_ARTIFACT_DIR=str(self.root)), \ - patch("lib.inference_metal.chip", return_value="Mac"), \ - patch("lib.inference_metal.working_set", return_value=100 * 1024**3), \ - patch("lib.inference_metal.available_memory", return_value=100 * 1024**3): - execute() - self.assertEqual(calls, [("m1", 0), ("m1", 0), ("m2", 0), ("m2", 0), ("m1", None), ("m2", None)]) - result = read_json(self.root / "performance.json") - self.assertEqual(len(result["samples"]), 4) - self.assertEqual(len(result["diagnostic"]["failures"]), 2) - self.assertTrue((self.root / "traces.tar.gz").is_file()) + def test_a_failed_trace_pass_is_reported_while_a_failed_round_fails_the_job(self): + step = self.functions["measure_step"] + work = self.root / "work" + (work / "built").mkdir(parents=True) + (work / "models").mkdir() + write_json(work / "built" / "candidate.json", {"label": "candidate"}) + write_json(work / "helps.json", {"candidate": "help"}) + write_json(work / "models" / "m.json", {"model": "m.gguf", "inputs": {}}) + write_json(self.root / "performance.json", {"samples": [], "diagnostic": {"samples": [], "failures": []}}) + plan = {"arms": [{"label": "candidate"}], "rounds": 1, "trace": True, "backend": "metal"} + overrides = dict(native_plan=lambda: plan, scenario=lambda _: {"servers": [{"id": "s"}]}, + measure=Mock(side_effect=RuntimeError("trace failed")), BUILT=work / "built", + HELPS=work / "helps.json", MODELS=work / "models", TRACES=work / "traces") + with patch.dict(step.__globals__, **overrides), \ + patch.dict("os.environ", JIANYANG_ARTIFACT_DIR=str(self.root)): + step("m", "candidate", "s") + with self.assertRaisesRegex(RuntimeError, "trace failed"): + step("m", "candidate", "s", 1) + record = read_json(self.root / "performance.json") + self.assertEqual((record["diagnostic"]["failures"], record["samples"]), (["m/s: trace failed"], [])) if __name__ == "__main__":