diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index 2b357b398..80a0c84dd 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -2,7 +2,7 @@ name: Docker image CI on: pull_request: - branches: [ "master", "develop" ] + branches: [ "master", "develop", "pytorchsim-triton-backend" ] workflow_dispatch: env: diff --git a/CLAUDE.md b/CLAUDE.md index c19dba19f..88e66593b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -182,7 +182,7 @@ Conan deps for TOGSim: `boost/1.79.0`, `robin-hood-hashing/3.11.5`, `spdlog/1.11 ## Gotchas / things I've already learned -- The repo expects `python` to be a Python 3.10+ binary with `torch==2.10.0` (torchvision `0.25.0`, triton `3.6.0`). The frontend extends the PyTorch 2 Inductor stack — pin to this version. 2.10 specifically: it is the first release whose Inductor targets triton 3.6, the version PyTorchSim-Triton-Backend is built against. The pins live in `Dockerfile.base`, and editing that file changes the base-image tag automatically (the tag is `thirdparty-`, see `scripts/ci/thirdparty_base_pin.sh`). +- The repo expects `python` to be a Python 3.10+ binary with `torch==2.14.0` (torchvision `0.29.0`, triton `3.8.0`). The frontend extends the PyTorch 2 Inductor stack — pin to this version: 2.14's Inductor targets triton 3.8, the version PyTorchSim-Triton-Backend is built against. The device extension builds as C++20, which 2.14's headers require. The pins live in `Dockerfile.base`, and editing that file changes the base-image tag automatically (the tag is `thirdparty-`, see `scripts/ci/thirdparty_base_pin.sh`). - gem5 and Spike are the vcix-accelerator environment's, found through `VCIX_ENV_ROOT`; both load the accelerator model `TORCHSIM_COMPILE_VCIX_MODEL` (default `$TORCHSIM_PREFIX/vcix-build/libtpu.so`). Override with `GEM5_PATH` / `TORCHSIM_SPIKE` if you build elsewhere. - `_C.cpython-311-*.so` and `torch_openreg/lib/` are build artifacts — already in `.gitignore`, don't commit. - **Parallel runs sharing a `TORCHSIM_DUMP_PATH`** share every per-kernel workdir, and that is deliberate: the workdir holds what compiling produced, which is a function of the source and the machine. A **launch** is not, so each process gets `/launch-/` (`Simulator/session.py`) holding its own `runtime/*.raw`, its own `trace_shape.txt` and symlinks to the shared trace — TOGSim resolves the cycle table and the shape from the directory of the trace it is handed, so linking is enough. What is left locked is only *building* the shared thing, once: `.compile.lock` (compile) and `.timing.lock` (trace.so + its gem5 cycle table). Launches take no lock. Measured on a warm cache, two `test_add.py` in parallel: 40s when launches were locked, **31s** now, against 30s for one run alone. diff --git a/Dockerfile.base b/Dockerfile.base index e4c77a893..e9a6386b9 100644 --- a/Dockerfile.base +++ b/Dockerfile.base @@ -52,20 +52,17 @@ RUN apt-get -y update && \ rm -rf /var/lib/apt/lists/* # CPU PyTorch (no CUDA wheels). torchvision is required by the vision model tests. -# torch 2.10 is pinned for the Triton codegen route: it is the first release whose -# Inductor targets triton 3.6, which is the version PyTorchSim-Triton-Backend is built against -# (triton 3.6 pins LLVM 23, and both sides of the compiler's textual IR seam must be -# the same LLVM). On 2.8 the frontend had to be shimmed onto a triton it did not -# expect; on 2.10 the versions simply agree. +# torch 2.14 is pinned for the Triton codegen route: its Inductor targets triton 3.8, +# the version PyTorchSim-Triton-Backend is built against. RUN python3.11 -m pip install --no-cache-dir \ - torch==2.10.0 torchvision==0.25.0 --index-url https://download.pytorch.org/whl/cpu + torch==2.14.0 torchvision==0.29.0 --index-url https://download.pytorch.org/whl/cpu # Triton, for the Inductor Triton codegen route (PyTorchSimCodegen). # Inductor imports triton while GENERATING a kernel, so it is needed even though # nothing here compiles or launches through triton's own runtime -- the PTB layer # compiles the kernel ahead of time to a RISC-V ELF using its own triton build. # Not a dependency of the CPU torch wheels, hence installed explicitly. -RUN python3.11 -m pip install --no-cache-dir triton==3.6.0 +RUN python3.11 -m pip install --no-cache-dir triton==3.8.0 # TorchSim Python dependencies. # diff --git a/PyTorchSimCodegen/codecache.py b/PyTorchSimCodegen/codecache.py index 64cc0703b..4c889a894 100644 --- a/PyTorchSimCodegen/codecache.py +++ b/PyTorchSimCodegen/codecache.py @@ -83,6 +83,17 @@ def _spad_overflow(exc): return (int(m.group(1)), int(m.group(2))) if m else None +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).""" + over = _spad_overflow(exc) + if over is not None: + return "%d bytes/lane over a budget of %d" % over + if "spill not allowed" in (getattr(exc, "output", None) or str(exc)): + 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 @@ -167,25 +178,55 @@ def _time_tile(src_code, meta, kernel_name, workdir, timeout): return float("inf") +def _template_tiles(src_code, meta): + """Every mapped tile of an mm template kernel, best first, as (M, N, K) blocks; [] for + any other kernel.""" + shape = _mm_template(src_code, meta) + if shape is None: + return [] + from .inductor_patches import _gemm_tiles + m, n, k, size, out_size = shape + return [(c.block_m, c.block_n, c.block_k) for c in _gemm_tiles(m, n, k, size, out_size)] + + +def _smaller_tiles(src_code, meta): + """(tile, source, meta) to retry with after a scratchpad overflow, in order: the other + mapped tiles of an mm template, else each smaller fixed_config tile.""" + shape = _mm_template(src_code, meta) + if shape is not None: + mnk = shape[:3] + now = tuple(int(_TILE_RE[k].search(src_code).group(2)) + for k in ("BLOCK_M", "BLOCK_N", "BLOCK_K")) + for tile in _template_tiles(src_code, meta): + if tile != now: + yield (dict(zip(("BLOCK_M", "BLOCK_N", "BLOCK_K"), tile)), + *_retile(src_code, meta, mnk, tile)) + return + 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 + + def _autotune_template(src_code, meta, kernel_name, write_path): """develop's template autotune: the top-k mapped tiles, each compiled with what is fused - into it and simulated alone; the fewest cycles wins. The first tile to finish sets the - others' time limit (its wall time plus codegen_autotune_wall_slack_sec).""" + into it and simulated alone; the fewest cycles wins. Only in timing mode, since cycles + are what it ranks by; the first tile to finish limits the others' wall time.""" shape = _mm_template(src_code, meta) if shape is None: return src_code, meta - from .inductor_patches import _gemm_tiles - m, n, k, size, out_size = shape + m, n, k = shape[:3] strategy = config.codegen_mapping_strategy known = _recorded_tile(m, n, k) if "external" in strategy else None if known is not None: logger.info("[autotune] %s BLOCK_M/N/K=%s: from %s", kernel_name, known, config.codegen_external_mapping_file) return _retile(src_code, meta, (m, n, k), known) - if "autotune" not in strategy: + if "autotune" not in strategy or not config.pytorchsim_timing_mode: return src_code, meta - tiles = [(c.block_m, c.block_n, c.block_k) for c in _gemm_tiles(m, n, k, size, out_size)] - tiles = tiles[:config.codegen_autotune_template_topk] + tiles = _template_tiles(src_code, meta)[:config.codegen_autotune_template_topk] best, timeout = (float("inf"), src_code, meta, None), None for tile in tiles: s, mt = _retile(src_code, meta, (m, n, k), tile) @@ -254,8 +295,7 @@ def torchsim_compile(src_code, meta, kernel_name): with open(os.path.join(write_path, "kernel.py"), "w") as f: f.write(src_code) timing.store_meta(write_path, meta) - tiles = iter(_get_tile_candidates(meta)) - next(tiles) + retries = _smaller_tiles(src_code, meta) while True: kernel_spec.write_spec_file(src_code, meta, spec_path, compiler_bridge.compiler_dir()) @@ -267,22 +307,19 @@ def torchsim_compile(src_code, meta, kernel_name): breakdown.ingest_compile(write_path, kernel_name) break except compiler_bridge.CompilerError as exc: - over = _spad_overflow(exc) - if over is None: + why = _too_big(exc) + if why is None: raise - tile = next(tiles, None) - if tile is None: - logger.warning( - "[torchsim-compile] %s: %d bytes/lane over a budget of %d, and " - "no tile with every block >= 2 is left to try", - kernel_name, over[0], over[1]) + 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 - meta["fixed_config"].update(tile) - logger.info( - "[torchsim-compile] %s: %d bytes/lane over a budget of %d, trying " - "%s", kernel_name, over[0], over[1], - {k: v for k, v in meta["fixed_config"].items() - if k.endswith("BLOCK")}) + 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) timing.store_meta(write_path, meta) provenance.store(write_path) else: diff --git a/PyTorchSimCodegen/compiler_bridge.py b/PyTorchSimCodegen/compiler_bridge.py index 14c6e9113..ea1c5cbfd 100644 --- a/PyTorchSimCodegen/compiler_bridge.py +++ b/PyTorchSimCodegen/compiler_bridge.py @@ -19,15 +19,19 @@ class CompilerError(RuntimeError): _SIGNAL = re.compile( r"^(?!\s|Traceback|During handling|The above)" r"(.*\berror:\s.*|.*failed to legalize.*|" - r"[\w.]*(?:Error|Exception)\b.*|.*Assertion.*)$", re.M) + r"[\w.]*(?:Error|Exception)\b.*|.*Assertion.*|" + r"[A-Za-z_]\w*(?:\.\w+)+: .+|\[(?:transform|lower|binary)\] .*(?:refused|not allowed).*)$", re.M) _FRAME = re.compile(r'^\s|^\s*File "|^\s*\^') + _STAGE_FAIL = re.compile(r"^\[\d+/\d+\] \S+\s+FAIL\s.*\n\n( \S.*)$", re.M) def __init__(self, message, cmd=None, output=None): self.cmd = cmd self.output = output if output: - hits = [h.strip() for h in self._SIGNAL.findall(output) - if not self._FRAME.match(h)] + hits = [h.strip() for h in self._STAGE_FAIL.findall(output)] + if not hits: + hits = [h.strip() for h in self._SIGNAL.findall(output) + if not self._FRAME.match(h)] if not hits: hits = [l for l in output.strip().splitlines() if l.strip() and not self._FRAME.match(l)] diff --git a/PyTorchSimCodegen/inductor_patches.py b/PyTorchSimCodegen/inductor_patches.py index 0fc8deeed..bd3a58b53 100644 --- a/PyTorchSimCodegen/inductor_patches.py +++ b/PyTorchSimCodegen/inductor_patches.py @@ -141,7 +141,7 @@ def _get_config_generator(self): def configs(m, n, k, **kwargs): from torch._inductor.virtualized import V try: - mnk = [int(V.graph.sizevars.size_hint(s)) for s in (m, n, k)] + mnk = [int(V.graph.sizevars.optimization_hint(s)) for s in (m, n, k)] except Exception: yield from generic(m, n, k, **kwargs) return @@ -386,7 +386,7 @@ def wrapped(*args, _orig=lowerings[op], **kwargs): try: m, n, k, layout = mm_args(*args[bias:bias + 2], layout=kwargs.get("layout"))[:4] - m, n, k = (int(V.graph.sizevars.size_hint(s)) for s in (m, n, k)) + m, n, k = (int(V.graph.sizevars.optimization_hint(s)) for s in (m, n, k)) except Exception: return _orig(*args, **kwargs) if not _is_npu(layout): @@ -429,6 +429,10 @@ def _npu_choices_class(): torch.int16: 16, torch.int8: 8, torch.uint8: 8, torch.bool: 8} class NPUChoices(InductorChoices): + def uuid(self): + """This class's part of Inductor's cache key.""" + return "pytorchsim-npu-choices-1" + def triton_kernel_kwargs(self, kernel_cls, features, groups, kernel_kwargs): """Pin this machine's blocks as a FixedTritonConfig, before the kernel is generated. @@ -492,19 +496,18 @@ def should_use_persistent_reduction(features, cooperative_reduction): persistent = 1 << (extent - 1).bit_length() return persistent <= launch.reduction_block_for(extent) - @staticmethod - def reduction_split_factor(device, reduction_numel_hint, numel_hint, + def reduction_split_factor(self, device, reduction_numel_hint, numel_hint, inner_reduction): """Split a reduction only when a core would otherwise sit idle, and at most cores ways. One core, or a parallel axis that already fills the cores, means no split. """ if getattr(device, "type", device) != "npu": - return InductorChoices.reduction_split_factor( + return super().reduction_split_factor( device, reduction_numel_hint, numel_hint, inner_reduction) cores = _num_cores() if cores > 1: - want = InductorChoices.reduction_split_factor( + want = super().reduction_split_factor( device, reduction_numel_hint, numel_hint, inner_reduction) try: if int(numel_hint) >= cores: diff --git a/PyTorchSimCodegen/kernel_spec.py b/PyTorchSimCodegen/kernel_spec.py index bbf103047..2f8b91e22 100644 --- a/PyTorchSimCodegen/kernel_spec.py +++ b/PyTorchSimCodegen/kernel_spec.py @@ -45,7 +45,7 @@ def _buffer_numel(name): if buf is None: return None lay = buf.get_layout() - hint = V.graph.sizevars.size_hint + hint = V.graph.sizevars.optimization_hint size = [int(hint(s)) for s in lay.size] if any(s <= 0 for s in size): return 0 @@ -148,11 +148,12 @@ def collect_meta(kernel, kernel_name): if not signature: signature = _signature_from_argdefs(arg_defs, arg_types) + call_params = [getattr(a, "name", str(a)) for a in arg_defs] args = [] for a in arg_defs: name = getattr(a, "name", str(a)) role, buf = roles.get(name, (None, None)) - if role is None: + if role is None or not signature.get(name, "*").startswith("*"): continue args.append({ "name": name, @@ -165,7 +166,7 @@ def collect_meta(kernel, kernel_name): numels = {} for prefix, val in (getattr(kernel, "numels", None) or {}).items(): try: - numels[f"{prefix}numel"] = int(V.graph.sizevars.size_hint(val)) + numels[f"{prefix}numel"] = int(V.graph.sizevars.optimization_hint(val)) except Exception: numels[f"{prefix}numel"] = None @@ -174,6 +175,7 @@ def collect_meta(kernel, kernel_name): "signature": {str(k): str(v) for k, v in signature.items()}, "constants": {str(k): v for k, v in constants.items()}, "args": args, + "call_params": call_params, "numels": numels, "inside_reduction": bool(getattr(kernel, "inside_reduction", False)), "fixed_config": launch.fixed_config_for(kernel, numels, args), @@ -225,10 +227,10 @@ def _dtype_tokens(): def scalar_args(meta): - """User scalar parameters, in kernel order, as [(name, c_type, value)]. + """Scalar parameters in kernel order, as [(name, c_type, default)]. - the linalg lowering keeps these ahead of its own six grid/pid arguments, so the - wrapper must pass them or every later argument lands one slot early. + A numel's value is known at codegen; an input Inductor unwrapped to a scalar (a 0-d CPU + tensor, Adam's step) only at launch, so its default is None and the launch passes it. """ numels = meta["numels"] out = [] @@ -240,11 +242,8 @@ def scalar_args(meta): raise SpecIncomplete( f"{meta['kernel_name']}: scalar '{name}' has type {token!r}, " f"which has no C mapping in _C_TYPE") - if numels.get(name) is None: - raise SpecIncomplete( - f"{meta['kernel_name']}: no value for scalar '{name}' -- " - f"collect_meta resolves these from kernel.numels") - out.append((name, ctype, int(numels[name]))) + v = numels.get(name) + out.append((name, ctype, None if v is None else int(v))) return out @@ -361,7 +360,7 @@ def write_spec_file(src_code, meta, path, compiler_dir): grid=launch.grid_xyz(meta), parallel_axes=tuple(launch.launch_axes(meta)), scalar_decls=[(n, c) for n, c, _ in scalars], - scalar_values={n: v for n, _, v in scalars}, + scalar_values={n: v for n, _, v in scalars if v is not None}, ) with open(path, "w") as f: f.write(text) diff --git a/PyTorchSimCodegen/launch.py b/PyTorchSimCodegen/launch.py index f27d81fc6..97c92344e 100644 --- a/PyTorchSimCodegen/launch.py +++ b/PyTorchSimCodegen/launch.py @@ -38,7 +38,7 @@ def template_grid(kernel): return None name = getattr(kernel, "kernel_name", kernel) try: - vals = [int(V.graph.sizevars.size_hint(s)) for s in sizes] + vals = [int(V.graph.sizevars.optimization_hint(s)) for s in sizes] grid = grid_fn(*vals, dict(getattr(kernel, "meta", None) or {})) extents = [int(g) for g in grid] except Exception as e: @@ -75,7 +75,7 @@ def combo_grid(kernel): meta_fn = getattr(kernel, "combo_grid_meta", None) if meta_fn is None: return None - grid_meta = meta_fn() + grid_meta = meta_fn([kernel.select_heuristics(k)[1] for k in kernel.sub_kernels]) xblock = (grid_meta.get("default_config") or {}).get("XBLOCK") if not xblock: return None @@ -196,9 +196,10 @@ def _covers(want, n): """`want`, clamped to the smallest legal block that covers `n`. A block wider than its numel strands the mask's rank-1 index rows ONE_LANE - against banked data. A numel of 1 is NOT clamped: it leaves the lanes none. + against banked data, and a numel of 1 under a lane-wide block is a tile of + digits whose mask the DMA cannot state; the lanes go to another axis. """ - if not n or n <= 1: + if not n: return want cover = 1 while cover < n: diff --git a/PyTorchSimCodegen/scheduling.py b/PyTorchSimCodegen/scheduling.py index 412b8364c..4a20438a3 100644 --- a/PyTorchSimCodegen/scheduling.py +++ b/PyTorchSimCodegen/scheduling.py @@ -6,7 +6,7 @@ """ from torch._inductor.codecache import get_hash -from torch._inductor.codegen.common import IndentedBuffer +from torch._inductor.codegen.common import BackendFeature, IndentedBuffer from torch._inductor.codegen.triton import TritonKernel, TritonScheduling from torch._inductor.utils import Placeholder, get_fused_kernel_name from torch._inductor.virtualized import V @@ -24,12 +24,19 @@ 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=False) + wrapper.generate_kernel_call(name, call_args, triton=True) class TritonNPUScheduling(TritonScheduling): kernel_type = TritonNPUKernel + @classmethod + def get_backend_features(cls, device): + """Triton's features without FOREACH: a foreach op is one kernel per tensor here. The + machine has no launch to amortise, and a combo kernel picks its tensors by program id, + a branch the TOG cannot time.""" + return super().get_backend_features(device) - {BackendFeature.FOREACH} + def define_kernel(self, src_code, node_schedule, kernel): """Name the kernel by its source, capture its metadata, and emit our compile call. diff --git a/PyTorchSimCodegen/wrapper_codegen.py b/PyTorchSimCodegen/wrapper_codegen.py index 7a534f9e6..d998680d7 100644 --- a/PyTorchSimCodegen/wrapper_codegen.py +++ b/PyTorchSimCodegen/wrapper_codegen.py @@ -4,11 +4,11 @@ the functional-verify calls) and walks the wrapper IR lines once. """ import contextlib +import dataclasses import torch from torch._inductor.codegen import wrapper from torch._inductor.ir import GraphPartitionSignature -from torch._inductor.utils import IndentedBuffer from torch._inductor.virtualized import V from typing import Optional @@ -35,6 +35,15 @@ def _mutated(line): return () +@dataclasses.dataclass +class _VerifyLine(wrapper.WrapperLine): + """One per-kernel verify call in the wrapper body.""" + text: str + + def codegen(self, code): + code.writeline(self.text) + + class TritonNPUWrapperCodegen(wrapper.PythonWrapperCodegen): """The npu wrapper: kernels are compiled by torchsim_compile and called as plain functions.""" @@ -53,132 +62,64 @@ def create( ) return cls() - def wrap_kernel_call(self, name, call_args): - """The kernel call line, with sympy call args rendered as strings first.""" - return super().wrap_kernel_call( - name, self.prepare_triton_kernel_call(call_args)) - def write_header(self): + """Inductor's own header, then the names the npu wrapper adds: torchsim_compile, verify, the log line.""" + super().write_header() self.header.splice( f""" - from ctypes import c_void_p, c_long - import torch - import math - import random - import os - import tempfile - from math import inf, nan - from torch._inductor.hooks import run_intermediate_hooks - from torch._inductor.utils import maybe_profile - from torch._inductor.codegen.memory_planning import _align as align - from torch._inductor.async_compile import AsyncCompile - - from torch import device, empty, empty_strided from PyTorchSimFrontend.config import setup_logger from Simulator import functional_verify as _fverify - from torch._inductor.select_algorithm import extern_kernels from {codecache.__name__} import torchsim_compile _logger = setup_logger("PyTorchSimCodegen.generated_wrapper") - - aten = torch.ops.aten - inductor_ops = torch.ops.inductor - assert_size_stride = torch._C._dynamo.guards.assert_size_stride - assert_alignment = torch._C._dynamo.guards.assert_alignment - empty_strided_cpu = torch._C._dynamo.guards._empty_strided_cpu - alloc_from_pool = torch.ops.inductor._alloc_from_pool - reinterpret_tensor = torch.ops.inductor._reinterpret_tensor - async_compile = AsyncCompile() _logger.info(f'Wrapper Codegen Path = {{__file__}}') """ ) - def write_prefix(self): - self.write_async_compile_wait() - self.prefix.splice( - """ - def call(args): - """ - ) - with self.prefix.indent(): - inp_len = len(V.graph.graph_inputs.keys()) - if inp_len != 0: - lhs = f"{', '.join(V.graph.graph_inputs.keys())}{'' if inp_len != 1 else ','}" - self.prefix.writeline(f"{lhs} = args") - self.prefix.writeline("args.clear()") - - if _func_verify.enabled(): - gm = getattr(V.graph, "module", None) - if gm is not None: - gid = _func_verify.register_graph(gm) - in_names = list(V.graph.graph_inputs.keys()) - self.prefix.writeline( - f"_fverify.verify_init({gid}, [{', '.join(in_names)}])") - - self.codegen_inputs() - self.codegen_input_size_asserts() - - def _generate_kernel_call_helper( - self, - kernel_name: str, - call_args, - *, - device=None, - triton=True, - arg_types=None, - raw_keys=None, - raw_args=None, - triton_meta=None, - graph_name="", - original_fxnode_name=None, - ): + def write_args(self, input_names): + """Unpack the inputs as Inductor does, then (per-kernel verify on) build the CPU golden from them.""" + super().write_args(input_names) + if not _func_verify.enabled(): + return + gm = getattr(V.graph, "module", None) + if gm is not None: + gid = _func_verify.register_graph(gm) + self.prefix.writeline( + f"_fverify.verify_init({gid}, [{', '.join(V.graph.graph_inputs.keys())}])") + + 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 to its value, decided for the kernel's device, since this line is rendered + after the CPU island's); grid, stream and autotune do not apply. A C++ kernel keeps + Inductor's own call.""" + if triton: + with (V.graph.set_current_device(device) if device is not None + else contextlib.nullcontext()): + call_args = self.prepare_triton_kernel_call(call_args) + 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)) - return - - def generate(self, is_inference): - result = IndentedBuffer() + 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.""" + super().run_wrapper_ir_passes(is_inference) + if not _func_verify.enabled(): + return self._fverify_seen = set() - self._fverify_last = None - with contextlib.ExitStack() as stack: - stack.enter_context(self.wrapper_call.indent()) - if torch._inductor.config.allow_buffer_reuse: - self.estimate_peak = wrapper.EfficientPeakEstimate() - self.memory_plan_reuse() - with self.set_writeline(self.wrapper_call.writeline): - for line in self.lines: - if isinstance(line, wrapper.MemoryPlanningLine): - line.codegen(self.wrapper_call) - elif isinstance(line, wrapper.KernelCallLine): - self.wrapper_call.writeline(self.wrap_kernel_call(line.kernel_name, line.call_args)) - if _func_verify.enabled(): - self._fverify_emit_checks(line.call_args, id(line), - line.kernel_name) - else: - if isinstance(line, wrapper.WrapperLine): - line.codegen(self.wrapper_call) - if _func_verify.enabled(): - self._fverify_emit_mutation_checks(line) - else: - self.wrapper_call.writeline(line) - output_refs = self.get_output_refs() - self.mark_output_type() - self.generate_return(output_refs) - - result.splice(self.header) - - self.finalize_prefix() - result.splice(self.prefix) - - with result.indent(): - result.splice(self.wrapper_call) - - self.generate_end(result) - self.add_benchmark_harness(result) - return ( - result.getvaluewithlinemap(), - self.kernel_declarations.getvaluewithlinemap(), - ) + self._fverify_last = self._fverify_last_writer() + lines = [] + for line in self.lines: + lines.append(line) + if isinstance(line, wrapper.KernelCallLine): + checks = self._fverify_emit_checks(line.call_args, id(line), line.kernel_name) + elif isinstance(line, wrapper.WrapperLine): + checks = self._fverify_emit_mutation_checks(line) + else: + checks = [] + lines.extend(_VerifyLine(c) for c in checks) + self.lines = lines def _fverify_last_writer(self): """{buffer name: id of the last wrapper line that writes it}. @@ -200,12 +141,11 @@ def _fverify_last_writer(self): return last def _fverify_emit_checks(self, call_args, line_id=None, kernel_name=None): - """Emit a verify_check after this kernel for each buffer it writes and finishes. + """The verify_check lines after this kernel, one per buffer it writes and finishes. Only written arguments are checked: a reused buffer that is only read carries another origin. """ - if self._fverify_last is None: - self._fverify_last = self._fverify_last_writer() + checks = [] for pos, a in enumerate(call_args): if not isinstance(a, str): continue @@ -214,33 +154,33 @@ def _fverify_emit_checks(self, call_args, line_id=None, kernel_name=None): continue if not _writes(kernel_name, pos): continue - self._fverify_check_one(name, line_id) + checks += self._fverify_check_one(name, line_id) + return checks def _fverify_emit_mutation_checks(self, line): - """The same check, after a fallback that finishes a buffer in place.""" - if self._fverify_last is None: - self._fverify_last = self._fverify_last_writer() + """The same checks, after a fallback that finishes a buffer in place.""" + checks = [] for name in _mutated(line): - self._fverify_check_one(name, id(line)) + checks += self._fverify_check_one(name, id(line)) + return checks def _fverify_check_one(self, name, line_id): - """One `verify_check` for `name`, if this line is its last writer.""" + """The `verify_check` line for `name` ([] or one), if this line is its last writer.""" if name in self._fverify_seen: - return + return [] if line_id is not None and self._fverify_last.get(name) != line_id: - return + return [] self._fverify_seen.add(name) if name in V.graph.graph_inputs: - return + return [] try: buf = V.graph.get_buffer(name) except Exception: buf = None if buf is None: - return + return [] origin = getattr(buf, "origin_node", None) if origin is None: - return + return [] op = str(getattr(origin, "target", "?")) - self.wrapper_call.writeline( - f'_fverify.verify_check({name}, "{name}", "{origin.name}", "{op}")') + return [f'_fverify.verify_check({name}, "{name}", "{origin.name}", "{op}")'] diff --git a/PyTorchSimDevice/CMakeLists.txt b/PyTorchSimDevice/CMakeLists.txt index 2c207ca63..21259777f 100644 --- a/PyTorchSimDevice/CMakeLists.txt +++ b/PyTorchSimDevice/CMakeLists.txt @@ -5,7 +5,7 @@ project(TORCH_OPENREG CXX C) include(GNUInstallDirs) include(CheckCXXCompilerFlag) -set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD 20) set(CMAKE_C_STANDARD 11) set(CMAKE_CXX_EXTENSIONS OFF) diff --git a/PyTorchSimDevice/csrc/aten/OpenRegMinimal.cpp b/PyTorchSimDevice/csrc/aten/OpenRegMinimal.cpp index 21ab3fefd..f9e5e8d5e 100644 --- a/PyTorchSimDevice/csrc/aten/OpenRegMinimal.cpp +++ b/PyTorchSimDevice/csrc/aten/OpenRegMinimal.cpp @@ -77,6 +77,14 @@ at::Tensor wrapper__copy_from_and_resize( return at::native::openreg::_copy_from_and_resize(self, dst); } +at::Tensor& wrapper_fill__Scalar(at::Tensor& self, const at::Scalar& value) { + return at::native::openreg::fill_(self, value); +} + +at::Tensor& wrapper_zero_(at::Tensor& self) { + return at::native::openreg::zero_(self); +} + at::Scalar wrapper__local_scalar_densor(const at::Tensor& self) { return at::native::openreg::_local_scalar_dense(self); } @@ -141,6 +149,8 @@ TORCH_LIBRARY_IMPL(aten, PrivateUse1, m) { m.impl("_reshape_alias", wrapper__reshape_alias); m.impl("_copy_from", wrapper__copy_from); m.impl("_copy_from_and_resize", wrapper__copy_from_and_resize); + m.impl("fill_.Scalar", wrapper_fill__Scalar); + m.impl("zero_", wrapper_zero_); m.impl("_local_scalar_dense", wrapper__local_scalar_densor); m.impl("set_.source_Tensor", wrapper_set_source_Tensor_); m.impl("set_.source_Storage", wrapper_set_source_Storage_); diff --git a/PyTorchSimDevice/csrc/aten/native/Minimal.cpp b/PyTorchSimDevice/csrc/aten/native/Minimal.cpp index 8a3263bb8..513f29411 100644 --- a/PyTorchSimDevice/csrc/aten/native/Minimal.cpp +++ b/PyTorchSimDevice/csrc/aten/native/Minimal.cpp @@ -128,6 +128,28 @@ at::Tensor _copy_from( return dst; } +at::Tensor& fill_(at::Tensor& self, const at::Scalar& value) { + MemoryGuard guard(self); + at::Tensor self_as_cpu = at::from_blob( + self.data_ptr(), + self.sizes(), + self.strides(), + self.options().device(at::kCPU)); + self_as_cpu.fill_(value); + return self; +} + +at::Tensor& zero_(at::Tensor& self) { + MemoryGuard guard(self); + at::Tensor self_as_cpu = at::from_blob( + self.data_ptr(), + self.sizes(), + self.strides(), + self.options().device(at::kCPU)); + self_as_cpu.zero_(); + return self; +} + at::Tensor _copy_from_and_resize( const at::Tensor& self, const at::Tensor& dst) { diff --git a/PyTorchSimDevice/csrc/aten/native/Minimal.h b/PyTorchSimDevice/csrc/aten/native/Minimal.h index a2e5cf02d..860a88c4f 100644 --- a/PyTorchSimDevice/csrc/aten/native/Minimal.h +++ b/PyTorchSimDevice/csrc/aten/native/Minimal.h @@ -40,6 +40,8 @@ at::Tensor _copy_from( bool non_blocking); at::Tensor _copy_from_and_resize(const at::Tensor& self, const at::Tensor& dst); +at::Tensor& fill_(at::Tensor& self, const at::Scalar& value); +at::Tensor& zero_(at::Tensor& self); at::Scalar _local_scalar_dense(const at::Tensor& self); diff --git a/PyTorchSimDevice/torch_openreg/__init__.py b/PyTorchSimDevice/torch_openreg/__init__.py index 020730c85..cd18d0c63 100644 --- a/PyTorchSimDevice/torch_openreg/__init__.py +++ b/PyTorchSimDevice/torch_openreg/__init__.py @@ -29,7 +29,7 @@ TritonNPUScheduling, TritonNPUWrapperCodegen) torch._inductor.codegen.common.register_backend_for_device( "npu", - lambda scheduling: TritonNPUScheduling(scheduling), + TritonNPUScheduling, TritonNPUWrapperCodegen ) diff --git a/PyTorchSimDevice/torch_openreg/openreg/__init__.py b/PyTorchSimDevice/torch_openreg/openreg/__init__.py index a77344dee..631f0c2cd 100644 --- a/PyTorchSimDevice/torch_openreg/openreg/__init__.py +++ b/PyTorchSimDevice/torch_openreg/openreg/__init__.py @@ -18,8 +18,6 @@ # Ops with no npu kernel that Inductor can codegen. Registering them here rather # than per test is what keeps `every operation runs on the NPU` true by default. DEFAULT_EAGER_TO_COMPILE = ( - "aten::fill_.Scalar", - "aten::zero_", "aten::cat.out", "aten::mm.out", "aten::max_pool2d_with_indices.out", @@ -358,6 +356,12 @@ def _run_on_cpu(op, args, kwargs): return _tree_to(result, device) if device is not None else result +def _compile_in_flight(): + """Is a torch.compile running on this thread? An eager op reached then is compile-time work + (a constant Inductor folds), not the workload, and a compile inside a compile breaks dynamo.""" + return torch.compiler.is_compiling() + + def eager_to_compile(op_name): """ Register an eager mode operation as a graph-based implementation using torch.compile(). @@ -400,7 +404,7 @@ def wrapper(*args, **kwargs): for part in [namespace] + op_path.split("."): op = getattr(op, part) - if getattr(in_flight, "busy", False): + if getattr(in_flight, "busy", False) or _compile_in_flight(): return _run_on_cpu(op, args, kwargs) @torch.compile(dynamic=False) diff --git a/PyTorchSimDevice/torch_openreg/openreg/extension_device_interface.py b/PyTorchSimDevice/torch_openreg/openreg/extension_device_interface.py index e0a6783c4..9df2df936 100644 --- a/PyTorchSimDevice/torch_openreg/openreg/extension_device_interface.py +++ b/PyTorchSimDevice/torch_openreg/openreg/extension_device_interface.py @@ -36,7 +36,7 @@ def set_device(device: int): def current_device() -> int: if "extension_device" in caching_worker_current_devices: return caching_worker_current_devices["extension_device"] - return torch.xpu.current_device() + return torch.npu.current_device() @staticmethod def get_device_properties(device: torch.types.Device = None) -> _ExtensionDeviceProperties: @@ -62,6 +62,16 @@ def get_device_properties(device: torch.types.Device = None) -> _ExtensionDevice def get_compute_capability(device: torch.types.Device = None): return 36 + @staticmethod + def is_available() -> bool: + """The simulated device is always there.""" + return True + + @staticmethod + def is_triton_capable(device: torch.types.Device = None) -> bool: + """Kernels for npu are Triton, compiled by PyTorchSim-Triton-Backend.""" + return True + @staticmethod def is_bf16_supported(including_emulation: bool = False) -> bool: """Answer Inductor's bf16 gate, which the base class only raises on. diff --git a/Simulator/functional.py b/Simulator/functional.py index e525347a4..90151f714 100644 --- a/Simulator/functional.py +++ b/Simulator/functional.py @@ -84,11 +84,11 @@ def _check(meta, pairs): f"{meta['kernel_name']}: '{m['name']}' spans " f"{_storage_numel(t)} element(s) of storage, but the binary was " f"compiled for {m['numel']}. " - f"the compiler bakes the extents, the grid and the scalar values into " - f"the kernel, so a dynamic-shape graph reuses an ELF that does " - f"not fit. The timing path does handle this (it takes the grid " - f"at run time); set pytorchsim_functional_mode: False to study " - f"cycles alone, or keep shapes static to check values.") + f"the compiler bakes the extents and the grid into the kernel, so a " + f"dynamic-shape graph reuses an ELF that does not fit. The timing " + f"path does handle this (it takes the grid at run time); set " + f"pytorchsim_functional_mode: False to study cycles alone, or keep " + f"shapes static to check values.") if str(t.dtype).removeprefix("torch.") != m["dtype"]: raise ShapeMismatch( f"{meta['kernel_name']}: '{m['name']}' is {t.dtype}, but the " @@ -244,8 +244,9 @@ def run(workdir, meta, args): f"{workdir} has no kernel.json -- compile the kernel first") raw_paths = {a["name"]: os.path.join(runtime, f"{a['name']}.raw") for a in manifest["args"]} + scalars = spike_run.argv_scalars(manifest, dict(zip(meta.get("call_params", ()), args))) try: - spike_run.launch(workdir, manifest, runtime, raw_paths, logger.debug) + spike_run.launch(workdir, manifest, runtime, raw_paths, logger.debug, scalars=scalars) except spike_run.SpikeError as e: raise RuntimeError(f"[Spike] {meta['kernel_name']} failed:\n{e}") from None diff --git a/Simulator/spike_run.py b/Simulator/spike_run.py index b2b99c271..c7cf767c5 100644 --- a/Simulator/spike_run.py +++ b/Simulator/spike_run.py @@ -51,6 +51,20 @@ def argv_order(manifest): return [a["name"] for a in manifest["args"]] +def argv_scalars(manifest, values): + """The scalar values main() reads after the tensor paths, as strings in parameter order: + the launch's by name, else the manifest's defaults.""" + out = [] + for s in manifest.get("scalars", []): + v = values.get(s["name"], s["default"]) + if v is None: + raise SpikeError(f"{manifest['name']}: no value for scalar '{s['name']}' in this " + f"launch, and the spec gave it no default") + out.append(repr(float(v)) if s["ctype"] in ("float", "double", "_Float16") + else str(int(v))) + return out + + def grid3(manifest): """The launch grid padded to three axes.""" g = list(manifest["grid"]) + [1, 1, 1] @@ -113,7 +127,7 @@ def _run(cmd, cwd, log): return proc -def launch(obj_dir, manifest, runtime, raw_paths, log, jobs=None): +def launch(obj_dir, manifest, runtime, raw_paths, log, jobs=None, scalars=()): """Run the whole launch grid, leaving each written argument in its .raw.""" elf = artifact(obj_dir, manifest, "elf") shutil.rmtree(os.path.join(runtime, "indirect_access"), ignore_errors=True) @@ -135,7 +149,7 @@ def launch(obj_dir, manifest, runtime, raw_paths, log, jobs=None): f"--machine-config={yml}", f"--kernel-addr={lo:x}:{hi:x}", f"--base-path={runtime}", - PK, elf, *argv_paths, + PK, elf, *argv_paths, *scalars, ] total = 1 diff --git a/Simulator/timing.py b/Simulator/timing.py index 8d9f554dd..3138f510a 100644 --- a/Simulator/timing.py +++ b/Simulator/timing.py @@ -75,7 +75,7 @@ def write_tensors(workdir): def write_shape(workdir, meta, args=()): """Write the grid extents the trace producer reads as shape_args. - The trailing integers of `args` are the parallel numels, in meta order. A + The parallel numels are read off `args` by the kernel's parameter names. A template's trailing arguments ARE its grid, so its extents are used as is. """ numels = dict(meta["numels"]) @@ -85,10 +85,16 @@ def write_shape(workdir, meta, args=()): return grid passed = [k for k in numels if not k.startswith("r")] - trailing = [a for a in args if isinstance(a, int) and not isinstance(a, bool)] - if passed and len(trailing) >= len(passed): - for key, val in zip(passed, trailing[-len(passed):]): - numels[key] = val + bound = dict(zip(meta.get("call_params", ()), args)) + if bound: + for key in passed: + if isinstance(bound.get(key), int) and not isinstance(bound[key], bool): + numels[key] = bound[key] + else: + trailing = [a for a in args if isinstance(a, int) and not isinstance(a, bool)] + if passed and len(trailing) >= len(passed): + for key, val in zip(passed, trailing[-len(passed):]): + numels[key] = val grid = list(launch.grid_of({**meta, "numels": numels})) _write_extents(workdir, grid, "grid") diff --git a/scripts/ci/triton_route_passing.txt b/scripts/ci/triton_route_passing.txt index ea5b1edaf..3b89d9f4d 100644 --- a/scripts/ci/triton_route_passing.txt +++ b/scripts/ci/triton_route_passing.txt @@ -249,7 +249,6 @@ tests/ops/attention/test_gqa.py tests/ops/elementwise/test_activation.py tests/ops/elementwise/test_add.py tests/ops/elementwise/test_exponent.py -tests/ops/elementwise/test_fp8.py tests/ops/elementwise/test_transcendental.py tests/ops/fusion/test_addmm_residual.py tests/ops/fusion/test_matmul_scalar.py diff --git a/tests/system/test_patch_scope.py b/tests/system/test_patch_scope.py index 85b992f24..f7710635c 100644 --- a/tests/system/test_patch_scope.py +++ b/tests/system/test_patch_scope.py @@ -19,9 +19,9 @@ def test_reduction_split_is_upstream_off_device(): """A cpu reduction keeps upstream's split factor, not this route's fixed 1.""" device = torch.device("cpu") shapes = ((1 << 20, 2), (1 << 16, 1), (1 << 14, 4)) - ours = [config.inductor_choices_class.reduction_split_factor( + ours = [config.inductor_choices_class().reduction_split_factor( device, r, n, True) for r, n in shapes] - upstream = [InductorChoices.reduction_split_factor( + upstream = [InductorChoices().reduction_split_factor( device, r, n, True) for r, n in shapes] test_result("ReductionSplitOffDevice", torch.tensor(ours), torch.tensor(upstream)) @@ -68,7 +68,7 @@ def test_conv_grid_is_upstream_off_device(): def test_this_device_still_gets_its_own_answers(): """The scoping did not disable the route: npu keeps split 1 and allocation.""" - split = config.inductor_choices_class.reduction_split_factor( + split = config.inductor_choices_class().reduction_split_factor( torch.device("npu"), 1 << 20, 2, True) operand = AlgorithmSelectorCache.generate_example_value( (64,), (1,), "npu", torch.float32, 0) diff --git a/thirdparty/pytorchsim-triton-backend.json b/thirdparty/pytorchsim-triton-backend.json index f3addf3a7..303c52a1b 100644 --- a/thirdparty/pytorchsim-triton-backend.json +++ b/thirdparty/pytorchsim-triton-backend.json @@ -2,6 +2,6 @@ "description": "Pin for the PyTorchSim-Triton-Backend layer: the compiler the codegen route lowers through, its LLVM and Triton, and the vcix-accelerator environment (RISC-V toolchain, pk, Spike, gem5) with the accelerator model. Kept out of github-releases.json so the main torchsim_base image is not rebuilt when this moves. CI builds ghcr.io/.../torchsim_ptb_base:ptb-<12 hex>-base-<12 hex> when missing, pin = sha256 of this file plus Dockerfile.ptb. ref is a commit. The repository is private: the workflow needs a PAT in secrets.TNPU_TOKEN that can read it and its vcix-accelerator submodule.", "pytorchsim_triton_backend": { "repository": "PSAL-POSTECH/PyTorchSim-Triton-Backend", - "ref": "62b7cc32ba86992686a7645b24cb0ac3f06ae570" + "ref": "a901c55dad43cd9f8269a4614ffb411eb56c4dda" } }