Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
28 changes: 14 additions & 14 deletions .claude/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,13 @@ and same device, two transformers:
5.x rewrote the MoE block to remove the graph breaks (12 graphs -> 1), and paid
for it in fallbacks. The wrong number came with them.

**WHAT TO DO INSTEAD.** A rewrite in `pytorchsim/frontend/rewrite_fx_graph.py`,
written in aten ops the backend already lowers, so the work stays in the graph.
That file exists for exactly this and says so. Note that casting an operand until
the CPU kernel accepts it is only half the job: the histc decomposition there
still leaves `aten.histc` as an extern call, and its own docstring names the
device-side form it should have been (`(x == bin).sum()` against `arange(bins)` —
one elementwise and one reduce).
**WHAT TO DO INSTEAD.** A rewrite in `pytorchsim/frontend/inductor/post_grad_pass.py`,
the npu's `device_custom_pass`, written in aten ops Inductor lowers as they are
(the pass runs after decomposition), so the work stays in the graph. Casting an
operand until the CPU kernel accepts it is only half the job: histc, for one, is
counted there with aten's own bin rule, so no histc leaves the device. An op
with a Triton kernel of its own (topk, grouped_mm, SDPA) registers it through
torch.library instead, in its own file under `pytorchsim/frontend/dispatcher/`.

