Skip to content
Draft
6 changes: 4 additions & 2 deletions docs/stages.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,8 +234,10 @@ scopes and placement; kernels keep the libraries already linked, the rest get th
builds them with `codegen="first"`, one configuration, so two measurements compare and a kernel a move left unchanged
keeps its build and verdict; `finalize` keeps the sweep:

- `structured`: the whole program's time, and whether its outputs match `reference` (the bench's own reference and
grading tolerance, when the plugin has one);
- `structured`: the whole program's time, and whether its outputs match `reference` (the bench's own reference,
graded by the bench's own `grade_outputs` as the judge grades it: the kernel's `rtol`/`atol` with the accumulation
floor `eps_acc * sqrt(l) * ||expected||_inf`, strict-small checks and graded extent; `mismatch_detail` gives the
error of each output that fails);
- `offloading`: each kernel's device and every transfer between memories, with bytes;
- `kernels`: each kernel's correctness, time and share, and the hints above.

Expand Down
18 changes: 14 additions & 4 deletions plugin/tactics/routes/tactics.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,18 @@
from hpcagent_bench_plugins.tactics.wire import IDENTITY, MCP_PATH, ROUTE, TOOLS

from tactics.plugin_record import PLUGIN, SCHEMA, episode_record, journal_entry, keep_capped
from tactics.server import CALLS, CHANGING, MEASURING, POLL_S, Reply, SessionProcess, Setup, applied, move_text
from tactics.server import (
CALLS,
CHANGING,
MEASURING,
POLL_S,
Reply,
SessionProcess,
Setup,
applied,
move_text,
session_preset,
)
from tactics.session import Restored, Sweep, TuneResult
from tactics.stages.families import checked_families, family_of
from tactics.stages.moves import ROLLBACK, size_argument
Expand Down Expand Up @@ -293,9 +304,8 @@ def session_of(
journal = journal_of(episode_id, kernel)
gpu = canonical_parallel_form_target() is Target.GPU
root, families, phases = str(agent_root(episode_id)), episode.families or (), episode.phases or ()
setup = Setup(
kernel, judge.cfg.preset.text, judge.cfg.datatype, gpu, root, disabled_families=families, agent_phases=phases
)
preset = session_preset(judge.cfg.preset.text)
setup = Setup(kernel, preset, judge.cfg.datatype, gpu, root, disabled_families=families, agent_phases=phases)
session = SessionProcess(setup)
for tool, arguments in journal:
repeated = session.call(tool, arguments, gone, slot=slot, timed=False)
Expand Down
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ dependencies = [
# DaCe's einsum of three or more operands imports it, but DaCe lists it only under its testing extras.
"opt-einsum>=3.0",
# DaCe extended (import dace), released from the ThrudPrimrose/dace fork; never also install spcl's PyPI `dace`.
"dace-extended>=1.0.5",
# Below 1.0.6, which shifts loops to start at 0 and fails 11 tests on this branch (spcl/tactics#123).
"dace-extended>=1.0.5,<1.0.6",
"dace-relayout>=0.1.2",
# tactics.mcp_server: the tools as an MCP server (the low-level Server of the 2.x SDK).
"mcp>=2.3",
Expand Down
48 changes: 48 additions & 0 deletions tactics/build/grading.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
reassociation floor ``eps_acc * sqrt(l)`` at the output's accumulation length (:mod:`tactics.ir.accumulation`) and
the bench's grading knobs (``grading.fp_checks``: ``strict_small_l2``, ``strict_small_sign``, ``relative_atol``). The bench grades only program outputs,
against its own reference; a kernel has neither, so Tactics supplies the oracle and ``l`` and the bench the rule.
The whole program is graded by the bench's own ``grade_outputs`` (:func:`grade_program`), so Tactics' verdict on it is
the judge's.

The bench is imported inside the functions: importing tactics never loads it."""

Expand All @@ -13,11 +15,15 @@
import math
from collections.abc import Mapping
from dataclasses import dataclass, field
from typing import TYPE_CHECKING

import numpy as np

from tactics.build.isolation import Result

if TYPE_CHECKING:
from hpcagent_bench.spec import BenchSpec


@dataclass(frozen=True, slots=True)
class Expected:
Expand Down Expand Up @@ -95,3 +101,45 @@ def grade_kernel(expected: Expected, outputs: Mapping[str, np.ndarray]) -> Grade
if not any(np.size(want) for want in expected.outputs.values()):
return Grade(ok=False, error=math.inf, detail="no output element to compare")
return Grade(ok=not failures, error=worst, detail="; ".join(failures))


@dataclass(frozen=True, slots=True)
class ProgramRule:
"""How the bench grades a kernel's whole program (``grade_outputs``): its spec, the accumulation length ``l`` and
``eps_acc`` of the floor ``eps_acc * sqrt(l) * ||expected||_inf``, and the bench's name of each program output."""

spec: BenchSpec
#: Bench output name -> ``l`` (``harness.grading.contracted_extents``).
lengths: Mapping[str, int]
eps_acc: float
#: Program output name -> the bench's, where the generator renamed it (``frac`` -> ``__frac``).
bench_names: Mapping[str, str] = field(default_factory=dict)


def grade_program(
rule: ProgramRule,
expected: Mapping[str, np.ndarray],
actual: Mapping[str, np.ndarray],
rtol: float,
atol: float,
) -> tuple[list[str], str]:
"""The program outputs the bench's ``grade_outputs`` fails, and its detail for each (the error it measured).
The bench reports only its first failure, so each output is graded alone, on the spec restricted to it.

:param rule: The kernel's grading rule (:func:`tactics.server.bench_data` builds it).
:param expected: The reference outputs, by program name.
:param actual: The program's outputs in their logical shape, by program name.
:param rtol: The kernel's relative tolerance (``frameworks.test.kernel_tolerances``).
:param atol: Its absolute tolerance."""
from hpcagent_bench.harness.grading import grade_outputs

wrong, details = [], []
for name, want in expected.items():
bench = rule.bench_names.get(name, name)
alone = rule.spec.model_copy(update={"output_args": (bench,)})
got = {bench: actual[name]} if name in actual else {}
ok, _, detail = grade_outputs(alone, {bench: want}, got, rtol, atol, lengths=rule.lengths, eps_acc=rule.eps_acc)
if not ok:
wrong.append(name)
details.append(detail if detail.startswith(f"{bench}:") else f"{bench}: {detail}")
return wrong, "; ".join(details)
39 changes: 39 additions & 0 deletions tactics/ir/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,19 @@
from typing import TypeAlias, cast

import dace
import sympy
from dace import dtypes
from dace.frontend.operations import detect_reduction_type
from dace.libraries.standard.nodes.external_call import one_element
from dace.sdfg import nodes
from dace.sdfg.graph import SubgraphView
from dace.sdfg.state import ConditionalBlock, ControlFlowBlock, LoopRegion, SDFGState
from dace.sdfg.type_inference import infer_expr_type
from dace.symbolic_facts import Relation, RelationKind
from dace.transformation import helpers
from dace.transformation.passes.analysis import loop_analysis

from tactics.ir.loops import enclosing_loops

# TypeAlias, not ``type``: isinstance needs the runtime union
CfgNest: TypeAlias = LoopRegion | ConditionalBlock # noqa: UP040
Expand Down Expand Up @@ -139,13 +144,47 @@ def inherit_symbol_predicates(standalone: dace.SDFG, nsdfg_node: nodes.NestedSDF
outer = outer.parent_sdfg


def iterator_range(loop: LoopRegion) -> tuple[sympy.Expr, sympy.Expr] | None:
"""``(low, high)`` with ``low <= iterator <= high`` in every iteration of ``loop``, or ``None`` for a loop that is
not a counted range with a constant, nonzero step."""
start = loop_analysis.get_init_assignment(loop)
end = loop_analysis.get_loop_end(loop)
stride = loop_analysis.get_loop_stride(loop)
if start is None or end is None or stride is None:
return None
step = sympy.sympify(stride)
if not step.is_number or step == 0:
return None
low, high = sympy.sympify(start), sympy.sympify(end)
return (low, high) if step > 0 else (high, low)


def inherit_loop_ranges(standalone: dace.SDFG, nsdfg_node: nodes.NestedSDFG, state: SDFGState) -> None:
"""Assume on ``standalone`` the range of every counted loop around the nest whose iterator the nest receives under
its own name (``0 <= _loop_it_0 <= K - 1``). Cut from the loop, the iterator is a plain argument, and DaCe can no
longer prove an exponent such as ``K - _loop_it_0 - 1`` nonnegative: ``R**e`` then stays a libm ``pow``, which an
index truncates to one less than the power when the device's ``pow`` rounds down."""
names = {name for name, value in nsdfg_node.symbol_mapping.items() if str(value) == name}
declared = set(standalone.symbols.keys())
for loop in enclosing_loops(state):
bounds = iterator_range(loop)
if loop.loop_variable not in names & declared or bounds is None:
continue
iterator = dace.symbolic.symbol(loop.loop_variable)
low, high = bounds
for relation in (Relation(RelationKind.LE, low, iterator), Relation(RelationKind.LE, iterator, high)):
if {str(s) for s in relation.lhs.free_symbols | relation.rhs.free_symbols} <= declared:
standalone.add_symbol_relation(relation)


def boundary_from_nsdfg(nsdfg_node: nodes.NestedSDFG, state: SDFGState) -> Boundary:
start_reductions(nsdfg_node, state)
inputs = sorted(nsdfg_node.in_connectors.keys())
outputs = sorted(nsdfg_node.out_connectors.keys())
symbols = sorted(str(s) for s in nsdfg_node.symbol_mapping.keys())
standalone = detach(nsdfg_node.sdfg)
inherit_symbol_predicates(standalone, nsdfg_node, state)
inherit_loop_ranges(standalone, nsdfg_node, state)
return Boundary(
inputs=inputs,
outputs=outputs,
Expand Down
46 changes: 42 additions & 4 deletions tactics/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
from dace.frontend.python.parser import DaceProgram
from dace.libraries.standard.nodes.external_call import external_calls

from tactics.build.grading import ProgramRule
from tactics.build.isolation import CHILD_CPUS, SEAL_KEEP_ENV, restrict_cpus
from tactics.build.toolchain import SymbolValue
from tactics.corpus.bench import corpus_kernel, preset_sizes
Expand Down Expand Up @@ -311,7 +312,8 @@ def bench_data(setup: Setup) -> tuple[dict[str, np.ndarray], Reference | None]:
from hpcagent_bench.categories import Preset
from hpcagent_bench.frameworks.benchmark import Benchmark
from hpcagent_bench.frameworks.test import kernel_tolerances
from hpcagent_bench.harness.grading import ReferenceUnavailable
from hpcagent_bench.harness.grading import ReferenceUnavailable, contracted_extents
from hpcagent_bench.harness.scoring import grade_eps
from hpcagent_bench.numerical_oracle import compiled_reference
from hpcagent_bench.support.bindings.contract import graded_datatype

Expand Down Expand Up @@ -347,8 +349,18 @@ def bench_data(setup: Setup) -> tuple[dict[str, np.ndarray], Reference | None]:
file=sys.stderr,
flush=True,
)
rtol, atol = kernel_tolerances(kernel.spec, graded_datatype(kernel.spec, setup.datatype))
return inputs, Reference({renames.get(k, k): v for k, v in expected.items()}, rtol, atol, source)
datatype = graded_datatype(kernel.spec, setup.datatype)
rtol, atol = kernel_tolerances(kernel.spec, datatype)
# the judge's l comes from a write probe of the oracle (contracted_extents(..., written=probe_mask)); without the
# probe, l is the declared chain length or the contracted extent, which the probe only changes for partly written
# outputs
rule = ProgramRule(
kernel.spec,
contracted_extents(kernel.spec, data),
grade_eps(datatype),
{renames.get(name, name): name for name in expected},
)
return inputs, Reference({renames.get(k, k): v for k, v in expected.items()}, rtol, atol, source, rule=rule)


def reference_source(kernel_name: str) -> str:
Expand All @@ -374,8 +386,8 @@ def numpy_outputs(spec: Any, data: dict[str, Any]) -> dict[str, np.ndarray]:
module_path = f"hpcagent_bench.benchmarks.{spec.relative_path.replace('/', '.')}.{path.stem}"
try:
function = vars(importlib.import_module(module_path))[spec.func_name]
names = list(inspect.signature(function).parameters)
widened = ieee_reference_data(dict(data))
names = reference_parameters(function, widened)
# a function writes its outputs in place: give it copies, so the session's inputs stay as drawn
args = {name: copy.deepcopy(widened[name]) for name in names}
result = function(**args)
Expand All @@ -391,6 +403,18 @@ def numpy_outputs(spec: Any, data: dict[str, Any]) -> dict[str, np.ndarray]:
raise ReferenceUnavailable(f"NumPy function of {spec.short_name}: {type(err).__name__}: {err}") from err


def reference_parameters(function: Callable[..., Any], data: Mapping[str, Any]) -> list[str]:
"""The parameters of a NumPy reference to pass from ``data``: every one ``data`` holds, and every one without a
default, so a missing required input still fails, by name. A parameter with a default that ``data`` lacks keeps
its default, as the bench's own calls do (``numba_call_order``): ``cegterg_numpy``'s configuration flags
(``gamma_only=False``, ...) are not inputs."""
return [
name
for name, param in inspect.signature(function).parameters.items()
if name in data or param.default is inspect.Parameter.empty
]


def size_rung(preset: str) -> str:
"""The rung a session of the judge's ``preset`` token runs on: a fuzzed token (``XL+fuzz``, ``fuzzed``) draws its
sizes around a rung, and a session measures on that rung."""
Expand All @@ -399,6 +423,20 @@ def size_rung(preset: str) -> str:
return str(parse_preset(preset).anchor.text)


def session_preset(preset: str) -> str:
"""The token a session of the judge's resolved ``preset`` starts from: ``resolve_preset`` leaves a fuzzed token
as the bare ``fuzzed`` and moves its rung into the ``fuzz.anchor`` override, which a spawned session process does
not see, so ``fuzzed`` gets that rung back (``L+fuzz``); every other token is kept. Call it in the judge's
process, as the bench reads the rung of a fuzzed run (``hpcagent_bench.harness.service.profile_size``)."""
from hpcagent_bench import config
from hpcagent_bench.categories import Preset
from hpcagent_bench.spec import FUZZ_SUFFIX

if preset != Preset.FUZZED.text:
return preset
return f"{config.current().fuzz.anchor.text}+{FUZZ_SUFFIX}"


def start(setup: Setup, codegen: Codegen = "sweep") -> tuple[Session, dict[str, np.ndarray], Reference | None]:
"""The canonicalized session of ``setup``'s kernel, and the data its whole program runs on."""
session = started_session(setup, codegen)
Expand Down
Loading
Loading