diff --git a/AGENTS.md b/AGENTS.md index 8f3a4651..35ae02d4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -81,8 +81,9 @@ package, run `PYTHONPATH=src python -m dnn_benchmarking ...`. | 3 | At least one engine row failed validation. 3 wins over 1, and 1 wins over 0. Only `role == "engine"` rows count, as in `summary()`. | | 130 / 143 | SIGINT / SIGTERM. The result file is partial (`run.complete = false`). | -`dnn-benchmark compare` uses 0 (no regression), 1 (regression) and 2 (usage -or unreadable input). +`dnn-benchmark compare` uses 0 (no regression), 1 (regression, or coverage +loss under `--strict-coverage`), and 2 (usage, unreadable input, or +incompatible `cache_mode`/`timing_block` without `--allow-mismatch`). ## Architecture diff --git a/docs/methodology.md b/docs/methodology.md index 745531cf..4e20cf78 100644 --- a/docs/methodology.md +++ b/docs/methodology.md @@ -49,6 +49,7 @@ uses `events` mode and records the reason in `timing.fallback_reason`: | `device does not support hipStreamWaitValue32` | The device or driver has no stream wait-value support. | | `host sync in enqueue: ...` | The PyTorch graph reads a device value on the host. A stalled stream would then never complete. | | `stall gate failed in this graph; every row remeasured unstalled` | See below. | +| `another row in this graph fell back to events; every row remeasured in events mode` | One row on the graph fell back to `events` mode, so every row on that graph was remeasured in `events` mode. | The stall gate has a watchdog. If the gate cannot arm, cannot be created, or the watchdog releases it before the host finished the enqueue, that sample @@ -56,20 +57,21 @@ includes host gaps and is invalid. The tool then discards every row of the graph and measures the whole graph again in `events` mode. A warning on stderr gives the cause. -Rows of one graph share one mode only when no per-row fallback applies. -These cases give a graph rows in different modes: +The same graph-wide rerun applies when a per-row fallback (for example, +`host sync in enqueue: ...` on a PyTorch reference row or a PyTorch/rocKE +engine row) leaves a graph with both `staged` and `events` rows: the tool +discards the partial graph and remeasures every row in `events` mode so all +rows share one timing mode. Rows that did not fail their own probe record +`another row in this graph fell back to events; every row remeasured in events mode`. -- The `--validate pytorch` reference row can fall back to `events` mode - alone (for example, `host sync in enqueue: ...`). The hipDNN engine rows of - the same graph stay in `staged` mode. -- With several runtimes (`--runtime hipdnn,pytorch` or `hipdnn,rocke`), a - PyTorch or rocKE engine row can fall back to `events` mode alone. The hipDNN - rows of the same graph stay in `staged` mode. -- With `--oracle`, the tuned plan can use a different mode than the OOTB +These cases can still produce different modes: + +- With `--oracle`, the tuned child can use a different mode than the OOTB plan. The oracle verdict is then `mixed-timing` (see `docs/usage.md`). - `--timing-block N` (N > 1) times every row of the run in `block` mode. -Read `timing.mode` of each row before you compare two rows. +Read `timing.mode` and `timing.launch_mode` of each row before you compare +two rows. In `events` mode each iteration records the start event, calls `enqueue()`, records the stop event and waits. The device records the start event before @@ -315,42 +317,44 @@ kernel CV of 9.7 % and a maximum of 50.6 us (2 x median). Warmup through the timed path gave a CV of 0.95 % and a maximum of 26.2 us. The median did not change (25.4 to 25.6 us). -`timing.warmup_iters` is the number of untimed launches that actually ran. -Outside block mode it is `max(priming launches, --warmup)`: priming is 1 -launch for hipDNN, 2 for the PyTorch runtime (the host-sync probe), and 3 -when the probe finds a host sync and runs the launch again. So it is 1 or -more, also when `--warmup 0` is given. In block mode it is the priming -launches plus `--warmup` for every sample, the discarded first sample -included. +`timing.warmup_iters` is the number of untimed launches that actually ran +inside `measure()`. Outside block mode it is `max(priming launches, --warmup)`: +priming is 1 launch for hipDNN, 2 for torch-driven runtimes (PyTorch, rocKE +and AITER: first call plus host-sync probe), and 3 when the probe finds a host +sync and runs the launch again. `timing.requested_warmup_iters` records the +requested `--warmup` separately. In block mode `warmup_iters` is the priming +launches plus `--warmup` for every sample, the discarded first sample included. + +## Event-span overhead + +`kernel_med` is a **device event span** (stop event minus start event), not a +profiler dispatch sum. On ROCm, even an empty or busy-wait staged span includes +a fixed event/dispatch boundary floor (measured at ~7.8 µs on MI210, ~3.1–3.7 µs +on MI325X, and ~3.6–4.1 µs on MI355X). For short kernels (<50 µs), this common +offset compresses cross-runtime latency ratios toward 1.0x. Do not subtract a +universal constant across workloads; use dispatch sums from a profiler trace +when isolating sub-20 µs device busy time. ## Cache modes | Mode | Behavior | |---|---| -| `warm` (default) | No flush. Inputs, outputs and workspace stay in L2 and MALL between iterations if they fit. This is the steady state of a layer that runs many times. | -| `cold` | Before each warmup and timed iteration: write zeros to a 512 MiB device buffer, then do a full device sync. Then the iteration starts. | +| `warm` (default) | No flush. Inputs, outputs and workspace stay in L2 and MALL between iterations if they fit. | +| `cold` | Before each warmup and timed iteration: zero a 512 MiB buffer on the device, then drain the device. | Notes for `cold`: -- The flush and the sync are outside the timed span. Priming launches are - never flushed. -- 512 MiB is two times or more the largest last-level cache that the tool - targets (MI300X MALL, 256 MiB). MI210 L2 is 8 MiB. -- The tool allocates the buffer at the first cold iteration and keeps it for - the process. It frees the buffer before an `--oracle` child starts, and the - next cold iteration allocates it again. The hipDNN path uses - `hipdnn_frontend.DeviceBuffer`. The CUDA path uses a PyTorch tensor. If - the allocation fails, the row fails with an error that tells you to use - `--cache-mode warm`. -- The zero writes leave dirty lines in the cache. The first kernel in the - span can pay the write-back of these lines. `triton.testing.do_bench` has - the same effect. -- The flush does not change the instruction cache or TLB state. -- Each cold iteration costs more wall time than a warm iteration. The kernel - time budget (`--min-time-ms`) does not count the flush. - -`dnn-benchmark compare` refuses to compare files with different -`cache_mode` or `timing_block` values unless you give `--allow-mismatch`. +- The flush and drain run outside the timed span. Priming launches are not + flushed. +- 512 MiB is at least 2 x the largest last-level cache targeted (256 MiB MALL + on MI300X). The buffer is allocated once per process and freed before + `--oracle` child processes start. +- This does not reset the instruction cache or guarantee an empty hardware + cache. +- `--cache-mode cold` requires `--timing-block 1`. + +`dnn-benchmark compare` refuses to compare files with different `cache_mode` +or `timing_block` values unless you give `--allow-mismatch`. ## Stop rule @@ -406,11 +410,12 @@ The tool does not remove outliers. It adds warnings to the row: |---|---| | `noisy: IQR x% of median` | `iqr_ms / median_ms` more than 5 % and 10 or more samples. The table marks `kernel_med` with `*`. | | `outlier: max Nx median` | Maximum more than 2 x median. The table marks `kernel_med` with `*` and shows the warning in `note`. | -| `host-bound: submit is x% of kernel_med in timing; ...` | Block or events timing only. The median host submit time is 90 % or more of the median span. The span then measures the launch cost, not the device. Use the default staged timing for such kernels. | - -The noise flag uses IQR/median, not CV. A few slow samples raise the CV a -lot but do not change the IQR. The `outlier` flag reports those samples. +| `timer resolution: zero or nonpositive sample(s)` | One or more timed samples are `<= 0` ms. | +| `host-bound: submit is x% of kernel_med in timing; ...` | Block or events timing only. The median host submit time is 90 % or more of the median span. The span likely measures host launch overhead rather than pure device time. | +The noise flag uses IQR/median, not CV (the console verbose block reports +mean, standard deviation, min, p95 and max; CV is derivable as `std / mean` +but is not printed directly). The `outlier` flag reports slow spikes. The median is the headline because one slow iteration moves the mean but not the median. In the MI210 runs below, one 37.6 us sample in a 29 us matmul run moved the mean and the standard deviation, but not the median. @@ -471,32 +476,40 @@ engine must ignore these values. ## TFLOP/s and GB/s -`tflops = flops / median` and `gbps = io_bytes / median`: - -- `flops` is an analytical count from the graph JSON (FMA = 2 FLOPs). The - dispatch table is in `metrics/analytical/__init__.py`; the per-op formulas - are in its sibling modules (`conv.py`, `matmul.py`, `elementwise.py`, - `normalization.py`, `reduction.py`, `sdpa.py`). When any node of the graph - has no formula, `flops` and `tflops` are `null`, not a partial count. -- For an SDPA node with variable lengths, `flops` sums the count of each - batch from its valid lengths. The lengths come from the generated input - data, not from the tensor dims. A paged graph counts the real KV lengths - of its batches, not the page size. Without input data, a paged graph - counts the page-table width times the page size, capped by - `max_seq_len_kv`, for each sequence. -- `io_bytes` is the sum of the sizes of all non-virtual tensors. It is a - lower bound of the real memory traffic. A tensor with valid lengths counts - only its valid elements: `sum(lengths) * elements per position * element - size`. Paged K and V containers count their full size. -- In `warm` mode, a small problem can stay in L2. GB/s can then be more than - the HBM bandwidth. Use `--cache-mode cold` to measure from memory. - -## Clocks after the timed loop - -With `--metrics` (default) and amdsmi available, the runner reads the GPU -clocks right after the timed loop: `sclk_mhz`, `mclk_mhz`, `power_w`, -`temp_hotspot_c` and `throttle_status`. The row gets the warning `throttled` -when `throttle_status` is not 0. The tool does not set or lock clocks. +`tflops` and `gbps` are **graph-normalized rates**, not physical hardware +compute utilization or measured HBM bandwidth: + +- `tflops = flops / (kernel.median_ms * 1e9)` (decimal 10^12 FLOP/s). +- `gbps = io_bytes / (kernel.median_ms * 1e6)` (decimal 10^9 bytes/s). +- `flops` is an analytical count from the graph JSON (`FMA = 2 FLOPs`; version + recorded in `metrics.flops_formula_version`). Convolution counts use the + standard dense-equivalent convention (every tap at every output position, + including padded boundary positions). Normalization, reduction, pointwise, + and pooling ops use fixed per-element proxy multipliers rather than + instruction counts. SDPA counts only the QK and PV contractions (excluding + softmax). When any node has no formula or lacks required dims — including + packed paged SDPA with a diagonal mask and no sequence lengths — `flops` and + `tflops` are `null`. +- Every runtime row on a graph shares the same graph numerator, even if one + runtime executes extra padding, fill, or copy kernels inside its timed call + (noted in `timing.timed_work_notes` where known). +- `io_bytes` is the **graph tensor footprint** across non-virtual tensors, not + a lower bound on HBM traffic: strided spans include unreferenced holes, + non-ragged paged K, V, Q, and O containers count their full storage size, and + non-ragged padded outputs may still be written to memory. Variable-length + tensors with valid lengths count only their valid elements. +- In `warm` mode, working sets that fit in L2/MALL can report `gbps` above HBM + bandwidth. Use `--cache-mode cold` or `--cache-mode rotate` to evict + benchmark data from caches. + +## GPU telemetry during and after the timed loop + +With `--metrics` (default) and amdsmi available on the mapped HIP PCI device, +the runner samples GPU clocks, power, hotspot temperature and throttle status +during the timed loop and once immediately after it (`metrics.clocks_after`). +The row gets the warning `throttled` when either the post-loop +`throttle_status` is nonzero or `throttle_any` is `true`. The tool does not +set or lock clocks. ## PyTorch dispatch record @@ -534,13 +547,12 @@ it. The first profiler start in a process can take about one second. another thread only through a private PyTorch flag (`torch.autograd.profiler._is_profiler_enabled`). PyTorch has no public check for this case, so the capture is opt-in. - ## Profiling child process -`--pmc`, `--trace`, `--perf` and `--roofline` do not change the timed -numbers. After the timed row completes, the tool starts one child process for +`--pmc`, `--trace`, `--perf` and `--roofline` do not alter the parent's buffer +backend or overwrite timed samples. After all OOTB rows of the graph complete +(and GPU reference tensors are released), the tool starts one child process for each pass under the profiler: - ```text python -m dnn_benchmarking --internal-profiling-run --graph G --engine E \ --warmup W --iters 5 --seed S [--plugin-path P] @@ -637,14 +649,13 @@ with PyTorch (`torch.utils.benchmark.Timer.blocked_autorange`, | Host submit time | Yes (`host`) | No | Timer: wall time only | | Cache flush | `--cache-mode cold`, 512 MiB | Documented only | do_bench: 256 MB zero before each launch | | Rotating buffers | No | Documented only | No | -| Graph replay | No | Yes | `do_bench_cudagraph` | +| Graph replay | Raw launches (`launch_mode = raw` recorded) | Yes | `do_bench_cudagraph` | | Outliers | Flagged (IQR/median noise flag, max/median outlier flag), never removed; block mode discards the first sample | Discard first run | Timer: IQR warnings | -| Statistics | n, mean, std, CV, min, p25, median, p75, p95, max, IQR | median, min, max, mean, stdev, spread | do_bench: mean or quantiles. Timer: median, IQR. | +| Statistics | n, mean, std, min, p25, median, p75, p95, max, IQR | median, min, max, mean, stdev, spread | do_bench: mean or quantiles. Timer: median, IQR. | | Headline | Median | Median over attempts | do_bench: mean (default). Timer: median. | | TFLOP/s basis | Median | Median | User calculates | | Cross-process repeats | No | Yes (attempts, new process) | No | -| Clock capture | Before warmup and after the loop | Advice: lock clocks | None | - +| Clock capture | Sampled during and after the timed loop | Advice: lock clocks | None | ### Measured numbers (MI210, gfx90a) These runs used the default warmup (10) and `--iters 100`. Values are kernel @@ -819,21 +830,6 @@ The tool does not do these things yet: buffers with separate code. Both use the same timed loop. - Graph-replay timing (HIP or CUDA graph capture). Back-to-back timing is available with `--timing-block`. -- Rotating input buffers. `--cache-mode cold` controls the cache state, but - the rocKE runbook also advises rotating buffers for bandwidth work. -- Signed input distribution for all operations. The operands (data, filter - and incoming gradient) of a convolution with an fp16 output are uniform in - [-1, 1). With U[0, 1) data, a backward-weights sum over more than about - 262,000 terms passes the fp16 maximum (65504). Signed data lets the terms - cancel. All other floating-point inputs are uniform in [0, 1), because - BatchNorm variance inputs must not be negative. A tensor that also feeds a - non-convolution node stays in [0, 1). Convolutions with an fp32 or bf16 - output keep [0, 1): they do not overflow, and signed data puts fp32 outputs - near zero, where the fixed fp32 atol (1e-6) is smaller than the rounding - difference of two correct kernels. Signed convolution operands start at - tool version 0.3.0 (`tool.version` in the result file). Do not compare - fp16 convolution correctness results with results from earlier versions. - Signed data for other operations needs a role for each tensor first. - Validation of large fp16 SDPA backward gradients. On the six fp16 `aotriton_test_perf` graphs (B4, H48, D128, S 1024 to 4096), dK reaches about 440. Against the earlier AOTriton reference, the ASM SDPA engine diff --git a/docs/results-schema.md b/docs/results-schema.md index ab108c34..58e39328 100644 --- a/docs/results-schema.md +++ b/docs/results-schema.md @@ -69,8 +69,8 @@ the keys below. | `reference_precision` | string or null | `--reference-precision` (`float64` or `native`). `null` when validation is off. Each row's `correctness.reference_precision` gives the reference that the row met. | | `oracle` | bool | `--oracle`. | | `autotune` | bool | `--autotune`. | -| `benchmark_work_dir` | string | The work directory: `--benchmark-work-dir`, else the default. Without `--fresh-state`, runs use its kept selection state (`ootb/`, or `tuned/` for `--autotune` and for a true `HIPDNN_FORCE_BENCHMARKING` in the environment), so they can be warm. `--oracle` tuned runs always use `tuned/`. See [usage.md](usage.md#work-directory---benchmark-work-dir). | -| `fresh_state` | bool | `--fresh-state`: the command ran on a new, empty selection state, removed at exit. `--oracle` tuned runs still used the kept tuned state. | +| `benchmark_work_dir` | string | The work directory: `--benchmark-work-dir`, else the default. Without `--fresh-state`, runs use its kept selection state (`ootb/`, or `tuned/` for `--autotune` and for a true `HIPDNN_FORCE_BENCHMARKING` in the environment), so they can be warm. `--oracle` tuned runs use `tuned/`, or a fresh temporary state when `--fresh-state` is set. See [usage.md](usage.md#work-directory---benchmark-work-dir). | +| `fresh_state` | bool | `--fresh-state`: the command and its `--oracle` tuned children ran on new, empty selection state, removed at exit. | | `fast` | bool | `--fast`. Do not compare the numbers of a `--fast` run with a run without it; see [usage.md](usage.md#fast-mode---fast). | | `pytorch_sdpa_backend` | string or null | `--pytorch-sdpa-backend`. `null` unless `--runtime pytorch` or `--validate pytorch`. | | `pytorch_rocm_fa_library` | string or null | `--pytorch-rocm-fa-library`. `null` unless PyTorch is selected. | @@ -110,8 +110,8 @@ The CLI collects these values one time, at suite start. | `rocm_build_untested` | array of strings | The Quartz test suites (`rocm`, `pytorch`) that report no result for the GPU architecture of that ROCm build. `[]` when both suites tested it. `null` when setup read no Quartz `status.json` (for example `rocm-pin.json` or an unknown `--rocm-version`). See [setup.md](setup.md#rocm-nightly-selection). | | `python_version` | string | Python version. | | `torch_version` | string | `__version__` of `torch/version.py`. | -| `amdsmi_available` | bool | `true` when amdsmi loads. Without amdsmi, `gpu_hbm_gb`, `gpu_pcie_link`, `amdgpu_driver_version`, `gpu_power_cap_w`, `gpu_max_sclk_mhz`, `gpu_compute_partition` and all clock values are `null`. | -| `selection_env` | object or null | Kernel-selection environment variables at start: `HIPDNN_DISABLE_EXACT_ENGINE_CACHE`, `HIPDNN_CACHE_DIR`, `HIPDNN_DISABLE_CACHE`, `HIPDNN_FORCE_BENCHMARKING`, `MIOPEN_USER_DB_PATH`, `MIOPEN_CUSTOM_CACHE_DIR`. `null` unless `--oracle` or `--autotune` is set. | +| `amdsmi_available` | bool | `true` when amdsmi loads, initializes and exposes at least one processor handle. Without amdsmi or a mapped handle, `gpu_hbm_gb`, `gpu_pcie_link`, `amdgpu_driver_version`, `gpu_power_cap_w`, `gpu_max_sclk_mhz`, `gpu_compute_partition` and all clock values are `null`. | +| `selection_env` | object or null | Effective kernel-selection environment variables (`HIPDNN_CACHE_DIR`, `MIOPEN_USER_DB_PATH`, `HIPDNN_FORCE_BENCHMARKING`, `HIPDNN_DISABLE_CACHE`, `HIPDNN_DISABLE_EXACT_ENGINE_CACHE`, `MIOPEN_CUSTOM_CACHE_DIR`), each string or `null`. `null` unless `--oracle` or `--autotune`. | ## summary @@ -170,7 +170,7 @@ NaN or infinity has no `graph_id`, and its `status` is `error`. |Version|Change| |---|---| -|3|`graph_id` is the 64-character geometry hash. A rename or a `metadata` change keeps it.| +|3|`graph_id` is the 64-character geometry hash. A rename or a `metadata` change keeps it. Also adds `metrics.flops_formula_version`, `timing` (`launch_mode`, `requested_warmup_iters`, `timed_work_notes`), and in-run `metrics.clocks_after` telemetry (`in_run_samples`, `throttle_any`, `power_max_w`, `sclk_min_mhz`, `sclk_max_mhz`).| |2|`graph_id` is the first 12 hex characters of the SHA-256 of the whole canonical graph JSON, `name` and `metadata` included.| All other keys are the same in versions 2 and 3. One exception: files @@ -219,13 +219,13 @@ plan compare key by key. `oracle` adds the keys in [oracle](#oracle). | Key | Type | Meaning | |---|---|---| -| `build_ms` | float or null | CPU time of the plan build only: `create_execution_plan_ext`, `check_support` and `build_plans`. Every run first builds the OOTB plan once, untimed, so `build_ms` excludes one-time provider setup and cold file reads. `null` for PyTorch, which has no plan build. | -| `timing` | object | How the samples were measured. See [timing](#timing). | -| `kernel` | object or null | Device time per launch. See [stats](#stats). | -| `host` | object or null | Host submit time per launch (enqueue call only). See [stats](#stats). | +| `build_ms` | float or null | CPU time of the runtime's prepare/build phase: for hipDNN, `create_execution_plan_ext`, `check_support` and `build_plans` after priming; for rocKE variants, code-object load; for rocKE auto and AITER, initial prepare launch; `null` for PyTorch. Because phases differ across runtimes, do not compare `build_ms` across runtimes as one phase. | +| `timing` | object or null | How the samples were measured (`null` only on an untimed plan object). See [timing](#timing). | +| `kernel` | object or null | Device event span per launch (milliseconds). See [stats](#stats). | +| `host` | object or null | Host submit time per launch (Python callback wall time around enqueue, milliseconds). See [stats](#stats). | | `workspace_bytes` | int or null | Workspace that hipDNN reserved for the plan. `null` for PyTorch. | -| `tflops` | float or null | `metrics.flops / kernel.median_ms`, in 10^12 FLOP/s. | -| `gbps` | float or null | `metrics.io_bytes / kernel.median_ms`, in 10^9 bytes/s. | +| `tflops` | float or null | Graph-normalized rate `metrics.flops / (kernel.median_ms * 1e9)`, in decimal 10^12 FLOP/s. `null` when `metrics.flops` is `null` or `kernel.median_ms` is missing, non-finite, or `<= 0`; `0.0` when `metrics.flops == 0`. | +| `gbps` | float or null | Graph-footprint rate `metrics.io_bytes / (kernel.median_ms * 1e6)`, in decimal 10^9 bytes/s. `null` when `metrics.io_bytes` is `null` or `kernel.median_ms` is missing, non-finite, or `<= 0`; `0.0` when `metrics.io_bytes == 0`. | | `correctness` | object or null | See [correctness](#correctness). `null` when validation did not run. | | `dispatch` | object or null | PyTorch rows with `--pytorch-dispatch`: the SDPA backend and the GPU kernels that the plan ran. See [dispatch](#dispatch). `null` without `--pytorch-dispatch`, on hipDNN, rocKE and AITER rows, and when the capture failed (the row then has a warning). Files written before this key do not have it; read it as `null`. | @@ -233,18 +233,20 @@ plan compare key by key. `oracle` adds the keys in [oracle](#oracle). | Key | Type | Meaning | |---|---|---| -| `mode` | string | `staged` (stall-gated device span), `events` (event pair around each launch), or `block` (event pair around `timing_block` back-to-back launches; samples are `elapsed / timing_block`). | +| `mode` | string | `staged` (stall-gated device event span), `events` (event pair around each launch), or `block` (event pair around `timing_block` back-to-back launches; samples are `elapsed / timing_block`). | | `timer` | string | Event timer: `hip` (HIP events) or `torch` (`torch.cuda.Event`). | -| `warmup_iters` | int | Untimed launches that actually ran: priming (and, for PyTorch, the host-sync probe and its rerun) plus the discarded warmups. Always 1 or more. In `block` mode, also the `--warmup` launches before every sample, the discarded first sample included. See [methodology.md](methodology.md#warmup). | +| `warmup_iters` | int | Untimed launches that actually ran inside `measure()`: priming (and, for torch-driven runtimes — PyTorch, rocKE and AITER — the host-sync probe and its rerun) plus the discarded warmups. Always 1 or more. In `block` mode, also the `--warmup` launches before every sample, the discarded first sample included. See [methodology.md](methodology.md#warmup). | +| `requested_warmup_iters` | int or null | The requested `--warmup` value before adding priming/probe launches. | | `samples` | int | Number of timed samples behind `kernel` and `host` (`n` below). Equal to `--iters` unless `--min-time-ms` extends the loop. | -| `first_call_ms` | float | Wall time of the first launch plus a device sync. It includes one-time costs such as kernel compile and MIOpen find. | +| `first_call_ms` | float | Wall time of the first launch inside `measure()` plus a device sync. Includes one-time costs not already paid in `prepare()`. | | `capped` | bool | `true` when the `max_iters` cap (`max(10000, --iters)`) stopped the loop before `--min-time-ms` was reached. | -| `fallback_reason` | string or null | Why `staged` mode was not used. In `block` mode, set when the PyTorch `enqueue()` syncs with the host. | +| `fallback_reason` | string or null | Why `staged` mode was not used. In `block` mode, set when the enqueue syncs with the host. | +| `launch_mode` | string | `raw` (direct kernel launches) or `graph_replay` (internal HIP graph replay). | +| `timed_work_notes` | array of string or null | Non-core work included in the timed callback when known (for example `output_allocated`, `head_padding`, `triton_buffer_fills`, `split_kv_scratch`, `varlen_per_batch_copy`). | The cache mode and the launches per sample apply to the whole run, so they -are only in `run.config` (`cache_mode`, `timing_block`). See +are in `run.config` (`cache_mode`, `timing_block`). See [methodology.md](methodology.md) for the meaning of each mode. - ### stats `kernel` and `host` use the same object. All values are milliseconds. The @@ -266,29 +268,36 @@ file does not store them. | Key | Type | Meaning | |---|---|---| -| `flops` | int or null | Analytical FLOPs for one launch of the graph. For an SDPA node with variable lengths, it sums the counts over batches. Each count comes from the valid lengths of that batch. A paged graph uses the real KV lengths. `null` when any node has no FLOP formula, or lacks the tensor data its formula needs. A partial count is never reported. `tflops` is then `null` too. | -| `io_bytes` | int or null | Sum of the sizes of all non-virtual tensors, bytes. A tensor with valid lengths (SDPA with `seq_len`, `cu_seq_len` or ragged tensors, including a ragged Q/O over a paged K/V cache) counts only its valid elements. A non-ragged paged K, V, Q or O container counts its full size. | -| `clocks_after` | object or null | GPU clocks right after the default plan's timed loop. See [clocks](#clocks). | +| `flops` | int or null | Analytical graph FLOPs for one launch. For an SDPA node with variable lengths, it sums the counts over batches from valid lengths. A paged graph uses the real KV lengths; a packed paged graph with a diagonal mask and no length data returns `null`. `null` when any node has no FLOP formula or lacks tensor dims. A partial count is never reported. | +| `flops_formula_version` | int or null | Version of the analytical FLOP/IO formula set (`2`), or `null` when `flops` is `null`. | +| `io_bytes` | int or null | Graph-footprint bytes across all non-virtual tensors (not a hardware traffic lower bound). A tensor with valid lengths counts only its valid elements. Non-ragged paged K, V, Q and O containers count their full size. | +| `clocks_after` | object or null | GPU telemetry sampled during and right after the default plan's timed loop. See [clocks](#clocks). | `--no-metrics` sets these values and the plan `workspace_bytes`, `tflops` and `gbps` to `null`. #### clocks -amdsmi supplies these values. The object is `null` without amdsmi. A value is -`null` when the platform does not report it. The tool finds the amdsmi device -of the run by its PCI address, from PyTorch or from the loaded HIP runtime. If -that fails while `HIP_VISIBLE_DEVICES`, `ROCR_VISIBLE_DEVICES`, -`CUDA_VISIBLE_DEVICES` or `GPU_DEVICE_ORDINAL` is set, the object and the -amdsmi values of `environment` are `null`, and a warning gives the reason. +amdsmi supplies these values. The object is `null` without amdsmi or a mapped +device handle. A value is `null` when the platform does not report it. The +tool finds the amdsmi device of the run by its PCI address, from PyTorch or +from the loaded HIP runtime. If that fails while `HIP_VISIBLE_DEVICES`, +`ROCR_VISIBLE_DEVICES`, `CUDA_VISIBLE_DEVICES` or `GPU_DEVICE_ORDINAL` is set, +the object and the amdsmi values of `environment` are `null`, and a warning +gives the reason. | Key | Unit | |---|---| -| `sclk_mhz` | Shader clock, MHz. | -| `mclk_mhz` | Memory clock, MHz. | -| `power_w` | Socket power, W. | -| `temp_hotspot_c` | Hotspot temperature, degrees C. | -| `throttle_status` | Throttle status bit field. `0` means no throttle. | +| `sclk_mhz` | Post-loop shader clock, MHz. | +| `mclk_mhz` | Post-loop memory clock, MHz. | +| `power_w` | Post-loop socket power, W. | +| `temp_hotspot_c` | Post-loop hotspot temperature, degrees C. | +| `throttle_status` | Post-loop throttle status bit field. `0` means no throttle. | +| `in_run_samples` | Total telemetry samples collected during and after the timed loop. | +| `throttle_any` | `true` if any in-run or post-loop sample reported nonzero throttle status. | +| `power_max_w` | Peak socket power observed across in-run and post-loop samples, W. | +| `sclk_min_mhz` | Minimum shader clock observed across in-run and post-loop samples, MHz. | +| `sclk_max_mhz` | Maximum shader clock observed across in-run and post-loop samples, MHz. | ### dispatch @@ -303,7 +312,6 @@ tuned child process recorded the object with the tuned state, so tuning | `sdpa_backend` | string or null | The PyTorch SDPA backend that the launch called: `flash`, `efficient`, `math`, `cudnn` or `overrideable`. With `--pytorch-sdpa-backend default`, this is the choice of the PyTorch dispatcher. `null` when the launch called no PyTorch SDPA op: the graph has no SDPA node, or the tool computes the attention with its own formula (for example the backward formula of an ALiBi graph). When SDPA calls used different backends, the names are joined with `,` in the order of the first call. | | `fa_library` | string or null | The preferred ROCm Flash Attention library, `aotriton` or `ck`, when `sdpa_backend` includes `flash` on a ROCm build. `--pytorch-rocm-fa-library` sets it; else `torch.backends.cuda.preferred_rocm_fa_library()` gives it, and its `default` value is `aotriton`. PyTorch can use another library for an operation that the preferred library does not implement: `kernels` shows what ran. `null` otherwise. | | `kernels` | array of string or null | The distinct GPU kernel names of the launch, in the order of the first launch of each. Input fills, warmup launches, cache flushes, copies and the setup of the first call are not included. `null` when the profiler recorded no kernel (the row then has a warning). | - ### correctness | Key | Type | Meaning | @@ -320,19 +328,20 @@ tuned child process recorded the object with the tuned state, so tuning | `message` | string or null | Why `match` is `false` or `null`. | ### Row warnings - -`warnings` holds short notes. The console table shows the first note in the -`note` column. The runner adds these notes after the default plan's timed -loop. Paths are relative to the row: +`warnings` holds short notes. The console table shows the first non-noise note +in the `note` column (`noisy:` warnings are indicated by `*` on `kernel_med` +and printed in full under `-v`). The runner adds these notes after the default +plan's timed loop. Paths are relative to the row: | Note | Condition | |---|---| | `noisy: IQR x% of median` | `(ootb.kernel.p75_ms - ootb.kernel.p25_ms) / ootb.kernel.median_ms` is more than 0.05 and `ootb.timing.samples` is 10 or more. | | `outlier: max Nx median` | The slowest sample is more than 2 x `ootb.kernel.median_ms`. | +| `timer resolution: zero or nonpositive sample(s)` | One or more timed samples were `<= 0` ms. | | `capped at max_iters` | `ootb.timing.capped` is `true`. | | `host-bound: submit is x% of kernel_med in timing; ...` | `ootb.timing.mode` is `block` or `events`, and `ootb.host.median_ms` is 0.9 x `ootb.kernel.median_ms` or more. | | ` timing: ` | `ootb.timing.fallback_reason` is set. `` is `events` or `block` (`ootb.timing.mode`). stderr also shows the same text one time per process. | -| `throttled` | `metrics.clocks_after.throttle_status` is not 0. | +| `throttled` | `metrics.clocks_after.throttle_status` is nonzero or `metrics.clocks_after.throttle_any` is `true`. | | `profiling failed: ` | A profiling pass raised an exception. The timed values stay in the row. | | `dispatch not recorded: ` | PyTorch rows only. The [dispatch](#dispatch) capture failed (`ootb.dispatch` is `null`), or the profiler recorded no GPU kernel (`ootb.dispatch.kernels` is `null`). stderr also shows it one time per process. The timed values stay in the row. | | `tuned run: dispatch not recorded: ` | PyTorch rows with `--oracle` only. The same failure in the tuned child process, for `oracle.dispatch`. | diff --git a/docs/usage.md b/docs/usage.md index a4ad06fb..08cb9799 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -94,8 +94,8 @@ in the same way. | `--plugin-path PATHS` | see below | Plugin directory or plugin library file, or a comma list with one path for each `--engine` entry. A directory loads every plugin library in it; a file loads only that plugin. `--runtime rocke` needs directories. `--fast` needs one library file. | | `--autotune`, `--no-autotune` | off | Sets `HIPDNN_FORCE_BENCHMARKING=1`: each plan benchmarks its candidate kernels on the first execute and caches the winner in the tuned state of the work directory. See [Kernel selection](#kernel-selection---autotune). | | `--benchmark-work-dir PATH` | `$DNN_BENCH_WORKSPACE/work`, else `$XDG_CACHE_HOME/dnn-benchmark/work`, else `/dnn-benchmark-/work` | Work directory for the caches and the kernel-selection state. See [Work directory](#work-directory---benchmark-work-dir). Recorded as `run.config.benchmark_work_dir`. | -| `--fresh-state`, `--no-fresh-state` | off | Runs the command on a new, empty selection state in the system temporary directory, removed when the command ends. Use it for cold first-run numbers. See [Work directory](#work-directory---benchmark-work-dir). Recorded as `run.config.fresh_state`. | -| `--fast`, `--no-fast` | off | Runs every graph through one engine in this process: one hipDNN handle with only the plugin under test loaded, the engine primed once, and warm caches. Requires one `--engine` and a `--plugin-path` that names the plugin library file. See [Fast mode](#fast-mode---fast). | +| `--fresh-state`, `--no-fresh-state` | off | Runs the command (and its `--oracle` tuned children) on a new, empty selection state in the system temporary directory, removed when the command ends. Use it for cold first-run numbers. See [Work directory](#work-directory---benchmark-work-dir). Recorded as `run.config.fresh_state`. | +| `--fast`, `--no-fast` | off | Run every graph through one hipDNN engine in this process, keeping handle and plugin state across graphs. Requires one `--engine` and one plugin library `--plugin-path`. See [Fast mode](#fast-mode---fast). | | `--pytorch-sdpa-backend {default,flash,math,efficient,cudnn,overrideable}` | default | PyTorch SDPA category. A non-default category is strict: the graph fails if PyTorch cannot use it. GQA and MQA graphs use `enable_gqa` with `default` and `flash`. Other categories get K and V expanded once before timing. See [PyTorch SDPA setup](methodology.md#pytorch-sdpa-setup). SDPA backward graphs run the backward kernel of the selected category (`default`, `flash` or `efficient`); see [PyTorch SDPA backward](methodology.md#pytorch-sdpa-backward). | | `--pytorch-rocm-fa-library LIBRARY` | none | ROCm Flash Attention implementation for PyTorch, for example `aotriton`. Requires `--pytorch-sdpa-backend flash`. | | `--pytorch-dispatch`, `--no-pytorch-dispatch` | off | Records the SDPA backend and the GPU kernels of each PyTorch row in the plan's `dispatch` object. The tool runs one untimed `torch.profiler` launch after the timed loop. See [PyTorch dispatch record](#pytorch-dispatch-record). Recorded as `run.config.pytorch_dispatch`. | @@ -973,7 +973,8 @@ reads JSON only, not CSV. | `--by {best,ref,engine}` | best | `best`: the fastest usable engine row of each graph. `ref`: the reference rows. `engine`: the same engine in both files. | | `--metric {kernel,host}` | kernel | Compare kernel medians or submit medians. | | `--threshold PCT` | 5 | Regression threshold in percent. | -| `--allow-mismatch` | off | Compare also when `run.config.cache_mode` or `run.config.timing_block` is different. | +| `--allow-mismatch` | off | Compare also when `run.config` (`cache_mode`, `timing_block`), row timing/launch mode, or validation state differs. | +| `--strict-coverage` | off | Exit 1 if validation failures, incompatible modes, unknown spread, or missing graphs/rows reduce comparison coverage. | | `--csv` | off | Write CSV to stdout. Not with `--json`. | | `--json` | off | Write JSON to stdout. Not with `--csv`. | @@ -1003,32 +1004,38 @@ Rules: rows with `--by ref`. Rows join on runtime, engine ID and engine name. When a file has more than one row with the same key, the rows pair in order of appearance. -- `best` and `ref` select only rows with the verdict `passed`, `unchecked` - or `reference`. In `engine` mode, a `failed` row gets a speedup with the - label `A failed`, `B failed` or `A+B failed`, but it is not in the - geometric mean. Rows with `error` or `skipped` get no speedup. -- A row with a `null` median (the writer stores NaN and infinity as `null`) - gets no speedup and is not in the geometric mean. In `engine` mode the - pair label is `A no time` or `B no time`. `best` and `ref` skip the row; - when no row is left, the label is `no A row` or `no B row`. +- When validation ran on a graph (any engine row has verdict `passed` or + `failed`), `best` selects only `passed` rows and excludes `unchecked` rows. + When no passing row exists but a `failed` row exists, `best` reports + `A failed` / `B failed` rather than `no A/B row`. A nonpositive median never + preempts a positive-median sibling. +- Pairs whose kernel `timing.mode` (`staged` vs `events` vs `block`) or + `timing.launch_mode` (`raw` vs `graph_replay`) differ are excluded from the + geometric mean with label `mixed timing (...)` / `mixed launch (...)` unless + `--allow-mismatch` is given. +- Pairs where one side is `passed` and the other is `unchecked` are excluded + from the geometric mean with label `mixed validation (...)` unless + `--allow-mismatch` is given. +- A row with a `null` or nonpositive median, or missing quartile spread + (`p25_ms`/`p75_ms`), does not enter the geometric mean (`A/B no time` or + `unknown spread`). - A pair is `within noise` when the relative change is not more than - `max(threshold / 100, 2 * sqrt(r_A^2 + r_B^2))`, where `threshold` is the - `--threshold` percent and `r` is `(p75_ms - p25_ms) / median_ms` of the compared - metric in each file (`a_rel_iqr`, `b_rel_iqr` in the - `--json` and `--csv` output). A slower B beyond that limit is a - `REGRESSION`. A faster B is `faster`. + `max(threshold / 100, 2 * sqrt(r_A^2 + r_B^2))` (within floating-point + tolerance), where `threshold` is the `--threshold` percent and `r` is + `(p75_ms - p25_ms) / median_ms` of the compared metric in each file + (`a_rel_iqr`, `b_rel_iqr` in the `--json` and `--csv` output). A slower B + beyond that limit is a `REGRESSION`. A faster B is `faster`. - A different `run.config` value gives a warning on stderr. A different - `cache_mode` or `timing_block` stops the comparison, unless you give - `--allow-mismatch`. The error names the keys that differ. -- When no pair gets a speedup (for example, the files share no graph), the - tool writes `warning: no timings were compared` on stderr. The exit code - stays 0. - -Exit codes: 0 no regression, 1 one or more regressions, 2 usage error, a -file that cannot be read, has a different schema version or has malformed -rows (missing keys, wrong types), or a different `cache_mode` or -`timing_block` without `--allow-mismatch`. - + `cache_mode`, `timing_block`, or `input_recipe` stops the comparison, unless + you give `--allow-mismatch`. The error names the keys that differ. +- When no pair enters the geometric mean, the tool writes + `warning: no timings were compared` on stderr. + +Exit codes: 0 no regression (and full coverage if `--strict-coverage` is off), +1 one or more regressions (or lost coverage with `--strict-coverage`), 2 usage +error, a file that cannot be read, has a different schema version or has +malformed rows (missing keys, wrong types), or a gated `run.config` mismatch +without `--allow-mismatch`. ```bash dnn-benchmark -g 'graphs/*.json' -o base.json dnn-benchmark -g 'graphs/*.json' -o new.json diff --git a/setup_env.py b/setup_env.py index e26020c6..94b83bb9 100755 --- a/setup_env.py +++ b/setup_env.py @@ -2273,6 +2273,17 @@ def pull_provider_artifacts(self) -> None: ca_bundle = env.get("PIP_CERT") or env.get("SSL_CERT_FILE") if ca_bundle: env.setdefault("AWS_CA_BUNDLE", ca_bundle) + # Keep the DVC cache inside the writable workspace when no global DVC + # config dir is set, avoiding EROFS failures on read-only repo mounts. + if not env.get("DVC_GLOBAL_CONFIG_DIR"): + dvc_cfg_dir = self.workspace / "dvc-config" + dvc_cache = self.workspace / "dvc-cache" + dvc_cfg_dir.mkdir(parents=True, exist_ok=True) + dvc_cache.mkdir(parents=True, exist_ok=True) + (dvc_cfg_dir / "config").write_text( + f"[cache]\n dir = {dvc_cache}\n", encoding="utf-8" + ) + env["DVC_GLOBAL_CONFIG_DIR"] = str(dvc_cfg_dir) print(f"Pulling {len(targets)} provider descriptor artifact(s)...") run( [self.py, "-m", "dvc", "pull", *targets], diff --git a/src/dnn_benchmarking/cli/hipdnn_tuned_child.py b/src/dnn_benchmarking/cli/hipdnn_tuned_child.py index 6ec9721d..1223f502 100644 --- a/src/dnn_benchmarking/cli/hipdnn_tuned_child.py +++ b/src/dnn_benchmarking/cli/hipdnn_tuned_child.py @@ -48,6 +48,7 @@ from ..execution.suite_runner import set_plugin_path from ..execution.timing import StallFallbackError from ..graph.loader import GraphLoader +from ..graph.varlen import resolve_varlen_layouts def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace: @@ -117,9 +118,11 @@ def _run(args: argparse.Namespace) -> None: # hipDNN ignores a knob the engine does not expose; such a tuned run # re-measures the OOTB configuration. tuning_available = BENCHMARKING_KNOB in executor.engine_knob_ids(args.engine) + input_data = generate_input_data(tensor_infos, args.seed, graph_json) + tensor_infos = resolve_varlen_layouts(tensor_infos, graph_json, input_data) with BufferManager(tensor_infos) as bm: bm.allocate_all() - bm.load_input_data(generate_input_data(tensor_infos, args.seed, graph_json)) + bm.load_input_data(input_data) bm.zero_outputs() variant_pack = bm.create_variant_pack() m = executor.benchmark(handle, variant_pack) diff --git a/src/dnn_benchmarking/cli/main.py b/src/dnn_benchmarking/cli/main.py index f7ed3023..a983859e 100644 --- a/src/dnn_benchmarking/cli/main.py +++ b/src/dnn_benchmarking/cli/main.py @@ -248,6 +248,7 @@ def main(argv: Optional[Sequence[str]] = None, *, tuned_child: bool = False) -> reporter=reporter, tarball_source=tarball_source, argv=[sys.argv[0], *argv], + tuned_child=tuned_child, ) finally: for td in tmpdirs: diff --git a/src/dnn_benchmarking/cli/suite_runner_cli.py b/src/dnn_benchmarking/cli/suite_runner_cli.py index 47e6c0f5..b74ad103 100644 --- a/src/dnn_benchmarking/cli/suite_runner_cli.py +++ b/src/dnn_benchmarking/cli/suite_runner_cli.py @@ -24,6 +24,7 @@ SuiteConfig, ) from ..graph.loader import GraphLoader +from ..metrics.gpu_smi import is_amdsmi_available from ..metrics.machine_info import collect_environment_info from ..metrics.profiling_orchestrator import check_requested_tools from ..reporting.reporter import Reporter @@ -105,6 +106,8 @@ def run_suite_cli( reporter: Reporter, tarball_source: Optional[str] = None, argv: Optional[List[str]] = None, + *, + tuned_child: bool = False, ) -> int: """Build the config, run startup checks, run the suite; return the exit code. @@ -135,7 +138,6 @@ def run_suite_cli( reporter.error(message) if missing: return 2 - # The runtime's handles are destroyed when ``resources`` closes, on every # exit path, while the selection state that ``cli.main`` owns still # exists. @@ -144,12 +146,16 @@ def run_suite_cli( if config.fast: reporter.info("--fast: one process, one handle for every graph") _warn_ignored_options(config, reporter) - _apply_pytorch_environment(config, reporter) + _apply_pytorch_environment(config, reporter, tuned=tuned_child) if RuntimeName.HIPDNN in config.runtimes: _apply_tuning_environment(config, reporter) if config.oracle: _warn_oracle(reporter) + # Initialise amdsmi before start_runtime() imports torch: on ROCm, + # importing torch first can load a bundled libamd_smi that makes + # amdsmi_get_processor_handles() return empty. + is_amdsmi_available() try: run_graph = start_runtime(config, reporter, resources) except RuntimeStartupError as e: @@ -304,7 +310,11 @@ def write() -> bool: return False interrupted: Optional[int] = None - previous_sigterm = signal.signal(signal.SIGTERM, _raise_terminated) + previous_sigterm = ( + signal.signal(signal.SIGTERM, _raise_terminated) + if signal.getsignal(signal.SIGTERM) is not None + else None + ) disarm_watchdog = _arm_sigterm_watchdog() try: last_write = time.monotonic() @@ -324,14 +334,23 @@ def write() -> bool: interrupted = 143 finally: # A second Ctrl-C or SIGTERM must not lose the results on disk. - previous_sigint = signal.signal(signal.SIGINT, signal.SIG_IGN) - signal.signal(signal.SIGTERM, signal.SIG_IGN) + # Preserve non-Python native signal handlers (e.g. rocprofv3), for + # which getsignal() returns None and signal.signal(sig, None) raises. + previous_sigint = ( + signal.signal(signal.SIGINT, signal.SIG_IGN) + if signal.getsignal(signal.SIGINT) is not None + else None + ) + if previous_sigterm is not None: + signal.signal(signal.SIGTERM, signal.SIG_IGN) try: write_ok = write() finally: disarm_watchdog() - signal.signal(signal.SIGINT, previous_sigint) - signal.signal(signal.SIGTERM, previous_sigterm) + if previous_sigint is not None: + signal.signal(signal.SIGINT, previous_sigint) + if previous_sigterm is not None: + signal.signal(signal.SIGTERM, previous_sigterm) if interrupted is not None: where = ( @@ -414,7 +433,9 @@ def _warn_oracle(reporter: Reporter) -> None: ) -def _apply_pytorch_environment(config: SuiteConfig, reporter: Reporter) -> None: +def _apply_pytorch_environment( + config: SuiteConfig, reporter: Reporter, *, tuned: bool = False +) -> None: """Set PyTorch's kernel-selection controls when PyTorch is timed or used. Must run before the first PyTorch conv or SDPA call. A replaced shell @@ -425,15 +446,15 @@ def _apply_pytorch_environment(config: SuiteConfig, reporter: Reporter) -> None: or config.validation.provider is ReferenceProviderName.PYTORCH ): return - effective, replaced = apply_pytorch_environment() + effective, replaced = apply_pytorch_environment(tuned=tuned) for name, old in replaced.items(): reporter.warning( f"PyTorch kernel selection: {name}={old!r} from the environment is " f"replaced with {name}={effective[name]!r}" ) settings = ", ".join(f"{k}={v}" for k, v in effective.items()) - tuned = "; tuned runs use an isolated subprocess" if config.oracle else "" - reporter.info(f"PyTorch kernel selection: {settings}{tuned}") + tuned_note = "; tuned runs use an isolated subprocess" if config.oracle else "" + reporter.info(f"PyTorch kernel selection: {settings}{tuned_note}") def _report_selection_state(config: SuiteConfig, reporter: Reporter) -> None: diff --git a/src/dnn_benchmarking/common/pytorch_tuning.py b/src/dnn_benchmarking/common/pytorch_tuning.py index 185c3a2e..b440275b 100644 --- a/src/dnn_benchmarking/common/pytorch_tuning.py +++ b/src/dnn_benchmarking/common/pytorch_tuning.py @@ -20,8 +20,8 @@ from .work_dir import SelectionState -# Always on. Each value is read from the environment by PyTorch itself. -_DEFAULT_ENV = { +# Always on for both OOTB and tuned PyTorch. +_BASE_ENV = { # PyTorch's MIOpen conv path ignores channels-last strides unless this is # set, and instead transposes to NCHW inside the timed region. "PYTORCH_MIOPEN_SUGGEST_NHWC": "1", @@ -30,27 +30,42 @@ "TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL": "1", } +# Explicitly disable TunableOp on the OOTB path so inherited shell flags +# cannot silently tune the OOTB baseline. Tuned children preserve the +# TunableOp=1 variables set by tuned_subprocess_env(). +_OOTB_ONLY_ENV = { + "PYTORCH_TUNABLEOP_ENABLED": "0", + "PYTORCH_TUNABLEOP_TUNING": "0", +} + +_DEFAULT_ENV = {**_BASE_ENV, **_OOTB_ONLY_ENV} + ENV_NAMES = tuple(_DEFAULT_ENV) -def apply_pytorch_environment() -> Tuple[Dict[str, str], Dict[str, str]]: +def apply_pytorch_environment( + *, tuned: bool = False +) -> Tuple[Dict[str, str], Dict[str, str]]: """Set the always-on PyTorch ROCm controls. Forced, not defaulted: the CLI is the only control, so a value inherited - from the shell cannot change what PyTorch rows measure. + from the shell cannot change what PyTorch rows measure. When ``tuned`` is + True (inside ``cli.pytorch_tuned_child``), TunableOp variables set by + :func:`tuned_subprocess_env` are preserved rather than forced to ``0``. Must run before the first conv or SDPA call, because PyTorch caches these. Returns: The settings in effect, and the inherited value of each setting whose inherited value was different and is now replaced. """ + target = _BASE_ENV if tuned else _DEFAULT_ENV replaced = { name: os.environ[name] - for name, value in _DEFAULT_ENV.items() + for name, value in target.items() if os.environ.get(name, value) != value } - os.environ.update(_DEFAULT_ENV) - return dict(_DEFAULT_ENV), replaced + os.environ.update(target) + return dict(target), replaced def tuned_subprocess_env(state_dir: str, tuned: SelectionState) -> Dict[str, str]: diff --git a/src/dnn_benchmarking/config/benchmark_config.py b/src/dnn_benchmarking/config/benchmark_config.py index 20492714..d5660bbe 100644 --- a/src/dnn_benchmarking/config/benchmark_config.py +++ b/src/dnn_benchmarking/config/benchmark_config.py @@ -189,6 +189,7 @@ class TimingPolicy: cache_mode: str = "warm" timing_block: int = 1 stall_gate: bool = True + stall_fallback_reason: Optional[str] = None def __post_init__(self) -> None: """Validate loop bounds and the cache mode; messages name CLI flags.""" diff --git a/src/dnn_benchmarking/execution/aiter_executor.py b/src/dnn_benchmarking/execution/aiter_executor.py index 15ca4fee..3a8f5d7d 100644 --- a/src/dnn_benchmarking/execution/aiter_executor.py +++ b/src/dnn_benchmarking/execution/aiter_executor.py @@ -12,13 +12,15 @@ cache lookup otherwise. """ +import atexit import importlib.util import os import shutil +import stat import sys +import tempfile from pathlib import Path -from typing import Any, Callable, Dict, Iterator, Optional, Tuple - +from typing import Any, Callable, Dict, Iterator, Optional, Sequence, Tuple import torch from ..common import torch_support @@ -35,6 +37,47 @@ #: write the graph's O tensor. _ALLOCATES_OUTPUT = frozenset({"auto", "triton", "gluon"}) +#: Profiler env vars that can inject tool warnings into ``hipconfig --version`` +#: stdout when AITER probes the ROCm version under rocprofv3. +_PROFILER_ENV_VARS = ( + "LD_PRELOAD", + "ROCP_TOOL_LIBRARIES", + "HSA_TOOLS_LIB", + "ROCPROFILER_METRICS_PATH", + "ROCP_METRICS", +) +_hipconfig_shim_dir: Optional[tempfile.TemporaryDirectory[str]] = None + + +def _isolate_hipconfig_from_profiler() -> None: + """Prepend a clean ``hipconfig`` wrapper when profiler env vars are active. + + AITER runs ``hipconfig --version`` and parses its stdout. Under rocprofv3, + inherited tool variables can emit profiler messages onto stdout and break + version parsing. Stripping profiler vars for ``hipconfig`` only keeps + kernel profiling intact while isolating metadata probing. + """ + global _hipconfig_shim_dir + if sys.platform == "win32": + return + if not any(os.environ.get(v) for v in _PROFILER_ENV_VARS): + return + if _hipconfig_shim_dir is not None: + return + real_hipconfig = shutil.which("hipconfig") + if not real_hipconfig: + return + shim_dir = tempfile.TemporaryDirectory(prefix="dnn-bench-hipconfig-") + shim_path = Path(shim_dir.name) / "hipconfig" + unset_args = " ".join(f"-u {v}" for v in _PROFILER_ENV_VARS) + shim_path.write_text(f'#!/bin/sh\nexec env {unset_args} {real_hipconfig!r} "$@"\n') + shim_path.chmod( + shim_path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH + ) + _hipconfig_shim_dir = shim_dir + atexit.register(shim_dir.cleanup) + os.environ["PATH"] = os.pathsep.join([shim_dir.name, os.environ.get("PATH", "")]) + def prepare_aiter_environment() -> None: """Set the JIT directory and toolchain of AITER; call before ``import aiter``. @@ -54,6 +97,7 @@ def prepare_aiter_environment() -> None: interpreter's ``bin``, which holds the SDK's ``hipcc``, first on ``PATH``. The first ``import aiter`` compiles AITER's core module. """ + _isolate_hipconfig_from_profiler() if sys.prefix != sys.base_prefix: os.environ.setdefault("AITER_JIT_DIR", str(Path(sys.prefix) / "aiter-jit")) spec = importlib.util.find_spec("_rocm_sdk_devel") @@ -69,6 +113,7 @@ def prepare_aiter_environment() -> None: hipcc is None or Path(hipcc).parent != bin_dir ): os.environ["PATH"] = os.pathsep.join([str(bin_dir), os.environ.get("PATH", "")]) + _isolate_hipconfig_from_profiler() def _launch_for( @@ -178,13 +223,10 @@ def __init__( self._o: Optional[torch.Tensor] = None self.build_time_ms: Optional[float] = None - def prepare(self, tensors: Dict[int, torch.Tensor]) -> None: - """Bind the backend to the graph tensors and launch it once. - - Raises: - ExecutionError: The first launch fails (an AITER compile error, a - shape that the backend rejects, a HIP error). - """ + def _bind_tensors( + self, tensors: Dict[int, torch.Tensor] + ) -> Tuple[Launch, torch.Tensor]: + """Validate packed BSHD views and bind this backend to ``tensors``.""" p = self._problem # Graph order is [B, H, S, D] over packed BSHD memory; the permuted # views are the contiguous [B, S, H, D] tensors AITER reads. @@ -194,10 +236,21 @@ def prepare(self, tensors: Dict[int, torch.Tensor]) -> None: ) if not all(t.is_contiguous() for t in (q, k, v, o)): raise ExecutionError("AITER runtime needs packed BSHD Q/K/V/O tensors") + return _launch_for(self._backend, p, q, k, v, o), o + + def prepare(self, tensors: Dict[int, torch.Tensor]) -> None: + """Bind the backend to the graph tensors and launch it once. + + Raises: + ExecutionError: The first launch fails (an AITER compile error, a + shape that the backend rejects, a HIP error). + """ try: - launch = _launch_for(self._backend, p, q, k, v, o) + launch, o = self._bind_tensors(tensors) with Timer() as t: self._run_once(launch, o) + except ExecutionError: + raise except Exception as e: raise ExecutionError( f"AITER {self._backend.name} failed: {type(e).__name__}: {e}" @@ -222,6 +275,23 @@ def _run_once(self, launch: Launch, o: torch.Tensor) -> None: o.copy_(out) self._stream.synchronize() + def _timed_work_notes(self) -> list[str]: + """Extra work inside the timed AITER call beyond pure attention.""" + notes: list[str] = [] + name = self._backend.name + p = self._problem + if name in _ALLOCATES_OUTPUT: + notes.append("output_allocated") + if name in ("auto", "triton", "gluon") and ( + p.head_size_qk % 8 != 0 or p.head_size_v % 8 != 0 + ): + notes.append("head_padding") + if name == "triton": + notes.append("triton_buffer_fills") + if name == "native_splitkv": + notes.append("split_kv_scratch") + return notes + def benchmark(self) -> Measurement: """Time the backend per the executor's policy. @@ -242,6 +312,7 @@ def benchmark(self) -> Measurement: policy=self._policy, timer=self._timer, torch_stream=self._stream, + timed_work_notes=self._timed_work_notes() or None, ) finally: self._stream.synchronize() diff --git a/src/dnn_benchmarking/execution/aiter_sdpa.py b/src/dnn_benchmarking/execution/aiter_sdpa.py index cffd9325..f7eb425a 100644 --- a/src/dnn_benchmarking/execution/aiter_sdpa.py +++ b/src/dnn_benchmarking/execution/aiter_sdpa.py @@ -30,9 +30,9 @@ This module needs neither torch nor AITER at import time. """ +import os from dataclasses import dataclass from typing import Any, Dict, List, Tuple - from ..common.exceptions import UnsupportedGraphError from ..graph.tensor_info import TensorInfo from .sdpa_graph import DenseSdpa, dense_sdpa @@ -173,23 +173,78 @@ def _padded_head_sizes(p: DenseSdpa) -> Tuple[int, int]: return (-(-p.head_size_qk // 8) * 8, -(-p.head_size_v // 8) * 8) +def _ck_asm_asymmetric_decode_bug(p: DenseSdpa) -> bool: + """True for single-query GQA decode with Dqk != Dv. + + Pinned AITER CK (``mha_fwd_kernels.cu``) and ASM v3 (``asm_mha_fwd.cu``) + allocate/view O with ``Dv`` during the GQA-decode swap then reshape O + ending in ``Dqk``, failing with a shape mismatch when ``Dqk != Dv``. + """ + return ( + p.seqlen_q == 1 + and p.num_query_heads > p.num_kv_heads + and p.head_size_qk != p.head_size_v + ) + + +def _env_flag_nonzero(name: str) -> bool: + """Match AITER's ``int(os.getenv(name, "0")) != 0`` flag parsing.""" + raw = os.environ.get(name) + if raw is None: + return False + try: + return int(raw.strip()) != 0 + except ValueError: + return False + + +def _auto_routes_to_opus(p: DenseSdpa, device: AiterDevice) -> bool: + """True when ``aiter:auto`` dispatches to OPUS on this device and env.""" + if device.arch != "gfx950" or p.data_type != "bfloat16": + return False + heads = _padded_head_sizes(p) + if heads == (192, 128): + return not _env_flag_nonzero("AITER_DISABLE_FMHA_OPUS") + return ( + heads == (128, 128) + and _kv_extent_fits(p, 128) + and _env_flag_nonzero("AITER_ENABLE_FMHA_OPUS") + ) + + def _auto_runs(p: DenseSdpa, device: AiterDevice) -> bool: # flash_attn_func pads both head sizes to a multiple of 8. Above 256 no # v3, native, OPUS or FlyDSL path takes a dense fp16/bf16 problem, and the # Triton fallback runs only with CK disabled, so it ends in mha_fwd, which # checks head sizes <= 256 (csrc/py_itfs_ck/mha_fwd_kernels.cu). - return max(_padded_head_sizes(p)) <= _CK_MAX_HEAD_SIZE + if max(_padded_head_sizes(p)) > _CK_MAX_HEAD_SIZE: + return False + routes_opus = _auto_routes_to_opus(p, device) + # OPUS replaces explicit nonpositive scale with 1/sqrt(Dqk). + if routes_opus and p.scale <= 0: + return False + # When auto does not route to OPUS, asymmetric GQA decode hits CK/ASM's + # output reshape bug. + if _ck_asm_asymmetric_decode_bug(p) and not routes_opus: + return False + return True def _ck_runs(p: DenseSdpa, device: AiterDevice) -> bool: # mha_fwd takes head sizes that are multiples of 8 up to 256; this row # launches mha_fwd itself, without flash_attn_func's padding. heads = (p.head_size_qk, p.head_size_v) - return all(h % 8 == 0 for h in heads) and max(heads) <= _CK_MAX_HEAD_SIZE + return ( + all(h % 8 == 0 for h in heads) + and max(heads) <= _CK_MAX_HEAD_SIZE + and not _ck_asm_asymmetric_decode_bug(p) + ) def _asm_v3_runs(p: DenseSdpa, device: AiterDevice) -> bool: # AITER can_impl_fmha_v3_fwd, without the features this runtime rejects. + if _ck_asm_asymmetric_decode_bug(p): + return False heads = (p.head_size_qk, p.head_size_v) if heads == (192, 128): fits = _kv_extent_fits(p, 192) and _kv_extent_fits(p, 128) @@ -201,6 +256,9 @@ def _asm_v3_runs(p: DenseSdpa, device: AiterDevice) -> bool: def _opus_runs(p: DenseSdpa, device: AiterDevice) -> bool: # AITER can_impl_fmha_fwd_bf16_opus. aiter:auto runs the 128/128 kernel # only with AITER_ENABLE_FMHA_OPUS=1; this row runs it directly. + # OPUS replaces scale <= 0 with 1/sqrt(Dqk) instead of honoring the graph. + if p.scale <= 0: + return False heads = (p.head_size_qk, p.head_size_v) if heads == (128, 128): fits = _kv_extent_fits(p, 128) diff --git a/src/dnn_benchmarking/execution/correctness.py b/src/dnn_benchmarking/execution/correctness.py index 21189252..8cf8bbba 100644 --- a/src/dnn_benchmarking/execution/correctness.py +++ b/src/dnn_benchmarking/execution/correctness.py @@ -177,8 +177,12 @@ def check_correctness( ) rtol, atol = tolerance_for(config, ti) result = _compare_output(buffer_manager, ti, ref, rtol, atol) - if result is not None: - compared.append((ti.uid, rtol, atol, result)) + if result is None: + return mismatch( + config, + f"Engine did not produce output tensor UID {ti.uid}", + ) + compared.append((ti.uid, rtol, atol, result)) except (ValueError, RuntimeError, ExecutionError) as e: return mismatch(config, str(e)) diff --git a/src/dnn_benchmarking/execution/oracle.py b/src/dnn_benchmarking/execution/oracle.py index 78be644a..0aaf83d6 100644 --- a/src/dnn_benchmarking/execution/oracle.py +++ b/src/dnn_benchmarking/execution/oracle.py @@ -95,8 +95,17 @@ def _set_throughputs(oracle: OracleResult, row: ProviderEngineResult) -> None: ) -def _tuned_state(config: SuiteConfig) -> SelectionState: - """The tuned selection state that every tuned run shares, created.""" +def _tuned_state( + config: SuiteConfig, fresh_root: Optional[Path] = None +) -> SelectionState: + """The tuned selection state, created. + + When ``config.fresh_state`` is set and ``fresh_root`` is supplied, create + an isolated empty selection state inside the child's temporary directory + instead of reusing the persistent ``/tuned`` state. + """ + if config.fresh_state and fresh_root is not None: + return SelectionState.under(fresh_root / "tuned-state").create() return tuned_state(work_dir(config.benchmark_work_dir)).create() @@ -148,13 +157,15 @@ def _hipdnn_tuned_argv( TUNED_CHILD_ENV = {"HIPDNN_FORCE_BENCHMARKING": "1"} -def _hipdnn_tuned_env(config: SuiteConfig) -> Dict[str, str]: +def _hipdnn_tuned_env( + config: SuiteConfig, fresh_root: Optional[Path] = None +) -> Dict[str, str]: """The tuned child's environment: :data:`TUNED_CHILD_ENV` and the tuned selection state (``HIPDNN_CACHE_DIR``, ``MIOPEN_USER_DB_PATH``). An inherited ``HIPDNN_DISABLE_CACHE`` stays as it is.""" env = dict(os.environ) env.update(TUNED_CHILD_ENV) - env.update(_tuned_state(config).env()) + env.update(_tuned_state(config, fresh_root).env()) return env @@ -249,10 +260,15 @@ def _run_hipdnn_tuned_child( timeout_s = config.oracle_timeout_s or None release_flush_buffers() argv = _hipdnn_tuned_argv( - graph_path, engine_id, plugin_path, config, out_dir, save_outputs + graph_path, + engine_id, + plugin_path, + config, + out_dir, + save_outputs, ) try: - proc = run_capped(argv, timeout_s, env=_hipdnn_tuned_env(config)) + proc = run_capped(argv, timeout_s, env=_hipdnn_tuned_env(config, out_dir)) except subprocess.TimeoutExpired: raise RuntimeError( f"tuned hipDNN child timed out after {timeout_s} s (--oracle-timeout)" @@ -313,6 +329,8 @@ def _pytorch_tuned_argv( argv += ["--pytorch-rocm-fa-library", config.pytorch_rocm_fa_library] if config.pytorch_dispatch: argv.append("--pytorch-dispatch") + if config.fresh_state: + argv.append("--fresh-state") if not config.timing_policy.stall_gate: argv.append("--no-stall-gate") return argv @@ -340,7 +358,9 @@ def _run_pytorch_tuned_child(graph_path: Path, config: SuiteConfig) -> Dict[str, proc = run_capped( _pytorch_tuned_argv(graph_path, config, output), timeout_s, - env=tuned_subprocess_env(state_dir, _tuned_state(config)), + env=tuned_subprocess_env( + state_dir, _tuned_state(config, Path(state_dir)) + ), ) except subprocess.TimeoutExpired: raise RuntimeError( diff --git a/src/dnn_benchmarking/execution/pytorch_executor.py b/src/dnn_benchmarking/execution/pytorch_executor.py index e403c645..0a4f5ebc 100644 --- a/src/dnn_benchmarking/execution/pytorch_executor.py +++ b/src/dnn_benchmarking/execution/pytorch_executor.py @@ -116,13 +116,17 @@ def benchmark(self, tensors: Dict[int, torch.Tensor]) -> Measurement: # One stream context around the whole loop: entering it per iteration # would put its host cost inside the submit bracket. with torch.cuda.device(self._device), torch.cuda.stream(stream): - return measure( + measurement = measure( lambda: self._execute_graph(replay), stream=int(stream.cuda_stream), policy=self._policy, timer=self._timer, torch_stream=stream, ) + work_notes = getattr(replay, "timed_work_notes", None) + if work_notes: + measurement.timed_work_notes = list(work_notes) + return measurement def capture_dispatch(self) -> Dict[str, Any]: """Profile one untimed launch of the timed path; return what it ran. diff --git a/src/dnn_benchmarking/execution/pytorch_ops/_common.py b/src/dnn_benchmarking/execution/pytorch_ops/_common.py index 65962292..9f95598e 100644 --- a/src/dnn_benchmarking/execution/pytorch_ops/_common.py +++ b/src/dnn_benchmarking/execution/pytorch_ops/_common.py @@ -73,6 +73,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self._int_cache: Dict[int, List[int]] = {} self._derived_cache: Dict[Hashable, Any] = {} self.notes: List[str] = [] + self.timed_work_notes: List[str] = [] def host_ints(self, uid: int) -> List[int]: """Return tensor ``uid`` flattened to host ints, resolved once.""" @@ -98,6 +99,11 @@ def note(self, text: str) -> None: if text not in self.notes: self.notes.append(text) + def timed_work_note(self, text: str) -> None: + """Record extra runtime work that runs inside each timed iteration.""" + if text not in self.timed_work_notes: + self.timed_work_notes.append(text) + def _as_tuple( values: Optional[Sequence[Any]], default: Sequence[int] diff --git a/src/dnn_benchmarking/execution/pytorch_ops/handlers/sdpa.py b/src/dnn_benchmarking/execution/pytorch_ops/handlers/sdpa.py index 1df67e6c..548cb79a 100644 --- a/src/dnn_benchmarking/execution/pytorch_ops/handlers/sdpa.py +++ b/src/dnn_benchmarking/execution/pytorch_ops/handlers/sdpa.py @@ -1537,6 +1537,8 @@ def run_varlen( v: torch.Tensor, ) -> None: s = setup(tensors, "varlen", lambda: prepare_varlen(tensors, q, k, v)) + if isinstance(tensors, ReplayTensors): + tensors.timed_work_note("varlen_per_batch_copy") for batch in s.batches: if s.sink is not None: o, stats = _sink_attention( diff --git a/src/dnn_benchmarking/execution/rocke_executor.py b/src/dnn_benchmarking/execution/rocke_executor.py index 982f0867..767bba02 100644 --- a/src/dnn_benchmarking/execution/rocke_executor.py +++ b/src/dnn_benchmarking/execution/rocke_executor.py @@ -10,8 +10,9 @@ """ import hashlib +import inspect from pathlib import Path -from typing import Any, Callable, Dict, NamedTuple, Optional, Tuple +from typing import Any, Callable, Dict, NamedTuple, Optional, Sequence, Tuple import torch @@ -203,14 +204,12 @@ def __init__( ) self._stream = torch.cuda.default_stream(self._device) self._launch: Optional[Callable[[], None]] = None + self._launch_mode: str = "raw" self.build_time_ms: Optional[float] = None - def prepare(self, tensors: Dict[int, torch.Tensor]) -> None: - """Build the kernel and bind it to the graph tensors. - - Raises: - ExecutionError: The build, the load or the first launch fails. - """ + def _bshd_views( + self, tensors: Dict[int, torch.Tensor] + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: p = self._problem # Graph order is [B, H, S, D] over packed BSHD memory; the permuted # views are the contiguous [B, S, H, D] tensors rocKE kernels read. @@ -220,6 +219,15 @@ def prepare(self, tensors: Dict[int, torch.Tensor]) -> None: ) if not all(t.is_contiguous() for t in (q, k, v, o)): raise ExecutionError("rocKE runtime needs packed BSHD Q/K/V/O tensors") + return q, k, v, o + + def prepare(self, tensors: Dict[int, torch.Tensor]) -> None: + """Build the kernel and bind it to the graph tensors. + + Raises: + ExecutionError: The build, the load or the first launch fails. + """ + q, k, v, o = self._bshd_views(tensors) try: if isinstance(self._kernel, CatalogKernel): self._prepare_catalog(q, k, v, o) @@ -270,6 +278,19 @@ def _prepare_auto(self, q, k, v, o) -> None: # scalar correctness kernel when the tiled path declines. backend = "tiled" if kernel.path == "2d" else "3d" stream = int(self._stream.cuda_stream) + extra_kwargs: Dict[str, Any] = {} + try: + sig = inspect.signature(run_unified_attention_torch) + if "use_graph" in sig.parameters: + # Force raw launches so rocKE auto matches hipDNN, catalog + # variants and other runtimes instead of silently timing + # internal HIP graph replay. + extra_kwargs["use_graph"] = False + self._launch_mode = "raw" + else: + self._launch_mode = "graph_replay" + except (TypeError, ValueError): + self._launch_mode = "raw" def launch() -> None: run_unified_attention_torch( @@ -285,6 +306,7 @@ def launch() -> None: softcap=0.0, backend=backend, stream=stream, + **extra_kwargs, ) with Timer() as t, torch.cuda.device(self._device): @@ -317,10 +339,28 @@ def benchmark(self) -> Measurement: policy=self._policy, timer=self._timer, torch_stream=self._stream, + after_iteration=self._release_retained, + launch_mode=self._launch_mode, ) finally: self._release() + def _release_retained(self) -> None: + """Drop rocKE's retained launch arguments after an external stream sync. + + ``timing.measure`` synchronizes the stop event on every iteration; + clearing the completed bucket outside the timed bracket keeps eager 3D + scratch memory O(1) instead of accumulating across all iterations. + """ + import rocke.runtime as rr + + stream = int(self._stream.cuda_stream) + release = getattr(rr, "release_retained_for_stream", None) + if callable(release): + release(stream) + else: + rr.wait_stream_and_release(stream) + def _release(self) -> None: """Drain the stream and free the kernel arguments rocKE retains.""" from rocke.runtime import wait_stream_and_release diff --git a/src/dnn_benchmarking/execution/suite_runner.py b/src/dnn_benchmarking/execution/suite_runner.py index 76a60afd..04f5e4cd 100644 --- a/src/dnn_benchmarking/execution/suite_runner.py +++ b/src/dnn_benchmarking/execution/suite_runner.py @@ -39,10 +39,18 @@ ) from ..execution.buffer_manager import BufferManager, generate_input_data from ..execution.executor import Executor -from ..execution.timing import Measurement, StallFallbackError, Timer +from ..execution.timing import ( + MIXED_MODE_RERUN_REASON, + STALL_RERUN_REASON, + Measurement, + MixedModeFallbackError, + StallFallbackError, + Timer, +) from ..graph.tensor_info import TensorInfo from ..graph.varlen import resolve_varlen_layouts from ..metrics import GpuSmiProbe, compute_flops, compute_io_bytes, derive_throughputs +from ..metrics.analytical import ANALYTICAL_FORMULA_VERSION from ..metrics._diagnostic import warn_once from ..reporting.reporter import Reporter from ..reporting.statistics import ( @@ -174,8 +182,9 @@ def _report_row( def _throttled(after: Optional[Dict[str, Any]]) -> bool: # Only the SMU's throttle status counts: sclk alone moves with DPM demand # (1700 -> 1430 MHz over a 3-iteration loop on an idle MI210), so a lower - # after-sample is not evidence of throttling. - return bool(after and after.get("throttle_status")) + # after-sample is not evidence of throttling. Check both the post-loop + # status and any in-run sample. + return bool(after and (after.get("throttle_status") or after.get("throttle_any"))) def _measure_row( @@ -186,10 +195,14 @@ def _measure_row( """Run the timed loop and record stats, provenance, clocks and warnings.""" basic = ctx.config.metrics.basic probe = GpuSmiProbe() if basic else None - m = benchmark() - if probe is not None: - row.clocks_after = probe.clocks() - + if probe is not None and hasattr(probe, "sample_during"): + with probe.sample_during() as telemetry: + m = benchmark() + row.clocks_after = telemetry or None + else: + m = benchmark() + if probe is not None: + row.clocks_after = probe.clocks() kernel = BenchmarkStats.from_timings(m.kernel_ms) host = BenchmarkStats.from_timings(m.host_ms) row.ootb.gpu_kernel_stats = kernel @@ -214,6 +227,9 @@ def _measure_row( if probe is not None: row.analytical_flops = ctx.flops + row.flops_formula_version = ( + ANALYTICAL_FORMULA_VERSION if ctx.flops is not None else None + ) row.analytical_io_bytes = ctx.io_bytes row.ootb.derived_tflops_per_s, row.ootb.derived_gbytes_per_s = ( derive_throughputs(ctx.flops, ctx.io_bytes, kernel.median_ms) @@ -509,11 +525,10 @@ def _time_pytorch_row( # engine rows are graded against come from repeatable SDPA. with pytorch_ops.reference_sdpa_pass(): executor.execute_once(tensors) - # A profiling child allocates its own VRAM, so profiled runs - # keep host-only references (and DeviceBuffer I/O). - outputs = _pytorch_reference_outputs_from_buffer( - bm, keep_device=not config.metrics.opt_in_pass_requested - ) + # Keep GPU reference outputs on the device during OOTB timing + # so profiling flags do not change the parent buffer backend. + # Device references are freed before any profiling child runs. + outputs = _pytorch_reference_outputs_from_buffer(bm, keep_device=True) stage = "post" if role == "reference": row.warnings = (row.warnings or []) + pytorch_ops.get_reference_warnings( @@ -659,8 +674,6 @@ def run_single_provider_engine( plugin_path=plugin_path, config=config, ) - if config.metrics.opt_in_pass_requested: - _run_profiling(row, ctx, engine_id, engine_name, plugin_path) return row @@ -858,14 +871,10 @@ def _use_float64_reference( _release_torch_cache() _note_native_reference(ctx, row, error or "no outputs") return False - keep_device = not ctx.config.metrics.opt_in_pass_requested for ref in outputs.values(): if ref.device_data is None: continue - if keep_device: - ref.device_data = _owned(ref.device_data) - else: - ref.data, ref.device_data = ref.host_data(), None + ref.device_data = _owned(ref.device_data) ctx.reference_outputs = outputs # Return the float64 temporaries and the replaced native outputs to the # device before the engine rows allocate. @@ -929,17 +938,40 @@ def _with_stall_fallback( graph instead of mixing staged and events rows. Each rerun row records the reason in ``timing.fallback_reason`` and ``warnings``. """ + mixed_mode = False try: return run(config) except StallFallbackError as e: reason = str(e) + mixed_mode = isinstance(e, MixedModeFallbackError) # Rerun outside the except block: the caught exception's traceback holds # every frame of the first attempt, with its inputs, references, device # buffers and workspaces, until the block exits. reporter.warning(f"{reason}; remeasuring every row of this graph without stalling") unstalled = copy.copy(config) - unstalled.timing_policy = replace(config.timing_policy, stall_gate=False) - return run(unstalled) + unstalled.timing_policy = replace( + config.timing_policy, + stall_gate=False, + stall_fallback_reason=( + MIXED_MODE_RERUN_REASON if mixed_mode else STALL_RERUN_REASON + ), + ) + result = run(unstalled) + if mixed_mode: + for row in result.results: + for plan in (row.ootb, row.oracle): + if ( + plan is not None + and plan.timing is not None + and plan.timing.fallback_reason == STALL_RERUN_REASON + ): + plan.timing.fallback_reason = MIXED_MODE_RERUN_REASON + if row.warnings: + row.warnings = [ + w.replace(STALL_RERUN_REASON, MIXED_MODE_RERUN_REASON) + for w in row.warnings + ] + return result @dataclass @@ -1052,6 +1084,31 @@ def labelled(plan: RuntimePlan, text: str) -> str: for plan in plans: graph.results.extend(plan.rows(ctx)) + if config.timing_policy.stall_gate and config.timing_policy.timing_block == 1: + modes = { + r.ootb.timing.mode + for r in graph.results + if r.status == "success" and r.ootb.timing is not None + } + if "staged" in modes and "events" in modes: + raise MixedModeFallbackError( + "mixed staged and events timing within this graph" + ) + if ctx is not None and config.metrics.opt_in_pass_requested: + # Free GPU reference tensors before launching external profiler + # children so profiling never shifts parent buffer allocation during + # OOTB timing and children still get full VRAM. + ctx.reference_outputs = None + _release_torch_cache() + for row in graph.results: + if ( + row.runtime == "hipdnn" + and row.role == "engine" + and row.status == "success" + and isinstance(row.engine_id, int) + ): + plugin = Path(row.plugin_path) if row.plugin_path else None + _run_profiling(row, ctx, row.engine_id, row.engine_name or "", plugin) return graph diff --git a/src/dnn_benchmarking/execution/timing.py b/src/dnn_benchmarking/execution/timing.py index 6a82f2cb..12020d9b 100644 --- a/src/dnn_benchmarking/execution/timing.py +++ b/src/dnn_benchmarking/execution/timing.py @@ -29,7 +29,7 @@ import warnings from dataclasses import dataclass from types import TracebackType -from typing import Any, Callable, Dict, List, Optional, Tuple, Type +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type from ..common.exceptions import ExecutionError from ..config.benchmark_config import TimingPolicy @@ -67,6 +67,9 @@ class Measurement: capped: bool = False fallback_reason: Optional[str] = None timing_block: int = 1 + launch_mode: str = "raw" + requested_warmup_iters: Optional[int] = None + timed_work_notes: Optional[List[str]] = None class StallFallbackError(RuntimeError): @@ -75,10 +78,19 @@ class StallFallbackError(RuntimeError): whole graph without stalling (see ``suite_runner``).""" +class MixedModeFallbackError(StallFallbackError): + """A row in this graph fell back to events mode while another ran staged, + so the suite runner remeasures the whole graph uniformly in events mode.""" + + #: ``fallback_reason`` of a row that a stall-gate failure remeasured unstalled. STALL_RERUN_REASON = "stall gate failed in this graph; every row remeasured unstalled" - +#: ``fallback_reason`` of a row remeasured in events mode because another row +#: on the same graph fell back to events mode. +MIXED_MODE_RERUN_REASON = ( + "another row in this graph fell back to events; every row remeasured in events mode" +) _HIP_API = ("HipEvent", "hip_get_device_count", "hip_device_synchronize") _STAGED_HIP_API = ("HipStallGate", "hip_can_use_stream_wait_value") @@ -347,6 +359,9 @@ def measure( policy: TimingPolicy, timer: str = "hip", torch_stream: Any = None, + after_iteration: Optional[Callable[[], None]] = None, + launch_mode: str = "raw", + timed_work_notes: Optional[Sequence[str]] = None, ) -> Measurement: """Prime, warm up, then time ``enqueue`` per ``policy`` (a ``TimingPolicy``). @@ -371,19 +386,26 @@ def measure( policy: Warmup/iteration counts, time budget, and cache mode. timer: ``hip`` or ``torch`` timer. torch_stream: torch.cuda.Stream the enqueue runs on, if torch-driven. + after_iteration: Optional callback invoked after every synchronized + iteration outside the timed bracket (e.g. releasing rocKE's + retained eager scratch). + launch_mode: ``"raw"`` or ``"graph_replay"`` launch provenance. + timed_work_notes: Extra non-core work inside the timed closure. Raises: ExecutionError: If the cold-cache flush buffer cannot be allocated. - StallFallbackError: If stall-gated timing failed (see ``StalledRegionTimer``); the caller remeasures without stalling. RuntimeError: If the timer is unavailable. """ events = EventTimer(timer, stream, torch_stream) + notes = list(timed_work_notes) if timed_work_notes else None t0 = time.perf_counter() enqueue() device_sync(timer) first_call_ms = (time.perf_counter() - t0) * 1000.0 + if after_iteration is not None: + after_iteration() primed = 1 reason: Optional[str] = None if torch_stream is not None: @@ -391,18 +413,28 @@ def measure( # A detected sync costs a second (unchecked) enqueue. primed += 1 if reason is None else 2 device_sync(timer) + if after_iteration is not None: + after_iteration() if policy.timing_block > 1: return _measure_blocks( - enqueue, events, policy, timer, first_call_ms, primed, reason + enqueue, + events, + policy, + timer, + first_call_ms, + primed, + reason, + after_iteration=after_iteration, + launch_mode=launch_mode, + timed_work_notes=notes, ) - staged: Optional[StalledRegionTimer] = None if reason is None: if timer != "hip": reason = "staged timing requires the hip timer" elif not policy.stall_gate: - reason = STALL_RERUN_REASON + reason = policy.stall_fallback_reason or STALL_RERUN_REASON else: reason = _staged_unavailable_reason() if reason is None: @@ -418,13 +450,17 @@ def iteration() -> Tuple[float, float]: if cold: _flush_cache(timer) if staged is not None: - return staged.measure(enqueue) - events.start() - t0 = time.perf_counter() - enqueue() - t1 = time.perf_counter() - events.stop() - return (t1 - t0) * 1000.0, events.elapsed_ms() + sample = staged.measure(enqueue) + else: + events.start() + t0 = time.perf_counter() + enqueue() + t1 = time.perf_counter() + events.stop() + sample = (t1 - t0) * 1000.0, events.elapsed_ms() + if after_iteration is not None: + after_iteration() + return sample for _ in range(primed, policy.warmup_iters): iteration() @@ -452,6 +488,9 @@ def iteration() -> Tuple[float, float]: first_call_ms=first_call_ms, capped=capped, fallback_reason=reason, + launch_mode=launch_mode, + requested_warmup_iters=policy.warmup_iters, + timed_work_notes=notes, ) @@ -463,6 +502,10 @@ def _measure_blocks( first_call_ms: float, untimed: int, host_sync: Optional[str], + *, + after_iteration: Optional[Callable[[], None]] = None, + launch_mode: str = "raw", + timed_work_notes: Optional[List[str]] = None, ) -> Measurement: """rocKE block timing (``time_launches`` / Solera ``measure()``). @@ -491,6 +534,8 @@ def _measure_blocks( enqueue() untimed += policy.warmup_iters device_sync(timer) + if after_iteration is not None: + after_iteration() events.start() t0 = time.perf_counter() for _ in range(block): @@ -498,6 +543,8 @@ def _measure_blocks( t1 = time.perf_counter() events.stop() kernel = events.elapsed_ms() / block + if after_iteration is not None: + after_iteration() if discard_first: discard_first = False continue @@ -516,6 +563,9 @@ def _measure_blocks( capped=capped, fallback_reason=host_sync, timing_block=block, + launch_mode=launch_mode, + requested_warmup_iters=policy.warmup_iters, + timed_work_notes=timed_work_notes, ) diff --git a/src/dnn_benchmarking/metrics/analytical/__init__.py b/src/dnn_benchmarking/metrics/analytical/__init__.py index 50e6c704..8bfeb039 100644 --- a/src/dnn_benchmarking/metrics/analytical/__init__.py +++ b/src/dnn_benchmarking/metrics/analytical/__init__.py @@ -63,12 +63,16 @@ """ from functools import partial +import math from typing import Any, Dict, Iterable, List, Optional, Tuple from ...graph.tensor_info import TensorInfo from ...graph.varlen import read_input_ints from .._diagnostic import warn_once from ._common import tensor_lookup + +#: Version of the analytical graph-rate formulas emitted into result files. +ANALYTICAL_FORMULA_VERSION = 2 from .conv import conv_dgrad_flops, conv_fwd_flops, conv_wgrad_flops from .elementwise import ( block_scale_dequantize_flops, @@ -182,14 +186,13 @@ def compute_flops( def compute_io_bytes(tensor_infos: Iterable[TensorInfo]) -> int: - """Sum bytes of all non-virtual tensors (inputs + outputs + weights). - - Virtual tensors are intermediate buffers that hipDNN may allocate - inside a fused kernel and never materialise to global memory, so - they are excluded. Uses :attr:`TensorInfo.size_bytes`, which already - accounts for non-contiguous strides. A tensor with a variable-length - layout counts only its valid elements (:attr:`TensorInfo.valid_elements`), - because the padding is never read or written. + """Sum graph-footprint bytes of all non-virtual tensors (inputs + outputs + weights). + + This is a graph-level footprint metric, not a lower bound on hardware HBM + traffic: strided spans may include unreferenced holes, paged KV caches + count full pool storage, and non-ragged padded outputs may still be written + to memory. Virtual tensors are excluded. A tensor with a variable-length + layout counts its valid elements (:attr:`TensorInfo.valid_elements`). """ total = 0 for ti in tensor_infos: @@ -207,27 +210,28 @@ def derive_throughputs( io_bytes: Optional[int], kernel_median_ms: Optional[float], ) -> Tuple[Optional[float], Optional[float]]: - """Derive TFLOPs/s and GB/s from totals + median kernel time. + """Derive graph-normalized TFLOP/s and GB/s from totals + median event span. - The median is the denominator the rocKE benchmark pipeline - (Solera -> Strata) uses for its TFLOP/s, so the two sources are - comparable for the same shape. It is also robust to a single noisy - iteration, unlike the mean. - - Args: - flops: Total analytical FLOPs (or ``None``). - io_bytes: Total non-virtual tensor bytes (or ``None``). - kernel_median_ms: Median GPU kernel time in ms (or ``None``). + Units use decimal SI prefixes: + ``tflops = flops / (kernel_median_ms / 1000) / 1e12 = flops / (kernel_median_ms * 1e9)`` + ``gbps = io_bytes / (kernel_median_ms / 1000) / 1e9 = io_bytes / (kernel_median_ms * 1e6)`` Returns: - ``(tflops_per_s, gbytes_per_s)`` — either component is ``None`` - when its inputs are missing or zero. + ``(tflops_per_s, gbytes_per_s)`` — either component is ``None`` when + ``kernel_median_ms`` is missing/non-finite/non-positive or its + numerator is ``None``; a known-zero numerator yields ``0.0``. """ - if not kernel_median_ms or kernel_median_ms <= 0: + if ( + kernel_median_ms is None + or not math.isfinite(kernel_median_ms) + or kernel_median_ms <= 0 + ): return None, None seconds = kernel_median_ms / 1000.0 - tflops = (flops / seconds / 1e12) if flops else None - gbytes = (io_bytes / seconds / 1e9) if io_bytes else None + tflops = (flops / seconds / 1e12) if flops is not None and flops >= 0 else None + gbytes = ( + (io_bytes / seconds / 1e9) if io_bytes is not None and io_bytes >= 0 else None + ) return tflops, gbytes diff --git a/src/dnn_benchmarking/metrics/analytical/_common.py b/src/dnn_benchmarking/metrics/analytical/_common.py index a315c51b..766aff0c 100644 --- a/src/dnn_benchmarking/metrics/analytical/_common.py +++ b/src/dnn_benchmarking/metrics/analytical/_common.py @@ -10,11 +10,11 @@ from typing import Any, Dict, Optional -def tensor_dim_product(tensor: Dict[str, Any]) -> int: - """Return the product of a tensor's dims, or 0 when dims are missing.""" - dims = tensor.get("dims") or [] - if not dims: - return 0 +def tensor_dim_product(tensor: Dict[str, Any]) -> Optional[int]: + """Return the product of a tensor's dims, 1 for a scalar ``[]``, or None when dims are absent.""" + dims = tensor.get("dims") + if dims is None: + return None n = 1 for d in dims: n *= int(d) diff --git a/src/dnn_benchmarking/metrics/analytical/reduction.py b/src/dnn_benchmarking/metrics/analytical/reduction.py index e9ceabc4..49044ace 100644 --- a/src/dnn_benchmarking/metrics/analytical/reduction.py +++ b/src/dnn_benchmarking/metrics/analytical/reduction.py @@ -59,6 +59,8 @@ def resample_bwd_flops( if not dy: return None elems = tensor_dim_product(dy) + if elems is None: + return None if str(node_param(node, "resample_mode", "")).upper() == "MAXPOOL": return elems window = _window_size(node) diff --git a/src/dnn_benchmarking/metrics/analytical/sdpa.py b/src/dnn_benchmarking/metrics/analytical/sdpa.py index c0f74adb..afd80043 100644 --- a/src/dnn_benchmarking/metrics/analytical/sdpa.py +++ b/src/dnn_benchmarking/metrics/analytical/sdpa.py @@ -188,6 +188,15 @@ def _attention_terms( _nonmasked_pairs(lq, lkv, *band) for lq, lkv in zip(lengths[0], lengths[1]) ) return num_q_heads * pairs, int(q_dims[-1]), int(v_dims[-1]) + # Packed paged Q across multiple sequences with a diagonal mask has no + # unique pair count without per-sequence lengths (F-4). + if ( + len(table_dims) >= 2 + and int(table_dims[0]) > 1 + and int(q_dims[0]) == 1 + and (band[0] is not None or band[1] is not None) + ): + return None pairs = _nonmasked_pairs(q_seqlen, kv_seqlen, *band) return rows * pairs, int(q_dims[-1]), int(v_dims[-1]) diff --git a/src/dnn_benchmarking/metrics/gpu_smi.py b/src/dnn_benchmarking/metrics/gpu_smi.py index 4279b0be..f64c88e4 100644 --- a/src/dnn_benchmarking/metrics/gpu_smi.py +++ b/src/dnn_benchmarking/metrics/gpu_smi.py @@ -25,8 +25,9 @@ import functools import os import sys -from typing import Any, Callable, Dict, Optional, Tuple - +import threading +from contextlib import contextmanager +from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple from ..common import torch_support from ._diagnostic import warn_once @@ -73,8 +74,14 @@ def _amdsmi() -> Optional[Any]: def is_amdsmi_available() -> bool: - """True when amdsmi imports and initialises.""" - return _amdsmi() is not None + """True when amdsmi imports, initialises and exposes at least one handle.""" + amdsmi = _amdsmi() + if amdsmi is None: + return False + try: + return bool(amdsmi.amdsmi_get_processor_handles()) + except Exception: + return False def _hip_device_bdf(device_index: Optional[int]) -> Optional[str]: @@ -135,8 +142,8 @@ def _hip_runtime_bdf(device_index: Optional[int]) -> Optional[str]: @functools.lru_cache(maxsize=None) -def _handle_for(device_index: Optional[int]) -> Optional[Any]: - """amdsmi processor handle for a HIP device index (None = current).""" +def _handle_for_bdf(device_index: Optional[int], bdf: Optional[str]) -> Optional[Any]: + """Cached amdsmi handle lookup keyed by ``(device_index, hip_bdf)``.""" amdsmi = _amdsmi() if amdsmi is None: return None @@ -146,7 +153,6 @@ def _handle_for(device_index: Optional[int]) -> Optional[Any]: return None if not handles: return None - bdf = _hip_device_bdf(device_index) if bdf is not None: for handle in handles: # amdsmi reports "dddd:bb:dd.f"; torch exposes no function number. @@ -166,6 +172,25 @@ def _handle_for(device_index: Optional[int]) -> Optional[Any]: return handles[index] if index < len(handles) else None +def _handle_for(device_index: Optional[int]) -> Optional[Any]: + """amdsmi processor handle for a HIP device index (None = current). + + Resolves the HIP PCI address dynamically so an early pre-HIP lookup + cannot pin a stale fallback once HIP or torch initialises. + """ + if _amdsmi() is None: + return None + bdf = _hip_device_bdf(device_index) + handle = _handle_for_bdf(device_index, bdf) + if handle is None and bdf is None: + # Do not cache an unresolved pre-init None permanently. + _handle_for_bdf.cache_clear() + return handle + + +_handle_for.cache_clear = _handle_for_bdf.cache_clear # type: ignore[attr-defined] + + class GpuSmiProbe: """amdsmi queries for one GPU (HIP device index; None = current device).""" @@ -209,6 +234,58 @@ def power() -> Any: ), } + @contextmanager + def sample_during(self, interval_s: float = 0.1) -> Iterator[Dict[str, Any]]: + """Sample clocks, power and throttle status during a timed loop. + + Yields a mutable dict populated on exit with the post-loop reading + (same keys as :meth:`clocks`) plus in-run aggregates: + ``in_run_samples``, ``throttle_any``, ``power_max_w``, + ``sclk_min_mhz``, and ``sclk_max_mhz``. When amdsmi or the device is + unavailable the yielded dict stays empty. + """ + result: Dict[str, Any] = {} + if self._handle is None: + yield result + return + samples: List[Dict[str, Any]] = [] + stop = threading.Event() + + def poll() -> None: + while not stop.wait(interval_s): + reading = self.clocks() + if reading is not None: + samples.append(reading) + + thread = threading.Thread(target=poll, daemon=True) + thread.start() + try: + yield result + finally: + stop.set() + thread.join(timeout=1.0) + after = self.clocks() + if after is not None: + samples.append(after) + result.update(after) + if samples: + powers = [s["power_w"] for s in samples if s.get("power_w") is not None] + sclks = [ + s["sclk_mhz"] for s in samples if s.get("sclk_mhz") is not None + ] + throttles = [ + s["throttle_status"] + for s in samples + if s.get("throttle_status") is not None + ] + result["in_run_samples"] = len(samples) + result["throttle_any"] = ( + any(bool(t) for t in throttles) if throttles else None + ) + result["power_max_w"] = max(powers) if powers else None + result["sclk_min_mhz"] = min(sclks) if sclks else None + result["sclk_max_mhz"] = max(sclks) if sclks else None + def identity(self) -> Tuple[Optional[str], Optional[str]]: """``(target_graphics_version, market_name)``; None where unreported. diff --git a/src/dnn_benchmarking/reporting/compare.py b/src/dnn_benchmarking/reporting/compare.py index 1cc32e55..af3c624e 100644 --- a/src/dnn_benchmarking/reporting/compare.py +++ b/src/dnn_benchmarking/reporting/compare.py @@ -10,8 +10,9 @@ slower than that. Failed/error rows never enter the geomean. Exit codes: 0 no regression (stderr warns when no timings were compared), -1 regression beyond threshold, 2 usage error, unreadable or incompatible input -(run.config cache_mode or timing_block differs, unless ``--allow-mismatch``). +1 regression beyond threshold (or coverage loss under ``--strict-coverage``), +2 usage error, unreadable or incompatible input (run.config ``cache_mode`` +or ``timing_block`` differs, unless ``--allow-mismatch``). """ import argparse @@ -78,7 +79,14 @@ def _parser() -> argparse.ArgumentParser: p.add_argument( "--allow-mismatch", action="store_true", - help="compare even when run.config cache_mode or timing_block differs", + help="compare even when timing mode, cache_mode, timing_block " + "or validation state differs", + ) + p.add_argument( + "--strict-coverage", + action="store_true", + help="exit 1 if validation failures, incompatible modes, or missing " + "rows drop comparison coverage", ) fmt = p.add_mutually_exclusive_group() fmt.add_argument("--csv", action="store_true", help="CSV on stdout") @@ -91,28 +99,71 @@ def _engine_label(row: Dict[str, Any]) -> str: return e["name"] or e["id"] or row["runtime"] +def _timing_meta( + row: Dict[str, Any], +) -> Tuple[Optional[str], Optional[str], Optional[str]]: + """Return ``(mode, timer, launch_mode)`` from a row's ``ootb.timing``.""" + timing = (row.get("ootb") or {}).get("timing") or {} + if not isinstance(timing, dict): + return None, None, None + return timing.get("mode"), timing.get("timer"), timing.get("launch_mode") + + def _stat(row: Dict[str, Any], metric: str) -> Tuple[Optional[float], Optional[float]]: s = (row["ootb"] or {}).get(metric) if row["verdict"] in ("error", "skipped") or not s: return None, None # The writer stores NaN/inf as null; a null median leaves the pair unusable. median, p25, p75 = s["median_ms"], s["p25_ms"], s["p75_ms"] - if median is None or p25 is None or p75 is None or median <= 0: + if median is None or not math.isfinite(median): + return None, None + if median <= 0: + return median, None + if p25 is None or p75 is None or not math.isfinite(p25) or not math.isfinite(p75): return median, None return median, (p75 - p25) / median def _pick(graph: Dict[str, Any], by: str, metric: str) -> Optional[Dict[str, Any]]: - """Row to compare for ``best``/``ref``: fastest usable row of that role.""" + """Row to compare for ``best``/``ref``: fastest usable positive-median row. + + When validation ran on this graph (any engine row has verdict ``passed`` + or ``failed``), ``unchecked`` engine rows are excluded so they cannot beat + or replace validated rows. Nonpositive medians never preempt a usable + sibling. When no passing row exists but a failed row does, the failed row + is returned so the pair reports validation failure rather than a missing row. + """ role = "reference" if by == "ref" else "engine" - usable = [ - r - for r in graph["results"] - if r["role"] == role - and r["verdict"] in _USABLE - and _stat(r, metric)[0] is not None + role_rows = [r for r in graph["results"] if r["role"] == role] + if role == "engine" and any( + r["verdict"] in ("passed", "failed") for r in role_rows + ): + allowed = ("passed",) + else: + allowed = _USABLE + + eligible = [r for r in role_rows if r["verdict"] in allowed] + positive = [ + r for r in eligible if (ms := _stat(r, metric)[0]) is not None and ms > 0 ] - return min(usable, key=lambda r: _stat(r, metric)[0], default=None) + if positive: + return min(positive, key=lambda r: _stat(r, metric)[0]) + + nonpositive = [r for r in eligible if _stat(r, metric)[0] is not None] + if nonpositive: + return nonpositive[0] + + failed = [r for r in role_rows if r["verdict"] == "failed"] + if failed: + timed_failed = [ + r for r in failed if (ms := _stat(r, metric)[0]) is not None and ms > 0 + ] + return ( + min(timed_failed, key=lambda r: _stat(r, metric)[0]) + if timed_failed + else failed[0] + ) + return None def _keyed(rows: List[Dict[str, Any]]) -> Dict[Tuple[Any, ...], Dict[str, Any]]: @@ -134,6 +185,8 @@ def _pair( metric: str, threshold: float, kind: str = "engine", + *, + allow_mismatch: bool = False, ) -> Pair: a_ms, a_iqr = _stat(ra, metric) if ra else (None, None) b_ms, b_iqr = _stat(rb, metric) if rb else (None, None) @@ -156,22 +209,43 @@ def _pair( pair.label = pair.label or f"no {side} row" elif ms is None or ms <= 0: why = ( - row["verdict"] if row["verdict"] in ("error", "skipped") else "no time" + row["verdict"] + if row["verdict"] in ("error", "skipped", "failed") + else "no time" ) pair.label = pair.label or f"{side} {why}" if pair.label: return pair - pair.speedup = a_ms / b_ms failed = [s for s, r in (("A", ra), ("B", rb)) if r["verdict"] == "failed"] if failed: + pair.speedup = a_ms / b_ms pair.label = f"{'+'.join(failed)} failed" return pair + if metric == "kernel" and not allow_mismatch: + mode_a, _, launch_a = _timing_meta(ra) + mode_b, _, launch_b = _timing_meta(rb) + if mode_a is not None and mode_b is not None and mode_a != mode_b: + pair.label = f"mixed timing ({mode_a} vs {mode_b})" + return pair + if launch_a is not None and launch_b is not None and launch_a != launch_b: + pair.label = f"mixed launch ({launch_a} vs {launch_b})" + return pair + if not allow_mismatch and {ra["verdict"], rb["verdict"]} == {"passed", "unchecked"}: + pair.speedup = a_ms / b_ms + pair.label = f"mixed validation (A {ra['verdict']}, B {rb['verdict']})" + return pair + pair.speedup = a_ms / b_ms + if a_iqr is None or b_iqr is None: + pair.label = "unknown spread" + return pair pair.in_geomean = True # hypot: the two runs' spreads are independent. 2x: heuristic margin so a # median shift inside the combined IQR (ordinary run-to-run drift) is noise. - band = max(threshold / 100.0, 2.0 * math.hypot(a_iqr or 0.0, b_iqr or 0.0)) + band = max(threshold / 100.0, 2.0 * math.hypot(a_iqr, b_iqr)) change = b_ms / a_ms - 1.0 # positive = B slower - if abs(change) <= band: + # 1e-12 avoids false regressions when exact decimal ratios (e.g. 2.1/2.0-1) + # round slightly above the threshold in binary floating point. + if abs(change) <= band + 1e-12: pair.label = "within noise" else: pair.label = "REGRESSION" if change > 0 else "faster" @@ -240,24 +314,58 @@ def compare( by: str = "best", metric: str = "kernel", threshold: float = 5.0, + allow_mismatch: bool = False, ) -> Dict[str, Any]: """Compare two loaded v2 or v3 documents; returns the JSON-shaped report.""" matched, only_a, only_b, ambiguous = _match_graphs(a, b, _join_key(a, b)) pairs: List[Pair] = [] + timer_mismatches = 0 for ga, gb in matched: name = ga["graph_name"] if by != "engine": ra, rb = _pick(ga, by, metric), _pick(gb, by, metric) kind = "ref" if by == "ref" else "engine" - pairs.append(_pair(name, ra, rb, metric, threshold, kind)) + if ra is not None and rb is not None and metric == "kernel": + _, ta, _ = _timing_meta(ra) + _, tb, _ = _timing_meta(rb) + if ta is not None and tb is not None and ta != tb: + timer_mismatches += 1 + pairs.append( + _pair( + name, + ra, + rb, + metric, + threshold, + kind, + allow_mismatch=allow_mismatch, + ) + ) continue # Reference rows are compared with --by ref, not here. rows_b = _keyed([r for r in gb["results"] if r["role"] == "engine"]) engines_a = [r for r in ga["results"] if r["role"] == "engine"] for key, ra in _keyed(engines_a).items(): - pairs.append(_pair(name, ra, rows_b.pop(key, None), metric, threshold)) - pairs.extend(_pair(name, None, rb, metric, threshold) for rb in rows_b.values()) + rb = rows_b.pop(key, None) + if rb is not None and metric == "kernel": + _, ta, _ = _timing_meta(ra) + _, tb, _ = _timing_meta(rb) + if ta is not None and tb is not None and ta != tb: + timer_mismatches += 1 + pairs.append( + _pair(name, ra, rb, metric, threshold, allow_mismatch=allow_mismatch) + ) + pairs.extend( + _pair(name, None, rb, metric, threshold, allow_mismatch=allow_mismatch) + for rb in rows_b.values() + ) ratios = [p.speedup for p in pairs if p.in_geomean] + validation_failures = sum(p.label.endswith(" failed") for p in pairs) + mixed_timing = sum( + p.label.startswith(("mixed timing", "mixed launch")) for p in pairs + ) + mixed_validation = sum(p.label.startswith("mixed validation") for p in pairs) + unknown_spread = sum(p.label == "unknown spread" for p in pairs) return { "convention": CONVENTION, "by": by, @@ -269,6 +377,11 @@ def compare( "ambiguous": ambiguous, "geomean_speedup": geometric_mean(ratios) if ratios else None, "regressions": sum(p.label == "REGRESSION" for p in pairs), + "validation_failures": validation_failures, + "mixed_timing": mixed_timing, + "mixed_validation": mixed_validation, + "unknown_spread": unknown_spread, + "timer_mismatches": timer_mismatches, } @@ -344,10 +457,20 @@ def _print_table( print(_clip(line, width), file=out) geo = report["geomean_speedup"] n = sum(p["in_geomean"] for p in pairs) + extras = [] + if report.get("validation_failures"): + extras.append(f"{report['validation_failures']} validation failure(s)") + if report.get("mixed_timing"): + extras.append(f"{report['mixed_timing']} mixed-timing") + if report.get("mixed_validation"): + extras.append(f"{report['mixed_validation']} mixed-validation") + if report.get("unknown_spread"): + extras.append(f"{report['unknown_spread']} unknown-spread") + extra_str = ("; " + ", ".join(extras)) if extras else "" footer = ( f"{len(pairs)} pairs, {n} in geomean; geomean B speedup vs A: " f"{'-' if geo is None else f'{geo:.3f}x'}; " - f"{report['regressions']} regression(s); " + f"{report['regressions']} regression(s){extra_str}; " f"graphs only in A: {len(report['only_in_a'])}, " f"graphs only in B: {len(report['only_in_b'])}" ) @@ -436,8 +559,46 @@ def main(argv: List[str]) -> int: ) return 2 try: - report = compare(a, b, by=args.by, metric=args.metric, threshold=args.threshold) - if all(p["speedup"] is None for p in report["pairs"]): + report = compare( + a, + b, + by=args.by, + metric=args.metric, + threshold=args.threshold, + allow_mismatch=args.allow_mismatch, + ) + if report["mixed_timing"]: + print( + f"warning: {report['mixed_timing']} pair(s) excluded from geomean " + "due to mixed timing or launch mode (pass --allow-mismatch to pool)", + file=sys.stderr, + ) + if report["mixed_validation"]: + print( + f"warning: {report['mixed_validation']} pair(s) excluded from geomean " + "due to mixed validation state (passed vs unchecked; pass " + "--allow-mismatch to pool)", + file=sys.stderr, + ) + if report["validation_failures"]: + print( + f"warning: {report['validation_failures']} pair(s) excluded due to " + "validation failure", + file=sys.stderr, + ) + if report["unknown_spread"]: + print( + f"warning: {report['unknown_spread']} pair(s) excluded due to " + "missing quartile spread", + file=sys.stderr, + ) + if report["timer_mismatches"]: + print( + f"warning: {report['timer_mismatches']} pair(s) used different " + "event timers (e.g. hip vs torch)", + file=sys.stderr, + ) + if all(not p["in_geomean"] for p in report["pairs"]): print("warning: no timings were compared", file=sys.stderr) if report["ambiguous"]: print( @@ -460,4 +621,11 @@ def main(argv: List[str]) -> int: except (KeyError, TypeError, ValueError) as e: # malformed input, not a regression print(f"error: {e}", file=sys.stderr) return 2 - return 1 if report["regressions"] else 0 + coverage_lost = bool( + report["only_in_a"] + or report["only_in_b"] + or any(not p["in_geomean"] for p in report["pairs"]) + ) + if report["regressions"] or (args.strict_coverage and coverage_lost): + return 1 + return 0 diff --git a/src/dnn_benchmarking/reporting/reporter.py b/src/dnn_benchmarking/reporting/reporter.py index d04f5216..6703e3e8 100644 --- a/src/dnn_benchmarking/reporting/reporter.py +++ b/src/dnn_benchmarking/reporting/reporter.py @@ -9,6 +9,7 @@ written, including ``warn_once`` diagnostics routed through the sink. """ +import math import shutil import sys import textwrap @@ -86,6 +87,8 @@ def _unit(ms: float) -> Tuple[float, str]: def _fmt_time(ms: float) -> str: """Per-launch time with an automatic µs/ms/s unit.""" + if not math.isfinite(ms): + return "-" scale, suffix = _unit(ms) digits = 2 if suffix == "µs" else 3 return f"{ms * scale:.{digits}f} {suffix}" @@ -93,12 +96,20 @@ def _fmt_time(ms: float) -> str: def _fmt_duration(ms: float) -> str: """Wall-clock cost (setup, build): 2 significant digits below 10 ms.""" + if not math.isfinite(ms): + return "-" if ms < 10: return f"{ms:.2g} ms" return f"{ms:.0f} ms" if ms < 1e3 else f"{ms / 1e3:.1f} s" -def _iqr_pct(stats: BenchmarkStats) -> float: +def _iqr_pct(stats: BenchmarkStats) -> Optional[float]: + if ( + not math.isfinite(stats.median_ms) + or not math.isfinite(stats.p25_ms) + or not math.isfinite(stats.p75_ms) + ): + return None return stats.iqr_ms / stats.median_ms * 100 if stats.median_ms > 0 else 0.0 @@ -281,7 +292,9 @@ def _outcome(pe: ProviderEngineResult) -> str: parts.append(_fmt_time(kernel.median_ms)) detail = [] if kernel is not None: - detail.append(f"iqr {_iqr_pct(kernel):.1f}%") + iqr = _iqr_pct(kernel) + if iqr is not None: + detail.append(f"iqr {iqr:.1f}%") if pe.ootb.timing is not None: detail.append(f"setup {_fmt_duration(pe.ootb.timing.first_call_ms)}") elif pe.elapsed_time_ms: @@ -410,34 +423,45 @@ def print_graph_table(self, graph_result: GraphResult) -> None: return rows = gr.results - best_candidates = [ - pe.ootb.gpu_kernel_stats.median_ms + has_validated_engine = any( + pe.role == "engine" and pe.verdict in ("passed", "failed") for pe in rows + ) + eligible_verdicts = ( + ("passed",) if has_validated_engine else ("passed", "unchecked") + ) + eligible_rows = [ + pe for pe in rows if pe.role == "engine" - and pe.verdict in ("passed", "unchecked") + and pe.verdict in eligible_verdicts and pe.ootb.gpu_kernel_stats is not None + and math.isfinite(pe.ootb.gpu_kernel_stats.median_ms) and pe.ootb.gpu_kernel_stats.median_ms > 0 ] - best = min(best_candidates) if best_candidates else None + eligible_modes = { + (pe.ootb.timing.mode, pe.ootb.timing.launch_mode) + for pe in eligible_rows + if pe.ootb.timing is not None + } + best = ( + min(pe.ootb.gpu_kernel_stats.median_ms for pe in eligible_rows) + if eligible_rows and len(eligible_modes) <= 1 + else None + ) with_oracle = any(pe.oracle is not None or pe.oracle_error for pe in rows) + def iqr_cell(pe: ProviderEngineResult) -> str: + if pe.ootb.gpu_kernel_stats is None: + return "-" + pct = _iqr_pct(pe.ootb.gpu_kernel_stats) + return "-" if pct is None else f"{pct:.1f}" + # (header, right-aligned, cells) columns: List[Tuple[str, bool, List[str]]] = [ ("engine", False, [_display_name(pe) for pe in rows]), ("verdict", False, [pe.verdict for pe in rows]), ("kernel_med", True, [self._kernel_cell(pe) for pe in rows]), - ( - "iqr%", - True, - [ - ( - "-" - if pe.ootb.gpu_kernel_stats is None - else f"{_iqr_pct(pe.ootb.gpu_kernel_stats):.1f}" - ) - for pe in rows - ], - ), + ("iqr%", True, [iqr_cell(pe) for pe in rows]), ( "submit", True, @@ -463,7 +487,11 @@ def print_graph_table(self, graph_result: GraphResult) -> None: for pe in rows ], ), - ("vs_best", True, [self._vs_best_cell(pe, best) for pe in rows]), + ( + "vs_best", + True, + [self._vs_best_cell(pe, best, eligible_verdicts) for pe in rows], + ), ] if with_oracle: columns.append(("oracle", True, [self._oracle_cell(pe) for pe in rows])) @@ -503,23 +531,35 @@ def print_graph_table(self, graph_result: GraphResult) -> None: @staticmethod def _legend(rows: Sequence[ProviderEngineResult]) -> str: - timing = next( - (pe.ootb.timing for pe in rows if pe.ootb.timing is not None), None - ) - how = ( - f" ({_TIMING_MODE_LABEL.get(timing.mode, timing.mode)})" - if timing is not None - else "" + pairs = list( + dict.fromkeys( + (pe.ootb.timing.mode, pe.ootb.timing.launch_mode) + for pe in rows + if pe.ootb.timing is not None + ) ) + if len(pairs) > 1: + distinct_launches = {lm for _, lm in pairs} + labels = [ + f"{m}/{lm}" if len(distinct_launches) > 1 else m for m, lm in pairs + ] + how = f" (mixed modes: {', '.join(labels)})" + elif len(pairs) == 1: + mode, launch = pairs[0] + label = _TIMING_MODE_LABEL.get(mode, mode) + how = f" ({label}, {launch})" if launch != "raw" else f" ({label})" + else: + how = "" return ( - f" kernel_med = median device time per launch{how}; " - "submit = host enqueue time; vs_best = best median / row median; * = noisy" + f" kernel_med = median device event span per launch{how}; " + "submit = host enqueue time; tflops/gbps = graph-normalized rates; " + "vs_best = best median / row median; * = noisy or outlier" ) @staticmethod def _kernel_cell(pe: ProviderEngineResult) -> str: stats = pe.ootb.gpu_kernel_stats - if stats is None: + if stats is None or not math.isfinite(stats.median_ms): return "- " # Always one marker column so the numbers stay aligned. return _fmt_time(stats.median_ms) + ("*" if noise_warnings(stats) else " ") @@ -531,14 +571,19 @@ def _tflops_cell(pe: ProviderEngineResult) -> str: return f"{pe.ootb.derived_tflops_per_s:.2f}" @staticmethod - def _vs_best_cell(pe: ProviderEngineResult, best: Optional[float]) -> str: + def _vs_best_cell( + pe: ProviderEngineResult, + best: Optional[float], + eligible_verdicts: Tuple[str, ...] = ("passed", "unchecked"), + ) -> str: if pe.role == "reference": return "ref" stats = pe.ootb.gpu_kernel_stats if ( best is None - or pe.verdict not in ("passed", "unchecked") # best_candidates' rule + or pe.verdict not in eligible_verdicts or stats is None + or not math.isfinite(stats.median_ms) or stats.median_ms <= 0 ): return "-" @@ -598,11 +643,20 @@ def add(key: str, text: str) -> None: if pe.ootb.timing is not None: t = pe.ootb.timing text = f"{t.mode}/{t.timer}, warmup {t.warmup_iters}" + if ( + t.requested_warmup_iters is not None + and t.requested_warmup_iters != t.warmup_iters + ): + text += f" (requested {t.requested_warmup_iters})" + if t.launch_mode != "raw": + text += f", launch {t.launch_mode}" if t.capped: text += ", capped at max iters" if t.fallback_reason: text += f", fallback: {t.fallback_reason}" add("timing", text) + if t.timed_work_notes: + add("timed work", ", ".join(t.timed_work_notes)) lines.extend(self._stats_lines(pe)) clocks = self._clocks_text(pe.clocks_after) if clocks: diff --git a/src/dnn_benchmarking/reporting/statistics.py b/src/dnn_benchmarking/reporting/statistics.py index 83a653fc..b7e5a66d 100644 --- a/src/dnn_benchmarking/reporting/statistics.py +++ b/src/dnn_benchmarking/reporting/statistics.py @@ -3,6 +3,7 @@ """Benchmark statistics calculation.""" +import math from dataclasses import asdict, dataclass from typing import Any, Dict, List, Optional, Sequence @@ -95,17 +96,31 @@ def to_dict(self) -> Dict[str, Any]: def noise_warnings(stats: BenchmarkStats) -> List[str]: - """Flag dispersion a reader should know about; samples are never trimmed. + """Flag dispersion and resolution hazards; samples are never trimmed. Noise uses the robust spread IQR/median, so a few slow samples (reported by the outlier flag) do not mark an otherwise tight distribution noisy. """ warnings: List[str] = [] - if stats.n >= 10 and stats.median_ms > 0: + if not math.isfinite(stats.median_ms): + warnings.append("non-finite median timing") + return warnings + if math.isfinite(stats.min_ms) and stats.min_ms <= 0: + warnings.append("timer resolution: zero or nonpositive sample(s)") + if ( + stats.n >= 10 + and stats.median_ms > 0 + and math.isfinite(stats.p25_ms) + and math.isfinite(stats.p75_ms) + ): spread = stats.iqr_ms / stats.median_ms if spread > NOISY_IQR: warnings.append(f"noisy: IQR {spread:.1%} of median") - if stats.median_ms > 0 and stats.max_ms > OUTLIER_RATIO * stats.median_ms: + if ( + stats.median_ms > 0 + and math.isfinite(stats.max_ms) + and stats.max_ms > OUTLIER_RATIO * stats.median_ms + ): warnings.append(f"outlier: max {stats.max_ms / stats.median_ms:.1f}x median") return warnings @@ -113,19 +128,24 @@ def noise_warnings(stats: BenchmarkStats) -> List[str]: def host_bound_warnings( kernel: BenchmarkStats, host: BenchmarkStats, mode: str ) -> List[str]: - """Flag a kernel time that the host submit time sets. + """Flag a kernel event span that the host submit time sets. Block and events spans include the host's launch gaps. The staged span starts after the host has enqueued the work, so it is never host-bound. """ - if mode == "staged" or kernel.median_ms <= 0: + if ( + mode == "staged" + or not math.isfinite(kernel.median_ms) + or not math.isfinite(host.median_ms) + or kernel.median_ms <= 0 + ): return [] ratio = host.median_ms / kernel.median_ms if ratio < HOST_BOUND: return [] return [ f"host-bound: submit is {ratio:.0%} of kernel_med in {mode} timing; " - "the time is launch cost, not device time" + "the span likely reflects host launch overhead rather than pure device time" ] @@ -146,10 +166,14 @@ class TimingInfo: first_call_ms: float capped: bool = False fallback_reason: Optional[str] = None + launch_mode: str = "raw" + requested_warmup_iters: Optional[int] = None + timed_work_notes: Optional[List[str]] = None @classmethod def from_measurement(cls, m: Any) -> "TimingInfo": """Copy the provenance fields of an ``execution.timing.Measurement``.""" + notes = getattr(m, "timed_work_notes", None) return cls( mode=m.mode, timer=m.timer, @@ -158,6 +182,9 @@ def from_measurement(cls, m: Any) -> "TimingInfo": first_call_ms=m.first_call_ms, capped=m.capped, fallback_reason=m.fallback_reason, + launch_mode=getattr(m, "launch_mode", "raw"), + requested_warmup_iters=getattr(m, "requested_warmup_iters", None), + timed_work_notes=list(notes) if notes else None, ) def to_dict(self) -> Dict[str, Any]: diff --git a/src/dnn_benchmarking/reporting/suite_results.py b/src/dnn_benchmarking/reporting/suite_results.py index d0468a57..83bd2be7 100644 --- a/src/dnn_benchmarking/reporting/suite_results.py +++ b/src/dnn_benchmarking/reporting/suite_results.py @@ -387,6 +387,7 @@ class ProviderEngineResult: oracle_error: Optional[str] = None clocks_after: Optional[Dict[str, Any]] = None engine_name: Optional[str] = None + flops_formula_version: Optional[int] = None def __post_init__(self) -> None: """Validate status and role.""" @@ -490,6 +491,7 @@ def to_dict(self) -> Dict[str, Any]: "elapsed_s": self.elapsed_time_ms / 1000.0, "metrics": { "flops": self.analytical_flops, + "flops_formula_version": self.flops_formula_version, "io_bytes": self.analytical_io_bytes, "clocks_after": self.clocks_after, }, @@ -502,10 +504,14 @@ def to_dict(self) -> Dict[str, Any]: def timing_modes_differ(row: ProviderEngineResult) -> bool: - """True when the OOTB and tuned plans were timed in different modes.""" + """True when the OOTB and tuned plans were timed in incompatible modes.""" a = row.ootb.timing b = row.oracle.timing if row.oracle is not None else None - return a is not None and b is not None and a.mode != b.mode + return ( + a is not None + and b is not None + and (a.mode != b.mode or a.launch_mode != b.launch_mode) + ) def oracle_speedup(row: ProviderEngineResult) -> Optional[float]: @@ -513,7 +519,7 @@ def oracle_speedup(row: ProviderEngineResult) -> Optional[float]: None when the row has no tuned run, either plan failed validation, the two plans were timed in different modes (one plan fell back to - ``events``), or a median is missing or + ``events``), or a median is missing, non-finite or non-positive. Rows with ``tuning_available`` False still get a ratio; callers report them as "no-search" and keep them out of averages. The speedup is derived, never stored in the result file. @@ -529,7 +535,11 @@ def oracle_speedup(row: ProviderEngineResult) -> Optional[float]: if timing_modes_differ(row): return None ootb, tuned = row.ootb.gpu_kernel_stats.median_ms, oracle.gpu_kernel_stats.median_ms - if ootb <= 0.0 or tuned <= 0.0: + if ( + not (math.isfinite(ootb) and math.isfinite(tuned)) + or ootb <= 0.0 + or tuned <= 0.0 + ): return None return ootb / tuned diff --git a/tests/unit/cli/test_suite_cli.py b/tests/unit/cli/test_suite_cli.py index f8b6e5f6..0b340cf0 100644 --- a/tests/unit/cli/test_suite_cli.py +++ b/tests/unit/cli/test_suite_cli.py @@ -1105,7 +1105,7 @@ def test_internal_flags_are_hidden_from_help() -> None: assert "--no-stall-gate" not in help_text -_PYTORCH_ENV = dict.fromkeys(pytorch_tuning.ENV_NAMES, "1") +_PYTORCH_ENV = dict(pytorch_tuning._DEFAULT_ENV) @pytest.mark.parametrize( diff --git a/tests/unit/common/test_pytorch_tuning.py b/tests/unit/common/test_pytorch_tuning.py index faa6de71..ddcd053a 100644 --- a/tests/unit/common/test_pytorch_tuning.py +++ b/tests/unit/common/test_pytorch_tuning.py @@ -33,11 +33,39 @@ def test_defaults_enable_nhwc_and_aotriton() -> None: assert os.environ["PYTORCH_MIOPEN_SUGGEST_NHWC"] == "1" -def test_ootb_environment_never_enables_tuning_or_touches_miopen() -> None: - """OOTB PyTorch and the hipDNN MIOpen plugin share this process.""" - before = _tuning_vars() +def test_ootb_environment_never_enables_tuning_or_touches_miopen(monkeypatch) -> None: + """OOTB PyTorch disables TunableOp and never touches MIOPEN_* variables.""" + monkeypatch.setenv("MIOPEN_LOG_LEVEL", "3") + miopen_before = {k: v for k, v in os.environ.items() if k.startswith("MIOPEN_")} pytorch_tuning.apply_pytorch_environment() - assert _tuning_vars() == before + assert os.environ["PYTORCH_TUNABLEOP_ENABLED"] == "0" + assert os.environ["PYTORCH_TUNABLEOP_TUNING"] == "0" + miopen_after = {k: v for k, v in os.environ.items() if k.startswith("MIOPEN_")} + assert miopen_after == miopen_before + + +def test_tuned_child_preserves_tunableop_variables(monkeypatch, tmp_path) -> None: + """B3: tuned_subprocess_env followed by the child's env setup keeps TunableOp=1.""" + from dnn_benchmarking.cli.suite_runner_cli import _apply_pytorch_environment + from dnn_benchmarking.config.benchmark_config import RuntimeName, SuiteConfig + from dnn_benchmarking.reporting.reporter import Reporter + + tuned = SelectionState.under(tmp_path / "tuned") + child_env = pytorch_tuning.tuned_subprocess_env(str(tmp_path), tuned) + for key in ( + "PYTORCH_TUNABLEOP_ENABLED", + "PYTORCH_TUNABLEOP_TUNING", + "PYTORCH_TUNABLEOP_FILENAME", + ): + monkeypatch.setenv(key, child_env[key]) + + cfg = SuiteConfig(runtime=RuntimeName.PYTORCH) + _apply_pytorch_environment(cfg, Reporter(quiet=True), tuned=True) + + assert os.environ["PYTORCH_TUNABLEOP_ENABLED"] == "1" + assert os.environ["PYTORCH_TUNABLEOP_TUNING"] == "1" + assert os.environ["PYTORCH_MIOPEN_SUGGEST_NHWC"] == "1" + assert os.environ["TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL"] == "1" def test_tuned_subprocess_env_forces_tuning_and_the_shared_state( diff --git a/tests/unit/execution/test_correctness.py b/tests/unit/execution/test_correctness.py index c9709799..2c0cddcb 100644 --- a/tests/unit/execution/test_correctness.py +++ b/tests/unit/execution/test_correctness.py @@ -221,7 +221,7 @@ def test_passing_outputs_report_diffs_without_message(): "refs, outputs, reason", [ ({}, {1: np.zeros(4, np.float32)}, "did not produce output tensor UID 1"), - ({1: _ref([0, 0, 0, 0])}, {}, "No output tensors to compare"), + ({1: _ref([0, 0, 0, 0])}, {}, "Engine did not produce output tensor UID 1"), ], ) def test_missing_side_is_a_failure_not_a_pass(refs, outputs, reason): diff --git a/tests/unit/execution/test_suite_runner.py b/tests/unit/execution/test_suite_runner.py index 22ed58c4..dc9131ff 100644 --- a/tests/unit/execution/test_suite_runner.py +++ b/tests/unit/execution/test_suite_runner.py @@ -530,6 +530,9 @@ def test_row_timing_throughput_and_noise_from_the_measurement(fake, monkeypatch) "first_call_ms": 5.0, "capped": True, "fallback_reason": "no stream wait", + "launch_mode": "raw", + "requested_warmup_iters": None, + "timed_work_notes": None, } assert row.ootb.workspace_bytes == 64 assert row.ootb.cpu_build_time_ms == 2.0 @@ -1190,14 +1193,28 @@ def test_failed_cpu_float64_reference_falls_back_to_the_native_cpu_reference( @pytest.mark.parametrize("profiled", [False, True]) -def test_profiled_runs_keep_the_float64_reference_on_the_host( +def test_profiled_runs_keep_float64_reference_on_device_and_free_before_profiling( fake_torch, monkeypatch, profiled ): - """Profiled runs keep host-only references, as the timed row does.""" + """O-8: profiling keeps the float64 reference on device during OOTB timing + (matching unprofiled runs), then releases device references and clears the + torch cache before launching profiling children.""" import torch from dnn_benchmarking.metrics import profiling_orchestrator - monkeypatch.setattr(profiling_orchestrator, "run_profiling_passes", lambda **kw: {}) + events = [] + orig_release = suite_runner._release_torch_cache + + def track_release(): + events.append("release_torch_cache") + orig_release() + + def track_profile(**kw): + events.append("profile") + return {} + + monkeypatch.setattr(suite_runner, "_release_torch_cache", track_release) + monkeypatch.setattr(profiling_orchestrator, "run_profiling_passes", track_profile) fake_torch.discovered = [1] reference = fake_torch.cpu_reference reference.float64 = True @@ -1230,11 +1247,10 @@ def recording_check(bm, infos, refs, *args): assert graph.results[1].verdict == "passed" (ref,) = {id(r): r for r in seen}.values() assert ref.precision == "float64" + assert ref.device_data is not None and ref.data is None if profiled: - assert ref.device_data is None - assert ref.data.dtype == np.float64 - else: - assert ref.device_data is not None and ref.data is None + assert "release_torch_cache" in events and "profile" in events + assert events.index("release_torch_cache") < events.index("profile") def test_owned_compacts_a_view_and_keeps_an_owning_tensor(): @@ -1398,12 +1414,12 @@ def test_reference_warnings_go_on_the_reference_row_only(fake_torch, monkeypatch assert "manual op" not in (engine.warnings or []) -@pytest.mark.parametrize("profiling, device", [(False, "cuda"), (True, None)]) -def test_profiled_run_keeps_host_only_references( - fake_torch, monkeypatch, profiling, device +@pytest.mark.parametrize("profiling", [False, True]) +def test_profiled_run_keeps_same_parent_buffer_backend_during_ootb( + fake_torch, monkeypatch, profiling ): - """A profiling child allocates its own VRAM, so a profiled run must not - keep the PyTorch reference (and hipDNN buffers) on the device.""" + """O-8: profiling flags must not alter the parent hipDNN buffer backend + before OOTB timing; device references are freed after OOTB rows finish.""" from dnn_benchmarking.metrics import profiling_orchestrator monkeypatch.setattr(profiling_orchestrator, "run_profiling_passes", lambda **kw: {}) @@ -1412,7 +1428,7 @@ def test_profiled_run_keeps_host_only_references( _validate(metrics=MetricsConfig(perf=profiling)) - assert fake_torch.buffer_devices == [device] + assert fake_torch.buffer_devices == ["cuda"] def test_profiling_runs_after_teardown_with_the_rows_payload(fake, monkeypatch): diff --git a/tests/unit/reporting/test_schema_v3.py b/tests/unit/reporting/test_schema_v3.py index 834e021e..bf8a866a 100644 --- a/tests/unit/reporting/test_schema_v3.py +++ b/tests/unit/reporting/test_schema_v3.py @@ -60,7 +60,7 @@ "extra_metrics", } # fmt: skip ENGINE_KEYS = {"id", "name", "version"} -METRICS_KEYS = {"flops", "io_bytes", "clocks_after"} +METRICS_KEYS = {"flops", "flops_formula_version", "io_bytes", "clocks_after"} PLAN_KEYS = { "build_ms", "timing", "kernel", "host", "workspace_bytes", "tflops", "gbps", "correctness", "dispatch", @@ -68,7 +68,8 @@ DISPATCH_KEYS = {"sdpa_backend", "fa_library", "kernels"} STATS_KEYS = {"p25_ms", "median_ms", "p75_ms"} TIMING_KEYS = { - "mode", "timer", "warmup_iters", "samples", "first_call_ms", "capped", "fallback_reason", + "mode", "timer", "warmup_iters", "samples", "first_call_ms", "capped", + "fallback_reason", "launch_mode", "requested_warmup_iters", "timed_work_notes", } # fmt: skip CORRECTNESS_KEYS = { "match", "rtol", "atol", "max_abs_diff", "max_rel_diff", "n_mismatch", @@ -235,6 +236,7 @@ def test_full_row_values() -> None: } assert row["metrics"] == { "flops": 10**9, + "flops_formula_version": None, "io_bytes": 10**6, "clocks_after": {"sclk_mhz": 1650}, } @@ -275,6 +277,9 @@ def test_full_row_values() -> None: "first_call_ms": 13.5, "capped": False, "fallback_reason": None, + "launch_mode": "raw", + "requested_warmup_iters": None, + "timed_work_notes": None, }, "workspace_bytes": 2048, "tflops": 4.0, diff --git a/tests/unit/reporting/test_suite_reporter.py b/tests/unit/reporting/test_suite_reporter.py index ad68981f..dacac799 100644 --- a/tests/unit/reporting/test_suite_reporter.py +++ b/tests/unit/reporting/test_suite_reporter.py @@ -113,9 +113,11 @@ def test_long_name_warning_and_plugin_path_stay_within_terminal_width( def test_vs_best_is_best_successful_engine_median_over_row_median(self) -> None: text = _table( - _row("FAST", 0.020), - _row("MID", 0.025), - _row("SLOW", 0.040), + _row("FAST", 0.020, correctness=_verdict(True)), + _row("MID", 0.025, correctness=_verdict(True)), + _row("SLOW", 0.040, correctness=_verdict(True)), + # An unchecked row cannot win or score alongside validated rows (O-7). + _row("UNCHECKED", 0.008), # A wrong answer is not a "best", so it gets no ratio either; the # reference is not an engine. _row("WRONG", 0.005, correctness=_verdict(False)), @@ -124,9 +126,16 @@ def test_vs_best_is_best_successful_engine_median_over_row_median(self) -> None: assert _cells(text, "FAST")[-1] == "1.00x" assert _cells(text, "MID")[-1] == "0.80x" assert _cells(text, "SLOW")[-1] == "0.50x" + assert _cells(text, "UNCHECKED")[-1] == "-" assert _cells(text, "WRONG")[-1] == "-" assert _cells(text, "pytorch")[-1] == "ref" + def test_vs_best_ranks_unchecked_rows_when_validation_is_off(self) -> None: + """Default runs without --validate have only unchecked rows and rank them.""" + text = _table(_row("FAST", 0.020), _row("SLOW", 0.040)) + assert _cells(text, "FAST")[-1] == "1.00x" + assert _cells(text, "SLOW")[-1] == "0.50x" + def test_skipped_and_error_rows_show_their_reason(self) -> None: skipped = ProviderEngineResult.skipped_row( "hipdnn", diff --git a/tests/unit/test_perf_integrity.py b/tests/unit/test_perf_integrity.py new file mode 100644 index 00000000..4f1885ee --- /dev/null +++ b/tests/unit/test_perf_integrity.py @@ -0,0 +1,919 @@ +# Copyright © Advanced Micro Devices, Inc., or its affiliates. +# SPDX-License-Identifier: MIT + +"""Regression tests for timing integrity, compare gates, runtime guards, and telemetry.""" + +from __future__ import annotations + +import json +import signal +import types +from pathlib import Path +from typing import Any, Dict, List + +import numpy as np +import pytest + +from dnn_benchmarking.cli import hipdnn_tuned_child, suite_runner_cli +from dnn_benchmarking.config.benchmark_config import ( + SuiteConfig, + TimingPolicy, + ValidationConfig, +) +from dnn_benchmarking.execution import aiter_sdpa, oracle, suite_runner, timing +from dnn_benchmarking.execution.correctness import check_correctness +from dnn_benchmarking.execution.sdpa_graph import DenseSdpa +from dnn_benchmarking.graph.tensor_info import TensorInfo +from dnn_benchmarking.metrics import gpu_smi +from dnn_benchmarking.metrics.analytical import ( + ANALYTICAL_FORMULA_VERSION, + compute_flops, + derive_throughputs, +) +from dnn_benchmarking.metrics.analytical._common import tensor_dim_product +from dnn_benchmarking.reporting import compare +from dnn_benchmarking.reporting.reporter import Reporter +from dnn_benchmarking.reporting.statistics import ( + BenchmarkStats, + TimingInfo, + noise_warnings, +) +from dnn_benchmarking.reporting.suite_results import ( + CorrectnessResult, + GraphResult, + PlanResult, + ProviderEngineResult, + RunInfo, + SuiteResult, +) +from dnn_benchmarking.validation import ReferenceOutput + + +def _stats(median: float, spread: float = 0.0) -> BenchmarkStats: + return BenchmarkStats.from_timings([median - spread, median + spread] * 10) + + +def _row( + name: str, + median: float, + *, + mode: str = "staged", + timer: str = "hip", + launch_mode: str = "raw", + match: bool | None = True, + validated: bool = True, + role: str = "engine", + timings: List[float] | None = None, +) -> ProviderEngineResult: + stats = BenchmarkStats.from_timings(timings) if timings else _stats(median) + return ProviderEngineResult( + "hipdnn", + 1, + "success", + role=role, + engine_name=name, + ootb=PlanResult( + gpu_kernel_stats=stats, + timing=TimingInfo( + mode=mode, + timer=timer, + warmup_iters=10, + samples=stats.n, + first_call_ms=1.0, + launch_mode=launch_mode, + ), + correctness=(CorrectnessResult(match, 1e-3, 1e-5) if validated else None), + ), + ) + + +def _write_suite(tmp_path: Path, fname: str, graphs, **cfg) -> str: + suite = SuiteResult( + run=RunInfo( + "t", + [], + { + "cache_mode": "warm", + "timing_block": 1, + "input_recipe": "centered", + **cfg, + }, + complete=True, + ), + environment={"gpu_model": "MI210", "gpu_arch": "gfx90a"}, + graphs=[ + GraphResult(name, f"{name}.json", rows, engine_ids=[1], graph_id=gid) + for name, gid, rows in graphs + ], + ) + out = tmp_path / fname + suite.write(out) + return str(out) + + +# --- P0: Compare compatibility, validation loopholes, and exact thresholds --- + + +def test_compare_excludes_mixed_timing_modes_by_default(tmp_path, capsys) -> None: + a = _write_suite( + tmp_path, "a.json", [("g", "id", [_row("E", 0.08, mode="staged")])] + ) + b = _write_suite( + tmp_path, "b.json", [("g", "id", [_row("E", 0.12, mode="events")])] + ) + + code = compare.main([a, b, "--json"]) + cap = capsys.readouterr() + report = json.loads(cap.out) + assert code == 0 + assert report["mixed_timing"] == 1 + assert report["pairs"][0]["in_geomean"] is False + assert "mixed timing" in report["pairs"][0]["label"] + assert "mixed timing" in cap.err + + # Explicit --allow-mismatch permits scoring the pair. + code_allowed = compare.main([a, b, "--allow-mismatch", "--json"]) + report_allowed = json.loads(capsys.readouterr().out) + assert code_allowed == 1 + assert report_allowed["pairs"][0]["label"] == "REGRESSION" + + +def test_compare_excludes_mixed_launch_modes(tmp_path, capsys) -> None: + a = _write_suite( + tmp_path, "a.json", [("g", "id", [_row("E", 0.08, launch_mode="raw")])] + ) + b = _write_suite( + tmp_path, + "b.json", + [("g", "id", [_row("E", 0.05, launch_mode="graph_replay")])], + ) + + code = compare.main([a, b, "--json"]) + report = json.loads(capsys.readouterr().out) + assert code == 0 + assert report["mixed_timing"] == 1 + assert report["pairs"][0]["in_geomean"] is False + assert "mixed launch" in report["pairs"][0]["label"] + + +def test_compare_excludes_mixed_passed_vs_unchecked(tmp_path, capsys) -> None: + a = _write_suite( + tmp_path, "a.json", [("g", "id", [_row("E", 1.0, validated=True, match=True)])] + ) + b = _write_suite( + tmp_path, "b.json", [("g", "id", [_row("E", 1.5, validated=False)])] + ) + + code = compare.main([a, b, "--json"]) + report = json.loads(capsys.readouterr().out) + assert code == 0 + assert report["mixed_validation"] == 1 + assert report["pairs"][0]["in_geomean"] is False + assert "mixed validation" in report["pairs"][0]["label"] + + +def test_compare_failed_only_b_reports_failed_and_strict_coverage_exits_1( + tmp_path, capsys +) -> None: + a = _write_suite(tmp_path, "a.json", [("g", "id", [_row("E", 6.0, match=True)])]) + b = _write_suite(tmp_path, "b.json", [("g", "id", [_row("E", 7.0, match=False)])]) + + code = compare.main([a, b, "--json"]) + report = json.loads(capsys.readouterr().out) + assert code == 0 + assert report["validation_failures"] == 1 + assert report["pairs"][0]["label"] == "B failed" + assert report["pairs"][0]["in_geomean"] is False + + assert compare.main([a, b, "--strict-coverage", "--json"]) == 1 + capsys.readouterr() + + +def test_compare_zero_median_does_not_preempt_valid_sibling(tmp_path, capsys) -> None: + a = _write_suite(tmp_path, "a.json", [("g", "id", [_row("E1", 0.9)])]) + b = _write_suite( + tmp_path, "b.json", [("g", "id", [_row("ZERO", 0.0), _row("E1", 0.3)])] + ) + + code = compare.main([a, b, "--json"]) + report = json.loads(capsys.readouterr().out) + assert code == 0 + assert report["pairs"][0]["engine_b"] == "E1" + assert report["pairs"][0]["speedup"] == pytest.approx(3.0) + assert report["pairs"][0]["in_geomean"] is True + + +def test_compare_exact_threshold_is_within_noise(tmp_path, capsys) -> None: + # 2.1 / 2.0 - 1.0 == 0.050000000000000044 in binary float; must not regress at 5%. + a = _write_suite(tmp_path, "a.json", [("g", "id", [_row("E", 2.0)])]) + b = _write_suite(tmp_path, "b.json", [("g", "id", [_row("E", 2.1)])]) + + code = compare.main([a, b, "--threshold", "5", "--json"]) + report = json.loads(capsys.readouterr().out) + assert code == 0 + assert report["pairs"][0]["label"] == "within noise" + + +def test_compare_missing_quartile_is_unknown_spread_not_zero(tmp_path, capsys) -> None: + a = _write_suite(tmp_path, "a.json", [("g", "id", [_row("E", 2.0)])]) + b = _write_suite( + tmp_path, + "b.json", + [("g", "id", [_row("E", 2.4, timings=[2.4] * 7 + [float("inf")] * 5)])], + ) + + code = compare.main([a, b, "--json"]) + report = json.loads(capsys.readouterr().out) + assert code == 0 + assert report["unknown_spread"] == 1 + assert report["pairs"][0]["label"] == "unknown spread" + assert report["pairs"][0]["in_geomean"] is False + + +def test_partial_missing_actual_output_fails_validation() -> None: + class PartialBM: + def get_output_tensor(self, uid): + return None + + def get_output_data(self, uid): + return np.zeros(4, np.float32) if uid == 1 else None + + infos = [ + TensorInfo(1, "o1", [4], [1], "float", is_virtual=False, is_output=True), + TensorInfo(2, "o2", [4], [1], "float", is_virtual=False, is_output=True), + ] + refs = { + 1: ReferenceOutput(data=np.zeros(4, np.float32), tensor_uid=1), + 2: ReferenceOutput(data=np.zeros(4, np.float32), tensor_uid=2), + } + cfg = SuiteConfig(validation=ValidationConfig(provider="pytorch")) + res = check_correctness(PartialBM(), infos, refs, "pytorch", cfg) + assert res.tolerance_match is False + assert "UID 2" in (res.error_message or "") + + +def test_reporter_refuses_vs_best_across_mixed_modes() -> None: + import io + + out = io.StringIO() + gr = GraphResult( + "g", + "/tmp/g.json", + [_row("E1", 0.05, mode="staged"), _row("E2", 0.08, mode="events")], + engine_ids=[1, 2], + ) + Reporter(out, io.StringIO()).print_graph_table(gr) + text = out.getvalue() + assert "mixed modes: staged, events" in text + assert "1.00x" not in text + + +# --- P1: AITER guards, AMD SMI handle/in-run telemetry, signal restore, fresh oracle --- + + +def _sdpa(**kw) -> DenseSdpa: + defaults = dict( + data_type="bfloat16", + batch=1, + num_query_heads=8, + num_kv_heads=2, + seqlen_q=1, + seqlen_kv=2048, + head_size_qk=192, + head_size_v=128, + causal=False, + bottom_right=True, + scale=0.125, + q_uid=1, + k_uid=2, + v_uid=3, + o_uid=4, + ) + defaults.update(kw) + return DenseSdpa(**defaults) + + +def test_aiter_opus_excludes_nonpositive_scale(monkeypatch) -> None: + dev = aiter_sdpa.AiterDevice(arch="gfx950", num_cus=256, gluon=False) + monkeypatch.setenv("AITER_ENABLE_FMHA_OPUS", "1") + zero_128 = _sdpa( + seqlen_q=128, seqlen_kv=128, head_size_qk=128, head_size_v=128, scale=0.0 + ) + names = [b.name for b in aiter_sdpa.backend_rows(zero_128, dev)] + assert "opus" not in names + assert "auto" not in names + + pos_128 = _sdpa( + seqlen_q=128, seqlen_kv=128, head_size_qk=128, head_size_v=128, scale=0.125 + ) + pos_names = [b.name for b in aiter_sdpa.backend_rows(pos_128, dev)] + assert "opus" in pos_names and "auto" in pos_names + + +def test_aiter_asymmetric_gqa_decode_excluded_from_ck_and_asm_v3() -> None: + asym = _sdpa( + seqlen_q=1, num_query_heads=8, num_kv_heads=2, head_size_qk=192, head_size_v=128 + ) + dev942 = aiter_sdpa.AiterDevice(arch="gfx942", num_cus=304, gluon=False) + names942 = [b.name for b in aiter_sdpa.backend_rows(asym, dev942)] + assert "ck" not in names942 and "asm_v3" not in names942 and "auto" not in names942 + + # On gfx950 BF16 192/128, OPUS handles it cleanly; CK and ASM v3 remain excluded. + dev950 = aiter_sdpa.AiterDevice(arch="gfx950", num_cus=256, gluon=False) + names950 = [b.name for b in aiter_sdpa.backend_rows(asym, dev950)] + assert "ck" not in names950 and "asm_v3" not in names950 + assert "opus" in names950 and "auto" in names950 + + # Symmetric width or Sq=2 remains enabled. + sym = _sdpa(seqlen_q=1, head_size_qk=128, head_size_v=128) + assert "ck" in [b.name for b in aiter_sdpa.backend_rows(sym, dev942)] + sq2 = _sdpa(seqlen_q=2, head_size_qk=192, head_size_v=128) + assert "ck" in [b.name for b in aiter_sdpa.backend_rows(sq2, dev942)] + + +def test_amdsmi_unavailable_with_zero_handles(monkeypatch) -> None: + fake = types.SimpleNamespace(amdsmi_get_processor_handles=lambda: []) + monkeypatch.setattr(gpu_smi, "_amdsmi", lambda: fake) + assert gpu_smi.is_amdsmi_available() is False + + +def test_unresolved_pre_init_amdsmi_handle_is_not_pinned_forever(monkeypatch) -> None: + gpu_smi._handle_for.cache_clear() + monkeypatch.setenv("HIP_VISIBLE_DEVICES", "1") + fake = types.SimpleNamespace( + amdsmi_get_processor_handles=lambda: ["h0", "h1"], + amdsmi_get_gpu_device_bdf=lambda h: ( + "0000:09:00.0" if h == "h0" else "0000:0c:00.0" + ), + ) + monkeypatch.setattr(gpu_smi, "_amdsmi", lambda: fake) + # Before HIP init, BDF is unavailable -> None, not cached permanently. + monkeypatch.setattr(gpu_smi, "_hip_device_bdf", lambda _i: None) + assert gpu_smi.GpuSmiProbe()._handle is None + # After HIP init, BDF resolves -> h1! + monkeypatch.setattr(gpu_smi, "_hip_device_bdf", lambda _i: "0000:0c:00") + assert gpu_smi.GpuSmiProbe()._handle == "h1" + gpu_smi._handle_for.cache_clear() + + +def test_gpu_smi_sample_during_detects_in_run_throttle() -> None: + """Background telemetry polling catches mid-loop throttling deterministically.""" + import threading + + readings = [ + { + "sclk_mhz": 1300.0, + "mclk_mhz": 1600.0, + "power_w": 750.0, + "temp_hotspot_c": 80.0, + "throttle_status": 4, + }, + { + "sclk_mhz": 1700.0, + "mclk_mhz": 1600.0, + "power_w": 200.0, + "temp_hotspot_c": 65.0, + "throttle_status": 0, + }, + ] + probe = gpu_smi.GpuSmiProbe.__new__(gpu_smi.GpuSmiProbe) + probe._handle = "h0" + idx = {"n": 0} + sampled = threading.Event() + + def clocks(): + i = min(idx["n"], len(readings) - 1) + idx["n"] += 1 + sampled.set() + return readings[i] + + probe.clocks = clocks + with probe.sample_during(interval_s=0.0) as telemetry: + assert sampled.wait(timeout=2.0) + assert telemetry["throttle_status"] == 0 + assert telemetry["throttle_any"] is True + assert telemetry["power_max_w"] == 750.0 + assert telemetry["sclk_min_mhz"] == 1300.0 + assert suite_runner._throttled(telemetry) is True + + +def test_fresh_state_isolates_oracle_tuned_state(tmp_path) -> None: + cfg = SuiteConfig( + benchmark_work_dir=str(tmp_path / "work"), + fresh_state=True, + oracle=True, + ) + fresh_root = tmp_path / "child_tmp" + state = oracle._tuned_state(cfg, fresh_root) + assert fresh_root in state.hipdnn_cache.parents + assert (tmp_path / "work" / "tuned") not in state.hipdnn_cache.parents + argv = oracle._pytorch_tuned_argv(tmp_path / "g.json", cfg, tmp_path / "out.json") + assert "--fresh-state" in argv + + +_MINIMAL_GRAPH = { + "name": "g", + "compute_data_type": "float", + "intermediate_data_type": "float", + "io_data_type": "float", + "tensors": [ + {"uid": 1, "name": "x", "dims": [4], "strides": [1], "data_type": "float"}, + {"uid": 2, "name": "y", "dims": [4], "strides": [1], "data_type": "float"}, + ], + "nodes": [ + { + "name": "relu", + "type": "PointwiseAttributes", + "inputs": {"in_0_tensor_uid": 1, "operation": "relu_fwd"}, + "outputs": {"out_0_tensor_uid": 2}, + } + ], +} + + +def test_hipdnn_tuned_child_resolves_varlen_before_allocation( + tmp_path, monkeypatch +) -> None: + events: List[str] = [] + graph_path = tmp_path / "g.json" + graph_path.write_text(json.dumps(_MINIMAL_GRAPH)) + out_dir = tmp_path / "out" + out_dir.mkdir() + cache_dir = tmp_path / "cache" + db_dir = tmp_path / "db" + cache_dir.mkdir() + db_dir.mkdir() + monkeypatch.setenv("HIPDNN_FORCE_BENCHMARKING", "1") + monkeypatch.setenv("HIPDNN_CACHE_DIR", str(cache_dir)) + monkeypatch.setenv("MIOPEN_USER_DB_PATH", str(db_dir)) + monkeypatch.setattr(hipdnn_tuned_child, "initialize_pip_rocm_runtime", lambda: None) + monkeypatch.setattr(hipdnn_tuned_child, "set_plugin_path", lambda h, p: None) + + class FakeExec: + build_time_ms = 1.0 + workspace_size = 0 + + def __init__(self, *a, **kw): + pass + + def prime(self, *a, **kw): + pass + + def prepare(self, *a, **kw): + pass + + def engine_knob_ids(self, eid): + return [] + + def benchmark(self, handle, vp): + return timing.Measurement([1.0], [0.1], "staged", "hip", "warm", 1, 1.0) + + class FakeBM: + def __init__(self, infos): + pass + + def __enter__(self): + return self + + def __exit__(self, *a): + pass + + def allocate_all(self): + events.append("allocate_all") + + def load_input_data(self, data): + events.append("load_input_data") + + def zero_outputs(self): + pass + + def create_variant_pack(self): + return {} + + import sys + + monkeypatch.setitem( + sys.modules, "hipdnn_frontend", types.SimpleNamespace(Handle=lambda: object()) + ) + monkeypatch.setattr(hipdnn_tuned_child, "Executor", FakeExec) + monkeypatch.setattr(hipdnn_tuned_child, "BufferManager", FakeBM) + monkeypatch.setattr( + hipdnn_tuned_child, + "generate_input_data", + lambda *a, **kw: (events.append("generate_input_data"), {})[1], + ) + monkeypatch.setattr( + hipdnn_tuned_child, + "resolve_varlen_layouts", + lambda infos, gj, data: (events.append("resolve_varlen_layouts"), infos)[1], + ) + + rc = hipdnn_tuned_child.main( + [ + "--graph", + str(graph_path), + "--engine", + "1", + "--seed", + "0", + "--timing-policy", + json.dumps({"warmup_iters": 1, "iters": 1}), + "--out-dir", + str(out_dir), + ] + ) + assert rc == 0 + assert events.index("generate_input_data") < events.index("resolve_varlen_layouts") + assert events.index("resolve_varlen_layouts") < events.index("allocate_all") + + +def test_signal_restore_skips_native_none_handlers(tmp_path, monkeypatch) -> None: + """When rocprofv3 installs a native C signal handler, getsignal() returns None.""" + calls = [] + monkeypatch.setattr(signal, "getsignal", lambda sig: None) + monkeypatch.setattr(signal, "signal", lambda sig, h: calls.append((sig, h))) + monkeypatch.setattr( + suite_runner_cli, "_arm_sigterm_watchdog", lambda: (lambda: None) + ) + monkeypatch.setattr( + suite_runner_cli, "collect_environment_info", lambda: {"gpu_arch": "gfx90a"} + ) + gpath = tmp_path / "g.json" + gpath.write_text(json.dumps(_MINIMAL_GRAPH)) + cfg = SuiteConfig() + rc = suite_runner_cli._run_suite( + [gpath], + cfg, + lambda p, gj, ti: GraphResult("g", str(p), [], engine_ids=[1]), + None, + Reporter(), + ["dnn-benchmark"], + ) + assert rc == 0 + assert calls == [] + + +# --- Analytical FLOPs and timer resolution warnings --- + + +def test_packed_paged_sdpa_without_lengths_returns_none() -> None: + graph = { + "tensors": [ + {"uid": 1, "dims": [1, 1, 4, 128], "data_type": "half"}, + {"uid": 2, "dims": [2, 1, 8, 128], "data_type": "half"}, + {"uid": 3, "dims": [2, 1, 8, 128], "data_type": "half"}, + {"uid": 4, "dims": [1, 1, 4, 128], "data_type": "half"}, + {"uid": 5, "dims": [2, 1, 1, 1], "data_type": "int32"}, + ], + "nodes": [ + { + "type": "SdpaAttributes", + "inputs": { + "q_tensor_uid": 1, + "k_tensor_uid": 2, + "v_tensor_uid": 3, + "page_table_k_tensor_uid": 5, + }, + "outputs": {"o_tensor_uid": 4}, + "attributes": {"causal_mask": True}, + } + ], + } + assert compute_flops(graph) is None + + +def test_missing_dims_scalar_and_known_zero_rates() -> None: + assert tensor_dim_product({}) is None + assert tensor_dim_product({"dims": []}) == 1 + assert tensor_dim_product({"dims": [0, 4]}) == 0 + assert ANALYTICAL_FORMULA_VERSION == 2 + + # Missing dims on a node output makes whole-graph FLOPs None, never partial. + graph = { + "tensors": [ + {"uid": 1, "dims": [4, 4]}, + {"uid": 2, "dims": [4, 4]}, + {"uid": 3, "dims": [4, 4]}, + {"uid": 4}, # missing dims + ], + "nodes": [ + { + "type": "MatmulAttributes", + "inputs": {"a_tensor_uid": 1, "b_tensor_uid": 2}, + "outputs": {"c_tensor_uid": 3}, + }, + { + "type": "PointwiseAttributes", + "inputs": {"in_0_tensor_uid": 3}, + "outputs": {"out_0_tensor_uid": 4}, + }, + ], + } + assert compute_flops(graph) is None + assert derive_throughputs(0, 0, 2.0) == (0.0, 0.0) + + +def test_zero_sample_emits_timer_resolution_warning() -> None: + stats = BenchmarkStats.from_timings([0.0] + [0.016] * 19) + assert any("timer resolution" in w for w in noise_warnings(stats)) + + +# --- Reporter, DVC setup, AITER env flags, and runtime invariants --- + + +def test_reporter_nonfinite_iqr_and_launch_mode_legend() -> None: + import io + + bad_stats = BenchmarkStats.from_timings([2.4] * 7 + [float("inf")] * 5) + bad_row = ProviderEngineResult( + "hipdnn", + 1, + "success", + engine_name="E1", + ootb=PlanResult( + gpu_kernel_stats=bad_stats, + timing=TimingInfo( + mode="staged", + timer="hip", + warmup_iters=5, + samples=12, + first_call_ms=1.0, + ), + ), + ) + # Non-finite IQR must not raise TypeError in _outcome. + text = Reporter._outcome(bad_row) + assert "iqr" not in text and "unchecked" in text + + # Legend names launch_mode when rows mix raw vs graph_replay. + out = io.StringIO() + gr = GraphResult( + "g", + "/tmp/g.json", + [ + _row("E1", 0.05, mode="staged", launch_mode="raw"), + _row("E2", 0.04, mode="staged", launch_mode="graph_replay"), + ], + engine_ids=[1, 2], + ) + Reporter(out, io.StringIO()).print_graph_table(gr) + rendered = out.getvalue() + assert "staged/raw" in rendered and "staged/graph_replay" in rendered + assert "1.00x" not in rendered + + +def test_setup_env_sets_dvc_global_config_dir(tmp_path, monkeypatch) -> None: + import importlib.util + + spec = importlib.util.spec_from_file_location( + "setup_env_under_test", + Path(__file__).resolve().parents[2] / "setup_env.py", + ) + assert spec and spec.loader + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + + dvc_root = tmp_path / "rocm-libs" + desc_dir = dvc_root / "desc" + desc_dir.mkdir(parents=True) + (desc_dir / "a.dvc").write_text("md5: 123\n") + monkeypatch.setattr(mod, "ROCM_LIBRARIES_DIR", dvc_root) + monkeypatch.setattr(mod, "PROVIDER_DESCRIPTOR_ROOT", desc_dir) + + captured: Dict[str, Any] = {} + monkeypatch.setattr(mod, "run", lambda cmd, **kw: captured.update(cmd=cmd, **kw)) + + monkeypatch.setattr(mod.Setup, "py", property(lambda self: "/usr/bin/python3")) + setup = mod.Setup.__new__(mod.Setup) + setup.workspace = tmp_path / "ws" + setup.env = {} + setup.pull_provider_artifacts() + cfg_dir = Path(captured["env"]["DVC_GLOBAL_CONFIG_DIR"]) + assert (cfg_dir / "config").is_file() + assert str(setup.workspace / "dvc-cache") in (cfg_dir / "config").read_text() + + +def test_aiter_opus_env_flags_scope_and_int_parsing(monkeypatch) -> None: + """AITER_DISABLE_FMHA_OPUS gates 192/128 only; 128/128 follows AITER_ENABLE_FMHA_OPUS != 0.""" + dev = aiter_sdpa.AiterDevice(arch="gfx950", num_cus=256, gluon=False) + p_192 = _sdpa(seqlen_q=128, seqlen_kv=128, head_size_qk=192, head_size_v=128) + p_128 = _sdpa( + seqlen_q=128, seqlen_kv=128, head_size_qk=128, head_size_v=128, scale=0.0 + ) + monkeypatch.delenv("AITER_DISABLE_FMHA_OPUS", raising=False) + monkeypatch.delenv("AITER_ENABLE_FMHA_OPUS", raising=False) + assert aiter_sdpa._auto_routes_to_opus(p_192, dev) is True + # Non-zero integers other than "1" also disable 192/128 OPUS (int(...) != 0). + monkeypatch.setenv("AITER_DISABLE_FMHA_OPUS", "2") + assert aiter_sdpa._auto_routes_to_opus(p_192, dev) is False + monkeypatch.setenv("AITER_DISABLE_FMHA_OPUS", "0") + assert aiter_sdpa._auto_routes_to_opus(p_192, dev) is True + # 128/128 depends only on AITER_ENABLE_FMHA_OPUS, even if DISABLE is set. + monkeypatch.setenv("AITER_DISABLE_FMHA_OPUS", "1") + monkeypatch.setenv("AITER_ENABLE_FMHA_OPUS", "2") + assert aiter_sdpa._auto_routes_to_opus(p_128, dev) is True + names = [b.name for b in aiter_sdpa.backend_rows(p_128, dev)] + assert "auto" not in names and "opus" not in names + + +def test_per_graph_mode_unification_reruns_with_mixed_mode_reason( + tmp_path, monkeypatch +) -> None: + """Mixed staged/events rows trigger a graph rerun with MIXED_MODE_RERUN_REASON in timing and warnings.""" + calls: List[bool] = [] + emitted_warnings: List[str] = [] + monkeypatch.setattr( + suite_runner, "warn_once", lambda key, msg: emitted_warnings.append(msg) + ) + + class FakeEventTimer: + def __init__(self, *a, **kw): + pass + + def start(self): + pass + + def stop(self): + pass + + def elapsed_ms(self): + return 0.06 + + monkeypatch.setattr(timing, "EventTimer", FakeEventTimer) + monkeypatch.setattr(timing, "device_sync", lambda _t: None) + + def planner(gp, gj, ti, cfg, rep): + def rows(ctx): + calls.append(cfg.timing_policy.stall_gate) + if cfg.timing_policy.stall_gate: + return [ + _row("E1", 0.05, mode="staged"), + _row("E2", 0.08, mode="events"), + ] + r1 = ProviderEngineResult("hipdnn", 1, "success", engine_name="E1") + suite_runner._measure_row( + r1, + ctx, + lambda: timing.measure( + lambda: None, + stream=0, + policy=cfg.timing_policy, + timer="hip", + ), + ) + r2 = _row("E2", 0.08, mode="events") + r2.ootb.timing.fallback_reason = "host sync in enqueue" + return [r1, r2] + + return suite_runner.RuntimePlan( + "hipdnn", engine_ids=[1, 2], rows=rows, needs_inputs=True + ) + + gr = suite_runner.run_graph( + tmp_path / "g.json", + _MINIMAL_GRAPH, + [], + SuiteConfig(warmup_iters=1, benchmark_iters=2), + Reporter(quiet=True), + [planner], + ) + assert calls == [True, False] + assert [r.ootb.timing.mode for r in gr.results] == ["events", "events"] + assert gr.results[0].ootb.timing.fallback_reason == timing.MIXED_MODE_RERUN_REASON + assert gr.results[1].ootb.timing.fallback_reason == "host sync in enqueue" + assert any(timing.MIXED_MODE_RERUN_REASON in w for w in gr.results[0].warnings) + assert not any(timing.STALL_RERUN_REASON in w for w in gr.results[0].warnings) + assert not any(timing.STALL_RERUN_REASON in w for w in emitted_warnings) + + +def test_suite_runner_cli_tuned_child_preserves_tunableop_env( + tmp_path, monkeypatch +) -> None: + """run_suite_cli(tuned_child=True) keeps PYTORCH_TUNABLEOP_* set by tuned_subprocess_env.""" + import os + from dnn_benchmarking.cli.parser import create_parser + + gpath = tmp_path / "g.json" + gpath.write_text(json.dumps(_MINIMAL_GRAPH)) + monkeypatch.setenv("PYTORCH_TUNABLEOP_ENABLED", "1") + monkeypatch.setenv("PYTORCH_TUNABLEOP_TUNING", "1") + seen_env: Dict[str, Any] = {} + + def fake_start_runtime(config, reporter, resources): + seen_env["enabled"] = os.environ.get("PYTORCH_TUNABLEOP_ENABLED") + seen_env["tuning"] = os.environ.get("PYTORCH_TUNABLEOP_TUNING") + return lambda p, gj, ti: GraphResult("g", str(p), [], engine_ids=[0]) + + monkeypatch.setattr(suite_runner_cli, "start_runtime", fake_start_runtime) + monkeypatch.setattr(suite_runner_cli, "is_amdsmi_available", lambda: False) + monkeypatch.setattr( + suite_runner_cli, "collect_environment_info", lambda: {"gpu_arch": "gfx90a"} + ) + args = create_parser().parse_args( + [ + "--graph", + str(gpath), + "--runtime", + "pytorch", + "--warmup", + "1", + "--iters", + "1", + "--no-metrics", + "--quiet", + "--benchmark-work-dir", + str(tmp_path / "work"), + ] + ) + rc = suite_runner_cli.run_suite_cli( + args, + [gpath], + Reporter(quiet=True), + argv=["dnn-benchmark"], + tuned_child=True, + ) + assert rc == 0 + assert seen_env == {"enabled": "1", "tuning": "1"} + + +def test_rocke_passes_after_iteration_scratch_release(monkeypatch) -> None: + """RockeExecutor passes after_iteration scratch cleanup into measure().""" + import contextlib + import sys + from dnn_benchmarking.execution import rocke_executor + + released: List[Any] = [] + fake_rt = types.SimpleNamespace( + release_retained_for_stream=lambda s: released.append(s), + wait_stream_and_release=lambda s: None, + no_fence=contextlib.nullcontext, + ) + monkeypatch.setitem(sys.modules, "rocke", types.SimpleNamespace(runtime=fake_rt)) + monkeypatch.setitem(sys.modules, "rocke.runtime", fake_rt) + + captured_hook = {} + + def fake_measure(launch, **kw): + captured_hook["fn"] = kw.get("after_iteration") + return timing.Measurement([1.0], [0.1], "staged", "torch", "warm", 1, 1.0) + + fake_torch = types.SimpleNamespace( + cuda=types.SimpleNamespace( + device=lambda _d: contextlib.nullcontext(), + stream=lambda _s: contextlib.nullcontext(), + ) + ) + monkeypatch.setattr(rocke_executor, "torch", fake_torch) + monkeypatch.setattr(rocke_executor, "measure", fake_measure) + + ex = rocke_executor.RockeExecutor.__new__(rocke_executor.RockeExecutor) + ex._launch = lambda: None + ex._device = "cuda:0" + ex._stream = types.SimpleNamespace(cuda_stream=99) + ex._policy = TimingPolicy() + ex._launch_mode = "raw" + ex._timer = "torch" + + ex.benchmark() + assert callable(captured_hook["fn"]) + captured_hook["fn"]() + assert released == [99] + + +def test_pytorch_executor_surfaces_timed_work_notes_on_measurement(monkeypatch) -> None: + """PyTorchCudaExecutor attaches handler timed_work_notes (e.g. varlen copy) to Measurement.""" + import contextlib + from dnn_benchmarking.execution import pytorch_executor + from dnn_benchmarking.execution.pytorch_ops import ReplayTensors + + fake_torch = types.SimpleNamespace( + cuda=types.SimpleNamespace( + device=lambda _d: contextlib.nullcontext(), + stream=lambda _s: contextlib.nullcontext(), + ) + ) + monkeypatch.setattr(pytorch_executor, "torch", fake_torch) + + def fake_measure(enqueue_fn, **kw): + enqueue_fn() + return timing.Measurement([0.5], [0.1], "staged", "torch", "warm", 1, 0.5) + + monkeypatch.setattr(pytorch_executor, "measure", fake_measure) + ex = pytorch_executor.PyTorchCudaExecutor.__new__( + pytorch_executor.PyTorchCudaExecutor + ) + ex._device = "cuda:0" + ex._stream = types.SimpleNamespace(cuda_stream=5, synchronize=lambda: None) + ex._policy = TimingPolicy() + ex._timer = "torch" + ex._sdpa_backend_state = None + ex.notes = [] + + def fake_execute(tensors): + if isinstance(tensors, ReplayTensors): + tensors.timed_work_note("varlen_per_batch_copy") + tensors.timed_work_note("varlen_per_batch_copy") # deduplicated + + ex._execute_graph = fake_execute + m = ex.benchmark({1: object()}) + assert m.timed_work_notes == ["varlen_per_batch_copy"]