diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index 843dee2c7..7bbe2d381 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -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 @@ -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) | @@ -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`). diff --git a/.github/workflows/pytorchsim_test.yml b/.github/workflows/pytorchsim_test.yml index 5708900ea..b592d9b8c 100644 --- a/.github/workflows/pytorchsim_test.yml +++ b/.github/workflows/pytorchsim_test.yml @@ -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_attribute_sources.py - tests/system/test_breakdown_viewer.py diff --git a/device/torch_openreg/__init__.py b/device/torch_openreg/__init__.py index 1e407115a..038898662 100644 --- a/device/torch_openreg/__init__.py +++ b/device/torch_openreg/__init__.py @@ -19,9 +19,8 @@ sys.path.append(os.environ.get('TORCHSIM_DIR', default='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/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 @@ -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() diff --git a/pytorchsim/frontend/grouped_mm.py b/pytorchsim/frontend/grouped_mm.py index fae30a1ed..82f386037 100644 --- a/pytorchsim/frontend/grouped_mm.py +++ b/pytorchsim/frontend/grouped_mm.py @@ -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 reads as -runtime attributes; 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 reads as runtime attributes. Both ops register one entry through torch.library.""" import torch import triton @@ -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) diff --git a/pytorchsim/frontend/inductor_patches.py b/pytorchsim/frontend/inductor_patches.py index 9cab9c91e..871e723b2 100644 --- a/pytorchsim/frontend/inductor_patches.py +++ b/pytorchsim/frontend/inductor_patches.py @@ -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" diff --git a/pytorchsim/frontend/post_grad_pass.py b/pytorchsim/frontend/post_grad_pass.py new file mode 100644 index 000000000..d1d950232 --- /dev/null +++ b/pytorchsim/frontend/post_grad_pass.py @@ -0,0 +1,292 @@ +"""The npu's post-grad pass: rewrites that keep ops with no npu kernel on the device. + +pytorchsim_post_grad_pass is the device_custom_pass Inductor runs on npu graphs only, after its post-grad +passes: histc, polar, a row times a matrix, complex values as real pairs. topk and grouped_mm are +frontend/topk.py and frontend/grouped_mm.py. +""" + +import torch +from torch import fx +from torch.fx import traceback as fx_traceback +from torch._inductor.custom_graph_pass import CustomGraphModulePass, get_hash_for_files + +from pytorchsim import config + +aten = torch.ops.aten +prims = torch.ops.prims + +logger = config.setup_logger() + + +class _pytorchsim_post_grad_pass(CustomGraphModulePass): + """The four rewrites in this order on an npu graph (polar before the complex values it makes); its uuid + hashes this file, so an edit here is a new cache key.""" + + def __call__(self, gm: fx.GraphModule) -> None: + graph, fake_mode = gm.graph, _fake_mode(gm.graph) + changed = (rewrite_aten_histc(graph, fake_mode) + + rewrite_aten_polar(graph, fake_mode) + + rewrite_aten_mm_addmm_row(graph, fake_mode) + + rewrite_aten_view_as_complex(graph, fake_mode)) + if changed: + graph.eliminate_dead_code() + gm.recompile() + + def uuid(self): + return get_hash_for_files((__file__,)) + + +pytorchsim_post_grad_pass = _pytorchsim_post_grad_pass() + + +def rewrite_aten_histc(graph, fake_mode) -> int: + """Every aten.histc as a count on the device (_insert_histc); one without a fake value is left to aten, + logged. Returns how many were rewritten.""" + def build(call, node): + x = node.args[0] + if _val(x) is None: + logger.info("[post_grad_pass] histc without a fake value: left to aten") + return None + said = dict(zip(("bins", "min", "max"), node.args[1:]), **node.kwargs) + return _insert_histc(call, x, _val(x), int(said.get("bins", 100)), said.get("min", 0), said.get("max", 0)) + return _replace(graph, fake_mode, graph.find_nodes(op="call_function", target=aten.histc.default), build) + + +def _insert_histc(call, x, xv, bins, lo, hi): + """aten's histc: bin (x - lo) * bins / (hi - lo), integral in int64 and floating in x's dtype, the top + edge in the last bin, outside [lo, hi] dropped; lo == hi takes x's range, widened by 1 if it is one value.""" + integral = not xv.is_floating_point() + flat = call(prims.convert_element_type.default, call(aten.reshape.default, x, [-1]), + torch.int64 if integral else xv.dtype) + if lo == hi and xv.numel(): + lo, hi = call(aten.amin.default, flat, [0]), call(aten.amax.default, flat, [0]) + one = call(aten.eq.Tensor, lo, hi) + lo, hi = (call(aten.where.self, one, call(aten.sub.Tensor, lo, 1), lo), + call(aten.where.self, one, call(aten.add.Tensor, hi, 1), hi)) + width = call(aten.sub.Tensor, hi, lo) + else: + if lo == hi: + lo, hi = lo - 1, hi + 1 + if integral: + lo, hi = int(lo), int(hi) + if hi <= lo: + raise RuntimeError(f"torch.histc: max must be larger than min (min {lo}, max {hi})") + width = hi - lo + scaled = call(aten.mul.Tensor, call(aten.sub.Tensor, flat, lo), bins) + if integral: + pos = call(aten.div.Tensor_mode, scaled, width, rounding_mode="floor") + else: + pos = call(prims.convert_element_type.default, call(aten.div.Tensor, scaled, width), torch.int64) + pos = call(aten.clamp_max.default, pos, bins - 1) + ge, le = ((aten.ge.Tensor, aten.le.Tensor) if isinstance(lo, fx.Node) + else (aten.ge.Scalar, aten.le.Scalar)) + inside = call(aten.logical_and.default, call(ge, flat, lo), call(le, flat, hi)) + seats = call(prims.iota.default, bins, start=0, step=1, dtype=torch.int64, device=xv.device, + requires_grad=False) + hits = call(aten.logical_and.default, + call(aten.eq.Tensor, call(aten.reshape.default, pos, [-1, 1]), + call(aten.reshape.default, seats, [1, -1])), + call(aten.reshape.default, inside, [-1, 1])) + return call(prims.convert_element_type.default, call(aten.sum.dim_IntList, hits, [0]), xv.dtype) + + +def rewrite_aten_polar(graph, fake_mode) -> int: + """polar(abs, angle) as view_as_complex of the pair (abs*cos, abs*sin), built contiguous since + view_as_complex needs a unit last stride; rewrite_aten_view_as_complex then takes it to real pairs.""" + def build(call, node): + r, angle = node.args[:2] + return call(aten.view_as_complex.default, + _join(call, call(aten.mul.Tensor, r, call(aten.cos.default, angle)), + call(aten.mul.Tensor, r, call(aten.sin.default, angle)))) + return _replace(graph, fake_mode, graph.find_nodes(op="call_function", target=aten.polar.default), build) + + +def rewrite_aten_mm_addmm_row(graph, fake_mode) -> int: + """Replace a 1 x K row times a K x N matrix with the row broadcast down the matrix, a + multiply and a sum over K: vector work, where the mm template would run it on the array.""" + def build(call, node): + found = _row_times_matrix(node) + if found is None: + return None + a, b, bias = found + column = call(aten.view.default, a, [int(_val(a).shape[1]), 1]) + out = call(aten.sum.dim_IntList, call(aten.mul.Tensor, column, b), [0], True) + return out if bias is None else call(aten.add.Tensor, out, bias) + return _replace(graph, fake_mode, graph.find_nodes(op="call_function", target=aten.mm.default) + + graph.find_nodes(op="call_function", target=aten.addmm.default), build) + + +def _row_times_matrix(node): + """(a, b, bias) of an mm or a plain addmm of real floating operands whose left one is a row, else None.""" + if node.target is aten.mm.default: + (a, b), bias = node.args, None + elif not node.kwargs: + bias, a, b = node.args + else: + return None + av, bv = _val(a), _val(b) + if av is None or bv is None or av.dim() != 2 or bv.dim() != 2 or av.shape[0] != 1: + return None + if not (av.is_floating_point() and bv.is_floating_point()): + return None + return a, b, bias + + +def rewrite_aten_view_as_complex(graph, fake_mode) -> int: + """Each component of complex values whose ops _REAL_PAIR has a rule for becomes real [..., 2] pairs; any + other component stays as it is, logged with why. Returns the components rewritten.""" + changed = 0 + for component in _complex_components([n for n in graph.nodes if _is_complex(n)]): + why = _why_not_real(component) + if why is not None: + logger.info("[post_grad_pass] %d complex nodes left to aten: %s", len(component), why) + continue + _to_real_pairs(graph, fake_mode, component) + changed += 1 + return changed + + +def _complex_components(nodes): + """The complex nodes grouped by the complex values joining them, each group in graph order.""" + parent = {n: n for n in nodes} + + def root(n): + while parent[n] is not n: + parent[n] = parent[parent[n]] + n = parent[n] + return n + + for n in nodes: + for a in n.all_input_nodes: + if a in parent: + parent[root(a)] = root(n) + groups = {} + for n in nodes: + groups.setdefault(root(n), []).append(n) + return list(groups.values()) + + +def _why_not_real(component): + """Why the component has no real-pair form, or None: a node _REAL_PAIR has no rule for (a placeholder or + attribute among them), or a complex value read by anything but _REAL_PAIR and view_as_real (the output too).""" + for n in component: + if n.target not in _REAL_PAIR: + return f"{n.op} {n.target}" + for user in n.users: + if user.target is not aten.view_as_real.default and user.target not in _REAL_PAIR: + return f"{user.op} {user.name} reads {n.name}'s complex value" + return None + + +def _to_real_pairs(graph, fake_mode, component): + """Rewrite one eligible component: each complex value becomes its [..., 2] pair and every view_as_real of + it reads the pair.""" + pair = {} + for n in component: + pair[n] = _REAL_PAIR[n.target](_inserter(graph, fake_mode, n), n, pair) + + for n in component: + for user in list(n.users): + if user.target is aten.view_as_real.default: + user.replace_all_uses_with(pair[n]) + + +def _pair_of_view(call, n, pair): + """view_as_complex(x): its pair is x.""" + return n.args[0] + + +def _pair_of_unsqueeze(call, n, pair): + """unsqueeze(z, dim): the pair unsqueezed before its last axis.""" + dim = n.args[1] + return call(aten.unsqueeze.default, pair[n.args[0]], dim if dim >= 0 else dim - 1) + + +def _pair_of_mul(call, n, pair): + """z * w as (zr*wr - zi*wi, zr*wi + zi*wr) when w is complex (a value or a Python complex); z * r scales + the pair when r is real.""" + a, b = n.args[0], n.args[1] + cx, other = (a, b) if _is_complex(a) else (b, a) + if not (_is_complex(other) or isinstance(other, complex)): + if isinstance(other, fx.Node): + other = call(aten.unsqueeze.default, other, -1) + return call(aten.mul.Tensor, pair[cx], other) + ar, ai = call(aten.select.int, pair[cx], -1, 0), call(aten.select.int, pair[cx], -1, 1) + if isinstance(other, complex): + br, bi = other.real, other.imag + else: + br, bi = call(aten.select.int, pair[other], -1, 0), call(aten.select.int, pair[other], -1, 1) + re = call(aten.sub.Tensor, call(aten.mul.Tensor, ar, br), call(aten.mul.Tensor, ai, bi)) + im = call(aten.add.Tensor, call(aten.mul.Tensor, ar, bi), call(aten.mul.Tensor, ai, br)) + return _join(call, re, im) + + +_REAL_PAIR = { + aten.view_as_complex.default: _pair_of_view, + aten.unsqueeze.default: _pair_of_unsqueeze, + aten.mul.Tensor: _pair_of_mul, + aten.mul.Scalar: _pair_of_mul, +} + + +def _replace(graph, fake_mode, nodes, build): + """Each node of nodes for which build(call, node) returns a value is replaced by it and erased, call + being _inserter's for that node. Returns how many were replaced.""" + changed = 0 + for node in nodes: + out = build(_inserter(graph, fake_mode, node), node) + if out is not None: + node.replace_all_uses_with(out) + graph.erase_node(node) + changed += 1 + return changed + + +def _inserter(graph, fake_mode, origin): + """call(target, *args, **kwargs): a node just before origin, made through FX's tracer under origin's meta + so FX copies its provenance and records origin in from_node; its fake value is set, as nothing after does.""" + def unwrap(a): + if isinstance(a, (list, tuple)): + return type(a)(unwrap(x) for x in a) + if isinstance(a, dict): + return {k: unwrap(v) for k, v in a.items()} + return _val(a) + + tracer = fx.proxy.GraphAppendingTracer(graph) + + def call(target, *args, **kwargs): + with graph.inserting_before(origin), fx_traceback.preserve_node_meta(), \ + fx_traceback.set_current_meta(origin): + node = tracer.create_node("call_function", target, args, kwargs) + if fake_mode is not None: + with fake_mode: + node.meta["val"] = target(*unwrap(args), **unwrap(kwargs)) + return node + + return call + + +def _join(call, re, im): + """The [..., 2] real pair of re and im.""" + return call(aten.cat.default, [call(aten.unsqueeze.default, re, -1), + call(aten.unsqueeze.default, im, -1)], -1) + + +def _val(node): + """The fake value of a node, or the argument itself when it is not a node.""" + return node.meta.get("val", None) if isinstance(node, fx.Node) else node + + +def _is_complex(node): + """Whether the node holds a complex tensor.""" + v = _val(node) + return isinstance(v, torch.Tensor) and v.is_complex() + + +def _fake_mode(graph): + """The fake mode of the graph's tensors, or None.""" + for n in graph.nodes: + v = _val(n) + if isinstance(v, torch.Tensor) and hasattr(v, "fake_mode"): + return v.fake_mode + return None diff --git a/pytorchsim/frontend/rewrite_fx_graph.py b/pytorchsim/frontend/rewrite_fx_graph.py deleted file mode 100644 index f146ff23c..000000000 --- a/pytorchsim/frontend/rewrite_fx_graph.py +++ /dev/null @@ -1,404 +0,0 @@ -"""Our rewrites of the FX graph, so ops with no npu kernel stay on the device. - -Decompositions (histc, polar) and post-grad passes (grouped_mm, topk, complex to -real pairs), all chained onto Inductor's one post-grad hook by install(). -""" - -from operator import getitem - -import torch -from torch import fx -from torch._inductor.custom_graph_pass import CustomGraphPass -from torch._inductor.decomposition import register_decomposition - -aten = torch.ops.aten -prims = torch.ops.prims - - -@register_decomposition(aten.histc.default) -def decompose_histc(self, bins: int = 100, min: int = 0, max: int = 0): - """Counts of an integral tensor, on the device when the bins are the values. - - Exact for bins=N, min=0, max=N-1; any other edges keep the CPU hop. - """ - if self.is_floating_point(): - return NotImplemented - if int(min) == 0 and int(max) == int(bins) - 1: - vals = torch.arange(int(bins), device=self.device, dtype=self.dtype) - counts = (self.reshape(-1, 1) == vals.reshape(1, -1)).sum(0) - return counts.to(self.dtype) - counts = torch.histc(self.to(torch.float32), bins, min, max) - return counts.to(self.dtype) - - -@register_decomposition(aten.polar.default) -def decompose_polar(abs, angle): - """`polar` as a view over a real pair, so it never becomes an extern call. - - The pair is made contiguous because view_as_complex needs a unit last stride. - """ - pair = torch.stack((abs * torch.cos(angle), abs * torch.sin(angle)), dim=-1) - return torch.view_as_complex(pair.contiguous()) - - -def is_npu_graph(g) -> bool: - """Whether any tensor in this graph lives on the npu device.""" - graph = getattr(g, "graph", g) - for node in graph.nodes: - val = node.meta.get("val") - for t in (val if isinstance(val, (tuple, list)) else (val,)): - if isinstance(t, torch.Tensor) and t.device.type == "npu": - return True - return False - - -def npu_only(fn): - """The same pass, a no-op on a graph with no npu tensor.""" - def _gated(graph): - if is_npu_graph(graph): - fn(graph) - return _gated - - -def _identity(fn): - """A name for a foreign callable that is the same in every process.""" - uuid = getattr(fn, "uuid", None) - if callable(uuid): - return uuid() - module = getattr(fn, "__module__", "?") - name = getattr(fn, "__qualname__", None) - return f"{module}.{name}" if name else f"{module}." - - -class _Chain(CustomGraphPass): - """Inductor's single post-grad slot, as a chain that knows what is in it.""" - - def __init__(self, foreign): - self._foreign = foreign - self._keys = [] - self._passes = [] - - def add(self, key, fn) -> bool: - """Append fn under key, or report that key is already chained.""" - if key in self._keys: - return False - self._keys.append(key) - self._passes.append(fn) - return True - - def uuid(self): - head = () if self._foreign is None else (_identity(self._foreign),) - return head + tuple(self._keys) - - def __call__(self, graph): - if self._foreign is not None: - self._foreign(graph) - for fn in self._passes: - fn(graph) - - -def install_once(key, fn): - """Chain fn onto Inductor's post-grad hook, at most once per key.""" - from torch._inductor import config - - chain = config.post_grad_custom_post_pass - if not isinstance(chain, _Chain): - chain = _Chain(chain) - config.post_grad_custom_post_pass = chain - return chain.add(key, fn) - - -def _recompile(g): - """Drop what a rewrite left dead and refresh the owning module's code.""" - g.eliminate_dead_code() - if g.owning_module is not None: - g.owning_module.recompile() - - -def _grouped_mm_target(): - """transformers' grouped_mm_fallback overload, or None until transformers is imported.""" - ns = getattr(torch.ops, "transformers", None) - op = getattr(ns, "grouped_mm_fallback", None) if ns is not None else None - return op.default if op is not None else None - - -def _emit_dense_grouped_mm(g, inp, weight, offs, s, e, o, dtype, dev): - """Every expert over the whole input, masked to its own rows and summed. - - Returns the (s, o) result node. - """ - call = g.call_function - i64 = torch.int64 - rows = call(prims.iota.default, (s,), - {"start": 0, "step": 1, "dtype": i64, "device": dev, - "requires_grad": False}) - rows2 = call(aten.view.default, (rows, [s, 1])) - offs64 = call(prims.convert_element_type.default, (offs, i64)) - offs2 = call(aten.view.default, (offs64, [1, e])) - reached = call(aten.ge.Tensor, (rows2, offs2)) - reached64 = call(prims.convert_element_type.default, (reached, i64)) - expert_of = call(aten.sum.dim_IntList, (reached64, [1])) - - out = call(aten.full.default, ([s, o], 0), {"dtype": dtype, "device": dev}) - for i in range(e): - wi = call(aten.clone.default, (call(aten.select.int, (weight, 0, i)),), - {"memory_format": torch.contiguous_format}) - part = call(aten.mm.default, (inp, wi)) - keep = call(aten.eq.Scalar, (expert_of, i)) - keep2 = call(aten.view.default, (keep, [s, 1])) - keepf = call(prims.convert_element_type.default, (keep2, dtype)) - out = call(aten.add.Tensor, (out, call(aten.mul.Tensor, (part, keepf)))) - return out - - -def rewrite_grouped_mm(g) -> None: - """Replace every `transformers.grouped_mm_fallback` call with the dense form.""" - target = _grouped_mm_target() - if target is None: - return - if isinstance(g, fx.GraphModule): - g = g.graph - changed = 0 - for node in list(g.nodes): - if node.op != "call_function" or node.target is not target: - continue - inp, weight, offs = node.args[0], node.args[1], node.args[2] - iv = inp.meta.get("val") if hasattr(inp, "meta") else None - wv = weight.meta.get("val") if hasattr(weight, "meta") else None - if iv is None or wv is None or iv.dim() != 2 or wv.dim() != 3: - continue - s, e, o = int(iv.shape[0]), int(wv.shape[0]), int(wv.shape[2]) - with g.inserting_before(node): - dense = _emit_dense_grouped_mm(g, inp, weight, offs, s, e, o, - iv.dtype, iv.device) - node.replace_all_uses_with(dense) - changed += 1 - if changed: - _recompile(g) - - -def _spent(dtype, largest): - """The value a taken element is replaced with, so it cannot win again.""" - info = torch.finfo(dtype) if dtype.is_floating_point else torch.iinfo(dtype) - return info.min if largest else info.max - - -def _emit_topk(g, x, k, dim, largest, shape, dtype, dev): - """Emit k rounds of max-and-mask and return the (values, indices) nodes.""" - call = g.call_function - i64 = torch.int64 - n = int(shape[dim]) - seat_shape = [1] * len(shape) - seat_shape[dim] = n - - rows = call(prims.iota.default, (n,), - {"start": 0, "step": 1, "dtype": i64, "device": dev, - "requires_grad": False}) - ar = call(aten.view.default, (rows, seat_shape)) - seat = call(aten.expand.default, (ar, list(shape))) - late = call(aten.full.default, (list(shape), n), {"dtype": i64, "device": dev}) - gone = call(aten.full.default, (list(shape), _spent(dtype, largest)), - {"dtype": dtype, "device": dev}) - - work, vals, idxs = x, [], [] - for _ in range(k): - best = call(aten.amax.default if largest else aten.amin.default, - (work, [dim], True)) - cand = call(aten.where.self, (call(aten.eq.Tensor, (work, best)), - seat, late)) - where = call(aten.amin.default, (cand, [dim], True)) - vals.append(best) - idxs.append(where) - work = call(aten.where.self, - (call(aten.eq.Tensor, (ar, where)), gone, work)) - return call(aten.cat.default, (vals, dim)), call(aten.cat.default, (idxs, dim)) - - -def rewrite_topk(g) -> None: - """Replace every `aten.topk.default` whose users are getitem with the rounds.""" - if isinstance(g, fx.GraphModule): - g = g.graph - changed = 0 - for node in list(g.nodes): - if node.op != "call_function" or node.target is not aten.topk.default: - continue - users = list(node.users) - if any(u.op != "call_function" or u.target is not getitem for u in users): - continue - x = node.args[0] - xv = x.meta.get("val") if hasattr(x, "meta") else None - if xv is None or xv.dim() == 0 or not xv.numel(): - continue - k = int(node.args[1]) - dim = int(node.args[2]) if len(node.args) > 2 else -1 - dim = dim if dim >= 0 else dim + xv.dim() - largest = bool(node.args[3]) if len(node.args) > 3 else True - if k < 1 or k > int(xv.shape[dim]): - continue - with g.inserting_before(node): - values, indices = _emit_topk(g, x, k, dim, largest, list(xv.shape), - xv.dtype, xv.device) - for u in users: - u.replace_all_uses_with(values if u.args[1] == 0 else indices) - changed += 1 - if changed: - _recompile(g) - - -def _row_times_matrix(node): - """(a, b, bias) of an mm or a plain addmm whose left operand is one row, else None.""" - if node.op != "call_function": - return None - if node.target is aten.mm.default: - (a, b), bias = node.args, None - elif node.target is aten.addmm.default and not node.kwargs: - bias, a, b = node.args - else: - return None - av, bv = _val(a), _val(b) - if av is None or bv is None or av.dim() != 2 or bv.dim() != 2 or av.shape[0] != 1: - return None - return a, b, bias - - -def rewrite_row_mm(g) -> None: - """Replace a 1 x K row times a K x N matrix with the row broadcast down the matrix, a - multiply and a sum over K: vector work, where the mm template would run it on the array.""" - if isinstance(g, fx.GraphModule): - g = g.graph - changed = 0 - for node in list(g.nodes): - found = _row_times_matrix(node) - if found is None: - continue - a, b, bias = found - k = int(_val(a).shape[1]) - with g.inserting_before(node): - column = g.call_function(aten.view.default, (a, [k, 1])) - scaled = g.call_function(aten.mul.Tensor, (column, b)) - out = g.call_function(aten.sum.dim_IntList, (scaled, [0], True)) - if bias is not None: - out = g.call_function(aten.add.Tensor, (out, bias)) - node.replace_all_uses_with(out) - changed += 1 - if changed: - _recompile(g) - - -_MUL = (aten.mul.Tensor, aten.mul.Scalar) -_SHAPE = (aten.unsqueeze.default,) -_HANDLED = (aten.view_as_complex.default,) + _MUL + _SHAPE - - -def _val(node): - """The fake value of a node, or the argument itself when it is not a node.""" - return node.meta.get("val", None) if isinstance(node, torch.fx.Node) else node - - -def _is_complex(node): - """Whether the node holds a complex tensor.""" - v = _val(node) - return isinstance(v, torch.Tensor) and v.is_complex() - - -def _fake_mode(graph): - """The fake mode of the graph's tensors, or None.""" - for n in graph.nodes: - v = _val(n) - if isinstance(v, torch.Tensor) and hasattr(v, "fake_mode"): - return v.fake_mode - return None - - -class ComplexToRealPairs(CustomGraphPass): - """Complex values become their real [..., 2] pairs, whole component or nothing. - - Handles view_as_complex, mul and unsqueeze; any other complex op leaves the graph as is. - """ - - def uuid(self): - return "pytorchsim-complex-to-real-pairs-2" - - def __call__(self, graph: torch.fx.Graph) -> None: - complex_nodes = [n for n in graph.nodes if _is_complex(n)] - if not complex_nodes: - return - - for n in complex_nodes: - if n.op != "call_function": - return - if n.target not in _HANDLED: - return - for user in n.users: - if user.op == "output": - return - if user.target is aten.view_as_real.default: - continue - if user.target in _HANDLED: - continue - return - - fake_mode = _fake_mode(graph) - - def _unwrap(a): - if isinstance(a, (list, tuple)): - return type(a)(_unwrap(x) for x in a) - return _val(a) - - def call(target, *args): - node = graph.call_function(target, args) - if fake_mode is not None: - with fake_mode: - node.meta["val"] = target(*[_unwrap(a) for a in args]) - return node - - pair = {} - for n in complex_nodes: - with graph.inserting_before(n): - if n.target is aten.view_as_complex.default: - pair[n] = n.args[0] - continue - - if n.target in _SHAPE: - dim = n.args[1] - pair[n] = call(n.target, pair[n.args[0]], - dim if dim >= 0 else dim - 1) - continue - - a, b = n.args[0], n.args[1] - if _is_complex(a) and _is_complex(b): - pa, pb = pair[a], pair[b] - ar = call(aten.select.int, pa, -1, 0) - ai = call(aten.select.int, pa, -1, 1) - br = call(aten.select.int, pb, -1, 0) - bi = call(aten.select.int, pb, -1, 1) - re = call(aten.sub.Tensor, call(aten.mul.Tensor, ar, br), - call(aten.mul.Tensor, ai, bi)) - im = call(aten.add.Tensor, call(aten.mul.Tensor, ar, bi), - call(aten.mul.Tensor, ai, br)) - pair[n] = call(aten.cat.default, - [call(aten.unsqueeze.default, re, -1), - call(aten.unsqueeze.default, im, -1)], -1) - else: - cx, other = (a, b) if _is_complex(a) else (b, a) - if isinstance(other, torch.fx.Node): - other = call(aten.unsqueeze.default, other, -1) - pair[n] = call(aten.mul.Tensor, pair[cx], other) - - for n in complex_nodes: - for user in list(n.users): - if user.target is aten.view_as_real.default: - user.replace_all_uses_with(pair[n]) - - graph.eliminate_dead_code() - - -_COMPLEX_TO_REAL = ComplexToRealPairs() - - -def install(): - """Chain the post-grad passes onto Inductor's hook, each at most once.""" - install_once("pytorchsim-grouped-mm", npu_only(rewrite_grouped_mm)) - install_once("pytorchsim-topk", npu_only(rewrite_topk)) - install_once("pytorchsim-row-mm", npu_only(rewrite_row_mm)) - install_once(_COMPLEX_TO_REAL.uuid(), npu_only(_COMPLEX_TO_REAL)) diff --git a/pytorchsim/frontend/topk.py b/pytorchsim/frontend/topk.py new file mode 100644 index 000000000..f4bf9b914 --- /dev/null +++ b/pytorchsim/frontend/topk.py @@ -0,0 +1,182 @@ +"""topk on the npu: one Triton kernel where it takes the call, the same rounds as aten ops elsewhere. + +The kernel puts a row on each lane and runs K rounds of max (min), first index of it, and mask, +gathering the K values and indices of its rows in registers and storing each once, as a TPU +kernel would. `topk_plan` is the one place that decides whether it takes a call; a call it +declines runs the rounds as aten ops (Inductor's kernels), and says why. + +aten::topk's npu kernel is registered at AutogradPrivateUse1, so it runs when torch.compile traces +(and at PrivateUse1, where a call under inference_mode lands), and calls `torchsim::topk`, a +`triton_op` whose body launches the kernel through `wrap_triton`. Its backward scatters the values' +gradient to the indices, aten's own topk backward. Eagerly the op runs the rounds, since a Triton +kernel cannot launch on the npu outside a compiled graph. ROUTED counts the kernel's launches and +the eager calls. +""" + +import torch +import triton +import triton.language as tl +from torch.library import triton_op, wrap_triton + +from pytorchsim import config + +logger = config.setup_logger() + +#: The calls that ran each route: "kernel" launches, "rounds" eager calls; a trace is not a call. +ROUTED = {} + + +def _count(route): + ROUTED[route] = ROUTED.get(route, 0) + 1 + + +@triton.jit +def _topk_kernel(x_ptr, v_ptr, i_ptr, rows, E: tl.constexpr, EP: tl.constexpr, K: tl.constexpr, + KP: tl.constexpr, XBLOCK: tl.constexpr, LARGEST: tl.constexpr): + r = tl.program_id(0) * XBLOCK + tl.arange(0, XBLOCK)[:, None] + c = tl.arange(0, EP)[None, :] + j = tl.arange(0, KP)[None, :] + live = r < rows + if LARGEST: + spent = float("-inf") + else: + spent = float("inf") + x = tl.load(x_ptr + r * E + c, mask=live & (c < E), other=spent) + vals = tl.zeros([XBLOCK, KP], dtype=x.dtype) + idxs = tl.zeros([XBLOCK, KP], dtype=tl.int32) + for n in tl.static_range(K): + if LARGEST: + best = tl.max(x, axis=1)[:, None] + else: + best = tl.min(x, axis=1)[:, None] + at = tl.min(tl.where(x == best, c, EP), axis=1)[:, None] + vals = tl.where(j == n, best, vals) + idxs = tl.where(j == n, at, idxs) + x = tl.where(c == at, spent, x) + out = live & (j < K) + tl.store(v_ptr + r * K + j, vals, mask=out) + tl.store(i_ptr + r * K + j, idxs.to(tl.int64), mask=out) + + +def _p2(n): + return 1 << max(0, (int(n) - 1).bit_length()) + + +def _tiles(xblock, ep, kp, esize): + """The tiles one program of _topk_kernel holds: the row and its masked copy, the index + candidates, and the gathered values and int64 indices.""" + return [(xblock, ep, esize), (xblock, ep, esize), (xblock, ep, 4), (xblock, kp, esize), + (xblock, kp, 8)] + + +def topk_plan(x, k, dim): + """(the kernel's blocks, None) when it takes topk of `x` along `dim`, else (None, why). A + program takes a row on each lane, those past the last masked, halved while its tiles overrun + the scratchpad budget.""" + from pytorchsim.frontend.attention import _fits + if not x.is_floating_point(): + return None, f"{x.dtype} is not a floating dtype" + if x.dim() == 0 or x.numel() == 0: + return None, "an empty or 0-d input" + if dim != x.dim() - 1: + return None, f"dim {dim} is not the last of {x.dim()}" + E = int(x.shape[-1]) + ep, kp = _p2(E), _p2(k) + xblock = int(config.CONFIG_MACHINE.vector_lanes) + while xblock > 1 and not _fits(_tiles(xblock, ep, kp, x.dtype.itemsize)): + xblock //= 2 + if not _fits(_tiles(xblock, ep, kp, x.dtype.itemsize)): + return None, f"a row of {E} overruns the scratchpad budget" + return {"XBLOCK": xblock, "EP": ep, "KP": kp}, None + + +def _spent(dtype, largest): + """The value a taken element is replaced with, so it cannot win again.""" + info = torch.finfo(dtype) if dtype.is_floating_point else torch.iinfo(dtype) + return info.min if largest else info.max + + +def _rounds(x, k, dim, largest): + """The kernel's rounds as aten ops: (values, int64 indices), the first index of each best.""" + if x.dim() == 0: + v, i = _rounds(x.view(1), k, 0, largest) + return v.view(x.shape[:0] if k else (0,)), i.view(x.shape[:0] if k else (0,)) + if k == 0: + shape = [*x.shape[:dim], 0, *x.shape[dim + 1:]] + return x.new_empty(shape), x.new_empty(shape, dtype=torch.int64) + n = int(x.shape[dim]) + seat_t = torch.int32 if n < 2**31 else torch.int64 + shape = [1] * x.dim() + shape[dim] = n + ar = torch.arange(n, dtype=seat_t, device=x.device).view(shape) + seat = ar.expand(x.shape) + late = torch.full(x.shape, n, dtype=seat_t, device=x.device) + gone = torch.full(x.shape, _spent(x.dtype, largest), dtype=x.dtype, device=x.device) + work, vals, idxs = x, [], [] + for _ in range(k): + best = work.amax(dim, keepdim=True) if largest else work.amin(dim, keepdim=True) + where = torch.where(work == best, seat, late).amin(dim, keepdim=True) + vals.append(best) + idxs.append(where.to(torch.int64)) + work = torch.where(ar == where, gone, work) + return torch.cat(vals, dim), torch.cat(idxs, dim) + + +@triton_op("torchsim::topk", mutates_args=()) +def topk(x: torch.Tensor, k: int, dim: int, largest: bool) -> tuple[torch.Tensor, torch.Tensor]: + """topk of `x` along `dim` (non-negative), sorted, as a compiled graph sees it: the kernel + where topk_plan takes it, else the rounds. The kernel's arguments are passed by position.""" + plan, why = topk_plan(x, k, dim) + if plan is None: + logger.info("topk on the npu runs the rounds as aten ops, not the kernel: x %s %s k=%d " + "dim=%d (%s)", tuple(x.shape), x.dtype, k, dim, why) + return _rounds(x, k, dim, largest) + xc = x.contiguous() + E = int(x.shape[-1]) + rows = x.numel() // E + v = torch.empty(*x.shape[:-1], k, dtype=x.dtype, device=x.device) + i = torch.empty(*x.shape[:-1], k, dtype=torch.int64, device=x.device) + wrap_triton(_topk_kernel)[(triton.cdiv(rows, plan["XBLOCK"]), 1, 1)]( + xc, v, i, rows, E, plan["EP"], k, plan["KP"], plan["XBLOCK"], largest) + return v, i + + +@topk.register_kernel("npu") +def _topk_eager(x, k, dim, largest): + _count("rounds") + return _rounds(x, k, dim, largest) + + +def _setup_backward(ctx, inputs, output): + x, _, dim, _ = inputs + ctx.dim, ctx.shape = dim, x.shape + ctx.save_for_backward(output[1]) + + +def _backward(ctx, grad_values, grad_indices): + (indices,) = ctx.saved_tensors + grad = grad_values.new_zeros(ctx.shape).scatter(ctx.dim, indices, grad_values) + return grad, None, None, None + + +topk.register_autograd(_backward, setup_context=_setup_backward) + + +def _aten_topk(x, k, dim=-1, largest=True, sorted=True): + """aten::topk on the npu: torchsim::topk with a non-negative dim; its values are sorted.""" + return topk(x, int(k), dim % max(x.dim(), 1), bool(largest)) + + +_lib = None + + +def install(): + """Register aten::topk's npu kernel above autograd and functionalization, and at the backend + key, where a call made under inference_mode lands. Count each kernel launch.""" + global _lib + if _lib is None: + from pytorchsim.driver import codecache + codecache.observe_launches(_topk_kernel, lambda: _count("kernel")) + _lib = torch.library.Library("aten", "IMPL") + for key in ("AutogradPrivateUse1", "PrivateUse1"): + _lib.impl("topk", _aten_topk, key) diff --git a/scripts/ci/triton_route_passing.txt b/scripts/ci/triton_route_passing.txt index c1fd8af81..d83ec26e7 100644 --- a/scripts/ci/triton_route_passing.txt +++ b/scripts/ci/triton_route_passing.txt @@ -273,6 +273,7 @@ tests/ops/misc/test_polar.py 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_bundle_reuse.py tests/system/test_eager.py diff --git a/tests/models/DeepSeek/test_deepseek_v3_base.py b/tests/models/DeepSeek/test_deepseek_v3_base.py index 375c83cf6..b08e24e09 100644 --- a/tests/models/DeepSeek/test_deepseek_v3_base.py +++ b/tests/models/DeepSeek/test_deepseek_v3_base.py @@ -53,7 +53,7 @@ def exec_module(self, module): # RecursionError: maximum recursion depth exceeded # # DeepSeek-V2's complex RoPE closed that loop. It no longer does: - # rewrite_fx_graph.py rewrites the complex multiply into real + # frontend/post_grad_pass.py rewrites the complex multiply into real # arithmetic, Inductor generates a kernel, and no fallback is emitted. # Measured both ways, and pinned by # tests/ops/misc/test_eager_to_compile_recursion.py. diff --git a/tests/models/Llama/test_llama4.py b/tests/models/Llama/test_llama4.py index f058dfea4..6af4ed495 100644 --- a/tests/models/Llama/test_llama4.py +++ b/tests/models/Llama/test_llama4.py @@ -39,7 +39,7 @@ Fifteen ops run eager: 11 `fill_` and 4 `topk`. The complex arithmetic used to be the bulk of that list -- 7 `view_as_complex`, 7 `mul.out`, 6 `view_as_real`, -twenty calls leaving the simulator -- and `rewrite_fx_graph` (84ad277) +twenty calls leaving the simulator -- and the npu post-grad pass (84ad277) now keeps all of it in the graph. That pass was written and measured against DeepSeek-V2's rope, and it covers this one unchanged: Llama 4's complex path uses no op outside the set it already knew. The kernel count went 30 -> 31 as diff --git a/tests/ops/gemm/test_grouped_mm.py b/tests/ops/gemm/test_grouped_mm.py index b3339ed65..0f9735d51 100644 --- a/tests/ops/gemm/test_grouped_mm.py +++ b/tests/ops/gemm/test_grouped_mm.py @@ -5,9 +5,11 @@ few_rows fewer rows than groups: every block holds rows, the grid stops at the row count eager outside torch.compile the call runs group by group (no Triton launch outside a compiled graph) grad inputs that require grad run group by group, and their gradients match the CPU's + fallback transformers' grouped_mm_fallback (its call when the weight is not bf16) takes the same kernel Usage: test_grouped_mm.py [case ...] (all cases when none is named) """ +import importlib import sys import torch @@ -40,7 +42,11 @@ def _err(out, ref): return ((out.float().cpu() - ref).abs().max() / ref.abs().max()).item() -def _run_compiled(sizes, k, n): +def _fallback(a, b, offs): + return torch.ops.transformers.grouped_mm_fallback(a, b, offs=offs) + + +def _run_compiled(sizes, k, n, fn=_gmm, dtype=torch.bfloat16): """(relative error, grouped-kernel launches, calls left to aten) of one compiled call.""" from pytorchsim.driver import codecache from pytorchsim.frontend import grouped_mm @@ -48,8 +54,9 @@ def _run_compiled(sizes, k, n): codecache.observe_launches(grouped_mm._grouped_mm_kernel, lambda: launches.append(1)) codecache.observe_every_extern(externs.append) a, b, offs = _inputs(sizes, k, n) + a, b = a.to(dtype), b.to(dtype) torch._dynamo.reset() - out = torch.compile(_gmm, dynamic=False)(a.to(device), b.to(device), offs.to(device)) + out = torch.compile(fn, dynamic=False)(a.to(device), b.to(device), offs.to(device)) return _err(out, _reference(a, b, offs)), len(launches), externs @@ -80,7 +87,14 @@ def case_grad(): return ea < TOL and eb < TOL, f"grad err a {ea:.3g}, b {eb:.3g}" -CASES = {"routed": case_routed, "few_rows": case_few_rows, "eager": case_eager, "grad": case_grad} +def case_fallback(): + importlib.import_module("transformers.integrations.moe") + err, launched, externs = _run_compiled([0, 130, 7, 0, 64, 1, 0, 30], 256, 256, _fallback, torch.float32) + return err < TOL and launched == 1 and not externs, f"err {err:.3g}, launches {launched}, externs {externs}" + + +CASES = {"routed": case_routed, "few_rows": case_few_rows, "eager": case_eager, "grad": case_grad, + "fallback": case_fallback} if __name__ == "__main__": diff --git a/tests/ops/misc/test_complex_to_real.py b/tests/ops/misc/test_complex_to_real.py index 3ee57786e..14fdeddaa 100644 --- a/tests/ops/misc/test_complex_to_real.py +++ b/tests/ops/misc/test_complex_to_real.py @@ -7,7 +7,7 @@ sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) from _pytorchsim_utils import test_result -from pytorchsim.frontend.rewrite_fx_graph import ComplexToRealPairs +from pytorchsim.frontend.post_grad_pass import pytorchsim_post_grad_pass aten = torch.ops.aten @@ -23,15 +23,20 @@ def _rope(x, a): def _trace(fn, *args): - # WITH INDUCTOR'S DECOMPOSITION TABLE, because that is the graph the pass - # actually runs on. A bare make_fx keeps aten.polar.default, which this - # backend decomposes one stage earlier (pytorchsim/frontend/rewrite_fx_graph.py) and - # which the pass therefore does not handle -- tracing without the table - # measures a graph the pipeline never produces. + """The graph Inductor hands its post-grad passes: make_fx with Inductor's decomposition table, which + keeps aten.polar, so the device pass rewrites it before the complex values.""" return make_fx(fn, decomposition_table=select_decomp_table(), tracing_mode="fake")(*args) +def _unlowered(gm): + """The ops of gm Inductor has no lowering for; the device pass runs after decomposition, so any it + inserts must lower as they are.""" + from torch._inductor.lowering import lowerings + return sorted({str(m.target) for m in gm.graph.nodes if callable(m.target) + and m.target not in lowerings and m.target.overloadpacket not in lowerings}) + + def _complex_nodes(graph): out = [] for n in graph.nodes: @@ -52,7 +57,7 @@ def test_pass_leaves_no_complex(): before = _complex_nodes(gm.graph) assert before, "the traced graph should have complex nodes to rewrite" - ComplexToRealPairs()(gm.graph) + pytorchsim_post_grad_pass(gm) gm.recompile() after = _complex_nodes(gm.graph) @@ -72,6 +77,66 @@ def test_rope_on_device(device): test_result("complex-to-real (RoPE on device)", npu_out, cpu_out) +def test_complex_scalar_multiply(): + """A complex Python scalar on either side is multiplied as a complex number, not + broadcast over the real pair.""" + def f(x): + z = torch.view_as_complex(x.reshape(1, 32, 32, 2)) + return torch.cat([torch.view_as_real(z * (0.6 - 0.8j) * 0.5), + torch.view_as_real(2j * z)], -1).flatten(-2) + + x = torch.randn(1, 32, 64) + gm = _trace(f, x) + pytorchsim_post_grad_pass(gm) + gm.recompile() + after = _complex_nodes(gm.graph) + assert not after, f"complex nodes survived the pass: {[str(n.target) for n in after]}" + assert not _unlowered(gm), f"no Inductor lowering for {_unlowered(gm)}" + test_result("complex-to-real (complex scalar)", gm(x), f(x)) + + +def test_components_are_judged_apart(): + """A component the pass cannot say in real arithmetic leaves a separate one it can rewritten; every node it + makes keeps the stack trace of the node it replaces, and its from_node names that node.""" + def f(x, y): + a = torch.view_as_real(torch.view_as_complex(x) * (0.6 - 0.8j)) + b = torch.view_as_real(torch.exp(torch.view_as_complex(y))) + return a, b + + x, y = torch.randn(4, 8, 2), torch.randn(4, 8, 2) + gm = _trace(f, x, y) + for n in gm.graph.nodes: + n.meta["stack_trace"] = f"user.py:{n.name}" + n.meta["from_node"] = [n.name] + before = {n.name for n in gm.graph.nodes} + pytorchsim_post_grad_pass(gm) + for n in gm.graph.nodes: + if n.name in before: + continue + src = n.meta.get("from_node", []) + last = src[-1] if src else None + assert getattr(last, "name", None) in before, f"{n.name}: from_node {src}" + left = sorted(str(n.target) for n in _complex_nodes(gm.graph)) + assert left == ["aten.exp.default", "aten.view_as_complex.default"], f"complex nodes left: {left}" + bare = [n.name for n in gm.graph.nodes if callable(n.target) and "stack_trace" not in n.meta] + assert not bare, f"nodes without provenance: {bare}" + out = gm(x, y) + test_result("complex-to-real (components apart)", out[0], f(x, y)[0]) + + +def test_row_mm_stays_real(): + """The GEMV rewrite takes real floating operands only: a complex 1 x K mm stays one mm.""" + def f(a, b): + return torch.view_as_real(torch.view_as_complex(a) @ torch.view_as_complex(b)) + + a, b = torch.randn(1, 8, 2), torch.randn(8, 4, 2) + gm = _trace(f, a, b) + pytorchsim_post_grad_pass(gm) + mms = [n for n in gm.graph.nodes if n.target is aten.mm.default] + assert len(mms) == 1, f"complex mm rewritten: {[str(n.target) for n in gm.graph.nodes]}" + test_result("complex 1 x K mm", gm(a, b), f(a, b)) + + def test_unhandled_op_is_left_alone(): # WHOLE OR NOTHING. A complex op the pass cannot say in real arithmetic # makes the whole component ineligible -- half a rewrite is a graph with @@ -83,7 +148,7 @@ def f(x): x = torch.randn(1, 32, 64) gm = _trace(f, x) before = [str(n.target) for n in _complex_nodes(gm.graph)] - ComplexToRealPairs()(gm.graph) + pytorchsim_post_grad_pass(gm) after = [str(n.target) for n in _complex_nodes(gm.graph)] assert before == after, f"an ineligible component was rewritten: {before} -> {after}" print("unhandled complex op left alone:", after) @@ -92,5 +157,8 @@ def f(x): if __name__ == "__main__": device = torch.device("npu:0") test_pass_leaves_no_complex() + test_complex_scalar_multiply() + test_components_are_judged_apart() + test_row_mm_stays_real() test_unhandled_op_is_left_alone() test_rope_on_device(device) diff --git a/tests/ops/misc/test_eager_to_compile_recursion.py b/tests/ops/misc/test_eager_to_compile_recursion.py index b27f13eb4..62575a06d 100644 --- a/tests/ops/misc/test_eager_to_compile_recursion.py +++ b/tests/ops/misc/test_eager_to_compile_recursion.py @@ -20,7 +20,7 @@ # RecursionError: maximum recursion depth exceeded # # DeepSeek-V2's RoPE closed that loop, because it multiplies complex tensors. -# It does not close any more: rewrite_fx_graph.py rewrites the complex +# It does not close any more: frontend/post_grad_pass.py rewrites the complex # multiply into real arithmetic, so Inductor generates a kernel and no fallback # is emitted. This test is that sentence, executable -- it recurses on a tree # without that pass and passes with it. diff --git a/tests/ops/misc/test_histc.py b/tests/ops/misc/test_histc.py index 440d9b4e4..1aef2190d 100644 --- a/tests/ops/misc/test_histc.py +++ b/tests/ops/misc/test_histc.py @@ -2,9 +2,15 @@ import sys import torch import torch._dynamo +from torch import fx +from torch._subclasses.fake_tensor import FakeTensorMode sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) from _pytorchsim_utils import test_result +from pytorchsim.frontend.post_grad_pass import pytorchsim_post_grad_pass + +aten = torch.ops.aten + def _histc(x, bins, lo, hi): return torch.histc(x, bins=bins, min=lo, max=hi) @@ -22,8 +28,7 @@ def test_histc_integral(device, n=64, bins=8): # and "mps", integral otherwise -- so `npu` gets the branch written for # CUDA and the fallback then lands on the very kernel the first branch # exists to avoid. That is what stopped DeepSeek-V3 under transformers - # 5.15.0, and pytorchsim/frontend/rewrite_fx_graph.py is the answer: - # counting is dtype-blind, so it casts in and back out. + # 5.15.0; post_grad_pass.rewrite_aten_histc counts it on the device. # # Both integral widths are here because they take different paths back: # the counts return in the INPUT's dtype, which is the contract the CUDA @@ -43,9 +48,7 @@ def test_histc_integral(device, n=64, bins=8): def test_histc_float_unchanged(device, n=64, bins=8): - # The floating case must keep going to ATen -- the decomposition returns - # NotImplemented there, which is also what stops it recursing on the cast - # it just made. + """A floating histc is counted on the device too, and comes back in its own dtype.""" g = torch.Generator().manual_seed(1) cpu_x = torch.rand(n, generator=g) * (bins - 1) cpu_out = torch.histc(cpu_x, bins=bins, min=0, max=bins - 1) @@ -57,7 +60,65 @@ def test_histc_float_unchanged(device, n=64, bins=8): test_result("histc float32", npu_out, cpu_out) +def _unlowered(gm): + """The ops of gm Inductor has no lowering for; the device pass runs after decomposition, so any it + inserts must lower as they are.""" + from torch._inductor.lowering import lowerings + return sorted({str(m.target) for m in gm.graph.nodes if callable(m.target) + and m.target not in lowerings and m.target.overloadpacket not in lowerings}) + + +def _histc_graph(x, bins, lo, hi): + """A graph of one aten.histc of x as the post-grad passes see it; built by hand, since make_fx cannot + trace an integral histc on the CPU.""" + mode = FakeTensorMode() + g = fx.Graph() + p = g.placeholder("x") + p.meta["val"] = mode.from_tensor(x) + h = g.call_function(aten.histc.default, (p, bins, lo, hi)) + with mode: + h.meta["val"] = torch.empty(bins, dtype=x.dtype) + g.output(h) + return fx.GraphModule(torch.nn.Module(), g) + + +def test_pass_counts_on_the_device(n=64): + """The device pass alone leaves no aten.histc and counts what aten counts: bins that are the values, + wider edges, int8 past 127 bins, floats with values on and past the edges, and min == max.""" + g = torch.Generator().manual_seed(2) + ints = torch.randint(-4, 20, (n,), generator=g) + floats = torch.cat([torch.rand(n, generator=g) * 3 - 1, torch.tensor([0., 0.5, 1., 1.0000001, float("nan")])]) + cases = ( + ("values", ints.clamp(0, 7).to(torch.int32), 8, 0, 7), + ("wide edges", ints.to(torch.int32), 8, 0, 15), + ("int8 past 127 bins", torch.tensor([0, 1, 127, -100, -100, -100], dtype=torch.int8), 200, 0, 199), + ("float", floats, 4, 0, 1), + ("float min == max", floats.nan_to_num(0.0), 5, 0, 0), + ("int64 min == max", ints, 6, 0, 0), + ("one value", torch.full((7,), 3, dtype=torch.int64), 4, 0, 0), + ) + for name, x, bins, lo, hi in cases: + gm = _histc_graph(x, bins, lo, hi) + pytorchsim_post_grad_pass(gm) + left = [m for m in gm.graph.nodes if m.target is aten.histc.default] + assert not left, f"{name}: {len(left)} aten.histc left" + assert not _unlowered(gm), f"{name}: no Inductor lowering for {_unlowered(gm)}" + ref = torch.histc(x.double() if not x.is_floating_point() else x, bins, lo, hi).to(x.dtype) + out = gm(x) + assert torch.equal(out, ref), f"{name}: {out.tolist()} != {ref.tolist()}" + print(f"histc pass {name}: {out.tolist()}") + for name, x, lo, hi in (("int edges that truncate to one", ints.to(torch.int32), 0.2, 0.8), + ("float max below min", floats, 1.0, 0.0)): + try: + pytorchsim_post_grad_pass(_histc_graph(x, 4, lo, hi)) + except RuntimeError as e: + assert "max must be larger than min" in str(e), f"{name}: {e}" + else: + raise AssertionError(f"{name}: [{lo}, {hi}] was not refused") + + if __name__ == "__main__": device = torch.device("npu:0") + test_pass_counts_on_the_device() test_histc_integral(device) test_histc_float_unchanged(device) diff --git a/tests/ops/misc/test_polar.py b/tests/ops/misc/test_polar.py index ec75a07e9..5e87aff8f 100644 --- a/tests/ops/misc/test_polar.py +++ b/tests/ops/misc/test_polar.py @@ -2,9 +2,13 @@ import sys import torch import torch._dynamo +from torch.fx.experimental.proxy_tensor import make_fx +from torch._inductor.decomposition import select_decomp_table sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) from _pytorchsim_utils import test_result +from pytorchsim.frontend.post_grad_pass import pytorchsim_post_grad_pass + def _rope_like(a): # DeepSeek-V2's RoPE: freqs arrives as a TRANSPOSED view out of a bmm, and @@ -26,10 +30,9 @@ def test_polar_on_transposed(device, n=32): # 'torch.ops.aten.polar.default') # AssertionError: expected size 32==32, stride 32==1 at dim=1 # - # pytorchsim/frontend/rewrite_fx_graph.py takes the extern call out - # instead of arguing about the layout: the pair is built with ops this - # backend compiles and view_as_complex names it, which Inductor already - # treats as a view over real data. + # post_grad_pass.rewrite_aten_polar takes the extern call out instead + # of arguing about the layout: the pair is built contiguous with ops this + # backend compiles, and the complex rewrite takes it to real pairs. x = torch.randn(1, n, n) cpu_out = _rope_like(x) @@ -40,8 +43,7 @@ def test_polar_on_transposed(device, n=32): def test_polar_contiguous(device, n=32): - # The ordinary case, which passed before the decomposition too: it is here - # so a future rewrite that only handles the transposed shape is caught. + """The ordinary case, so a rewrite that only handles the transposed shape is caught.""" def f(a): return torch.view_as_real(torch.polar(torch.ones_like(a), a)) @@ -51,7 +53,30 @@ def f(a): test_result("polar on a contiguous tile", npu_out, cpu_out) +def _unlowered(gm): + """The ops of gm Inductor has no lowering for; the device pass runs after decomposition, so any it + inserts must lower as they are.""" + from torch._inductor.lowering import lowerings + return sorted({str(m.target) for m in gm.graph.nodes if callable(m.target) + and m.target not in lowerings and m.target.overloadpacket not in lowerings}) + + +def test_pass_leaves_no_polar(n=32): + """The device pass alone, on a traced polar of a transposed view: no aten.polar and no complex value + is left, and the real pairs are polar's.""" + x = torch.randn(1, n, n) + gm = make_fx(_rope_like, decomposition_table=select_decomp_table(), tracing_mode="fake")(x) + pytorchsim_post_grad_pass(gm) + left = [str(m.target) for m in gm.graph.nodes + if m.target is torch.ops.aten.polar.default + or (isinstance(m.meta.get("val"), torch.Tensor) and m.meta["val"].is_complex())] + assert not left, f"left after the pass: {left}" + assert not _unlowered(gm), f"no Inductor lowering for {_unlowered(gm)}" + test_result("polar pass", gm(x), _rope_like(x)) + + if __name__ == "__main__": device = torch.device("npu:0") + test_pass_leaves_no_polar() test_polar_on_transposed(device) test_polar_contiguous(device) diff --git a/tests/ops/sort/test_topk.py b/tests/ops/sort/test_topk.py index e27c199db..ba75b7bfb 100644 --- a/tests/ops/sort/test_topk.py +++ b/tests/ops/sort/test_topk.py @@ -1,30 +1,126 @@ +"""torch.topk on the npu: the topk kernel where topk.topk_plan takes the call, the rounds as aten ops +where it does not, against torch.topk on the CPU. + +Each case states the route it must take and checks topk.ROUTED: one "kernel" count per launch of a +compiled call the kernel takes, one "rounds" count per eager call, nothing for rounds compiled into +the graph (Inductor's own kernels). Ties take the first index, as a stable descending sort does. + + kernel rows a whole number of programs and not, a row length that is not a power of two, the + smallest k, bf16, ties + rounds topk along a dim that is not the last + grad a compiled call whose input requires grad runs the kernel, and its gradient is aten's + eager outside torch.compile, and under inference_mode eagerly and compiled + counts a compiled call run twice counts two launches, not its traces + +Usage: test_topk.py [case ...] (all cases when none is named) +""" import os import sys + import torch -import torch._dynamo -import torch.utils.cpp_extension -sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result -def test_topk(device, size=(128, 128), k=5, dim=-1, largest=True, sorted=True): - # dim 해석을 위해 양수 인덱스로 변환 - dim_ = dim if dim >= 0 else (len(size) + dim) - assert 0 <= dim_ < len(size), "dim이 텐서 차원 범위를 벗어났습니다." - assert k <= size[dim_], f"k(={k})는 size[dim](={size[dim_]}) 이하여야 합니다." +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), + "tests")) + +device = torch.device("npu:0") + +# name: (route, shape, k, dim, largest, dtype) +CASES = { + "router": ("kernel", (64, 128), 8, -1, True, torch.float32), + "ragged_rows": ("kernel", (100, 128), 5, -1, True, torch.float32), + "row_not_pow2": ("kernel", (32, 100), 3, -1, True, torch.float32), + "smallest": ("kernel", (64, 128), 4, -1, False, torch.float32), + "bf16": ("kernel", (64, 128), 8, -1, True, torch.bfloat16), + "ties": ("kernel", (64, 128), 8, -1, True, torch.float32), + "dim0": ("rounds", (128, 32), 4, 0, True, torch.float32), +} + + +def _input(shape, dtype, ties=False, seed=0): + g = torch.Generator().manual_seed(seed) + x = torch.randn(*shape, generator=g) + return ((x * 4).round() if ties else x).to(dtype) + + +def _ref(x, k, dim, largest): + """Values and indices of a stable sort: among equal values the first index comes first.""" + order = torch.sort(x.float(), dim=dim, descending=largest, stable=True).indices.narrow(dim, 0, k) + return x.gather(dim, order), order + + +def _routed(): + from pytorchsim.frontend import topk + return topk.ROUTED + + +def _check(name, got, want, route, took): + """Values and indices equal, and ROUTED is `route` (a dict of counts).""" + ok = torch.equal(got[0].cpu(), want[0]) and torch.equal(got[1].cpu(), want[1]) and took == route + print(f"{name}: route={took} want={route} {'PASS' if ok else 'FAIL'}", flush=True) + return ok + + +def run_case(name): + route, shape, k, dim, largest, dtype = CASES[name] + x = _input(shape, dtype, ties=name == "ties") + _routed().clear() + torch._dynamo.reset() + f = torch.compile(lambda t: torch.topk(t, k, dim=dim, largest=largest), dynamic=False) + want = {} if route == "rounds" else {route: 1} + return _check(name, f(x.to(device)), _ref(x, k, dim, largest), want, dict(_routed())) + + +def run_grad(name): + """values.sum().backward() through the compiled kernel: the gradient is 1 at each index taken.""" + x = _input((64, 128), torch.float32) + ref = x.clone().requires_grad_() + torch.topk(ref, 8, -1).values.sum().backward() + dev = x.to(device).requires_grad_() + _routed().clear() + torch._dynamo.reset() + v, i = torch.compile(lambda t: torch.topk(t, 8, -1), dynamic=False)(dev) + v.sum().backward() + ok = torch.equal(dev.grad.cpu(), ref.grad) and dict(_routed()) == {"kernel": 1} + print(f"{name}: route={dict(_routed())} want=kernel {'PASS' if ok else 'FAIL'}", flush=True) + return ok + + +def run_eager(name): + """Outside torch.compile the rounds run (one count); compiled under inference_mode, the kernel.""" + x = _input((64, 128), torch.float32) + want = _ref(x, 8, -1, True) + _routed().clear() + torch._dynamo.reset() + compiled = name == "inference_mode_compiled" + f = (torch.compile(lambda t: torch.topk(t, 8, -1), dynamic=False) if compiled + else lambda t: torch.topk(t, 8, -1)) + ctx = torch.no_grad() if name == "eager" else torch.inference_mode() + with ctx: + got = f(x.to(device)) + return _check(name, got, want, {"kernel": 1} if compiled else {"rounds": 1}, dict(_routed())) + - def topk_fn(a): - return torch.topk(a, k, dim=dim, largest=largest, sorted=sorted) +def run_counts(name): + """A compiled call run twice counts two launches.""" + x = _input((64, 128), torch.float32) + _routed().clear() + torch._dynamo.reset() + f = torch.compile(lambda t: torch.topk(t, 8, -1), dynamic=False) + for _ in range(2): + f(x.to(device)) + ok = dict(_routed()) == {"kernel": 2} + print(f"{name}: route={dict(_routed())} want={{'kernel': 2}} {'PASS' if ok else 'FAIL'}", + flush=True) + return ok - x = torch.randn(size) - x = x.to(device=device) - opt_topk = torch.compile(dynamic=False)(topk_fn) - res_values, res_indices = opt_topk(x) - ref_values, ref_indices = torch.topk(x.cpu(), k, dim=dim, largest=largest, sorted=sorted) +EXTRA = {"grad": run_grad, "eager": run_eager, "inference_mode": run_eager, + "inference_mode_compiled": run_eager, "counts": run_counts} - test_result("TopK/values", res_values, ref_values) - test_result("TopK/indices", res_indices, ref_indices) if __name__ == "__main__": - device = torch.device('npu:0') - test_topk(device, (128, 128), k=2, dim=-1) \ No newline at end of file + names = sys.argv[1:] or [*CASES, *EXTRA] + results = [EXTRA[n](n) if n in EXTRA else run_case(n) for n in names] + if not all(results): + sys.exit(1) + print("PASS")