Skip to content
Closed
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
18 changes: 9 additions & 9 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/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, attention) registers it
through torch.library instead, in its own file under `pytorchsim/frontend/`.

**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,7 +67,7 @@ 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), `topk.py`, `grouped_mm.py`, `attention.py` (ops with a Triton kernel of their own, through torch.library) and `inductor_patches.py` (decompositions, template and tile choices, the patches that make Inductor's Triton route serve `npu`) |
| `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) |
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 (`topk.py`, `grouped_mm.py`, `attention.py`). 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 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
1 change: 1 addition & 0 deletions .github/workflows/pytorchsim_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ jobs:
- tests/ops/misc/test_user_triton_kernel.py
- tests/ops/misc/test_widen_dtype.py
- tests/ops/reduce/test_batchnorm.py
- tests/ops/sort/test_topk.py
- tests/ops/view/test_view3D_2D.py
- tests/system/test_breakdown_viewer.py
- tests/system/test_bundle_reuse.py
Expand Down
6 changes: 3 additions & 3 deletions device/torch_openreg/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@
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
from pytorchsim.frontend import post_grad_pass as _post_grad_pass

_rewrite_fx_graph.install()
_inductor_patches.install()

# The `npu` codegen route: Inductor's own Triton codegen, lowered by the
Expand All @@ -31,7 +30,8 @@
torch._inductor.codegen.common.register_backend_for_device(
"npu",
TritonNPUScheduling,
TritonNPUWrapperCodegen
TritonNPUWrapperCodegen,
device_custom_pass=_post_grad_pass.pytorchsim_post_grad_pass,
)

torch_openreg.openreg.init()
Expand Down
30 changes: 19 additions & 11 deletions pytorchsim/frontend/grouped_mm.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""aten._grouped_mm on the npu (2-D A grouped by offs, times 3-D B) as one Triton kernel in fused_moe form: a
program is a block of BM rows of one group, its group, first row and row count read from a table the TOG takes
as launch data; a block without rows runs its K loop zero times. Registered through torch.library."""
"""aten._grouped_mm and transformers' grouped_mm_fallback on the npu (2-D A grouped by offs, times 3-D B) as one
Triton kernel in fused_moe form: a program is a block of BM rows of one group, its group, first row and row count
read from a table the TOG takes as launch data. Both ops register one entry through torch.library."""

import torch
import triton
Expand Down Expand Up @@ -111,14 +111,22 @@ def _aten_grouped_mm(a, b, offs=None, bias=None, out_dtype=None):
return grouped_mm(a, b, offs)


_lib = None
def _transformers_grouped_mm_fallback(input, weight, offs):
"""transformers' grouped_mm_fallback, which it calls instead of aten._grouped_mm (under torch.compile when the
weight is not bf16), on aten._grouped_mm's route."""
return _aten_grouped_mm(input, weight, offs)


_libs = []


def install():
"""Register aten._grouped_mm's npu kernel above autograd and functionalization, and at the backend key,
where a call made under inference_mode lands."""
global _lib
if _lib is None:
_lib = torch.library.Library("aten", "IMPL")
for key in ("AutogradPrivateUse1", "PrivateUse1"):
_lib.impl("_grouped_mm", _aten_grouped_mm, key)
"""Register the npu kernel of aten._grouped_mm and of transformers::grouped_mm_fallback above autograd and
functionalization, and at the backend key, where a call made under inference_mode lands."""
if not _libs:
for ns, op, fn in (("aten", "_grouped_mm", _aten_grouped_mm),
("transformers", "grouped_mm_fallback", _transformers_grouped_mm_fallback)):
lib = torch.library.Library(ns, "IMPL")
for key in ("AutogradPrivateUse1", "PrivateUse1"):
lib.impl(op, fn, key)
_libs.append(lib)
3 changes: 2 additions & 1 deletion pytorchsim/frontend/inductor_patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -645,9 +645,10 @@ def install():
_install_npu_choices()
_decompose_convolution_for_npu()
_install_selection()
from pytorchsim.frontend import attention, grouped_mm
from pytorchsim.frontend import attention, grouped_mm, topk
attention.install()
grouped_mm.install()
topk.install()

inductor_config.max_autotune_gemm = True
inductor_config.max_autotune_gemm_backends = "ATEN,TRITON"
Expand Down
Loading