From 5f6f692b3915847bb761db0692dec0600c3853d8 Mon Sep 17 00:00:00 2001 From: Samuel Reeder Date: Tue, 24 Nov 2026 19:04:56 +0000 Subject: [PATCH] feat(knobs): add strict --knob validation, --sweep-knobs, and --knob-candidates --- AGENTS.md | 2 +- docs/methodology.md | 2 +- docs/results-schema.md | 6 +- docs/usage.md | 11 +- sample_configs/config.toml.example | 2 + .../cli/hipdnn_tuned_child.py | 9 +- .../cli/internal_profiling.py | 15 +- src/dnn_benchmarking/cli/parser.py | 70 +++- src/dnn_benchmarking/cli/suite_runner_cli.py | 23 +- src/dnn_benchmarking/common/exceptions.py | 12 + .../config/benchmark_config.py | 35 ++ src/dnn_benchmarking/execution/executor.py | 63 +++- src/dnn_benchmarking/execution/knob_sweep.py | 221 ++++++++++++ src/dnn_benchmarking/execution/oracle.py | 7 + .../execution/suite_runner.py | 140 +++++++- .../metrics/profiling_orchestrator.py | 11 +- .../reporting/suite_results.py | 6 + tests/unit/cli/test_suite_cli.py | 2 + tests/unit/reporting/test_schema_v3.py | 6 +- tests/unit/test_perf_integrity.py | 320 +++++++++++++++++- 20 files changed, 919 insertions(+), 44 deletions(-) create mode 100644 src/dnn_benchmarking/execution/knob_sweep.py diff --git a/AGENTS.md b/AGENTS.md index c627c5b1..21ecd82b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -77,7 +77,7 @@ package, run `PYTHONPATH=src python -m dnn_benchmarking ...`. |---|---| | 0 | Success. An all-skipped run is also 0. | | 1 | Engine row error, graph error, failed final result write (not a periodic one), no graph files, or runtime not available at startup. | -| 2 | Usage error: argparse, config file, runtime-incompatible option, unknown `--engine`, unwritable `-o` or `--profiling-output-dir`, missing profiler tool. | +| 2 | Usage error: argparse, config file, runtime-incompatible option, unknown `--engine`, unknown `--knob` ID or wrong `--knob` value type, unreadable or malformed `--knob-candidates`, unwritable `-o` or `--profiling-output-dir`, missing profiler tool. If `-o` is set and a fatal `--knob` fails mid-run, the written file is partial (`run.complete = false`). Per-graph `--knob` domain or range mismatches skip the row instead. | | 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`). | diff --git a/docs/methodology.md b/docs/methodology.md index bc4e19d4..43d303d4 100644 --- a/docs/methodology.md +++ b/docs/methodology.md @@ -583,7 +583,7 @@ backend or overwrite timed samples. After all OOTB rows of the graph complete 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] [--input-recipe R] + --warmup W --iters 5 --seed S [--plugin-path P] [--input-recipe R] [--knobs-json JSON] ``` The child builds one engine, fills the inputs with the same seed as the timed diff --git a/docs/results-schema.md b/docs/results-schema.md index 79b5440c..6e6fcbf2 100644 --- a/docs/results-schema.md +++ b/docs/results-schema.md @@ -66,6 +66,8 @@ the keys below. | `seed` | int | Input data seed. | | `input_recipe` | string | `--input-recipe` (`centered`, `llm`, `heavy_tail`, `legacy`, or `zeros`). | | `input_recipe_version` | int | Version of the input-generation recipe implementation. | +| `knobs` | object or null | Explicit `--knob` settings applied to hipDNN engines, or `null`. | +| `sweep_knobs` | bool | `--sweep-knobs`. | | `validate` | string or null | Reference runtime (`pytorch`), or `null` when validation is off. | | `rtol` | float or null | `--rtol` as given. When both `rtol` and `atol` are `null`, validation uses dtype-aware defaults. When only one is given, it also sets the other, which stays `null` here; each row's `correctness.rtol` and `correctness.atol` hold the values a comparison applied (see [correctness](#correctness) for rows where none ran). | | `atol` | float or null | `--atol` as given. `null` follows the same rule as `rtol`. | @@ -174,7 +176,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. Also adds `run.config` (`rotate_buffers`, `input_recipe`, `input_recipe_version`), `graph.input_fingerprint`, `metrics.flops_formula_version`, `timing` (`launch_mode`, `requested_warmup_iters`, `flush_method`, `flush_bytes`, `rotated_buffers`, `timed_work_notes`), and in-run `metrics.clocks_after` telemetry (`in_run_samples`, `throttle_any`, `power_max_w`, `sclk_min_mhz`, `sclk_max_mhz`).| +|3|`graph_id` is the 64-character geometry hash. A rename or a `metadata` change keeps it. Also adds `run.config` (`rotate_buffers`, `input_recipe`, `input_recipe_version`, `knobs`, `sweep_knobs`), `graph.input_fingerprint`, `engine` (`plan_name`, `knobs`), `timing` (`launch_mode`, `requested_warmup_iters`, `flush_method`, `flush_bytes`, `rotated_buffers`, `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 @@ -211,6 +213,8 @@ See [usage.md](usage.md#compare). | `id` | string or null | hipDNN rows: engine ID as `0x` plus 16 upper-case hex digits. rocKE and AITER rows: the row name, which is stable across runs. `null` for PyTorch rows. | | `name` | string or null | Engine name, for example `MIOPEN_ENGINE`. `pytorch` on PyTorch rows. | | `version` | string | Plugin version, or `"unavailable"`. On PyTorch rows, the torch version. | +| `plan_name` | string or null | Resolved hipDNN plan or descriptor name when exposed by the provider, else `null`. | +| `knobs` | object or null | Explicit knob tuple applied to this row, or `null` for unpinned runs. | hipDNN engine IDs are signed 64-bit integers. JSON readers that use floating-point numbers lose precision above 2^53. For this reason the file diff --git a/docs/usage.md b/docs/usage.md index 0950cc75..e467c78d 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -93,6 +93,9 @@ in the same way. |---|---|---| | `-r`, `--runtime RUNTIMES` | hipdnn | `hipdnn` runs the engine plugins. `pytorch` runs the graph through PyTorch (ROCm or CUDA). `rocke` launches rocKE kernels directly (SDPA forward today). `aiter` launches AITER SDPA forward kernels directly: `aiter:auto` (AITER's own selection) and one row per backend; `aiter:auto` runs only the `aiter:auto` row. A comma list, for example `hipdnn,rocke`, adds the rows of each runtime to each graph. See [Several runtimes](#several-runtimes). | | `-e`, `--engine ENGINES` | all discovered | Comma list of engines, run in the given order. See [Engine selection](#engine-selection). | +| `--knob KEY=VAL[,...]` | none | Comma list of explicit hipDNN knob settings (requires `--engine`). Validated strictly against the engine's exposed knobs. | +| `--sweep-knobs`, `--no-sweep-knobs` | off | Run the unpinned baseline plus every exact candidate knob tuple for each `--engine` (uses candidate enumeration or `--knob-candidates`). | +| `--knob-candidates PATH` | none | JSON file listing exact candidate knob-tuple objects for `--sweep-knobs`. | | `--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`. | @@ -753,8 +756,8 @@ The tool builds the OOTB plan through one timed path: | Plan | Knobs | Build time in JSON | |---|---|---| -| OOTB | none | `ootb.build_ms` | -| Tuned | `global.benchmarking=1` | `oracle.build_ms` | +| OOTB | none (or user `--knob` settings when given) | `ootb.build_ms` | +| Tuned | `global.benchmarking=1` (merged over user `--knob` settings when given) | `oracle.build_ms` | The build time covers only those three calls. Graph deserialization, the operation graph build and the workspace allocation are not timed. @@ -940,7 +943,7 @@ with code 143 without it. The file then holds the last periodic write. |---|---| | 0 | All engine rows ran. No engine row failed validation. A run where every row is skipped also exits 0. | | 1 | An engine row error, a graph error, a failed final result write (a failed periodic write alone does not count), no graph files found, no graph that matches `--tag`, a tarball that cannot be read, a graph store that cannot be listed or read, or a runtime that is not available at startup (hipDNN, PyTorch, rocKE or the reference provider). | -| 2 | Usage error: a bad flag (a `--tag` without `KEY=VALUE`, a store URL without a bucket), a bad config file, an option that the runtime does not support, an unknown `--engine`, an output path or a `--profiling-output-dir` that cannot be written, or a missing profiler tool. | +| 2 | Usage error: a bad flag (a `--tag` without `KEY=VALUE`, a store URL without a bucket), a bad config file, an option that the runtime does not support, an unknown `--engine`, an unknown `--knob` ID or wrong `--knob` value type, an unreadable or malformed `--knob-candidates` file, an output path or a `--profiling-output-dir` that cannot be written, or a missing profiler tool. If `-o` is set and a fatal `--knob` fails mid-run, the written file holds the graphs finished so far with `run.complete = false`. Per-graph `--knob` domain or range mismatches skip that row instead. | | 3 | At least one engine row failed validation. | | 130 | Interrupted by SIGINT (Ctrl-C). | | 143 | Interrupted by SIGTERM. On Linux the run ends within 30 seconds, also when it is blocked in GPU code. | @@ -1055,7 +1058,7 @@ Each requested pass runs this child process under its profiler: ```text python -m dnn_benchmarking --internal-profiling-run --graph G --engine E \ - --warmup W --iters 5 --seed S [--plugin-path P] [--input-recipe R] + --warmup W --iters 5 --seed S [--plugin-path P] [--input-recipe R] [--knobs-json JSON] ``` The child does not recurse and does not print on success. diff --git a/sample_configs/config.toml.example b/sample_configs/config.toml.example index 42a13853..3ca0dbb0 100644 --- a/sample_configs/config.toml.example +++ b/sample_configs/config.toml.example @@ -37,6 +37,8 @@ runtime = "hipdnn" # "hipdnn" or "pytorch" # plugin_path = "/lib/hipdnn_plugins/engines" autotune = false # benchmark candidate kernels and cache the winner +sweep_knobs = false # sweep exact candidate knob tuples for explicit engines +# knob_candidates = "/tmp/candidates.json" # exact candidate tuples for sweep_knobs # runs that do not tune, fast included, kept) and tuned/ (the same for # autotune and oracle tuned runs, kept). Default: $DNN_BENCH_WORKSPACE/work, # else $XDG_CACHE_HOME/dnn-benchmark/work, else a directory in the system diff --git a/src/dnn_benchmarking/cli/hipdnn_tuned_child.py b/src/dnn_benchmarking/cli/hipdnn_tuned_child.py index 19c1df41..bd8eeaa5 100644 --- a/src/dnn_benchmarking/cli/hipdnn_tuned_child.py +++ b/src/dnn_benchmarking/cli/hipdnn_tuned_child.py @@ -73,6 +73,12 @@ def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace: parser.add_argument("--plugin-path", type=Path) parser.add_argument("--save-outputs", action="store_true") parser.add_argument("--rotate-count", type=int, default=1) + parser.add_argument( + "--knobs", + type=lambda text: json.loads(text), + default=None, + help="Optional base knobs as a JSON object merged under global.benchmarking=1", + ) return parser.parse_args(argv) @@ -121,7 +127,8 @@ def _run(args: argparse.Namespace) -> None: # the OOTB row does. Executor(graph_json_str, policy).prime(handle, args.engine) executor = Executor(graph_json_str, policy) - executor.prepare(handle, engine_id=args.engine, knobs={BENCHMARKING_KNOB: 1}) + knobs = {**(args.knobs or {}), BENCHMARKING_KNOB: 1} + executor.prepare(handle, engine_id=args.engine, knobs=knobs) # 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) diff --git a/src/dnn_benchmarking/cli/internal_profiling.py b/src/dnn_benchmarking/cli/internal_profiling.py index f8c0d72e..af69b3db 100644 --- a/src/dnn_benchmarking/cli/internal_profiling.py +++ b/src/dnn_benchmarking/cli/internal_profiling.py @@ -11,10 +11,10 @@ Argv (built by ``profiling_orchestrator.build_inner_argv``): ``--internal-profiling-run --graph G --engine E --warmup W --iters I ---seed S [--plugin-path P] [--input-recipe R]``. The child builds the one -engine, fills the inputs exactly as the timed pass did, and dispatches -``W + I`` plain executions. It prints nothing on success so profiler log -capture stays clean. +--seed S [--plugin-path P] [--input-recipe R] [--knobs-json JSON]``. The +child builds the one engine, fills the inputs exactly as the timed pass did, +and dispatches ``W + I`` plain executions. It prints nothing on success so +profiler log capture stays clean. """ import argparse @@ -72,7 +72,12 @@ def run_internal_profiling(args: argparse.Namespace) -> int: tensor_infos = loader.extract_tensor_info(graph_json) executor = Executor(json.dumps(graph_json), policy) - executor.prepare(handle, engine_id=engine_id) + knobs_json = getattr(args, "knobs_json", None) + if knobs_json: + knobs = json.loads(knobs_json) + else: + knobs = getattr(args, "knob", None) + executor.prepare(handle, engine_id=engine_id, knobs=knobs) # sequence lengths need valid integers, not uniform noise. recipe = getattr(args, "input_recipe", "centered") if recipe == "centered": diff --git a/src/dnn_benchmarking/cli/parser.py b/src/dnn_benchmarking/cli/parser.py index 2054fb48..4228f2a3 100644 --- a/src/dnn_benchmarking/cli/parser.py +++ b/src/dnn_benchmarking/cli/parser.py @@ -185,6 +185,37 @@ def _parse_tag(s: str) -> str: return f"{key}={value}" +def _parse_knob_value(raw: str) -> Any: + """Parse a knob value string as int, float, or str.""" + text = raw.strip() + if re.fullmatch(r"[+-]?\d+", text): + return int(text) + try: + value = float(text) + if math.isfinite(value): + return value + except ValueError: + pass + return text + + +def parse_knob_list(s: str) -> Dict[str, Any]: + """Parse ``--knob`` as a comma list of ``KEY=VALUE`` pairs.""" + parts = [p.strip() for p in s.split(",") if p.strip()] + if not parts: + raise argparse.ArgumentTypeError("requires at least one KEY=VALUE pair") + knobs: Dict[str, Any] = {} + for part in parts: + if "=" not in part: + raise argparse.ArgumentTypeError(f"expected KEY=VALUE, got {part!r}") + key, raw = part.split("=", 1) + key = key.strip() + if not key: + raise argparse.ArgumentTypeError(f"empty knob name in {part!r}") + knobs[key] = _parse_knob_value(raw) + return knobs + + def _bool_option( flags: tuple[str, ...], dest: str, group: str, cls: type, field: str, help: str ) -> CliOption: @@ -384,6 +415,36 @@ def _choice_option( help="comma list of engine names, decimal IDs or 0x hex IDs, run in order " "(default: all discovered)", ), + CliOption( + flags=("--knob",), + dest="knob", + group="Runtime/Selection", + parser_type=parse_knob_list, + default=None, + metavar="KEY=VAL[,...]", + help="comma list of explicit hipDNN knob settings (requires --engine); " + "validated strictly against the engine's exposed knobs", + ), + _bool_option( + ("--sweep-knobs",), + "sweep_knobs", + "Runtime/Selection", + SuiteConfig, + "sweep_knobs", + "benchmark the unpinned baseline plus every exact candidate knob tuple " + "for each --engine (requires --engine; uses candidate enumeration or " + "--knob-candidates)", + ), + CliOption( + flags=("--knob-candidates",), + dest="knob_candidates", + group="Runtime/Selection", + parser_type=Path, + metavar="PATH", + help="JSON file listing exact candidate knob-tuple objects for --sweep-knobs", + config_key="knob_candidates", + config_kind=ConfigKind.PATH, + ), CliOption( flags=("--plugin-path",), dest="plugin_path", @@ -771,7 +832,14 @@ def create_parser(*, suppress_defaults: bool = False) -> argparse.ArgumentParser default=False, help=argparse.SUPPRESS, ) - # Hidden: the --oracle tuned-PyTorch child of a graph that the parent + # Hidden: typed knob dict passed as JSON to --internal-profiling-run so + # string/bool/int/float types never mutate through K=V text re-parsing. + parser.add_argument( + "--knobs-json", + dest="knobs_json", + default=None, + help=argparse.SUPPRESS, + ) # remeasured after a stall-gate failure times unstalled too. parser.add_argument( "--no-stall-gate", diff --git a/src/dnn_benchmarking/cli/suite_runner_cli.py b/src/dnn_benchmarking/cli/suite_runner_cli.py index af393df0..254002bf 100644 --- a/src/dnn_benchmarking/cli/suite_runner_cli.py +++ b/src/dnn_benchmarking/cli/suite_runner_cli.py @@ -14,7 +14,7 @@ from pathlib import Path from typing import Any, Callable, Dict, List, Optional -from ..common.exceptions import UnsupportedGraphError +from ..common.exceptions import ExecutionError, InvalidKnobError, UnsupportedGraphError from ..common.pytorch_tuning import apply_pytorch_environment from ..common.work_dir import env_switch_on, ootb_state, tuned_state, work_dir from ..config.benchmark_config import ( @@ -139,6 +139,17 @@ def run_suite_cli( reporter.error(message) if missing: return 2 + if config.knob_candidates is not None: + from ..execution.knob_sweep import load_knob_candidates + + try: + config.parsed_knob_candidates = tuple( + load_knob_candidates(config.knob_candidates) + ) + except ExecutionError as e: + reporter.error(str(e)) + 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. @@ -222,6 +233,8 @@ def _run_config(config: SuiteConfig) -> Dict[str, Any]: "seed": config.seed, "input_recipe": config.input_recipe, "input_recipe_version": INPUT_RECIPE_VERSION, + "knobs": dict(config.knobs) if config.knobs else None, + "sweep_knobs": config.sweep_knobs, "validate": ( config.validation.provider.value if config.validation.enabled else None ), @@ -264,6 +277,8 @@ def _run_one_graph(graph_path: Path, run_graph: GraphRunner) -> GraphResult: loader.validate(graph_json) tensor_infos = loader.extract_tensor_info(graph_json) return run_graph(graph_path, graph_json, tensor_infos) + except InvalidKnobError: + raise except UnsupportedGraphError as e: return GraphResult( graph_name=graph_path.stem, @@ -314,6 +329,7 @@ def write() -> bool: return False interrupted: Optional[int] = None + invalid_knob: Optional[str] = None previous_sigterm = ( signal.signal(signal.SIGTERM, _raise_terminated) if signal.getsignal(signal.SIGTERM) is not None @@ -332,6 +348,8 @@ def write() -> bool: last_write = time.monotonic() suite.run.finished_at = _now() suite.run.complete = True + except InvalidKnobError as e: + invalid_knob = str(e) except KeyboardInterrupt: interrupted = 130 except _Terminated: @@ -356,6 +374,9 @@ def write() -> bool: if previous_sigterm is not None: signal.signal(signal.SIGTERM, previous_sigterm) + if invalid_knob is not None: + reporter.error(invalid_knob) + return 2 if interrupted is not None: where = ( f"partial results in {output_path}" diff --git a/src/dnn_benchmarking/common/exceptions.py b/src/dnn_benchmarking/common/exceptions.py index c41f92c1..9f8b44b9 100644 --- a/src/dnn_benchmarking/common/exceptions.py +++ b/src/dnn_benchmarking/common/exceptions.py @@ -26,3 +26,15 @@ class UnsupportedGraphError(ExecutionError): """ pass + + +class InvalidKnobError(ExecutionError): + """Raised when a requested hipDNN knob ID or value type is invalid for an engine.""" + + pass + + +class KnobConstraintError(InvalidKnobError): + """Raised when a hipDNN knob value violates a per-graph domain or range constraint.""" + + pass diff --git a/src/dnn_benchmarking/config/benchmark_config.py b/src/dnn_benchmarking/config/benchmark_config.py index a5aa1a9a..a3ae9a01 100644 --- a/src/dnn_benchmarking/config/benchmark_config.py +++ b/src/dnn_benchmarking/config/benchmark_config.py @@ -45,6 +45,9 @@ class RuntimeName(str, Enum): RuntimeName.HIPDNN: frozenset( { "--engine", + "--knob", + "--sweep-knobs", + "--knob-candidates", "--pmc", "--trace", "--perf", @@ -482,6 +485,16 @@ class SuiteConfig: timing_block: int = 1 #: Named input-value generation recipe (see INPUT_RECIPE_CHOICES). input_recipe: str = "centered" + #: Explicit hipDNN knob pins (``knob_id -> int|float|str``). + knobs: Optional[Dict[str, Any]] = None + #: Sweep exact candidate knob tuples for explicit hipDNN engines. + sweep_knobs: bool = False + #: Optional JSON file supplying exact candidate knob tuples for ``--sweep-knobs``. + knob_candidates: Optional[Path] = None + #: Preloaded candidates from ``knob_candidates``, populated at CLI startup. + parsed_knob_candidates: Optional[Tuple[Any, ...]] = field( + default=None, init=False, repr=False + ) #: Suppress progress output; tables and the summary still print. quiet: bool = False #: Write the JSON result without whitespace (default: one-space indent). @@ -524,6 +537,9 @@ def from_namespace(cls, args: argparse.Namespace) -> "SuiteConfig": seed=args.seed, input_recipe=getattr(args, "input_recipe", "centered"), engine_filter=args.engine, + knobs=getattr(args, "knob", None), + sweep_knobs=bool(getattr(args, "sweep_knobs", False)), + knob_candidates=getattr(args, "knob_candidates", None), verbose=args.verbose, quiet=args.quiet, compact_json=args.compact_json, @@ -565,6 +581,8 @@ def __post_init__(self) -> None: raise ValueError( "--input-recipe must be one of: " + ", ".join(INPUT_RECIPE_CHOICES) ) + if isinstance(self.knob_candidates, str): + self.knob_candidates = Path(self.knob_candidates) self.timing_policy = TimingPolicy( warmup_iters=self.warmup_iters, iters=self.benchmark_iters, @@ -615,8 +633,24 @@ def __post_init__(self) -> None: self.pytorch_sdpa_backend, self.pytorch_rocm_fa_library, ) + if self.knobs and self.engine_filter is None: + raise ValueError("--knob requires --engine") + if self.knobs and self.sweep_knobs: + raise ValueError("--knob cannot be combined with --sweep-knobs") + if self.sweep_knobs: + if self.engine_filter is None: + raise ValueError("--sweep-knobs requires --engine") + if self.autotune or self.oracle: + raise ValueError( + "--sweep-knobs cannot be combined with --autotune or --oracle" + ) + if self.knob_candidates is not None and not self.sweep_knobs: + raise ValueError("--knob-candidates requires --sweep-knobs") runtime_options = [ ("--engine", self.engine_filter is not None), + ("--knob", bool(self.knobs)), + ("--sweep-knobs", self.sweep_knobs), + ("--knob-candidates", self.knob_candidates is not None), ("--pmc", self.metrics.pmc_set is not None), ("--trace", self.metrics.trace), ("--perf", self.metrics.perf), @@ -654,6 +688,7 @@ def _check_fast(self) -> None: rejected = [ ("--validate", self.validation.enabled), ("--oracle", self.oracle), + ("--sweep-knobs", self.sweep_knobs), ("--pmc", self.metrics.pmc_set is not None), ("--trace", self.metrics.trace), ("--perf", self.metrics.perf), diff --git a/src/dnn_benchmarking/execution/executor.py b/src/dnn_benchmarking/execution/executor.py index 8e3e08b3..38c247fd 100644 --- a/src/dnn_benchmarking/execution/executor.py +++ b/src/dnn_benchmarking/execution/executor.py @@ -9,6 +9,7 @@ from ..common.exceptions import ExecutionError, UnsupportedGraphError from ..config.benchmark_config import TimingPolicy from ..reporting.suite_results import engine_id_hex +from .knob_sweep import validate_knobs_strict from .timing import Measurement, StallFallbackError, Timer, device_sync, measure @@ -38,6 +39,8 @@ def __init__(self, graph_json_str: str, policy: TimingPolicy) -> None: self._workspace_ptr: int = 0 self._workspace_size: int = 0 self._build_time_ms: float = 0.0 + self._plan_name: Optional[str] = None + self._validated_knobs: Optional[Dict[str, Any]] = None def _build_through_operation_graph(self, handle: Any) -> Any: """Create the hipdnn graph and run it up to ``build_operation_graph``. @@ -151,11 +154,36 @@ def prime(self, handle: Any, engine_id: int) -> None: self._build_plan(hipdnn, engine_id, None) self._graph = None + def _get_exposed_knobs(self, engine_id: int) -> Any: + """Query knobs for ``engine_id``, mapping inapplicable engines to ``UnsupportedGraphError``.""" + try: + return self._graph.get_knobs_for_engine(engine_id) + except RuntimeError as e: + raise UnsupportedGraphError( + f"Forced engine {engine_id_hex(engine_id)} not applicable " + f"to this graph: {e}" + ) from e + + def validate_knobs( + self, handle: Any, engine_id: int, knobs: Dict[str, Any] + ) -> Dict[str, Any]: + """Validate ``knobs`` against ``engine_id`` without priming or building a plan.""" + if not knobs: + return {} + self._build_through_operation_graph(handle) + try: + exposed = self._get_exposed_knobs(engine_id) + return validate_knobs_strict(exposed, knobs) + finally: + self._graph = None + def _build_plan( self, hipdnn: Any, engine_id: Optional[int], knobs: Optional[Dict[str, Any]], + *, + strict_knobs: bool = False, ) -> None: """Create, support-check, and compile the execution plan.""" if engine_id is not None: @@ -163,9 +191,14 @@ def _build_plan( # create_execution_plan_ext reports a bad result if the engine is # not valid/applicable, so it can never silently fall back to a # different engine the way the soft preferred-engine path could. + effective_knobs = knobs or {} + if strict_knobs and effective_knobs: + exposed = self._get_exposed_knobs(engine_id) + effective_knobs = validate_knobs_strict(exposed, effective_knobs) + self._validated_knobs = dict(effective_knobs) if effective_knobs else None settings = [ hipdnn.KnobSetting(knob_id, value) - for knob_id, value in (knobs or {}).items() + for knob_id, value in effective_knobs.items() ] result = self._graph.create_execution_plan_ext(engine_id, settings) if result.is_bad(): @@ -174,6 +207,7 @@ def _build_plan( f"to this graph: {result.get_message()}" ) else: + self._validated_knobs = None result = self._graph.create_execution_plans() if result.is_bad(): raise ExecutionError( @@ -195,6 +229,8 @@ def prepare( handle: Any, engine_id: Optional[int] = None, knobs: Optional[Dict[str, Any]] = None, + *, + strict_knobs: bool = False, ) -> None: """Build the operation graph and one execution plan. @@ -206,11 +242,14 @@ def prepare( engine_id: Build the plan for exactly this engine. When None, the backend heuristic picks the engine. knobs: Knob settings for the ``engine_id`` plan, keyed by knob id. + With ``strict_knobs=True``, unknown or out-of-domain knobs + raise ``UnsupportedGraphError`` instead of being dropped. + strict_knobs: Enforce strict knob validation before plan creation. Raises: ValueError: If ``knobs`` is given without ``engine_id``. ExecutionError: If graph building fails. - UnsupportedGraphError: If support check fails. + UnsupportedGraphError: If strict knob validation or support fails. """ if knobs and engine_id is None: raise ValueError("knobs require an explicit engine_id") @@ -218,10 +257,18 @@ def prepare( hipdnn = self._build_through_operation_graph(handle) with Timer() as build_timer: - self._build_plan(hipdnn, engine_id, knobs) + self._build_plan(hipdnn, engine_id, knobs, strict_knobs=strict_knobs) self._build_time_ms = build_timer.elapsed_ms self._check_selected_engine(engine_id) + get_plan_name = getattr(self._graph, "get_plan_name", None) + if callable(get_plan_name): + try: + name = get_plan_name() + self._plan_name = str(name) if name else None + except Exception: + self._plan_name = None + workspace_size = self._graph.get_workspace_size() self._workspace_size = int(workspace_size) if workspace_size > 0: @@ -330,6 +377,16 @@ def enqueue_rotating() -> None: except RuntimeError as e: raise ExecutionError(str(e)) from e + @property + def plan_name(self) -> Optional[str]: + """Resolved plan/descriptor name reported by hipDNN, if available.""" + return self._plan_name + + @property + def validated_knobs(self) -> Optional[Dict[str, Any]]: + """Validated, type-coerced knobs applied during ``prepare()``.""" + return self._validated_knobs + @property def build_time_ms(self) -> float: """Plan create, support check and compile time in milliseconds.""" diff --git a/src/dnn_benchmarking/execution/knob_sweep.py b/src/dnn_benchmarking/execution/knob_sweep.py new file mode 100644 index 00000000..3153c78b --- /dev/null +++ b/src/dnn_benchmarking/execution/knob_sweep.py @@ -0,0 +1,221 @@ +# Copyright © Advanced Micro Devices, Inc., or its affiliates. +# SPDX-License-Identifier: MIT + +"""Exact candidate-tuple knob discovery and strict knob validation for hipDNN. + +Hard engine selection in hipDNN warns and drops unknown knobs rather than +failing. This module validates user-supplied ``--knob`` settings strictly +against the engine's exposed knobs, and discovers exact candidate tuples for +``--sweep-knobs`` without blindly expanding a Cartesian product of marginal +knob domains. +""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence + +from ..common.exceptions import ExecutionError, InvalidKnobError, KnobConstraintError + + +@dataclass(frozen=True) +class KnobCandidate: + """One exact candidate kernel tuple for a hipDNN engine.""" + + candidate_id: str + knobs: Dict[str, Any] + + +def _parse_candidate_entry(index: int, entry: Any) -> KnobCandidate: + """Normalize one candidate entry from JSON or ``hipdnn_bench enumerate``.""" + if not isinstance(entry, dict): + raise ExecutionError( + f"Candidate entry {index} must be a JSON object, got {type(entry).__name__}" + ) + if "knobs" in entry and isinstance(entry["knobs"], dict): + knobs = dict(entry["knobs"]) + cid = str( + entry.get("id") + or entry.get("candidate_id") + or entry.get("descriptor_id") + or entry.get("name") + or f"c{index}" + ) + return KnobCandidate(candidate_id=cid, knobs=knobs) + if "knob_settings" in entry and isinstance(entry["knob_settings"], dict): + knobs = dict(entry["knob_settings"]) + cid = str( + entry.get("id") + or entry.get("candidate_id") + or entry.get("descriptor_id") + or entry.get("name") + or f"c{index}" + ) + return KnobCandidate(candidate_id=cid, knobs=knobs) + # Plain dict of knob_id -> value. + cid = ",".join(f"{k}={v}" for k, v in sorted(entry.items())) or f"c{index}" + return KnobCandidate(candidate_id=cid, knobs=dict(entry)) + + +def load_knob_candidates(path: Path) -> List[KnobCandidate]: + """Load exact candidate knob tuples from a JSON file.""" + try: + raw = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as e: + raise ExecutionError(f"Cannot read --knob-candidates {path}: {e}") from e + if isinstance(raw, dict) and isinstance(raw.get("candidates"), list): + items = raw["candidates"] + elif isinstance(raw, list): + items = raw + else: + raise ExecutionError( + f"--knob-candidates {path} must contain a JSON array or " + "{'candidates': [...]}" + ) + if not items: + raise ExecutionError(f"--knob-candidates {path} contains no candidates") + return [_parse_candidate_entry(i, item) for i, item in enumerate(items)] + + +def _find_hipdnn_bench() -> Optional[str]: + """Locate ``hipdnn_bench`` on PATH or under ``$ROCM_PATH/bin``.""" + found = shutil.which("hipdnn_bench") + if found: + return found + rocm_path = os.environ.get("ROCM_PATH") + if rocm_path: + candidate = Path(rocm_path) / "bin" / "hipdnn_bench" + if candidate.is_file() and os.access(candidate, os.X_OK): + return str(candidate) + return None + + +def enumerate_candidates( + *, + graph_path: Path, + engine_name: str, + plugin_path: Optional[Path] = None, + engine_id: Optional[int] = None, + candidates_file: Optional[Path] = None, + preloaded_candidates: Optional[Sequence[KnobCandidate]] = None, +) -> List[KnobCandidate]: + """Enumerate exact candidate tuples for one hipDNN engine on one graph. + + Discovery order: + 1. Preloaded candidates (parsed at CLI startup from ``--knob-candidates``). + 2. Explicit ``--knob-candidates`` JSON file. + 3. ``hipdnn_bench enumerate --json`` subprocess (discovery only; timing + always runs through ``dnn_benchmarking``). + """ + if preloaded_candidates is not None: + return list(preloaded_candidates) + if candidates_file is not None: + return load_knob_candidates(candidates_file) + + bench = _find_hipdnn_bench() + if bench is None: + raise ExecutionError( + "--sweep-knobs requires exact candidate enumeration via " + "hipdnn_bench on PATH or --knob-candidates " + ) + cmd = [ + bench, + "enumerate", + "--json", + "--graph", + str(graph_path), + "--engine-name", + engine_name, + ] + if plugin_path is not None: + pdir = plugin_path.parent if plugin_path.is_file() else plugin_path + cmd += ["--plugin-dir", str(pdir)] + try: + proc = subprocess.run( + cmd, check=False, capture_output=True, text=True, timeout=60 + ) + except (OSError, subprocess.SubprocessError) as e: + raise ExecutionError(f"hipdnn_bench enumerate failed: {e}") from e + if proc.returncode != 0: + detail = (proc.stderr or proc.stdout or "").strip() + raise ExecutionError( + f"hipdnn_bench enumerate exited {proc.returncode}: {detail}" + ) + try: + payload = json.loads(proc.stdout) + except json.JSONDecodeError as e: + raise ExecutionError( + f"hipdnn_bench enumerate returned invalid JSON: {e}" + ) from e + items = ( + payload.get("candidates", []) + if isinstance(payload, dict) + else payload if isinstance(payload, list) else [] + ) + return [_parse_candidate_entry(i, item) for i, item in enumerate(items)] + + +def _coerce_and_check_constraint(knob_id: str, knob: Any, value: Any) -> Any: + """Validate ``value`` against a hipDNN ``Knob`` value type and constraint.""" + vtype = str(getattr(knob, "value_type", "")).upper() + if "INT" in vtype: + if isinstance(value, bool) or not isinstance(value, int): + raise InvalidKnobError( + f"Knob {knob_id!r} expects an integer, got {value!r}" + ) + elif "FLOAT" in vtype or "DOUBLE" in vtype: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise InvalidKnobError(f"Knob {knob_id!r} expects a float, got {value!r}") + value = float(value) + elif "STRING" in vtype: + if not isinstance(value, str): + value = str(value) + + constraint = getattr(knob, "constraint", None) + if constraint is None: + return value + valid_values = getattr(constraint, "valid_values", None) + if valid_values: + allowed = list(valid_values) + if value not in allowed: + raise KnobConstraintError( + f"Knob {knob_id!r}={value!r} is not in allowed values {allowed}" + ) + min_val = getattr(constraint, "min_value", None) + max_val = getattr(constraint, "max_value", None) + if min_val is not None and value < min_val: + raise KnobConstraintError( + f"Knob {knob_id!r}={value!r} is below minimum {min_val!r}" + ) + if max_val is not None and value > max_val: + raise KnobConstraintError( + f"Knob {knob_id!r}={value!r} exceeds maximum {max_val!r}" + ) + return value + + +def validate_knobs_strict( + exposed_knobs: Sequence[Any], requested: Dict[str, Any] +) -> Dict[str, Any]: + """Verify every requested knob exists on the engine and meets its constraint. + + Raises: + InvalidKnobError: Any requested knob is unknown or out of domain. + """ + by_id = {str(k.knob_id): k for k in exposed_knobs} + validated: Dict[str, Any] = {} + for knob_id, raw_value in requested.items(): + if knob_id not in by_id: + avail = ", ".join(sorted(by_id)) or "none" + raise InvalidKnobError( + f"Knob {knob_id!r} is not exposed by this engine (available: {avail})" + ) + validated[knob_id] = _coerce_and_check_constraint( + knob_id, by_id[knob_id], raw_value + ) + return validated diff --git a/src/dnn_benchmarking/execution/oracle.py b/src/dnn_benchmarking/execution/oracle.py index 8a971934..d0dc136a 100644 --- a/src/dnn_benchmarking/execution/oracle.py +++ b/src/dnn_benchmarking/execution/oracle.py @@ -129,6 +129,7 @@ def _hipdnn_tuned_argv( save_outputs: bool, *, rotate_count: int = 1, + knobs: Optional[Dict[str, Any]] = None, ) -> List[str]: """Argv of ``cli/hipdnn_tuned_child.py``, with the full timing policy.""" argv = [ @@ -154,6 +155,8 @@ def _hipdnn_tuned_argv( argv.append("--save-outputs") if rotate_count > 1: argv += ["--rotate-count", str(rotate_count)] + if knobs: + argv += ["--knobs", json.dumps(knobs)] return argv @@ -207,6 +210,8 @@ def run_hipdnn_tuned( child_extra: Dict[str, Any] = {} if rotate_count > 1: child_extra["rotate_count"] = rotate_count + if row.knobs: + child_extra["knobs"] = row.knobs result = _run_hipdnn_tuned_child( graph_path, engine_id, @@ -259,6 +264,7 @@ def _run_hipdnn_tuned_child( save_outputs: bool, *, rotate_count: int = 1, + knobs: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: """Run ``cli/hipdnn_tuned_child.py``; return its ``result.json``. @@ -280,6 +286,7 @@ def _run_hipdnn_tuned_child( out_dir, save_outputs, rotate_count=rotate_count, + knobs=knobs, ) try: proc = run_capped(argv, timeout_s, env=_hipdnn_tuned_env(config, out_dir)) diff --git a/src/dnn_benchmarking/execution/suite_runner.py b/src/dnn_benchmarking/execution/suite_runner.py index dba180e6..81b93a08 100644 --- a/src/dnn_benchmarking/execution/suite_runner.py +++ b/src/dnn_benchmarking/execution/suite_runner.py @@ -32,6 +32,8 @@ from ..common.exceptions import ( ExecutionError, + InvalidKnobError, + KnobConstraintError, UnsupportedGraphError, ) from ..config.benchmark_config import ( @@ -48,6 +50,7 @@ input_fingerprint, ) from ..execution.executor import Executor +from ..execution.knob_sweep import enumerate_candidates from ..execution.timing import ( MIXED_MODE_RERUN_REASON, STALL_RERUN_REASON, @@ -729,6 +732,10 @@ def run_single_provider_engine( engine_name: str, engine_version: str, plugin_path: Optional[Path], + *, + knobs: Optional[Dict[str, Any]] = None, + strict_knobs: bool = False, + knob_errors_fatal: bool = False, ) -> ProviderEngineResult: """Build, time and validate one hipDNN engine; then its tuned run in a child.""" config = ctx.config @@ -740,14 +747,34 @@ def run_single_provider_engine( status="success", engine_version=engine_version, plugin_path=plugin, + knobs=dict(knobs) if knobs else None, ) memory_at_start = _gpu_memory_at_row_start() try: + effective_knobs = dict(knobs) if knobs else None + if effective_knobs and strict_knobs and knob_errors_fatal: + validator = Executor(ctx.graph_json_str, config.timing_policy) + effective_knobs = validator.validate_knobs( + handle, engine_id, effective_knobs + ) + row.knobs = dict(effective_knobs) # Absorb the engine's one-time build costs (provider setup, cold # plugin and kernel file reads) before the timed build. primer.prime(handle, ctx.graph_json_str, config.timing_policy, engine_id) executor = Executor(ctx.graph_json_str, config.timing_policy) - executor.prepare(handle, engine_id=engine_id) + if effective_knobs: + executor.prepare( + handle, + engine_id=engine_id, + knobs=effective_knobs, + strict_knobs=strict_knobs, + ) + validated = getattr(executor, "validated_knobs", None) + if validated: + row.knobs = dict(validated) + else: + executor.prepare(handle, engine_id=engine_id) + row.plan_name = getattr(executor, "plan_name", None) row.ootb.cpu_build_time_ms = executor.build_time_ms if config.metrics.basic: row.ootb.workspace_bytes = executor.workspace_size @@ -792,6 +819,12 @@ def run_single_provider_engine( del executor except StallFallbackError: raise # run_graph remeasures the whole graph unstalled. + except KnobConstraintError as e: + return _failed_row(ProviderEngineResult.skipped_row, row, str(e)) + except InvalidKnobError as e: + if knob_errors_fatal: + raise + return _failed_row(ProviderEngineResult.skipped_row, row, str(e)) except UnsupportedGraphError as e: return _failed_row(ProviderEngineResult.skipped_row, row, str(e)) except Exception as e: @@ -895,6 +928,8 @@ def _run_profiling( prof_extra: Dict[str, Any] = {} if ctx.config.input_recipe != "centered": prof_extra["input_recipe"] = ctx.config.input_recipe + if row.knobs: + prof_extra["knobs"] = row.knobs extra = run_profiling_passes( graph_path=ctx.graph_path, engine_id=engine_id, @@ -1311,8 +1346,11 @@ def plan( "hipdnn", engine_ids=engine_ids, rows=lambda ctx: [ - _run_engine_selection(ctx, handle, primer, s.engine_id, s.plugin_path) + row for s in selections + for row in _run_engine_selection( + ctx, handle, primer, s.engine_id, s.plugin_path + ) ], message=message, needs_inputs=True, @@ -1327,8 +1365,8 @@ def _run_engine_selection( primer: EnginePrimer, engine_id: int, plugin_path: Optional[Path], -) -> ProviderEngineResult: - """One engine row, creating a plugin-scoped handle when none is shared.""" +) -> List[ProviderEngineResult]: + """Run one engine selection (plus candidate-tuple sweep rows when requested).""" if handle is None: try: import hipdnn_frontend as hipdnn @@ -1337,25 +1375,97 @@ def _run_engine_selection( handle = hipdnn.Handle() except Exception as e: label = engine_id_hex(engine_id) or "" - return _report_row( + return [ + _report_row( + ctx.reporter, + label, + lambda: ProviderEngineResult.error_row( + "hipdnn", + engine_id, + f"{type(e).__name__}: {e}", + engine_name=label, + plugin_path=str(plugin_path) if plugin_path else None, + ), + ) + ] + name, version = _engine_identity(handle, engine_id) + if not ctx.config.sweep_knobs: + knobs = ctx.config.knobs + return [ + _report_row( ctx.reporter, - label, + name, + lambda: run_single_provider_engine( + ctx, + handle, + primer, + engine_id, + name, + version, + plugin_path, + knobs=knobs, + strict_knobs=bool(knobs), + knob_errors_fatal=bool(knobs), + ), + ) + ] + + # --sweep-knobs: measure the unpinned baseline first, then each exact + # candidate tuple discovered for this engine on this graph. + rows: List[ProviderEngineResult] = [ + _report_row( + ctx.reporter, + name, + lambda: run_single_provider_engine( + ctx, handle, primer, engine_id, name, version, plugin_path + ), + ) + ] + try: + candidates = enumerate_candidates( + graph_path=ctx.graph_path, + engine_name=name, + plugin_path=plugin_path, + engine_id=engine_id, + candidates_file=ctx.config.knob_candidates, + preloaded_candidates=ctx.config.parsed_knob_candidates, + ) + except Exception as e: + rows.append( + _report_row( + ctx.reporter, + f"{name}[sweep]", lambda: ProviderEngineResult.error_row( "hipdnn", engine_id, f"{type(e).__name__}: {e}", - engine_name=label, + engine_name=f"{name}[sweep]", plugin_path=str(plugin_path) if plugin_path else None, ), ) - name, version = _engine_identity(handle, engine_id) - return _report_row( - ctx.reporter, - name, - lambda: run_single_provider_engine( - ctx, handle, primer, engine_id, name, version, plugin_path - ), - ) + ) + return rows + + for cand in candidates: + label = f"{name}[{cand.candidate_id}]" + rows.append( + _report_row( + ctx.reporter, + label, + lambda c=cand, lbl=label: run_single_provider_engine( + ctx, + handle, + primer, + engine_id, + lbl, + version, + plugin_path, + knobs=c.knobs, + strict_knobs=True, + ), + ) + ) + return rows def pytorch_plan( diff --git a/src/dnn_benchmarking/metrics/profiling_orchestrator.py b/src/dnn_benchmarking/metrics/profiling_orchestrator.py index 2c06a497..f4e5e4be 100644 --- a/src/dnn_benchmarking/metrics/profiling_orchestrator.py +++ b/src/dnn_benchmarking/metrics/profiling_orchestrator.py @@ -21,6 +21,7 @@ """ import hashlib +import json import re import sys from datetime import datetime, timezone @@ -118,12 +119,14 @@ def build_inner_argv( plugin_path: Optional[Path], *, input_recipe: str = "centered", + knobs: Optional[Dict[str, Any]] = None, ) -> List[str]: """Argv for the ``--internal-profiling-run`` child (frozen contract). ``-m dnn_benchmarking --internal-profiling-run --graph G --engine E - --warmup W --iters I --seed S [--plugin-path P] [--input-recipe R]``. - No profiling flag is ever forwarded, so the child cannot recurse. + --warmup W --iters I --seed S [--plugin-path P] [--input-recipe R] + [--knobs-json JSON]``. No profiling flag is ever forwarded, so the child + cannot recurse. """ argv = [ sys.executable, @@ -145,6 +148,8 @@ def build_inner_argv( argv += ["--plugin-path", str(plugin_path)] if input_recipe != "centered": argv += ["--input-recipe", input_recipe] + if knobs: + argv += ["--knobs-json", json.dumps(knobs, sort_keys=True)] return argv @@ -218,6 +223,7 @@ def run_profiling_passes( out_dir: Optional[Path] = None, *, input_recipe: str = "centered", + knobs: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: """Run every requested profiling source. Returns a merged dict. @@ -252,6 +258,7 @@ def run_profiling_passes( iters, plugin_path, input_recipe=input_recipe, + knobs=knobs, ) context = f"{graph_path.stem}/{engine_name}" sources = ( diff --git a/src/dnn_benchmarking/reporting/suite_results.py b/src/dnn_benchmarking/reporting/suite_results.py index 523a5c88..97629af5 100644 --- a/src/dnn_benchmarking/reporting/suite_results.py +++ b/src/dnn_benchmarking/reporting/suite_results.py @@ -48,6 +48,8 @@ "seed", "input_recipe", "input_recipe_version", + "knobs", + "sweep_knobs", "validate", "rtol", "atol", @@ -390,6 +392,8 @@ class ProviderEngineResult: oracle_error: Optional[str] = None clocks_after: Optional[Dict[str, Any]] = None engine_name: Optional[str] = None + plan_name: Optional[str] = None + knobs: Optional[Dict[str, Any]] = None flops_formula_version: Optional[int] = None def __post_init__(self) -> None: @@ -486,6 +490,8 @@ def to_dict(self) -> Dict[str, Any]: ), "name": self.engine_name, "version": self.engine_version, + "plan_name": self.plan_name, + "knobs": self.knobs, }, "status": self.status, "verdict": self.verdict, diff --git a/tests/unit/cli/test_suite_cli.py b/tests/unit/cli/test_suite_cli.py index 9fba6427..e244c4b9 100644 --- a/tests/unit/cli/test_suite_cli.py +++ b/tests/unit/cli/test_suite_cli.py @@ -526,6 +526,8 @@ def test_run_config_records_effective_values_that_compare_checks( "seed": 7, "input_recipe": "centered", "input_recipe_version": 1, + "knobs": None, + "sweep_knobs": False, "validate": "pytorch", "rtol": None, "atol": None, diff --git a/tests/unit/reporting/test_schema_v3.py b/tests/unit/reporting/test_schema_v3.py index 7ccf3251..31bab7cd 100644 --- a/tests/unit/reporting/test_schema_v3.py +++ b/tests/unit/reporting/test_schema_v3.py @@ -25,7 +25,7 @@ CONFIG_KEYS = { "runtime", "runtimes", "engine_filter", "plugin_paths", "warmup_iters", "iters", "min_time_ms", "cache_mode", "rotate_buffers", "timing_block", "seed", - "input_recipe", "input_recipe_version", "validate", + "input_recipe", "input_recipe_version", "knobs", "sweep_knobs", "validate", "rtol", "atol", "reference_precision", "oracle", "autotune", "benchmark_work_dir", "fresh_state", "fast", "pytorch_sdpa_backend", "pytorch_rocm_fa_library", "pytorch_dispatch", @@ -61,7 +61,7 @@ "elapsed_s", "metrics", "ootb", "oracle", "oracle_error", "warnings", "extra_metrics", } # fmt: skip -ENGINE_KEYS = {"id", "name", "version"} +ENGINE_KEYS = {"id", "name", "version", "plan_name", "knobs"} METRICS_KEYS = {"flops", "flops_formula_version", "io_bytes", "clocks_after"} PLAN_KEYS = { "build_ms", "timing", "kernel", "host", "workspace_bytes", "tflops", "gbps", @@ -236,6 +236,8 @@ def test_full_row_values() -> None: "id": "0x15B46865C717A122", "name": "MIOPEN_ENGINE", "version": "1.0", + "plan_name": None, + "knobs": None, } assert row["metrics"] == { "flops": 10**9, diff --git a/tests/unit/test_perf_integrity.py b/tests/unit/test_perf_integrity.py index 26c1e32d..c08b719f 100644 --- a/tests/unit/test_perf_integrity.py +++ b/tests/unit/test_perf_integrity.py @@ -15,6 +15,7 @@ import pytest from dnn_benchmarking.cli import hipdnn_tuned_child, suite_runner_cli +from dnn_benchmarking.cli.parser import parse_knob_list from dnn_benchmarking.config.benchmark_config import ( INPUT_RECIPE_CHOICES, SuiteConfig, @@ -27,6 +28,10 @@ input_fingerprint, ) from dnn_benchmarking.execution.correctness import check_correctness +from dnn_benchmarking.execution.knob_sweep import ( + load_knob_candidates, + validate_knobs_strict, +) from dnn_benchmarking.execution.sdpa_graph import DenseSdpa from dnn_benchmarking.graph.tensor_info import TensorInfo from dnn_benchmarking.metrics import gpu_smi @@ -116,7 +121,7 @@ def _write_suite(tmp_path: Path, fname: str, graphs, **cfg) -> str: return str(out) -# --- P0: Compare compatibility, validation loopholes, and exact thresholds --- +# --- Compare compatibility, validation completeness, and exact thresholds --- def test_compare_excludes_mixed_timing_modes_by_default(tmp_path, capsys) -> None: @@ -285,7 +290,7 @@ def test_reporter_refuses_vs_best_across_mixed_modes() -> None: assert "1.00x" not in text -# --- P1: AITER guards, AMD SMI handle/in-run telemetry, signal restore, fresh oracle --- +# --- AITER guards, AMD SMI handle/in-run telemetry, signal restore, fresh oracle --- def _sdpa(**kw) -> DenseSdpa: @@ -570,7 +575,7 @@ def test_signal_restore_skips_native_none_handlers(tmp_path, monkeypatch) -> Non assert calls == [] -# --- Analytical FLOPs and timer resolution warnings --- +# --- Cache modes, input recipes, and strict knob validation --- def test_flush_bytes_for_arch_and_rotate_policy() -> None: @@ -623,6 +628,43 @@ def test_all_input_recipes_finite_deterministic_and_fingerprinted(recipe) -> Non assert input_fingerprint(mutated, recipe, 42) != fp1 +def test_knob_parsing_strict_validation_and_candidate_file(tmp_path) -> None: + from dnn_benchmarking.common.exceptions import InvalidKnobError, KnobConstraintError + + assert parse_knob_list("block_m=256,scale=1.5,mode=fast") == { + "block_m": 256, + "scale": 1.5, + "mode": "fast", + } + + knob = types.SimpleNamespace( + knob_id="block_m", + value_type="INT64", + constraint=types.SimpleNamespace(valid_values=[64, 128, 256]), + ) + assert validate_knobs_strict([knob], {"block_m": 128}) == {"block_m": 128} + # Unknown knob ID and wrong type raise base InvalidKnobError (fatal), not KnobConstraintError. + with pytest.raises(InvalidKnobError, match="not exposed") as exc_unknown: + validate_knobs_strict([knob], {"unknown_knob": 1}) + assert not isinstance(exc_unknown.value, KnobConstraintError) + with pytest.raises(InvalidKnobError, match="integer") as exc_type: + validate_knobs_strict([knob], {"block_m": "not_an_int"}) + assert not isinstance(exc_type.value, KnobConstraintError) + # Per-graph constraint failure raises KnobConstraintError (non-fatal skip). + with pytest.raises(KnobConstraintError, match="allowed values"): + validate_knobs_strict([knob], {"block_m": 32}) + + cfile = tmp_path / "cands.json" + cfile.write_text( + json.dumps([{"id": "t1", "knobs": {"block_m": 128}}, {"block_m": 256}]) + ) + cands = load_knob_candidates(cfile) + assert [(c.candidate_id, c.knobs) for c in cands] == [ + ("t1", {"block_m": 128}), + ("block_m=256", {"block_m": 256}), + ] + + # --- Analytical FLOPs and timer resolution warnings --- @@ -865,23 +907,32 @@ def create_variant_pack(self): out_dir, False, rotate_count=3, + knobs={"block_m": 128}, ) assert "--rotate-count" in argv and argv[argv.index("--rotate-count") + 1] == "3" + assert "--knobs" in argv rc = hipdnn_tuned_child.main(argv[3:]) assert rc == 0 - assert seen["knobs"] == {oracle.BENCHMARKING_KNOB: 1} + assert seen["knobs"] == {"block_m": 128, oracle.BENCHMARKING_KNOB: 1} assert len(seen["variant_packs"]) == 3 assert seen["rotated_bytes"] == 3 * 32 # 2 tensors * 4 floats * 4 bytes each -def test_profiling_orchestrator_forwards_input_recipe(monkeypatch) -> None: +def test_profiling_orchestrator_forwards_recipe_and_typed_knobs(monkeypatch) -> None: from dnn_benchmarking.cli.parser import create_parser from dnn_benchmarking.metrics.profiling_orchestrator import build_inner_argv default_argv = build_inner_argv(Path("/g.json"), 1, 0, 2, 5, None) - assert "--input-recipe" not in default_argv - + assert "--input-recipe" not in default_argv and "--knobs-json" not in default_argv + + typed_knobs = { + "block_m": 128, + "str_num": "128", + "csv_opt": "a,b", + "flag": True, + "ratio": 1.5, + } argv = build_inner_argv( Path("/g.json"), 1, @@ -890,9 +941,11 @@ def test_profiling_orchestrator_forwards_input_recipe(monkeypatch) -> None: 5, None, input_recipe="llm", + knobs=typed_knobs, ) parsed = create_parser().parse_args(argv[3:]) assert parsed.input_recipe == "llm" + assert json.loads(parsed.knobs_json) == typed_knobs def test_reporter_nonfinite_iqr_and_launch_mode_legend() -> None: @@ -969,6 +1022,205 @@ def test_compare_treats_missing_input_recipe_as_legacy_across_schemas( assert "input_recipe" in capsys.readouterr().err +def test_invalid_knob_and_bad_candidates_exit_2_through_real_runner( + tmp_path, monkeypatch +) -> None: + """Unknown user --knob exits 2 through run_single_provider_engine -> _run_suite; unreadable candidates exits 2 at startup.""" + from dnn_benchmarking.cli.parser import create_parser + from dnn_benchmarking.common.exceptions import InvalidKnobError + from dnn_benchmarking.execution import executor as exec_mod + + gpath = tmp_path / "g.json" + gpath.write_text(json.dumps(_MINIMAL_GRAPH)) + + # Unreadable --knob-candidates exits 2 at run_suite_cli startup before running graphs. + bad_cands = tmp_path / "missing.json" + args = create_parser().parse_args( + [ + "-g", + str(gpath), + "-e", + "1", + "--sweep-knobs", + "--knob-candidates", + str(bad_cands), + ] + ) + rc = suite_runner_cli.run_suite_cli(args, [gpath], Reporter(quiet=True)) + assert rc == 2 + + # Real call path: _run_suite -> run_graph -> _run_engine_selection -> run_single_provider_engine -> Executor.validate_knobs. + monkeypatch.setattr( + suite_runner_cli, "_arm_sigterm_watchdog", lambda: (lambda: None) + ) + monkeypatch.setattr( + suite_runner_cli, "collect_environment_info", lambda: {"gpu_arch": "gfx90a"} + ) + monkeypatch.setattr(suite_runner, "_engine_identity", lambda h, eid: ("ENG", "1.0")) + + class RejectingExecutor: + def __init__(self, *a, **kw): + pass + + def validate_knobs(self, handle, engine_id, knobs): + raise InvalidKnobError("Knob 'bogus' is not exposed by this engine") + + monkeypatch.setattr(suite_runner, "Executor", RejectingExecutor) + monkeypatch.setattr(exec_mod, "Executor", RejectingExecutor) + + cfg = SuiteConfig( + engine_filter=[1], + knobs={"bogus": 1}, + warmup_iters=1, + benchmark_iters=1, + ) + planner = lambda gp, gj, ti, c, rep: suite_runner.RuntimePlan( + "hipdnn", + engine_ids=[1], + rows=lambda ctx: suite_runner._run_engine_selection( + ctx, object(), suite_runner.EnginePrimer(), 1, None + ), + needs_inputs=True, + ) + rc2 = suite_runner_cli._run_suite( + [gpath], + cfg, + lambda p, gj, ti: suite_runner.run_graph( + p, gj, ti, cfg, Reporter(quiet=True), [planner] + ), + None, + Reporter(quiet=True), + ["dnn-benchmark"], + ) + assert rc2 == 2 + + +def test_per_graph_knob_constraint_skips_only_affected_graph( + tmp_path, monkeypatch +) -> None: + """Out-of-range --knob skips only the constrained graph and keeps running subsequent graphs (exit 0).""" + from dnn_benchmarking.common.exceptions import KnobConstraintError + + g1 = tmp_path / "g1.json" + g2 = tmp_path / "g2.json" + g3 = tmp_path / "g3.json" + for name, p in [("g1", g1), ("g2", g2), ("g3", g3)]: + p.write_text(json.dumps({**_MINIMAL_GRAPH, "name": name})) + + monkeypatch.setattr( + suite_runner_cli, "_arm_sigterm_watchdog", lambda: (lambda: None) + ) + monkeypatch.setattr( + suite_runner_cli, "collect_environment_info", lambda: {"gpu_arch": "gfx90a"} + ) + monkeypatch.setattr(suite_runner, "_engine_identity", lambda h, eid: ("ENG", "1.0")) + + class PerGraphLimitExecutor: + build_time_ms = 1.0 + workspace_size = 0 + plan_name = "p0" + validated_knobs = {"global.workspace_size_limit": 100000} + + def __init__(self, graph_json_str, *a, **kw): + self._name = json.loads(graph_json_str)["name"] + + def validate_knobs(self, handle, engine_id, knobs): + if self._name == "g2": + raise KnobConstraintError( + "Knob 'global.workspace_size_limit'=100000 exceeds maximum 1800" + ) + return dict(knobs) + + def prime(self, *a, **kw): + pass + + def prepare(self, *a, **kw): + pass + + def benchmark(self, *a, **kw): + return timing.Measurement([0.5], [0.1], "staged", "hip", "warm", 1, 0.5) + + def execute_once(self, *a, **kw): + pass + + class FakeBM: + def __init__(self, *a, **kw): + pass + + def __enter__(self): + return self + + def __exit__(self, *a): + pass + + def allocate_all(self): + pass + + def load_input_data(self, data): + pass + + def zero_outputs(self): + pass + + def create_variant_pack(self): + return {} + + monkeypatch.setattr(suite_runner, "Executor", PerGraphLimitExecutor) + monkeypatch.setattr(suite_runner, "BufferManager", FakeBM) + + cfg = SuiteConfig( + engine_filter=[1], + knobs={"global.workspace_size_limit": 100000}, + warmup_iters=1, + benchmark_iters=1, + ) + planner = lambda gp, gj, ti, c, rep: suite_runner.RuntimePlan( + "hipdnn", + engine_ids=[1], + rows=lambda ctx: suite_runner._run_engine_selection( + ctx, object(), suite_runner.EnginePrimer(), 1, None + ), + needs_inputs=True, + ) + out_file = tmp_path / "out.json" + rc = suite_runner_cli._run_suite( + [g1, g2, g3], + cfg, + lambda p, gj, ti: suite_runner.run_graph( + p, gj, ti, cfg, Reporter(quiet=True), [planner] + ), + out_file, + Reporter(quiet=True), + ["dnn-benchmark"], + ) + assert rc == 0 + doc = json.loads(out_file.read_text()) + assert doc["run"]["complete"] is True + statuses = [g["results"][0]["status"] for g in doc["graphs"]] + assert statuses == ["success", "skipped", "success"] + + +def test_unsupported_graph_with_knob_is_skipped_not_error(monkeypatch) -> None: + """When get_knobs_for_engine raises RuntimeError for an inapplicable engine, the row is skipped.""" + from dnn_benchmarking.common.exceptions import UnsupportedGraphError + from dnn_benchmarking.execution.executor import Executor + + ex = Executor.__new__(Executor) + ex._graph = types.SimpleNamespace( + get_knobs_for_engine=lambda eid: (_ for _ in ()).throw( + RuntimeError("Failed to get knobs for engine: Failed to finalize") + ) + ) + ex._build_through_operation_graph = lambda h: None + with pytest.raises(UnsupportedGraphError, match="not applicable"): + ex.validate_knobs(object(), 1, {"global.benchmarking": 1}) + + +def test_suite_config_rejects_combining_knob_and_sweep_knobs() -> None: + with pytest.raises(ValueError, match="--knob"): + SuiteConfig(engine_filter=[1], knobs={"a": 1}, sweep_knobs=True) + + def test_setup_env_sets_dvc_global_config_dir(tmp_path, monkeypatch) -> None: import importlib.util @@ -1223,6 +1475,60 @@ def zeros(self): assert method == "zero_fill" and nbytes == 4096 and zero_calls["n"] == 1 +def test_executor_strict_knobs_rejects_before_create_plan() -> None: + """Executor._build_plan rejects invalid knobs strictly before calling create_execution_plan_ext.""" + from dnn_benchmarking.common.exceptions import InvalidKnobError + from dnn_benchmarking.execution.executor import Executor + + called = {"create": False} + knob = types.SimpleNamespace( + knob_id="valid_knob", value_type="INT64", constraint=None + ) + ex = Executor.__new__(Executor) + ex._graph = types.SimpleNamespace( + get_knobs_for_engine=lambda eid: [knob], + create_execution_plan_ext=lambda eid, s: called.update(create=True), + ) + fake_hipdnn = types.SimpleNamespace(KnobSetting=lambda k, v: (k, v)) + with pytest.raises(InvalidKnobError, match="not exposed"): + ex._build_plan(fake_hipdnn, 1, {"bogus": 7}, strict_knobs=True) + assert called["create"] is False + + +def test_sweep_knobs_emits_baseline_and_candidate_rows(monkeypatch) -> None: + """_run_engine_selection runs unpinned baseline then each exact candidate tuple.""" + from dnn_benchmarking.execution.knob_sweep import KnobCandidate + + cfg = SuiteConfig(sweep_knobs=True, engine_filter=[1]) + cfg.parsed_knob_candidates = ( + KnobCandidate("c0", {"block_m": 64}), + KnobCandidate("c1", {"block_m": 128}), + ) + ctx = suite_runner._GraphContext( + graph_path=Path("g.json"), + graph_json=_MINIMAL_GRAPH, + graph_name="g", + tensor_infos=[], + config=cfg, + reporter=Reporter(quiet=True), + input_data={}, + ) + monkeypatch.setattr(suite_runner, "_engine_identity", lambda h, eid: ("ENG", "1.0")) + + def fake_single(ctx, handle, primer, eid, name, ver, ppath, *, knobs=None, **kw): + r = _row(name, 0.1) + r.knobs = dict(knobs) if knobs else None + return r + + monkeypatch.setattr(suite_runner, "run_single_provider_engine", fake_single) + rows = suite_runner._run_engine_selection(ctx, object(), object(), 1, None) + assert [(r.engine_name, r.knobs) for r in rows] == [ + ("ENG", None), + ("ENG[c0]", {"block_m": 64}), + ("ENG[c1]", {"block_m": 128}), + ] + + def test_rocke_passes_after_iteration_scratch_release(monkeypatch) -> None: """RockeExecutor passes after_iteration scratch cleanup into measure().""" import contextlib