From 183699a384571eba8384b82a59b928f9e624971a Mon Sep 17 00:00:00 2001 From: Nicolas Pereira Ribeiro Date: Fri, 27 Nov 2026 21:31:53 +0100 Subject: [PATCH 1/8] A session of a fuzzed judge runs at the fuzz anchor, not always XL The judge route and the tactics_bench tuner columns hand Setup the judge's resolved preset. resolve_preset turns every '+fuzz' token into the bare 'fuzzed' and moves the rung into the fuzz.anchor override, so size_rung saw 'fuzzed' and started every session at XL: on an L+fuzz judge the session built XL inputs while the judge graded around L (OOM on a 16 GB machine, every kernel). The spawned session process cannot read the judge's override, so session_preset gives 'fuzzed' its anchor back in the caller's process, as the bench reads the rung of a fuzzed run (service.profile_size). Co-Authored-By: Claude Opus 5.5 --- plugin/tactics/routes/tactics.py | 18 ++++++++++++++---- tactics/server.py | 14 ++++++++++++++ tactics_bench/__init__.py | 7 ++++--- tests/test_bench_data.py | 22 +++++++++++++++++++++- tests/test_bench_plugin.py | 11 +++++++---- 5 files changed, 60 insertions(+), 12 deletions(-) diff --git a/plugin/tactics/routes/tactics.py b/plugin/tactics/routes/tactics.py index 6005678..36d06d2 100644 --- a/plugin/tactics/routes/tactics.py +++ b/plugin/tactics/routes/tactics.py @@ -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 @@ -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) diff --git a/tactics/server.py b/tactics/server.py index 2b19060..7a1ba54 100644 --- a/tactics/server.py +++ b/tactics/server.py @@ -399,6 +399,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) diff --git a/tactics_bench/__init__.py b/tactics_bench/__init__.py index 74b2f02..e6b2d75 100644 --- a/tactics_bench/__init__.py +++ b/tactics_bench/__init__.py @@ -31,7 +31,7 @@ from tactics.plugin_record import SCHEMA, episode_record, keep_capped from tactics.replay import Context, Script, Solution, baseline, load_solution from tactics.records import KernelStatus, MoveStatus, spelled -from tactics.server import Setup, start +from tactics.server import Setup, session_preset, start from tactics.stages.families import ALL, checked_families from tactics.session import DEFAULTS_PREFIX, MoveResult, kernel_language @@ -83,8 +83,9 @@ class ReferenceOptimizer(FlavorOptimizer): def tune(self, task: Task, pipeline: str) -> Submission: gpu = task.image != "cpu" service = config.current().service - # the service's preset is a token ("XL+fuzz"); the judge grades on the preset it resolves to - preset = resolve_preset(service.preset).text + # the service's preset is a token ("XL+fuzz"); the judge grades on the preset it resolves to, and a fuzzed + # one keeps its rung only through session_preset + preset = session_preset(resolve_preset(service.preset).text) session, _, _ = start(Setup(task.kernel, preset, service.datatype, gpu, disabled_families=self.families)) script = Script(session) solution = reference_solution(task.kernel) if self.references else None diff --git a/tests/test_bench_data.py b/tests/test_bench_data.py index e1f1e11..bccb87a 100644 --- a/tests/test_bench_data.py +++ b/tests/test_bench_data.py @@ -11,7 +11,7 @@ from hpcagent_bench.harness.grading import ReferenceUnavailable import tactics.server as server_mod -from tactics.server import KERNELBENCH_DIR_VAR, Setup, bench_data, numpy_outputs, size_rung +from tactics.server import KERNELBENCH_DIR_VAR, Setup, bench_data, numpy_outputs, session_preset, size_rung from tactics.stages.performance import BENCH_REFERENCE, NUMPY_REFERENCE @@ -84,3 +84,23 @@ def test_the_numpy_function_leaves_the_inputs_it_was_given_as_drawn() -> None: def test_a_fuzzed_token_runs_a_session_on_its_rung() -> None: """A judge on ``XL+fuzz`` hands the token to the reference flavor and ``fuzzed`` to the agent's route.""" assert [size_rung(token) for token in ("S", "M+fuzz", "XL+fuzz", "fuzzed")] == ["S", "M", "XL", "XL"] + + +# Reproducer: an L+fuzz judge started every Tactics session at XL and OOMed on a Mac (T48-34, jacobi_1d, f58cc92) +def test_a_session_of_a_fuzzed_judge_keeps_the_anchor_rung() -> None: + """``resolve_preset("L+fuzz")`` leaves ``fuzzed`` and moves L into ``fuzz.anchor``; the session's token must + carry L, since the spawned session process does not see that override.""" + from hpcagent_bench import config, fuzz + from hpcagent_bench.categories import Preset + from hpcagent_bench.spec import resolve_preset + + try: + resolved = resolve_preset("L+fuzz") + assert resolved is Preset.FUZZED + assert session_preset(resolved.text) == "L+fuzz" + assert size_rung(session_preset(resolved.text)) == "L" + assert size_rung(session_preset(resolve_preset("XL+fuzz").text)) == "XL" + assert [session_preset(kept) for kept in ("S", "M+fuzz", "XL")] == ["S", "M+fuzz", "XL"] + finally: + config.clear_override("fuzz.anchor") + config.clear_override(fuzz.PRESET_SEED_KEY) diff --git a/tests/test_bench_plugin.py b/tests/test_bench_plugin.py index 3a5dd74..fa49986 100644 --- a/tests/test_bench_plugin.py +++ b/tests/test_bench_plugin.py @@ -55,7 +55,7 @@ from tactics import plugin_record from tactics.paths import REPO_ROOT from tactics.records import KernelStatus, MoveStatus, Refusal, Refused -from tactics.server import CALLS, CHANGING, STOP_GRACE_S, TOOL_PHASES, TOOL_TIMEOUT_S, Reply, Setup +from tactics.server import CALLS, CHANGING, STOP_GRACE_S, TOOL_PHASES, TOOL_TIMEOUT_S, Reply, Setup, size_rung from tactics.session import KernelOutcome, Move, MoveResult, Restored, Session, TunedValue, TuneResult from tactics.stages.families import FAMILIES from tactics_bench import DefaultOptimizer, NoWaveOptimizer, ReferenceOptimizer @@ -1135,10 +1135,13 @@ def recording_start(setup: Setup) -> None: monkeypatch.setattr(tactics_bench, "start", recording_start) sut = ReferenceOptimizer("dace_cpu_canon_tactics_reference") - with config.scoped_environment({"HPCAGENT_BENCH_SERVICE_PRESET": "XL+fuzz"}), pytest.raises(Started): - sut.tune(Task(KERNEL, SourceMode.ANY, Language.CPP), "canon_cpu") + for token in ("XL+fuzz", "L+fuzz"): + with config.scoped_environment({"HPCAGENT_BENCH_SERVICE_PRESET": token}), pytest.raises(Started): + sut.tune(Task(KERNEL, SourceMode.ANY, Language.CPP), "canon_cpu") - assert presets == ["fuzzed"] + # the fuzzed base keeps its rung: a bare "fuzzed" would start an L+fuzz judge's session at XL (T48-34) + assert presets == ["XL+fuzz", "L+fuzz"] + assert [size_rung(preset) for preset in presets] == ["XL", "L"] class FinalizedSession: From 8d5a24ea3e45a37c9bf500be8bacba1cdfa35219 Mon Sep 17 00:00:00 2001 From: Nicolas Pereira Ribeiro Date: Sat, 28 Nov 2026 12:47:57 +0100 Subject: [PATCH 2/8] A kernel's check skips a ScatterConflictCheck's tag scratch The scratch a ScatterConflictCheck writes is never read before it is written and may carry stale values (DaCe's contract), so no oracle can predict it. The kernel check compared it with the oracle's zeros and judged the kernel wrong while the whole program was correct: ilu0, lulesh, qe_vexx_k and sparse_cholesky on the CPU target (T48-42). checked_probe now leaves out the outputs the kernel does not define (unspecified_outputs), resolved through nested SDFGs to the boundary's names. Co-Authored-By: Claude Opus 5.5 --- tactics/stages/kernel.py | 34 ++++++++++++++++++++++++- tests/test_kernel_stage.py | 52 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 1 deletion(-) diff --git a/tactics/stages/kernel.py b/tactics/stages/kernel.py index c24be5a..5d8a18d 100644 --- a/tactics/stages/kernel.py +++ b/tactics/stages/kernel.py @@ -19,6 +19,7 @@ from dace import dtypes from dace.codegen import cpf from dace.codegen.common import get_gpu_backend +from dace.libraries.sort.nodes.scatter_conflict_check import SCRATCH_CONNECTOR_NAME, ScatterConflictCheck from dace.libraries.standard.nodes.external_call import ExternalCall from dace.sdfg import nodes from dace.sdfg.state import LoopRegion @@ -458,8 +459,39 @@ def expected(self) -> Expected: return Expected(self.oracle, self.lengths) +def outermost_name(sdfg: dace.SDFG, name: str) -> str: + """The container of the top SDFG that ``name`` of nested ``sdfg`` is written into, through each parent's output + connector of that name.""" + while sdfg.parent_nsdfg_node is not None and sdfg.parent is not None: + state, node = sdfg.parent, sdfg.parent_nsdfg_node + edge = next((e for e in state.out_edges(node) if e.src_conn == name), None) + if edge is None: + return name + name = state.memlet_path(edge)[-1].dst.data + sdfg = state.sdfg + return name + + +def unspecified_outputs(boundary: Boundary) -> list[str]: + """The outputs of ``boundary`` whose values the kernel does not define: the tag scratch a ``ScatterConflictCheck`` + writes (DaCe: never read before it is written, and it may carry stale values), which no oracle can predict.""" + names: list[str] = [] + for node, state in boundary.standalone_sdfg.all_nodes_recursive(): + if not isinstance(node, ScatterConflictCheck): + continue + for edge in state.out_edges(node): + if edge.src_conn == SCRATCH_CONNECTOR_NAME: + name = outermost_name(state.sdfg, state.memlet_path(edge)[-1].dst.data) + if name in boundary.outputs and name not in names: + names.append(name) + return names + + def checked_probe(boundary: Boundary, timed: Workload, checked: Workload, oracle: dict[str, np.ndarray]) -> Probe: - """A probe compared on ``checked``, with the accumulation length of each output at its sizes.""" + """A probe compared on ``checked``, with the accumulation length of each output at its sizes. An output whose + values the kernel leaves undefined (:func:`unspecified_outputs`) is not compared.""" + unspecified = unspecified_outputs(boundary) + oracle = {name: array for name, array in oracle.items() if name not in unspecified} arrays = {**checked.inputs, **oracle} lengths = accumulation_lengths(boundary.standalone_sdfg, checked.sizes, arrays, boundary.outputs) return Probe(timed, checked, oracle, lengths=lengths) diff --git a/tests/test_kernel_stage.py b/tests/test_kernel_stage.py index 42911ae..b5ebfd8 100644 --- a/tests/test_kernel_stage.py +++ b/tests/test_kernel_stage.py @@ -16,6 +16,12 @@ import pytest from dace.codegen.common import get_gpu_backend from dace.frontend.python.parser import DaceProgram +from dace.libraries.sort.nodes.scatter_conflict_check import ( + INPUT_CONNECTOR_NAME, + OUTPUT_CONNECTOR_NAME, + SCRATCH_CONNECTOR_NAME, + ScatterConflictCheck, +) from dace.libraries.standard.nodes.external_call import ExternalCall from helpers import extern_declaration_and_call @@ -32,12 +38,15 @@ GPU_FORMS, KernelSource, KernelVerdict, + Workload, build_kernel_library, + checked_probe, gpu_schedule, kernel_runtime_libraries, kernel_text, schedule_kernel, split_kernel_text, + unspecified_outputs, use_kernel_library, validate_kernel, ) @@ -578,3 +587,46 @@ def test_the_cuda_archive_compiles_every_unit_into_one_library(tmp_path: Path, m assert [cmd[cmd.index("-c") + 1] for cmd in commands] == [str(u) for u in units] assert linked == [[tmp_path / "out" / "k.o", tmp_path / "out" / "k_device.o"]] + + +def scatter_check_sdfg(nested: bool) -> dace.SDFG: + """A ``ScatterConflictCheck`` writing its flag into ``flag`` and its tag scratch into ``owner``, at the top level + or inside a nested SDFG whose connectors carry other names.""" + inner_names = ("i", "f", "o") if nested else ("idx", "flag", "owner") + body = dace.SDFG("check_body" if nested else "check") + for name, shape in zip(inner_names, ([dace.symbol("N")], [1], [dace.symbol("M")]), strict=True): + body.add_array(name, shape, dace.int64) + state = body.add_state("check") + node = ScatterConflictCheck("check") + node.add_out_connector(SCRATCH_CONNECTOR_NAME) + state.add_node(node) + idx, flag, owner = inner_names + state.add_edge(state.add_read(idx), None, node, INPUT_CONNECTOR_NAME, dace.Memlet(f"{idx}[0:N]")) + state.add_edge(node, OUTPUT_CONNECTOR_NAME, state.add_write(flag), None, dace.Memlet(f"{flag}[0]")) + state.add_edge(node, SCRATCH_CONNECTOR_NAME, state.add_write(owner), None, dace.Memlet(f"{owner}[0:M]")) + if not nested: + return body + sdfg = dace.SDFG("check") + for name, shape in (("idx", [dace.symbol("N")]), ("flag", [1]), ("owner", [dace.symbol("M")])): + sdfg.add_array(name, shape, dace.int64) + outer = sdfg.add_state("outer") + call = outer.add_nested_sdfg(body, inputs={"i"}, outputs={"f", "o"}) + outer.add_edge(outer.add_read("idx"), None, call, "i", dace.Memlet("idx[0:N]")) + outer.add_edge(call, "f", outer.add_write("flag"), None, dace.Memlet("flag[0]")) + outer.add_edge(call, "o", outer.add_write("owner"), None, dace.Memlet("owner[0:M]")) + return sdfg + + +# Reproducer: a ScatterConflictCheck's tag scratch graded against zeros failed a correct kernel (T48-42, ilu0 CPU) +@pytest.mark.parametrize("nested", [False, True]) +def test_a_scatter_checks_tag_scratch_is_not_graded(nested: bool) -> None: + sdfg = scatter_check_sdfg(nested) + boundary = Boundary( + inputs=["idx"], outputs=["flag", "owner"], symbols=["N", "M"], nsdfg_node=None, state=None, standalone_sdfg=sdfg + ) + assert unspecified_outputs(boundary) == ["owner"] + sizes = {"N": 4, "M": 4} + workload = Workload({"idx": np.arange(4, dtype=np.int64)}, sizes) + oracle = {"flag": np.zeros(1, dtype=np.int64), "owner": np.zeros(4, dtype=np.int64)} + probe = checked_probe(boundary, workload, workload, oracle) + assert list(probe.expected.outputs) == ["flag"] From a98fa29c08df4771e84fc3c564080b8cba5dacf3 Mon Sep 17 00:00:00 2001 From: Nicolas Pereira Ribeiro Date: Sun, 29 Nov 2026 17:10:37 +0100 Subject: [PATCH 3/8] A kernel cut from a loop keeps the range of the loop's iterator A kernel left inside a sequential loop takes the loop's iterator as a plain argument. Cut from the loop, DaCe can no longer prove an exponent such as K - _loop_it_0 - 1 nonnegative, so RelaxIntegerPowers keeps R**e as a libm pow, and every index and loop bound truncates it to an integer. When the device's pow(2, 11) rounds down, that drops elements: stockham_fft on the GPU left Tmp4[2048] and Tmp4[4095] unwritten at K = 12, and the whole program was wrong from K = 12 on (T48-49, Daint jobs 5480009 and 5484421). inherit_loop_ranges adds low <= it and it <= high for every counted loop around the kernel whose iterator it receives under its own name, to the extracted nest and to the ExternalCall's standalone SDFG, beside inherit_symbol_predicates. DaCe then emits ipow: stockham's doall27 and lib_linalg0 render with no pow in any index or bound. Co-Authored-By: Claude Opus 5.5 --- tactics/ir/extract.py | 39 ++++++++++++++++++++++++ tactics/stages/scopes.py | 3 ++ tests/test_loop_iterator_symbols.py | 47 +++++++++++++++++++++++++++++ 3 files changed, 89 insertions(+) diff --git a/tactics/ir/extract.py b/tactics/ir/extract.py index cb6b003..5821fef 100644 --- a/tactics/ir/extract.py +++ b/tactics/ir/extract.py @@ -11,6 +11,7 @@ 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 @@ -18,7 +19,11 @@ 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 @@ -139,6 +144,39 @@ 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()) @@ -146,6 +184,7 @@ def boundary_from_nsdfg(nsdfg_node: nodes.NestedSDFG, state: SDFGState) -> Bound 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, diff --git a/tactics/stages/scopes.py b/tactics/stages/scopes.py index efa9991..282090a 100644 --- a/tactics/stages/scopes.py +++ b/tactics/stages/scopes.py @@ -42,6 +42,7 @@ extract_blocks, extract_map_nest, extract_state_nodes, + inherit_loop_ranges, inherit_symbol_predicates, ) from tactics.ir.introspect import Row @@ -133,7 +134,9 @@ def replace_nsdfg_with_external(boundary: Boundary, name: str) -> ExternalCall: numpy_source=oracle.numpy_source, ) # DaCe's reference_sdfg cuts the parent, and with it the signs the program declares for the kernel's symbols + # and the ranges of the loops around it inherit_symbol_predicates(ext.standalone_sdfg, nsdfg, state) + inherit_loop_ranges(ext.standalone_sdfg, nsdfg, state) # The oracle's scratch is the oracle harness's to allocate; the kernel allocates its own. own = {*boundary.inputs, *boundary.outputs, *boundary.symbols} ext.abi_order = [arg for arg in oracle.args if arg in own] diff --git a/tests/test_loop_iterator_symbols.py b/tests/test_loop_iterator_symbols.py index c961771..c16d5b4 100644 --- a/tests/test_loop_iterator_symbols.py +++ b/tests/test_loop_iterator_symbols.py @@ -11,7 +11,9 @@ import dace import numpy as np import pytest +import sympy from dace.sdfg.state import LoopRegion +from dace.symbolic_facts import Relation, RelationKind from dace.transformation.passes.analysis import loop_analysis from tactics.build.sdfg import compile_linked_program, generate_program @@ -153,3 +155,48 @@ def test_a_loop_inside_a_loop_without_a_value_gets_none_while_one_outside_keeps_ inside = depends.add_state("inside", is_start_block=True) assert loop_symbol_values(inside, SIZES) == {"i": 3}, "range(0, 8) has 8 iterations and the middle one is i=3" + + +R = dace.symbol("R", dtype=dace.int64) +K = dace.symbol("K", dtype=dace.int64) +POWER_SIZES = {"R": 2, "K": 4} + + +@dace.program +def power_strided_stages(A: dace.float64[K, R**K], B: dace.float64[R**K]) -> None: + for k in range(1, K): + for j in dace.map[0 : R ** (K - k - 1)]: + A[k, j] = A[k - 1, j] + B[j] + + +def power_session(tmp_path: Path) -> Session: + sdfg = power_strided_stages.to_sdfg(simplify=True) + sdfg.name = f"{sdfg.name}_{os.getpid()}" + session = Session(sdfg, Targets(gpu=False), work_dir=str(tmp_path), sizes=POWER_SIZES) + session.canonicalize() + session.default_scopes() + return session + + +# Reproducer: a kernel cut from its loop lost the iterator range; R**(K-k-1) stayed a truncated pow (stockham, T48-49) +def test_a_kernel_inside_a_loop_assumes_the_range_of_the_loops_iterator(tmp_path: Path) -> None: + session = power_session(tmp_path) + iterator = iterator_of(session) + (kernel,) = session.list_kernels() + + relations = {str(r) for r in session.kernel(kernel.name).standalone_sdfg.facts().relations} + + it = dace.symbolic.symbol(iterator) + assert str(Relation(RelationKind.LE, sympy.Integer(1), it)) in relations, "range(1, K) starts at 1" + assert str(Relation(RelationKind.LE, it, K - 1)) in relations + + +# Reproducer: a kernel cut from its loop lost the iterator range; R**(K-k-1) stayed a truncated pow (stockham, T48-49) +def test_a_power_of_a_loop_iterator_renders_as_an_exact_integer_power(tmp_path: Path) -> None: + session = power_session(tmp_path) + (kernel,) = session.list_kernels() + + unit = session.default_kernel(kernel.name).unit.read_text() + + assert "ipow(" in unit + assert "std::pow(" not in unit, "an integer power of the iterator must not go through a floating pow" From 55a5d044e10ebb1b5d1358ffa918ff4f05eee5fa Mon Sep 17 00:00:00 2001 From: Nicolas Pereira Ribeiro Date: Sun, 29 Nov 2026 17:47:25 +0100 Subject: [PATCH 4/8] The loop-range test reads the range from the loop, not a literal dace-extended 1.0.6 shifts range(1, K) to start at 0, so the iterator's range is 0 <= it <= K - 2 there and 1 <= it <= K - 1 on 1.0.5. The test now compares the kernel's assumed relations with the enclosing loop's own bounds, so it holds on both. The pow-to-ipow test is unchanged and still fails without the fix on both versions (1.0.6 renders int64_t(std::pow(R, K - _loop_it_0 - 2))). Co-Authored-By: Claude Opus 5.5 --- tests/test_loop_iterator_symbols.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/tests/test_loop_iterator_symbols.py b/tests/test_loop_iterator_symbols.py index c16d5b4..02fe70b 100644 --- a/tests/test_loop_iterator_symbols.py +++ b/tests/test_loop_iterator_symbols.py @@ -17,7 +17,7 @@ from dace.transformation.passes.analysis import loop_analysis from tactics.build.sdfg import compile_linked_program, generate_program -from tactics.ir.extract import find_state_of_node +from tactics.ir.extract import find_state_of_node, iterator_range from tactics.ir.loops import enclosing_loops, loop_symbol_values from tactics.session import Session from tactics.stages.canonicalize import Targets @@ -183,12 +183,19 @@ def test_a_kernel_inside_a_loop_assumes_the_range_of_the_loops_iterator(tmp_path session = power_session(tmp_path) iterator = iterator_of(session) (kernel,) = session.list_kernels() + ext = session.kernel(kernel.name) + # the loop's own bounds: DaCe may shift range(1, K) to start at 0 (dace-extended 1.0.6 does) + (loop,) = enclosing_loops(find_state_of_node(session.sdfg, ext)) + bounds = iterator_range(loop) + assert bounds is not None - relations = {str(r) for r in session.kernel(kernel.name).standalone_sdfg.facts().relations} + relations = {str(r) for r in ext.standalone_sdfg.facts().relations} + low, high = bounds it = dace.symbolic.symbol(iterator) - assert str(Relation(RelationKind.LE, sympy.Integer(1), it)) in relations, "range(1, K) starts at 1" - assert str(Relation(RelationKind.LE, it, K - 1)) in relations + assert str(Relation(RelationKind.LE, low, it)) in relations + assert str(Relation(RelationKind.LE, it, high)) in relations + assert {str(s) for s in sympy.sympify(high).free_symbols} == {"K"}, "the upper bound is the program's K" # Reproducer: a kernel cut from its loop lost the iterator range; R**(K-k-1) stayed a truncated pow (stockham, T48-49) From 7a40c72574ff73b5966f78f50631f08bc417af25 Mon Sep 17 00:00:00 2001 From: Nicolas Pereira Ribeiro Date: Sun, 29 Nov 2026 17:52:01 +0100 Subject: [PATCH 5/8] Pin dace-extended below 1.0.6 dace-extended 1.0.6 (released 2026-11-29) shifts a loop such as range(1, T) to start at 0. With it, 7 unit tests and 1 integration test fail on this branch's parent 8d5a24e as well (split_doall, tree_view, comm_subsets, durbin costing, the middle loop value, quickstart's jacobi loops), and all of them pass on 1.0.5. There is no lock file, so CI took 1.0.6. The pin keeps this PR on the version its runs use (1.0.5 with spcl/dace#2811 applied) until Tactics is adapted to 1.0.6. Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index e27ca48..5655d1f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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", From f5da9d53e2661b849137ca7a2dffde97481c89b1 Mon Sep 17 00:00:00 2001 From: Nicolas Pereira Ribeiro Date: Mon, 30 Nov 2026 13:20:41 +0100 Subject: [PATCH 6/8] A NumPy reference keeps the defaults of parameters the data does not hold numpy_outputs passed every parameter of the bench's NumPy function from the data. cegterg_numpy takes its configuration flags as keywords with defaults (gamma_only=False, noncolin=False, ...), which the bench data does not hold, so the call raised KeyError: 'gamma_only' and qe_cegterg went ungraded wherever the bench's numba and C references cannot run. reference_parameters passes what the data holds and every parameter without a default, so a missing required input still fails by name; a defaulted one keeps its default, as the bench's own numba_call_order does. Tests: tests/test_bench_data.py gains a tagged reproducer on qe_cegterg's S data (ReferenceUnavailable: KeyError 'gamma_only' before) and a unit test of the required/defaulted rule. qe_cegterg (CPU, S) is now correct against its NumPy function. Co-Authored-By: Claude Opus 5.5 --- tactics/server.py | 14 +++++++++++++- tests/test_bench_data.py | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/tactics/server.py b/tactics/server.py index 7a1ba54..20803b8 100644 --- a/tactics/server.py +++ b/tactics/server.py @@ -374,8 +374,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) @@ -391,6 +391,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.""" diff --git a/tests/test_bench_data.py b/tests/test_bench_data.py index bccb87a..b484fbb 100644 --- a/tests/test_bench_data.py +++ b/tests/test_bench_data.py @@ -11,7 +11,15 @@ from hpcagent_bench.harness.grading import ReferenceUnavailable import tactics.server as server_mod -from tactics.server import KERNELBENCH_DIR_VAR, Setup, bench_data, numpy_outputs, session_preset, size_rung +from tactics.server import ( + KERNELBENCH_DIR_VAR, + Setup, + bench_data, + numpy_outputs, + reference_parameters, + session_preset, + size_rung, +) from tactics.stages.performance import BENCH_REFERENCE, NUMPY_REFERENCE @@ -81,6 +89,30 @@ def test_the_numpy_function_leaves_the_inputs_it_was_given_as_drawn() -> None: assert np.array_equal(first["out"], second["out"]) +# Reproducer: qe_cegterg's NumPy reference raised KeyError: 'gamma_only', so it went ungraded (T49-05) +def test_a_numpy_reference_keeps_the_defaults_of_parameters_the_data_does_not_hold() -> None: + """``cegterg_numpy`` takes its configuration flags as keywords with defaults (``gamma_only=False``); the bench + data does not hold them, and the call takes their defaults instead of failing on the first one.""" + from hpcagent_bench.categories import Preset + from hpcagent_bench.frameworks.benchmark import Benchmark + + kernel = corpus_kernel("qe_cegterg") + data = dict(Benchmark(kernel.short_name).get_data(preset=Preset.parse("S"))) + assert "gamma_only" not in data + + outputs = numpy_outputs(kernel.spec, data) + + assert set(outputs) == set(kernel.spec.output_args) + assert all(np.isfinite(value).all() for value in outputs.values()) + + +def test_a_required_parameter_the_data_lacks_still_fails_by_name() -> None: + def reference(a: np.ndarray, n: int, *, flag: bool = False) -> None: ... + + assert reference_parameters(reference, {"a": np.zeros(2)}) == ["a", "n"] + assert reference_parameters(reference, {"a": np.zeros(2), "n": 2, "flag": True}) == ["a", "n", "flag"] + + def test_a_fuzzed_token_runs_a_session_on_its_rung() -> None: """A judge on ``XL+fuzz`` hands the token to the reference flavor and ``fuzzed`` to the agent's route.""" assert [size_rung(token) for token in ("S", "M+fuzz", "XL+fuzz", "fuzzed")] == ["S", "M", "XL", "XL"] From e303f87e056936f32bd4775cb52ff37d6e293b4f Mon Sep 17 00:00:00 2001 From: Nicolas Pereira Ribeiro Date: Mon, 30 Nov 2026 14:22:01 +0100 Subject: [PATCH 7/8] Build a session's kernels at once: default_builds Stage 5 built a session's kernels one after another: render the CPF unit, run the compiler, link. A program with many kernels (qe_cegterg: 29, about 420 s of builds on the GPU target at S on Daint) spent most of a checking unit waiting on one compiler at a time. Session.default_builds renders the kernels and looks them up in first_builds one after another (Python), runs the compilers of the kernels not built before in a thread pool of build_workers() (the compiler runs outside the interpreter, as in a sweep), then links each in the given order and keeps it as a first build. The result is the serial one's: the same units, variants and archives, bound in the same order; a failed build raises once the kernels before it are linked; a stop cancels the compilers not started. Only codegen "first" without a pass pipeline takes this path; other codegens build one after another as before. kernel_evidence (so performance) and finalize use it. first_build's key and keep step become first_build_key and remember_first_build, shared by both paths. Tests: tests/test_parallel_builds.py (same units and variants as the serial builds, the compilers overlap, a failed build in the middle, a second pass reuses what the serial pass reuses). qe_cegterg CPU at S in a Linux container with 8 cores: stage 5 21.6 s serial, 13.9 s parallel; the units match except a dependence comment whose solver example differs between two serial builds too. Co-Authored-By: Claude Opus 5.5 --- tactics/session.py | 80 ++++++++++++++++----- tests/test_parallel_builds.py | 128 ++++++++++++++++++++++++++++++++++ 2 files changed, 191 insertions(+), 17 deletions(-) create mode 100644 tests/test_parallel_builds.py diff --git a/tactics/session.py b/tactics/session.py index 9d09794..ffa0645 100644 --- a/tactics/session.py +++ b/tactics/session.py @@ -10,6 +10,7 @@ from __future__ import annotations import atexit +import concurrent.futures import contextlib import copy import dataclasses @@ -232,7 +233,7 @@ lower_group_to_external_call, node_boundary, ) -from tactics.stages.variants import Variant, VariantCell, device_variants, select_variant +from tactics.stages.variants import Variant, VariantCell, build_workers, device_variants, select_variant from tactics.stages.vectorize import VECTORIZE_DOALL #: Characters of a failed build's error text a caller gets back. @@ -3108,22 +3109,70 @@ def default_build(self, name: str) -> None: def first_build(self, name: str) -> None: """Stage 5's default build, or the one made before for the same kernel body and sizes: a move changes few kernels, and rendering is most of a kernel's cost, so the key needs no rendering.""" - ext = self.kernel(name) - body = (kernel_device(ext), ext.standalone_sdfg.hash_sdfg(), *strings(ext.abi_order)) - key: FirstBuildKey = ( - name, - body, - tuple(sorted(self.kernel_sizes(name).items())), - self.mode_of(name), - self.pipeline, - ) + key = self.first_build_key(name) known = self.first_builds.get(key) if known is None: self.optimize_kernel(name) - known = kept(self.builds[name], self.swept_dir / f"{name}_first_{len(self.first_builds)}") - self.first_builds[key] = known + known = self.remember_first_build(name, key) self.bind(name, known) + def first_build_key(self, name: str) -> FirstBuildKey: + ext = self.kernel(name) + body = (kernel_device(ext), ext.standalone_sdfg.hash_sdfg(), *strings(ext.abi_order)) + return name, body, tuple(sorted(self.kernel_sizes(name).items())), self.mode_of(name), self.pipeline + + def remember_first_build(self, name: str, key: FirstBuildKey) -> KernelBuild: + """The kernel's bound build, copied out of its work folder and kept as the first build of ``key``.""" + known = kept(self.builds[name], self.swept_dir / f"{name}_first_{len(self.first_builds)}") + self.first_builds[key] = known + return known + + def default_builds(self, names: Iterable[str]) -> None: + """:meth:`default_build` of every kernel in ``names`` without a build, the compilers running at once. + + Under ``codegen="first"`` without a pass pipeline, each kernel is looked up in :attr:`first_builds` and + rendered one after another (Python), then every kernel not built before is compiled in a thread pool of + :func:`build_workers` (the compiler runs outside the interpreter), then each is linked in the order of + ``names``. The result is the serial one's: the same units, variants and archives, bound in the same order; a + failed build raises once the kernels before it are linked. Any other codegen builds one after another.""" + todo = [name for name in dict.fromkeys(names) if name not in self.builds] + if self.codegen != "first" or self.pipeline is not None: + for name in todo: + self.default_build(name) + return + keys = {name: self.first_build_key(name) for name in todo} + known = {name: self.first_builds[key] for name, key in keys.items() if key in self.first_builds} + jobs = { + name: (src, self.first_variant(src.device, name), self.work_dir / name / "library") + for name in todo + if name not in known + for src in [self.default_kernel(name)] + } + archives = self.compile_at_once(jobs) + for name in todo: + if name not in known: + src, variant, _ = jobs[name] + self.bind(name, KernelBuild(src, variant, archives[name].result())) + known[name] = self.remember_first_build(name, keys[name]) + self.bind(name, known[name]) + + def compile_at_once( + self, jobs: Mapping[str, tuple[KernelSource, Variant, Path]] + ) -> dict[str, concurrent.futures.Future[Path]]: + """Every job's :func:`build_kernel_library`, at most :func:`build_workers` at once, all finished on return. A + stop leaves the running compilers to finish in the background and starts no other, as a sweep does.""" + pool = concurrent.futures.ThreadPoolExecutor(max(1, min(build_workers(), len(jobs)))) + try: + with self.stopper.armed(): + futures = { + name: pool.submit(build_kernel_library, src, variant.compiler, list(variant.flags), folder) + for name, (src, variant, folder) in jobs.items() + } + concurrent.futures.wait(futures.values()) + finally: + pool.shutdown(wait=False, cancel_futures=True) + return futures + # Stage 7: feedback def last_change(self) -> str: @@ -3152,9 +3201,8 @@ def feedback(self, reps: int = TIMED_REPS) -> str: def kernel_evidence(self, reps: int = TIMED_REPS) -> list[Evidence]: """Every kernel's validation, time and compiler remarks, building the default library where none is bound.""" evidence: list[Evidence] = [] + self.default_builds(ext.name for ext in external_calls(self.sdfg)) for ext in external_calls(self.sdfg): - if ext.name not in self.builds: - self.default_build(ext.name) build = self.builds[ext.name] if build.verdict is None: with self.stopper.armed(): @@ -3191,9 +3239,7 @@ def finalize(self, out_dir: Path | None = None) -> Final: trial.default_scopes() if trial.targets.gpu: trial.default_placement() # a GPU program is assembled as placed, its copies inserted - for ext in external_calls(trial.sdfg): - if ext.name not in trial.builds: - trial.default_build(ext.name) + trial.default_builds(ext.name for ext in external_calls(trial.sdfg)) variants = {name: build.variant.label for name, build in trial.builds.items()} final_dir = out_dir or self.work_dir / "final" return assemble(trial.sdfg, self.bench, variants, final_dir, requests_of(self.layout)) diff --git a/tests/test_parallel_builds.py b/tests/test_parallel_builds.py new file mode 100644 index 0000000..1988d63 --- /dev/null +++ b/tests/test_parallel_builds.py @@ -0,0 +1,128 @@ +# Copyright 2021 ETH Zurich and the Tactics authors. +# SPDX-License-Identifier: GPL-3.0-or-later +"""Session.default_builds: a session's kernels compiled at once, bound as the serial builds bind them (T49-06).""" + +import threading +import time +from pathlib import Path +from typing import Any + +import dace +import numpy as np +import pytest + +from tactics import session as session_module +from tactics.session import Session +from tactics.stages.kernel import build_kernel_library + +N = dace.symbol("N", dtype=dace.int64) + +pytestmark = pytest.mark.e2e + + +@dace.program +def three_steps(a: dace.float64[N], b: dace.float64[N], c: dace.float64[N], d: dace.float64[N]) -> None: + for i in dace.map[0:N]: + c[i] = 2.0 * a[i] + for i in dace.map[0:N]: + d[i] = c[i] + b[i] + for i in dace.map[0:N]: + c[i] = d[i] * d[i] + + +def scoped(tmp_path: Path, name: str) -> tuple[Session, list[str]]: + session = Session(three_steps.to_sdfg(simplify=True), work_dir=str(tmp_path / name), sizes={"N": 64}) + names = [kernel.name for kernel in session.default_scopes()] + assert len(names) >= 2, "the test needs several kernels" + return session, names + + +def assert_computes(session: Session) -> None: + rng = np.random.default_rng(0) + a, b = rng.random(64), rng.random(64) + c, d = np.zeros(64), np.zeros(64) + session.sdfg(a=a, b=b, c=c, d=d, N=64) + np.testing.assert_allclose(c, (2.0 * a + b) ** 2, rtol=1e-14, atol=0) + + +def test_parallel_builds_bind_what_the_serial_builds_bind(tmp_path: Path) -> None: + serial, names = scoped(tmp_path, "serial") + for name in names: + serial.default_build(name) + parallel, same = scoped(tmp_path, "parallel") + assert same == names + + parallel.default_builds(names) + + for name in names: + one, other = serial.builds[name], parallel.builds[name] + assert one.variant == other.variant + assert one.source.unit.read_text() == other.source.unit.read_text() + assert parallel.kernel(name).lib_path == str(other.archive) + assert len(parallel.first_builds) == len(names) + assert_computes(parallel) + + +def test_the_compilers_run_at_once(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + session, names = scoped(tmp_path, "at_once") + running, most = 0, 0 + lock = threading.Lock() + build = build_kernel_library + + def slow_build(*args: Any) -> Path: + nonlocal running, most + with lock: + running += 1 + most = max(most, running) + time.sleep(0.5) + try: + return build(*args) + finally: + with lock: + running -= 1 + + monkeypatch.setattr(session_module, "build_kernel_library", slow_build) + monkeypatch.setattr(session_module, "build_workers", lambda: 8) + + session.default_builds(names) + + assert most == len(names), f"{most} of {len(names)} compilers ran at once" + assert_computes(session) + + +def test_a_failed_build_raises_once_the_kernels_before_it_are_linked( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + session, names = scoped(tmp_path, "failed") + broken = names[1] + build = build_kernel_library + + def failing(src: Any, *args: Any) -> Path: + if src.name == broken: + raise RuntimeError(f"compiler failed on {broken}") + return build(src, *args) + + monkeypatch.setattr(session_module, "build_kernel_library", failing) + + with pytest.raises(RuntimeError, match=broken): + session.default_builds(names) + + assert names[0] in session.builds, "the kernel before the failed one is linked, as the serial builds leave it" + assert broken not in session.builds and names[2:] and names[2] not in session.builds + + +def test_a_second_pass_reuses_the_first_builds_the_serial_pass_reuses(tmp_path: Path) -> None: + """Linking a kernel can change its first-build key (its ``abi_order``), so a second pass may compile some kernels + again; the parallel pass reuses exactly what the serial pass reuses.""" + serial, names = scoped(tmp_path, "serial_again") + parallel, _ = scoped(tmp_path, "parallel_again") + for _ in range(2): + for name in names: + serial.default_build(name) + parallel.default_builds(names) + serial.builds.clear() + parallel.builds.clear() + + assert len(parallel.first_builds) == len(serial.first_builds) + parallel.default_builds(names) + assert_computes(parallel) From a11f4964d19ed91092844784602480abb73b88ae Mon Sep 17 00:00:00 2001 From: Nicolas Pereira Ribeiro Date: Tue, 1 Dec 2026 17:59:43 +0100 Subject: [PATCH 8/8] Grade the whole program by the bench's own rule Tactics checked the whole program with a plain per-element allclose(rtol, atol), while HPCAgent-Bench's judge (grade_outputs) also raises atol to the accumulation floor eps_acc * sqrt(l) * ||expected||_inf and applies its strict-small checks, graded extent and mismatch fraction. lulesh's default was graded WRONG by Tactics and right by the bench: dxx/dyy/dzz failed allclose on 3-4 of 10^6 cancelled elements, error <= 5.2e-10 on values up to 1.3e5 (L and XL, with one thread and without FMA alike). Reference gains an optional ProgramRule (spec, accumulation lengths, eps_acc, bench names), built in bench_data from the bench's contracted_extents and grade_eps. With it, grade_program calls the bench's grade_outputs once per output on the spec restricted to that output, so every failing output is named, and ProgramReport.mismatch_detail carries the bench's error. A Reference without a rule keeps allclose. The move check at the check rung uses the same reference. Co-Authored-By: Claude Opus 5.5 --- docs/stages.md | 6 +- tactics/build/grading.py | 48 +++++++++++++ tactics/server.py | 18 ++++- tactics/stages/performance.py | 30 ++++++-- tests/test_bench_data.py | 10 +++ tests/test_program_grade.py | 126 ++++++++++++++++++++++++++++++++++ 6 files changed, 226 insertions(+), 12 deletions(-) create mode 100644 tests/test_program_grade.py diff --git a/docs/stages.md b/docs/stages.md index 8c88b67..68cd276 100644 --- a/docs/stages.md +++ b/docs/stages.md @@ -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. diff --git a/tactics/build/grading.py b/tactics/build/grading.py index 720950d..22c813c 100644 --- a/tactics/build/grading.py +++ b/tactics/build/grading.py @@ -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.""" @@ -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: @@ -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) diff --git a/tactics/server.py b/tactics/server.py index 20803b8..9eb679a 100644 --- a/tactics/server.py +++ b/tactics/server.py @@ -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 @@ -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 @@ -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: diff --git a/tactics/stages/performance.py b/tactics/stages/performance.py index 430484f..8aa5f95 100644 --- a/tactics/stages/performance.py +++ b/tactics/stages/performance.py @@ -18,6 +18,7 @@ from relayout.layout import IndexMap from tactics.build.arena import US_PER_S, reps_within_budget, rewind +from tactics.build.grading import ProgramRule, grade_program from tactics.build.isolation import Failure, Result, run_isolated, run_spawned from tactics.build.sdfg import BuiltSDFG, build_linked_program from tactics.build.toolchain import SymbolValue, parse_params, signature @@ -31,7 +32,8 @@ class ProgramReport(Record): """The whole program at the session's sizes: its time, and whether its outputs match the reference (``None`` without one; ``mismatched`` names the outputs that differ). ``error`` set when it did not build or run. ``unchecked`` says why ``correct`` is ``None``: a time with it set is of a program nothing was compared against. - ``reference`` is where the reference outputs came from (empty when there was none).""" + ``reference`` is where the reference outputs came from (empty when there was none). ``mismatch_detail`` is the + bench's account of each mismatched output (the error it measured), when the reference carries the bench's rule.""" time_us: float | None = None correct: bool | None = None @@ -39,6 +41,7 @@ class ProgramReport(Record): error: str = "" unchecked: str = "" reference: str = "" + mismatch_detail: str = "" #: ``Reference.source``: the bench's own reference (the torch model on a machine-learning kernel, else its oracles), or @@ -91,11 +94,13 @@ class Performance(Record): class ProgramTime(Result): time_us: float mismatched: list[str] | None + mismatch_detail: str = "" @dataclass(frozen=True, slots=True) class Reference: - """The outputs the whole program must reproduce, and the tolerance it is graded at.""" + """The outputs the whole program must reproduce, and the tolerance it is graded at. With ``rule`` (a bench + kernel), the bench's own ``grade_outputs`` grades them, as the judge does; without one, plain ``allclose``.""" outputs: dict[str, np.ndarray] rtol: float @@ -106,20 +111,30 @@ class Reference: #: their logical shape at ``sizes`` before the comparison, as the harness reads them. layouts: Mapping[str, tuple[IndexMap, np.dtype]] = field(default_factory=dict) sizes: Mapping[str, int] = field(default_factory=dict) + #: How the bench grades this kernel's program; ``None`` for a reference no bench kernel stands behind. + rule: ProgramRule | None = None def mismatched(self, buffers: dict[str, np.ndarray]) -> list[str]: - """The outputs ``buffers`` gets wrong: exactly compared when both sides are integer, else ``allclose``.""" + """The outputs ``buffers`` gets wrong (:meth:`graded`).""" + return self.graded(buffers)[0] + + def graded(self, buffers: dict[str, np.ndarray]) -> tuple[list[str], str]: + """The outputs ``buffers`` gets wrong, and the bench's detail of each (empty without a rule): by the bench's + rule when there is one, else exactly where both sides are integer and ``allclose`` otherwise.""" buffers = logical_outputs(buffers, self.layouts, self.sizes) + actual = {name: buffers[name].reshape(np.shape(want)) for name, want in self.outputs.items()} + if self.rule is not None: + return grade_program(self.rule, self.outputs, actual, self.rtol, self.atol) wrong: list[str] = [] for name, expected in self.outputs.items(): - got = buffers[name].reshape(np.shape(expected)) + got = actual[name] if got.dtype.kind in "iub" and np.asarray(expected).dtype.kind in "iub": same = np.array_equal(got, expected) else: same = np.allclose(got, expected, rtol=self.rtol, atol=self.atol, equal_nan=True) if not same: wrong.append(name) - return wrong + return wrong, "" @dataclass(frozen=True, slots=True) @@ -150,7 +165,7 @@ def run_program(call: ProgramCall) -> ProgramTime: start = time.perf_counter() built.program(call.buffers, call.sizes) reps = reps_within_budget(call.reps, time.perf_counter() - start) - mismatched = call.reference.mismatched(call.buffers) if call.reference is not None else None + mismatched, detail = call.reference.graded(call.buffers) if call.reference is not None else (None, "") call_once = built.bind(call.buffers, call.sizes) # rewind restores in place, so the bound pointers stay valid total = 0.0 for _ in range(reps): @@ -158,7 +173,7 @@ def run_program(call: ProgramCall) -> ProgramTime: start = time.perf_counter() call_once() total += time.perf_counter() - start - return ProgramTime(time_us=total / reps * US_PER_S, mismatched=mismatched) + return ProgramTime(time_us=total / reps * US_PER_S, mismatched=mismatched, mismatch_detail=detail) finally: built.close() @@ -230,6 +245,7 @@ def timed_report(timed: ProgramTime, reference: Reference | None) -> ProgramRepo correct=not timed.mismatched, mismatched=timed.mismatched, reference=reference.source, + mismatch_detail=timed.mismatch_detail, ) diff --git a/tests/test_bench_data.py b/tests/test_bench_data.py index b484fbb..dc23a6a 100644 --- a/tests/test_bench_data.py +++ b/tests/test_bench_data.py @@ -33,6 +33,16 @@ def test_a_renamed_argument_reaches_the_program_by_its_new_name() -> None: assert reference is not None and set(reference.outputs) == {"G", "fl", "prec", "q"} +def test_the_reference_carries_the_bench_rule_for_every_output() -> None: + """The program is graded as the judge grades it: every output has an accumulation length under its bench name.""" + _, reference = bench_data(Setup("graupel_substep_sedimentation", "S", "float64", False)) + assert reference is not None and reference.rule is not None + rule = reference.rule + assert set(rule.bench_names) == set(reference.outputs) + assert {rule.bench_names[name] for name in reference.outputs} <= set(rule.lengths) + assert all(length > 0 for length in rule.lengths.values()) and rule.eps_acc > 0.0 + + def test_a_kernel_without_renames_keeps_its_names() -> None: assert corpus_kernel("tsvc_2_s231").renames() == {} diff --git a/tests/test_program_grade.py b/tests/test_program_grade.py new file mode 100644 index 0000000..521e5e7 --- /dev/null +++ b/tests/test_program_grade.py @@ -0,0 +1,126 @@ +# Copyright 2021 ETH Zurich and the Tactics authors. +# SPDX-License-Identifier: GPL-3.0-or-later +"""The whole program graded by HPCAgent-Bench's own ``grade_outputs`` (``Reference.rule``): a result the judge passes +is not marked wrong by Tactics, a wrong one still fails, and the verdict is the bench's on a real kernel.""" + +import pickle + +import numpy as np +from helpers import corpus_kernel +from hpcagent_bench.harness.grading import grade_outputs +from hpcagent_bench.harness.scoring import grade_eps + +from tactics.build.grading import ProgramRule +from tactics.server import Setup, bench_data +from tactics.stages.performance import Reference + +#: lulesh XL's accumulation length of ``dxx`` (``contracted_extents``, Daint job 5504603). +LULESH_XL_LENGTH = 1_030_301 + +#: The largest strain rate of lulesh XL, and the error its default left on a few cancelled elements (job 5504603). +LARGEST = 1.3e5 +ROUNDING = 5e-10 + +#: A cancelled strain rate: two values near ``LARGEST`` that nearly cancel. +CANCELLED = 0.1 + +#: The fp64 band ``kernel_tolerances`` gives lulesh. +RTOL, ATOL = 1e-9, 1e-11 + +#: Elements of the synthetic output, and how many of them cancel. +ELEMENTS = 10_000 +CANCELLED_COUNT = 4 + +#: A relative error far outside the band: a wrong result, not rounding. +WRONG = 1e-6 + + +def lulesh_rule() -> ProgramRule: + return ProgramRule(corpus_kernel("lulesh").spec, {"dxx": LULESH_XL_LENGTH}, grade_eps("float64")) + + +def strain_rates() -> tuple[np.ndarray, np.ndarray]: + """A ``dxx`` as lulesh's default leaves it: rounding everywhere, ``ROUNDING`` on a few cancelled elements.""" + rng = np.random.default_rng(0) + want = rng.uniform(-LARGEST, LARGEST, ELEMENTS) + want[:CANCELLED_COUNT] = CANCELLED + got = want * (1 + rng.uniform(-1, 1, ELEMENTS) * np.finfo(np.float64).eps) + got[:CANCELLED_COUNT] += ROUNDING + return want, got + + +# Reproducer: lulesh's dxx/dyy/dzz graded WRONG by Tactics' allclose, right by the bench (T49-08, Daint job 5504603) +def test_rounding_on_cancelled_elements_passes_as_the_bench_passes_it() -> None: + want, got = strain_rates() + assert not np.allclose(got, want, rtol=RTOL, atol=ATOL), "the old check failed it" + + reference = Reference({"dxx": want}, RTOL, ATOL, rule=lulesh_rule()) + + assert reference.graded({"dxx": got}) == ([], "") + assert Reference({"dxx": want}, RTOL, ATOL).mismatched({"dxx": got}) == ["dxx"], "without a rule: allclose" + + +def test_a_wrong_output_still_fails_and_says_by_how_much() -> None: + want, got = strain_rates() + got[ELEMENTS // 2] *= 1 + WRONG + + wrong, detail = Reference({"dxx": want}, RTOL, ATOL, rule=lulesh_rule()).graded({"dxx": got}) + + assert wrong == ["dxx"] + assert detail.startswith("dxx: ") and len(detail) > len("dxx: "), detail + + +def test_a_renamed_output_is_graded_under_the_bench_name() -> None: + want, got = strain_rates() + rule = ProgramRule(lulesh_rule().spec, {"dxx": LULESH_XL_LENGTH}, grade_eps("float64"), {"__dxx": "dxx"}) + got[0] *= 1 + WRONG + + wrong, detail = Reference({"__dxx": want}, RTOL, ATOL, rule=rule).graded({"__dxx": got}) + + assert wrong == ["__dxx"] and detail.startswith("dxx: "), detail + + +def test_an_integer_output_compares_exactly() -> None: + """amg_setup's hierarchy counts: an off-by-one count fails whatever the band (W49-04).""" + spec = corpus_kernel("amg_setup").spec + rule = ProgramRule(spec, {"level_n": 1}, grade_eps("float64")) + want = np.array([884736, 49324, 2222, 39] + [0] * 12, dtype=np.int64) + off = want.copy() + off[2] += 6 + + reference = Reference({"level_n": want}, RTOL, ATOL, rule=rule) + + assert reference.mismatched({"level_n": want.copy()}) == [] + assert reference.mismatched({"level_n": off}) == ["level_n"] + + +def test_a_reference_with_a_rule_pickles_into_a_spawned_child() -> None: + """The GPU path sends ``ProgramCall`` (and its reference) to a spawned child.""" + want, got = strain_rates() + copied = pickle.loads(pickle.dumps(Reference({"dxx": want}, RTOL, ATOL, rule=lulesh_rule()))) + assert copied.rule is not None and copied.graded({"dxx": got}) == ([], "") + + +def test_the_verdict_is_the_bench_verdict_on_a_real_kernel() -> None: + """jacobi_2d at S through bench_data: the reference itself passes, a perturbed output fails, as one call of the + bench's grade_outputs over every output says.""" + _, reference = bench_data(Setup("jacobi_2d", "S", "float64", False)) + assert reference is not None and reference.rule is not None + rule = reference.rule + name = next(iter(reference.outputs)) + perturbed = {key: np.array(value, copy=True) for key, value in reference.outputs.items()} + flat = perturbed[name].reshape(-1) + flat[np.argmax(np.abs(flat))] *= 1 + WRONG # the largest element: a boundary zero would not change + + for actual, expected_wrong in ((reference.outputs, []), (perturbed, [name])): + bench_ok = grade_outputs( + rule.spec, + {rule.bench_names.get(k, k): v for k, v in reference.outputs.items()}, + {rule.bench_names.get(k, k): v for k, v in actual.items()}, + reference.rtol, + reference.atol, + lengths=rule.lengths, + eps_acc=rule.eps_acc, + )[0] + assert reference.mismatched(dict(actual)) == expected_wrong + assert bench_ok is (not expected_wrong)