From b1df71be5f36413b31cf747af6bf4ecf8ab3ee17 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 9 Oct 2026 21:22:07 +0900 Subject: [PATCH 01/15] [Deps] torch 2.14 / triton 3.8, to match PyTorchSim-Triton-Backend PyTorchSim-Triton-Backend moved to Triton 3.8 on 2026-10-07, and the first Inductor that targets Triton 3.8 is torch 2.14's. The pins move from torch 2.10 / torchvision 0.25 / triton 3.6 to 2.14.0 / 0.29.0 / 3.8.0, and the frontend follows the Inductor APIs that changed on the way: sizevars.size_hint -> optimization_hint (inductor_patches, kernel_spec, launch) inductor_choices_class must implement uuid(); reduction_split_factor is an instance method and calls super() register_backend_for_device takes the scheduling class, not a factory has_triton() asks every device interface is_available() and is_triton_capable(); npu answers yes write_header puts the imports in self.imports, and the wrapper's call() is a method of a Runner class, so the copied generate/write_prefix go: write_header splices our setup after super(), write_args adds verify_init, and run_wrapper_ir_passes inserts the per-buffer verify lines as WrapperLines KernelCallLine.codegen passes inductor_meta and friends as kwargs ComboKernel.combo_grid_meta takes the sub-kernels' size hints torch 2.14's headers need C++20 (PyTorchSimDevice/CMakeLists.txt) Verified on a cleared cache with torch 2.14.0+cpu and PTB main bb37976: the allowlist sweep (scripts/ci/triton_route_sweep.py) passes 40 of 44 with the commits that follow this one; the four left are deepseek, qwen and qwen_next (fixed next) and test_fp8, whose f8E5M2 the compiler no longer lowers. --- CLAUDE.md | 2 +- Dockerfile.base | 11 +- PyTorchSimCodegen/inductor_patches.py | 15 +- PyTorchSimCodegen/kernel_spec.py | 4 +- PyTorchSimCodegen/launch.py | 4 +- PyTorchSimCodegen/wrapper_codegen.py | 181 ++++++------------ PyTorchSimDevice/CMakeLists.txt | 2 +- PyTorchSimDevice/torch_openreg/__init__.py | 2 +- .../openreg/extension_device_interface.py | 10 + tests/system/test_patch_scope.py | 6 +- 10 files changed, 90 insertions(+), 147 deletions(-) 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/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..995d2738b 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 @@ -165,7 +165,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 diff --git a/PyTorchSimCodegen/launch.py b/PyTorchSimCodegen/launch.py index f27d81fc6..5ee2a9cff 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 diff --git a/PyTorchSimCodegen/wrapper_codegen.py b/PyTorchSimCodegen/wrapper_codegen.py index 7a534f9e6..c0e70e488 100644 --- a/PyTorchSimCodegen/wrapper_codegen.py +++ b/PyTorchSimCodegen/wrapper_codegen.py @@ -3,12 +3,11 @@ Emits the header the wrapper needs (torchsim_compile, 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 +34,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.""" @@ -59,126 +67,52 @@ def wrap_kernel_call(self, name, call_args): 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, **kwargs): + """A kernel call is a plain function call; grid, stream and autotune do not apply.""" 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 +134,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 +147,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/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/extension_device_interface.py b/PyTorchSimDevice/torch_openreg/openreg/extension_device_interface.py index e0a6783c4..ec4129e3a 100644 --- a/PyTorchSimDevice/torch_openreg/openreg/extension_device_interface.py +++ b/PyTorchSimDevice/torch_openreg/openreg/extension_device_interface.py @@ -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/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) From 2416736f1e111a49d058c17abc30cdbc5b8aceb0 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 9 Oct 2026 21:22:08 +0900 Subject: [PATCH 02/15] [Codegen] Autotune only in timing mode; a template too big for the machine retries the next mapped tile Template autotune compiled the top-4 mm tiles each with --tog, gem5 and a TOGSim run, in a functional-only run as well, where no cycle is ever read. That is where the big models' time went: test_llama alone spent 10 minutes in autotune (one bmm candidate took 204 s) and timed out the sweep, as did llama3x, gemma and qwen. Autotune now runs only when pytorchsim_timing_mode is on, since cycles are what it ranks by. test_llama passes in 239 s on the functional config, gemma in 804 s, llama3x in 292 s. The scratchpad-overflow retry knew only pointwise and reduction blocks: a template kernel's BLOCK_M/N/K are literals in its source, so nothing was retried and mobilenet's 1x1 conv via mm stopped at BLOCK_M=16384 with 458880 bytes/lane over 262144. _smaller_tiles now yields the other mapped tiles of an mm template (best first) and the fixed_config halvings for every other kernel, and the same loop retries when the ELF spills: the compiler refuses any vector register spill ([binary] spill not allowed), and a tile that spills is a tile too big for the register file the same way. qwen_next's mm 16x8192x64 spilled at BLOCK_N=8192 and compiles at 4096; test_qwen_next passes in 364 s, test_mobilenet in 1148 s. --- PyTorchSimCodegen/codecache.py | 83 ++++++++++++++++++++++++---------- 1 file changed, 60 insertions(+), 23 deletions(-) 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: From 785ef98ccd10870c38448ae729edb835627b93db Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 9 Oct 2026 21:22:08 +0900 Subject: [PATCH 03/15] [Codegen] CompilerError carries the compiler's own stage diagnostic The compiler prints one failure paragraph under the stage that failed: [2/2] torchsim-compile:lower FAIL (0.4s) ... no fold or peel states this rank-5 tile [16, 2, 8, 4, 2] in 4 descriptor dims: ... The message filter skipped it: _SIGNAL rejects indented lines, and the paragraph is indented, so a failure like the one above reached Inductor as three "[transform] ..." progress lines. The paragraph's first line is now taken first, _SIGNAL second; the latter also accepts a dotted exception name with its message (DigitRefused) and the [transform]/[lower]/[binary] refusals, which it missed before. --- PyTorchSimCodegen/compiler_bridge.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) 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)] From 51bbb5e1c6aa623ad55be7b323647f63d0406281 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 9 Oct 2026 21:22:08 +0900 Subject: [PATCH 04/15] [Codegen] A 0-d CPU input stays a pointer argument on npu Inductor unwraps a 0-d CPU tensor input into a scalar kernel argument on every device but cpu (should_unwrap_unspec_arg), so the kernel signature said fp32 while the spec, built from the argument types, said *fp32, and the launch passed a tensor where the compiler had baked a scalar. Adam's step counter is such an input, so test_mlp's training step failed at its first fused kernel. The compiler bakes scalars into the ELF, and this one changes on every call, so on npu the input stays a tensor the kernel loads. test_mlp passes (10 checks, 37 s). --- PyTorchSimCodegen/inductor_patches.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/PyTorchSimCodegen/inductor_patches.py b/PyTorchSimCodegen/inductor_patches.py index bd3a58b53..eea6c1c4b 100644 --- a/PyTorchSimCodegen/inductor_patches.py +++ b/PyTorchSimCodegen/inductor_patches.py @@ -560,6 +560,22 @@ def _npu_convolution(input, weight, bias, stride, padding, dilation, return conv1d_to_conv2d(input, weight, bias, stride, padding, dilation, groups) +def _keep_zero_dim_inputs_as_pointers(): + """On npu, a 0-d CPU input (Adam's step) stays a tensor the kernel loads, not a scalar. + + The compiler bakes scalars into the ELF, and this one changes on every call. + """ + from torch._inductor.codegen import triton, triton_utils, wrapper + + orig = triton_utils.should_unwrap_unspec_arg + + def should_unwrap_unspec_arg(name): + return not _lowering_npu() and orig(name) + + for mod in (triton_utils, triton, wrapper): + mod.should_unwrap_unspec_arg = should_unwrap_unspec_arg + + def _install_selection(): """Patch algorithm selection for npu choices: no precompile, no benchmark, allocate-only examples.""" from torch._inductor.select_algorithm import AlgorithmSelectorCache @@ -617,6 +633,7 @@ def install(): _short_circuit_degenerate_gemms() _install_npu_choices() _lower_conv1d_as_conv2d() + _keep_zero_dim_inputs_as_pointers() _install_selection() inductor_config.max_autotune_gemm = True From b7e8a77dbfac9662e372ff44558ea78bed29ea04 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 9 Oct 2026 21:22:08 +0900 Subject: [PATCH 05/15] [Device] eager_to_compile keeps dynamo's torch-function mode stack A compiled call under `with torch.device("npu")` failed with "trying to pop from empty mode stack". Dynamo saves the torch-function mode stack in a module-level TorchFunctionModeStackStateManager while it traces, and restores it when tracing ends. An op the device has no eager kernel for reaches eager_to_compile from inside Inductor's tracing (Dynamo runs the graph's constants eagerly), and its own torch.compile entered the same manager, whose __exit__ reset the saved stack to [] -- so the outer trace restored nothing and the device context's __exit__ had nothing to pop. The nested compile now puts the outer stack back on the manager when it returns. test_swinv2, which names the default device for the compiled call, passes (86 s). --- PyTorchSimDevice/torch_openreg/openreg/__init__.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/PyTorchSimDevice/torch_openreg/openreg/__init__.py b/PyTorchSimDevice/torch_openreg/openreg/__init__.py index a77344dee..03f365c03 100644 --- a/PyTorchSimDevice/torch_openreg/openreg/__init__.py +++ b/PyTorchSimDevice/torch_openreg/openreg/__init__.py @@ -407,11 +407,15 @@ def wrapper(*args, **kwargs): def dummy_graph(*args, **kwargs): return op(*args, **kwargs) + from torch._dynamo.variables.torch_function import ( + torch_function_mode_stack_state_mgr as modes) + outer = modes.stack in_flight.busy = True try: return dummy_graph(*args, **kwargs) finally: in_flight.busy = False + modes.stack = outer if op_name in _eager_compiled: return From 6781336f71c7c5ef76ea0385e1c1c494956803ac Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 9 Oct 2026 21:26:21 +0900 Subject: [PATCH 06/15] [Codegen] A numel of 1 pins a block of 1 _covers left an axis whose numel is 1 at the lane-wide block, on the reasoning that a block of 1 leaves the lanes none. For a reduction kernel that is the wrong axis to spend them on: a sort over 64 values with xnumel = 1 became a 256x64 tile with one valid row, TritonGPU laid its lanes over both axes, materialize_layouts cut the rows into digits, and the masked store on that axis was refused: DigitRefused: a DMA masked_axes on a dim cut into digits which stopped DeepSeek-V3 and Qwen3 at their first top-k sort kernel, and test_sort at its first kernel. With XBLOCK = 1 the tile is 1x64, the lanes go to the reduction axis, and the same kernel compiles; a pointwise kernel of one element compiles at a block of 1 too, so nothing needs the old exception any more. Verified on cleared caches: test_deepseek_v3_base passes (333 s), test_qwen (514 s), test_topk (6 s); test_sort gets past its first ten checks and now stops at a 64-row kernel the compiler cannot fit into four descriptor dims, which is the compiler's gap, not this one's. --- PyTorchSimCodegen/launch.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/PyTorchSimCodegen/launch.py b/PyTorchSimCodegen/launch.py index 5ee2a9cff..97c92344e 100644 --- a/PyTorchSimCodegen/launch.py +++ b/PyTorchSimCodegen/launch.py @@ -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: From 5d7d84017d8fafb027faa009d5c140684e27d7ac Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 9 Oct 2026 22:15:07 +0900 Subject: [PATCH 07/15] [Codegen] A kernel's scalar parameters are passed at launch, not baked into the ELF The compiler took every scalar parameter (`r0_numel`, and an input Inductor unwraps to a value) as a literal in the spec's `scalar_values` and compiled it into the driver, so the previous commit had to keep Adam's step counter a pointer by patching Inductor's should_unwrap_unspec_arg. PyTorchSim- Triton-Backend 7787b4c reads the scalars off argv after the tensor paths and lists them in kernel.json, so that patch goes and the kernel is the one every other Triton backend compiles. collect_meta records `call_params`, the kernel's parameter names in call order, and leaves a scalar out of the tensor args; scalar_args gives a numel its codegen value as the default and an unwrapped input none; the launch binds call_params to the call's arguments, and spike_run appends each scalar's value (argv_scalars) after the .raw paths. write_shape reads the parallel numels by name instead of taking the trailing integers, which a runtime integer scalar would have joined. gem5 passes no argv and keeps the defaults; the trace producer never reads a scalar. The wrapper applied prepare_triton_kernel_call to every kernel call, so the CPU island's C++ foreach kernel (the step counters' `+= 1`) was handed `.item()` values where it expects tensors once the unwrap was on. A C++ kernel's call is now rendered plainly, as Inductor's own path does. The compiler pin moves to 7787b4c (branch runtime-scalars, PSAL-POSTECH/ PyTorchSim-Triton-Backend#39) for the ABI and for the pass that lowers the shared-body foreach kernel Inductor emits once the scalar is a scalar. Verified: test_mlp passes 10 checks in 28 s (Adam over four parameters, the step a scalar parameter of the combo kernel); test_add, test_topk, test_swinv2 pass; allowlist sweep in the PR. --- PyTorchSimCodegen/inductor_patches.py | 17 ----------------- PyTorchSimCodegen/kernel_spec.py | 19 +++++++++---------- PyTorchSimCodegen/wrapper_codegen.py | 16 +++++++++------- Simulator/functional.py | 13 +++++++------ Simulator/spike_run.py | 18 ++++++++++++++++-- Simulator/timing.py | 16 +++++++++++----- thirdparty/pytorchsim-triton-backend.json | 2 +- 7 files changed, 53 insertions(+), 48 deletions(-) diff --git a/PyTorchSimCodegen/inductor_patches.py b/PyTorchSimCodegen/inductor_patches.py index eea6c1c4b..bd3a58b53 100644 --- a/PyTorchSimCodegen/inductor_patches.py +++ b/PyTorchSimCodegen/inductor_patches.py @@ -560,22 +560,6 @@ def _npu_convolution(input, weight, bias, stride, padding, dilation, return conv1d_to_conv2d(input, weight, bias, stride, padding, dilation, groups) -def _keep_zero_dim_inputs_as_pointers(): - """On npu, a 0-d CPU input (Adam's step) stays a tensor the kernel loads, not a scalar. - - The compiler bakes scalars into the ELF, and this one changes on every call. - """ - from torch._inductor.codegen import triton, triton_utils, wrapper - - orig = triton_utils.should_unwrap_unspec_arg - - def should_unwrap_unspec_arg(name): - return not _lowering_npu() and orig(name) - - for mod in (triton_utils, triton, wrapper): - mod.should_unwrap_unspec_arg = should_unwrap_unspec_arg - - def _install_selection(): """Patch algorithm selection for npu choices: no precompile, no benchmark, allocate-only examples.""" from torch._inductor.select_algorithm import AlgorithmSelectorCache @@ -633,7 +617,6 @@ def install(): _short_circuit_degenerate_gemms() _install_npu_choices() _lower_conv1d_as_conv2d() - _keep_zero_dim_inputs_as_pointers() _install_selection() inductor_config.max_autotune_gemm = True diff --git a/PyTorchSimCodegen/kernel_spec.py b/PyTorchSimCodegen/kernel_spec.py index 995d2738b..2f8b91e22 100644 --- a/PyTorchSimCodegen/kernel_spec.py +++ b/PyTorchSimCodegen/kernel_spec.py @@ -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, @@ -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/wrapper_codegen.py b/PyTorchSimCodegen/wrapper_codegen.py index c0e70e488..651b69173 100644 --- a/PyTorchSimCodegen/wrapper_codegen.py +++ b/PyTorchSimCodegen/wrapper_codegen.py @@ -61,11 +61,6 @@ 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() @@ -91,8 +86,15 @@ def write_args(self, input_names): self.prefix.writeline( f"_fverify.verify_init({gid}, [{', '.join(V.graph.graph_inputs.keys())}])") - def _generate_kernel_call_helper(self, kernel_name, call_args, **kwargs): - """A kernel call is a plain function call; grid, stream and autotune do not apply.""" + def _generate_kernel_call_helper(self, kernel_name, call_args, *, 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); grid, stream and autotune do not apply. A C++ kernel, a + CPU island's, keeps Inductor's own call.""" + if triton: + 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)) def run_wrapper_ir_passes(self, is_inference): 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/thirdparty/pytorchsim-triton-backend.json b/thirdparty/pytorchsim-triton-backend.json index f3addf3a7..6bbf1d9cf 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": "7787b4cafb89253e7f0b60524662af4a27e27149" } } From ce4dc9a07cc1ac88a2e46c36e11190ac1b01cbd0 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 9 Oct 2026 22:15:07 +0900 Subject: [PATCH 08/15] [Device] fill_ and zero_ run natively; eager_to_compile no longer touches dynamo's mode stack fill_.Scalar and zero_ were in DEFAULT_EAGER_TO_COMPILE, so every constant the device made in eager mode (`torch.zeros(..., device="npu")`, and the constants Inductor folds while lowering a graph) went through its own torch.compile. A compile nested inside a compile is what broke swinv2: the nested one reset dynamo's module-level TorchFunctionModeStackStateManager, and the previous commit put the saved stack back through a private dynamo symbol. The device's memory is host memory, so a fill is a host write on the same storage, the way _copy_from already copies: fill_ and zero_ are registered for npu over a CPU view of the tensor, and leave the eager-to-compile list. Nothing is simulated for them, which is also true of cudaMemset; the nested compile for a constant is gone, and with it the dynamo patch. The ops left in DEFAULT_EAGER_TO_COMPILE (cat, mm, pooling, argmax, ...) would still nest a compile if Inductor folded one as a constant; none of the allowlisted models does, and the proper fix for that is a reentrant state manager upstream. Verified: test_swinv2 passes (`with torch.device("npu")` around the compiled call, 92 s); the dynamo repro (torch.zeros inside a compiled function under the device context) passes. --- PyTorchSimDevice/csrc/aten/OpenRegMinimal.cpp | 10 +++++++++ PyTorchSimDevice/csrc/aten/native/Minimal.cpp | 22 +++++++++++++++++++ PyTorchSimDevice/csrc/aten/native/Minimal.h | 2 ++ .../torch_openreg/openreg/__init__.py | 6 ----- 4 files changed, 34 insertions(+), 6 deletions(-) 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/openreg/__init__.py b/PyTorchSimDevice/torch_openreg/openreg/__init__.py index 03f365c03..f2ef69ddc 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", @@ -407,15 +405,11 @@ def wrapper(*args, **kwargs): def dummy_graph(*args, **kwargs): return op(*args, **kwargs) - from torch._dynamo.variables.torch_function import ( - torch_function_mode_stack_state_mgr as modes) - outer = modes.stack in_flight.busy = True try: return dummy_graph(*args, **kwargs) finally: in_flight.busy = False - modes.stack = outer if op_name in _eager_compiled: return From 1950ad2d77efb8146a1b7cf714689b4a1c6e6815 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 9 Oct 2026 22:15:07 +0900 Subject: [PATCH 09/15] [CI] test_fp8 leaves the allowlist PyTorchSim-Triton-Backend refuses 8-bit floats by decision (tests/cases/mechanism/ops/ops_fp8_roundtrip.py: "not on this backend's path ... what remains is upstream LLVM or a fork of the RISC-V backend, and we are not carrying it"), since its adapt-ttgir rework. The test fails at the first fp8 kernel with "f8E5M2 is not an element type this machine runs" and cannot gate a PR. The CI matrix in pytorchsim_test.yml already lacked it, so the two agree again. --- scripts/ci/triton_route_passing.txt | 1 - 1 file changed, 1 deletion(-) 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 From 59c5c908c0ce42a82a6740588f06c3bc00d5354e Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 9 Oct 2026 22:17:49 +0900 Subject: [PATCH 10/15] [Deps] Compiler pin: the integration of PyTorchSim-Triton-Backend #37, #38 and #39 The three compiler changes this branch needs are open as separate pull requests (replica reads through a gather or a merging collapse; the gathered axis matched by tensor axis; scalar parameters at launch and the shared-body foreach kernel). Until they land on main the pin is their merge, branch integration-torch214, so the CI image carries all three; it moves to main once they do. --- thirdparty/pytorchsim-triton-backend.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/thirdparty/pytorchsim-triton-backend.json b/thirdparty/pytorchsim-triton-backend.json index 6bbf1d9cf..c6641d761 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": "7787b4cafb89253e7f0b60524662af4a27e27149" + "ref": "32968d131be9963791e2905e0f12897418c0575c" } } From f404393460c34a23a59e339731950b530d3a9e16 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 9 Oct 2026 22:53:54 +0900 Subject: [PATCH 11/15] [Codegen] No foreach combo kernels on npu; an npu kernel call is a Triton call Inductor fuses torch._foreach_* over a parameter list into one combo kernel that picks each sub-kernel's tensors by program id and runs one body. That dispatch is a GPU launch-overhead trade this machine has nothing to gain from, and the branch is one the TOG cannot time: every form of the kernel, the per-branch bodies of before and the shared body of now, was refused by the trace producer ("15 loop(s) survive into the trace without a TOG node"), so test_mlp never had a timing mode. BackendFeature.FOREACH is dropped from the npu scheduling's features, the hook Inductor gives a backend for this, and a foreach op lowers to one kernel per tensor. The compiler's sink-into-pointer-ifs pass stays for the Triton that does pick pointers by program id. call_kernel passed triton=False, which was how the call escaped the stream and grid rendering; the wrapper's helper now takes triton=True as the npu path, so the call goes through prepare_triton_kernel_call and a 0-d CPU input is unwrapped to its value as the kernel's signature says. The helper renders the line under the kernel's own device: the line is emitted after the CPU island's, when the graph's current device is cpu, where the unwrap is decided the other way for a mutated input. Verified: test_mlp passes 10 checks in functional mode (29 s) and, for the first time, in timing mode (140 s, 24 TOGSim launches); test_add passes. --- PyTorchSimCodegen/scheduling.py | 11 +++++++++-- PyTorchSimCodegen/wrapper_codegen.py | 13 +++++++++---- 2 files changed, 18 insertions(+), 6 deletions(-) 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 651b69173..d998680d7 100644 --- a/PyTorchSimCodegen/wrapper_codegen.py +++ b/PyTorchSimCodegen/wrapper_codegen.py @@ -3,6 +3,7 @@ Emits the header the wrapper needs (torchsim_compile, the functional-verify calls) and walks the wrapper IR lines once. """ +import contextlib import dataclasses import torch @@ -86,12 +87,16 @@ def write_args(self, input_names): self.prefix.writeline( f"_fverify.verify_init({gid}, [{', '.join(V.graph.graph_inputs.keys())}])") - def _generate_kernel_call_helper(self, kernel_name, call_args, *, triton=True, **kwargs): + 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); grid, stream and autotune do not apply. A C++ kernel, a - CPU island's, keeps Inductor's own call.""" + 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: - call_args = self.prepare_triton_kernel_call(call_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) 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] From c5d0d722a80f5bbbb91739cfb09f54bcf3e89251 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 9 Oct 2026 23:37:23 +0900 Subject: [PATCH 12/15] [Deps] Compiler pin: the integration without the sink pass (PyTorchSim-Triton-Backend #37, #38, #39) The pass that lowered Inductor's shared-body foreach kernel is its own pull request now (#40), and nothing on npu asks for that kernel form since BackendFeature.FOREACH went, so the pin is the merge of the three the branch needs. test_mlp, test_add and test_swinv2 pass against it. --- thirdparty/pytorchsim-triton-backend.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/thirdparty/pytorchsim-triton-backend.json b/thirdparty/pytorchsim-triton-backend.json index c6641d761..7fa5c2487 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": "32968d131be9963791e2905e0f12897418c0575c" + "ref": "7dac000e4a4aa3e40b936ade98fa059dcfeac98d" } } From 4fcd5facf29193df9f1b991771543be9cf620b2e Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 9 Oct 2026 23:51:24 +0900 Subject: [PATCH 13/15] [Device] An eager op reached while a compile is in flight runs on the host, not through a second compile eager_to_compile exists so model work that lands in eager mode (a graph break, an op with no eager kernel) is still compiled and simulated. It was also reached from INSIDE the compiler: Inductor folds a constant by running its ops on the device at compile time, and a registered op (fill_ for torch.zeros, mul in `torch.ones(4) * 3`) then started a torch.compile under the one already running. Dynamo keeps the torch-function mode stack in one non-reentrant manager, so the inner compile emptied what the outer one restores and `with torch.device("npu")` failed on exit ("trying to pop from empty mode stack"); on torch 2.14 that is how swinv2 died, and `torch.ones(4) * 3` with mul registered reproduces it on demand. Compile-time work is not the workload: the constant is computed once, by the compiler, and never timed. So an eager op that finds torch.compiler.is_compiling() true runs on the host, like the recursion guard already did, and no compile ever starts inside a compile. The rule is the public API's; the earlier private-symbol patch is not needed. The device interface's Worker.current_device fell through to torch.xpu.current_device(), a leftover of the XPU interface it was copied from, which Inductor's decode_device hits for a factory op whose device has no index (`torch.device("npu")`). It answers torch.npu.current_device(). Verified: the mul reproducer passes with the device given with and without an index; test_eager, test_eager_to_compile_recursion, test_swinv2 (48 s) and test_deepseek_v3_base (259 s, which registers its own eager ops) pass. --- PyTorchSimDevice/torch_openreg/openreg/__init__.py | 8 +++++++- .../torch_openreg/openreg/extension_device_interface.py | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/PyTorchSimDevice/torch_openreg/openreg/__init__.py b/PyTorchSimDevice/torch_openreg/openreg/__init__.py index f2ef69ddc..631f0c2cd 100644 --- a/PyTorchSimDevice/torch_openreg/openreg/__init__.py +++ b/PyTorchSimDevice/torch_openreg/openreg/__init__.py @@ -356,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(). @@ -398,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 ec4129e3a..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: From e09cf96444df2eab7a088caffe5c2f9b1ded63a2 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Sat, 10 Oct 2026 00:16:10 +0900 Subject: [PATCH 14/15] [Deps] Compiler pin: PyTorchSim-Triton-Backend main a901c55, with #37, #41 and #39 merged The integration branch the pin pointed at is retired; main carries the replica reads through a gather or a merging collapse (#37), the gathered axis matched by tensor axis (#41, the retargeted #38) and the scalar parameters at launch with DRAM arguments by tensor ordinal (#39). --- thirdparty/pytorchsim-triton-backend.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/thirdparty/pytorchsim-triton-backend.json b/thirdparty/pytorchsim-triton-backend.json index 7fa5c2487..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": "7dac000e4a4aa3e40b936ade98fa059dcfeac98d" + "ref": "a901c55dad43cd9f8269a4614ffb411eb56c4dda" } } From 453bf1311b34560435dbc73073d4b300d1d0bcfe Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Sat, 10 Oct 2026 00:16:10 +0900 Subject: [PATCH 15/15] [CI] The PR gate also runs for pull requests into pytorchsim-triton-backend docker-image.yml triggered on pull requests into master and develop only, so no PR into the branch PyTorchSim-Triton-Backend pins has ever been gated: #329, #330 and #331 show no checks. The branch everyone shares joins the list. --- .github/workflows/docker-image.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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: