Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
b1df71b
[Deps] torch 2.14 / triton 3.8, to match PyTorchSim-Triton-Backend
student-Jungmin Oct 9, 2026
2416736
[Codegen] Autotune only in timing mode; a template too big for the ma…
student-Jungmin Oct 9, 2026
785ef98
[Codegen] CompilerError carries the compiler's own stage diagnostic
student-Jungmin Oct 9, 2026
51bbb5e
[Codegen] A 0-d CPU input stays a pointer argument on npu
student-Jungmin Oct 9, 2026
b7e8a77
[Device] eager_to_compile keeps dynamo's torch-function mode stack
student-Jungmin Oct 9, 2026
6781336
[Codegen] A numel of 1 pins a block of 1
student-Jungmin Oct 9, 2026
5d7d840
[Codegen] A kernel's scalar parameters are passed at launch, not bake…
student-Jungmin Oct 9, 2026
ce4dc9a
[Device] fill_ and zero_ run natively; eager_to_compile no longer tou…
student-Jungmin Oct 9, 2026
1950ad2
[CI] test_fp8 leaves the allowlist
student-Jungmin Oct 9, 2026
59c5c90
[Deps] Compiler pin: the integration of PyTorchSim-Triton-Backend #37…
student-Jungmin Oct 9, 2026
f404393
[Codegen] No foreach combo kernels on npu; an npu kernel call is a Tr…
student-Jungmin Oct 9, 2026
c5d0d72
[Deps] Compiler pin: the integration without the sink pass (PyTorchSi…
student-Jungmin Oct 9, 2026
4fcd5fa
[Device] An eager op reached while a compile is in flight runs on the…
student-Jungmin Oct 9, 2026
e09cf96
[Deps] Compiler pin: PyTorchSim-Triton-Backend main a901c55, with #37…
student-Jungmin Oct 9, 2026
453bf13
[CI] The PR gate also runs for pull requests into pytorchsim-triton-b…
student-Jungmin Oct 9, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/docker-image.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: Docker image CI

on:
pull_request:
branches: [ "master", "develop" ]
branches: [ "master", "develop", "pytorchsim-triton-backend" ]
workflow_dispatch:

env:
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<sha256 of thirdparty/github-releases.json + Dockerfile.base>`, 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-<sha256 of thirdparty/github-releases.json + Dockerfile.base>`, 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 `<workdir>/launch-<pid>/` (`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.
Expand Down
11 changes: 4 additions & 7 deletions Dockerfile.base
Original file line number Diff line number Diff line change
Expand Up @@ -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.
#
Expand Down
83 changes: 60 additions & 23 deletions PyTorchSimCodegen/codecache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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())
Expand All @@ -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:
Expand Down
10 changes: 7 additions & 3 deletions PyTorchSimCodegen/compiler_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
15 changes: 9 additions & 6 deletions PyTorchSimCodegen/inductor_patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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:
Expand Down
23 changes: 11 additions & 12 deletions PyTorchSimCodegen/kernel_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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

Expand All @@ -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),
Expand Down Expand Up @@ -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 = []
Expand All @@ -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


Expand Down Expand Up @@ -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)
Expand Down
9 changes: 5 additions & 4 deletions PyTorchSimCodegen/launch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
11 changes: 9 additions & 2 deletions PyTorchSimCodegen/scheduling.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.

Expand Down
Loading