Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`). |

Expand Down
2 changes: 1 addition & 1 deletion docs/methodology.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion docs/results-schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`. |
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
11 changes: 7 additions & 4 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<system temp dir>/dnn-benchmark-<user>/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`. |
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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. |
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions sample_configs/config.toml.example
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ runtime = "hipdnn" # "hipdnn" or "pytorch"
# plugin_path = "<selected-prefix>/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
Expand Down
9 changes: 8 additions & 1 deletion src/dnn_benchmarking/cli/hipdnn_tuned_child.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down Expand Up @@ -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)
Expand Down
15 changes: 10 additions & 5 deletions src/dnn_benchmarking/cli/internal_profiling.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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":
Expand Down
70 changes: 69 additions & 1 deletion src/dnn_benchmarking/cli/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
23 changes: 22 additions & 1 deletion src/dnn_benchmarking/cli/suite_runner_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
),
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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}"
Expand Down
12 changes: 12 additions & 0 deletions src/dnn_benchmarking/common/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading
Loading