**IF YOU CANNOT REMOVE ONE,** say so in those words and name it. A fallback left
in place is a known hole in what "this model runs" means, and it belongs in the
Expand All @@ -67,17 +67,17 @@ report next to the number it produced — never folded into a pass.
| Path | Purpose |
|---|---|
| `pytorchsim/config.py` | The central settings reader, shared by every stage |
| `pytorchsim/frontend/` | The graph side, where the framework is met: `rewrite_fx_graph.py` (our FX graph rewrites, so ops with no `npu` kernel stay on the device) and `inductor_patches.py` (decompositions, template and tile choices, the patches that make Inductor's Triton route serve `npu`) |
| `pytorchsim/frontend/` | The graph side, where the framework is met: `post_grad_pass.py` (the npu's post-grad pass, Inductor's `device_custom_pass`: rewrites so ops with no `npu` kernel stay on the device), `triton_ops/` (`topk.py`, `grouped_mm.py`, `attention.py`: ops with a Triton kernel of their own, SDPA's fused ones among them, through torch.library) `choices.py` (NPUChoices, Inductor's `inductor_choices_class`: conv tiles, persistent reductions, splits, recorded picks; the mm/bmm template heuristics; `pinned_blocks`), `selection.py` (how a template's config is picked: TOGSim cycles in timing mode), `triton_gpu.py` (npu as a Triton GPU to Inductor) and `inductor_patches.py` (the lowering patches with no Inductor hook, npu's conv decompositions, and `install()`, which applies everything) |
| `pytorchsim/contract.py` | What the stages share, so none of them imports another for it: the axes and programs of a launch, how far a strided layout reaches in storage, and the kernel workdir (the manifest and artifacts the compiler left, and each process's launch directory) |
| `pytorchsim/codegen/` | What runs while Inductor generates code: `inductor_hooks.py` (the scheduling and wrapper classes registered for `npu`; Inductor writes the Triton source, these wrap it), `kernel_metadata.py` (what the compile step needs from an Inductor kernel), `tiling.py` (block sizes, a template's grid, this machine's mm tiles), `verify.py` (the per-kernel CPU cross-check, both the lines put in the wrapper and the check they call) |
| `pytorchsim/driver/` | Building a kernel and having it run: `codecache.py` (the compile entry point, the cache and the identity that admits it, the launcher), `select.py` (a template's config: Inductor's selection timed on TOGSim, and the recorded picks), `autotune.py` (smaller pinned blocks when the compiler says too big), `compiler_input.py` (what the compiler is handed: the rewritten Triton source and the KernelSpec file), `compiler_bridge.py` (PyTorchSim-Triton-Backend in a subprocess, the target description) |
| `pytorchsim/frontend/inductor/codegen/` | What runs while Inductor generates code: `inductor_hooks.py` (the scheduling and wrapper classes registered for `npu`; Inductor writes the Triton source, these wrap it), `kernel_metadata.py` (what the compile step needs from an Inductor kernel), `tiling.py` (block sizes, a template's grid, this machine's mm tiles), `verify.py` (the per-kernel CPU cross-check, both the lines put in the wrapper and the check they call) |
| `pytorchsim/backend/` | Building a kernel and having it run: `codecache.py` (the compile entry point, the cache and the identity that admits it, the launcher), `select.py` (a template's config: Inductor's selection timed on TOGSim, and the recorded picks), `autotune.py` (smaller pinned blocks when the compiler says too big), `compiler_input.py` (what the compiler is handed: the rewritten Triton source and the KernelSpec file), `compiler_bridge.py` (PyTorchSim-Triton-Backend in a subprocess, the target description) |
| `pytorchsim/simulator/` | What runs a kernel object: `functional.py` (tensors to disk, Spike, tensors back), `timing.py` (gem5 tile cycles, the cycle and unit tables beside the TOG, TOGSim), `togsim.py` (`TOGSimProcess`, the TOGSim process, and `poisson_request_generator`), `wallclock.py` (where the run's own time went) |
| `device/` | C++ PyTorch backend registering the `npu` device. Built as a pip-installed package via `setup.py`. Based on `torch_openreg` (PrivateUse1 example). Produces `_C.cpython-*.so` |
| `$TOGSIM_DIR` (not in this repo) | TOGSim, the repository PSAL-POSTECH/TOGSim, as the compiler checkout carries it: `$TORCHSIM_COMPILE_DIR/third_party/TOGSim`. C++ source in `src/` and `include/` (`include/togsim_runtime.h` is the C ABI a TOG is compiled against), the built `build/bin/Simulator`, and `configs/` |
| `$TOGSIM_DIR/configs/` | TOGSim machine files (YAML); `config.CONFIG_TOGSIM_CONFIG_DIR`. `TORCHSIM_TARGET` names one (`tpuv6e` by default, i.e. `tpuv6e.yml`) |
| `tests/` | Op- and model-level tests organized under `ops/<family>/` (elementwise, reduce, gemm, conv, attention, view, sort, misc, fusion), `models/<name>/` (Llama, Mixtral8x7B, DeepSeek, Diffusion, MoE, MLP, MobileNet, Yolov5) plus single-file model tests (test_resnet, test_transformer, test_vit, test_mlp, test_single_perceptron), and `system/` (eager, vectorops, TOGSim session and result, selection). Shared helper: `tests/_pytorchsim_utils.py`. **Which of them pass is `scripts/ci/triton_route_passing.txt`**; the rest are known gaps, swept and reported by `scripts/ci/triton_route_sweep.py --all` |
| `tests/` | Op- and model-level tests organized under `ops/<family>/` (elementwise, reduce, gemm, conv, attention, view, sort, misc, fusion), `models/<name>/` (Llama, Mixtral8x7B, DeepSeek, Diffusion, MoE, MLP, MobileNet, Yolov5) plus single-file model tests (test_resnet, test_transformer, test_vit, test_mlp, test_single_perceptron), and `system/` (eager, vectorops, TOGSim session and result, selection). Shared helper: `tests/result_check.py` (`check_result`). **Which of them pass is `scripts/ci/triton_route_passing.txt`**; the rest are known gaps, swept and reported by `scripts/ci/triton_route_sweep.py --all` |
| `experiments/artifact/` | Paper reproduction scripts (`cycle_validation/run_cycle.sh`, `speedup/run_speedup.sh`) |
| `scripts/` | Dev tools (`util_viewer.py`, `trace_timeline.py`, `op_coverage.py`, `clear_codegen_cache.sh`, `setup_worktree.sh`) and CI helpers (`ci/`). `build_from_source.sh` builds the compiler and its simulators through PTB |
| `scripts/` | Dev tools (`util_viewer.py`, `trace_timeline.py`, `clear_codegen_cache.sh`, `setup_worktree.sh`) and CI helpers (`ci/`). `build_from_source.sh` builds the compiler and its simulators through PTB |
| `docker/` | CI's images: `Dockerfile.base` (the compiler's published image at the pin plus the test stack) and `Dockerfile` (this tree on top of it), each with its own `.dockerignore`. The build context is the repository root |
| `third_party/` | Version pins, no code: `pytorchsim-triton-backend.json` (the compiler commit, which is also what pins TOGSim) and `github-releases.json` |
| `togsim_results/` | TOGSim log + trace dump directory (per-run) |
Expand Down Expand Up @@ -111,7 +111,7 @@ export TORCHSIM_FUNCTIONAL_MODE=0 # skips Spike; outputs are not computed, so
reach is the one that owns it.

**To find which op a wrong result first diverges at** (per-kernel CPU cross-check;
sub-option of functional mode, `pytorchsim/codegen/verify.py`). Set `TORCHSIM_FUNCTIONAL_VERIFY_PER_KERNEL=1`,
sub-option of functional mode, `pytorchsim/frontend/inductor/codegen/verify.py`). Set `TORCHSIM_FUNCTIONAL_VERIFY_PER_KERNEL=1`,
clear the codegen cache, and re-run: each compiled kernel's
output is compared to a CPU golden and the run stops at the first divergent
kernel, naming the op and offending indices.
Expand Down Expand Up @@ -173,7 +173,7 @@ with torch.npu.TOGSimulator(config_path=...):

## Where to look for X

- **Adding a new op:** nothing here, usually — Inductor's own Triton lowerings emit the kernel and PyTorchSim-Triton-Backend lowers it. What lives here is our FX graph rewrites, `rewrite_fx_graph.py`: decompositions and post-grad passes for ops with no `npu` kernel (histc, polar, topk, transformers' grouped_mm, complex arithmetic). GEMM/BMM tile selection: `pytorchsim/codegen/tiling.py` (`gemm_tile_candidates`). Kernel source fixups before the compiler sees them: `pytorchsim/driver/compiler_input.py`.
- **Adding a new op:** nothing here, usually — Inductor's own Triton lowerings emit the kernel and PyTorchSim-Triton-Backend lowers it. What lives here is the npu's post-grad pass, `post_grad_pass.py`, for ops with no `npu` kernel (histc, polar, a row times a matrix, complex arithmetic), and torch.library kernels for ops with a Triton kernel of their own (`triton_ops/topk.py`, `triton_ops/grouped_mm.py`, `triton_ops/attention.py`). GEMM/BMM tile selection: `pytorchsim/frontend/inductor/codegen/tiling.py` (`gemm_tile_candidates`). Kernel source fixups before the compiler sees them: `pytorchsim/backend/compiler_input.py`.
- **Adding a PyTorch device op:** `device/csrc/aten/native/*` (Minimal/Extra split mirrors `torch_openreg`).
- **TOGSim hardware model changes:** in the TOGSim repository, `src/{Core,Dram,Interconnect,L2Cache,Tile,TileGraph}.cc` + matching `include/*.h`. They reach this repository when the compiler pins that TOGSim commit and this repository pins that compiler commit.
- **TOG generation:** the compiler emits the tile-operation-graph (TOG) as C++, compiles it to `tog.so` against TOGSim's `togsim_runtime.h` and records the compute type of each tile (`pytorchsim_triton_compiler/lowering/tog/`; `tog_cpp`, `tog_so` and `tile_types` in `kernel.json`); this repo measures the tiles under gem5 and writes `tog_cycles.tsv` and `tog_units.tsv` beside the TOG (`pytorchsim/simulator/timing.py`); TOGSim replays the TOG into a TileGraph (`tog_to_tilegraph`).
Expand Down
2 changes: 1 addition & 1 deletion device/csrc/aten/native/Extra.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ int64_t _fused_sdp_choice(

// The overrideable op carries a call it can state whole: no mask, no dropout, no gradient (its
// npu kernel has no backward), H dividing Hq. Whether a fused kernel then takes it is
// pytorchsim/frontend/attention.py's fused_plan alone; what that declines runs SDPA's math.
// pytorchsim/frontend/dispatcher/attention.py's fused_plan alone; what that declines runs SDPA's math.
const int64_t Hq = query.size(-3), H = key.size(-3);
const bool grad = at::GradMode::is_enabled() &&
(query.requires_grad() || key.requires_grad() || value.requires_grad());
Expand Down
20 changes: 4 additions & 16 deletions device/torch_openreg/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,27 +18,15 @@

sys.path.append(os.environ.get('TORCHSIM_DIR', default='/workspace/PyTorchSim'))
import pytorchsim.config # noqa: F401
from pytorchsim.frontend import inductor_patches as _inductor_patches
from pytorchsim.frontend import rewrite_fx_graph as _rewrite_fx_graph

_rewrite_fx_graph.install()
_inductor_patches.install()

# The `npu` codegen route: Inductor's own Triton codegen, lowered by the
# compiler passes. Registered here because Inductor registers a backend per
# device, once.
from pytorchsim.codegen import TritonNPUScheduling, TritonNPUWrapperCodegen
torch._inductor.codegen.common.register_backend_for_device(
"npu",
TritonNPUScheduling,
TritonNPUWrapperCodegen
)
from pytorchsim import frontend as _frontend

_frontend.install()

torch_openreg.openreg.init()
torch_openreg.openreg.register_eager_to_compile(
torch_openreg.openreg.DEFAULT_EAGER_TO_COMPILE)
sys.modules['torch.npu'] = torch_openreg.openreg

def _autoload():
# It is a placeholder function here to be registered as an entry point.
"""A placeholder registered as torch's device-backend entry point."""
pass
4 changes: 0 additions & 4 deletions device/torch_openreg/openreg/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,9 @@
import threading

import torch
from torch._dynamo.device_interface import register_interface_for_device
import torch_openreg._C # type: ignore[misc]

from . import meta # noqa: F401
from . import extension_device_op_overrides
from .extension_device_interface import ExtensionDeviceInterface

_initialized = False
_default_streams = {} # Dictionary to store default streams per device
Expand Down Expand Up @@ -80,7 +77,6 @@ def _lazy_init():
return

torch_openreg._C._init()
register_interface_for_device(custom_device(), ExtensionDeviceInterface)
_initialized = True

# Create default streams for all devices
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
"""A kernel the compiler refuses as too big is retried at smaller blocks.

A kernel's pinned blocks (its fixed_config) halve when the compiler says they do not fit. A
template's own blocks are its config, which Inductor chose (driver/select.py), and are built as
template's own blocks are its config, which Inductor chose (backend/select.py), and are built as
rendered.
"""

import copy
import itertools

from pytorchsim.driver import compiler_bridge
from pytorchsim.backend import compiler_bridge


def too_big(exc):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from pytorchsim import config

from pytorchsim import contract
from pytorchsim.driver import autotune, compiler_bridge, compiler_input
from pytorchsim.backend import autotune, compiler_bridge, compiler_input
from pytorchsim.simulator import functional, timing, wallclock

logger = config.setup_logger()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,8 @@ def compiler_env():


def run_pipeline(spec_path, workdir, to_stage="torchsim-compile", tog=False, timeout=1800):
"""Drive the compiler's stages over `spec_path`, writing artifacts into `workdir`.

Stops at `to_stage`, by default `torchsim-compile` -- the ELF: spike and verify
want tensors and a per-kernel reference this route has no graph-level answer for.
"""
"""Drive the compiler's stages over `spec_path`, writing artifacts into `workdir`, up to
`to_stage` (by default `torchsim-compile`, the ELF)."""
cmd = [config.CONFIG_TORCHSIM_COMPILE_PYTHON,
os.path.join(compiler_dir(), "pytorchsim-triton-compiler"), spec_path,
"--from", "triton-compile", "--to", to_stage, "--workdir", workdir] + (["--tog"] if tog else [])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from pytorchsim import contract
from pytorchsim.contract import SpecIncomplete
from pytorchsim.driver import compiler_bridge
from pytorchsim.backend import compiler_bridge

_C_TYPE = {"i32": "int32_t", "i64": "int64_t", "fp32": "float"}

Expand All @@ -35,7 +35,7 @@ def scalar_args(meta):


SPEC_TEMPLATE = '''\
"""Generated by pytorchsim/driver/compiler_input.py -- do not edit.
"""Generated by pytorchsim/backend/compiler_input.py -- do not edit.

Inductor kernel {kernel_name!r}: the compiler takes its @triton.jit function, with the block
sizes pinned as constexprs, so the launch shape is static. See compiler_input.py for why.
Expand Down
6 changes: 3 additions & 3 deletions pytorchsim/driver/select.py → pytorchsim/backend/select.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
import time

from pytorchsim import config, contract
from pytorchsim.codegen import kernel_metadata
from pytorchsim.driver import autotune, compiler_bridge, compiler_input
from pytorchsim.frontend.inductor.codegen import kernel_metadata
from pytorchsim.backend import autotune, compiler_bridge, compiler_input
from pytorchsim.simulator import timing

logger = config.setup_logger()
Expand Down Expand Up @@ -181,7 +181,7 @@ def record_path():
def identity():
"""What a recorded pick was timed with: the compiler this tree pins, the machine and TOGSim's
runtime ABI."""
from pytorchsim.driver import codecache
from pytorchsim.backend import codecache
with open(PIN_FILE) as f:
pin = json.load(f)["pytorchsim_triton_backend"]["ref"]
whole = codecache.identity()
Expand Down
6 changes: 3 additions & 3 deletions pytorchsim/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,13 @@ def __getattr__(name):
if name == "CONFIG_TORCHSIM_TARGET":
return os.environ.get("TORCHSIM_TARGET") or "tpuv6e"
if name == "CONFIG_MACHINE":
from pytorchsim.driver import compiler_bridge
from pytorchsim.backend import compiler_bridge
return compiler_bridge.target()
if name == "CONFIG_MACHINE_FILE":
from pytorchsim.driver import compiler_bridge
from pytorchsim.backend import compiler_bridge
return compiler_bridge.target().file
if name == "CONFIG_NUM_CORES":
from pytorchsim.driver import compiler_bridge
from pytorchsim.backend import compiler_bridge
with open(compiler_bridge.target().file) as f:
return yaml.safe_load(f)["num_cores"]

Expand Down
25 changes: 24 additions & 1 deletion pytorchsim/frontend/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,24 @@
"""The graph side: FX rewrites and the Inductor patches that make its Triton route serve npu."""
"""What PyTorchSim plugs into torch.compile, one package per layer it meets:

dynamo/ npu's DeviceInterface
inductor/ npu as an Inductor backend and the patches to Inductor's passes, choices and codegen
dispatcher/ ops with a Triton kernel of their own, registered at the npu dispatch keys

What compiles and runs a kernel after Inductor is pytorchsim/backend and pytorchsim/simulator.
"""


def install():
"""Plug npu into every layer, once."""
global _installed
if _installed:
return
from . import dispatcher, dynamo, inductor

dynamo.install()
inductor.install()
dispatcher.install()
_installed = True


_installed = False
11 changes: 11 additions & 0 deletions pytorchsim/frontend/dispatcher/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
"""Ops the npu takes as a Triton kernel of our own: each module registers its op's npu kernel through
torch.library and launches the kernel as a triton_op (torchsim::<op>). Rewrites into aten ops are
frontend/post_grad_pass.py instead."""


def install():
"""Register every op's npu kernel, once each."""
from . import attention, grouped_mm, topk
attention.install()
grouped_mm.install()
topk.install()
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def _decode_tiles(GP, BKV, D, esize):

def _fits(tiles):
"""Whether `tiles` fit one lane's scratchpad budget, and each is a tensor Triton builds."""
from pytorchsim.codegen import tiling
from pytorchsim.frontend.inductor.codegen import tiling
big = tiling.triton_max_numel()
return (all(r * c <= big for r, c, _ in tiles)
and _lane_bytes(tiles) <= int(config.CONFIG_MACHINE.spad_budget))
Expand Down Expand Up @@ -278,7 +278,7 @@ def install():
backend key, where a call made under inference_mode lands. Count each fused kernel launch."""
global _lib
if _lib is None:
from pytorchsim.driver import codecache
from pytorchsim.backend import codecache
codecache.observe_launches(_prefill_kernel, lambda: _count("prefill"))
codecache.observe_launches(_decode_kernel, lambda: _count("decode"))
_lib = torch.library.Library("aten", "IMPL")
Expand Down
Loading