From a76c2a9328e741450b649421100735cffbcab77c Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Mon, 16 Nov 2026 22:49:31 +0900 Subject: [PATCH 01/11] [Backend] A compile that leaves failure.json stopped, even when the compiler exits 0 Since PTB #260 (342f8fe7) the compiler exits 0 when a kernel file stops exactly where its expect_stop declares, after writing failure.json. run_pipeline read failure.json only on a non-zero exit, so a borrowed PTB case declared blocked at binary (tile_spad_over_budget.py, SPAD_OVERFLOW 786432 > 524288 bytes/lane) came back as compiled, and tests/system/test_compiler_failure.py failed with "... compiled". Inductor's kernels declare no stop, so their runs are unchanged; the compiler clears failure.json at the start of every run. Measured in torchsim-test:2fd9ca08: test_compiler_failure.py fails before, passes after; tests/ops/elementwise/test_add.py passes. --- pytorchsim/backend/compiler_bridge.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/pytorchsim/backend/compiler_bridge.py b/pytorchsim/backend/compiler_bridge.py index 91e8ea7a..da8675a6 100644 --- a/pytorchsim/backend/compiler_bridge.py +++ b/pytorchsim/backend/compiler_bridge.py @@ -136,7 +136,8 @@ def compiler_env(): def run_pipeline(spec_path, workdir, to_stage="pytorchsim-compile", tog=False, timeout=None): """Drive the compiler's stages over `spec_path`, writing artifacts into `workdir`, up to - `to_stage` (by default `pytorchsim-compile`, the ELF). `timeout` is seconds, by default + `to_stage` (by default `pytorchsim-compile`, the ELF); a run that leaves failure.json stopped, even when + it exits 0 because the kernel file declares that stop. `timeout` is seconds, by default TORCHSIM_COMPILE_TIMEOUT or 1800; 0 waits as long as it takes.""" if timeout is None: timeout = int(os.environ.get("TORCHSIM_COMPILE_TIMEOUT") or 1800) @@ -147,8 +148,8 @@ def run_pipeline(spec_path, workdir, to_stage="pytorchsim-compile", tog=False, t proc = subprocess.run(cmd, capture_output=True, text=True, cwd=compiler_dir(), env=compiler_env(), timeout=timeout) - if proc.returncode != 0: - failure = compiler_contract("failure").read(workdir) + failure = compiler_contract("failure").read(workdir) + if proc.returncode != 0 or failure: said = (f"at {failure['stage']} ({failure['kind']}): {failure['message']}" if failure else f"outside every stage:\n{proc.stderr}") raise CompilerError(f"the compiler pipeline failed (exit {proc.returncode}) {said}", From 6e5c6c9cfdf9cd3b04dda10402a333571fb8d102 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Mon, 16 Nov 2026 22:49:31 +0900 Subject: [PATCH 02/11] [Backend] Every kernel retiles through Inductor's standard autotune path on PTB's Triton backend Generated kernels: TritonNPUKernel puts tiling.candidate_blocks in inductor_meta and registered npu codegen heuristics (pointwise, reduction) turn them into configs; a dynamic graph's kernels take their candidates over the size hints. Templates: the mm heuristics hand the choices a select-time spec and GEMM_CANDIDATES tiles; a choice that overflows is dropped at precompile, and can_fuse_vertical refuses a template fusion whose kernel does not fit. User-defined kernels are Inductor's own async_compile.triton, their spec added to the launch kwargs Inductor turns into backend_options, and the roles of their arguments are recorded when they are defined. PTB's backend raises OutOfResources for a config that does not fit and autotune drops it. Launch: backend/launcher.py is registered with driver.set_launcher (Spike, TOGSim) and backend/config_pick.py with register_benchmarker (first compiled config in functional mode, TOGSim cycles in timing mode). Spike takes the launch grid; PTB builds a binary again for extents it was not built for. The wrapper names each call argument's buffer (torchsim_call), so launch.json and tog_tensor_addrs.txt keep their names; copy nodes' TOGs reach the workdir. In timing mode a template's choices are ranked by Inductor's benchmark_choices through the npu benchmarker (time_choices, its pool, cut and memo are gone). Inductor's compile pool is no longer forced to one thread (BERT seq 128: about 125 s -> 81 s). assert_indirect_indexing stays on. The depthwise conv is offered a config per candidate block. Removed: torchsim_compile, retile.py, codecache.py, the make_precompile_fn and pick_config patches, the triton_kernel_kwargs pin, kernel_metadata.compile_call. Tests: test_candidate_overflow, test_depthwise_candidate_overflow, test_dynamic_shape_spike, test_launch_record (addrs file), test_parallel_compile, test_indirect_index_assert, test_select (rewritten to read what each compile built); test_togsim_result, test_graph_prefetch(_xla), test_compiler_failure, test_attention_causal_cycles and npuwattch follow the new path. --- pytorchsim/backend/codecache.py | 171 ------------------ pytorchsim/backend/compiler_input.py | 31 ++++ pytorchsim/backend/config_pick.py | 41 +++++ pytorchsim/backend/launch_hooks.py | 25 +++ pytorchsim/backend/launcher.py | 142 +++++++++++++++ pytorchsim/backend/retile.py | 59 ------ pytorchsim/backend/template_timing.py | 81 ++------- .../dispatcher/custom_fused_kernel.py | 14 ++ .../frontend/dispatcher/depthwise_conv.py | 10 +- pytorchsim/frontend/inductor/__init__.py | 8 +- .../autotune/generated_kernel_blocks.py | 12 ++ .../autotune/generated_kernel_configs.py | 27 +++ .../autotune/template_kernel_configs.py | 31 +++- .../autotune/template_kernel_selection.py | 56 +++--- .../inductor/autotune/template_kernel_spec.py | 36 ++++ .../frontend/inductor/codegen/__init__.py | 4 +- .../inductor/codegen/kernel_metadata.py | 27 ++- .../frontend/inductor/codegen/scheduling.py | 137 +++++++++----- .../frontend/inductor/codegen/user_kernel.py | 101 ++--------- .../frontend/inductor/codegen/wrapper.py | 92 +++------- pytorchsim/frontend/inductor/registration.py | 91 +++++++++- pytorchsim/frontend/tiling.py | 47 +++++ pytorchsim/simulator/functional/__init__.py | 3 +- pytorchsim/simulator/functional/spike.py | 4 +- pytorchsim/simulator/timing/__init__.py | 4 + pytorchsim/simulator/timing/npuwattch.py | 5 +- .../attention/test_attention_causal_cycles.py | 4 +- .../conv/test_depthwise_candidate_overflow.py | 54 ++++++ .../elementwise/test_candidate_overflow.py | 49 +++++ tests/ops/misc/test_indirect_index_assert.py | 40 ++++ .../data/npuwattch_tpuv3/kernel/meta.json | 2 +- tests/system/stub_compile.py | 16 ++ tests/system/test_compiler_failure.py | 11 +- tests/system/test_dynamic_shape_spike.py | 6 +- tests/system/test_graph_prefetch.py | 52 ++---- tests/system/test_graph_prefetch_xla.py | 6 +- tests/system/test_launch_record.py | 19 ++ tests/system/test_npuwattch_json.py | 19 ++ tests/system/test_parallel_compile.py | 32 ++++ tests/system/test_select.py | 152 +++++----------- tests/system/test_togsim_result.py | 11 +- tests/system/test_tuned_blocks_on_hit.py | 40 ---- 42 files changed, 1020 insertions(+), 752 deletions(-) delete mode 100644 pytorchsim/backend/codecache.py create mode 100644 pytorchsim/backend/config_pick.py create mode 100644 pytorchsim/backend/launcher.py delete mode 100644 pytorchsim/backend/retile.py create mode 100644 pytorchsim/frontend/inductor/autotune/generated_kernel_configs.py create mode 100644 pytorchsim/frontend/inductor/autotune/template_kernel_spec.py create mode 100644 tests/ops/conv/test_depthwise_candidate_overflow.py create mode 100644 tests/ops/elementwise/test_candidate_overflow.py create mode 100644 tests/ops/misc/test_indirect_index_assert.py create mode 100644 tests/system/stub_compile.py create mode 100644 tests/system/test_parallel_compile.py delete mode 100644 tests/system/test_tuned_blocks_on_hit.py diff --git a/pytorchsim/backend/codecache.py b/pytorchsim/backend/codecache.py deleted file mode 100644 index 51fbf390..00000000 --- a/pytorchsim/backend/codecache.py +++ /dev/null @@ -1,171 +0,0 @@ -"""Compile cache for the codegen route: torchsim_compile(src, meta, kernel_name) turns one kernel into -a launcher the call site calls with the kernel's args; one directory per source hash holds the -compiler's kernel file and every artifact.""" - -import copy -import os - -from filelock import FileLock -from torch._inductor.codecache import get_hash - -from pytorchsim import config, contract -from pytorchsim.backend import retile, compiler_bridge, compiler_input, launch_hooks -from pytorchsim.backend.build_identity import cached_elf, store_identity -from pytorchsim.simulator import functional, timing, wallclock - -logger = config.setup_logger() - -LOCK_TIMEOUT = 600 - - -def _write_path(src_code, meta): - """The kernel's workdir, keyed by everything its ELF is built from: the source, and the - constexprs, grid, arguments and graph_prefetch the spec bakes in (a held and a streamed - build of one source differ only there).""" - baked = (meta.get("signature"), meta.get("constants"), meta.get("fixed_config"), - meta.get("template_grid"), meta["graph_prefetch"], meta.get("numels"), - [(a["name"], a["role"], a["dtype"], a["numel"]) for a in meta.get("args", ())]) - return os.path.join(config.get_dump_path(), - "triton_" + get_hash(src_code.strip() + repr(baked))[1:12]) - - -class TritonNPULauncher: - """What a compiled kernel name is bound to in the generated wrapper: each call launches the whole - grid, Spike first so the tensors hold real values even if TOGSim fails; Spike on the ELF built for - the launch's extents, a new one per extents the import-time build (a dynamic graph's hints) missed.""" - def __init__(self, kernel_name, workdir, meta, src_code=None): - self.kernel_name = kernel_name - self.workdir = workdir - self.meta = meta - self.src_code = src_code - self._builds = {} - - def __call__(self, *args, torchsim_arg_names=None): - launch_hooks.notify_launch(self, args) - if config.pytorchsim_functional_mode: - build = self._get_build_for(args) - with wallclock.span(wallclock.SPIKE, self.kernel_name): - written = functional.run(build.workdir, build.meta, args) - logger.info("[Spike] %s wrote %s", self.kernel_name, written) - else: - logger.warning( - "[Spike] %s: functional mode is off, so the output tensors keep " - "whatever they held", self.kernel_name) - - if not config.pytorchsim_timing_mode: - logger.warning( - "[timing] %s: timing mode is off, so no cycles are reported", - self.kernel_name) - return None - - result = timing.run(self.workdir, self.meta, args, torchsim_arg_names) - if result is None: - logger.info("[TOGSim] %s queued on the open TOGSimulator; the stream's cycles " - "are reported when the simulator closes", self.kernel_name) - else: - logger.info("[TOGSim] %s simulated: %d cycles", self.kernel_name, result["total_cycles"]) - return result - - def _get_build_for(self, args): - """This launcher when the launch's extents are the ones it was built for, else the build for - them: each tensor's storage span and each numel the launch passes as a scalar, baked in an ELF.""" - extents = _get_launch_extents(self.meta, args) - if extents == _get_launch_extents(self.meta, None) or self.src_code is None: - return self - if extents not in self._builds: - from pytorchsim.simulator.placement import tensor_args - meta = copy.deepcopy(self.meta) - for a, (_, t), (_, span) in zip(meta["args"], tensor_args(self.meta, args), extents[0]): - a["numel"] = span - if a.get("sizes") is not None: - a["sizes"] = list(t.shape) - meta["numels"].update(dict(extents[1])) - logger.info("[torchsim-compile] %s: a launch over %s, not the %s it was built for; building it", - self.kernel_name, extents, _get_launch_extents(self.meta, None)) - self._builds[extents] = torchsim_compile(self.src_code, meta, self.kernel_name) - return self._builds[extents] - - -def _get_launch_extents(meta, args): - """((arg, storage span) per tensor, (numel, value) per numel passed as a scalar) of a launch, or of the - build itself when `args` is None.""" - from pytorchsim.contract import storage_span - from pytorchsim.simulator.placement import tensor_args - - if args is None: - spans = tuple((a["name"], a["numel"]) for a in meta["args"]) - return spans, tuple(sorted((k, v) for k, v in meta["numels"].items() if k in _get_runtime_params(meta))) - spans = tuple((m["name"], storage_span(t.shape, t.stride())) for m, t in tensor_args(meta, args)) - bound = dict(zip(_get_runtime_params(meta), args)) - numels = tuple(sorted((k, bound[k]) for k in meta["numels"] if k in bound - and isinstance(bound[k], int) and not isinstance(bound[k], bool))) - return spans, numels - - -def _get_runtime_params(meta): - """The kernel's parameters a launch passes, in order: the signature's that are not constexprs.""" - return [k for k, v in (meta.get("signature") or {}).items() if v != "constexpr"] - - -def torchsim_compile(src_code, meta, kernel_name): - """Compile one Inductor-generated Triton kernel through the compiler, synchronously, when the - generated wrapper is imported, holding what meta's graph_prefetch states; the compiler's - refusal to hold it is an error: the lowering's election and the compiler disagree.""" - write_path = _write_path(src_code, meta) - os.makedirs(write_path, exist_ok=True) - - lock = FileLock(os.path.join(write_path, ".compile.lock"), timeout=LOCK_TIMEOUT) - with lock: - spec_path = os.path.join(write_path, f"{kernel_name}_spec.py") - elf = cached_elf(write_path, kernel_name) - if (elf is not None and config.pytorchsim_timing_mode - and contract.artifact(write_path, "tog_so") is None): - logger.info("[torchsim-compile] %s: cached without --tog, rebuilding for timing", - kernel_name) - elf = None - if elf is None: - with open(os.path.join(write_path, "kernel.py"), "w") as f: - f.write(src_code) - compiler_input.store_meta(write_path, meta) - retries = retile.smaller_tiles(src_code, meta) - while True: - compiler_input.write(src_code, meta, spec_path) - try: - with wallclock.span(wallclock.TORCHSIM_COMPILE, kernel_name): - compiler_bridge.run_pipeline( - spec_path, write_path, to_stage="pytorchsim-compile", - tog=bool(config.pytorchsim_timing_mode)) - wallclock.ingest_compile(write_path, kernel_name) - break - except compiler_bridge.CompilerError as exc: - _refuse_held(exc, meta) - why = retile.too_big(exc) - if why is None: - raise - retry = next(retries, None) - if retry is None: - logger.warning("[torchsim-compile] %s: %s, and no smaller tile is " - "left to try", kernel_name, why) - raise - tile, src_code, tuned = retry - meta.update(tuned) - logger.info("[torchsim-compile] %s: %s, trying %s", kernel_name, why, tile) - with open(os.path.join(write_path, "kernel.py"), "w") as f: - f.write(src_code) - compiler_input.store_meta(write_path, meta) - store_identity(write_path) - else: - compiler_input.load_tuned_blocks(write_path, meta) - logger.info("[torchsim-compile] %s -> %s", kernel_name, write_path) - return TritonNPULauncher(kernel_name, write_path, meta, src_code) - - -def _refuse_held(exc, meta): - """Raise, naming the kernel and the held args, when the compiler refused to hold what meta's - graph_prefetch states (contract/failure): a scratchpad overflow or no prefetch candidate.""" - got = getattr(exc, "failure", None) or {} - kinds = compiler_bridge.compiler_contract("failure") - if meta["graph_prefetch"] and got.get("kind") in (kinds.SPAD_OVERFLOW, kinds.NOT_A_PREFETCH_CANDIDATE): - raise compiler_bridge.CompilerError( - f"{meta['kernel_name']}: the compiler refuses to hold {meta['graph_prefetch']} " - f"({got['kind']}: {got.get('message')}), which the lowering elected", exc.cmd, got) from exc diff --git a/pytorchsim/backend/compiler_input.py b/pytorchsim/backend/compiler_input.py index b54a4267..10caaf9b 100644 --- a/pytorchsim/backend/compiler_input.py +++ b/pytorchsim/backend/compiler_input.py @@ -185,6 +185,37 @@ def write(src_code, meta, path, recorded=None, scalars=None): return path +def spec_json(meta): + """The kernel's spec in the compiler's JSON_FIELDS form (contract/kernel_spec), as the PTB Triton backend + takes it in the pytorchsim_spec option: what its Triton IR does not hold. The kernel's name, signature + and each tensor's name and dtype are the IR's; each tensor is stated by role and storage span, in order.""" + missing = [a["name"] for a in meta["args"] if not a["numel"]] + if missing: + raise SpecIncomplete(f"{meta['kernel_name']}: no numel for {missing} -- " + f"collect_meta could not resolve them from V.graph") + scalars = scalar_args(meta) + return json.dumps(spec_dict( + [(a["role"], a["numel"]) for a in meta["args"]], contract.grid_xyz(meta), + list(graph_prefetch(meta)), list(contract.launch_axes(meta)), + {"scalar_args": [[n, c] for n, c, _ in scalars], + "scalar_values": {n: v for n, _, v in scalars if v is not None}})) + + +def backend_options(spec): + """The Triton backend's options for a kernel whose spec JSON is `spec`: the spec, whether the compile builds the + TOG (timing mode), and the machine TORCHSIM_TARGET names, which the compile otherwise takes from its environment.""" + from pytorchsim import config + return {"pytorchsim_spec": spec, "pytorchsim_tog": bool(config.pytorchsim_timing_mode), + "pytorchsim_target": compiler_bridge.target().file} + + +def spec_dict(tensors, grid, held=(), axes=("x",), extra=None): + """A JSON spec: `tensors` as (role, numel) per pointer parameter in order, the default launch `grid`, the + tensor indices held, the axes the launch spreads over.""" + return {"args": [{"role": r, "shape": [n]} for r, n in tensors], "grid": list(grid), "grid_rule": True, + "graph_prefetch": list(held), "parallel_axes": list(axes), "extra": extra or {}} + + META_JSON = "meta.json" diff --git a/pytorchsim/backend/config_pick.py b/pytorchsim/backend/config_pick.py new file mode 100644 index 00000000..656d4aab --- /dev/null +++ b/pytorchsim/backend/config_pick.py @@ -0,0 +1,41 @@ +"""Which of a kernel's compiled configs runs: Inductor's autotuner times each through the benchmarker registered +for npu. Functional mode picks the first that compiled, in the order its candidates were offered, without +launching any; timing mode launches each as a measurement, which TOGSim answers in cycles.""" + +import contextlib +import itertools +import threading + +_ORDER = itertools.count(1) +_STATE = threading.local() + + +def measuring(): + """Whether a launch is being timed by the benchmarker: it then yields its cycles and runs nothing else.""" + return getattr(_STATE, "cycles", None) is not None + + +def report(cycles): + """The launch being measured took `cycles` on TOGSim.""" + _STATE.cycles.append(cycles) + + +def benchmark(benchmarker, fn, *, warmup, rep, **kwargs): + """The 'time' of fn, in ms: in functional mode later calls are larger, so the first config offered wins + and fn is not called; in timing mode fn launches the kernel, and TOGSim's cycles (1 cycle = 1 ns) come back, + inf when it launched nothing (an extern kernel) or did not simulate.""" + from pytorchsim import config + if not config.pytorchsim_timing_mode: + return next(_ORDER) * 1e-3 + with _measure() as got: + fn() + return got[-1] * 1e-6 if got else float("inf") + + +@contextlib.contextmanager +def _measure(): + _STATE.cycles = [] + try: + yield _STATE.cycles + finally: + _STATE.cycles = None diff --git a/pytorchsim/backend/launch_hooks.py b/pytorchsim/backend/launch_hooks.py index 5f140095..6cf9c429 100644 --- a/pytorchsim/backend/launch_hooks.py +++ b/pytorchsim/backend/launch_hooks.py @@ -2,9 +2,11 @@ launch's inputs, and at every call Inductor leaves to aten (the generated wrapper's torchsim_extern).""" _LAUNCH_OBSERVERS = {} +_USER_KERNEL_NAMES = {} _EVERY_LAUNCH = [] _EVERY_LAUNCH_INPUTS = [] _EVERY_EXTERN = [] +_CALL_NAMES = [] def user_kernel_id(kernel): @@ -12,6 +14,16 @@ def user_kernel_id(kernel): return f"{kernel.__module__}.{kernel.__qualname__}" +def user_kernel_of(kernel_name): + """The id of the user-defined Triton kernel that compiled as `kernel_name`, or None.""" + return _USER_KERNEL_NAMES.get(kernel_name) + + +def name_user_kernel(kernel_name, kernel): + """Record that `kernel_name` is the compile of the user-defined Triton kernel `kernel`.""" + _USER_KERNEL_NAMES[kernel_name] = user_kernel_id(kernel) + + def observe_launches(kernel, callback): """Call `callback()` at every launch of the user-defined Triton kernel `kernel`.""" _LAUNCH_OBSERVERS[user_kernel_id(kernel)] = callback @@ -40,6 +52,19 @@ def torchsim_extern(call): callback(call) +def torchsim_call(names): + """The generated wrapper's note before a Triton kernel's call: the buffer each argument is, taken by the + launch that follows it (a kernel's variable in the wrapper is not the name its binary carries).""" + _CALL_NAMES[:] = [names] + + +def take_call_names(count): + """The buffer names of the first `count` arguments the wrapper noted for this launch, once (a template's + call also lists its grid), or None when it noted none (a launch made while Inductor benchmarks).""" + names = _CALL_NAMES.pop() if _CALL_NAMES else None + return names[:count] if names is not None and len(names) >= count else None + + def notify_launch(launcher, args): """Call, before `launcher` runs: its user-defined kernel's observer, every launch's, and every launch's with its inputs.""" diff --git a/pytorchsim/backend/launcher.py b/pytorchsim/backend/launcher.py new file mode 100644 index 00000000..d0a2f846 --- /dev/null +++ b/pytorchsim/backend/launcher.py @@ -0,0 +1,142 @@ +"""The runner PTB's Triton driver launches a compiled kernel through (driver.set_launcher): the ELF and +kernel.json it is handed become a workdir, and the launch runs on Spike and, in timing mode, TOGSim.""" + +import base64 +import hashlib +import json +import math +import os + +from filelock import FileLock + +from pytorchsim import config +from pytorchsim.backend import compiler_input, config_pick, launch_hooks +from pytorchsim.simulator import functional, timing, wallclock + +logger = config.setup_logger() + +LOCK_TIMEOUT = 600 +_AXES = ("x", "y", "z") + + +class Launch: + """What launch_hooks observers see of a launch: the kernel, where its object is, and its meta.""" + + def __init__(self, kernel_name, workdir, meta): + self.kernel_name = kernel_name + self.workdir = workdir + self.meta = meta + + +def install(): + """Register run_launch as the runner of PTB's Triton driver.""" + from triton.backends.pytorchsim.driver import set_launcher + + set_launcher(run_launch) + + +def run_launch(binary, kernel_object, grid, args, artifacts=None): + """One launch over `grid`: Spike first, so the tensors hold real values even if TOGSim fails, then (timing + mode) TOGSim; returns TOGSim's result, None otherwise or when the launch is queued on the open simulator.""" + manifest = json.loads(kernel_object) + workdir = _get_workdir(binary, kernel_object, manifest, artifacts) + meta = _get_meta(manifest, grid, args) + launch = Launch(manifest["name"], workdir, meta) + if config_pick.measuring(): + config_pick.report(_simulate_alone(workdir, meta, args)) + return None + launch_hooks.notify_launch(launch, args) + if config.pytorchsim_functional_mode: + with wallclock.span(wallclock.SPIKE, launch.kernel_name): + written = functional.run(workdir, meta, args) + logger.info("[Spike] %s wrote %s", launch.kernel_name, written) + else: + logger.warning("[Spike] %s: functional mode is off, so the output tensors keep " + "whatever they held", launch.kernel_name) + + if not config.pytorchsim_timing_mode: + logger.warning("[timing] %s: timing mode is off, so no cycles are reported", launch.kernel_name) + return None + result = timing.run(workdir, meta, args, launch_hooks.take_call_names(len(args))) + if result is None: + logger.info("[TOGSim] %s queued on the open TOGSimulator; the stream's cycles are reported " + "when the simulator closes", launch.kernel_name) + else: + logger.info("[TOGSim] %s simulated: %d cycles", launch.kernel_name, result["total_cycles"]) + return result + + +def _store_meta(workdir, meta, args, names): + """workdir/meta.json, once: the launch's meta with each tensor's sizes and buffer, which npuwattch reads.""" + import torch + + path = os.path.join(workdir, compiler_input.META_JSON) + if os.path.exists(path): + return + tensors = [(i, a) for i, a in enumerate(args) if torch.is_tensor(a)] + stored = dict(meta, args=[dict(m, sizes=list(t.shape), buffer=names[i] if names else None) + for m, (i, t) in zip(meta["args"], tensors)]) + with open(path + ".tmp", "w") as f: + json.dump(stored, f) + os.replace(path + ".tmp", path) + + +def _simulate_alone(workdir, meta, args): + """TOGSim cycles of this launch run alone (a configuration being timed): inf when it does not simulate.""" + from pytorchsim import contract + from pytorchsim.backend import template_timing + + try: + timing.write_cycle_tables(workdir, meta) + mine = contract.link_shared(workdir, timing.SHARED) + timing.write_shape(workdir, meta, args) + timing.write_tensors(workdir) + return timing.simulate_standalone(workdir, mine, template_timing._records(workdir, meta), + autotune_mode=True)["total_cycles"] + except (RuntimeError, FileNotFoundError) as exc: + logger.info("[select] %s: %s", meta["kernel_name"], exc) + return float("inf") + + +def _get_workdir(binary, kernel_object, manifest, artifacts): + """The directory of this binary's kernel object, one per (ELF, kernel.json) under the dump path, written + once, with the other files its object names beside it.""" + key = hashlib.sha256(bytes(binary) + kernel_object.encode()).hexdigest()[:11] + workdir = os.path.join(config.get_dump_path(), f"triton_{key}") + os.makedirs(workdir, exist_ok=True) + arts = manifest["artifacts"] + files = {arts["elf"]: bytes(binary), "kernel.json": kernel_object.encode()} + for item in json.loads(artifacts).values() if artifacts else (): + files[item["name"]] = base64.b64decode(item["data"]) + with FileLock(os.path.join(workdir, ".launch.lock"), timeout=LOCK_TIMEOUT): + for name, data in files.items(): + path = os.path.join(workdir, name) + if not os.path.exists(path): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path + ".tmp", "wb") as f: + f.write(data) + os.chmod(path + ".tmp", 0o755) + os.replace(path + ".tmp", path) + return workdir + + +def _get_meta(manifest, grid, args): + """The launch's meta, as the functional and timing runners read it: the manifest's tensors by role, + dtype and storage span, each argument's parameter name in order, the launch's extents per axis.""" + import torch + + tensors = iter(manifest["args"]) + scalars = iter(manifest.get("scalars", ())) + call_params = [next(tensors)["name"] if torch.is_tensor(a) else next(scalars)["name"] for a in args] + axes = manifest["abi"]["parallel_axes"] + return { + "kernel_name": manifest["name"], + "args": [{"name": a["name"], "role": a["role"], "dtype": a["dtype"], + "numel": math.prod(a["shape"]), "sizes": None} for a in manifest["args"]], + "call_params": call_params, + "numels": {}, + "template_grid": None, + "launch_grid": tuple(int(g) for g in grid), + "launch_extents": [int(grid[_AXES.index(a)]) for a in axes], + "user_kernel": launch_hooks.user_kernel_of(manifest["name"]), + } diff --git a/pytorchsim/backend/retile.py b/pytorchsim/backend/retile.py deleted file mode 100644 index b0924705..00000000 --- a/pytorchsim/backend/retile.py +++ /dev/null @@ -1,59 +0,0 @@ -"""A kernel the compiler refuses as too big is retried at smaller blocks: its pinned blocks (its -fixed_config) halve; a template's blocks are its config, which Inductor chose, and are built as rendered.""" - -import copy -import itertools - -from pytorchsim.backend import compiler_bridge - - -def too_big(exc): - """Why this failure means the tile is too big, else None: the scratchpad budget it broke or the - register file (llc spilled, which the compiler's ELF refuses), as the compiler's failure.json - names it. Triton's own block limit is never the reason: every block tiling pins is under it.""" - got = getattr(exc, "failure", None) or {} - kinds = compiler_bridge.compiler_contract("failure") - if got.get("kind") == kinds.SPAD_OVERFLOW: - return "%d bytes/lane over a budget of %d" % (got["usage"], got["budget"]) - if got.get("kind") == kinds.SPILL_NOT_ALLOWED: - return "the vector register file spills" - return None - - -def _get_tile_candidates(meta): - """Every tile the search may try, LARGEST FIRST: each block the kernel takes as - an argument halves down to 2, never 1. Equal sizes go to the larger reduction - block; the first is the tile fixed_config_for pinned.""" - cfg = meta.get("fixed_config") or {} - signature = meta.get("signature") or {} - movable = [k for k, v in cfg.items() if k in signature and v and v >= 2] - ranges = [] - for k in movable: - vs, v = [], cfg[k] - while v >= 2: - vs.append(v) - v //= 2 - ranges.append(vs) - - def _product(tile, keep): - n = 1 - for k, v in tile.items(): - if keep(k): - n *= v - return n - tiles = [dict(zip(movable, vs)) for vs in itertools.product(*ranges)] - tiles.sort(key=lambda t: (-_product(t, lambda k: True), - -_product(t, lambda k: k.startswith("R")), - [-t[k] for k in movable])) - return tiles - - -def smaller_tiles(src_code, meta): - """(tile, source, meta) to retry with after the compiler refuses a kernel as too big: each - smaller fixed_config tile.""" - tiles = iter(_get_tile_candidates(meta)) - next(tiles, None) - for tile in tiles: - meta = copy.deepcopy(meta) - meta["fixed_config"].update(tile) - yield {k: v for k, v in tile.items() if k.endswith("BLOCK")}, src_code, meta diff --git a/pytorchsim/backend/template_timing.py b/pytorchsim/backend/template_timing.py index 87acec8d..89832f06 100644 --- a/pytorchsim/backend/template_timing.py +++ b/pytorchsim/backend/template_timing.py @@ -1,28 +1,24 @@ -"""A template config timed in TOGSim cycles, in timing mode: every config of a timed template at once -(time_choices, a slow one cut), and a module Inductor wrote to benchmark a fusion (time_module). What a -timed pick leaves for next time is template_record.py.""" +"""A module Inductor wrote to benchmark an epilogue fusion, timed in TOGSim cycles (time_module); the configs of a +template are timed by Inductor's own selection through the npu benchmarker (config_pick.py). What a timed pick +leaves for next time is template_record.py.""" -import concurrent.futures import hashlib import json import os import subprocess -import time from pytorchsim import config, contract from pytorchsim.frontend.inductor.autotune import graph_prefetch from pytorchsim.frontend.inductor.codegen import kernel_metadata -from pytorchsim.backend import retile, compiler_bridge, compiler_input, template_record +from pytorchsim.backend import compiler_bridge, compiler_input, template_record from pytorchsim.simulator import timing logger = config.setup_logger() -def _time_tile(src_code, meta, kernel_name, workdir, cut=None): +def _time_tile(src_code, meta, kernel_name, workdir): """TOGSim cycles of one kernel, simulated alone; inf if it does not compile in the bridge's timeout - or run, or `cut` stops its simulation. TOGSim's refusal of a tile over the spad and a cut reach here - as RuntimeError.""" - from pytorchsim.simulator.timing.togsim import Cut + or run. TOGSim's refusal of a tile over the spad reaches here as RuntimeError.""" os.makedirs(workdir, exist_ok=True) spec_path = os.path.join(workdir, f"{kernel_name}_spec.py") with open(os.path.join(workdir, "kernel.py"), "w") as f: @@ -36,16 +32,28 @@ def _time_tile(src_code, meta, kernel_name, workdir, cut=None): timing.write_shape(workdir, meta) timing.write_tensors(workdir) return timing.simulate_standalone(workdir, mine, _records(workdir, meta), - autotune_mode=True, cut=cut)["total_cycles"] + autotune_mode=True)["total_cycles"] except subprocess.TimeoutExpired as exc: logger.info("[select] %s %s: not compiled in %.0f s", kernel_name, workdir, exc.timeout) return float("inf") except (compiler_bridge.CompilerError, RuntimeError, FileNotFoundError) as exc: - why = retile.too_big(exc) or (f"cut, {exc}" if isinstance(exc, Cut) else f"{type(exc).__name__}: {exc}") + why = _too_big(exc) or f"{type(exc).__name__}: {exc}" logger.info("[select] %s %s: %s", kernel_name, workdir, why) return float("inf") +def _too_big(exc): + """Why this compiler failure means the tile is too big, else None: the scratchpad budget it broke or + the register file (llc spilled), as the compiler's failure.json names it.""" + got = getattr(exc, "failure", None) or {} + kinds = compiler_bridge.compiler_contract("failure") + if got.get("kind") == kinds.SPAD_OVERFLOW: + return "%d bytes/lane over a budget of %d" % (got["usage"], got["budget"]) + if got.get("kind") == kinds.SPILL_NOT_ALLOWED: + return "the vector register file spills" + return None + + def _records(workdir, meta): """The runtime attribute records the TOG of the kernel in `workdir` reads: "" when it declares none, else a Spike run's on zeros, the launch's own when no record reads an input (its sources); records that read one @@ -94,55 +102,6 @@ def times(choices): return template_record.autotunes() and any(template_record.is_timed(c) for c in choices) -#: A config still simulating this many times the wall time the first config to finish took is cut. -#: The configs run at once, so a loaded host slows them alike and the ratio stands. -CUT_FACTOR = 3 - - -def time_choices(choices): - """Cycles per choice for AlgorithmSelectorCache: each config of a timed template as Inductor - rendered it, all at once, every other choice inf. A config whose simulation runs past - CUT_FACTOR times the wall time of the first one timed is cut, and is inf.""" - out = {c: float("inf") for c in choices} - timed = [c for c in choices if template_record.is_timed(c)] - jobs = [(c, *kernel_metadata.benchmark_request_meta(c.bmreq)) for c in timed] - for c, _, meta in jobs: - meta["graph_prefetch"] = graph_prefetch.choice_statement(c.annotations["ktc"], meta["args"]) - keys = {c: _timing_key(src, meta) for c, src, meta in jobs} - for c, _, _ in jobs: - if keys[c] in _timed: - logger.info("[select] %s %s: %s cycles, timed before in this process", - c.name, c.description, _timed[keys[c]]) - c.annotations["ktc"].annotations[template_record.SOURCE] = template_record.TIMED - out[c] = _timed[keys[c]] - jobs = [j for j in jobs if keys[j[0]] not in _timed] - t0, first = time.monotonic(), [] - - def cut(): - if first and time.monotonic() - t0 > CUT_FACTOR * first[0]: - return f"past {CUT_FACTOR}x the {first[0]:.0f} s the first config took" - return None - - def one(job): - c, src, meta = job - got = _time_tile(src, meta, c.bmreq.kernel_name, _workdir(c.bmreq.module_cache_key), cut) - if got != float("inf") and not first: - first.append(time.monotonic() - t0) - return got - - with concurrent.futures.ThreadPoolExecutor(max_workers=max(len(jobs), 1)) as pool: - cycles = pool.map(one, jobs) - for (c, _, _), got in zip(jobs, cycles): - logger.info("[select] %s %s: %s cycles", c.name, c.description, got) - c.annotations["ktc"].annotations[template_record.SOURCE] = template_record.TIMED - out[c] = _timed[keys[c]] = got - if timed and all(out[c] == float("inf") for c in timed): - raise RuntimeError( - f"no template config of {[c.name for c in timed]} compiled and ran on TOGSim; " - f"the [select] lines above say why each one did not") - return out - - def time_module(src_code, meta, path): """TOGSim cycles of a kernel module Inductor wrote to benchmark a fusion, named by its path.""" key = _timing_key(src_code, meta) diff --git a/pytorchsim/frontend/dispatcher/custom_fused_kernel.py b/pytorchsim/frontend/dispatcher/custom_fused_kernel.py index 577bbb12..b4cb23ec 100644 --- a/pytorchsim/frontend/dispatcher/custom_fused_kernel.py +++ b/pytorchsim/frontend/dispatcher/custom_fused_kernel.py @@ -118,6 +118,20 @@ def _count(self, route): self.calls[route] = self.calls.get(route, 0) + 1 +_AUTOTUNED = {} + + +def autotuned(kernel, name, sizes): + """`kernel` offered to Inductor with a config per size of its constexpr `name`, largest first: Triton's own + autotune, whose configs the compile drops one by one when they overflow the scratchpad.""" + import triton + key = (kernel, name, tuple(sizes)) + if key not in _AUTOTUNED: + _AUTOTUNED[key] = triton.autotune(configs=[triton.Config({name: s}, num_warps=1, num_stages=1) + for s in sizes], key=[])(kernel) + return _AUTOTUNED[key] + + def _describe(call): return ", ".join(f"{tuple(a.shape)} {a.dtype}" if isinstance(a, torch.Tensor) else repr(a) for a in call) diff --git a/pytorchsim/frontend/dispatcher/depthwise_conv.py b/pytorchsim/frontend/dispatcher/depthwise_conv.py index 31c57801..16526980 100644 --- a/pytorchsim/frontend/dispatcher/depthwise_conv.py +++ b/pytorchsim/frontend/dispatcher/depthwise_conv.py @@ -10,8 +10,9 @@ from torch.library import wrap_triton from pytorchsim import config +from pytorchsim.frontend import tiling from pytorchsim.frontend.dispatcher.custom_fused_kernel import ( - CustomFusedKernel, Decline, fits_scratchpad, next_pow2) + CustomFusedKernel, Decline, autotuned, fits_scratchpad, next_pow2) class DepthwiseConv2d(CustomFusedKernel): @@ -24,7 +25,7 @@ def kernels(self): def plan(self, x, w, bias, stride, padding, dilation): """BC channels a program: the lanes, doubled toward the channels' cover while a row's tiles fit the - scratchpad budget, else halved until they do.""" + scratchpad budget, else halved until they do; the launch offers it and its halves as configs.""" if not x.is_floating_point() or x.dtype != w.dtype: return Decline(f"input {x.dtype}, weight {w.dtype}") wo = _out_size(x.shape[3], w.shape[3], stride[1], padding[1], dilation[1]) @@ -48,9 +49,10 @@ def launch(self, plan, x: torch.Tensor, w: torch.Tensor, bias: Optional[torch.Te wo = _out_size(wd, kw, stride[1], padding[1], dilation[1]) out = x.new_empty(n, c, ho, wo) b = bias if bias is not None else w.new_zeros(c) - wrap_triton(_depthwise_kernel)[(n * triton.cdiv(c, plan["BC"]), ho, 1)]( + kernel = autotuned(_depthwise_kernel, "BC", tiling.candidate_sizes(plan["BC"])) + wrap_triton(kernel)[lambda meta: (n * triton.cdiv(c, meta["BC"]), ho, 1)]( x.contiguous(), w.contiguous(), b, out, c, h, wd, ho, wo, kh, kw, stride[0], stride[1], - padding[0], padding[1], dilation[0], dilation[1], plan["BC"], plan["BW"]) + padding[0], padding[1], dilation[0], dilation[1], BW=plan["BW"]) return out def fallback(self, x, w, bias, stride, padding, dilation): diff --git a/pytorchsim/frontend/inductor/__init__.py b/pytorchsim/frontend/inductor/__init__.py index 6e507204..d2c3ca35 100644 --- a/pytorchsim/frontend/inductor/__init__.py +++ b/pytorchsim/frontend/inductor/__init__.py @@ -27,7 +27,8 @@ def install(): def _configure_inductor(): """mm/conv template autotune on, at compile time off, its tables shown in debug mode unless the env sets them; Inductor's autotune cache off (template_timing records picks); no combo kernels, which pick tensors - by program id (a TOG cannot time that) and skip the triton_kernel_kwargs hook that pins blocks.""" + by program id (a TOG cannot time that); kernels compile in this process, where the Triton driver is the npu's; no device_assert in a kernel (a + debug compile, which the compiler does not lower).""" from torch._inductor import config as inductor_config if "TORCHINDUCTOR_AUTOTUNE_NUM_CHOICES_DISPLAYED" not in os.environ: @@ -35,7 +36,7 @@ def _configure_inductor(): if "TORCHINDUCTOR_MAX_AUTOTUNE_REPORT_CHOICES_STATS" not in os.environ: inductor_config.max_autotune_report_choices_stats = bool(config.CONFIG_DEBUG_MODE) inductor_config.max_autotune_gemm = True - inductor_config.max_autotune_gemm_backends = "ATEN,TRITON" + inductor_config.max_autotune_gemm_backends = "ATEN,TRITON" if config.pytorchsim_timing_mode else "TRITON" inductor_config.max_autotune_conv_backends = "ATEN,TRITON" inductor_config.triton.autotune_at_compile_time = False timed = bool(config.pytorchsim_timing_mode) @@ -43,8 +44,7 @@ def _configure_inductor(): inductor_config.max_epilogue_benchmarked_choices = config.codegen_autotune_template_topk inductor_config.autotune_local_cache = False inductor_config.combo_kernels = False - if timed: - inductor_config.compile_threads = 1 + inductor_config.dynamic_scale_rblock = False def is_npu(obj): diff --git a/pytorchsim/frontend/inductor/autotune/generated_kernel_blocks.py b/pytorchsim/frontend/inductor/autotune/generated_kernel_blocks.py index 8e65b202..06a0f907 100644 --- a/pytorchsim/frontend/inductor/autotune/generated_kernel_blocks.py +++ b/pytorchsim/frontend/inductor/autotune/generated_kernel_blocks.py @@ -25,6 +25,18 @@ def pinned_blocks(kernel_tiling, features): return FixedTritonConfig(cfg) if cfg else None +def candidates_for(kernel_tiling, features): + """The tiles a generated kernel of `kernel_tiling` is offered, largest first (tiling.candidate_blocks), + as dicts of block name to size, over the size hints of numels that are not static.""" + if features is None or not kernel_tiling: + return [] + from torch._inductor.virtualized import V + numels = {f"{prefix}numel": int(V.graph.sizevars.optimization_hint(n)) for prefix, n in kernel_tiling.items()} + shim = type("K", (), {"inside_reduction": bool(features.is_reduction()), "numels": numels})() + return tiling.candidate_blocks(shim, numels, _widest_dtype_args(features), + contiguous=_kept_axis_contiguous(features)) + + def blocks_for(numels, features): """tiling.fixed_config_for for a scheduled kernel of `numels` (numel -> int).""" shim = type("K", (), {"inside_reduction": bool(features.is_reduction()), "numels": numels})() diff --git a/pytorchsim/frontend/inductor/autotune/generated_kernel_configs.py b/pytorchsim/frontend/inductor/autotune/generated_kernel_configs.py new file mode 100644 index 00000000..cab21824 --- /dev/null +++ b/pytorchsim/frontend/inductor/autotune/generated_kernel_configs.py @@ -0,0 +1,27 @@ +"""The configs Inductor's pointwise and reduction heuristics hand a generated npu kernel: the candidate tiles +codegen put in inductor_meta (tiling.candidate_blocks), largest first; registered for npu in registration.py.""" + +from torch._inductor.heuristics.registry import CodegenConfigHeuristics + +CANDIDATES_KEY = "pytorchsim_candidates" + + +def _configs(inductor_meta): + """One triton.Config per candidate tile of the kernel, in the order codegen stated them.""" + import triton + + return [triton.Config(dict(c), num_warps=1, num_stages=1) for c in inductor_meta[CANDIDATES_KEY]] + + +class NPUPointwiseConfigs(CodegenConfigHeuristics): + def get_configs(self, size_hints, bs, triton_config, hinted_configs, tile_hint=None, + inductor_meta=None): + return _configs(inductor_meta) + + +class NPUReductionConfigs(CodegenConfigHeuristics): + def get_configs(self, size_hints, inductor_meta, triton_meta, num_dynamic=0): + return _configs(inductor_meta) + + def get_persistent_configs(self, size_hints, reduction_hint, inductor_meta, triton_meta): + return _configs(inductor_meta) diff --git a/pytorchsim/frontend/inductor/autotune/template_kernel_configs.py b/pytorchsim/frontend/inductor/autotune/template_kernel_configs.py index ee1f4055..38d969f1 100644 --- a/pytorchsim/frontend/inductor/autotune/template_kernel_configs.py +++ b/pytorchsim/frontend/inductor/autotune/template_kernel_configs.py @@ -8,6 +8,7 @@ from pytorchsim import config from pytorchsim.frontend import tiling +from pytorchsim.frontend.inductor.autotune import template_kernel_spec from pytorchsim.frontend.inductor import is_lowering_npu logger = config.setup_logger() @@ -32,6 +33,26 @@ def mm_config_heuristics(): class NPUMMTemplateConfigHeuristic(MMTemplateConfigMixin, BaseConfigHeuristic): bias = False + def _offered_tiles(self, m, n, k, dtype_size): + """The tiles one mm is offered, best first: the first codegen_autotune_template_topk of gemm_tiles + where the strategy autotunes, else tiling.GEMM_CANDIDATES of them, each compiled until one fits.""" + from pytorchsim.backend import template_record + limit = config.codegen_autotune_template_topk if template_record.autotunes() \ + else tiling.GEMM_CANDIDATES + return tiling.gemm_tiles(m, n, k, dtype_size, bias=self.bias)[:limit] + + def get_extra_kwargs(self, kernel_inputs, op_name): + """The mm kwargs and the spec its choices compile with (template_kernel_spec).""" + from torch._inductor.virtualized import V + kwargs = super().get_extra_kwargs(kernel_inputs, op_name) + mnk = [int(V.graph.sizevars.optimization_hint(s)) for s in kernel_inputs.mnk_symbolic()] + tiles = [(t.block_m, t.block_n) for t in + self._offered_tiles(*mnk, kernel_inputs.dtype().itemsize)] + if not tiles: + return kwargs + grids = [template_kernel_spec.mm_grid(kernel_inputs, t) for t in tiles] + return {**kwargs, "triton_meta": template_kernel_spec.triton_meta_for(kernel_inputs, grids)} + def _get_config_generator(self): """Configs for one m, n, k: the first codegen_autotune_template_topk of gemm_tiles (the first alone unless the strategy autotunes), or the generic set when none is a legal block.""" @@ -47,9 +68,7 @@ def configs(m, n, k, **kwargs): "Triton block; falling back to the generic set", *mnk) yield from generic(m, n, k, **kwargs) return - from pytorchsim.backend import template_record - topk = config.codegen_autotune_template_topk if template_record.autotunes() else 1 - yield from self._finalize_mm_configs(mapped[:topk]) + yield from self._finalize_mm_configs(self._offered_tiles(*mnk, kwargs.get("dtype_size", 4))) return configs @@ -72,6 +91,10 @@ class NPUResidentMMConfigHeuristic(TemplateConfigHeuristics): def _get_template_configs_impl(self, kernel_inputs, op_name): yield from mm_resident.configs(kernel_inputs) + def get_extra_kwargs(self, kernel_inputs, op_name): + """The spec the resident mm compiles with: one program over the whole output.""" + return {"triton_meta": template_kernel_spec.triton_meta_for(kernel_inputs, [(1, 1, 1)])} + class NPUResidentAddmmConfigHeuristic(AddMMConfigMixin, NPUResidentMMConfigHeuristic): pass @@ -103,7 +126,7 @@ def __init__(self): def get_conv_configs(self): def per_group(m, n, k, **kwargs): """Every tile a timed run ranks, the first alone otherwise: one candidate is picked by the - order it was offered, which is no ranking (template_timing.time_choices ranks the rest).""" + order it was offered, which is no ranking (the benchmarker ranks the rest).""" from torch._inductor.virtualized import V from pytorchsim.backend import template_record groups = conv_groups_now() diff --git a/pytorchsim/frontend/inductor/autotune/template_kernel_selection.py b/pytorchsim/frontend/inductor/autotune/template_kernel_selection.py index 1536c138..9548877f 100644 --- a/pytorchsim/frontend/inductor/autotune/template_kernel_selection.py +++ b/pytorchsim/frontend/inductor/autotune/template_kernel_selection.py @@ -1,6 +1,7 @@ -"""How a template's config is picked for npu: TOGSim cycles in timing mode (backend/template_timing.py), the -offered order otherwise, a recorded pick when there is one (through Inductor's recording hooks). Inductor has -no hook for timing a choice, so four AlgorithmSelectorCache methods are replaced, each Inductor's off npu.""" +"""How a template's config is picked for npu: Inductor's own selection over the choices that compiled, the npu's +benchmarker (backend/config_pick.py) ranking them by TOGSim cycles in timing mode and in offered order otherwise; +a recorded pick is the only choice (Inductor's recording hooks). Inductor has no hook for an unread operand or +for fusing only choices timed in cycles, so three AlgorithmSelectorCache methods are wrapped, each Inductor's off npu.""" import torch @@ -9,19 +10,17 @@ def install(): - """Patch algorithm selection for npu choices: cycles from TOGSim in timing mode, the offered - order otherwise; no precompile; allocate-only examples. A recorded pick is the only choice, - and a timed one is recorded.""" + """Patch algorithm selection for npu choices: allocate-only examples; no multi-template buffer unless timed. + A recorded pick is the only choice, and a timed one is recorded.""" from torch._inductor import config as inductor_config from torch._inductor import select_algorithm - from torch._inductor.select_algorithm import AlgorithmSelectorCache + from torch._inductor.select_algorithm import AlgorithmSelectorCache, NoValidChoicesError from pytorchsim.backend import template_timing from pytorchsim.backend import template_record orig_benchmark = AlgorithmSelectorCache.__dict__["benchmark_choices"].__func__ orig_call = AlgorithmSelectorCache.__call__ - orig_precompile = AlgorithmSelectorCache.make_precompile_fn orig_example = AlgorithmSelectorCache.__dict__["generate_example_value"].__func__ def _choices_are_npu(choices): @@ -35,22 +34,38 @@ def benchmark_choices(cls, choices, autotune_args, is_collective=False): raise RuntimeError( "TORCHSIM_TIMING_MODE changed after pytorchsim was installed: Inductor's " "epilogue-fusion benchmark follows the mode the process started in") - if timed and template_timing.times(choices): - return template_timing.time_choices(choices) if not timed: template_record.warn_untimed_autotune() - return pick_config(choices) + timings = orig_benchmark(cls, choices, autotune_args, is_collective) + if timed and template_timing.times(choices): + for c in choices: + if template_record.is_timed(c): + c.annotations["ktc"].annotations[template_record.SOURCE] = template_record.TIMED + return timings def __call__(self, name, choices, *args, **kwargs): """Inductor's selection; a fusion is benchmarked only for choices timed in cycles.""" if _choices_are_npu(choices) and not template_timing.times(choices): kwargs["return_multi_template"] = False - return orig_call(self, name, choices, *args, **kwargs) + try: + return orig_call(self, name, choices, *args, **kwargs) + except NoValidChoicesError: + _refuse_external(choices) + raise - def make_precompile_fn(self, choices, *args, **kwargs): - if not _choices_are_npu(choices): - return orig_precompile(self, choices, *args, **kwargs) - return lambda: None + def _refuse_external(choices): + """An external mapping's tile is the only candidate: its failure to compile is an error naming the + mapping file and the entry, with why.""" + for c in choices: + ktc = getattr(c, "annotations", {}).get("ktc") + if ktc is None or ktc.annotations.get(template_record.SOURCE) != template_record.EXTERNAL: + continue + m, n, k = ktc.inputs.mnk_hinted() + try: + c.precompile() + except Exception as e: # noqa: BLE001 + raise ValueError(f"{config.codegen_external_mapping_file}: the entry {m}_{n}_{k} -> " + f"{c.description} does not compile on this machine: {e}") from e def generate_example_value(size, stride, device, dtype, extra_size, allocation_size=None): @@ -68,16 +83,7 @@ def generate_example_value(size, stride, device, dtype, extra_size, AlgorithmSelectorCache.benchmark_choices = classmethod(benchmark_choices) AlgorithmSelectorCache.__call__ = __call__ - AlgorithmSelectorCache.make_precompile_fn = make_precompile_fn AlgorithmSelectorCache.generate_example_value = staticmethod( generate_example_value) select_algorithm.add_preprocessing_fn(template_record.keep_recorded) select_algorithm.add_feedback_saver(template_record.record) - - -def pick_config(choices): - """Timings in place of benchmarking: the offered order wins, extern last.""" - from torch._inductor.select_algorithm import ExternKernelCaller - - return {c: (1e3 if isinstance(c, ExternKernelCaller) else 1.0) + i * 1e-3 - for i, c in enumerate(choices)} diff --git a/pytorchsim/frontend/inductor/autotune/template_kernel_spec.py b/pytorchsim/frontend/inductor/autotune/template_kernel_spec.py new file mode 100644 index 00000000..1badae1e --- /dev/null +++ b/pytorchsim/frontend/inductor/autotune/template_kernel_spec.py @@ -0,0 +1,36 @@ +"""The spec a template choice is compiled with before its source exists: what its heuristic knows from the kernel's +inputs alone (each tensor's role and span, in the order the template's signature takes them, and the largest grid +of the tiles it offers). It reaches the choice's triton_meta through the heuristic's get_extra_kwargs.""" + +import json + +from torch._inductor.virtualized import V + +from pytorchsim.backend import compiler_input +from pytorchsim.contract import storage_span + + +def triton_meta_for(kernel_inputs, grids): + """The triton_meta kwarg for a mm-family choice: nodes in signature order (an addmm's bias first), then the + output; `grids` the (x, y, z) of each tile it is offered, the spec stating the one with the most programs.""" + tensors = [("in", _span(n.get_layout())) for n in kernel_inputs.nodes()] + tensors.append(("out", _span(kernel_inputs.output_layout()))) + grid = [max(g[i] for g in grids) for i in range(3)] + spec = compiler_input.spec_dict(tensors, grid, axes=("z", "y", "x")) + return {"backend_options": compiler_input.backend_options(json.dumps(spec))} + + +def mm_grid(kernel_inputs, tile): + """The mm or bmm launch grid of `tile` (block_m, block_n, ...): programs over output tiles, batches on y.""" + m, n, _ = (int(V.graph.sizevars.optimization_hint(s)) for s in kernel_inputs.mnk_symbolic()) + batch = kernel_inputs.nodes()[-1].get_size() + batches = int(V.graph.sizevars.optimization_hint(batch[0])) if len(batch) == 3 else 1 + return (-(-m // tile[0]) * -(-n // tile[1]), batches, 1) + + +def _span(layout): + hint = V.graph.sizevars.optimization_hint + size = [int(hint(s)) for s in layout.size] + if any(s <= 0 for s in size): + return 0 + return storage_span(size, [int(hint(s)) for s in layout.stride], int(hint(layout.offset))) diff --git a/pytorchsim/frontend/inductor/codegen/__init__.py b/pytorchsim/frontend/inductor/codegen/__init__.py index e3953a1e..bcae2aa9 100644 --- a/pytorchsim/frontend/inductor/codegen/__init__.py +++ b/pytorchsim/frontend/inductor/codegen/__init__.py @@ -2,8 +2,8 @@ Inductor -> TritonNPUScheduling.define_kernel (scheduling.py; the wrapper module: wrapper.py, a model's own Triton kernels: user_kernel.py) - -> torchsim_compile (backend/codecache.py, backend/compiler_input.py) - -> pytorchsim-triton-compiler, in a subprocess (backend/compiler_bridge.py) + -> async_compile.triton, through the PTB Triton backend (spec: backend/compiler_input.py) + -> backend/launcher.py (driver.set_launcher) -> Spike (simulator/functional/__init__.py) / TOGSim (simulator/timing/__init__.py) Registered for `npu` by frontend/inductor/registration.py. diff --git a/pytorchsim/frontend/inductor/codegen/kernel_metadata.py b/pytorchsim/frontend/inductor/codegen/kernel_metadata.py index 59faed28..84c2925c 100644 --- a/pytorchsim/frontend/inductor/codegen/kernel_metadata.py +++ b/pytorchsim/frontend/inductor/codegen/kernel_metadata.py @@ -6,7 +6,7 @@ from torch._inductor.virtualized import V from pytorchsim.frontend import tiling -from pytorchsim.frontend.inductor.autotune.generated_kernel_blocks import blocks_for +from pytorchsim.frontend.inductor.autotune.generated_kernel_blocks import blocks_for, candidates_for from pytorchsim import config from pytorchsim.contract import SpecIncomplete, storage_span @@ -121,18 +121,29 @@ def _held_blocks(kernel): def _blocks_without_pin(kernel, numels, args): - """Blocks for a kernel holding none: a TritonNPUKernel's from blocks_for, the answer pinning - gives; a template's from its numels and args alone.""" + """Blocks for a kernel holding none: a TritonNPUKernel's smallest candidate tile, the one that + launches the most programs (the grid its spec states bounds every candidate's); a template's from + its numels and args alone.""" from pytorchsim.frontend.inductor.codegen.scheduling import TritonNPUKernel if isinstance(kernel, TritonNPUKernel) and all(isinstance(v, int) for v in numels.values()): - return blocks_for(numels, kernel.features) + tiles = candidates_for(kernel.numels, kernel.features) + tile = tiles[-1] if tiles else blocks_for(numels, kernel.features) + return {**tile, "XBLOCK": 1} if kernel.no_x_dim else tile return tiling.fixed_config_for(kernel, numels, args) -def compile_call(src_code, meta, kernel_name): - """The wrapper's line compiling one kernel, torchsim_compile(source, meta=..., kernel_name=...): - the source as a Python literal, so a quote or backslash in it reaches the compiler as written.""" - return f"torchsim_compile({src_code!r},\n meta={meta!r},\n kernel_name={kernel_name!r})" +def apply_spec_to_source(src_code, kernel, meta): + """The one text edit of Inductor's source: `kernel`'s triton_meta, as the decorator holds it, gains the spec of + `meta` as backend_options. No hook can do it: triton_meta_common runs before the signature the spec needs + exists, and a template's decorator reads its triton_meta after its epilogue is fused, at render time.""" + from pytorchsim.backend import compiler_input + old = repr(kernel.triton_meta) + if src_code.count(f"triton_meta={old}") != 1: + raise SpecIncomplete(f"{kernel.__class__.__name__}: triton_meta is not in the source once; " + f"Inductor's decorator changed") + options = compiler_input.backend_options(compiler_input.spec_json(meta)) + new = repr({**kernel.triton_meta, "backend_options": options}) + return src_code.replace(f"triton_meta={old}", f"triton_meta={new}") def collect_meta(kernel, kernel_name): diff --git a/pytorchsim/frontend/inductor/codegen/scheduling.py b/pytorchsim/frontend/inductor/codegen/scheduling.py index 4358d162..0b313dbb 100644 --- a/pytorchsim/frontend/inductor/codegen/scheduling.py +++ b/pytorchsim/frontend/inductor/codegen/scheduling.py @@ -1,33 +1,60 @@ -"""npu's Inductor scheduling: Triton's, emitting a torchsim_compile call for each kernel's source into -the wrapper, and timing on TOGSim the modules Inductor's epilogue-fusion benchmark writes.""" +"""npu's Inductor scheduling: Triton's, each kernel's source carrying its spec to PTB's Triton backend, and the +modules Inductor's epilogue-fusion benchmark writes timed on TOGSim.""" from torch._inductor.codecache import PyCodeCache, get_hash from torch._inductor.codegen.common import BackendFeature from torch._inductor.codegen.triton import TritonKernel, TritonScheduling +from torch._inductor.ir import MultiTemplateBuffer +from torch._inductor.select_algorithm import TritonTemplateKernel from torch._inductor.utils import Placeholder, get_fused_kernel_name from torch._inductor.virtualized import V from pytorchsim import config -from pytorchsim.frontend.inductor.autotune import graph_prefetch +from pytorchsim.backend import compiler_input +from pytorchsim.frontend.inductor.autotune import generated_kernel_blocks, graph_prefetch +from pytorchsim.frontend.inductor.autotune.generated_kernel_configs import CANDIDATES_KEY from pytorchsim.frontend.inductor.codegen import kernel_metadata _logger = config.setup_logger() class TritonNPUKernel(TritonKernel): - """A TritonKernel launched as a plain call: upstream emits `kernel.run(..., grid=..., stream=...)`, - resolved at runtime. Its blocks are fixed when it is made (NPUChoices.triton_kernel_kwargs).""" - - def call_kernel(self, name: str, node=None, **kwargs): - wrapper = V.graph.wrapper_code - _, call_args, _, arg_types = self.args.python_argdefs() - self.add_numel_to_call_args(name, call_args, arg_types) - wrapper.generate_kernel_call(name, call_args, triton=True) + """A TritonKernel whose heuristics' configs are this machine's candidate tiles (inductor_meta) and whose + compile options carry its spec: the source is Inductor's own, autotune-ready, and each config that + overflows the scratchpad is dropped when it is compiled.""" + + def inductor_meta_per_kernel(self): + out = super().inductor_meta_per_kernel() + out[CANDIDATES_KEY] = self._get_candidates() + return out + + def _get_candidates(self): + """The candidate tiles, as dicts over the blocks this kernel takes as arguments, none twice.""" + taken = {f"{t.prefix.upper()}BLOCK" for t in self.range_trees + if t.tensor_dim is not None and not (t.is_reduction and self.persistent_reduction)} + out = [] + for tile in generated_kernel_blocks.candidates_for(self.numels, self.features): + tile = {k: v for k, v in tile.items() if k in taken} + if self.no_x_dim: + tile.pop("XBLOCK", None) + if tile not in out: + out.append(tile) + return out or [{}] + + def codegen_kernel(self, name=None): + """Inductor's source with the kernel's spec in its triton_meta (kernel_metadata.apply_spec_to_source).""" + src = super().codegen_kernel(name) + if name is not None: + return src + meta = kernel_metadata.collect_meta(self, str(Placeholder.KERNEL_NAME)) + meta["graph_prefetch"] = graph_prefetch.statement(self, meta["args"]) + self._npu_meta = meta + return kernel_metadata.apply_spec_to_source(src, self, meta) class TritonNPUScheduling(TritonScheduling): - """Triton's scheduling, emitting torchsim_compile calls, and timing on TOGSim the modules - Inductor's epilogue-fusion benchmark writes.""" + """Triton's scheduling over TritonNPUKernel, and the modules Inductor's epilogue-fusion benchmark writes + timed on TOGSim.""" kernel_type = TritonNPUKernel def __init__(self, scheduler): @@ -56,17 +83,47 @@ def generate_kernel_code_from_nodes(self, nodes, benchmark_kernel=False, hint_ov **kwargs): """The source Inductor benchmarks a fusion with, without its harness, and its metadata read as define_kernel reads it (the operand it holds too), kept for benchmark_codegened_module by the path - the source loads from.""" + the source loads from. A template's source takes its spec here, as define_kernel gives it.""" src_code = super().generate_kernel_code_from_nodes(nodes, False, hint_override, **kwargs) - meta = kernel_metadata.collect_meta(self._codegen_kernel, "triton_") - meta["graph_prefetch"] = graph_prefetch.statement(self._codegen_kernel, meta["args"]) - self._benchmarked[PyCodeCache.write(src_code)[1]] = (src_code, meta) - return src_code + kernel = self._codegen_kernel + meta = kernel_metadata.collect_meta(kernel, "triton_") + meta["graph_prefetch"] = graph_prefetch.statement(kernel, meta["args"]) + loaded = kernel_metadata.apply_spec_to_source(src_code, kernel, meta) \ + if isinstance(kernel, TritonTemplateKernel) else src_code + self._benchmarked[PyCodeCache.write(loaded)[1]] = (src_code, meta) + return loaded + + def can_fuse_vertical(self, node1, node2): + """Inductor's answer, and for a template fused with an epilogue or prologue, whether the fused + kernel compiles: the choice was picked for the template alone, and a fusion adds tiles to its + scratchpad (OutOfResources). A template still holding its timed choices is fused by benchmark.""" + if not super().can_fuse_vertical(node1, node2): + return False + if not (node1.is_template() or node2.is_template()): + return True + if any(isinstance(n.node, MultiTemplateBuffer) for n in (node1, node2) if n.is_template()): + return True + return self._compiles([*node1.get_nodes(), *node2.get_nodes()]) + + def _compiles(self, nodes): + """Whether the kernel fusing `nodes` compiles through the Triton backend with a config that fits.""" + from torch._inductor.runtime.triton_heuristics import NoTritonConfigsError + from triton.runtime.errors import OutOfResources + + with V.graph.set_current_device(nodes[0].get_device()): + mod = PyCodeCache.load(self.generate_kernel_code_from_nodes(nodes)) + try: + mod.triton_.precompile() + except (NoTritonConfigsError, OutOfResources) as e: + _logger.info("[torchsim-compile] %s: not fused, its kernel does not fit: %s", + [n.get_name() for n in nodes], e) + return False + return True def benchmark_codegened_module(self, mod, n_spills_threshold=8, node_names=None, skip_perf_cache=False): """(TOGSim cycles, path) of a module generate_kernel_code_from_nodes wrote: Inductor - compares these with the cycles template_timing.time_choices gave the unfused choices.""" + compares these with the cycles the benchmarker gave the unfused choices.""" from pytorchsim.backend import template_timing got = self._benchmarked.get(mod.__file__) @@ -77,37 +134,17 @@ def benchmark_codegened_module(self, mod, n_spills_threshold=8, node_names=None, return template_timing.time_module(*got, mod.__file__), mod.__file__ def define_kernel(self, src_code, node_schedule, kernel): - """Name the kernel by its source, capture its metadata and what it holds, and emit our compile call. - - The name is resolved into the source here, because the compiler side parses it. - """ - wrapper = V.graph.wrapper_code - if src_code in wrapper.src_to_kernel: - return wrapper.src_to_kernel[src_code] - - fused_name = get_fused_kernel_name(node_schedule, "original_aten") - kernel_name = "_".join( - x for x in ("pytorchsim_triton_compiler", fused_name, get_hash(src_code.strip())[1:9]) if x - ) - wrapper.src_to_kernel[src_code] = kernel_name - - src_code = src_code.replace(str(Placeholder.DESCRIPTIVE_NAME), kernel_name) - src_code = src_code.replace(str(Placeholder.KERNEL_NAME), kernel_name) - - meta = kernel_metadata.collect_meta(kernel, kernel_name) - meta["graph_prefetch"] = graph_prefetch.statement(kernel, meta["args"]) - meta["aten_ops"] = kernel_metadata.aten_ops(node_schedule) - kernel_metadata.record_roles(kernel_name, meta) - source = _tile_source(node_schedule) - if source is not None: - meta["tile_source"] = source - - origins = ", ".join( - sorted({str(o) for n in node_schedule - for o in getattr(getattr(n, "node", None), "origins", ()) or ()}) - ) - wrapper.define_kernel(kernel_name, kernel_metadata.compile_call(src_code, meta, kernel_name), - f"# origins: {origins}") + """Inductor's own: the kernel is an async_compile.triton call, compiled through the Triton backend; a + template's source takes the spec of its final form first, and the roles of the arguments are kept by + the kernel's name for the launch hooks.""" + meta = getattr(kernel, "_npu_meta", None) + if isinstance(kernel, TritonTemplateKernel): + meta = kernel_metadata.collect_meta(kernel, "") + meta["graph_prefetch"] = graph_prefetch.statement(kernel, meta["args"]) + src_code = kernel_metadata.apply_spec_to_source(src_code, kernel, meta) + kernel_name = super().define_kernel(src_code, node_schedule, kernel) + if meta is not None: + kernel_metadata.record_roles(kernel_name, meta) return kernel_name diff --git a/pytorchsim/frontend/inductor/codegen/user_kernel.py b/pytorchsim/frontend/inductor/codegen/user_kernel.py index 4e9f3125..453197a0 100644 --- a/pytorchsim/frontend/inductor/codegen/user_kernel.py +++ b/pytorchsim/frontend/inductor/codegen/user_kernel.py @@ -1,98 +1,35 @@ -"""A Triton kernel a model registers itself (torch.library.triton_op, wrap_triton) on npu: its spec -meta per launch and its torchsim_compile call, its source the kernel's own and its jit helpers'.""" +"""A Triton kernel a model registers itself (torch.library.triton_op, wrap_triton) on npu: the spec of each +launch, which Inductor's own async_compile.triton call carries to the Triton backend.""" -import dis -import types - -from torch._inductor.codegen.common import IndentedBuffer from torch._inductor.virtualized import V from pytorchsim import config -from pytorchsim.frontend.inductor.autotune import graph_prefetch -from pytorchsim.frontend.inductor.codegen import kernel_metadata _logger = config.setup_logger() -def user_kernel_compile(kernel, meta): - """The torchsim_compile call for a user-defined Triton kernel, with no source text read back: - the source is the kernel's own and its jit helpers' (Inductor's transitive closure), written - as it is (meta["user_defined"] keeps the Inductor-source rewriters off it).""" - from torch._inductor.codegen.wrapper import ( - user_defined_triton_kernel_transitive_closure_source_code) - - src = IndentedBuffer() - src.splice(""" - import triton - import triton.language as tl - """, strip=True) - for line in _extra_imports(kernel): - src.writeline(line) - src.writeline("@triton.jit") - src.splice(user_defined_triton_kernel_transitive_closure_source_code(kernel), strip=True) - return kernel_metadata.compile_call(src.getvalue(), meta, kernel.__name__) - - -def _extra_imports(kernel): - """An import of each Triton module other than triton and tl that the kernel or a jit helper it calls - reads as a global, under that name (`pytorchsim` for triton.language.extra.pytorchsim), found as - triton finds the kernel's unqualified loads; Inductor's closure imports a module global by __module__.""" - from triton.runtime.jit import JITFunction - - lines, seen, todo = [], set(), [kernel] - while todo: - fn = getattr(todo.pop(), "fn", None) - if fn is None or id(fn) in seen: - continue - seen.add(id(fn)) - for name in {i.argval for i in dis.Bytecode(fn) if i.opname == "LOAD_GLOBAL"}: - value = fn.__globals__.get(name) - if (isinstance(value, types.ModuleType) and name not in ("triton", "tl") - and value.__name__.split(".")[0] == "triton"): - line = f"import {value.__name__} as {name}" - if line not in lines: - lines.append(line) - elif isinstance(value, JITFunction): - todo.append(value) - return sorted(lines) - - -def user_kernel_meta(kernel, kwargs, triton_meta, grid): - """The spec meta of one launch of a user-defined Triton kernel: signature and constants from - Inductor's triton_meta, each pointer's dtype and span from its IR argument, and its role inout - where torch's mutation analysis says the launch writes it (every pointer, without that analysis).""" +def user_kernel_spec(kernel, kwargs, grids): + """The spec JSON of one launch of a user-defined Triton kernel: each tensor argument (kernel parameter + order) by role, where torch's mutation analysis says the launch writes it (every pointer without that + analysis), and storage span; the grid of the config with the most programs per axis.""" + import json + from torch._inductor import ir + from pytorchsim.backend import compiler_input from pytorchsim.contract import storage_span - from pytorchsim.backend.launch_hooks import user_kernel_id hint = V.graph.sizevars.optimization_hint - signature = {str(k): str(v) for k, v in triton_meta["signature"].items()} writes = _user_kernel_writes(kwargs) - args, call_params = [], [] - for arg, token in signature.items(): - if token == "constexpr": - continue - call_params.append(arg) - if not token.startswith("*"): + tensors = [] + for p in kernel.params: + arg = kwargs.get(p.name) + if not isinstance(arg, (ir.Buffer, ir.ReinterpretView)): continue - node = kwargs[arg] - layout = node.get_layout() - args.append({ - "name": arg, - "role": "inout" if writes is None or arg in writes else "in", - "buffer": node.get_name(), - "dtype": kernel_metadata.TOKEN_DTYPE[token], - "numel": storage_span([int(hint(s)) for s in layout.size], - [int(hint(s)) for s in layout.stride]), - }) - return { - "kernel_name": kernel.__name__, "signature": signature, - "constants": dict(triton_meta.get("constants") or {}), - "args": args, "call_params": call_params, "numels": {}, - "inside_reduction": False, "fixed_config": {}, - "template_grid": ([int(hint(g)) for g in grid] + [1, 1, 1])[:3], - "user_defined": True, "user_kernel": user_kernel_id(kernel), - "graph_prefetch": graph_prefetch.statement(kernel, args), - } + layout = arg.get_layout() + tensors.append(("inout" if writes is None or p.name in writes else "in", + storage_span([int(hint(s)) for s in layout.size], + [int(hint(s)) for s in layout.stride]))) + extents = [max(([int(hint(g)) for g in grid] + [1, 1, 1])[i] for grid in grids) for i in range(3)] + return json.dumps(compiler_input.spec_dict(tensors, extents, axes=("z", "y", "x"))) def _user_kernel_writes(kwargs): diff --git a/pytorchsim/frontend/inductor/codegen/wrapper.py b/pytorchsim/frontend/inductor/codegen/wrapper.py index f6dc6ed9..ec4563bc 100644 --- a/pytorchsim/frontend/inductor/codegen/wrapper.py +++ b/pytorchsim/frontend/inductor/codegen/wrapper.py @@ -1,28 +1,21 @@ """npu's Inductor wrapper: the Python module Inductor generates per graph, its kernels compiled by -torchsim_compile and called as plain functions, each extern call noted, and (verify on) a CPU +Inductor's async_compile.triton, each extern call noted, and (verify on) a CPU cross-check after each buffer's last writer.""" -import contextlib +import json from typing import Optional from torch._inductor.codegen import wrapper from torch._inductor.ir import GraphPartitionSignature, IRNode from torch._inductor.virtualized import V +from pytorchsim.backend import compiler_input, launch_hooks from pytorchsim.frontend.inductor.codegen import kernel_metadata, verify -from pytorchsim.frontend.inductor.codegen.user_kernel import user_kernel_compile, user_kernel_meta +from pytorchsim.frontend.inductor.codegen.user_kernel import user_kernel_spec class TritonNPUWrapperCodegen(verify.VerifyLines, wrapper.PythonWrapperCodegen): - """The npu wrapper: kernels are compiled by torchsim_compile and called as plain functions.""" - - def __init__(self): - """A model's own Triton kernels: the kernels define_kernel is collecting for the one being - defined (None between), Inductor's metadata line of each, the name of each launch variant.""" - self._npu_user_kernel = None - self._npu_user_notes = {} - self._npu_user_variants = {} - super().__init__() + """The npu wrapper: Inductor's, with a note before each extern call and the verify lines.""" @classmethod def create( @@ -40,14 +33,13 @@ def create( return cls() def write_header(self): - """Inductor's own header, then the names the npu wrapper adds: torchsim_compile, verify, the log line.""" + """Inductor's own header, then the names the npu wrapper adds: the launch notes, verify, the log line.""" super().write_header() self.header.splice( f""" from pytorchsim.config import setup_logger from pytorchsim.frontend.inductor.codegen import verify as _fverify - from pytorchsim.backend.codecache import torchsim_compile - from pytorchsim.backend.launch_hooks import torchsim_extern + from pytorchsim.backend.launch_hooks import torchsim_call, torchsim_extern _logger = setup_logger("pytorchsim.frontend.inductor.codegen.generated_wrapper") _logger.info(f'Wrapper Codegen Path = {{__file__}}') @@ -60,6 +52,13 @@ def note_extern(self, op, python_kernel_name): call = python_kernel_name if op is None else str(op) self.writeline(f"torchsim_extern({call!r})") + def generate_kernel_call(self, kernel_name, call_args, *, triton=True, raw_args=None, **kwargs): + """Before a Triton kernel's call, a torchsim_call line naming the buffer each argument is, which its + launch records in launch.json.""" + if triton: + self.writeline(f"torchsim_call({_get_arg_names(call_args, raw_args)!r})") + super().generate_kernel_call(kernel_name, call_args, triton=triton, raw_args=raw_args, **kwargs) + def generate_extern_kernel_out(self, node): self.note_extern(node.op_overload, node.python_kernel_name) super().generate_extern_kernel_out(node) @@ -104,61 +103,20 @@ def write_args(self, input_names): def define_user_defined_triton_kernel(self, kernel, configs, kwargs, restore_value_args, reset_to_zero_args, grids, epilogue_fusion, launch_kwargs): - """A Triton kernel a model registers (triton_op, wrap_triton) is compiled by torchsim_compile like - Inductor's own, not as the GPU's async_compile.triton; a launch whose spans or grid differ gets a - name and compile call of its own, as the spec bakes them in.""" - if len(grids) != 1 or configs: - raise NotImplementedError( - f"{kernel.__name__}: a user-defined Triton kernel autotuned over configs; the npu " - f"launches one grid fixed at codegen") + """A Triton kernel a model registers (triton_op, wrap_triton) is Inductor's own async_compile.triton + call; this launch's spec joins its launch kwargs, which Inductor turns into the kernel's backend_options, + and its arguments' roles are kept by the kernel's name for the launch hooks.""" if epilogue_fusion is not None: raise NotImplementedError( f"{kernel.__name__}: an epilogue fused into a user-defined Triton kernel") - self._npu_user_kernel = [] - try: - name, triton_meta, inductor_meta, extra = super().define_user_defined_triton_kernel( - kernel, configs, kwargs, restore_value_args, reset_to_zero_args, grids, - epilogue_fusion, launch_kwargs) - defined = self._npu_user_kernel - finally: - self._npu_user_kernel = None - notes = self._npu_user_notes - for _, metadata in defined: - notes[name] = metadata - meta = user_kernel_meta(kernel, kwargs, triton_meta, grids[0]) - variants = self._npu_user_variants - key = (name, repr(meta)) - if key not in variants: - count = sum(1 for n, _ in variants if n == name) - variants[key] = name if count == 0 else f"{name}_npu{count}" - kernel_metadata.record_roles(variants[key], meta) - super().define_kernel(variants[key], user_kernel_compile(kernel, meta), notes[name]) - return variants[key], triton_meta, inductor_meta, extra - - def define_kernel(self, kernel_name, kernel_body, metadata=None, gpu=True, - cpp_definition=None): - """Inductor's own, except the async_compile.triton of the user-defined Triton kernel - being defined, which define_user_defined_triton_kernel replaces.""" - if self._npu_user_kernel is not None: - self._npu_user_kernel.append((kernel_name, metadata)) - return None - return super().define_kernel(kernel_name, kernel_body, metadata, gpu, cpp_definition) - - def _generate_kernel_call_helper(self, kernel_name, call_args, *, device=None, triton=True, - **kwargs): - """An npu kernel call is a plain function call with Triton's argument rendering, a 0-d input - unwrapped for the kernel's device; grid, stream and autotune do not apply. A C++ kernel keeps - Inductor's own call.""" - if triton: - names = _get_arg_names(call_args, kwargs.get("raw_args")) - with (V.graph.set_current_device(device) if device is not None - else contextlib.nullcontext()): - call_args = self.prepare_triton_kernel_call(call_args) - call_args = [*call_args, f"torchsim_arg_names={names!r}"] - else: - call_args = [a if isinstance(a, str) else str(a) if isinstance(a, (int, float, bool)) - else wrapper.pexpr(V.graph.sizevars.simplify(a)) for a in call_args] - self.writeline(self.wrap_kernel_call(kernel_name, call_args)) + spec = user_kernel_spec(kernel, kwargs, grids) + options = compiler_input.backend_options(spec) + got = super().define_user_defined_triton_kernel( + kernel, configs, {**kwargs, **options}, restore_value_args, reset_to_zero_args, grids, + epilogue_fusion, [*launch_kwargs, *options]) + launch_hooks.name_user_kernel(kernel.__name__, kernel) + kernel_metadata.record_roles(got[0] if isinstance(got, tuple) else kernel.__name__, json.loads(spec)) + return got def run_wrapper_ir_passes(self, is_inference): """Inductor's passes, then (per-kernel verify on) a check line after each buffer's last writer.""" diff --git a/pytorchsim/frontend/inductor/registration.py b/pytorchsim/frontend/inductor/registration.py index 68da80d3..a2eb3949 100644 --- a/pytorchsim/frontend/inductor/registration.py +++ b/pytorchsim/frontend/inductor/registration.py @@ -8,6 +8,9 @@ device op overrides NPUDeviceOpOverrides: the device code in a wrapper Inductor's choices class NPUChoices, answered by autotune/ template heuristics the mm/bmm configs and the resident mm's, autotune/'s + codegen heuristics the configs of a generated pointwise or reduction kernel, autotune/'s + PTB's Triton driver the runner a launch goes to: Spike and TOGSim + Inductor's benchmarker what picks one of a kernel's compiled configs """ import functools @@ -33,6 +36,9 @@ def install(): _register_device_op_overrides() _register_choices() _register_template_heuristics() + _register_codegen_heuristics() + _register_launcher() + _register_benchmarker() # Dynamo's device interfaces (torch._dynamo.device_interface) @@ -69,9 +75,51 @@ def get_device_properties(device: torch.types.Device = None) -> NPUDevicePropert """One set for every npu device: the simulated machine's.""" return NPUDeviceProperties() + class device: + """`with interface.device(index):` -- the one npu device, so nothing is switched.""" + + def __init__(self, device): + self.idx = device + + def __enter__(self): + return self.idx + + def __exit__(self, *exc): + return False + + @staticmethod + def current_device() -> int: + return torch.npu.current_device() + + @staticmethod + def set_device(device: torch.types.Device) -> None: + torch.npu.set_device(device) + + @staticmethod + def exchange_device(device: int) -> int: + """The device a kernel loads on is the one device: nothing to switch, the previous is the same.""" + return torch.npu.current_device() + + @staticmethod + def maybe_exchange_device(device: int) -> int: + return torch.npu.current_device() + + @staticmethod + def device_count() -> int: + return 1 + + @staticmethod + def get_raw_stream(device_idx: int) -> int: + """The npu has no stream a kernel is launched on: 0, as the wrapper's get_raw_stream says.""" + return 0 + + @staticmethod + def synchronize(device: torch.types.Device = None) -> None: + pass + @staticmethod def get_compute_capability(device: torch.types.Device = None) -> int: - """None of CUDA's; Triton's compile metadata carries it, and torchsim_compile ignores it.""" + """None of CUDA's; Triton's compile metadata carries it, and PTB's backend ignores it.""" return 0 @staticmethod @@ -292,15 +340,6 @@ def _create_lookup_choices(self, *args, **kwargs): ktc.annotations[template_record.SOURCE] = template_record.RECORDED return ktcs - def triton_kernel_kwargs(self, kernel_cls, features, groups, kernel_kwargs): - """This machine's blocks pinned into every npu kernel Inductor generates (Inductor's - hook for a fixed config): the one it emits and the one its fusion benchmark times are - made the same way, so they are the same kernel.""" - kwargs = super().triton_kernel_kwargs(kernel_cls, features, groups, kernel_kwargs) - if is_lowering_npu() and kwargs.get("fixed_config") is None: - kwargs["fixed_config"] = generated_kernel_blocks.pinned_blocks(groups[0], features) - return kwargs - @staticmethod def should_use_persistent_reduction(features, cooperative_reduction): return generated_kernel_blocks.use_persistent_reduction( @@ -342,3 +381,35 @@ def _register_template_heuristics(): resident, resident_addmm = mm_resident_config_heuristic() register_template_heuristic(mm_resident.mm_resident_template.uid, "npu", op_name="mm")(resident) register_template_heuristic(mm_resident.mm_resident_template.uid, "npu", op_name="addmm")(resident_addmm) + + +# Inductor's codegen heuristics (torch._inductor.heuristics.registry) + +def _register_codegen_heuristics(): + """Register npu's pointwise and reduction config heuristics.""" + from torch._inductor.heuristics.registry import register_codegen_heuristic + + from pytorchsim.frontend.inductor.autotune import generated_kernel_configs + + register_codegen_heuristic("pointwise", "npu")(generated_kernel_configs.NPUPointwiseConfigs) + register_codegen_heuristic("reduction", "npu")(generated_kernel_configs.NPUReductionConfigs) + + +# PTB's Triton driver (set_launcher) + +def _register_launcher(): + """Register the runner a compiled kernel's launch goes to.""" + from pytorchsim.backend import launcher + + launcher.install() + + +# Inductor's benchmarker (torch._inductor.runtime.benchmarking.register_benchmarker) + +def _register_benchmarker(): + """Register npu's benchmarker: the pick among a kernel's compiled configs.""" + from torch._inductor.runtime.benchmarking import register_benchmarker + + from pytorchsim.backend import config_pick + + register_benchmarker("npu", config_pick.benchmark, override=True) diff --git a/pytorchsim/frontend/tiling.py b/pytorchsim/frontend/tiling.py index 2c06c0bc..08c528fa 100644 --- a/pytorchsim/frontend/tiling.py +++ b/pytorchsim/frontend/tiling.py @@ -1,6 +1,8 @@ """How a kernel is cut into blocks: the sizes pinned at codegen time and the mm tiles this machine takes, decided from the machine and the kernel, since nothing tunes the compiled binary later.""" +import itertools + from pytorchsim import config from pytorchsim.contract import block_name, parallel_axes, reduction_axes @@ -121,6 +123,47 @@ def fixed_config_for(kernel, numels, args, contiguous=None): return cfg +#: How many tiles a kernel offers its compile: each costs a compile of its own, and the first that fits wins. +CANDIDATE_LIMIT = 3 + + +def candidate_blocks(kernel, numels, args, contiguous=None): + """fixed_config_for's tile and the smaller ones after it, each block halved down to 2, largest tile + first (ties to the larger reduction block), at most CANDIDATE_LIMIT: the configs a kernel is offered.""" + cfg = fixed_config_for(kernel, numels, args, contiguous) + movable = [k for k, v in cfg.items() if k.endswith("BLOCK") and v and v >= 2] + ranges = [] + for k in movable: + vs, v = [], cfg[k] + while v >= 2: + vs.append(v) + v //= 2 + ranges.append(vs) + + def product(tile, keep): + n = 1 + for k, v in tile.items(): + if keep(k): + n *= v + return n + + tiles = [dict(zip(movable, vs)) for vs in itertools.product(*ranges)] + tiles.sort(key=lambda t: (-product(t, lambda k: True), -product(t, lambda k: k.startswith("R")), + [-t[k] for k in movable])) + rest = {k: v for k, v in cfg.items() if k.endswith("BLOCK") and v} + return [{**rest, **t} for t in tiles[:CANDIDATE_LIMIT]] + + +def candidate_sizes(first, limit=CANDIDATE_LIMIT): + """The sizes a hand-written kernel's one block is offered: `first` and its halves, largest first, down to 1, + at most `limit`; each is a config its compile may drop when it overflows.""" + sizes = [] + while first >= 1 and len(sizes) < limit: + sizes.append(int(first)) + first //= 2 + return sizes + + def kept_axis_rows_block(xnumel, rblock, elem_bytes, lanes, lane_bytes, max_numel): """XBLOCK of a reduction along its contiguous axis: rows of `rblock` filling the tile budget the other blocks here take (one lane's, times the lanes), at least the lane cover and no more @@ -205,6 +248,10 @@ def kept_axis_contiguous_blocks(xnumel, rnumel, elem_bytes, lanes, lane_bytes, m return best[1], best[2] +#: How many mm tiles a template offers when nothing times them: each is compiled, the first that fits wins. +GEMM_CANDIDATES = 3 + + def gemm_tiles(m, n, k, dtype_size, out_size=None, bias=False): """This machine's mm tiles for [m, k] @ [k, n] as GemmConfigs: per (tile_M, tile_N) the largest tile_K, ordered by gemm_tile_cost. C is held twice when stored at another width than summed at (fp32 halves); an addmm's diff --git a/pytorchsim/simulator/functional/__init__.py b/pytorchsim/simulator/functional/__init__.py index 466a5350..5bae3b1b 100644 --- a/pytorchsim/simulator/functional/__init__.py +++ b/pytorchsim/simulator/functional/__init__.py @@ -36,7 +36,8 @@ def run(workdir, meta, args): for a in manifest["args"]} values = dict(zip(meta.get("call_params", ()), args)) try: - spike.launch(workdir, manifest, runtime, raw_paths, logger.debug, scalar_values=values) + spike.launch(workdir, manifest, runtime, raw_paths, logger.debug, scalar_values=values, + grid=meta.get("launch_grid")) except spike.launcher().SpikeError as e: raise RuntimeError(f"[Spike] {meta['kernel_name']} failed:\n{e}") from None diff --git a/pytorchsim/simulator/functional/spike.py b/pytorchsim/simulator/functional/spike.py index 1d1fc67f..6e80f71d 100644 --- a/pytorchsim/simulator/functional/spike.py +++ b/pytorchsim/simulator/functional/spike.py @@ -5,7 +5,7 @@ from pytorchsim.backend import compiler_bridge -def launch(obj_dir, manifest, runtime, raw_paths, log, scalar_values=None): +def launch(obj_dir, manifest, runtime, raw_paths, log, scalar_values=None, grid=None): """Run the whole launch grid with the compiler's launcher, under the options the object was compiled for, leaving each written argument in its .raw.""" ko = compiler_bridge.compiler_contract("kernel_object") @@ -16,7 +16,7 @@ def launch(obj_dir, manifest, runtime, raw_paths, log, scalar_values=None): raise launcher().SpikeError(str(e)) from None tools = compiler_bridge.toolchain() return launcher().launch(elf, manifest, runtime, raw_paths, run, spike=tools.SPIKE, pk=tools.PK, log=log, - want_jobs=config.CONFIG_SPIKE_JOBS, scalar_values=scalar_values) + want_jobs=config.CONFIG_SPIKE_JOBS, scalar_values=scalar_values, grid=grid) def launcher(): diff --git a/pytorchsim/simulator/timing/__init__.py b/pytorchsim/simulator/timing/__init__.py index 49c90bd1..f656d792 100644 --- a/pytorchsim/simulator/timing/__init__.py +++ b/pytorchsim/simulator/timing/__init__.py @@ -188,6 +188,10 @@ def write_shape(workdir, meta, args=(), into=None): parameter name (a template's trailing arguments are its grid), then the integer scalars in the compiler's order (kernel_object.shape_args).""" numels = dict(meta["numels"]) + if meta.get("launch_extents") is not None: + grid = list(meta["launch_extents"]) + _write_extents(workdir, grid, "launch grid", meta, args, into) + return grid if meta.get("template_grid") is not None: grid = list(contract.launch_extents(meta)) _write_extents(workdir, grid, "template grid", meta, args, into) diff --git a/pytorchsim/simulator/timing/npuwattch.py b/pytorchsim/simulator/timing/npuwattch.py index 9417dc4f..2b16f421 100644 --- a/pytorchsim/simulator/timing/npuwattch.py +++ b/pytorchsim/simulator/timing/npuwattch.py @@ -350,9 +350,8 @@ def _sfu_vector_elems(workdir): def _fused_name(kernel_name): - """What Inductor named the kernel's ops, `pytorchsim_triton_compiler_fused__softmax_` -> - `softmax`, or None.""" - m = re.match(r"pytorchsim_triton_compiler_(?:fused_)?(.+)_[a-z0-9]+$", kernel_name or "") + """What Inductor named the kernel's ops, `triton_per_fused__softmax_0` -> `softmax`, or None.""" + m = re.match(r"triton_[a-z]+_(?:fused_)?(.+)_\d+$", kernel_name or "") return m.group(1).strip("_") or None if m else None diff --git a/tests/ops/attention/test_attention_causal_cycles.py b/tests/ops/attention/test_attention_causal_cycles.py index 5c0ca9dc..60c3c254 100644 --- a/tests/ops/attention/test_attention_causal_cycles.py +++ b/tests/ops/attention/test_attention_causal_cycles.py @@ -12,7 +12,7 @@ import re # noqa: E402 import torch # noqa: E402 the npu backend loads pytorchsim whole, before its parts are imported -from pytorchsim.backend import codecache # noqa: E402,F401 its logger set up before a handler joins it +from pytorchsim.backend import launcher # noqa: E402,F401 its logger set up before a handler joins it HQ, HKV, S, D = 16, 8, 4096, 128 BOUND = 800_000 @@ -31,7 +31,7 @@ def emit(self, record): def test_a_causal_prefill_takes_its_earlier_blocks_before_the_diagonal(): seen = _Cycles() - logging.getLogger("pytorchsim.backend.codecache").addHandler(seen) + logging.getLogger("pytorchsim.backend.launcher").addHandler(seen) dev = torch.device("npu:0") g = torch.Generator().manual_seed(0) q, k, v = (torch.randn(1, h, S, D, generator=g).bfloat16().to(dev) for h in (HQ, HKV, HKV)) diff --git a/tests/ops/conv/test_depthwise_candidate_overflow.py b/tests/ops/conv/test_depthwise_candidate_overflow.py new file mode 100644 index 00000000..05675b36 --- /dev/null +++ b/tests/ops/conv/test_depthwise_candidate_overflow.py @@ -0,0 +1,54 @@ +"""A custom kernel (the depthwise conv, a CustomFusedKernel) is offered a config per candidate block from tiling.py; +the first one overflows the scratchpad (tpuv3_32x32's, 1 MiB: v6e's holds the largest tile Triton builds), the Triton backend raises OutOfResources, Inductor drops that config and the +next one runs, with the CPU's values. Breaks when the kernel is launched with one fixed BC, or its configs are not +tried in order.""" +import os +import sys +from unittest import mock + +os.environ["TORCHSIM_TARGET"] = "tpuv3_32x32" + +import torch + +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) +from result_check import check_result # noqa: E402 + + +@torch.no_grad() +def test_first_candidate_overflows(channels=256, length=512, kernel=4): + from torch._inductor.runtime import triton_heuristics as th + from triton.runtime.errors import OutOfResources + from pytorchsim.frontend import tiling + + outcomes = [] + orig = th.CachingAutotuner._precompile_config + + def spy(self, cfg, **kw): + if "BC" not in cfg.kwargs: + return orig(self, cfg, **kw) + try: + got = orig(self, cfg, **kw) + except OutOfResources as e: + outcomes.append((cfg.kwargs["BC"], f"OutOfResources: {e}")) + raise + outcomes.append((cfg.kwargs["BC"], "compiled")) + return got + + torch._dynamo.reset() + torch.manual_seed(0) + conv = torch.nn.Conv1d(channels, channels, kernel, groups=channels, padding=kernel - 1, bias=False) + x = torch.randn(1, channels, length) + want = conv(x)[..., :length] + dev = conv.to("npu:0") + with mock.patch.object(tiling, "candidate_sizes", lambda first, limit=3: [1 << 10, 128, 64]), \ + mock.patch.object(th.CachingAutotuner, "_precompile_config", spy): + got = torch.compile(dynamic=False)(lambda t: dev(t)[..., :length])(x.to("npu:0")) + for bc, what in outcomes: + print(f"candidate BC={bc}: {what}") + assert outcomes[0][0] == 1 << 10 and outcomes[0][1].startswith("OutOfResources"), outcomes + assert (64, "compiled") in outcomes, outcomes + check_result("DepthwiseCandidateOverflow", got.cpu(), want, 1e-4, 1e-4) + + +if __name__ == "__main__": + test_first_candidate_overflows() diff --git a/tests/ops/elementwise/test_candidate_overflow.py b/tests/ops/elementwise/test_candidate_overflow.py new file mode 100644 index 00000000..38a5ba47 --- /dev/null +++ b/tests/ops/elementwise/test_candidate_overflow.py @@ -0,0 +1,49 @@ +"""A generated kernel whose first candidate tile overflows the scratchpad is dropped by Inductor's autotuner +(OutOfResources from the Triton backend) and the next candidate is the one that runs, with the right values. +Breaks if the kernel's configs are pinned to one tile, or the backend's overflow is not OutOfResources.""" +import os +import sys + +import torch +from unittest import mock + +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) +from result_check import check_result # noqa: E402 + + +def test_first_candidate_overflows(device, numel=1 << 20): + from torch._inductor.runtime import triton_heuristics as th + from triton.runtime.errors import OutOfResources + from pytorchsim.frontend import tiling + + outcomes = [] + orig = th.CachingAutotuner._precompile_config + + def spy(self, cfg, **kw): + try: + got = orig(self, cfg, **kw) + except OutOfResources as e: + outcomes.append((cfg.kwargs["XBLOCK"], f"OutOfResources: {e}")) + raise + outcomes.append((cfg.kwargs["XBLOCK"], "compiled")) + return got + + def fn(*xs): + out = xs[0] + for t in xs[1:]: + out = out * 0.5 + t + return out + + xs = [torch.randn(numel).to(device) for _ in range(32)] + with mock.patch.object(tiling, "candidate_blocks", lambda *a, **k: [{"XBLOCK": numel}, {"XBLOCK": 4096}]), \ + mock.patch.object(th.CachingAutotuner, "_precompile_config", spy): + res = torch.compile(dynamic=False)(fn)(*xs) + for xblock, what in outcomes: + print(f"candidate XBLOCK={xblock}: {what}") + assert outcomes[0][0] == numel and outcomes[0][1].startswith("OutOfResources"), outcomes + assert (4096, "compiled") in outcomes, outcomes + check_result("CandidateOverflow", res, fn(*[t.cpu() for t in xs])) + + +if __name__ == "__main__": + test_first_candidate_overflows(torch.device("npu:0")) diff --git a/tests/ops/misc/test_indirect_index_assert.py b/tests/ops/misc/test_indirect_index_assert.py new file mode 100644 index 00000000..5e32db89 --- /dev/null +++ b/tests/ops/misc/test_indirect_index_assert.py @@ -0,0 +1,40 @@ +"""A gather index out of range stops the launch with Inductor's own message: assert_indirect_indexing is on, so +the kernel's tl.device_assert reaches PTB, which stops Spike on it. Breaks when the flag is off (the gather reads +past its table and returns a value) or when PTB cannot lower a tensor tt.assert (the compile fails instead).""" +import os +import sys + +sys.path.insert(0, os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim")) +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) + +import torch # noqa: E402 +from result_check import check_result # noqa: E402 + + +def _gather(table, index): + return table[index] * 2.0 + + +def test_in_range_index_gathers(device): + torch.manual_seed(0) + table, index = torch.randn(64, 128), torch.randint(0, 64, [32]) + got = torch.compile(dynamic=False)(_gather)(table.to(device), index.to(device)) + check_result("in-range gather", got.cpu(), _gather(table, index)) + + +def test_out_of_range_index_stops_the_launch(device): + table, index = torch.randn(64, 128), torch.randint(0, 64, [32]) + index[5] = 64 + try: + torch.compile(dynamic=False)(_gather)(table.to(device), index.to(device)) + except Exception as e: # noqa: BLE001 + assert "index out of bounds" in str(e), str(e)[-600:] + print("Test Passed: the launch stopped with", [l for l in str(e).splitlines() if "index out of bounds" in l][:1]) + return + raise AssertionError("an index of 64 into a table of 64 rows did not stop the launch") + + +if __name__ == "__main__": + device = torch.device("npu:0") + test_in_range_index_gathers(device) + test_out_of_range_index_stops_the_launch(device) diff --git a/tests/system/data/npuwattch_tpuv3/kernel/meta.json b/tests/system/data/npuwattch_tpuv3/kernel/meta.json index ede9a75d..c8078988 100644 --- a/tests/system/data/npuwattch_tpuv3/kernel/meta.json +++ b/tests/system/data/npuwattch_tpuv3/kernel/meta.json @@ -1,5 +1,5 @@ { - "kernel_name": "pytorchsim_triton_compiler_fused_mm_au7umwrt", + "kernel_name": "triton_tem_fused_mm_0", "signature": { "arg_A": "*bf16", "arg_B": "*bf16", diff --git a/tests/system/stub_compile.py b/tests/system/stub_compile.py new file mode 100644 index 00000000..18d299ff --- /dev/null +++ b/tests/system/stub_compile.py @@ -0,0 +1,16 @@ +"""A graph lowered with its Triton kernels not compiled: what a test of the lowering's decisions reads.""" +import contextlib +from unittest import mock + + +class _NotCompiled: + def run(self, *args, **kwargs): + return None + + +@contextlib.contextmanager +def kernels_not_compiled(): + """Inductor's async_compile.triton hands back a kernel that launches nothing, so no kernel reaches PTB.""" + from torch._inductor.async_compile import AsyncCompile + with mock.patch.object(AsyncCompile, "triton", lambda self, name, source, device_str="cuda": _NotCompiled()): + yield diff --git a/tests/system/test_compiler_failure.py b/tests/system/test_compiler_failure.py index 266cd006..f8403618 100644 --- a/tests/system/test_compiler_failure.py +++ b/tests/system/test_compiler_failure.py @@ -1,6 +1,7 @@ """Why a compile failed is read from the failure.json the compiler leaves, never from what it -printed: a scratchpad over its budget is a tile too big by usage / budget, and a kernel file the -compiler cannot load stops outside every stage and is no reason to shrink anything.""" +printed: a scratchpad over its budget is a tile too big by usage / budget (PTB's Triton backend raises it as +OutOfResources, and Inductor drops that config), and a kernel file the compiler cannot load stops outside +every stage and is no reason to shrink anything.""" import os import sys import tempfile @@ -8,7 +9,7 @@ sys.path.insert(0, os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim")) import torch # noqa: F401 the npu backend loads pytorchsim whole, before its parts are imported -from pytorchsim.backend import retile, compiler_bridge +from pytorchsim.backend import compiler_bridge def _failed(spec_path): @@ -26,7 +27,7 @@ def test_spad_overflow_is_too_big(): e = _failed(spec) usage, budget = e.failure["usage"], e.failure["budget"] assert e.failure["kind"] == "spad-overflow" and usage > budget > 0 - assert retile.too_big(e) == "%d bytes/lane over a budget of %d" % (usage, budget) + assert e.failure["message"], e.failure def test_unloadable_kernel_is_not_too_big(): @@ -36,7 +37,7 @@ def test_unloadable_kernel_is_not_too_big(): e = _failed(f.name) finally: os.unlink(f.name) - assert e.failure is None and retile.too_big(e) is None + assert e.failure is None assert "not a kernel file" in str(e) diff --git a/tests/system/test_dynamic_shape_spike.py b/tests/system/test_dynamic_shape_spike.py index 01d9cc44..ca0c8bd6 100644 --- a/tests/system/test_dynamic_shape_spike.py +++ b/tests/system/test_dynamic_shape_spike.py @@ -1,6 +1,6 @@ -"""A graph compiled once over a dynamic size runs on Spike at every size: the launcher builds the ELF for -extents it was not built for (each tensor's span, each numel passed as a scalar). Breaks when a launch -reuses the import-time ELF, which Spike's placement refuses (ShapeMismatch). Values match the CPU.""" +"""A graph compiled once over a dynamic size runs on Spike at every size: PTB's Triton launcher builds the ELF for +extents it was not built for (each tensor's span, each numel passed as a scalar). Breaks when a launch reuses the +compile's ELF, which Spike's placement refuses (ShapeMismatch). Values match the CPU.""" import os import sys diff --git a/tests/system/test_graph_prefetch.py b/tests/system/test_graph_prefetch.py index f67b30d4..ef9bb0ce 100644 --- a/tests/system/test_graph_prefetch.py +++ b/tests/system/test_graph_prefetch.py @@ -7,9 +7,12 @@ from unittest import mock sys.path.insert(0, os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim")) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import torch # noqa: E402 the npu backend loads pytorchsim whole, before its parts are imported -from pytorchsim.backend import codecache, compiler_bridge, compiler_input # noqa: E402 +from pytorchsim.backend import compiler_input # noqa: E402 +from pytorchsim.frontend.inductor.codegen import kernel_metadata # noqa: E402 +from stub_compile import kernels_not_compiled # noqa: E402 from pytorchsim.frontend.inductor.autotune import graph_prefetch # noqa: E402 _A = torch.ops.aten @@ -145,49 +148,26 @@ def test_a_kernel_of_no_resident_form_states_nothing(): assert graph_prefetch.statement(object(), [{"name": "in_ptr0", "role": "in", "buffer": "w"}]) == [] -def test_a_refusal_is_an_error_naming_the_kernel_and_arg(): - """Breaks if the compiler's refusal to hold the elected operand is retried, retiled or built holding - nothing: the two sides disagree, and torchsim_compile raises.""" - kind = compiler_bridge.compiler_contract("failure").SPAD_OVERFLOW - calls = [] - - def refuse(*a, **kw): - calls.append(a) - raise compiler_bridge.CompilerError("x", failure={"kind": kind, "usage": 8, "budget": 4, - "message": "over"}) - meta = {"kernel_name": "mm", "signature": {"arg_A": "*bf16", "arg_B": "*bf16", "XBLOCK": "constexpr"}, - "constants": {}, "numels": {"xnumel": 4096}, "fixed_config": {"XBLOCK": 1024}, - "args": [{"name": n, "role": "in", "buffer": b, "dtype": "bfloat16", "numel": 64} - for n, b in (("arg_A", "x"), ("arg_B", "w"))], "graph_prefetch": ["arg_B"]} - with tempfile.TemporaryDirectory() as dump, mock.patch.dict(os.environ, {"TORCHSIM_DUMP_PATH": dump}), \ - mock.patch.object(codecache.compiler_bridge, "run_pipeline", refuse): - try: - codecache.torchsim_compile("def kernel(): pass\n", meta, "mm") - except compiler_bridge.CompilerError as e: - assert "mm" in str(e) and "arg_B" in str(e) and kind in str(e), e - else: - raise AssertionError("a refused hold compiled") - assert len(calls) == 1, calls - - -def test_the_build_key_holds_the_statement(): - """Breaks if an elected and a non-elected build of one source, constants and args share a workdir.""" - meta = {"signature": {}, "constants": {}, "args": [], "graph_prefetch": ["arg_B"]} - with tempfile.TemporaryDirectory() as dump, mock.patch.dict(os.environ, {"TORCHSIM_DUMP_PATH": dump}): - streamed = dict(meta, graph_prefetch=[]) - assert codecache._write_path("src", meta) != codecache._write_path("src", streamed) +def test_the_compile_key_holds_the_statement(): + """Breaks if an elected and a non-elected build of one source, constants and args share a Triton cache key: + the spec rides the compile's options, which the key hashes.""" + import json + from triton.backends.pytorchsim.compiler import CPUOptions + spec = lambda held: json.dumps(compiler_input.spec_dict([("in", 64), ("in", 64)], (1, 1, 1), held)) # noqa: E731 + assert CPUOptions(pytorchsim_spec=spec([1])).hash() != CPUOptions(pytorchsim_spec=spec([])).hash() def _compiled_metas(fn, *xs): - """The meta of each kernel torch.compile of `fn` defines, with the compiler faked away.""" + """The meta of each kernel torch.compile of `fn` defines, with the kernels not compiled.""" from torch._inductor import config as inductor_config got = [] + real = kernel_metadata.record_roles - def compile_(src, meta, kernel_name): + def record(kernel_name, meta): got.append(meta) - return lambda *args, **kwargs: None + real(kernel_name, meta) torch._dynamo.reset() - with mock.patch.object(codecache, "torchsim_compile", compile_), \ + with kernels_not_compiled(), mock.patch.object(kernel_metadata, "record_roles", record), \ inductor_config.patch(fx_graph_cache=False): torch.compile(fn, dynamic=False)(*[x.to("npu:0") for x in xs]) return got diff --git a/tests/system/test_graph_prefetch_xla.py b/tests/system/test_graph_prefetch_xla.py index 7b5a773d..ac226db3 100644 --- a/tests/system/test_graph_prefetch_xla.py +++ b/tests/system/test_graph_prefetch_xla.py @@ -7,10 +7,12 @@ from unittest import mock sys.path.insert(0, os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim")) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import torch # noqa: E402 the npu backend loads pytorchsim whole, before its parts are imported import torch.nn.functional as F # noqa: E402 -from pytorchsim.backend import codecache, compiler_bridge # noqa: E402 +from pytorchsim.backend import compiler_bridge # noqa: E402 +from stub_compile import kernels_not_compiled # noqa: E402 from pytorchsim.frontend.inductor.autotune import graph_prefetch # noqa: E402 BF = torch.bfloat16 @@ -149,7 +151,7 @@ def backend(gm, example): g = torch.Generator().manual_seed(0) xs = [torch.randn(*s, generator=g).to(BF).to("npu:0") for s in shapes] torch._dynamo.reset() - with mock.patch.object(codecache, "torchsim_compile", lambda src, meta, kernel_name: lambda *a, **k: None), \ + with kernels_not_compiled(), \ mock.patch.object(graph_prefetch, "elected", spy), \ inductor_config.patch(fx_graph_cache=False, pattern_matcher=not xla_form): torch.compile(fn, dynamic=False, backend=backend)(*xs) diff --git a/tests/system/test_launch_record.py b/tests/system/test_launch_record.py index 25e52b68..54ab25f0 100644 --- a/tests/system/test_launch_record.py +++ b/tests/system/test_launch_record.py @@ -86,7 +86,26 @@ def test_an_inline_view_is_named_by_its_buffer(): assert first["name"] == "arg0_1" and first["data_ptr"] == x.data_ptr() + 128 * 4, record +def test_addrs_file_and_record_name_each_argument(): + """tog_tensor_addrs.txt lines are `name addr bytes align role` with the kernel's parameter as the name, and + launch.json says which buffer each parameter is: an add of two inputs reads arg0_1 and arg1_1, writes buf0.""" + device = torch.device("npu:0") + x, y = torch.randn(64, 256).to(device), torch.randn(64, 256).to(device) + with torch.no_grad(), torch.npu.TOGSimulator() as sim: + out = torch.compile(lambda a, b: a * 2 + b, dynamic=False)(x, y) + torch.testing.assert_close(out.cpu(), x.cpu() * 2 + y.cpu()) + (d,) = _launch_dirs(sim.trace_path) + with open(os.path.join(d, "tog_tensor_addrs.txt")) as f: + lines = [line.split() for line in f] + with open(os.path.join(d, "launch.json")) as f: + args = json.load(f)["args"] + assert [(n, r) for n, _, _, _, r in lines] == [("in_ptr0", "in"), ("in_ptr1", "in"), ("out_ptr0", "out")], lines + assert [(a["param"], a["name"]) for a in args if "data_ptr" in a] == [ + ("in_ptr0", "arg0_1"), ("in_ptr1", "arg1_1"), ("out_ptr0", "buf0")], args + + if __name__ == "__main__": + test_addrs_file_and_record_name_each_argument() test_each_launch_keeps_its_own_record() test_an_inline_view_is_named_by_its_buffer() print("PASS") diff --git a/tests/system/test_npuwattch_json.py b/tests/system/test_npuwattch_json.py index 1d866844..c12b245f 100644 --- a/tests/system/test_npuwattch_json.py +++ b/tests/system/test_npuwattch_json.py @@ -99,3 +99,22 @@ def test_on_writes_a_kernel_per_launch(): doc = json.load(f) assert doc["schema"] == "pytorchsim.run_stats" and doc["schema_version"] == "1.1" assert [k["order"] for k in doc["kernels"]] == [0, 1] + + +def test_inductor_kernel_names_give_the_operation(): + """Breaks if the operation is read off a name Inductor no longer gives (pytorchsim_triton_compiler_fused_*).""" + assert [npuwattch._fused_name(n) for n in ("triton_tem_fused_mm_0", "triton_per_fused__softmax_3", + "triton_poi_fused_add_mul_12", "_add_one_kernel")] == [ + "mm", "softmax", "add_mul", None] + + +def test_a_launch_leaves_the_meta_npuwattch_reads(): + """Breaks if a launch leaves no meta.json in its workdir: kernel_entry reads each tensor's sizes and buffer.""" + import torch + from pytorchsim.backend import launcher + meta = {"kernel_name": "k", "args": [{"name": "in_ptr0", "role": "in", "dtype": "float32"}]} + with tempfile.TemporaryDirectory() as workdir: + launcher._store_meta(workdir, meta, [torch.empty(4, 8), 32], ("arg0_1", None)) + with open(os.path.join(workdir, "meta.json")) as f: + got = json.load(f) + assert got["args"][0]["sizes"] == [4, 8] and got["args"][0]["buffer"] == "arg0_1", got diff --git a/tests/system/test_parallel_compile.py b/tests/system/test_parallel_compile.py new file mode 100644 index 00000000..5b824325 --- /dev/null +++ b/tests/system/test_parallel_compile.py @@ -0,0 +1,32 @@ +"""Inductor compiles an npu graph's kernels in its worker pool, as on any device: PTB's Triton backend is importable +in a worker, so a kernel built there is the one the parent launches (values match the CPU). Breaks when compile_threads +is forced to 1 at install, or a worker cannot build a kernel for npu.""" +import os +import sys + +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) + +import torch # noqa: E402 +from result_check import check_result # noqa: E402 + + +def test_kernels_compile_in_the_pool(): + from torch._inductor import config as inductor_config + from torch._inductor.async_compile import AsyncCompile, get_compile_threads + + assert get_compile_threads() > 1 or os.environ.get("TORCHINDUCTOR_COMPILE_THREADS"), inductor_config.compile_threads + + def fn(x, y): + a = torch.relu(x) + y + b = torch.softmax(a, dim=-1) + c = (b * 3.0).sum(dim=0) + return torch.tanh(c) + a.mean(dim=1).sum() + + x, y = torch.randn(64, 256), torch.randn(64, 256) + got = torch.compile(dynamic=False)(fn)(x.to("npu:0"), y.to("npu:0")) + check_result("ParallelCompile", got.cpu(), fn(x, y)) + assert AsyncCompile._ready_future is not None or get_compile_threads() <= 1 + + +if __name__ == "__main__": + test_kernels_compile_in_the_pool() diff --git a/tests/system/test_select.py b/tests/system/test_select.py index 4a5273d4..77d248bd 100644 --- a/tests/system/test_select.py +++ b/tests/system/test_select.py @@ -1,5 +1,5 @@ """A template's config is Inductor's selection: in timing mode each offered config of a bmm is timed on TOGSim -and the fewest cycles wins, an epilogue fused when one is there; the pick is recorded and built again untimed. +(the npu benchmarker) and the fewest cycles wins, an epilogue fused when one is there; the pick is recorded and built again untimed. Each compile runs in a child process. A bmm, as an mm copy_node.plan holds is planned, not timed.""" import json import os @@ -19,25 +19,27 @@ SHAPE = (128, 256, 256) #: One compile of OP, template_timing's record kept in SELECT_RECORD_DIR and what was timed written to -#: SELECT_TIMED as [config, cycles] (unfused choices) and [meta, cycles] (fusion benchmarks). +#: SELECT_TIMED as [config, cycles] (unfused choices), [meta, cycles] (fusion benchmarks) and what each kernel was +#: built as: its name, how its config was chosen, a template's blocks, a generated kernel's blocks. CHILD = r""" import json, os, sys import torch -from pytorchsim.frontend.inductor.codegen.scheduling import TritonNPUScheduling +from torch._inductor.select_algorithm import AlgorithmSelectorCache +from pytorchsim.frontend.inductor.codegen.scheduling import TritonNPUScheduling, _tile_source from pytorchsim.backend import template_timing from pytorchsim.backend import template_record template_record.RECORD_DIR = os.environ["SELECT_RECORD_DIR"] -timed = {"choices": [], "modules": []} +timed = {"choices": [], "modules": [], "built": []} -def time_choices(choices, _orig=template_timing.time_choices): - out = _orig(choices) - for c, t in out.items(): +def benchmark(cls, choices, *a, _orig=AlgorithmSelectorCache.benchmark_choices.__func__, **k): + out = _orig(cls, choices, *a, **k) + for c, ms in out.items(): ktc = c.annotations.get("ktc") - if ktc is not None and t != float("inf"): - timed["choices"].append([ktc.params.to_kwargs(), t]) + if ktc is not None and ms != float("inf"): + timed["choices"].append([ktc.params.to_kwargs(), round(ms * 1e6)]) return out -template_timing.time_choices = time_choices +AlgorithmSelectorCache.benchmark_choices = classmethod(benchmark) def bench(self, mod, *a, _orig=TritonNPUScheduling.benchmark_codegened_module, **k): t, path = _orig(self, mod, *a, **k) @@ -45,6 +47,16 @@ def bench(self, mod, *a, _orig=TritonNPUScheduling.benchmark_codegened_module, * return t, path TritonNPUScheduling.benchmark_codegened_module = bench +def define(self, src_code, node_schedule, kernel, _orig=TritonNPUScheduling.define_kernel): + name = _orig(self, src_code, node_schedule, kernel) + meta = getattr(kernel, "_npu_meta", None) + timed["built"].append({ + "name": name, "tile_source": _tile_source(node_schedule), + "template_blocks": {k: v for k, v in (getattr(kernel, "meta", None) or {}).items() if k.startswith("BLOCK_")}, + "blocks": None if meta is None else [meta["numels"], meta["fixed_config"], meta["inside_reduction"]]}) + return name +TritonNPUScheduling.define_kernel = define + op = sys.argv[1] m, k, n = map(int, sys.argv[2:5]) a = torch.randn(2, m, k).to(torch.bfloat16).to("npu:0") @@ -71,19 +83,9 @@ def _compile(root, name, op, timing): return dump, json.load(f) -def _kernels(dump): - """{workdir name: meta} of every kernel the compile built.""" - out = {} - for name in os.listdir(dump): - meta = os.path.join(dump, name, "meta.json") - if name.startswith("triton_") and os.path.isfile(meta): - with open(meta) as f: - out[name] = json.load(f) - return out - - -def _templates(dump): - return {k: m for k, m in _kernels(dump).items() if "tile_source" in m} +def _templates(timed): + """What a compile built as a template: every built kernel whose config was chosen.""" + return [b for b in timed["built"] if b["tile_source"] is not None] def _picks(dump): @@ -103,18 +105,11 @@ def _merge(root, dump): assert proc.returncode == 0, proc.stderr[-4000:] -def _same_kernel(meta): - """What decides a kernel's cycles, without the names it is called by.""" - return {"signature": meta["signature"], "constants": meta["constants"], - "args": [(a["role"], a["dtype"], a["numel"]) for a in meta["args"]], - "numels": meta["numels"], "fixed_config": meta["fixed_config"], - "template_grid": meta["template_grid"], "inside_reduction": meta["inside_reduction"]} - - def test_select_record_and_rebuild(): """Timed alone: the fewest cycles is picked, recorded and built as timed. Timed with an epilogue: the top configs are timed fused, the epilogue alone at its built blocks. Recorded: built again untimed. A record timed with another compiler is not used.""" + blocks = lambda c: {k: c[k] for k in ("BLOCK_M", "BLOCK_N", "BLOCK_K")} # noqa: E731 with tempfile.TemporaryDirectory() as root: mm, mm_timed = _compile(root, "mm_timed", "bmm", timing=True) cycles = [t for _, t in mm_timed["choices"]] @@ -122,39 +117,35 @@ def test_select_record_and_rebuild(): (pick,) = _picks(mm) assert {k: v for k, v in pick["config"].items() if k not in ("template_id", "template_hash")} == best - (built,) = _templates(mm).values() + (built,) = _templates(mm_timed) assert built["tile_source"] == template_record.TIMED - bench = [json.load(open(os.path.join(mm, "select", d, "meta.json"))) - for d in os.listdir(os.path.join(mm, "select"))] - assert _same_kernel(built) in [_same_kernel(b) for b in bench] + assert built["template_blocks"] == blocks(best), (built, best) relu, relu_timed = _compile(root, "mm_relu_timed", "bmm_relu", timing=True) fused = [m for m, _ in relu_timed["modules"] if m["template_grid"] is not None] assert 1 <= len(fused) <= len(relu_timed["choices"]) - (built_relu,) = _templates(relu).values() + (built_relu,) = _templates(relu_timed) assert built_relu["tile_source"] == template_record.TIMED alone = [m for m, _ in relu_timed["modules"] if m["template_grid"] is None] - plain, _ = _compile(root, "relu", "relu", timing=False) - (relu_kernel,) = _kernels(plain).values() - blocks = lambda m: (m["numels"], m["fixed_config"], m["inside_reduction"]) - assert alone and all(blocks(m) == blocks(relu_kernel) for m in alone), (alone, relu_kernel) + _, plain = _compile(root, "relu", "relu", timing=False) + (relu_kernel,) = [b for b in plain["built"] if b["blocks"] is not None] + same = lambda m: [m["numels"], m["fixed_config"], m["inside_reduction"]] # noqa: E731 + assert alone and all(same(m) == relu_kernel["blocks"] for m in alone), (alone, relu_kernel) _merge(root, mm) for timing in (False, True): again, timed = _compile(root, f"mm_recorded_{int(timing)}", "bmm", timing=timing) - assert timed == {"choices": [], "modules": []} - assert {k: m["tile_source"] for k, m in _templates(again).items()} == \ - {k: template_record.RECORDED for k in _templates(mm)} - fused_again, _ = _compile(root, "mm_relu_recorded", "bmm_relu", timing=False) - assert [m["tile_source"] for m in _templates(fused_again).values()] == \ - [template_record.RECORDED_UNFUSED] + assert timed["choices"] == [] and timed["modules"] == [] + assert [b["tile_source"] for b in _templates(timed)] == [template_record.RECORDED] + _, fused_again = _compile(root, "mm_relu_recorded", "bmm_relu", timing=False) + assert [b["tile_source"] for b in _templates(fused_again)] == [template_record.RECORDED_UNFUSED] path = os.path.join(root, "record", os.listdir(os.path.join(root, "record"))[0]) rec = json.load(open(path)) rec["identity"]["compiler"] = "another" json.dump(rec, open(path, "w")) - stale, _ = _compile(root, "mm_stale", "bmm", timing=False) - assert [m["tile_source"] for m in _templates(stale).values()] == [template_record.HEURISTIC] + _, stale = _compile(root, "mm_stale", "bmm", timing=False) + assert [b["tile_source"] for b in _templates(stale)] == [template_record.HEURISTIC] def _choice(name, uid="triton::mm"): @@ -165,61 +156,12 @@ def _choice(name, uid="triton::mm"): return c -def _rendered(timed=None): - """Patches for time_choices off Inductor: each choice's source is its name, no prefetch, nothing timed yet.""" - from contextlib import ExitStack - stack = ExitStack() - stack.enter_context(mock.patch.object(template_timing.kernel_metadata, "benchmark_request_meta", - side_effect=lambda req: (req.module_cache_key, {"args": []}))) - stack.enter_context(mock.patch.object(template_timing.graph_prefetch, "choice_statement", - return_value=[])) - stack.enter_context(mock.patch.dict(template_timing._timed, timed or {}, clear=True)) - return stack - - -def test_a_refused_config_is_inf_and_none_left_is_an_error(): - a, b = _choice("a"), _choice("b") - with _rendered(), \ - mock.patch.object(template_timing, "_time_tile", - side_effect=lambda src, meta, name, wd, cut: 7.0 if wd.endswith("b") else float("inf")): - assert template_timing.time_choices([a, b]) == {a: float("inf"), b: 7.0} - with _rendered(), \ - mock.patch.object(template_timing, "_time_tile", return_value=float("inf")): - try: - template_timing.time_choices([a, b]) - except RuntimeError as e: - assert "no template config" in str(e) - else: - raise AssertionError("every config refused, and time_choices returned") - - -def test_a_config_running_past_the_cut_is_inf(): - """The configs run at once; one still simulating CUT_FACTOR times after the first finished is cut.""" - import time - - def tile(src, meta, name, wd, cut): - if wd.endswith("fast"): - time.sleep(0.2) - return 5.0 - while not cut(): - time.sleep(0.05) - return float("inf") - fast, slow = _choice("fast"), _choice("slow") - with _rendered(), mock.patch.object(template_timing, "_time_tile", side_effect=tile): - t0 = time.monotonic() - assert template_timing.time_choices([slow, fast]) == {slow: float("inf"), fast: 5.0} - assert time.monotonic() - t0 < 0.2 * template_timing.CUT_FACTOR + 1 - - -def test_a_config_timed_once_is_not_timed_again(): - """A config rendered the same at another node takes the cycles this process timed it at.""" - tile = mock.Mock(side_effect=lambda src, meta, name, wd, cut: 3.0 if wd.endswith("a") else 4.0) - with _rendered(), mock.patch.object(template_timing, "_time_tile", tile): - a, b = _choice("a"), _choice("b") - assert template_timing.time_choices([a, b]) == {a: 3.0, b: 4.0} - a2, b2 = _choice("a"), _choice("b") - assert template_timing.time_choices([a2, b2]) == {a2: 3.0, b2: 4.0} - assert tile.call_count == 2 +def test_a_launch_that_does_not_simulate_is_inf(): + """A configuration being timed whose TOGSim run refuses it (a tile over the spad) is inf, not an error: Inductor + drops it, and raises only when none is left.""" + from pytorchsim.backend import launcher + with mock.patch.object(launcher.timing, "write_cycle_tables", side_effect=RuntimeError("over the spad")): + assert launcher._simulate_alone("/nonexistent", {"kernel_name": "k"}, ()) == float("inf") def _machine(root, sub, **change): @@ -284,8 +226,6 @@ def test_a_convolution_is_offered_every_tile_a_timed_run_ranks(): test_a_convolution_config_is_timed() test_a_convolution_is_offered_every_tile_a_timed_run_ranks() test_graph_cache_key_names_the_machine() - test_a_config_running_past_the_cut_is_inf() - test_a_refused_config_is_inf_and_none_left_is_an_error() - test_a_config_timed_once_is_not_timed_again() + test_a_launch_that_does_not_simulate_is_inf() test_select_record_and_rebuild() print("PASS") diff --git a/tests/system/test_togsim_result.py b/tests/system/test_togsim_result.py index 44fd0f76..c0850e79 100644 --- a/tests/system/test_togsim_result.py +++ b/tests/system/test_togsim_result.py @@ -1,6 +1,7 @@ """TOGSim's results reach the frontend through the file it writes with --result, never its log; a session keeps the Simulator's output in its .log, a launch it queues has no result yet, and the attribute copies its launches held go when it shuts down. The Simulator is a stub, so no TOGSim is needed.""" +import json import os import stat import sys @@ -10,7 +11,7 @@ sys.path.insert(0, os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim")) from pytorchsim import config -from pytorchsim.backend import codecache +from pytorchsim.backend import launcher from pytorchsim.simulator import timing from pytorchsim.simulator.timing.togsim import PLACEMENT_VERSION, TOGSimProcess @@ -101,10 +102,12 @@ def test_a_session_removes_the_attribute_copies_its_launches_held(): def test_a_launch_queued_on_a_session_returns_no_result(): - launcher = codecache.TritonNPULauncher("k", "/nonexistent", {"kernel_name": "k"}) + kernel_object = json.dumps({"name": "k", "artifacts": {"elf": "k.elf"}}) with mock.patch.dict(os.environ, TORCHSIM_TIMING_MODE="1", TORCHSIM_FUNCTIONAL_MODE="0"), \ - mock.patch.object(codecache.timing, "run", return_value=None): - assert launcher() is None + mock.patch.object(launcher, "_get_workdir", return_value="/nonexistent"), \ + mock.patch.object(launcher, "_get_meta", return_value={"kernel_name": "k"}), \ + mock.patch.object(launcher.timing, "run", return_value=None): + assert launcher.run_launch(b"", kernel_object, (1, 1, 1), ()) is None if __name__ == "__main__": diff --git a/tests/system/test_tuned_blocks_on_hit.py b/tests/system/test_tuned_blocks_on_hit.py deleted file mode 100644 index c6e06974..00000000 --- a/tests/system/test_tuned_blocks_on_hit.py +++ /dev/null @@ -1,40 +0,0 @@ -"""A kernel the compiler refused at its first tile is built at a smaller one, and a later cache hit -launches with that tile: the hit's caller holds the untuned fixed_config, and the grid it derives -from it would launch the wrong number of programs on the tuned ELF.""" -import json -import os -import sys -import tempfile -from unittest import mock - -sys.path.insert(0, os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim")) - -import torch # noqa: F401,E402 the npu backend loads pytorchsim whole, before its parts are imported -from pytorchsim import contract # noqa: E402 -from pytorchsim.backend import codecache # noqa: E402 -from pytorchsim.backend import compiler_input # noqa: E402 - -SRC = "def kernel(): pass\n" - - -def _meta(xblock): - return {"kernel_name": "k", "numels": {"xnumel": 4096}, "fixed_config": {"XBLOCK": xblock}, - "signature": {"XBLOCK": "constexpr"}, "args": [], "graph_prefetch": []} - - -def test_a_hit_launches_the_tuned_tile(): - with tempfile.TemporaryDirectory() as dump, mock.patch.dict(os.environ, {"TORCHSIM_DUMP_PATH": dump}): - untuned = _meta(1024) - workdir = codecache._write_path(SRC, untuned) - os.makedirs(workdir) - compiler_input.store_meta(workdir, _meta(256)) - with mock.patch.object(codecache, "cached_elf", return_value=os.path.join(workdir, "k.elf")), \ - mock.patch.object(codecache.config, "pytorchsim_timing_mode", 0): - launcher = codecache.torchsim_compile(SRC, _meta(1024), "k") - assert launcher.meta["fixed_config"] == {"XBLOCK": 256}, launcher.meta["fixed_config"] - assert contract.grid_of(launcher.meta)[0] == 4096 // 256, contract.grid_of(launcher.meta) - - -if __name__ == "__main__": - test_a_hit_launches_the_tuned_tile() - print("PASS") From 5b6672c55949253dbb59cbed7bc9e996bd94f771 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Mon, 16 Nov 2026 22:49:31 +0900 Subject: [PATCH 03/11] [Backend] The spec reaches the Triton backend in triton_meta as Inductor sets it, not by editing the source TritonNPUKernel.triton_meta is a property whose setter adds backend_options when Inductor assigns the finished dict (triton.py:7338), so it does not depend on when the body is built (codegen_body also runs from SIMDKernel.disable_reduction, simd.py:806, before triton_meta exists). A template kernel is seeded with TemplateTritonMeta, whose update (made by TritonTemplateKernel.jit_lines at render time, after the epilogue is fused, select_algorithm.py:932-935) adds them: the templates that need it are Inductor's own instances, and giving them our kernel class would mean assigning TritonTemplate.kernel_type on them. apply_spec_to_source and its call sites are gone. test_standard_attachments.SpecInRenderedMeta fails on the source edit. mllama's vision tower (image 112) is the case the setter fixes over a codegen_body hook. --- .../inductor/codegen/kernel_metadata.py | 32 ++++++++++----- .../frontend/inductor/codegen/scheduling.py | 31 ++++++-------- tests/system/test_standard_attachments.py | 40 +++++++++++++++++++ 3 files changed, 74 insertions(+), 29 deletions(-) create mode 100644 tests/system/test_standard_attachments.py diff --git a/pytorchsim/frontend/inductor/codegen/kernel_metadata.py b/pytorchsim/frontend/inductor/codegen/kernel_metadata.py index 84c2925c..47dcc8bf 100644 --- a/pytorchsim/frontend/inductor/codegen/kernel_metadata.py +++ b/pytorchsim/frontend/inductor/codegen/kernel_metadata.py @@ -132,18 +132,28 @@ def _blocks_without_pin(kernel, numels, args): return tiling.fixed_config_for(kernel, numels, args) -def apply_spec_to_source(src_code, kernel, meta): - """The one text edit of Inductor's source: `kernel`'s triton_meta, as the decorator holds it, gains the spec of - `meta` as backend_options. No hook can do it: triton_meta_common runs before the signature the spec needs - exists, and a template's decorator reads its triton_meta after its epilogue is fused, at render time.""" +def spec_options(kernel, name): + """The backend_options carrying `kernel`'s spec; its meta is kept as kernel._npu_meta.""" from pytorchsim.backend import compiler_input - old = repr(kernel.triton_meta) - if src_code.count(f"triton_meta={old}") != 1: - raise SpecIncomplete(f"{kernel.__class__.__name__}: triton_meta is not in the source once; " - f"Inductor's decorator changed") - options = compiler_input.backend_options(compiler_input.spec_json(meta)) - new = repr({**kernel.triton_meta, "backend_options": options}) - return src_code.replace(f"triton_meta={old}", f"triton_meta={new}") + from pytorchsim.frontend.inductor.autotune import graph_prefetch + meta = collect_meta(kernel, name) + meta["graph_prefetch"] = graph_prefetch.statement(kernel, meta["args"]) + kernel._npu_meta = meta + return compiler_input.backend_options(compiler_input.spec_json(meta)) + + +class TemplateTritonMeta(dict): + """A template kernel's triton_meta, where TritonNPUKernel's setter cannot reach: its class is TritonTemplate.kernel_type + (select_algorithm.py:2687, :3121), Inductor's own instances' to choose, and jit_lines only .update()s a pre-set + triton_meta (select_algorithm.py:932-935), which is where the spec joins.""" + + def __init__(self, kernel): + super().__init__() + self._kernel = kernel + + def update(self, *args, **kwargs): + super().update(*args, **kwargs) + self["backend_options"] = spec_options(self._kernel, "") def collect_meta(kernel, kernel_name): diff --git a/pytorchsim/frontend/inductor/codegen/scheduling.py b/pytorchsim/frontend/inductor/codegen/scheduling.py index 0b313dbb..5d87a952 100644 --- a/pytorchsim/frontend/inductor/codegen/scheduling.py +++ b/pytorchsim/frontend/inductor/codegen/scheduling.py @@ -5,7 +5,6 @@ from torch._inductor.codegen.common import BackendFeature from torch._inductor.codegen.triton import TritonKernel, TritonScheduling from torch._inductor.ir import MultiTemplateBuffer -from torch._inductor.select_algorithm import TritonTemplateKernel from torch._inductor.utils import Placeholder, get_fused_kernel_name from torch._inductor.virtualized import V @@ -41,15 +40,16 @@ def _get_candidates(self): out.append(tile) return out or [{}] - def codegen_kernel(self, name=None): - """Inductor's source with the kernel's spec in its triton_meta (kernel_metadata.apply_spec_to_source).""" - src = super().codegen_kernel(name) - if name is not None: - return src - meta = kernel_metadata.collect_meta(self, str(Placeholder.KERNEL_NAME)) - meta["graph_prefetch"] = graph_prefetch.statement(self, meta["args"]) - self._npu_meta = meta - return kernel_metadata.apply_spec_to_source(src, self, meta) + @property + def triton_meta(self): + return self.__dict__.get("_triton_meta") + + @triton_meta.setter + def triton_meta(self, meta): + """Inductor sets triton_meta once its signature is whole; the spec joins it there, before it renders.""" + self.__dict__["_triton_meta"] = meta + if meta is not None: + meta["backend_options"] = kernel_metadata.spec_options(self, str(Placeholder.KERNEL_NAME)) class TritonNPUScheduling(TritonScheduling): @@ -76,6 +76,7 @@ def codegen_node_schedule_with_kernel(self, node_schedule, kernel): def _codegen_single_template(self, kernel, render, template_node, epilogue_nodes, prologue_nodes, *, only_gen_src_code=False): self._codegen_kernel = kernel + kernel.triton_meta = kernel_metadata.TemplateTritonMeta(kernel) return super()._codegen_single_template(kernel, render, template_node, epilogue_nodes, prologue_nodes, only_gen_src_code=only_gen_src_code) @@ -88,10 +89,8 @@ def generate_kernel_code_from_nodes(self, nodes, benchmark_kernel=False, hint_ov kernel = self._codegen_kernel meta = kernel_metadata.collect_meta(kernel, "triton_") meta["graph_prefetch"] = graph_prefetch.statement(kernel, meta["args"]) - loaded = kernel_metadata.apply_spec_to_source(src_code, kernel, meta) \ - if isinstance(kernel, TritonTemplateKernel) else src_code - self._benchmarked[PyCodeCache.write(loaded)[1]] = (src_code, meta) - return loaded + self._benchmarked[PyCodeCache.write(src_code)[1]] = (src_code, meta) + return src_code def can_fuse_vertical(self, node1, node2): """Inductor's answer, and for a template fused with an epilogue or prologue, whether the fused @@ -138,10 +137,6 @@ def define_kernel(self, src_code, node_schedule, kernel): template's source takes the spec of its final form first, and the roles of the arguments are kept by the kernel's name for the launch hooks.""" meta = getattr(kernel, "_npu_meta", None) - if isinstance(kernel, TritonTemplateKernel): - meta = kernel_metadata.collect_meta(kernel, "") - meta["graph_prefetch"] = graph_prefetch.statement(kernel, meta["args"]) - src_code = kernel_metadata.apply_spec_to_source(src_code, kernel, meta) kernel_name = super().define_kernel(src_code, node_schedule, kernel) if meta is not None: kernel_metadata.record_roles(kernel_name, meta) diff --git a/tests/system/test_standard_attachments.py b/tests/system/test_standard_attachments.py new file mode 100644 index 00000000..2338d776 --- /dev/null +++ b/tests/system/test_standard_attachments.py @@ -0,0 +1,40 @@ +"""PyTorchSim attaches to Inductor through its public extension points only (PTB rule 16); one check per +attachment that used to be a text edit or a patch, each failing on the tree that had it.""" +import os +import sys + +import torch +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) +from result_check import check_result + + +def test_spec_rides_in_triton_meta_without_a_text_edit(): + """A generated kernel and a template both reach define_kernel with the spec already in the decorator's + triton_meta, rendered by Inductor itself, and no function edits the source.""" + from pytorchsim.frontend.inductor.codegen import kernel_metadata + from pytorchsim.frontend.inductor.codegen.scheduling import TritonNPUScheduling + + seen = [] + orig = TritonNPUScheduling.define_kernel + + def define(self, src_code, node_schedule, kernel): + seen.append((src_code, kernel.triton_meta)) + return orig(self, src_code, node_schedule, kernel) + + TritonNPUScheduling.define_kernel = define + try: + device = torch.device("npu:0") + torch.compile(dynamic=False)(lambda a, b: a + b)(torch.randn(64, 64).to(device), + torch.randn(64, 64).to(device)) + torch.compile(dynamic=False)(torch.mm)(torch.randn(128, 128).to(device), + torch.randn(128, 128).to(device)) + finally: + TritonNPUScheduling.define_kernel = orig + carried = [("pytorchsim_spec" in src) and ("backend_options" in meta) for src, meta in seen] + check_result("SpecInRenderedMeta", torch.tensor([hasattr(kernel_metadata, "apply_spec_to_source"), + len(seen) >= 2, all(carried)]), + torch.tensor([False, True, True])) + + +if __name__ == "__main__": + test_spec_rides_in_triton_meta_without_a_text_edit() From f6ba1ce7fc9b90ba47e33581693615d48dd690a9 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Mon, 16 Nov 2026 22:49:31 +0900 Subject: [PATCH 04/11] [Frontend] Inductor is attached through its hooks; the patches left name the lines that leave no public route Removed: - AlgorithmSelectorCache.__call__ and benchmark_choices are no longer replaced: benchmark_epilogue_fusion is on only when timing mode autotunes, the TIMED mark is a feedback saver, an external tile that does not compile is refused by a preprocessing function, the untimed-autotune warning is the benchmarker's. - The aten.convolution lowering is no longer wrapped (groups are read off V.graph.current_node), and Inductor's conv2d/conv3d grid functions are left alone. - NPUChoices is a module-level class, without the __module__/__qualname__ rename. Kept, each docstring naming the Inductor lines: - generate_example_value: select_algorithm.py:5995 calls it as a staticmethod and input_gen_fns (:4046) turns multi-template off. - The conv templates' grid attribute: kernel/conv.py names conv2d_template at its call site and passes no grid. - GPU_TYPES.append("npu"): a plain list (utils.py:107) with no registry, read by is_gpu. - The scatter reinplace check: reinplace.inplaceable_ops (reinplace.py:379) has no registration API. - time_module, the epilogue-fusion benchmark: Inductor's harness subtracts a timing of clone_args (triton.py:8340-8349) that launches nothing, which the npu benchmarker answers inf, so every fusion would compare against -inf. test_standard_attachments (SelectionAndConvAreInductors, ConvGroupsOutsideLowering); test_patch_scope's conv grid test reads conv2d_template.grid. --- pytorchsim/backend/config_pick.py | 3 + pytorchsim/backend/template_record.py | 24 ++ pytorchsim/frontend/inductor/__init__.py | 4 +- .../autotune/template_kernel_configs.py | 72 ++---- .../autotune/template_kernel_selection.py | 62 +---- .../frontend/inductor/codegen/scheduling.py | 6 +- .../frontend/inductor/postgrad/scatter.py | 4 +- pytorchsim/frontend/inductor/registration.py | 240 +++++++++--------- tests/system/test_patch_scope.py | 4 +- tests/system/test_standard_attachments.py | 31 +++ 10 files changed, 209 insertions(+), 241 deletions(-) diff --git a/pytorchsim/backend/config_pick.py b/pytorchsim/backend/config_pick.py index 656d4aab..4c202c24 100644 --- a/pytorchsim/backend/config_pick.py +++ b/pytorchsim/backend/config_pick.py @@ -6,6 +6,8 @@ import itertools import threading +from pytorchsim.backend import template_record + _ORDER = itertools.count(1) _STATE = threading.local() @@ -26,6 +28,7 @@ def benchmark(benchmarker, fn, *, warmup, rep, **kwargs): inf when it launched nothing (an extern kernel) or did not simulate.""" from pytorchsim import config if not config.pytorchsim_timing_mode: + template_record.warn_untimed_autotune() return next(_ORDER) * 1e-3 with _measure() as got: fn() diff --git a/pytorchsim/backend/template_record.py b/pytorchsim/backend/template_record.py index 84e12fd4..bc89b2d3 100644 --- a/pytorchsim/backend/template_record.py +++ b/pytorchsim/backend/template_record.py @@ -73,6 +73,30 @@ def keep_recorded(choices): return choices +def refuse_external_that_does_not_compile(choices): + """Inductor's preprocessing step: an external mapping's tile is the only candidate, so its failure to compile is + an error naming the mapping file and the entry, with why.""" + if len(choices) == 1: + ktc = choices[0].annotations.get("ktc") + if ktc is not None and ktc.annotations.get(SOURCE) == EXTERNAL: + m, n, k = ktc.inputs.mnk_hinted() + try: + choices[0].precompile() + except Exception as e: # noqa: BLE001 + raise ValueError(f"{config.codegen_external_mapping_file}: the entry {m}_{n}_{k} -> " + f"{choices[0].description} does not compile on this machine: {e}") from e + return choices + + +def mark_timed(timings, name, input_nodes, choices, *_): + """Inductor's feedback saver: the configs of a timed template that the strategy autotuned are marked TIMED.""" + from pytorchsim.backend import template_timing + if config.pytorchsim_timing_mode and template_timing.times(choices): + for c in choices: + if is_timed(c): + c.annotations["ktc"].annotations[SOURCE] = TIMED + + def record(timings, name, input_nodes, choices, *_): """Inductor's feedback saver: append a timed pick to RECORD_LOG in lookup-table form, keyed the way the choices handler looks it up. Called before any fusion is benchmarked, so this is diff --git a/pytorchsim/frontend/inductor/__init__.py b/pytorchsim/frontend/inductor/__init__.py index d2c3ca35..5590ec3c 100644 --- a/pytorchsim/frontend/inductor/__init__.py +++ b/pytorchsim/frontend/inductor/__init__.py @@ -39,8 +39,8 @@ def _configure_inductor(): inductor_config.max_autotune_gemm_backends = "ATEN,TRITON" if config.pytorchsim_timing_mode else "TRITON" inductor_config.max_autotune_conv_backends = "ATEN,TRITON" inductor_config.triton.autotune_at_compile_time = False - timed = bool(config.pytorchsim_timing_mode) - inductor_config.benchmark_epilogue_fusion = timed + from pytorchsim.backend import template_record + inductor_config.benchmark_epilogue_fusion = bool(config.pytorchsim_timing_mode) and template_record.autotunes() inductor_config.max_epilogue_benchmarked_choices = config.codegen_autotune_template_topk inductor_config.autotune_local_cache = False inductor_config.combo_kernels = False diff --git a/pytorchsim/frontend/inductor/autotune/template_kernel_configs.py b/pytorchsim/frontend/inductor/autotune/template_kernel_configs.py index 38d969f1..05154fed 100644 --- a/pytorchsim/frontend/inductor/autotune/template_kernel_configs.py +++ b/pytorchsim/frontend/inductor/autotune/template_kernel_configs.py @@ -1,8 +1,6 @@ """The configs a template kernel (mm, bmm, addmm, baddbmm, conv) is offered on npu: this machine's mm tiles, for an ungrouped conv those of one tap's GEMM. A conv's groups reach the heuristic -through its lowering and size its grid per group, two patches Inductor has no hook for.""" - -import threading +through the node being lowered and size its grid per group, a template's grid Inductor has no hook for.""" import torch @@ -13,13 +11,13 @@ logger = config.setup_logger() -conv_groups = threading.local() +_CONVOLUTIONS = (torch.ops.aten.convolution, *(getattr(torch.ops.aten.convolution, o) + for o in torch.ops.aten.convolution.overloads())) def install(): - """Apply the two conv patches (Inductor has no hook for either); the heuristics are registered - by registration.py.""" - _record_conv_groups() + """Grid a grouped conv per group (Inductor's conv templates take no grid but the module's); the heuristics are + registered by registration.py.""" _size_grouped_conv_grid_per_group() @@ -148,55 +146,29 @@ def per_group(m, n, k, **kwargs): def conv_groups_now(): - """The groups of the convolution being lowered right now (1 outside one).""" - return getattr(conv_groups, "value", 1) or 1 - - -def _record_conv_groups(): - """Wrap aten.convolution's lowering to record its groups, which narrow the conv heuristic's BLOCK_N - to one group's channels (conv_groups_now).""" - import functools - import inspect - - from torch._inductor import lowering as inductor_lowering - from torch._inductor.kernel import conv as conv_kernel - - sig = inspect.signature(conv_kernel.convolution) - - def wrap(inner): - @functools.wraps(inner) - def convolution(*args, **kwargs): - bound = sig.bind(*args, **kwargs) - bound.apply_defaults() - groups = bound.arguments.get("groups", 1) - prev = getattr(conv_groups, "value", 1) - conv_groups.value = groups if isinstance(groups, int) else 1 - try: - return inner(*args, **kwargs) - finally: - conv_groups.value = prev - - return convolution + """The groups of the aten.convolution being lowered right now (1 outside one): the lowering hands the conv + heuristic its channels, not its groups, so they are read off the node V.graph is lowering.""" + from torch._inductor.virtualized import V - packet = torch.ops.aten.convolution - for key in [packet] + [getattr(packet, o) for o in packet.overloads()]: - inner = inductor_lowering.lowerings.get(key) - if inner is not None: - inductor_lowering.lowerings[key] = wrap(inner) + node = getattr(V.graph, "current_node", None) + if node is None or node.target not in _CONVOLUTIONS: + return 1 + groups = node.kwargs.get("groups", node.args[8] if len(node.args) > 8 else 1) + return groups if isinstance(groups, int) else 1 def _size_grouped_conv_grid_per_group(): - """Grid a grouped convolution over one group's channels, not all of them.""" + """Grid a grouped convolution over one group's channels, not all of them: the two conv templates' grid, an + upstream grid off the npu (the module's own functions are left as they are).""" from torch._inductor.kernel import conv as conv_kernel from torch._inductor.select_algorithm import SymbolicGridFn - orig2d = conv_kernel.conv2d_grid - orig3d = conv_kernel.conv3d_grid + upstream = {"conv2d_template": conv_kernel.conv2d_grid, "conv3d_template": conv_kernel.conv3d_grid} @SymbolicGridFn def conv2d_grid(n, c, h, w, meta, *, cdiv): if not is_lowering_npu(): - return orig2d(n, c, h, w, meta) + return upstream["conv2d_template"](n, c, h, w, meta) groups = meta.get("GROUPS", 1) or 1 return ( cdiv(n * h * w, meta["BLOCK_M"]), @@ -207,7 +179,7 @@ def conv2d_grid(n, c, h, w, meta, *, cdiv): @SymbolicGridFn def conv3d_grid(n, c, d, h, w, meta, *, cdiv): if not is_lowering_npu(): - return orig3d(n, c, d, h, w, meta) + return upstream["conv3d_template"](n, c, d, h, w, meta) groups = meta.get("GROUPS", 1) or 1 return ( cdiv(n * d * h * w, meta["BLOCK_M"]), @@ -215,9 +187,5 @@ def conv3d_grid(n, c, d, h, w, meta, *, cdiv): groups, ) - conv_kernel.conv2d_grid = conv2d_grid - conv_kernel.conv3d_grid = conv3d_grid - for tmpl, fn in ((getattr(conv_kernel, "conv2d_template", None), conv2d_grid), - (getattr(conv_kernel, "conv3d_template", None), conv3d_grid)): - if tmpl is not None: - tmpl.grid = fn + conv_kernel.conv2d_template.grid = conv2d_grid + conv_kernel.conv3d_template.grid = conv3d_grid diff --git a/pytorchsim/frontend/inductor/autotune/template_kernel_selection.py b/pytorchsim/frontend/inductor/autotune/template_kernel_selection.py index 9548877f..c2441662 100644 --- a/pytorchsim/frontend/inductor/autotune/template_kernel_selection.py +++ b/pytorchsim/frontend/inductor/autotune/template_kernel_selection.py @@ -1,7 +1,8 @@ """How a template's config is picked for npu: Inductor's own selection over the choices that compiled, the npu's benchmarker (backend/config_pick.py) ranking them by TOGSim cycles in timing mode and in offered order otherwise; -a recorded pick is the only choice (Inductor's recording hooks). Inductor has no hook for an unread operand or -for fusing only choices timed in cycles, so three AlgorithmSelectorCache methods are wrapped, each Inductor's off npu.""" +a recorded pick is the only choice. Registered through select_algorithm's preprocessing and feedback hooks; Inductor +has no hook for an unread operand, so generate_example_value (select_algorithm.py, called by benchmark_example_value) +alone is replaced, Inductor's off npu.""" import torch @@ -10,63 +11,14 @@ def install(): - """Patch algorithm selection for npu choices: allocate-only examples; no multi-template buffer unless timed. - A recorded pick is the only choice, and a timed one is recorded.""" - from torch._inductor import config as inductor_config + """Register the selection hooks; allocate-only examples for npu operands.""" from torch._inductor import select_algorithm - from torch._inductor.select_algorithm import AlgorithmSelectorCache, NoValidChoicesError + from torch._inductor.select_algorithm import AlgorithmSelectorCache - from pytorchsim.backend import template_timing from pytorchsim.backend import template_record - orig_benchmark = AlgorithmSelectorCache.__dict__["benchmark_choices"].__func__ - orig_call = AlgorithmSelectorCache.__call__ orig_example = AlgorithmSelectorCache.__dict__["generate_example_value"].__func__ - def _choices_are_npu(choices): - return any(is_npu(getattr(c, "layout", None)) for c in choices) - - def benchmark_choices(cls, choices, autotune_args, is_collective=False): - if not _choices_are_npu(choices): - return orig_benchmark(cls, choices, autotune_args, is_collective) - timed = bool(config.pytorchsim_timing_mode) - if timed != inductor_config.benchmark_epilogue_fusion: - raise RuntimeError( - "TORCHSIM_TIMING_MODE changed after pytorchsim was installed: Inductor's " - "epilogue-fusion benchmark follows the mode the process started in") - if not timed: - template_record.warn_untimed_autotune() - timings = orig_benchmark(cls, choices, autotune_args, is_collective) - if timed and template_timing.times(choices): - for c in choices: - if template_record.is_timed(c): - c.annotations["ktc"].annotations[template_record.SOURCE] = template_record.TIMED - return timings - - def __call__(self, name, choices, *args, **kwargs): - """Inductor's selection; a fusion is benchmarked only for choices timed in cycles.""" - if _choices_are_npu(choices) and not template_timing.times(choices): - kwargs["return_multi_template"] = False - try: - return orig_call(self, name, choices, *args, **kwargs) - except NoValidChoicesError: - _refuse_external(choices) - raise - - def _refuse_external(choices): - """An external mapping's tile is the only candidate: its failure to compile is an error naming the - mapping file and the entry, with why.""" - for c in choices: - ktc = getattr(c, "annotations", {}).get("ktc") - if ktc is None or ktc.annotations.get(template_record.SOURCE) != template_record.EXTERNAL: - continue - m, n, k = ktc.inputs.mnk_hinted() - try: - c.precompile() - except Exception as e: # noqa: BLE001 - raise ValueError(f"{config.codegen_external_mapping_file}: the entry {m}_{n}_{k} -> " - f"{c.description} does not compile on this machine: {e}") from e - def generate_example_value(size, stride, device, dtype, extra_size, allocation_size=None): """An unread benchmark operand, allocated rather than sampled.""" @@ -81,9 +33,9 @@ def generate_example_value(size, stride, device, dtype, extra_size, torch.empty(needed, dtype=dtype, device=device), shape, stride) return view if tuple(shape) == tuple(size) else view.as_strided(size, stride) - AlgorithmSelectorCache.benchmark_choices = classmethod(benchmark_choices) - AlgorithmSelectorCache.__call__ = __call__ AlgorithmSelectorCache.generate_example_value = staticmethod( generate_example_value) select_algorithm.add_preprocessing_fn(template_record.keep_recorded) + select_algorithm.add_preprocessing_fn(template_record.refuse_external_that_does_not_compile) + select_algorithm.add_feedback_saver(template_record.mark_timed) select_algorithm.add_feedback_saver(template_record.record) diff --git a/pytorchsim/frontend/inductor/codegen/scheduling.py b/pytorchsim/frontend/inductor/codegen/scheduling.py index 5d87a952..288dc30f 100644 --- a/pytorchsim/frontend/inductor/codegen/scheduling.py +++ b/pytorchsim/frontend/inductor/codegen/scheduling.py @@ -82,9 +82,9 @@ def _codegen_single_template(self, kernel, render, template_node, epilogue_nodes def generate_kernel_code_from_nodes(self, nodes, benchmark_kernel=False, hint_override=None, **kwargs): - """The source Inductor benchmarks a fusion with, without its harness, and its metadata read as - define_kernel reads it (the operand it holds too), kept for benchmark_codegened_module by the path - the source loads from. A template's source takes its spec here, as define_kernel gives it.""" + """The source Inductor benchmarks a fusion with, without its harness (triton.py:8308-8313 launches + it once unmeasured, :8340-8349 subtracts a no-launch benchmark: -inf cycles), its metadata kept for + benchmark_codegened_module by the path the source loads from.""" src_code = super().generate_kernel_code_from_nodes(nodes, False, hint_override, **kwargs) kernel = self._codegen_kernel meta = kernel_metadata.collect_meta(kernel, "triton_") diff --git a/pytorchsim/frontend/inductor/postgrad/scatter.py b/pytorchsim/frontend/inductor/postgrad/scatter.py index bfbdc967..49e12d87 100644 --- a/pytorchsim/frontend/inductor/postgrad/scatter.py +++ b/pytorchsim/frontend/inductor/postgrad/scatter.py @@ -9,8 +9,8 @@ # scatter_chain: a view scatter onto a scatter's result, reinplaced on the npu def install_scatter_chain(): - """A view scatter onto another scatter's result reinplaces on the npu when reinplace may: upstream - writes it functionally unless both are realized, a full copy of x per write.""" + """A view scatter onto another scatter's result reinplaces on the npu: upstream's extra_check (reinplace.py:385, read + at :822/:909 from the inplaceable_ops dict, no registration API) says no unless both are realized.""" from torch._inductor.fx_passes import reinplace scatter = reinplace._generalized_scatter diff --git a/pytorchsim/frontend/inductor/registration.py b/pytorchsim/frontend/inductor/registration.py index a2eb3949..fc2d4be2 100644 --- a/pytorchsim/frontend/inductor/registration.py +++ b/pytorchsim/frontend/inductor/registration.py @@ -20,7 +20,13 @@ from torch._dynamo.device_interface import DeviceInterface from torch._inductor.codegen.common import DeviceOpOverrides +from torch._inductor.choices import InductorChoices +from torch._inductor.lookup_table import LookupTableChoices + from pytorchsim import config +from pytorchsim.backend import template_record +from pytorchsim.frontend.inductor import is_lowering_npu +from pytorchsim.frontend.inductor.autotune import generated_kernel_blocks, template_kernel_configs logger = config.setup_logger() @@ -144,7 +150,8 @@ def _register_triton_gpu(): def _add_gpu_type(): - """Add npu to Inductor's GPU_TYPES, so Triton codegen is chosen for it.""" + """Add npu to GPU_TYPES (torch/_inductor/utils.py:107), a plain list is_gpu reads (:3443; use_triton_template + :1936, scheduler fusion :1497): no registry takes a device there.""" import torch._inductor.utils as inductor_utils if "npu" not in inductor_utils.GPU_TYPES: @@ -229,135 +236,118 @@ def _register_choices(): inductor_config.inductor_choices_class = npu_choices_class() -_NPU_CHOICES = None +class NPUChoices(LookupTableChoices): + """Inductor's lookup-table choices whose npu answers come from autotune/ (template kernels' configs and + recorded picks, generated kernels' reductions); every other device keeps Inductor's.""" + + def uuid(self): + """This class's part of Inductor's cache key: the machine and the picks it hands out.""" + return f"pytorchsim-npu-choices-5-{template_record.graph_digest()}" + + def _finalize_template_configs(self, template_choices, kernel_inputs, templates, op_name, + kwarg_overrides=None): + """An npu template's choices: the external mapping's tile, else a recorded pick (an + autotune strategy's only), else the heuristic's tiles.""" + if getattr(kernel_inputs, "device_type", None) == "npu": + external = self._external_choices(kernel_inputs, templates, op_name) + if external: + return external + if not template_record.autotunes(): + return InductorChoices._finalize_template_configs( + self, template_choices, kernel_inputs, templates, op_name, kwarg_overrides) + return super()._finalize_template_configs( + template_choices, kernel_inputs, templates, op_name, kwarg_overrides) + @staticmethod + def _external_tile_for(kernel_inputs, templates): + """The tile the external mapping states for this npu mm or bmm, or None.""" + from torch._inductor.kernel_inputs import MMKernelInputs + + if getattr(kernel_inputs, "device_type", None) != "npu" or \ + not isinstance(kernel_inputs, MMKernelInputs) or \ + not any(t.uid in template_record.EXTERNAL_TEMPLATES for t in templates): + return None + return template_record.external_tile(*kernel_inputs.mnk_hinted()) + + def _external_choices(self, kernel_inputs, templates, op_name): + """The choice built at the tile the external mapping states for this mm or bmm's + shape, marked external; [] when it states none. A tile this machine cannot build is refused.""" + from pytorchsim.frontend import tiling + + tile = self._external_tile_for(kernel_inputs, templates) + if tile is None: + return [] + uids = [t.uid for t in templates if t.uid in template_record.EXTERNAL_TEMPLATES] + m, n, k = kernel_inputs.mnk_hinted() + legal = [(c.block_m, c.block_n, c.block_k) + for c in tiling.gemm_tiles(m, n, k, kernel_inputs.dtype().itemsize)] + if tile not in legal: + raise ValueError( + f"{config.codegen_external_mapping_file}: {m}_{n}_{k} -> {tile} is no tile this " + f"machine builds (each side a lane multiple times a power of two, A, B and C in " + f"the spad budget); its tiles, largest first: {legal[:8]}") + tm, tn, tk = tile + entry = {"BLOCK_M": tm, "BLOCK_N": tn, "BLOCK_K": tk, "EVEN_K": k % tk == 0} + ktcs = LookupTableChoices._create_lookup_choices( + self, {uid: [entry] for uid in uids}, templates, kernel_inputs, op_name) + for ktc in ktcs: + ktc.annotations[template_record.SOURCE] = template_record.EXTERNAL + logger.info("[select] %s %sx%sx%s: the external mapping's tile %s", op_name, m, n, k, tile) + return ktcs + + def get_template_configs(self, kernel_inputs, templates, op_name, kwarg_overrides=None): + """Inductor's choices of `templates`, an npu mm or addmm offered the resident mm alone where + it holds (mm_resident.templates_for) and the external mapping states no tile for it, its + config marked as planned.""" + from pytorchsim.frontend.inductor.autotune import mm_resident + offered = templates if self._external_tile_for(kernel_inputs, templates) else \ + mm_resident.templates_for(kernel_inputs, templates, op_name) + got = super().get_template_configs(kernel_inputs, offered, op_name, kwarg_overrides) + for c in got: + ktc = c.annotations.get("ktc") + if ktc is not None and ktc.template is mm_resident.mm_resident_template: + ktc.annotations.setdefault(template_record.SOURCE, template_record.PLANNED) + return got + + def get_config_heuristics(self, device_type="cuda"): + if device_type == "npu": + return template_kernel_configs.conv_config_heuristic() + return super().get_config_heuristics(device_type) + + def _get_lookup_table(self): + """This machine's recorded picks; Inductor's own looks only on CUDA.""" + return template_record.lookup_table() -def npu_choices_class(): - """NPUChoices, built once: Inductor's lookup-table choices whose npu answers come from autotune/ - (template kernels' configs and recorded picks, generated kernels' reductions); every other - device keeps Inductor's.""" - global _NPU_CHOICES - if _NPU_CHOICES is not None: - return _NPU_CHOICES - from torch._inductor.choices import InductorChoices - from torch._inductor.lookup_table import LookupTableChoices - - from pytorchsim.backend import template_record - from pytorchsim.frontend.inductor import is_lowering_npu - from pytorchsim.frontend.inductor.autotune import (generated_kernel_blocks, - template_kernel_configs) - - class NPUChoices(LookupTableChoices): - def uuid(self): - """This class's part of Inductor's cache key: the machine and the picks it hands out.""" - return f"pytorchsim-npu-choices-5-{template_record.graph_digest()}" - - def _finalize_template_configs(self, template_choices, kernel_inputs, templates, op_name, - kwarg_overrides=None): - """An npu template's choices: the external mapping's tile, else a recorded pick (an - autotune strategy's only), else the heuristic's tiles.""" - if getattr(kernel_inputs, "device_type", None) == "npu": - external = self._external_choices(kernel_inputs, templates, op_name) - if external: - return external - if not template_record.autotunes(): - return InductorChoices._finalize_template_configs( - self, template_choices, kernel_inputs, templates, op_name, kwarg_overrides) - return super()._finalize_template_configs( - template_choices, kernel_inputs, templates, op_name, kwarg_overrides) + @staticmethod + def _get_device_key(device): + if getattr(device, "type", None) == "npu": + return template_record.device_key() + return LookupTableChoices._get_device_key(device) + + def _create_lookup_choices(self, *args, **kwargs): + """Inductor's choices from the recorded configs, each marked as recorded.""" + ktcs = super()._create_lookup_choices(*args, **kwargs) + for ktc in ktcs: + ktc.annotations[template_record.SOURCE] = template_record.RECORDED + return ktcs - @staticmethod - def _external_tile_for(kernel_inputs, templates): - """The tile the external mapping states for this npu mm or bmm, or None.""" - from torch._inductor.kernel_inputs import MMKernelInputs - - if getattr(kernel_inputs, "device_type", None) != "npu" or \ - not isinstance(kernel_inputs, MMKernelInputs) or \ - not any(t.uid in template_record.EXTERNAL_TEMPLATES for t in templates): - return None - return template_record.external_tile(*kernel_inputs.mnk_hinted()) - - def _external_choices(self, kernel_inputs, templates, op_name): - """The choice built at the tile the external mapping states for this mm or bmm's - shape, marked external; [] when it states none. A tile this machine cannot build is refused.""" - from pytorchsim.frontend import tiling - - tile = self._external_tile_for(kernel_inputs, templates) - if tile is None: - return [] - uids = [t.uid for t in templates if t.uid in template_record.EXTERNAL_TEMPLATES] - m, n, k = kernel_inputs.mnk_hinted() - legal = [(c.block_m, c.block_n, c.block_k) - for c in tiling.gemm_tiles(m, n, k, kernel_inputs.dtype().itemsize)] - if tile not in legal: - raise ValueError( - f"{config.codegen_external_mapping_file}: {m}_{n}_{k} -> {tile} is no tile this " - f"machine builds (each side a lane multiple times a power of two, A, B and C in " - f"the spad budget); its tiles, largest first: {legal[:8]}") - tm, tn, tk = tile - entry = {"BLOCK_M": tm, "BLOCK_N": tn, "BLOCK_K": tk, "EVEN_K": k % tk == 0} - ktcs = LookupTableChoices._create_lookup_choices( - self, {uid: [entry] for uid in uids}, templates, kernel_inputs, op_name) - for ktc in ktcs: - ktc.annotations[template_record.SOURCE] = template_record.EXTERNAL - logger.info("[select] %s %sx%sx%s: the external mapping's tile %s", op_name, m, n, k, tile) - return ktcs - - def get_template_configs(self, kernel_inputs, templates, op_name, kwarg_overrides=None): - """Inductor's choices of `templates`, an npu mm or addmm offered the resident mm alone where - it holds (mm_resident.templates_for) and the external mapping states no tile for it, its - config marked as planned.""" - from pytorchsim.backend import template_record - from pytorchsim.frontend.inductor.autotune import mm_resident - offered = templates if self._external_tile_for(kernel_inputs, templates) else \ - mm_resident.templates_for(kernel_inputs, templates, op_name) - got = super().get_template_configs(kernel_inputs, offered, op_name, kwarg_overrides) - for c in got: - ktc = c.annotations.get("ktc") - if ktc is not None and ktc.template is mm_resident.mm_resident_template: - ktc.annotations.setdefault(template_record.SOURCE, template_record.PLANNED) - return got - - def get_config_heuristics(self, device_type="cuda"): - if device_type == "npu": - return template_kernel_configs.conv_config_heuristic() - return super().get_config_heuristics(device_type) - - def _get_lookup_table(self): - """This machine's recorded picks; Inductor's own looks only on CUDA.""" - return template_record.lookup_table() + @staticmethod + def should_use_persistent_reduction(features, cooperative_reduction): + return generated_kernel_blocks.use_persistent_reduction( + features, + InductorChoices.should_use_persistent_reduction(features, cooperative_reduction)) - @staticmethod - def _get_device_key(device): - if getattr(device, "type", None) == "npu": - return template_record.device_key() - return LookupTableChoices._get_device_key(device) - - def _create_lookup_choices(self, *args, **kwargs): - """Inductor's choices from the recorded configs, each marked as recorded.""" - ktcs = super()._create_lookup_choices(*args, **kwargs) - for ktc in ktcs: - ktc.annotations[template_record.SOURCE] = template_record.RECORDED - return ktcs + def reduction_split_factor(self, device, reduction_numel_hint, numel_hint, inner_reduction): + upstream = functools.partial(super().reduction_split_factor, device, + reduction_numel_hint, numel_hint, inner_reduction) + if getattr(device, "type", device) != "npu": + return upstream() + return generated_kernel_blocks.reduction_split(reduction_numel_hint, numel_hint, + upstream) - @staticmethod - def should_use_persistent_reduction(features, cooperative_reduction): - return generated_kernel_blocks.use_persistent_reduction( - features, - InductorChoices.should_use_persistent_reduction(features, cooperative_reduction)) - - def reduction_split_factor(self, device, reduction_numel_hint, numel_hint, inner_reduction): - upstream = functools.partial(super().reduction_split_factor, device, - reduction_numel_hint, numel_hint, inner_reduction) - if getattr(device, "type", device) != "npu": - return upstream() - return generated_kernel_blocks.reduction_split(reduction_numel_hint, numel_hint, - upstream) - - NPUChoices.__module__ = __name__ - NPUChoices.__qualname__ = "NPUChoices" - globals()["NPUChoices"] = NPUChoices - _NPU_CHOICES = NPUChoices + +def npu_choices_class(): + """NPUChoices, the class registered as Inductor's choices.""" return NPUChoices diff --git a/tests/system/test_patch_scope.py b/tests/system/test_patch_scope.py index a6049ba4..81fcc611 100644 --- a/tests/system/test_patch_scope.py +++ b/tests/system/test_patch_scope.py @@ -55,8 +55,8 @@ def test_conv_grid_is_upstream_off_device(): import torch._inductor.kernel.conv as conv_kernel meta = {"BLOCK_M": 64, "BLOCK_N": 128, "GROUPS": 4} - got = torch.tensor(list(conv_kernel.conv2d_grid(2, 256, 8, 8, meta)) - + list(conv_kernel.conv3d_grid(2, 256, 4, 8, 8, meta))) + got = torch.tensor(list(conv_kernel.conv2d_template.grid(2, 256, 8, 8, meta)) + + list(conv_kernel.conv3d_template.grid(2, 256, 4, 8, 8, meta))) check_result("ConvGridOffDevice", got, torch.tensor([2, 2, 4, 8, 2, 4])) diff --git a/tests/system/test_standard_attachments.py b/tests/system/test_standard_attachments.py index 2338d776..e240fce4 100644 --- a/tests/system/test_standard_attachments.py +++ b/tests/system/test_standard_attachments.py @@ -36,5 +36,36 @@ def define(self, src_code, node_schedule, kernel): torch.tensor([False, True, True])) +def test_selection_and_conv_are_inductors_own_but_for_the_operand_and_grid(): + """Inductor's selection (__call__, benchmark_choices), its convolution lowering and its conv grid functions are + its own objects; the npu's choices class is importable under its own name without a rename.""" + import inspect + + import torch._inductor.kernel.conv as conv_kernel + from torch._inductor import lowering + from torch._inductor.select_algorithm import AlgorithmSelectorCache + + from pytorchsim.frontend.inductor import registration + + inductor = "torch._inductor" + own = [AlgorithmSelectorCache.__call__.__module__.startswith(inductor), + AlgorithmSelectorCache.benchmark_choices.__func__.__module__.startswith(inductor), + inductor in lowering.lowerings[torch.ops.aten.convolution.default].__code__.co_filename.replace("/", "."), + conv_kernel.conv2d_grid.fn.__module__.startswith(inductor), + conv_kernel.conv3d_grid.fn.__module__.startswith(inductor), + "__qualname__ =" not in inspect.getsource(registration)] + check_result("SelectionAndConvAreInductors", torch.tensor(own), torch.tensor([True] * len(own))) + + +def test_conv_groups_are_read_off_the_node_being_lowered(): + """The conv heuristic sees a grouped convolution's groups through V.graph's node, and 1 outside a lowering.""" + from pytorchsim.frontend.inductor.autotune import template_kernel_configs + + check_result("ConvGroupsOutsideLowering", torch.tensor([template_kernel_configs.conv_groups_now()]), + torch.tensor([1])) + + if __name__ == "__main__": test_spec_rides_in_triton_meta_without_a_text_edit() + test_selection_and_conv_are_inductors_own_but_for_the_operand_and_grid() + test_conv_groups_are_read_off_the_node_being_lowered() From ca18afdb9a58d151cf4c00548ff01b178c2be5c0 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Mon, 16 Nov 2026 22:49:31 +0900 Subject: [PATCH 05/11] [Backend] Hand-written kernels are offered a config per candidate tile: topk, grouped_mm, megablox, fused attention autotuned(kernel, configs) wraps a kernel with one triton.Config per dict of constexprs; tiling.candidate_sizes takes a floor and candidate_tiles halves several blocks together, each held at its floor. Each config carries what its block sets (padding, masks), so they follow the block. - topk: XBLOCK and its halves; a row stays whole. - grouped_mm: the machine's top three (BN, BK) mm tiles; BM stays the lanes; KP and the N grid follow the config. - megablox grouped_mm: torch_xla's TM (the visit table is counted in it); BN and BK halved together down to the lanes. - fused attention prefill: BQ and BKV halved together (LP, SP, QROWS, KEYS ride along); decode and paged decode: the KV step down to the register rows (SP, KV0, KEYS). - sort is not offered candidates: D fixes the block of four kernels and the merge launches Python schedules, which autotune cannot keep in agreement (Sort.plan). Tests (tests/small_machine.py gives a tpuv6e with a smaller scratchpad; tpuv3_32x32 has no matrix unit): test_topk_candidate_overflow, test_grouped_mm_candidate_overflow, test_grouped_mm_megablox_candidate_overflow, test_attention_candidate_overflow, test_attention_paged_candidate_overflow: the first config raises OutOfResources, a smaller one compiles, values match the CPU; each dies with NoTritonConfigsError before. test_grouped_mm_megablox_large records a failure present before this change: K = N = 1024 stops Spike in the output's zero-fill kernel. --- pytorchsim/frontend/dispatcher/attention.py | 63 ++++++++++++----- .../dispatcher/attention_paged_kvcache.py | 12 ++-- .../dispatcher/custom_fused_kernel.py | 10 +-- .../frontend/dispatcher/depthwise_conv.py | 2 +- pytorchsim/frontend/dispatcher/grouped_mm.py | 36 ++++++---- .../dispatcher/grouped_mm_megablox.py | 16 +++-- pytorchsim/frontend/dispatcher/sort.py | 4 +- pytorchsim/frontend/dispatcher/topk.py | 11 +-- pytorchsim/frontend/tiling.py | 22 ++++-- .../test_attention_candidate_overflow.py | 69 +++++++++++++++++++ ...test_attention_paged_candidate_overflow.py | 44 ++++++++++++ .../conv/test_depthwise_candidate_overflow.py | 1 + tests/ops/gemm/test_grouped_mm.py | 5 +- .../test_grouped_mm_candidate_overflow.py | 66 ++++++++++++++++++ ..._grouped_mm_megablox_candidate_overflow.py | 62 +++++++++++++++++ .../gemm/test_grouped_mm_megablox_large.py | 26 +++++++ .../ops/sort/test_topk_candidate_overflow.py | 52 ++++++++++++++ tests/small_machine.py | 58 ++++++++++++++++ 18 files changed, 499 insertions(+), 60 deletions(-) create mode 100644 tests/ops/attention/test_attention_candidate_overflow.py create mode 100644 tests/ops/attention/test_attention_paged_candidate_overflow.py create mode 100644 tests/ops/gemm/test_grouped_mm_candidate_overflow.py create mode 100644 tests/ops/gemm/test_grouped_mm_megablox_candidate_overflow.py create mode 100644 tests/ops/gemm/test_grouped_mm_megablox_large.py create mode 100644 tests/ops/sort/test_topk_candidate_overflow.py create mode 100644 tests/small_machine.py diff --git a/pytorchsim/frontend/dispatcher/attention.py b/pytorchsim/frontend/dispatcher/attention.py index 234f42a9..3ac2ae5d 100644 --- a/pytorchsim/frontend/dispatcher/attention.py +++ b/pytorchsim/frontend/dispatcher/attention.py @@ -12,8 +12,9 @@ from triton.language.extra import libdevice from pytorchsim import config +from pytorchsim.frontend import tiling from pytorchsim.frontend.dispatcher.custom_fused_kernel import ( - CustomFusedKernel, Decline, fits_scratchpad, next_pow2) + CustomFusedKernel, Decline, autotuned, fits_scratchpad, next_pow2) ATTENTION = "torchsim::attention" ATTENTION_SCHEMA = ("attention(Tensor query, Tensor key, Tensor value, float scale, bool is_causal=True, " @@ -55,21 +56,21 @@ def launch(self, plan, query: torch.Tensor, key: torch.Tensor, value: torch.Tens if plan["kernel"] is _decode_kernel: q, k, v = query.contiguous(), key.contiguous(), value.contiguous() o = q.new_empty(B, Hq, L, DV) - kv0 = (S - window) // plan["BKV"] * plan["BKV"] if window else 0 m, kind, mstride = _bias_as_strides(attn_bias, (B, Hq, L, S)) - wrap_triton(_decode_kernel)[(B * H, 1, 1)]( - q, k, v, o, m, H, Hq // H, plan["GP"], S, plan["SP"], D, plan["DA"], plan["DB"], - plan["DV"], DV, plan["BKV"], scale, softcap, window, kv0, - plan["KEYS"], plan["DW"], plan["VW"], kind, mstride[0], mstride[1], mstride[3]) + wrap_triton(autotuned(_decode_kernel, plan["CONFIGS"]))[(B * H, 1, 1)]( + q, k, v, o, m, HKV=H, G=Hq // H, GP=plan["GP"], S=S, D=D, DA=plan["DA"], DB=plan["DB"], + DV=plan["DV"], DVT=DV, SCALE=scale, SOFTCAP=softcap, WINDOW=window, DW=plan["DW"], + VW=plan["VW"], MKIND=kind, MB=mstride[0], MH=mstride[1], MK=mstride[3]) return o q, k, v = (t if t.stride(-1) == 1 else t.contiguous() for t in (query, key, value)) o = q.new_empty(B, Hq, L, DV) m, kind, mstride = _bias_as_strides(attn_bias, (B, Hq, L, S)) - wrap_triton(_prefill_kernel)[(B * Hq, 1, 1)]( - q, k, v, o, m, Hq, Hq // H, plan["LP"], plan["SP"], plan["DA"], plan["DB"], plan["DV"], - plan["BQ"], plan["BKV"], is_causal, scale, softcap, window, - plan["QROWS"], plan["KEYS"], plan["DW"], plan["VW"], kind, - *q.stride()[:3], *k.stride()[:3], *v.stride()[:3], *o.stride()[:3], *mstride) + qs, ks, vs, os_ = q.stride()[:3], k.stride()[:3], v.stride()[:3], o.stride()[:3] + wrap_triton(autotuned(_prefill_kernel, plan["CONFIGS"]))[(B * Hq, 1, 1)]( + q, k, v, o, m, HQ=Hq, G=Hq // H, DA=plan["DA"], DB=plan["DB"], DV=plan["DV"], CAUSAL=is_causal, + SCALE=scale, SOFTCAP=softcap, WINDOW=window, DW=plan["DW"], VW=plan["VW"], MKIND=kind, + QB=qs[0], QH=qs[1], QS=qs[2], KB=ks[0], KH=ks[1], KS=ks[2], VB=vs[0], VH=vs[1], VS=vs[2], + OB=os_[0], OH=os_[1], OS=os_[2], MB=mstride[0], MH=mstride[1], MQ=mstride[2], MK=mstride[3]) return o def fallback(self, query, key, value, attn_bias, dropout_p, is_causal, scale, window, softcap): @@ -376,11 +377,16 @@ def _choose_head_split(D, rows): return min(_enumerate_head_splits(D, rows), key=lambda s: (s[0] + s[1], 1 if s[1] else 0, -s[0])) +def _prefill_cap(n, rows): + """The most rows of a block over an extent of `n`: SPLASH_BLOCK, or what covers it.""" + return min(SPLASH_BLOCK, max(rows, next_pow2(n))) + + def _choose_prefill_blocks(L, S, DP, DVP, esize, causal, extra, rows): """BQ over L and BKV over S, each a power of two from min(SPLASH_BLOCK, what covers it) down to one row a lane, halved together until one query block's tiles fit the scratchpad; None when none does.""" lanes = int(config.CONFIG_MACHINE.vector_lanes) - qcap, kcap = (min(SPLASH_BLOCK, max(rows, next_pow2(n))) for n in (L, S)) + qcap, kcap = _prefill_cap(L, rows), _prefill_cap(S, rows) qfloor, kfloor = min(qcap, lanes), min(kcap, lanes) for t in range(max(qcap // qfloor, kcap // kfloor).bit_length()): bq, bkv = max(qfloor, qcap >> t), max(kfloor, kcap >> t) @@ -461,17 +467,36 @@ def fused_plan(query, key, value, is_causal, window=0, softcap=0.0, masked=False BKV = _choose_decode_step(GP, S, DA + DB, DVP, esize, extra + (0 if exact else 2), rows) if BKV is None: return Decline(f"a KV step of {rows} overruns the scratchpad budget") - SP = -(-S // BKV) * BKV - return {"kernel": _decode_kernel, "GP": GP, "BKV": BKV, "DA": DA, "DB": DB, "DV": DVP, - "SP": SP, **_padding_masks(1, 1, S, SP, D, DA + DB, DV, DVP)} + configs = [_decode_config(bkv, S, window, D, DA + DB, DV, DVP) + for bkv in tiling.candidate_sizes(BKV, floor=rows)] + return {"kernel": _decode_kernel, "GP": GP, "DA": DA, "DB": DB, "DV": DVP, "CONFIGS": configs, + **configs[0], **_padding_masks(1, 1, S, configs[0]["SP"], D, DA + DB, DV, DVP)} extra += 0 if exact and _is_p2(L) and L >= rows else 2 blocks = _choose_prefill_blocks(L, S, DA + DB, DVP, esize, is_causal, extra, rows) if blocks is None: return Decline(f"no query block of L {L} over S {S} fits the scratchpad budget") - BQ, BKV = blocks - LP, SP = -(-L // BQ) * BQ, -(-S // BKV) * BKV - return {"kernel": _prefill_kernel, "BQ": BQ, "BKV": BKV, "DA": DA, "DB": DB, "DV": DVP, - "LP": LP, "SP": SP, **_padding_masks(L, LP, S, SP, D, DA + DB, DV, DVP)} + floors = {"BQ": min(_prefill_cap(L, rows), int(config.CONFIG_MACHINE.vector_lanes)), + "BKV": min(_prefill_cap(S, rows), int(config.CONFIG_MACHINE.vector_lanes))} + configs = [_prefill_config(t["BQ"], t["BKV"], L, S, D, DA + DB, DV, DVP) + for t in tiling.candidate_tiles({"BQ": blocks[0], "BKV": blocks[1]}, floors)] + return {"kernel": _prefill_kernel, "DA": DA, "DB": DB, "DV": DVP, "CONFIGS": configs, **configs[0], + **_padding_masks(L, configs[0]["LP"], S, configs[0]["SP"], D, DA + DB, DV, DVP)} + + +def _decode_config(bkv, S, window, D, DK, DV, DVP): + """What one KV step `bkv` sets of _decode_kernel's constexprs: the steps' keys padded to SP, the keys masked + back to KEYS, and the window's first block.""" + sp = -(-S // bkv) * bkv + return {"BKV": bkv, "SP": sp, "KV0": (S - window) // bkv * bkv if window else 0, + "KEYS": _padding_masks(1, 1, S, sp, D, DK, DV, DVP)["KEYS"]} + + +def _prefill_config(bq, bkv, L, S, D, DK, DV, DVP): + """What blocks `bq` and `bkv` set of _prefill_kernel's constexprs: L and S padded to LP and SP, and the rows + and keys masked back to QROWS and KEYS.""" + lp, sp = -(-L // bq) * bq, -(-S // bkv) * bkv + masks = _padding_masks(L, lp, S, sp, D, DK, DV, DVP) + return {"BQ": bq, "BKV": bkv, "LP": lp, "SP": sp, "QROWS": masks["QROWS"], "KEYS": masks["KEYS"]} def _math(query, key, value, attn_bias=None, dropout_p=0.0, is_causal=False, *, scale=None): diff --git a/pytorchsim/frontend/dispatcher/attention_paged_kvcache.py b/pytorchsim/frontend/dispatcher/attention_paged_kvcache.py index 50c3e6e3..ed6921d7 100644 --- a/pytorchsim/frontend/dispatcher/attention_paged_kvcache.py +++ b/pytorchsim/frontend/dispatcher/attention_paged_kvcache.py @@ -9,6 +9,7 @@ import triton.language as tl from torch.library import wrap_triton +from pytorchsim.frontend.dispatcher.custom_fused_kernel import autotuned from pytorchsim.frontend.dispatcher.attention import FusedSDPA, _attend, _bias_as_strides, _decode_kernel @@ -26,12 +27,13 @@ def launch(self, plan, query: torch.Tensor, key: torch.Tensor, value: torch.Tens k, v = (t if t.stride(-1) == 1 else t.contiguous() for t in (key, value)) q = query.contiguous() o = q.new_empty(B, Hq, L, DV) - kv0 = (S - window) // plan["BKV"] * plan["BKV"] if window else 0 m, kind, mstride = _bias_as_strides(attn_bias, (B, Hq, L, S)) - wrap_triton(_paged_decode_kernel)[(B, 1, 1)]( - q, k, v, o, m, H, Hq // H, plan["GP"], S, D, plan["DA"], D - plan["DA"], DV, plan["BKV"], - scale, softcap, window, kv0, plan["KEYS"], plan["DW"], plan["VW"], - *k.stride()[:3], *v.stride()[:3], kind, mstride[0], mstride[1], mstride[3]) + configs = [{n: v for n, v in c.items() if n != "SP"} for c in plan["CONFIGS"]] + ks, vs = k.stride()[:3], v.stride()[:3] + wrap_triton(autotuned(_paged_decode_kernel, configs))[(B, 1, 1)]( + q, k, v, o, m, HKV=H, G=Hq // H, GP=plan["GP"], S=S, D=D, DA=plan["DA"], DB=D - plan["DA"], DV=DV, + SCALE=scale, SOFTCAP=softcap, WINDOW=window, DW=plan["DW"], VW=plan["VW"], KB=ks[0], KH=ks[1], + KS=ks[2], VB=vs[0], VH=vs[1], VS=vs[2], MKIND=kind, MB=mstride[0], MH=mstride[1], MK=mstride[3]) return o diff --git a/pytorchsim/frontend/dispatcher/custom_fused_kernel.py b/pytorchsim/frontend/dispatcher/custom_fused_kernel.py index b4cb23ec..27b418af 100644 --- a/pytorchsim/frontend/dispatcher/custom_fused_kernel.py +++ b/pytorchsim/frontend/dispatcher/custom_fused_kernel.py @@ -121,14 +121,14 @@ def _count(self, route): _AUTOTUNED = {} -def autotuned(kernel, name, sizes): - """`kernel` offered to Inductor with a config per size of its constexpr `name`, largest first: Triton's own +def autotuned(kernel, configs): + """`kernel` offered to Inductor with a config per dict of constexprs in `configs`, largest first: Triton's own autotune, whose configs the compile drops one by one when they overflow the scratchpad.""" import triton - key = (kernel, name, tuple(sizes)) + key = (kernel, tuple(tuple(sorted(c.items())) for c in configs)) if key not in _AUTOTUNED: - _AUTOTUNED[key] = triton.autotune(configs=[triton.Config({name: s}, num_warps=1, num_stages=1) - for s in sizes], key=[])(kernel) + _AUTOTUNED[key] = triton.autotune(configs=[triton.Config(dict(c), num_warps=1, num_stages=1) + for c in configs], key=[])(kernel) return _AUTOTUNED[key] diff --git a/pytorchsim/frontend/dispatcher/depthwise_conv.py b/pytorchsim/frontend/dispatcher/depthwise_conv.py index 16526980..c78bcf53 100644 --- a/pytorchsim/frontend/dispatcher/depthwise_conv.py +++ b/pytorchsim/frontend/dispatcher/depthwise_conv.py @@ -49,7 +49,7 @@ def launch(self, plan, x: torch.Tensor, w: torch.Tensor, bias: Optional[torch.Te wo = _out_size(wd, kw, stride[1], padding[1], dilation[1]) out = x.new_empty(n, c, ho, wo) b = bias if bias is not None else w.new_zeros(c) - kernel = autotuned(_depthwise_kernel, "BC", tiling.candidate_sizes(plan["BC"])) + kernel = autotuned(_depthwise_kernel, [{"BC": s} for s in tiling.candidate_sizes(plan["BC"])]) wrap_triton(kernel)[lambda meta: (n * triton.cdiv(c, meta["BC"]), ho, 1)]( x.contiguous(), w.contiguous(), b, out, c, h, wd, ho, wo, kh, kw, stride[0], stride[1], padding[0], padding[1], dilation[0], dilation[1], BW=plan["BW"]) diff --git a/pytorchsim/frontend/dispatcher/grouped_mm.py b/pytorchsim/frontend/dispatcher/grouped_mm.py index 08b0cbb0..cc50dee3 100644 --- a/pytorchsim/frontend/dispatcher/grouped_mm.py +++ b/pytorchsim/frontend/dispatcher/grouped_mm.py @@ -10,7 +10,8 @@ from torch.library import wrap_triton from pytorchsim import config -from pytorchsim.frontend.dispatcher.custom_fused_kernel import CustomFusedKernel, Decline +from pytorchsim.frontend import tiling +from pytorchsim.frontend.dispatcher.custom_fused_kernel import CustomFusedKernel, Decline, autotuned class GroupedMM(CustomFusedKernel): @@ -26,7 +27,8 @@ def arguments(self, op, a, b, offs=None, bias=None, out_dtype=None): return a, b, offs, bias, out_dtype def plan(self, a, b, offs, bias, out_dtype): - """(BM, BN, BK) for 2-D A times 3-D B grouped by offs, in one dtype, with no bias.""" + """(BM, BN, BK) for 2-D A times 3-D B grouped by offs, in one dtype, with no bias; "TILES" is its ranked + (BN, BK) list, which the launch offers as configs (BM stays the lanes: a row block is a lane multiple).""" if a.dim() != 2 or b.dim() != 3 or offs is None: return Decline(f"A {a.dim()}-D, B {b.dim()}-D, offs {'given' if offs is not None else 'none'} " "(it takes 2-D x 3-D)") @@ -34,22 +36,23 @@ def plan(self, a, b, offs, bias, out_dtype): return Decline("a bias or another out_dtype") if a.dtype != b.dtype: return Decline(f"A {a.dtype} and B {b.dtype}") - tiles = _tiles(b.shape[2], a.shape[1], a.element_size(), -(-a.shape[0] // min(b.shape[0], a.shape[0]))) + tiles = _rank_tiles(b.shape[2], a.shape[1], a.element_size(), -(-a.shape[0] // min(b.shape[0], a.shape[0]))) if tiles is None: return Decline(f"no mm tile of {config.CONFIG_MACHINE.vector_lanes} rows fits the scratchpad") - bm, bn, bk = tiles - return {"BM": bm, "BN": bn, "BK": bk} + bm = int(config.CONFIG_MACHINE.vector_lanes) + return {"BM": bm, "BN": tiles[0][0], "BK": tiles[0][1], "TILES": tiles} def launch(self, plan, a: torch.Tensor, b: torch.Tensor, offs: Optional[torch.Tensor], bias: Optional[torch.Tensor], out_dtype: Optional[torch.dtype]) -> torch.Tensor: s, k = a.shape g, _, n = b.shape - bm, bn, bk = plan["BM"], plan["BN"], plan["BK"] programs = min(g, s) c = a.new_empty(s, n) - wrap_triton(_grouped_mm_kernel)[(programs, triton.cdiv(n, bn), 1)]( + kernel = autotuned(_grouped_mm_kernel, [{"BN": bn, "BK": bk, "KP": triton.cdiv(k, bk) * bk} + for bn, bk in plan["TILES"]]) + wrap_triton(kernel)[lambda meta: (programs, triton.cdiv(n, meta["BN"]), 1)]( a.contiguous(), b, _groups(offs, programs), offs, c, b.stride(0), b.stride(1), b.stride(2), - k, triton.cdiv(k, bk) * bk, n, g, bm, bn, bk) + k, N=n, G=g, BM=plan["BM"]) return c def fallback(self, a, b, offs, bias, out_dtype): @@ -63,10 +66,10 @@ def install(): GROUPED_MM.install() -def _tiles(n, k, esize, rows): - """(BM, BN, BK) of the machine's mm tiles for BM = lanes, ranked: all of K first (each weight read once), then - the fewest N tiles where a group of `rows` rows is one row block, else no masked columns first; None for none.""" - from pytorchsim.frontend import tiling +def _rank_tiles(n, k, esize, rows): + """The (BN, BK) of the machine's mm tiles for BM = lanes, best first (at most CANDIDATE_LIMIT): all of K first + (each weight read once), then the fewest N tiles where a group of `rows` rows is one row block, else no masked + columns first; None for none.""" bm = int(config.CONFIG_MACHINE.vector_lanes) acc = 4 tiles = tiling.gemm_tile_candidates(bm, n, k, acc + esize, esize) @@ -75,8 +78,13 @@ def _tiles(n, k, esize, rows): blocks = lambda t: -(-n // t[1]) one = rows <= bm rank = lambda t: (t[2] < k, blocks(t) if one else n % t[1] != 0, n % t[1] != 0 if one else blocks(t)) - _, tn, tk = min(tiles, key=rank) - return bm, tn, tk + return [(tn, tk) for _, tn, tk in sorted(tiles, key=rank)[:tiling.CANDIDATE_LIMIT]] + + +def _tiles(n, k, esize, rows): + """(BM, BN, BK) of the best of _rank_tiles, None for none.""" + ranked = _rank_tiles(n, k, esize, rows) + return None if not ranked else (int(config.CONFIG_MACHINE.vector_lanes), *ranked[0]) @triton.jit diff --git a/pytorchsim/frontend/dispatcher/grouped_mm_megablox.py b/pytorchsim/frontend/dispatcher/grouped_mm_megablox.py index ce62f693..b6a77466 100644 --- a/pytorchsim/frontend/dispatcher/grouped_mm_megablox.py +++ b/pytorchsim/frontend/dispatcher/grouped_mm_megablox.py @@ -9,7 +9,9 @@ import triton.language as tl from torch.library import wrap_triton -from pytorchsim.frontend.dispatcher.custom_fused_kernel import Decline +from pytorchsim import config +from pytorchsim.frontend import tiling +from pytorchsim.frontend.dispatcher.custom_fused_kernel import Decline, autotuned from pytorchsim.frontend.dispatcher.grouped_mm import GroupedMM, _math #: torch_xla 2.9's gmm tiling (custom_kernel._get_tiling_size_for_gmm_kernel), which both its registered experts @@ -25,7 +27,8 @@ def kernels(self): def plan(self, a, b, offs, bias, out_dtype): """(TM, BN, BK): torch_xla's tiling; TK and TN as the largest power of two within it (triton's blocks), TM - exactly or declined, as the visits are counted in it.""" + exactly or declined, as the visits are counted in it; the launch offers BN and BK and their halves (down to the + lanes) as configs, TM fixed.""" declined = super().plan(a, b, offs, bias, out_dtype) if isinstance(declined, str): return declined @@ -38,12 +41,15 @@ def launch(self, plan, a: torch.Tensor, b: torch.Tensor, offs: Optional[torch.Te bias: Optional[torch.Tensor], out_dtype: Optional[torch.dtype]) -> torch.Tensor: s, k = a.shape g, _, n = b.shape - tm, bn, bk = plan["BM"], plan["BN"], plan["BK"] + tm = plan["BM"] group, tile = _visits(offs, tm, triton.cdiv(s, tm) + g - 1) c = a.new_zeros(s, n) - wrap_triton(_megablox_kernel)[(group.shape[0], triton.cdiv(n, bn), 1)]( + lanes = int(config.CONFIG_MACHINE.vector_lanes) + tiles = tiling.candidate_tiles({"BN": plan["BN"], "BK": plan["BK"]}, {"BN": lanes, "BK": lanes}) + kernel = autotuned(_megablox_kernel, [{**t, "KP": triton.cdiv(k, t["BK"]) * t["BK"]} for t in tiles]) + wrap_triton(kernel)[lambda meta: (group.shape[0], triton.cdiv(n, meta["BN"]), 1)]( a.contiguous(), b, group, tile, offs, c, b.stride(0), b.stride(1), b.stride(2), - s, k, triton.cdiv(k, bk) * bk, n, g, tm, bn, bk) + s, k, N=n, G=g, TM=tm) return c def fallback(self, a, b, offs, bias, out_dtype): diff --git a/pytorchsim/frontend/dispatcher/sort.py b/pytorchsim/frontend/dispatcher/sort.py index 7301dd4b..b1ba4bb0 100644 --- a/pytorchsim/frontend/dispatcher/sort.py +++ b/pytorchsim/frontend/dispatcher/sort.py @@ -33,7 +33,9 @@ def arguments(self, op, x, *args, **kwargs): def plan(self, x, dim, descending): """The [L, D] tile of a row of the last axis padded to n, on L = min(lanes, n) lanes; a row - longer than BLOCK_REGS registers a lane is sorted in blocks of that many and merged.""" + longer than BLOCK_REGS registers a lane is sorted in blocks of that many and merged. D is not offered as + configs: four kernels must agree on it and the merge launches below are scheduled from it, so a declined row + (the estimate here) falls back to the network as aten ops.""" if x.dtype not in _KEYS: return Decline(f"{x.dtype} is not a key the kernel orders") if x.dim() == 0 or x.numel() == 0: diff --git a/pytorchsim/frontend/dispatcher/topk.py b/pytorchsim/frontend/dispatcher/topk.py index 1f9dfca8..4fa25b9d 100644 --- a/pytorchsim/frontend/dispatcher/topk.py +++ b/pytorchsim/frontend/dispatcher/topk.py @@ -7,8 +7,9 @@ from torch.library import wrap_triton from pytorchsim import config +from pytorchsim.frontend import tiling from pytorchsim.frontend.dispatcher.custom_fused_kernel import ( - CustomFusedKernel, Decline, fits_scratchpad, next_pow2) + CustomFusedKernel, Decline, autotuned, fits_scratchpad, next_pow2) class TopK(CustomFusedKernel): @@ -23,7 +24,8 @@ def arguments(self, op, x, k, dim=-1, largest=True, sorted=True): return x, int(k), dim % max(x.dim(), 1), bool(largest) def plan(self, x, k, dim, largest): - """A row per lane, the block halved while its tiles overrun the scratchpad budget.""" + """A row per lane, the block halved while its tiles overrun the scratchpad budget; the launch offers it + and its halves (a row stays whole: K rounds read all of it) as configs the compile may drop.""" if not x.is_floating_point(): return Decline(f"{x.dtype} is not a floating dtype") if x.dim() == 0 or x.numel() == 0: @@ -45,8 +47,9 @@ def launch(self, plan, x: torch.Tensor, k: int, dim: int, rows = x.numel() // E v = torch.empty(*x.shape[:-1], k, dtype=x.dtype, device=x.device) i = torch.empty(*x.shape[:-1], k, dtype=torch.int64, device=x.device) - wrap_triton(_topk_kernel)[(triton.cdiv(rows, plan["XBLOCK"]), 1, 1)]( - x.contiguous(), v, i, rows, E, plan["EP"], k, plan["KP"], plan["XBLOCK"], largest) + kernel = autotuned(_topk_kernel, [{"XBLOCK": b} for b in tiling.candidate_sizes(plan["XBLOCK"])]) + wrap_triton(kernel)[lambda meta: (triton.cdiv(rows, meta["XBLOCK"]), 1, 1)]( + x.contiguous(), v, i, rows, E, plan["EP"], k, plan["KP"], LARGEST=largest) return v, i def fallback(self, x, k, dim, largest): diff --git a/pytorchsim/frontend/tiling.py b/pytorchsim/frontend/tiling.py index 08c528fa..878cf024 100644 --- a/pytorchsim/frontend/tiling.py +++ b/pytorchsim/frontend/tiling.py @@ -154,16 +154,30 @@ def product(tile, keep): return [{**rest, **t} for t in tiles[:CANDIDATE_LIMIT]] -def candidate_sizes(first, limit=CANDIDATE_LIMIT): - """The sizes a hand-written kernel's one block is offered: `first` and its halves, largest first, down to 1, - at most `limit`; each is a config its compile may drop when it overflows.""" +def candidate_sizes(first, limit=CANDIDATE_LIMIT, floor=1): + """The sizes a hand-written kernel's one block is offered: `first` and its halves, largest first, down to + `floor`, at most `limit`; each is a config its compile may drop when it overflows.""" sizes = [] - while first >= 1 and len(sizes) < limit: + while first >= floor and len(sizes) < limit: sizes.append(int(first)) first //= 2 return sizes +def candidate_tiles(first, floors, limit=CANDIDATE_LIMIT): + """The tiles a kernel with several blocks is offered: `first` ({block: size}) and then every block halved + together, each held at its floor, largest first, at most `limit`; a block that cannot halve stays.""" + tiles = [] + t = 0 + while len(tiles) < limit: + tile = {k: min(int(v), max(int(floors.get(k, 1)), int(v) >> t)) for k, v in first.items()} + if tiles and tile == tiles[-1]: + break + tiles.append(tile) + t += 1 + return tiles + + def kept_axis_rows_block(xnumel, rblock, elem_bytes, lanes, lane_bytes, max_numel): """XBLOCK of a reduction along its contiguous axis: rows of `rblock` filling the tile budget the other blocks here take (one lane's, times the lanes), at least the lane cover and no more diff --git a/tests/ops/attention/test_attention_candidate_overflow.py b/tests/ops/attention/test_attention_candidate_overflow.py new file mode 100644 index 00000000..72afad03 --- /dev/null +++ b/tests/ops/attention/test_attention_candidate_overflow.py @@ -0,0 +1,69 @@ +"""The fused attention kernels are offered a config per candidate block (the plan's and its halves); on a 16 KiB-a-lane +tpuv6e (tests/small_machine.py), with the plan's block choice made to take the biggest block (as an estimate that +undercounts would), the prefill's 512 x 512 and the decode's 2048-key step overflow the scratchpad, the Triton backend raises +OutOfResources, Inductor drops them and a smaller block runs, with the CPU's values. Breaks when either kernel is +launched with the one block the plan chose.""" +import os + +os.environ["TORCHINDUCTOR_COMPILE_THREADS"] = "1" + +import sys +from unittest import mock + +import torch + +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) +import small_machine # noqa: E402 + +small_machine.use_machine(16) + + +def _run(q, k, v, causal): + f = torch.compile(lambda a, b, c: torch.nn.functional.scaled_dot_product_attention( + a, b, c, is_causal=causal, enable_gqa=a.shape[1] != b.shape[1]), dynamic=False) + got = f(q.to("npu:0"), k.to("npu:0"), v.to("npu:0")).float().cpu() + rep = q.shape[1] // k.shape[1] + want = torch.nn.functional.scaled_dot_product_attention( + q.float(), k.float().repeat_interleave(rep, 1), v.float().repeat_interleave(rep, 1), is_causal=causal) + return got, want + + +def _qkv(hq, h, l, s, d=128): + g = torch.Generator().manual_seed(0) + return [torch.randn(1, n, t, d, generator=g).to(torch.bfloat16) for n, t in ((hq, l), (h, s), (h, s))] + + +@torch.no_grad() +def test_prefill_first_block_overflows(): + from pytorchsim.frontend.dispatcher import attention + torch._dynamo.reset() + q, k, v = _qkv(1, 1, 512, 512) + with mock.patch.object(attention, "_choose_prefill_blocks", lambda L, S, *a: (512, 512)), \ + small_machine.Outcomes("BQ") as outcomes: + got, want = _run(q, k, v, True) + for cfg, what in outcomes: + print(f"prefill candidate BQ={cfg['BQ']} BKV={cfg['BKV']}: {what}") + assert outcomes[0][0]["BQ"] == 512 and outcomes[0][1].startswith("OutOfResources"), outcomes + assert any(w == "compiled" for _, w in outcomes), outcomes + assert ((got - want).abs().max() / want.abs().max()).item() < 2e-2 + + +@torch.no_grad() +def test_decode_first_step_overflows(): + from pytorchsim.frontend.dispatcher import attention + torch._dynamo.reset() + q, k, v = _qkv(8, 2, 1, 4096) + with mock.patch.object(attention, "_choose_decode_step", lambda *a: 2048), \ + small_machine.Outcomes("BKV") as outcomes: + got, want = _run(q, k, v, False) + for cfg, what in outcomes: + print(f"decode candidate BKV={cfg['BKV']}: {what}") + assert outcomes[0][0]["BKV"] == 2048 and outcomes[0][1].startswith("OutOfResources"), outcomes + assert any(w == "compiled" for _, w in outcomes), outcomes + assert ((got - want).abs().max() / want.abs().max()).item() < 2e-2 + + +if __name__ == "__main__": + test_prefill_first_block_overflows() + test_decode_first_step_overflows() + print("-----------------------------------\n|AttentionCandidateOverflow Test Passed|\n-----------------------------------") diff --git a/tests/ops/attention/test_attention_paged_candidate_overflow.py b/tests/ops/attention/test_attention_paged_candidate_overflow.py new file mode 100644 index 00000000..41fb42f1 --- /dev/null +++ b/tests/ops/attention/test_attention_paged_candidate_overflow.py @@ -0,0 +1,44 @@ +"""The paged decode kernel (TORCHSIM_KVCACHE_LAYOUT=tokenwise) is offered a config per candidate KV step; on a 8 KiB-a-lane +tpuv6e (tests/small_machine.py), with the plan's step choice made to take 2048 keys, that step overflows the scratchpad, +Inductor drops it and a smaller one runs, reading K and V in place, with the CPU's values. Breaks when the kernel is +launched with the one step the plan chose.""" +import os + +os.environ["TORCHINDUCTOR_COMPILE_THREADS"] = "1" +os.environ["TORCHSIM_KVCACHE_LAYOUT"] = "tokenwise" + +import sys +from unittest import mock + +import torch + +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) +import small_machine # noqa: E402 + +small_machine.use_machine(8) + + +@torch.no_grad() +def test_paged_first_step_overflows(hq=8, h=2, s=4096, d=128): + from one_layer import _paged + from pytorchsim.frontend.dispatcher import attention + g = torch.Generator().manual_seed(0) + q, k, v = [torch.randn(1, n, t, d, generator=g).to(torch.bfloat16) for n, t in ((hq, 1), (h, s), (h, s))] + kp, vp = _paged(k.to("npu:0"), v.to("npu:0")) + want = torch.nn.functional.scaled_dot_product_attention( + q.float(), k.float().repeat_interleave(hq // h, 1), v.float().repeat_interleave(hq // h, 1)) + torch._dynamo.reset() + with mock.patch.object(attention, "_choose_decode_step", lambda *a: 2048), \ + small_machine.Outcomes("BKV") as outcomes: + got = torch.compile(lambda a, b, c: torch.nn.functional.scaled_dot_product_attention( + a, b, c, enable_gqa=True), dynamic=False)(q.to("npu:0"), kp, vp).float().cpu() + for cfg, what in outcomes: + print(f"paged candidate BKV={cfg['BKV']}: {what}") + assert outcomes[0][0]["BKV"] == 2048 and outcomes[0][1].startswith("OutOfResources"), outcomes + assert any(w == "compiled" for _, w in outcomes), outcomes + assert ((got - want).abs().max() / want.abs().max()).item() < 2e-2 + print("-----------------------------------\n|PagedAttentionCandidateOverflow Test Passed|\n-----------------------------------") + + +if __name__ == "__main__": + test_paged_first_step_overflows() diff --git a/tests/ops/conv/test_depthwise_candidate_overflow.py b/tests/ops/conv/test_depthwise_candidate_overflow.py index 05675b36..70ffe107 100644 --- a/tests/ops/conv/test_depthwise_candidate_overflow.py +++ b/tests/ops/conv/test_depthwise_candidate_overflow.py @@ -7,6 +7,7 @@ from unittest import mock os.environ["TORCHSIM_TARGET"] = "tpuv3_32x32" +os.environ["TORCHINDUCTOR_COMPILE_THREADS"] = "1" import torch diff --git a/tests/ops/gemm/test_grouped_mm.py b/tests/ops/gemm/test_grouped_mm.py index fe90d7ce..11b99850 100644 --- a/tests/ops/gemm/test_grouped_mm.py +++ b/tests/ops/gemm/test_grouped_mm.py @@ -79,7 +79,8 @@ def case_routed(): def _grids(sizes): - """(relative error, grouped-kernel launches, the grids it launched with) of one compiled call.""" + """(relative error, grouped-kernel launches, the grids it launched with) of one compiled call; a grid that reads + its config (axis 1, the N tiles) is taken at BN 1, axis 0 being the programs of every config.""" from torch._inductor import config as inductor_config from pytorchsim.frontend.dispatcher import grouped_mm grids, real = [], grouped_mm.wrap_triton @@ -89,7 +90,7 @@ def __init__(self, kernel): self.wrapped = real(kernel) def __getitem__(self, grid): - grids.append(tuple(grid)) + grids.append(tuple(grid({"BN": 1}) if callable(grid) else grid)) return self.wrapped[grid] grouped_mm.wrap_triton = _Recorded diff --git a/tests/ops/gemm/test_grouped_mm_candidate_overflow.py b/tests/ops/gemm/test_grouped_mm_candidate_overflow.py new file mode 100644 index 00000000..b71201e5 --- /dev/null +++ b/tests/ops/gemm/test_grouped_mm_candidate_overflow.py @@ -0,0 +1,66 @@ +"""grouped_mm is offered its ranked (BN, BK) tiles as configs. The tile search is made to rank an oversized tile first +(a 1024 x 1024 weight tile on a 16 KiB-a-lane scratchpad, as an estimate that undercounts would): the Triton backend raises +OutOfResources, Inductor drops that config and the next ranked one runs, with the reference's values. Breaks when the +kernel is launched with the one tile plan ranked first.""" +import os + +os.environ["TORCHINDUCTOR_COMPILE_THREADS"] = "1" + +import sys +from unittest import mock + +import torch + +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) +import small_machine # noqa: E402 + +small_machine.use_machine(16) + + +@torch.no_grad() +def test_first_tile_overflows(k=1024, n=1024, sizes=(40, 9, 4)): + from torch._inductor.runtime import triton_heuristics as th + from triton.runtime.errors import OutOfResources + from pytorchsim.frontend import tiling + + outcomes = [] + orig = th.CachingAutotuner._precompile_config + + def spy(self, cfg, **kw): + if "BN" not in cfg.kwargs: + return orig(self, cfg, **kw) + try: + got = orig(self, cfg, **kw) + except OutOfResources as e: + outcomes.append((cfg.kwargs["BN"], f"OutOfResources: {e}")) + raise + outcomes.append((cfg.kwargs["BN"], "compiled")) + return got + + real = tiling.gemm_tile_candidates + greedy = lambda m, n_, k_, c, p: [(m, n_, k_), *real(m, n_, k_, c, p)] + g = torch.Generator().manual_seed(0) + a = (torch.randn(sum(sizes), k, generator=g) * 0.1).to(torch.bfloat16) + b = (torch.randn(len(sizes), k, n, generator=g) * 0.1).to(torch.bfloat16) + offs = torch.cumsum(torch.tensor(sizes, dtype=torch.int32), 0, dtype=torch.int32) + want, lo = [], 0 + for gi, hi in enumerate(offs.tolist()): + want.append(a[lo:hi].float() @ b[gi].float()) + lo = hi + want = torch.cat(want) + torch._dynamo.reset() + with mock.patch.object(tiling, "gemm_tile_candidates", greedy), \ + mock.patch.object(th.CachingAutotuner, "_precompile_config", spy): + got = torch.compile(lambda *t: torch.nn.functional.grouped_mm(t[0], t[1], offs=t[2]), dynamic=False)( + a.to("npu:0"), b.to("npu:0"), offs.to("npu:0")).float().cpu() + for bn, what in outcomes: + print(f"candidate BN={bn}: {what}") + assert outcomes[0][0] == n and outcomes[0][1].startswith("OutOfResources"), outcomes + assert any(w == "compiled" for _, w in outcomes), outcomes + err = ((got - want).abs().max() / want.abs().max()).item() + assert err < 2e-2, err + print("-----------------------------------\n|GroupedMMCandidateOverflow Test Passed|\n-----------------------------------") + + +if __name__ == "__main__": + test_first_tile_overflows() diff --git a/tests/ops/gemm/test_grouped_mm_megablox_candidate_overflow.py b/tests/ops/gemm/test_grouped_mm_megablox_candidate_overflow.py new file mode 100644 index 00000000..028a0c1f --- /dev/null +++ b/tests/ops/gemm/test_grouped_mm_megablox_candidate_overflow.py @@ -0,0 +1,62 @@ +"""The megablox grouped_mm takes torch_xla's tiles (BN = BK = 512 here, TM = 128), no estimate of its own: on a 8 KiB-a-lane +scratchpad the weight tile alone overflows, the Triton backend raises OutOfResources, Inductor drops that config and +the halved BN and BK run, TM kept, with the reference's values. Breaks when the kernel is launched with torch_xla's tile only.""" +import os + +os.environ["TORCHINDUCTOR_COMPILE_THREADS"] = "1" +os.environ["TORCHSIM_GROUPED_MM_STRUCTURE"] = "megablox" + +import sys +from unittest import mock + +import torch + +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) +import small_machine # noqa: E402 + +small_machine.use_machine(8) + + +@torch.no_grad() +def test_megablox_first_tile_overflows(k=512, n=512, sizes=(100, 30, 10)): + from torch._inductor.runtime import triton_heuristics as th + from triton.runtime.errors import OutOfResources + + outcomes = [] + orig = th.CachingAutotuner._precompile_config + + def spy(self, cfg, **kw): + if "BN" not in cfg.kwargs: + return orig(self, cfg, **kw) + try: + got = orig(self, cfg, **kw) + except OutOfResources as e: + outcomes.append((cfg.kwargs["BN"], f"OutOfResources: {e}")) + raise + outcomes.append((cfg.kwargs["BN"], "compiled")) + return got + + g = torch.Generator().manual_seed(0) + a = (torch.randn(sum(sizes), k, generator=g) * 0.1).to(torch.bfloat16) + b = (torch.randn(len(sizes), k, n, generator=g) * 0.1).to(torch.bfloat16) + offs = torch.cumsum(torch.tensor(sizes, dtype=torch.int32), 0, dtype=torch.int32) + want, lo = [], 0 + for gi, hi in enumerate(offs.tolist()): + want.append(a[lo:hi].float() @ b[gi].float()) + lo = hi + want = torch.cat(want) + torch._dynamo.reset() + with mock.patch.object(th.CachingAutotuner, "_precompile_config", spy): + got = torch.compile(lambda *t: torch.nn.functional.grouped_mm(t[0], t[1], offs=t[2]), dynamic=False)( + a.to("npu:0"), b.to("npu:0"), offs.to("npu:0")).float().cpu() + for bn, what in outcomes: + print(f"candidate BN={bn}: {what}") + assert outcomes[0][0] == n and outcomes[0][1].startswith("OutOfResources"), outcomes + assert any(w == "compiled" for _, w in outcomes), outcomes + err = ((got - want).abs().max() / want.abs().max()).item() + assert err < 2e-2, err + print("-----------------------------------\n|MegabloxCandidateOverflow Test Passed|\n-----------------------------------") + + +if __name__ == "__main__": + test_megablox_first_tile_overflows() diff --git a/tests/ops/gemm/test_grouped_mm_megablox_large.py b/tests/ops/gemm/test_grouped_mm_megablox_large.py new file mode 100644 index 00000000..ad7528d2 --- /dev/null +++ b/tests/ops/gemm/test_grouped_mm_megablox_large.py @@ -0,0 +1,26 @@ +"""KNOWN FAILING (found while writing the megablox candidate test): the megablox grouped_mm on tpuv6e, K = N = 1024 +over 3 groups of 100, 30 and 10 rows, stops in Spike on 'User store segfault' at 0x8069e000, in +triton_poi_fused_new_zeros_2 (the output's zero fill, not the megablox kernel); K = N = 256 and 512 run. It fails on the +tree before retiling too. Cause not found.""" +import os + +os.environ["TORCHSIM_GROUPED_MM_STRUCTURE"] = "megablox" + +import torch + + +@torch.no_grad() +def test_megablox_k_n_1024(k=1024, n=1024, sizes=(100, 30, 10)): + g = torch.Generator().manual_seed(0) + a = (torch.randn(sum(sizes), k, generator=g) * 0.1).to(torch.bfloat16) + b = (torch.randn(len(sizes), k, n, generator=g) * 0.1).to(torch.bfloat16) + offs = torch.cumsum(torch.tensor(sizes, dtype=torch.int32), 0, dtype=torch.int32) + want = torch.cat([a[lo:hi].float() @ b[i].float() for i, (lo, hi) in enumerate( + zip([0, *offs.tolist()[:-1]], offs.tolist()))]) + got = torch.compile(lambda *t: torch.nn.functional.grouped_mm(t[0], t[1], offs=t[2]), dynamic=False)( + a.to("npu:0"), b.to("npu:0"), offs.to("npu:0")).float().cpu() + assert ((got - want).abs().max() / want.abs().max()).item() < 2e-2 + + +if __name__ == "__main__": + test_megablox_k_n_1024() diff --git a/tests/ops/sort/test_topk_candidate_overflow.py b/tests/ops/sort/test_topk_candidate_overflow.py new file mode 100644 index 00000000..1659bb7b --- /dev/null +++ b/tests/ops/sort/test_topk_candidate_overflow.py @@ -0,0 +1,52 @@ +"""topk is offered a config per candidate XBLOCK (the plan's rows a program and its halves); on tpuv3_32x32 (16 KiB a +lane) 32 rows of a 1024-wide row with K = 32 overflow the scratchpad, the Triton backend raises OutOfResources, Inductor +drops that config and 16 rows run, with the CPU's values and indices. Breaks when topk launches one fixed XBLOCK.""" +import os +import sys + +os.environ["TORCHSIM_TARGET"] = "tpuv3_32x32" +os.environ["TORCHINDUCTOR_COMPILE_THREADS"] = "1" + +import torch + +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) +from result_check import check_result # noqa: E402 + + +@torch.no_grad() +def test_first_candidate_overflows(rows=64, width=1024, k=32): + from torch._inductor.runtime import triton_heuristics as th + from triton.runtime.errors import OutOfResources + + outcomes = [] + orig = th.CachingAutotuner._precompile_config + + def spy(self, cfg, **kw): + if "XBLOCK" not in cfg.kwargs or "R0_BLOCK" in cfg.kwargs: + return orig(self, cfg, **kw) + try: + got = orig(self, cfg, **kw) + except OutOfResources as e: + outcomes.append((cfg.kwargs["XBLOCK"], f"OutOfResources: {e}")) + raise + outcomes.append((cfg.kwargs["XBLOCK"], "compiled")) + return got + + torch._dynamo.reset() + x = torch.randn(rows, width, generator=torch.Generator().manual_seed(0)) + want = torch.topk(x, k) + orig_patch, th.CachingAutotuner._precompile_config = orig, spy + try: + got = torch.compile(lambda t: torch.topk(t, k), dynamic=False)(x.to("npu:0")) + finally: + th.CachingAutotuner._precompile_config = orig_patch + for xb, what in outcomes: + print(f"candidate XBLOCK={xb}: {what}") + assert outcomes[0][0] == 32 and outcomes[0][1].startswith("OutOfResources"), outcomes + assert (16, "compiled") in outcomes, outcomes + check_result("TopKCandidateOverflow", got[0].cpu(), want.values, 1e-6, 1e-6) + assert torch.equal(got[1].cpu(), want.indices) + + +if __name__ == "__main__": + test_first_candidate_overflows() diff --git a/tests/small_machine.py b/tests/small_machine.py new file mode 100644 index 00000000..06ea879e --- /dev/null +++ b/tests/small_machine.py @@ -0,0 +1,58 @@ +"""use_machine(): TORCHSIM_TARGET as tpuv6e with a smaller scratchpad, written to a temp machine file, for the tests +that need the matrix unit (tpuv3_32x32 has none) and a scratchpad small enough that a candidate tile overflows.""" +import os +import tempfile + +import yaml + + +def use_machine(budget_kb, base="tpuv6e"): + """Point TORCHSIM_TARGET at `base` with budget_kb of scratchpad a lane left for a kernel; call before compiling.""" + os.environ["TORCHSIM_TARGET"] = base + from pytorchsim import config + src = config.CONFIG_MACHINE_FILE + with open(src) as f: + machine = yaml.safe_load(f) + machine["vpu_spad_size_kb_per_lane"] = budget_kb + machine.setdefault("compiler", {})["spad_scoped_kb_per_lane"] = 0 + here = os.path.dirname(src) + for key in ("ramulator_config_path", "booksim_config_path"): + if key in machine: + machine[key] = os.path.normpath(os.path.join(here, machine[key])) + path = os.path.join(tempfile.mkdtemp(prefix="torchsim-machine-"), f"{base}_{budget_kb}kb.yml") + with open(path, "w") as f: + yaml.safe_dump(machine, f) + os.environ["TORCHSIM_TARGET"] = path + return path + + +class Outcomes(list): + """(config kwargs, 'compiled' or the OutOfResources message) of each precompile of a config with `key`, in + order; a context manager, needs TORCHINDUCTOR_COMPILE_THREADS=1 so the precompile runs in this process.""" + + def __init__(self, key): + super().__init__() + self.key = key + + def __enter__(self): + from torch._inductor.runtime import triton_heuristics as th + from triton.runtime.errors import OutOfResources + self.th, self.orig = th, th.CachingAutotuner._precompile_config + outcomes = self + + def spy(this, cfg, **kw): + if outcomes.key not in cfg.kwargs: + return outcomes.orig(this, cfg, **kw) + try: + got = outcomes.orig(this, cfg, **kw) + except OutOfResources as e: + outcomes.append((dict(cfg.kwargs), f"OutOfResources: {e}")) + raise + outcomes.append((dict(cfg.kwargs), "compiled")) + return got + + th.CachingAutotuner._precompile_config = spy + return self + + def __exit__(self, *exc): + self.th.CachingAutotuner._precompile_config = self.orig From d54572df54b892503a4485c2e373c1f92bc71264 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Mon, 16 Nov 2026 22:49:31 +0900 Subject: [PATCH 06/11] [Test] test_mllama --image-size: the vision tower at a size Spike finishes The full 560 image is 6404 vision tokens; its fused attention did not finish on Spike in an hour. --image-size 112 (288 tokens, the same layers) runs in ~5 min. --- tests/models/Llama/test_mllama.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/tests/models/Llama/test_mllama.py b/tests/models/Llama/test_mllama.py index 38c5a87d..618cda72 100644 --- a/tests/models/Llama/test_mllama.py +++ b/tests/models/Llama/test_mllama.py @@ -115,9 +115,9 @@ def _dtype_from_str(name): }.get(name, torch.float32) -def _vision_config(): +def _vision_config(image_size=None): from transformers.models.mllama.configuration_mllama import MllamaVisionConfig - return MllamaVisionConfig(_attn_implementation="sdpa", **VISION) + return MllamaVisionConfig(_attn_implementation="sdpa", **dict(VISION, **({"image_size": image_size} if image_size else {}))) def _text_config(): @@ -127,14 +127,14 @@ def _text_config(): @torch.no_grad() def run_vision(device, batch=1, dtype="bfloat16", compile_model=True, - rtol=None, atol=None): + rtol=None, atol=None, image_size=None): """The vision tower on one image of 4 tiles, CPU against `device`, at `dtype`'s `_TOL` unless given.""" tol = _TOL.get(dtype, _TOL["float32"]) rtol, atol = tol[0] if rtol is None else rtol, tol[1] if atol is None else atol from transformers.models.mllama.modeling_mllama import MllamaVisionModel torch_dtype = _dtype_from_str(dtype) - cfg = _vision_config() + cfg = _vision_config(image_size) torch.manual_seed(0) model_cpu = MllamaVisionModel(cfg).to(dtype=torch_dtype).eval() @@ -240,6 +240,8 @@ def call(m, dev, dtype): parser.add_argument("--seq", type=int, default=32) parser.add_argument("--dtype", type=str, default="bfloat16", choices=["float32", "float16", "bfloat16"]) + parser.add_argument("--image-size", type=int, default=None, + help="vision image size, a multiple of 14 (default: the full 560)") parser.add_argument("--no-compile", dest="compile", action="store_false", default=True) parser.add_argument("--rtol", type=float, default=None, help="default: _TOL of --dtype") parser.add_argument("--atol", type=float, default=None, help="default: _TOL of --dtype") @@ -253,7 +255,8 @@ def call(m, dev, dtype): if args.part in ("vision", "all"): run_vision(device, batch=args.batch, dtype=args.dtype, - compile_model=args.compile, rtol=args.rtol, atol=args.atol) + compile_model=args.compile, rtol=args.rtol, atol=args.atol, + image_size=args.image_size) if args.part in ("text", "all"): run_text(device, batch=args.batch, seq_len=args.seq, dtype=args.dtype, compile_model=args.compile, rtol=args.rtol, atol=args.atol) From 603100cbc5bee2cfc887dabaf5109f5ba9cdeade Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Mon, 16 Nov 2026 22:49:31 +0900 Subject: [PATCH 07/11] [Frontend] Every candidate tile is one Inductor's generated source is correct for, down to a floor Inductor drops an axis's mask when numel is a multiple of ITS max block (4096 on x), and for y only within one y grid (TritonKernel._has_constant_mask). A candidate larger than that, not dividing numel, ran the last program unmasked past the tensor: MobileNet's 401408-element pointwise wrote one past its tensor (Spike segfault), and Yolov5's 3 x 409600 copy was launched past the compiled grid. TritonNPUKernel._is_mask_dropped follows that rule over public facts; on an axis whose mask is dropped a block is cut to numel's largest power-of-two divisor (not skipped, so the list is never empty), and no tile at all raises instead of yielding an empty config (Diffusion's bf16 channels-last silu, ynumel 102400 past one y grid, compiled with YBLOCK None). The spec's grid bounds every candidate: the per-axis maximum over them (_blocks_without_pin), not the last tile's. Candidates halve down to the lanes instead of stopping at three (CANDIDATE_LIMIT 16 caps multi-axis products; the hand-written kernels follow through candidate_sizes / candidate_tiles): Llama 4's gather x sigmoid pointwise overflowed at all three (131072 needs 549408 of 524288; 65536 fits). Tests: test_candidate_mask (MobileNet's shape, Yolov5's copy, the y axis past one grid), test_candidate_floor, test_cat_grid_bound (a cat of two masked halves, which PTB's grid_bound now bounds per access; bf16 tolerance 2e-2). Each fails before. --- .../inductor/codegen/kernel_metadata.py | 9 ++-- .../frontend/inductor/codegen/scheduling.py | 29 +++++++++++- pytorchsim/frontend/tiling.py | 18 ++++--- tests/ops/elementwise/test_candidate_floor.py | 43 +++++++++++++++++ tests/ops/elementwise/test_candidate_mask.py | 47 +++++++++++++++++++ tests/ops/elementwise/test_cat_grid_bound.py | 23 +++++++++ 6 files changed, 156 insertions(+), 13 deletions(-) create mode 100644 tests/ops/elementwise/test_candidate_floor.py create mode 100644 tests/ops/elementwise/test_candidate_mask.py create mode 100644 tests/ops/elementwise/test_cat_grid_bound.py diff --git a/pytorchsim/frontend/inductor/codegen/kernel_metadata.py b/pytorchsim/frontend/inductor/codegen/kernel_metadata.py index 47dcc8bf..e721eb23 100644 --- a/pytorchsim/frontend/inductor/codegen/kernel_metadata.py +++ b/pytorchsim/frontend/inductor/codegen/kernel_metadata.py @@ -121,13 +121,14 @@ def _held_blocks(kernel): def _blocks_without_pin(kernel, numels, args): - """Blocks for a kernel holding none: a TritonNPUKernel's smallest candidate tile, the one that - launches the most programs (the grid its spec states bounds every candidate's); a template's from - its numels and args alone.""" + """Blocks for a kernel holding none: a TritonNPUKernel's smallest block per axis over its candidates, so + the grid its spec states is the most programs any candidate launches there; a template's from its + numels and args alone.""" from pytorchsim.frontend.inductor.codegen.scheduling import TritonNPUKernel if isinstance(kernel, TritonNPUKernel) and all(isinstance(v, int) for v in numels.values()): tiles = candidates_for(kernel.numels, kernel.features) - tile = tiles[-1] if tiles else blocks_for(numels, kernel.features) + tile = {k: min(t[k] for t in tiles if k in t) for k in {k for t in tiles for k in t}} \ + if tiles else blocks_for(numels, kernel.features) return {**tile, "XBLOCK": 1} if kernel.no_x_dim else tile return tiling.fixed_config_for(kernel, numels, args) diff --git a/pytorchsim/frontend/inductor/codegen/scheduling.py b/pytorchsim/frontend/inductor/codegen/scheduling.py index 288dc30f..a59432be 100644 --- a/pytorchsim/frontend/inductor/codegen/scheduling.py +++ b/pytorchsim/frontend/inductor/codegen/scheduling.py @@ -5,6 +5,7 @@ from torch._inductor.codegen.common import BackendFeature from torch._inductor.codegen.triton import TritonKernel, TritonScheduling from torch._inductor.ir import MultiTemplateBuffer +from torch._inductor.runtime.runtime_utils import get_max_y_grid from torch._inductor.utils import Placeholder, get_fused_kernel_name from torch._inductor.virtualized import V @@ -28,18 +29,36 @@ def inductor_meta_per_kernel(self): return out def _get_candidates(self): - """The candidate tiles, as dicts over the blocks this kernel takes as arguments, none twice.""" + """The candidate tiles over the blocks this kernel takes, none twice. On an axis whose mask Inductor + drops (_is_mask_dropped) a block is cut to the largest power of two dividing numel, so every tile is + one the generated code is correct for; no tile at all is an error, never an empty config.""" taken = {f"{t.prefix.upper()}BLOCK" for t in self.range_trees if t.tensor_dim is not None and not (t.is_reduction and self.persistent_reduction)} + cap = {f"{t.prefix.upper()}BLOCK": _get_pow2_divisor(t.numel) for t in self.range_trees + if f"{t.prefix.upper()}BLOCK" in taken and self._is_mask_dropped(t)} out = [] for tile in generated_kernel_blocks.candidates_for(self.numels, self.features): - tile = {k: v for k, v in tile.items() if k in taken} + tile = {k: min(v, cap[k]) if k in cap else v for k, v in tile.items() if k in taken} if self.no_x_dim: tile.pop("XBLOCK", None) if tile not in out: out.append(tile) + if not out and taken: + raise RuntimeError(f"no candidate tile for the blocks {sorted(taken)} of numels {self.numels}") return out or [{}] + def _is_mask_dropped(self, tree): + """Inductor's constant-mask rule (TritonKernel._has_constant_mask) over its public facts: the axis + mask is dropped when numel is a multiple of the axis's max block, and for y only within one y grid.""" + sizevars = V.graph.sizevars + if not tree.supports_constant_mask() or not self.optimize_mask or self.fixed_config: + return False + if tree.prefix == "x" and self.no_x_dim: + return False + if not sizevars.statically_known_multiple_of(tree.numel, self.max_block(tree.prefix)): + return False + return tree.grid_dim != 1 or tree.has_zdim or sizevars.statically_known_leq(tree.numel, get_max_y_grid()) + @property def triton_meta(self): return self.__dict__.get("_triton_meta") @@ -162,3 +181,9 @@ def _tile_source(node_schedule): if source == template_record.RECORDED and len(nodes) > 1: return template_record.RECORDED_UNFUSED return source or template_record.HEURISTIC + + +def _get_pow2_divisor(numel): + """The largest power of two dividing `numel` (a block that tiles it exactly).""" + n = int(numel) + return n & -n diff --git a/pytorchsim/frontend/tiling.py b/pytorchsim/frontend/tiling.py index 878cf024..ad68b1d7 100644 --- a/pytorchsim/frontend/tiling.py +++ b/pytorchsim/frontend/tiling.py @@ -123,13 +123,14 @@ def fixed_config_for(kernel, numels, args, contiguous=None): return cfg -#: How many tiles a kernel offers its compile: each costs a compile of its own, and the first that fits wins. -CANDIDATE_LIMIT = 3 +#: The most tiles a kernel offers its compile: each costs a compile of its own, so the halving stops at the floor +#: (the lanes, or 2) and, for several blocks, at this many. +CANDIDATE_LIMIT = 16 def candidate_blocks(kernel, numels, args, contiguous=None): - """fixed_config_for's tile and the smaller ones after it, each block halved down to 2, largest tile - first (ties to the larger reduction block), at most CANDIDATE_LIMIT: the configs a kernel is offered.""" + """fixed_config_for's tile and the smaller ones after it, each block halved down to 2 while the tile holds + at least the lanes, largest tile first (ties to the larger reduction block), at most CANDIDATE_LIMIT.""" cfg = fixed_config_for(kernel, numels, args, contiguous) movable = [k for k, v in cfg.items() if k.endswith("BLOCK") and v and v >= 2] ranges = [] @@ -147,16 +148,19 @@ def product(tile, keep): n *= v return n - tiles = [dict(zip(movable, vs)) for vs in itertools.product(*ranges)] + lanes = int(config.CONFIG_MACHINE.vector_lanes) + floor = min(lanes, product(dict(zip(movable, (vs[0] for vs in ranges))), lambda k: True)) + tiles = [t for t in (dict(zip(movable, vs)) for vs in itertools.product(*ranges)) + if product(t, lambda k: True) >= floor] tiles.sort(key=lambda t: (-product(t, lambda k: True), -product(t, lambda k: k.startswith("R")), [-t[k] for k in movable])) rest = {k: v for k, v in cfg.items() if k.endswith("BLOCK") and v} return [{**rest, **t} for t in tiles[:CANDIDATE_LIMIT]] -def candidate_sizes(first, limit=CANDIDATE_LIMIT, floor=1): +def candidate_sizes(first, limit=CANDIDATE_LIMIT, floor=2): """The sizes a hand-written kernel's one block is offered: `first` and its halves, largest first, down to - `floor`, at most `limit`; each is a config its compile may drop when it overflows.""" + `floor` (2 unless stated), at most `limit`; each is a config its compile may drop when it overflows.""" sizes = [] while first >= floor and len(sizes) < limit: sizes.append(int(first)) diff --git a/tests/ops/elementwise/test_candidate_floor.py b/tests/ops/elementwise/test_candidate_floor.py new file mode 100644 index 00000000..c0cd75a3 --- /dev/null +++ b/tests/ops/elementwise/test_candidate_floor.py @@ -0,0 +1,43 @@ +"""Llama 4's gather x sigmoid (128 x 5120 bf16) plus an i64 column holds over 4 bytes per element live: 524288, 262144 +and 131072 overflow the scratchpad, so tiles go on down to a floor. Breaks if candidates stop at three +(NoTritonConfigsError); the unit check is red there, the gather alone fits at 65536 in this tree.""" +import os +import sys + +import torch + +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) +from result_check import check_result # noqa: E402 + + +def test_candidates_reach_the_floor(device): + from pytorchsim import config + from pytorchsim.frontend import tiling + + lanes = int(config.CONFIG_MACHINE.vector_lanes) + shim = type("K", (), {"inside_reduction": False, "numels": {"xnumel": 655360}})() + xs = [c["XBLOCK"] for c in tiling.candidate_blocks(shim, {"xnumel": 655360}, [{"dtype": "bfloat16"}])] + print("candidates", xs) + assert xs == sorted(xs, reverse=True) and len(set(xs)) == len(xs), xs + assert xs[-1] <= lanes, xs + sizes = tiling.candidate_sizes(1 << 16) + assert sizes[-1] == 2, sizes + + +def test_gather_sigmoid(device, rows=128, hidden=5120): + def fn(t1, t2, t3, t4, idx, gate, col): + e = [torch.nn.functional.embedding(idx, t).float() for t in (t1, t2, t3, t4)] + s = torch.sigmoid(gate[idx].float()).unsqueeze(-1) + return (e[0] * s + e[1] * s * 2 + e[2] * s * 3 + e[3] * s * 4 + (idx.unsqueeze(-1) + col).float()).bfloat16() + + tables = [torch.randn(rows, hidden).to(torch.bfloat16).to(device) for _ in range(4)] + idx = torch.randint(0, rows, (rows,)).to(device) + gate = torch.randn(rows).to(torch.bfloat16).to(device) + col = torch.arange(hidden).to(device) + res = torch.compile(dynamic=False)(fn)(*tables, idx, gate, col) + check_result("GatherSigmoid", res, fn(*[t.cpu() for t in tables], idx.cpu(), gate.cpu(), col.cpu())) + + +if __name__ == "__main__": + test_candidates_reach_the_floor(torch.device("npu:0")) + test_gather_sigmoid(torch.device("npu:0")) diff --git a/tests/ops/elementwise/test_candidate_mask.py b/tests/ops/elementwise/test_candidate_mask.py new file mode 100644 index 00000000..22b7451b --- /dev/null +++ b/tests/ops/elementwise/test_candidate_mask.py @@ -0,0 +1,47 @@ +"""Every tile a generated kernel is offered must be one Inductor's source is right for: Inductor drops an axis's +mask when numel divides its max block, so a candidate larger than that max block, not dividing numel, runs the +last program past the tensor. Breaks if a candidate outgrows TritonNPUKernel.max_block (MobileNet's 401408 and +Yolov5's 3 x 409600 channels-last copy fault or are refused). A y axis past one y grid keeps its mask; reading +it as dropped left Diffusion's bf16 channels-last silu (ynumel 102400) with no tile and a None YBLOCK.""" +import os +import sys + +import torch + +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) +from result_check import check_result # noqa: E402 + + +def test_pointwise_numel_multiple_of_4096(device, shape=(1, 32, 112, 112)): + def fn(a, b): + return (a * b + 1.5).clamp(0, 6) + + x = torch.randn(shape).to(device) + y = torch.randn(shape).to(device) + res = torch.compile(dynamic=False)(fn)(x, y) + check_result("PointwiseMaskElided", res, fn(x.cpu(), y.cpu())) + + +def test_channels_last_copy(device, shape=(1, 3, 640, 640)): + def fn(a): + return (a + 1).contiguous(memory_format=torch.channels_last) + + x = torch.randn(shape).to(device) + res = torch.compile(dynamic=False)(fn)(x) + check_result("ChannelsLastCopy", res, fn(x.cpu())) + + +def test_y_past_one_grid_keeps_its_mask(device, shape=(1, 9, 320, 320)): + def fn(a): + return torch.nn.functional.silu(a).contiguous() + + x = torch.randn(shape, dtype=torch.bfloat16).to(memory_format=torch.channels_last) + res = torch.compile(dynamic=False)(fn)(x.to(device)) + check_result("YPastOneGrid", res, fn(x)) + + +if __name__ == "__main__": + device = torch.device("npu:0") + test_pointwise_numel_multiple_of_4096(device) + test_channels_last_copy(device) + test_y_past_one_grid_keeps_its_mask(device) diff --git a/tests/ops/elementwise/test_cat_grid_bound.py b/tests/ops/elementwise/test_cat_grid_bound.py new file mode 100644 index 00000000..ac665c77 --- /dev/null +++ b/tests/ops/elementwise/test_cat_grid_bound.py @@ -0,0 +1,23 @@ +"""A cat of two inputs whose pointwise kernel masks each half (Yolov5's triton_poi_fused_add_cat_convolution_silu_5): +numel is a multiple of the block, so Inductor drops the numel mask and only the first half's clamp is left. The grid +covers both halves, so a bound read off that clamp alone refuses the launch.""" +import os +import sys + +import torch + +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) +from result_check import check_result # noqa: E402 + + +def test_cat_of_two_masked_halves(device, shape=(32, 25600)): + def fn(a, b, c): + return torch.cat([a + torch.nn.functional.silu(b), torch.nn.functional.silu(c)], dim=0) + + xs = [torch.randn(shape).to(torch.bfloat16).to(device) for _ in range(3)] + res = torch.compile(dynamic=False)(fn)(*xs) + check_result("CatMaskedHalves", res, fn(*[x.cpu() for x in xs]), rtol=2e-2, atol=2e-2) + + +if __name__ == "__main__": + test_cat_of_two_masked_halves(torch.device("npu:0")) From 988770cb0c274c29fab8f6776560936afef7ec5c Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Mon, 16 Nov 2026 22:49:31 +0900 Subject: [PATCH 08/11] [Backend] The spec states an unsigned tensor's dtype, which Triton IR spells as its signed width Triton IR has no unsigned pointer (!tt.ptr for uint8), so PTB read a uint8 input as int8 and the launch refused it (ShapeMismatch: 'in_ptr0' is torch.uint8, but the binary was compiled for int8). spec_dict now states the dtype of an unsigned tensor; PTB takes a stated dtype over the IR's. test_widen_dtype (uint8->int32, uint8->float32) failed before and passes. --- pytorchsim/backend/compiler_input.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/pytorchsim/backend/compiler_input.py b/pytorchsim/backend/compiler_input.py index 10caaf9b..280f945e 100644 --- a/pytorchsim/backend/compiler_input.py +++ b/pytorchsim/backend/compiler_input.py @@ -195,7 +195,7 @@ def spec_json(meta): f"collect_meta could not resolve them from V.graph") scalars = scalar_args(meta) return json.dumps(spec_dict( - [(a["role"], a["numel"]) for a in meta["args"]], contract.grid_xyz(meta), + [(a["role"], a["numel"], _UNSIGNED.get(a.get("dtype"))) for a in meta["args"]], contract.grid_xyz(meta), list(graph_prefetch(meta)), list(contract.launch_axes(meta)), {"scalar_args": [[n, c] for n, c, _ in scalars], "scalar_values": {n: v for n, _, v in scalars if v is not None}})) @@ -209,10 +209,15 @@ def backend_options(spec): "pytorchsim_target": compiler_bridge.target().file} +_UNSIGNED = {"uint8": "uint8", "uint16": "uint16", "uint32": "uint32", "uint64": "uint64"} +"""The dtypes a spec must state: Triton IR spells an unsigned pointer as its signed width (!tt.ptr).""" + + def spec_dict(tensors, grid, held=(), axes=("x",), extra=None): - """A JSON spec: `tensors` as (role, numel) per pointer parameter in order, the default launch `grid`, the - tensor indices held, the axes the launch spreads over.""" - return {"args": [{"role": r, "shape": [n]} for r, n in tensors], "grid": list(grid), "grid_rule": True, + """A JSON spec: `tensors` as (role, numel[, dtype]) per pointer parameter in order (a dtype only where the IR + cannot say it), the default launch `grid`, the tensor indices held, the axes the launch spreads over.""" + return {"args": [dict({"role": t[0], "shape": [t[1]]}, **({"dtype": t[2]} if len(t) > 2 and t[2] else {})) + for t in tensors], "grid": list(grid), "grid_rule": True, "graph_prefetch": list(held), "parallel_axes": list(axes), "extra": extra or {}} From 6df7a3335930205681866ad609d1a5f358eb1b59 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Mon, 16 Nov 2026 22:49:31 +0900 Subject: [PATCH 09/11] [Backend] The bundle writes each kernel file from the source and meta its definition left scripts/ci/bundle.py copied _spec.py and _triton.py from the launch's workdir, which the retile to Inductor's autotune path no longer writes. Every kernel's module text and meta are kept when it is defined (kernel_metadata.KERNEL_SOURCES: define_kernel for generated and template kernels; define_user_defined_triton_kernel for user kernels, through user_kernel_source and user_kernel_meta). The launch meta carries the manifest's scalars ({name, ctype, default}) and the constexprs the Triton backend built the kernel with; copy_kernel writes the files with compiler_input.write, those constexprs pinned, and launch_scalars reads the scalars without a default. test_bundle_reuse (KeyError: 'signature', then FileNotFoundError, before) and test_bundle_where pass. Bundling attention S=1024 (8 workloads) writes spec files that match validation/pytorchsim's but for the kernel's newer parameters; a decode and a prefill kernel compile and run on Spike in PTB's tests/run.py as the bundled ones there do. --- pytorchsim/backend/launcher.py | 5 +- .../inductor/codegen/kernel_metadata.py | 7 ++ .../frontend/inductor/codegen/scheduling.py | 2 + .../frontend/inductor/codegen/user_kernel.py | 88 ++++++++++++++++++- .../frontend/inductor/codegen/wrapper.py | 9 +- scripts/ci/bundle.py | 24 ++--- 6 files changed, 120 insertions(+), 15 deletions(-) diff --git a/pytorchsim/backend/launcher.py b/pytorchsim/backend/launcher.py index d0a2f846..a5984d82 100644 --- a/pytorchsim/backend/launcher.py +++ b/pytorchsim/backend/launcher.py @@ -122,7 +122,8 @@ def _get_workdir(binary, kernel_object, manifest, artifacts): def _get_meta(manifest, grid, args): """The launch's meta, as the functional and timing runners read it: the manifest's tensors by role, - dtype and storage span, each argument's parameter name in order, the launch's extents per axis.""" + dtype and storage span, its scalars ({name, ctype, default}), the constexprs it was built with, each + argument's parameter name in order, the launch's extents per axis.""" import torch tensors = iter(manifest["args"]) @@ -139,4 +140,6 @@ def _get_meta(manifest, grid, args): "launch_grid": tuple(int(g) for g in grid), "launch_extents": [int(grid[_AXES.index(a)]) for a in axes], "user_kernel": launch_hooks.user_kernel_of(manifest["name"]), + "scalars": [dict(x) for x in manifest.get("scalars", ())], + "constexprs": dict(manifest.get("constexprs", {})), } diff --git a/pytorchsim/frontend/inductor/codegen/kernel_metadata.py b/pytorchsim/frontend/inductor/codegen/kernel_metadata.py index e721eb23..57c655bd 100644 --- a/pytorchsim/frontend/inductor/codegen/kernel_metadata.py +++ b/pytorchsim/frontend/inductor/codegen/kernel_metadata.py @@ -100,12 +100,19 @@ def _roles(kernel): ROLES_BY_KERNEL = {} +KERNEL_SOURCES = {} +"""{kernel name: (module text, meta)} of every kernel this process defined, which a kernel file is written from.""" def record_roles(kernel_name, meta): ROLES_BY_KERNEL[kernel_name] = [a["role"] for a in meta.get("args", ())] +def record_source(kernel_name, src_code, meta): + """Keep `kernel_name`'s module text and meta (named after it) for a kernel file of it.""" + KERNEL_SOURCES[kernel_name] = (src_code, {**meta, "kernel_name": kernel_name}) + + def writes_arg(kernel_name, position): """Whether `kernel_name` writes the tensor argument at `position`; True when nothing is recorded.""" roles = ROLES_BY_KERNEL.get(kernel_name) diff --git a/pytorchsim/frontend/inductor/codegen/scheduling.py b/pytorchsim/frontend/inductor/codegen/scheduling.py index a59432be..c9579497 100644 --- a/pytorchsim/frontend/inductor/codegen/scheduling.py +++ b/pytorchsim/frontend/inductor/codegen/scheduling.py @@ -159,6 +159,8 @@ def define_kernel(self, src_code, node_schedule, kernel): kernel_name = super().define_kernel(src_code, node_schedule, kernel) if meta is not None: kernel_metadata.record_roles(kernel_name, meta) + kernel_metadata.record_source( + kernel_name, src_code.replace(str(Placeholder.KERNEL_NAME), kernel_name), meta) return kernel_name diff --git a/pytorchsim/frontend/inductor/codegen/user_kernel.py b/pytorchsim/frontend/inductor/codegen/user_kernel.py index 453197a0..1ace0ddc 100644 --- a/pytorchsim/frontend/inductor/codegen/user_kernel.py +++ b/pytorchsim/frontend/inductor/codegen/user_kernel.py @@ -1,5 +1,9 @@ """A Triton kernel a model registers itself (torch.library.triton_op, wrap_triton) on npu: the spec of each -launch, which Inductor's own async_compile.triton call carries to the Triton backend.""" +launch, which Inductor's own async_compile.triton call carries to the Triton backend, and the source and meta a +kernel file of it is written from.""" + +import dis +import types from torch._inductor.virtualized import V @@ -43,3 +47,85 @@ def _user_kernel_writes(kwargs): "node; every pointer argument is taken as written (inout)") return None return {dep.name for dep in node.arg_accesses.read_writes.writes} + + +def user_kernel_source(kernel): + """The module text of a user-defined Triton kernel as a kernel file loads it: the kernel's own source and its + jit helpers' (Inductor's transitive closure), with the Triton modules they read as globals imported.""" + from torch._inductor.codegen.common import IndentedBuffer + from torch._inductor.codegen.wrapper import user_defined_triton_kernel_transitive_closure_source_code + + src = IndentedBuffer() + src.splice(""" + import triton + import triton.language as tl + """, strip=True) + for line in _extra_imports(kernel): + src.writeline(line) + src.writeline("@triton.jit") + src.splice(user_defined_triton_kernel_transitive_closure_source_code(kernel), strip=True) + return src.getvalue() + + +def _extra_imports(kernel): + """An import of each Triton module other than triton and tl that the kernel or a jit helper it calls + reads as a global, under that name (`pytorchsim` for triton.language.extra.pytorchsim), found as + triton finds the kernel's unqualified loads; Inductor's closure imports a module global by __module__.""" + from triton.runtime.jit import JITFunction + + lines, seen, todo = [], set(), [kernel] + while todo: + fn = getattr(todo.pop(), "fn", None) + if fn is None or id(fn) in seen: + continue + seen.add(id(fn)) + for name in {i.argval for i in dis.Bytecode(fn) if i.opname == "LOAD_GLOBAL"}: + value = fn.__globals__.get(name) + if (isinstance(value, types.ModuleType) and name not in ("triton", "tl") + and value.__name__.split(".")[0] == "triton"): + line = f"import {value.__name__} as {name}" + if line not in lines: + lines.append(line) + elif isinstance(value, JITFunction): + todo.append(value) + return sorted(lines) + + +def user_kernel_meta(kernel, kwargs, triton_meta, grid): + """The spec meta of one launch of a user-defined Triton kernel: signature and constants from + Inductor's triton_meta, each pointer's dtype and span from its IR argument, and its role inout + where torch's mutation analysis says the launch writes it (every pointer, without that analysis).""" + from pytorchsim.contract import storage_span + from pytorchsim.backend.launch_hooks import user_kernel_id + from pytorchsim.frontend.inductor.autotune import graph_prefetch + from pytorchsim.frontend.inductor.codegen import kernel_metadata + + hint = V.graph.sizevars.optimization_hint + signature = {str(k): str(v) for k, v in triton_meta["signature"].items()} + writes = _user_kernel_writes(kwargs) + args, call_params = [], [] + for arg, token in signature.items(): + if token == "constexpr": + continue + call_params.append(arg) + if not token.startswith("*"): + continue + node = kwargs[arg] + layout = node.get_layout() + args.append({ + "name": arg, + "role": "inout" if writes is None or arg in writes else "in", + "buffer": node.get_name(), + "dtype": kernel_metadata.TOKEN_DTYPE[token], + "numel": storage_span([int(hint(s)) for s in layout.size], + [int(hint(s)) for s in layout.stride]), + }) + return { + "kernel_name": kernel.__name__, "signature": signature, + "constants": dict(triton_meta.get("constants") or {}), + "args": args, "call_params": call_params, "numels": {}, + "inside_reduction": False, "fixed_config": {}, + "template_grid": ([int(hint(g)) for g in grid] + [1, 1, 1])[:3], + "user_defined": True, "user_kernel": user_kernel_id(kernel), + "graph_prefetch": graph_prefetch.statement(kernel, args), + } diff --git a/pytorchsim/frontend/inductor/codegen/wrapper.py b/pytorchsim/frontend/inductor/codegen/wrapper.py index ec4563bc..fbf8b598 100644 --- a/pytorchsim/frontend/inductor/codegen/wrapper.py +++ b/pytorchsim/frontend/inductor/codegen/wrapper.py @@ -11,7 +11,7 @@ from pytorchsim.backend import compiler_input, launch_hooks from pytorchsim.frontend.inductor.codegen import kernel_metadata, verify -from pytorchsim.frontend.inductor.codegen.user_kernel import user_kernel_spec +from pytorchsim.frontend.inductor.codegen.user_kernel import user_kernel_meta, user_kernel_source, user_kernel_spec class TritonNPUWrapperCodegen(verify.VerifyLines, wrapper.PythonWrapperCodegen): @@ -115,7 +115,12 @@ def define_user_defined_triton_kernel(self, kernel, configs, kwargs, restore_val kernel, configs, {**kwargs, **options}, restore_value_args, reset_to_zero_args, grids, epilogue_fusion, [*launch_kwargs, *options]) launch_hooks.name_user_kernel(kernel.__name__, kernel) - kernel_metadata.record_roles(got[0] if isinstance(got, tuple) else kernel.__name__, json.loads(spec)) + name = got[0] if isinstance(got, tuple) else kernel.__name__ + kernel_metadata.record_roles(name, json.loads(spec)) + if isinstance(got, tuple) and len(got) > 1 and isinstance(got[1], dict) and "signature" in got[1]: + src, meta = user_kernel_source(kernel), user_kernel_meta(kernel, kwargs, got[1], grids[0]) + for n in {name, kernel.__name__}: + kernel_metadata.record_source(n, src, meta) return got def run_wrapper_ir_passes(self, is_inference): diff --git a/scripts/ci/bundle.py b/scripts/ci/bundle.py index d535cb1d..7327fad5 100644 --- a/scripts/ci/bundle.py +++ b/scripts/ci/bundle.py @@ -377,7 +377,7 @@ def attribute_inputs(launcher, args): def launch_scalars(launcher, args): """{name: launch value} of `launcher`'s scalars its meta gives no value for (a user kernel's row count), which a kernel file run on its own needs.""" - unset = {n for n, _, v in compiler_input.scalar_args(launcher.meta) if v is None} + unset = {x["name"] for x in launcher.meta.get("scalars", ()) if x["default"] is None} return {n: a.item() if isinstance(a, torch.Tensor) else a for n, a in zip(launcher.meta["call_params"], args) if n in unset} @@ -393,17 +393,19 @@ def kernel_files(launcher): def copy_kernel(launcher, recorded, dest): - """`launcher`'s kernel files into `dest`; with `recorded` (its attribute args' and unset scalars' launch - values) its kernel file is written again to take them from the launch.""" + """`launcher`'s kernel files into `dest`, written from the source and meta its definition left + (kernel_metadata.KERNEL_SOURCES) with the constexprs it was built with pinned; `recorded` (its attribute + args' and unset scalars' launch values) is what its make_inputs takes from the launch.""" + from pytorchsim.frontend.inductor.codegen import kernel_metadata tensors, scalars = recorded - if not tensors and not scalars: - for f in kernel_files(launcher): - shutil.copy(os.path.join(launcher.workdir, f), os.path.join(dest, f)) - return - spec, triton = kernel_files(launcher) - with open(os.path.join(launcher.workdir, triton)) as f: - src = f.read() - compiler_input.write(src, launcher.meta, os.path.join(dest, spec), recorded=tensors, scalars=scalars) + got = kernel_metadata.KERNEL_SOURCES.get(launcher.kernel_name) + if got is None: + raise RuntimeError(f"{launcher.kernel_name}: launched, but no definition of it left its source") + src, meta = got + pinned = {**(meta.get("fixed_config") or {}), **launcher.meta.get("constexprs", {})} + meta = {**meta, "fixed_config": {k: v for k, v in pinned.items() if k in meta["signature"]}} + spec, _ = kernel_files(launcher) + compiler_input.write(src, meta, os.path.join(dest, spec), recorded=tensors, scalars=scalars) def same_values(a, b): From c23cdb9e8dd10fb727997ba1dabb9f0b495b4553 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Tue, 17 Nov 2026 11:05:15 +0900 Subject: [PATCH 10/11] [Test] test_llama4 allows a tenth of the token rows to take other experts in bf16, as the CPU alone does Llama 4 Scout (4 MoE layers, top-1 of 16 experts) failed with 10 of 128 token rows apart from the f32 reference, 6 allowed (5%). Measured on the CPU without the compiler: bf16 eager leaves 12 of 128 rows apart. The router picks another expert for 1, 4, 3 and 8 tokens in layers 0-3; in layer 0 the f32 margin between the first and second expert of the flipped token is 0.005, and later layers flip wider margins because the earlier flips carried through. Each of the 45 kernels the compile builds matches on its own (Triton's interpreter, or torch for the mm templates). The bound is now 10%, which the CPU's bf16 run meets. --- tests/models/Llama/test_llama4.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/models/Llama/test_llama4.py b/tests/models/Llama/test_llama4.py index 34169a65..f2f95dbb 100644 --- a/tests/models/Llama/test_llama4.py +++ b/tests/models/Llama/test_llama4.py @@ -127,8 +127,9 @@ # (rtol, atol) per dtype; bf16 takes test_llama3x's measured bound (bf16 CPU bmm too slow to measure here). _TOL = {"bfloat16": (5e-2, 0.6), "float32": (1e-2, 1e-2)} -# Share of token rows a bf16 router near-tie may send to other experts (check_routed_rows); fp32 none. -_ROUTED = {"bfloat16": 0.05, "float32": 0.0} +# Share of token rows a bf16 router near-tie may send to other experts (check_routed_rows); fp32 none. bf16 on the +# CPU alone leaves 12 of 128 rows apart from the f32 reference here (top-1 of 16 experts, flips carried through 4 layers). +_ROUTED = {"bfloat16": 0.10, "float32": 0.0} def _dtype_from_str(name): From 6de680ee4b2e5571cef4a9c11a5024e42be62218 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Tue, 17 Nov 2026 13:51:07 +0900 Subject: [PATCH 11/11] [Pin] PyTorchSim-Triton-Backend at main f289fb35, which adds #406 (mask resolution and the Triton backend hooks this branch calls) --- third_party/pytorchsim-triton-backend.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/third_party/pytorchsim-triton-backend.json b/third_party/pytorchsim-triton-backend.json index 51f404ff..6731fa83 100644 --- a/third_party/pytorchsim-triton-backend.json +++ b/third_party/pytorchsim-triton-backend.json @@ -2,6 +2,6 @@ "description": "Pin for the compiler the codegen route lowers through: PyTorchSim-Triton-Backend, with its LLVM, Triton, the Coprocessor environment (RISC-V toolchain, pk, Spike, gem5), the accelerator model, and TOGSim, which the compiler carries as its third_party/TOGSim submodule: this pin is therefore also what pins the Simulator, the runtime header and the machine configs. CI builds its base image FROM ghcr.io/psal-postech/pytorchsim-triton-backend:, the image that repository publishes for every commit on its main and develop, so ref must be such a commit. scripts/build_from_source.sh checks the same ref out for a local toolchain. The repository is private; its package grants this repository read access.", "pytorchsim_triton_backend": { "repository": "PSAL-POSTECH/PyTorchSim-Triton-Backend", - "ref": "41c4c622b761a69e460106d8e000ffd39d17f6fe" + "ref": "f289fb35f1ce4d0be03834acfe90d70de502f7e1" } }