From 31747c86a0ab5e88beb944d98f899a531d1ee191 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Thu, 22 Oct 2026 23:50:20 +0900 Subject: [PATCH 01/12] [Frontend] A complex scalar times a complex value is a complex product in the real pairs ComplexToRealPairs multiplied the [..., 2] pair of a complex value by the other operand whenever that operand was not a complex node. Post-grad, z * (1+2j) is aten.mul.Tensor(z, (1+2j)), so the pair was multiplied by the Python complex itself: the result came out complex64 with the wrong values and no warning. A Python complex operand now takes the same (ar*br - ai*bi, ar*bi + ai*br) form as two complex nodes; a real scalar or tensor still scales the pair. The pass uuid moves to -3 so Inductor's FX cache does not replay a graph the old pass rewrote. torch 2.14 still does not lower complex mul (lowering.py warns and falls back; only complex add is decomposed), so the pass stays. tests/ops/misc/test_complex_to_real.py: test_complex_scalar_multiply puts a complex scalar on each side; it fails on the old pass (three aten.mul.Tensor left complex) and passes now. --- pytorchsim/frontend/rewrite_fx_graph.py | 24 +++++++++++++++--------- tests/ops/misc/test_complex_to_real.py | 18 ++++++++++++++++++ 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/pytorchsim/frontend/rewrite_fx_graph.py b/pytorchsim/frontend/rewrite_fx_graph.py index f146ff23c..ab3ab5b9e 100644 --- a/pytorchsim/frontend/rewrite_fx_graph.py +++ b/pytorchsim/frontend/rewrite_fx_graph.py @@ -317,7 +317,7 @@ class ComplexToRealPairs(CustomGraphPass): """ def uuid(self): - return "pytorchsim-complex-to-real-pairs-2" + return "pytorchsim-complex-to-real-pairs-3" def __call__(self, graph: torch.fx.Graph) -> None: complex_nodes = [n for n in graph.nodes if _is_complex(n)] @@ -352,6 +352,11 @@ def call(target, *args): node.meta["val"] = target(*[_unwrap(a) for a in args]) return node + def join(re, im): + return call(aten.cat.default, + [call(aten.unsqueeze.default, re, -1), + call(aten.unsqueeze.default, im, -1)], -1) + pair = {} for n in complex_nodes: with graph.inserting_before(n): @@ -366,21 +371,22 @@ def call(target, *args): continue a, b = n.args[0], n.args[1] - if _is_complex(a) and _is_complex(b): - pa, pb = pair[a], pair[b] + cx, other = (a, b) if _is_complex(a) else (b, a) + if _is_complex(other) or isinstance(other, complex): + pa = pair[cx] 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) + if isinstance(other, complex): + br, bi = other.real, other.imag + else: + br = call(aten.select.int, pair[other], -1, 0) + bi = 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)) - pair[n] = call(aten.cat.default, - [call(aten.unsqueeze.default, re, -1), - call(aten.unsqueeze.default, im, -1)], -1) + pair[n] = join(re, im) 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) diff --git a/tests/ops/misc/test_complex_to_real.py b/tests/ops/misc/test_complex_to_real.py index 3ee57786e..e5da2c1bb 100644 --- a/tests/ops/misc/test_complex_to_real.py +++ b/tests/ops/misc/test_complex_to_real.py @@ -72,6 +72,23 @@ 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) + ComplexToRealPairs()(gm.graph) + gm.recompile() + after = _complex_nodes(gm.graph) + assert not after, f"complex nodes survived the pass: {[str(n.target) for n in after]}" + test_result("complex-to-real (complex scalar)", gm(x), f(x)) + + 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 @@ -92,5 +109,6 @@ def f(x): if __name__ == "__main__": device = torch.device("npu:0") test_pass_leaves_no_complex() + test_complex_scalar_multiply() test_unhandled_op_is_left_alone() test_rope_on_device(device) From ad691161d689fa6ea5fa2d50961977de900e36ab Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Thu, 22 Oct 2026 23:50:23 +0900 Subject: [PATCH 02/12] [Frontend] rewrite_fx_graph names each rewrite by the op it takes, in snake case decompose_histc/polar -> decompose_aten_histc/polar, rewrite_grouped_mm -> rewrite_transformers_grouped_mm_fallback, rewrite_topk -> rewrite_aten_topk, rewrite_row_mm -> rewrite_aten_mm_addmm_row. ComplexToRealPairs, a class only for its uuid, is the function rewrite_aten_view_as_complex like the other passes; its uuid string is now its install_once key, so Inductor's cache key is unchanged. _Chain is _chain. No behaviour change. --- pytorchsim/frontend/rewrite_fx_graph.py | 180 ++++++++++++------------ tests/ops/misc/test_complex_to_real.py | 8 +- 2 files changed, 91 insertions(+), 97 deletions(-) diff --git a/pytorchsim/frontend/rewrite_fx_graph.py b/pytorchsim/frontend/rewrite_fx_graph.py index ab3ab5b9e..58939eadf 100644 --- a/pytorchsim/frontend/rewrite_fx_graph.py +++ b/pytorchsim/frontend/rewrite_fx_graph.py @@ -16,7 +16,7 @@ @register_decomposition(aten.histc.default) -def decompose_histc(self, bins: int = 100, min: int = 0, max: int = 0): +def decompose_aten_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. @@ -32,7 +32,7 @@ def decompose_histc(self, bins: int = 100, min: int = 0, max: int = 0): @register_decomposition(aten.polar.default) -def decompose_polar(abs, angle): +def decompose_aten_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. @@ -70,7 +70,7 @@ def _identity(fn): return f"{module}.{name}" if name else f"{module}." -class _Chain(CustomGraphPass): +class _chain(CustomGraphPass): """Inductor's single post-grad slot, as a chain that knows what is in it.""" def __init__(self, foreign): @@ -102,8 +102,8 @@ def install_once(key, fn): from torch._inductor import config chain = config.post_grad_custom_post_pass - if not isinstance(chain, _Chain): - chain = _Chain(chain) + if not isinstance(chain, _chain): + chain = _chain(chain) config.post_grad_custom_post_pass = chain return chain.add(key, fn) @@ -151,7 +151,7 @@ def _emit_dense_grouped_mm(g, inp, weight, offs, s, e, o, dtype, dev): return out -def rewrite_grouped_mm(g) -> None: +def rewrite_transformers_grouped_mm_fallback(g) -> None: """Replace every `transformers.grouped_mm_fallback` call with the dense form.""" target = _grouped_mm_target() if target is None: @@ -214,7 +214,7 @@ def _emit_topk(g, x, k, dim, largest, shape, dtype, dev): return call(aten.cat.default, (vals, dim)), call(aten.cat.default, (idxs, dim)) -def rewrite_topk(g) -> None: +def rewrite_aten_topk(g) -> None: """Replace every `aten.topk.default` whose users are getitem with the rounds.""" if isinstance(g, fx.GraphModule): g = g.graph @@ -261,7 +261,7 @@ def _row_times_matrix(node): return a, b, bias -def rewrite_row_mm(g) -> None: +def rewrite_aten_mm_addmm_row(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): @@ -310,101 +310,95 @@ def _fake_mode(graph): return None -class ComplexToRealPairs(CustomGraphPass): +def rewrite_aten_view_as_complex(graph) -> None: """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. """ + if isinstance(graph, fx.GraphModule): + graph = graph.graph + complex_nodes = [n for n in graph.nodes if _is_complex(n)] + if not complex_nodes: + return - def uuid(self): - return "pytorchsim-complex-to-real-pairs-3" - - def __call__(self, graph: torch.fx.Graph) -> None: - complex_nodes = [n for n in graph.nodes if _is_complex(n)] - if not complex_nodes: + for n in complex_nodes: + if n.op != "call_function": 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 + 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 - - def join(re, im): - return call(aten.cat.default, - [call(aten.unsqueeze.default, re, -1), - call(aten.unsqueeze.default, im, -1)], -1) - - 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] - cx, other = (a, b) if _is_complex(a) else (b, a) - if _is_complex(other) or isinstance(other, complex): - pa = pair[cx] - ar = call(aten.select.int, pa, -1, 0) - ai = call(aten.select.int, pa, -1, 1) - if isinstance(other, complex): - br, bi = other.real, other.imag - else: - br = call(aten.select.int, pair[other], -1, 0) - bi = 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)) - pair[n] = join(re, im) + 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 + + def join(re, im): + return call(aten.cat.default, + [call(aten.unsqueeze.default, re, -1), + call(aten.unsqueeze.default, im, -1)], -1) + + 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] + cx, other = (a, b) if _is_complex(a) else (b, a) + if _is_complex(other) or isinstance(other, complex): + pa = pair[cx] + ar = call(aten.select.int, pa, -1, 0) + ai = call(aten.select.int, pa, -1, 1) + if isinstance(other, complex): + br, bi = other.real, other.imag else: - 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() + br = call(aten.select.int, pair[other], -1, 0) + bi = 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)) + pair[n] = join(re, im) + else: + 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() 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)) + install_once("pytorchsim-grouped-mm", npu_only(rewrite_transformers_grouped_mm_fallback)) + install_once("pytorchsim-topk", npu_only(rewrite_aten_topk)) + install_once("pytorchsim-row-mm", npu_only(rewrite_aten_mm_addmm_row)) + install_once("pytorchsim-complex-to-real-pairs-3", npu_only(rewrite_aten_view_as_complex)) diff --git a/tests/ops/misc/test_complex_to_real.py b/tests/ops/misc/test_complex_to_real.py index e5da2c1bb..39605d325 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.rewrite_fx_graph import rewrite_aten_view_as_complex aten = torch.ops.aten @@ -52,7 +52,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) + rewrite_aten_view_as_complex(gm.graph) gm.recompile() after = _complex_nodes(gm.graph) @@ -82,7 +82,7 @@ def f(x): x = torch.randn(1, 32, 64) gm = _trace(f, x) - ComplexToRealPairs()(gm.graph) + rewrite_aten_view_as_complex(gm.graph) gm.recompile() after = _complex_nodes(gm.graph) assert not after, f"complex nodes survived the pass: {[str(n.target) for n in after]}" @@ -100,7 +100,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) + rewrite_aten_view_as_complex(gm.graph) 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) From 1c43abcbe1f8cea746ac6f51bbbc978b660d87aa Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Tue, 20 Oct 2026 15:58:55 +0900 Subject: [PATCH 03/12] [Frontend] topk on the npu is one Triton kernel that stores its values and indices once each rewrite_topk replaced aten.topk with K rounds of amax, first index and mask, then cat. Inductor fused the rounds into one kernel but made the cat of 2K reductions into 2K column views of the outputs: a kernel with 16 output pointers for k = 8, and 16 DMAs a program on TOGSim. With the TOG of the T 8192 router kernel cut to 2 contiguous stores and nothing else changed, TOGSim went 94331 -> 81815 cycles; 16 contiguous stores stayed at 93388, so the cost is the count of DMAs. Every other kernel of the compiler's validation bundle has one output. frontend/topk.py registers aten::topk's npu kernel at AutogradPrivateUse1 and PrivateUse1 (the route attention takes, torch.library only) and calls torchsim::topk, a triton_op. Its kernel takes a row on each lane, runs the same rounds and gathers the K values and indices of its rows in registers, then stores each once. topk_plan is the one gate: the last dim of a floating input whose row fits the scratchpad budget; a program takes vector_lanes rows (those past the end masked), so a call of fewer rows keeps the same layout instead of spreading the row over the lanes. A call the plan declines, and an eager call, run the rounds as aten ops; a declined one is logged with its reason. The backward scatters the values' gradient to the indices, aten's topk backward. rewrite_topk is removed: no aten.topk on the npu reaches the post-grad graph. tests/ops/sort/test_topk.py pins the routes and the values against a stable CPU sort: rows a whole number of programs and not, a row length that is not a power of two, smallest, bf16, ties to the first index, a dim that is not the last (rounds), the gradient, eager and inference_mode, and one launch counted per call. It joins the allowlist. Timed with PyTorchSim-Triton-Backend's validation/vector harness on its main 7fb7195 (TOGSim 601fa78, configs/tpuv6e.yml), the bundle built by scripts/ci/bundle.py with the topk suite (PyTorchSim #395) and the measured tables of PyTorchSim-Triton-Backend #208: the Qwen3-30B-A3B router topk, f32 [T, 128], k 8, T 1..8192, TOGSim over tpu-perf-archive topk_block pallas_t_lanes. Geomean 2.160 -> 0.945, within 10% 0 -> 9 of 10. T 1 is 0.73: its v6e row includes a 0.99 us layout copy XLA adds around the (1, 128) block. T >= 256 is 0.92-0.98, on the fast side. --- .github/workflows/pytorchsim_test.yml | 1 + pytorchsim/frontend/inductor_patches.py | 3 +- pytorchsim/frontend/rewrite_fx_graph.py | 75 +--------- pytorchsim/frontend/topk.py | 182 ++++++++++++++++++++++++ scripts/ci/triton_route_passing.txt | 1 + tests/ops/sort/test_topk.py | 136 +++++++++++++++--- 6 files changed, 304 insertions(+), 94 deletions(-) create mode 100644 pytorchsim/frontend/topk.py diff --git a/.github/workflows/pytorchsim_test.yml b/.github/workflows/pytorchsim_test.yml index 9564f3bf1..683c2fb40 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_breakdown_viewer.py - tests/system/test_bundle_reuse.py 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/rewrite_fx_graph.py b/pytorchsim/frontend/rewrite_fx_graph.py index 58939eadf..5e3922d4c 100644 --- a/pytorchsim/frontend/rewrite_fx_graph.py +++ b/pytorchsim/frontend/rewrite_fx_graph.py @@ -1,11 +1,9 @@ """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(). +Decompositions (histc, polar) and post-grad passes (grouped_mm, row mm, complex to real +pairs), all chained onto Inductor's one post-grad hook by install(). topk is frontend/topk.py. """ -from operator import getitem - import torch from torch import fx from torch._inductor.custom_graph_pass import CustomGraphPass @@ -177,74 +175,6 @@ def rewrite_transformers_grouped_mm_fallback(g) -> None: _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_aten_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": @@ -399,6 +329,5 @@ def join(re, im): def install(): """Chain the post-grad passes onto Inductor's hook, each at most once.""" install_once("pytorchsim-grouped-mm", npu_only(rewrite_transformers_grouped_mm_fallback)) - install_once("pytorchsim-topk", npu_only(rewrite_aten_topk)) install_once("pytorchsim-row-mm", npu_only(rewrite_aten_mm_addmm_row)) install_once("pytorchsim-complex-to-real-pairs-3", npu_only(rewrite_aten_view_as_complex)) 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/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") From 6886059bf52cdc12b6a5c13afbee92822b407aa5 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Thu, 22 Oct 2026 23:52:08 +0900 Subject: [PATCH 04/12] [Frontend] transformers' grouped_mm_fallback takes aten._grouped_mm's npu kernel; the dense rewrite goes transformers 5.x calls torch.ops.transformers.grouped_mm_fallback instead of aten._grouped_mm under torch.compile when the weight is not bf16 (integrations/moe.py _can_use_grouped_mm). rewrite_fx_graph rewrote it into a dense form: every expert's mm over every row, masked and summed, E times the work, which TOGSim then priced. grouped_mm.install now registers the same entry (_aten_grouped_mm, so the same triton_op and kernel, gate and math route) at AutogradPrivateUse1 and PrivateUse1 of transformers::grouped_mm_fallback too. The registration precedes transformers' own definition of the op and outranks its Autograd and CompositeExplicitAutograd kernels on the npu only; the CPU keeps transformers' kernel. rewrite_transformers_grouped_mm_fallback, _grouped_mm_target and _emit_dense_grouped_mm are removed. Needs aten._grouped_mm's npu kernel (PyTorchSim #412, on pytorchsim-triton-backend as a5d1fbd) and, for timing, the compiler's TOG data args (PyTorchSim-Triton-Backend #282, not yet in the pinned PTB). tests/ops/gemm/test_grouped_mm.py: case fallback runs the fallback op at f32 compiled and asks for one grouped-kernel launch and no extern call. --- pytorchsim/frontend/grouped_mm.py | 30 +++++++---- pytorchsim/frontend/rewrite_fx_graph.py | 69 ++----------------------- tests/ops/gemm/test_grouped_mm.py | 20 +++++-- 3 files changed, 39 insertions(+), 80 deletions(-) diff --git a/pytorchsim/frontend/grouped_mm.py b/pytorchsim/frontend/grouped_mm.py index 33f7328d8..eba736dca 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 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 @@ -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/rewrite_fx_graph.py b/pytorchsim/frontend/rewrite_fx_graph.py index 5e3922d4c..c5fb761d7 100644 --- a/pytorchsim/frontend/rewrite_fx_graph.py +++ b/pytorchsim/frontend/rewrite_fx_graph.py @@ -1,7 +1,8 @@ """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, row mm, complex to real -pairs), all chained onto Inductor's one post-grad hook by install(). topk is frontend/topk.py. +Decompositions (histc, polar) and post-grad passes (row mm, complex to real pairs), all +chained onto Inductor's one post-grad hook by install(). topk and grouped_mm are +frontend/topk.py and frontend/grouped_mm.py. """ import torch @@ -10,7 +11,6 @@ from torch._inductor.decomposition import register_decomposition aten = torch.ops.aten -prims = torch.ops.prims @register_decomposition(aten.histc.default) @@ -113,68 +113,6 @@ def _recompile(g): 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_transformers_grouped_mm_fallback(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 _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": @@ -328,6 +266,5 @@ def join(re, im): def install(): """Chain the post-grad passes onto Inductor's hook, each at most once.""" - install_once("pytorchsim-grouped-mm", npu_only(rewrite_transformers_grouped_mm_fallback)) install_once("pytorchsim-row-mm", npu_only(rewrite_aten_mm_addmm_row)) install_once("pytorchsim-complex-to-real-pairs-3", npu_only(rewrite_aten_view_as_complex)) 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__": From 685180ffc318a956fddefd6df8789f48880df683 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 23 Oct 2026 00:02:11 +0900 Subject: [PATCH 05/12] [Frontend] rewrite_fx_graph is the npu device_custom_pass; no global decomposition, no post-grad hook rewrite_fx_graph registered histc and polar in Inductor's global decomposition table, so every device's compile took them, CPU's included, and chained its passes onto config.post_grad_custom_post_pass, Inductor's one global slot, with its own gate (npu_only) and chain (_chain, install_once). Inductor has a hook for exactly this: register_backend_for_device's device_custom_pass, a CustomGraphModulePass it runs after its post-grad passes on a graph with an npu tensor only, its uuid in the FX cache key. npu_post_grad_pass is that pass, registered with the npu backend in torch_openreg; it runs REWRITES in order: rewrite_aten_histc integral input, bins its values: iota, eq, sum, cast (as the decomposition did); other edges count at float32 through aten.histc and cast back, and a float input is left to aten; both are logged rewrite_aten_polar view_as_complex of the contiguous pair (abs*cos, abs*sin), which the complex rewrite then takes to real pairs rewrite_aten_mm_addmm_row, rewrite_aten_view_as_complex unchanged histc and polar are in no Inductor decomposition table, so they reach the post-grad graph as nodes. The pass runs after Inductor's fake tensor update, so _emitter sets every new node's fake value. Its uuid hashes this file (get_hash_for_files, as Inductor's CustomPassBase recommends). Removed: register_decomposition, the post_grad_custom_post_pass chain, npu_only, is_npu_graph, _identity, install. register_backend_for_device is still torch._inductor, but it is the extension point for an out-of-tree device. Tests: test_histc test_pass_counts_on_the_device (no aten.histc left for bins 0..N-1, one at float32 for wider edges, values as the CPU's), test_polar test_pass_leaves_no_polar, and test_complex_to_real runs the whole pass, as Inductor does. On the npu (run/tc-solo toolchain at PTB main defa86b): test_complex_to_real, test_histc, test_polar, test_topk (12 cases) and test_grouped_mm (5 cases) pass; the one call left to aten in their wrappers is the float32 histc, logged. This commit goes with the topk commit before it (PyTorchSim #396): it takes rewrite_fx_graph with rewrite_topk already removed, and topk stays on the npu only through #396's frontend/topk.py. --- device/torch_openreg/__init__.py | 4 +- pytorchsim/frontend/rewrite_fx_graph.py | 269 +++++++++++------------- tests/ops/misc/test_complex_to_real.py | 15 +- tests/ops/misc/test_histc.py | 41 +++- tests/ops/misc/test_polar.py | 28 ++- 5 files changed, 185 insertions(+), 172 deletions(-) diff --git a/device/torch_openreg/__init__.py b/device/torch_openreg/__init__.py index 1e407115a..3dcf6b1b1 100644 --- a/device/torch_openreg/__init__.py +++ b/device/torch_openreg/__init__.py @@ -21,7 +21,6 @@ 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 @@ -31,7 +30,8 @@ torch._inductor.codegen.common.register_backend_for_device( "npu", TritonNPUScheduling, - TritonNPUWrapperCodegen + TritonNPUWrapperCodegen, + device_custom_pass=_rewrite_fx_graph.npu_post_grad_pass, ) torch_openreg.openreg.init() diff --git a/pytorchsim/frontend/rewrite_fx_graph.py b/pytorchsim/frontend/rewrite_fx_graph.py index c5fb761d7..bc523726b 100644 --- a/pytorchsim/frontend/rewrite_fx_graph.py +++ b/pytorchsim/frontend/rewrite_fx_graph.py @@ -1,116 +1,117 @@ """Our rewrites of the FX graph, so ops with no npu kernel stay on the device. -Decompositions (histc, polar) and post-grad passes (row mm, complex to real pairs), all -chained onto Inductor's one post-grad hook by install(). topk and grouped_mm are +npu_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._inductor.custom_graph_pass import CustomGraphPass -from torch._inductor.decomposition import register_decomposition +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() -@register_decomposition(aten.histc.default) -def decompose_aten_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) +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 -@register_decomposition(aten.polar.default) -def decompose_aten_polar(abs, angle): - """`polar` as a view over a real pair, so it never becomes an extern call. +def _is_complex(node): + """Whether the node holds a complex tensor.""" + v = _val(node) + return isinstance(v, torch.Tensor) and v.is_complex() - 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 _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 - def __call__(self, graph): - if self._foreign is not None: - self._foreign(graph) - for fn in self._passes: - fn(graph) +def _emitter(graph): + """call(target, *args, **kwargs): a node at the graph's insert point with its fake value set, since + nothing after the device pass sets it.""" + fake_mode = _fake_mode(graph) + + 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) + + def call(target, *args, **kwargs): + node = graph.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 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 _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 _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 rewrite_aten_histc(graph) -> None: + """histc of an integral tensor whose bins are its values (bins N, min 0, max N-1) as one compare and one + count in the input's dtype; other integral edges count at float32 and cast back, an extern call, logged.""" + call = _emitter(graph) + for node in list(graph.nodes): + if node.op != "call_function" or node.target is not aten.histc.default: + continue + x = node.args[0] + xv = _val(x) + said = dict(zip(("bins", "min", "max"), node.args[1:]), **node.kwargs) + bins, lo, hi = int(said.get("bins", 100)), said.get("min", 0), said.get("max", 0) + if xv is None or xv.is_floating_point(): + logger.info("[rewrite_fx_graph] histc %s: left to aten (no npu kernel)", + None if xv is None else xv.dtype) + continue + with graph.inserting_before(node): + if lo == 0 and hi == bins - 1: + seats = call(prims.iota.default, bins, start=0, step=1, dtype=xv.dtype, + device=xv.device, requires_grad=False) + hits = call(aten.eq.Tensor, call(aten.reshape.default, x, [-1, 1]), + call(aten.reshape.default, seats, [1, -1])) + out = call(prims.convert_element_type.default, + call(aten.sum.dim_IntList, hits, [0]), xv.dtype) + else: + logger.info("[rewrite_fx_graph] histc %s bins %d [%s, %s]: an extern call at float32", + xv.dtype, bins, lo, hi) + xf = call(prims.convert_element_type.default, x, torch.float32) + out = call(prims.convert_element_type.default, + call(aten.histc.default, xf, bins, lo, hi), xv.dtype) + node.replace_all_uses_with(out) + graph.erase_node(node) + + +def rewrite_aten_polar(graph) -> None: + """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.""" + call = _emitter(graph) + for node in list(graph.nodes): + if node.op != "call_function" or node.target is not aten.polar.default: + continue + r, angle = node.args[0], node.args[1] + with graph.inserting_before(node): + pair = _join(call, call(aten.mul.Tensor, r, call(aten.cos.default, angle)), + call(aten.mul.Tensor, r, call(aten.sin.default, angle))) + out = call(aten.view_as_complex.default, pair) + node.replace_all_uses_with(out) + graph.erase_node(node) def _row_times_matrix(node): @@ -129,28 +130,23 @@ def _row_times_matrix(node): return a, b, bias -def rewrite_aten_mm_addmm_row(g) -> None: +def rewrite_aten_mm_addmm_row(graph) -> 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): + call = _emitter(graph) + for node in list(graph.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)) + with graph.inserting_before(node): + column = call(aten.view.default, a, [k, 1]) + out = call(aten.sum.dim_IntList, call(aten.mul.Tensor, column, b), [0], True) if bias is not None: - out = g.call_function(aten.add.Tensor, (out, bias)) + out = call(aten.add.Tensor, out, bias) node.replace_all_uses_with(out) - changed += 1 - if changed: - _recompile(g) + graph.erase_node(node) _MUL = (aten.mul.Tensor, aten.mul.Scalar) @@ -158,33 +154,11 @@ def rewrite_aten_mm_addmm_row(g) -> None: _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 - - def rewrite_aten_view_as_complex(graph) -> None: """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. """ - if isinstance(graph, fx.GraphModule): - graph = graph.graph complex_nodes = [n for n in graph.nodes if _is_complex(n)] if not complex_nodes: return @@ -203,25 +177,7 @@ def rewrite_aten_view_as_complex(graph) -> None: 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 - - def join(re, im): - return call(aten.cat.default, - [call(aten.unsqueeze.default, re, -1), - call(aten.unsqueeze.default, im, -1)], -1) - + call = _emitter(graph) pair = {} for n in complex_nodes: with graph.inserting_before(n): @@ -250,7 +206,7 @@ def join(re, im): 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] = join(re, im) + pair[n] = _join(call, re, im) else: if isinstance(other, torch.fx.Node): other = call(aten.unsqueeze.default, other, -1) @@ -264,7 +220,20 @@ def join(re, im): graph.eliminate_dead_code() -def install(): - """Chain the post-grad passes onto Inductor's hook, each at most once.""" - install_once("pytorchsim-row-mm", npu_only(rewrite_aten_mm_addmm_row)) - install_once("pytorchsim-complex-to-real-pairs-3", npu_only(rewrite_aten_view_as_complex)) +REWRITES = (rewrite_aten_histc, rewrite_aten_polar, rewrite_aten_mm_addmm_row, rewrite_aten_view_as_complex) + + +class _npu_post_grad_pass(CustomGraphModulePass): + """REWRITES in order on an npu graph; its uuid hashes this file, so an edit here is a new cache key.""" + + def __call__(self, gm: fx.GraphModule) -> None: + for rewrite in REWRITES: + rewrite(gm.graph) + gm.graph.eliminate_dead_code() + gm.recompile() + + def uuid(self): + return get_hash_for_files((__file__,)) + + +npu_post_grad_pass = _npu_post_grad_pass() diff --git a/tests/ops/misc/test_complex_to_real.py b/tests/ops/misc/test_complex_to_real.py index 39605d325..958f2fa9e 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 rewrite_aten_view_as_complex +from pytorchsim.frontend.rewrite_fx_graph import npu_post_grad_pass aten = torch.ops.aten @@ -23,11 +23,8 @@ 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) @@ -52,7 +49,7 @@ def test_pass_leaves_no_complex(): before = _complex_nodes(gm.graph) assert before, "the traced graph should have complex nodes to rewrite" - rewrite_aten_view_as_complex(gm.graph) + npu_post_grad_pass(gm) gm.recompile() after = _complex_nodes(gm.graph) @@ -82,7 +79,7 @@ def f(x): x = torch.randn(1, 32, 64) gm = _trace(f, x) - rewrite_aten_view_as_complex(gm.graph) + npu_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]}" @@ -100,7 +97,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)] - rewrite_aten_view_as_complex(gm.graph) + npu_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) diff --git a/tests/ops/misc/test_histc.py b/tests/ops/misc/test_histc.py index 440d9b4e4..0429779df 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.rewrite_fx_graph import npu_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; rewrite_fx_graph.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 keeps aten's kernel: the device pass leaves it and logs why.""" 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,35 @@ def test_histc_float_unchanged(device, n=64, bins=8): test_result("histc float32", npu_out, cpu_out) +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, bins=8): + """The device pass alone, on a traced integral histc: bins that are the values leave no aten.histc; + other edges keep one, at float32, and both count what the CPU counts.""" + g = torch.Generator().manual_seed(2) + x = torch.randint(0, bins, (n,), generator=g).to(torch.int32) + for lo, hi, left in ((0, bins - 1, 0), (0, 2 * bins - 1, 1)): + gm = _histc_graph(x, bins, lo, hi) + npu_post_grad_pass(gm) + histcs = [n for n in gm.graph.nodes if n.target is aten.histc.default] + assert len(histcs) == left, f"[{lo}, {hi}]: {len(histcs)} aten.histc left, expected {left}" + test_result(f"histc pass [{lo}, {hi}]", gm(x), torch.histc(x.float(), bins, lo, hi).to(x.dtype)) + + 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..b1bae5ca6 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.rewrite_fx_graph import npu_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. + # rewrite_fx_graph.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,21 @@ def f(a): test_result("polar on a contiguous tile", npu_out, cpu_out) +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) + npu_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}" + 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) From f7e2012335284a4b0d474bedb3bac85d0f8976fe Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 23 Oct 2026 00:54:23 +0900 Subject: [PATCH 06/12] [Frontend] npu_post_grad_pass judges complex values per component, counts every histc on the device, and keeps provenance Four faults of rewrite_fx_graph, each reproduced first: rewrite_aten_view_as_complex checked every complex node of the graph at once and returned on the first it could not rewrite, silently: a graph with one exp of a complex value kept an unrelated RoPE multiply complex too, on the CPU. _complex_components groups the complex nodes by the values joining them; _why_not_real judges each group, _to_real_pairs rewrites the ones it takes, and a group left to aten is logged with why. rewrite_aten_histc counted on the device only when the bins were the values (min 0, max bins-1); any other edges and every floating input went to the CPU's histc. Its iota was in the input's dtype, so int8 with 200 bins wrapped past 127 and counted -100 in bin 156 (6 counts where aten gives 3). _emit_histc is aten's own rule for every case: bin (x - lo) * bins / (hi - lo), integral in int64 and floating in x's dtype, the top edge in the last bin, values outside [lo, hi] and NaN dropped, and min == max taking x's range, widened by one when x holds one value. No histc leaves the device now. _emitter set only a new node's fake value; it now also copies the rewritten node's original_aten, stack_trace, nn_module_stack, source_fn_stack, seq_nr and from_node, so kernel names and errors keep the op they came from. The pass recompiled every graph; it recompiles one it changed. The first device run found a fifth: aten.clamp.default, which the histc count used, is in Inductor's decomposition table and has no lowering, and this pass runs after decomposition. It uses clamp_max. Tests: test_histc test_pass_counts_on_the_device (bins that are the values, wider edges, int8 past 127 bins, floats on and past the edges and NaN, float and int64 min == max, one value: no aten.histc left, torch.equal to aten); test_complex_to_real test_components_are_judged_apart. Both fail on the pass before this commit. The histc, polar and complex scalar graph tests also ask that every op the pass emits has an Inductor lowering (they name clamp). On the npu (run/tc-solo, PTB main defa86b): complex, histc, polar, topk and grouped_mm pass, and their 27 wrappers hold no call left to aten. --- pytorchsim/frontend/rewrite_fx_graph.py | 179 ++++++++++++++++-------- tests/ops/misc/test_complex_to_real.py | 31 ++++ tests/ops/misc/test_histc.py | 40 ++++-- tests/ops/misc/test_polar.py | 9 ++ 4 files changed, 191 insertions(+), 68 deletions(-) diff --git a/pytorchsim/frontend/rewrite_fx_graph.py b/pytorchsim/frontend/rewrite_fx_graph.py index bc523726b..06e1ba23f 100644 --- a/pytorchsim/frontend/rewrite_fx_graph.py +++ b/pytorchsim/frontend/rewrite_fx_graph.py @@ -16,6 +16,8 @@ logger = config.setup_logger() +_KEPT_META = ("original_aten", "stack_trace", "nn_module_stack", "source_fn_stack", "seq_nr", "from_node") + def _val(node): """The fake value of a node, or the argument itself when it is not a node.""" @@ -37,11 +39,9 @@ def _fake_mode(graph): return None -def _emitter(graph): - """call(target, *args, **kwargs): a node at the graph's insert point with its fake value set, since - nothing after the device pass sets it.""" - fake_mode = _fake_mode(graph) - +def _emitter(graph, fake_mode, origin): + """call(target, *args, **kwargs): a node at the insert point with its fake value set (nothing after the + device pass sets it) and origin's provenance (_KEPT_META), origin being the node it rewrites.""" def unwrap(a): if isinstance(a, (list, tuple)): return type(a)(unwrap(x) for x in a) @@ -51,6 +51,9 @@ def unwrap(a): def call(target, *args, **kwargs): node = graph.call_function(target, args, kwargs) + for key in _KEPT_META: + if key in origin.meta: + node.meta[key] = origin.meta[key] if fake_mode is not None: with fake_mode: node.meta["val"] = target(*unwrap(args), **unwrap(kwargs)) @@ -65,46 +68,72 @@ def _join(call, re, im): call(aten.unsqueeze.default, im, -1)], -1) -def rewrite_aten_histc(graph) -> None: - """histc of an integral tensor whose bins are its values (bins N, min 0, max N-1) as one compare and one - count in the input's dtype; other integral edges count at float32 and cast back, an extern call, logged.""" - call = _emitter(graph) +def _emit_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) + 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_histc(graph, fake_mode) -> int: + """Every aten.histc as a count on the device (_emit_histc); one without a fake value is left to aten, + logged. Returns how many were rewritten.""" + changed = 0 for node in list(graph.nodes): if node.op != "call_function" or node.target is not aten.histc.default: continue x = node.args[0] xv = _val(x) + if xv is None: + logger.info("[rewrite_fx_graph] histc without a fake value: left to aten") + continue said = dict(zip(("bins", "min", "max"), node.args[1:]), **node.kwargs) bins, lo, hi = int(said.get("bins", 100)), said.get("min", 0), said.get("max", 0) - if xv is None or xv.is_floating_point(): - logger.info("[rewrite_fx_graph] histc %s: left to aten (no npu kernel)", - None if xv is None else xv.dtype) - continue with graph.inserting_before(node): - if lo == 0 and hi == bins - 1: - seats = call(prims.iota.default, bins, start=0, step=1, dtype=xv.dtype, - device=xv.device, requires_grad=False) - hits = call(aten.eq.Tensor, call(aten.reshape.default, x, [-1, 1]), - call(aten.reshape.default, seats, [1, -1])) - out = call(prims.convert_element_type.default, - call(aten.sum.dim_IntList, hits, [0]), xv.dtype) - else: - logger.info("[rewrite_fx_graph] histc %s bins %d [%s, %s]: an extern call at float32", - xv.dtype, bins, lo, hi) - xf = call(prims.convert_element_type.default, x, torch.float32) - out = call(prims.convert_element_type.default, - call(aten.histc.default, xf, bins, lo, hi), xv.dtype) + out = _emit_histc(_emitter(graph, fake_mode, node), x, xv, bins, lo, hi) node.replace_all_uses_with(out) graph.erase_node(node) + changed += 1 + return changed -def rewrite_aten_polar(graph) -> None: +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.""" - call = _emitter(graph) + changed = 0 for node in list(graph.nodes): if node.op != "call_function" or node.target is not aten.polar.default: continue + call = _emitter(graph, fake_mode, node) r, angle = node.args[0], node.args[1] with graph.inserting_before(node): pair = _join(call, call(aten.mul.Tensor, r, call(aten.cos.default, angle)), @@ -112,6 +141,8 @@ def rewrite_aten_polar(graph) -> None: out = call(aten.view_as_complex.default, pair) node.replace_all_uses_with(out) graph.erase_node(node) + changed += 1 + return changed def _row_times_matrix(node): @@ -130,14 +161,15 @@ def _row_times_matrix(node): return a, b, bias -def rewrite_aten_mm_addmm_row(graph) -> None: +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.""" - call = _emitter(graph) + changed = 0 for node in list(graph.nodes): found = _row_times_matrix(node) if found is None: continue + call = _emitter(graph, fake_mode, node) a, b, bias = found k = int(_val(a).shape[1]) with graph.inserting_before(node): @@ -147,6 +179,8 @@ def rewrite_aten_mm_addmm_row(graph) -> None: out = call(aten.add.Tensor, out, bias) node.replace_all_uses_with(out) graph.erase_node(node) + changed += 1 + return changed _MUL = (aten.mul.Tensor, aten.mul.Scalar) @@ -154,32 +188,46 @@ def rewrite_aten_mm_addmm_row(graph) -> None: _HANDLED = (aten.view_as_complex.default,) + _MUL + _SHAPE -def rewrite_aten_view_as_complex(graph) -> None: - """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. - """ - 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 +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: an op outside _HANDLED, a complex value leaving the + graph, or one read by an op outside _HANDLED and view_as_real.""" + for n in component: + if n.op != "call_function" or n.target not in _HANDLED: + return f"{n.op} {n.target}" 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 + return f"{n.target}'s complex value leaves the graph" + if user.target is not aten.view_as_real.default and user.target not in _HANDLED: + return f"{user.target} reads {n.target}'s complex value" + return None + - call = _emitter(graph) +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 complex_nodes: + for n in component: + call = _emitter(graph, fake_mode, n) with graph.inserting_before(n): if n.target is aten.view_as_complex.default: pair[n] = n.args[0] @@ -212,25 +260,38 @@ def rewrite_aten_view_as_complex(graph) -> None: other = call(aten.unsqueeze.default, other, -1) pair[n] = call(aten.mul.Tensor, pair[cx], other) - for n in complex_nodes: + 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]) - graph.eliminate_dead_code() + +def rewrite_aten_view_as_complex(graph, fake_mode) -> int: + """Each component of complex values (view_as_complex, mul, unsqueeze) becomes real [..., 2] pairs; a + component with any other complex op 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("[rewrite_fx_graph] %d complex nodes left to aten: %s", len(component), why) + continue + _to_real_pairs(graph, fake_mode, component) + changed += 1 + return changed REWRITES = (rewrite_aten_histc, rewrite_aten_polar, rewrite_aten_mm_addmm_row, rewrite_aten_view_as_complex) class _npu_post_grad_pass(CustomGraphModulePass): - """REWRITES in order on an npu graph; its uuid hashes this file, so an edit here is a new cache key.""" + """REWRITES in 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: - for rewrite in REWRITES: - rewrite(gm.graph) - gm.graph.eliminate_dead_code() - gm.recompile() + fake_mode = _fake_mode(gm.graph) + if sum(rewrite(gm.graph, fake_mode) for rewrite in REWRITES): + gm.graph.eliminate_dead_code() + gm.recompile() def uuid(self): return get_hash_for_files((__file__,)) diff --git a/tests/ops/misc/test_complex_to_real.py b/tests/ops/misc/test_complex_to_real.py index 958f2fa9e..dd862f19f 100644 --- a/tests/ops/misc/test_complex_to_real.py +++ b/tests/ops/misc/test_complex_to_real.py @@ -29,6 +29,14 @@ def _trace(fn, *args): 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 + emits must lower as they are.""" + from torch._inductor.lowering import lowerings + return sorted({str(m.target) for m in gm.graph.nodes if m.op == "call_function" + and m.target not in lowerings and m.target.overloadpacket not in lowerings}) + + def _complex_nodes(graph): out = [] for n in graph.nodes: @@ -83,9 +91,31 @@ def f(x): 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, and every + node it makes keeps the provenance of the node it replaces.""" + 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}" + npu_post_grad_pass(gm) + 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 n.op == "call_function" 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_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 @@ -107,5 +137,6 @@ def f(x): device = torch.device("npu:0") test_pass_leaves_no_complex() test_complex_scalar_multiply() + test_components_are_judged_apart() test_unhandled_op_is_left_alone() test_rope_on_device(device) diff --git a/tests/ops/misc/test_histc.py b/tests/ops/misc/test_histc.py index 0429779df..1641154f5 100644 --- a/tests/ops/misc/test_histc.py +++ b/tests/ops/misc/test_histc.py @@ -48,7 +48,7 @@ def test_histc_integral(device, n=64, bins=8): def test_histc_float_unchanged(device, n=64, bins=8): - """A floating histc keeps aten's kernel: the device pass leaves it and logs why.""" + """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) @@ -60,6 +60,14 @@ 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 + emits must lower as they are.""" + from torch._inductor.lowering import lowerings + return sorted({str(m.target) for m in gm.graph.nodes if m.op == "call_function" + 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.""" @@ -74,17 +82,31 @@ def _histc_graph(x, bins, lo, hi): return fx.GraphModule(torch.nn.Module(), g) -def test_pass_counts_on_the_device(n=64, bins=8): - """The device pass alone, on a traced integral histc: bins that are the values leave no aten.histc; - other edges keep one, at float32, and both count what the CPU counts.""" +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) - x = torch.randint(0, bins, (n,), generator=g).to(torch.int32) - for lo, hi, left in ((0, bins - 1, 0), (0, 2 * bins - 1, 1)): + 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) npu_post_grad_pass(gm) - histcs = [n for n in gm.graph.nodes if n.target is aten.histc.default] - assert len(histcs) == left, f"[{lo}, {hi}]: {len(histcs)} aten.histc left, expected {left}" - test_result(f"histc pass [{lo}, {hi}]", gm(x), torch.histc(x.float(), bins, lo, hi).to(x.dtype)) + 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()}") if __name__ == "__main__": diff --git a/tests/ops/misc/test_polar.py b/tests/ops/misc/test_polar.py index b1bae5ca6..8725728af 100644 --- a/tests/ops/misc/test_polar.py +++ b/tests/ops/misc/test_polar.py @@ -53,6 +53,14 @@ 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 + emits must lower as they are.""" + from torch._inductor.lowering import lowerings + return sorted({str(m.target) for m in gm.graph.nodes if m.op == "call_function" + 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.""" @@ -63,6 +71,7 @@ def test_pass_leaves_no_polar(n=32): 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)) From fd5761347f407943a5b4caaf79f35af858066f69 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 23 Oct 2026 01:00:12 +0900 Subject: [PATCH 07/12] [Frontend] npu_post_grad_pass leaves from_node to Inductor, rewrites real GEMVs only, and refuses a histc range aten refuses Three faults a second review of rewrite_fx_graph found, each with a test that fails on the commit before this one: _emitter copied the rewritten node's from_node list onto every node it made. Inductor's GraphTransformObserver writes from_node itself (CREATE when the pass makes a node, REPLACE on replace_all_uses_with), so the copy overwrote that record and put one list object on many nodes. from_node is no longer copied. _row_times_matrix took any dtype: a complex 1 x K mm became a complex mul and sum, which the complex rewrite then refuses (sum has no real-pair form), two calls left to aten instead of one. It takes real floating operands only. An integral histc whose edges truncate to one value (min 0.2, max 0.8) divided by a width of zero, and a range with max below min counted nothing; aten refuses both with "max must be larger than min". The pass now raises that at compile time, where the edges are known. Left as it is: with min == max the range comes from the data, and data holding NaN or inf gives zero counts where aten raises "range is not finite"; raising there needs an assert op in the graph, not done here. Tests: test_complex_to_real test_components_are_judged_apart (no from_node copied onto a new node), test_row_mm_stays_real; test_histc test_pass_counts_on_the_device (both ranges refused). On the npu (run/tc-solo): complex, histc and polar pass with no call left to aten. --- pytorchsim/frontend/rewrite_fx_graph.py | 8 ++++++-- tests/ops/misc/test_complex_to_real.py | 22 ++++++++++++++++++++-- tests/ops/misc/test_histc.py | 8 ++++++++ 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/pytorchsim/frontend/rewrite_fx_graph.py b/pytorchsim/frontend/rewrite_fx_graph.py index 06e1ba23f..54e286c86 100644 --- a/pytorchsim/frontend/rewrite_fx_graph.py +++ b/pytorchsim/frontend/rewrite_fx_graph.py @@ -16,7 +16,7 @@ logger = config.setup_logger() -_KEPT_META = ("original_aten", "stack_trace", "nn_module_stack", "source_fn_stack", "seq_nr", "from_node") +_KEPT_META = ("original_aten", "stack_trace", "nn_module_stack", "source_fn_stack", "seq_nr") def _val(node): @@ -85,6 +85,8 @@ def _emit_histc(call, x, xv, bins, 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: @@ -146,7 +148,7 @@ def rewrite_aten_polar(graph, fake_mode) -> int: def _row_times_matrix(node): - """(a, b, bias) of an mm or a plain addmm whose left operand is one row, else None.""" + """(a, b, bias) of an mm or a plain addmm of real floating operands whose left one is a row, else None.""" if node.op != "call_function": return None if node.target is aten.mm.default: @@ -158,6 +160,8 @@ def _row_times_matrix(node): 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 diff --git a/tests/ops/misc/test_complex_to_real.py b/tests/ops/misc/test_complex_to_real.py index dd862f19f..0df2ff8f1 100644 --- a/tests/ops/misc/test_complex_to_real.py +++ b/tests/ops/misc/test_complex_to_real.py @@ -96,8 +96,8 @@ def f(x): def test_components_are_judged_apart(): - """A component the pass cannot say in real arithmetic leaves a separate one it can rewritten, and every - node it makes keeps the provenance of the node it replaces.""" + """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 from_node is left to Inductor's observer.""" 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))) @@ -107,7 +107,11 @@ def f(x, y): 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} npu_post_grad_pass(gm) + copied = [n.name for n in gm.graph.nodes if n.name not in before and "from_node" in n.meta] + assert not copied, f"from_node copied onto new nodes: {copied}" 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 n.op == "call_function" and "stack_trace" not in n.meta] @@ -116,6 +120,19 @@ def f(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) + npu_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 @@ -138,5 +155,6 @@ def f(x): 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_histc.py b/tests/ops/misc/test_histc.py index 1641154f5..ad24d5cca 100644 --- a/tests/ops/misc/test_histc.py +++ b/tests/ops/misc/test_histc.py @@ -107,6 +107,14 @@ def test_pass_counts_on_the_device(n=64): 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: + npu_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__": From 14a57d28c228c109790d49f9b16d7a446a8f0258 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 23 Oct 2026 10:34:45 +0900 Subject: [PATCH 08/12] [Frontend] rewrite_fx_graph.py is post_grad_pass.py: pytorchsim_post_grad_pass on top, its rewrites below in run order The file is one thing now: the device_custom_pass Inductor runs on npu graphs after its own post-grad passes, renamed pytorchsim_post_grad_pass (was npu_post_grad_pass: npu names the device, not whose pass it is). It is named for that, after Inductor's fx_passes/post_grad.py, beside attention.py, grouped_mm.py and topk.py, which are named for what they take. The pass class opens the file and its __call__ names the four rewrites in the order they run (histc, polar, a row times a matrix, complex values), replacing the REWRITES tuple; each rewrite follows in that order with the helpers only it uses, and the shared ones (_inserter, _join, _val, _is_complex, _fake_mode) close the file. _emitter and _emit_histc are _inserter and _insert_histc: they insert FX nodes, FX's word (graph.inserting_before, graph.call_function); emit is codegen's. Besides those two names, only __call__ and the class docstring changed; every other line moved. The log prefix is [post_grad_pass]. References follow: torch_openreg's registration, the three tests that import the pass, comments naming the file in test_histc, test_polar, test_eager_to_compile_recursion, test_deepseek_v3_base and test_llama4, and .claude/CLAUDE.md, whose histc sentence (still an extern call) was wrong since the commit before last. Graph tests (7) pass; on the npu (run/tc-solo) complex, histc and polar pass with no call left to aten. --- .claude/CLAUDE.md | 18 +- device/torch_openreg/__init__.py | 4 +- ...{rewrite_fx_graph.py => post_grad_pass.py} | 223 +++++++++--------- .../models/DeepSeek/test_deepseek_v3_base.py | 2 +- tests/models/Llama/test_llama4.py | 2 +- tests/ops/misc/test_complex_to_real.py | 14 +- .../misc/test_eager_to_compile_recursion.py | 2 +- tests/ops/misc/test_histc.py | 10 +- tests/ops/misc/test_polar.py | 8 +- 9 files changed, 142 insertions(+), 141 deletions(-) rename pytorchsim/frontend/{rewrite_fx_graph.py => post_grad_pass.py} (88%) 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/device/torch_openreg/__init__.py b/device/torch_openreg/__init__.py index 3dcf6b1b1..038898662 100644 --- a/device/torch_openreg/__init__.py +++ b/device/torch_openreg/__init__.py @@ -19,7 +19,7 @@ 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 _inductor_patches.install() @@ -31,7 +31,7 @@ "npu", TritonNPUScheduling, TritonNPUWrapperCodegen, - device_custom_pass=_rewrite_fx_graph.npu_post_grad_pass, + device_custom_pass=_post_grad_pass.pytorchsim_post_grad_pass, ) torch_openreg.openreg.init() diff --git a/pytorchsim/frontend/rewrite_fx_graph.py b/pytorchsim/frontend/post_grad_pass.py similarity index 88% rename from pytorchsim/frontend/rewrite_fx_graph.py rename to pytorchsim/frontend/post_grad_pass.py index 54e286c86..5e0eb4459 100644 --- a/pytorchsim/frontend/rewrite_fx_graph.py +++ b/pytorchsim/frontend/post_grad_pass.py @@ -1,6 +1,6 @@ -"""Our rewrites of the FX graph, so ops with no npu kernel stay on the device. +"""The npu's post-grad pass: rewrites that keep ops with no npu kernel on the device. -npu_post_grad_pass is the device_custom_pass Inductor runs on npu graphs only, after its post-grad +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. """ @@ -19,56 +19,50 @@ _KEPT_META = ("original_aten", "stack_trace", "nn_module_stack", "source_fn_stack", "seq_nr") -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 _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 _emitter(graph, fake_mode, origin): - """call(target, *args, **kwargs): a node at the insert point with its fake value set (nothing after the - device pass sets it) and origin's provenance (_KEPT_META), origin being the node it rewrites.""" - 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) + def uuid(self): + return get_hash_for_files((__file__,)) - def call(target, *args, **kwargs): - node = graph.call_function(target, args, kwargs) - for key in _KEPT_META: - if key in origin.meta: - node.meta[key] = origin.meta[key] - if fake_mode is not None: - with fake_mode: - node.meta["val"] = target(*unwrap(args), **unwrap(kwargs)) - return node - return call +pytorchsim_post_grad_pass = _pytorchsim_post_grad_pass() -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 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.""" + changed = 0 + for node in list(graph.nodes): + if node.op != "call_function" or node.target is not aten.histc.default: + continue + x = node.args[0] + xv = _val(x) + if xv is None: + logger.info("[post_grad_pass] histc without a fake value: left to aten") + continue + said = dict(zip(("bins", "min", "max"), node.args[1:]), **node.kwargs) + bins, lo, hi = int(said.get("bins", 100)), said.get("min", 0), said.get("max", 0) + with graph.inserting_before(node): + out = _insert_histc(_inserter(graph, fake_mode, node), x, xv, bins, lo, hi) + node.replace_all_uses_with(out) + graph.erase_node(node) + changed += 1 + return changed -def _emit_histc(call, x, xv, bins, lo, hi): +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() @@ -106,28 +100,6 @@ def _emit_histc(call, x, xv, bins, lo, hi): return call(prims.convert_element_type.default, call(aten.sum.dim_IntList, hits, [0]), xv.dtype) -def rewrite_aten_histc(graph, fake_mode) -> int: - """Every aten.histc as a count on the device (_emit_histc); one without a fake value is left to aten, - logged. Returns how many were rewritten.""" - changed = 0 - for node in list(graph.nodes): - if node.op != "call_function" or node.target is not aten.histc.default: - continue - x = node.args[0] - xv = _val(x) - if xv is None: - logger.info("[rewrite_fx_graph] histc without a fake value: left to aten") - continue - said = dict(zip(("bins", "min", "max"), node.args[1:]), **node.kwargs) - bins, lo, hi = int(said.get("bins", 100)), said.get("min", 0), said.get("max", 0) - with graph.inserting_before(node): - out = _emit_histc(_emitter(graph, fake_mode, node), x, xv, bins, lo, hi) - node.replace_all_uses_with(out) - graph.erase_node(node) - changed += 1 - return changed - - 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.""" @@ -135,7 +107,7 @@ def rewrite_aten_polar(graph, fake_mode) -> int: for node in list(graph.nodes): if node.op != "call_function" or node.target is not aten.polar.default: continue - call = _emitter(graph, fake_mode, node) + call = _inserter(graph, fake_mode, node) r, angle = node.args[0], node.args[1] with graph.inserting_before(node): pair = _join(call, call(aten.mul.Tensor, r, call(aten.cos.default, angle)), @@ -147,24 +119,6 @@ def rewrite_aten_polar(graph, fake_mode) -> int: return changed -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.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 - if not (av.is_floating_point() and bv.is_floating_point()): - return None - return a, b, bias - - 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.""" @@ -173,7 +127,7 @@ def rewrite_aten_mm_addmm_row(graph, fake_mode) -> int: found = _row_times_matrix(node) if found is None: continue - call = _emitter(graph, fake_mode, node) + call = _inserter(graph, fake_mode, node) a, b, bias = found k = int(_val(a).shape[1]) with graph.inserting_before(node): @@ -187,11 +141,43 @@ def rewrite_aten_mm_addmm_row(graph, fake_mode) -> int: return changed +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.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 + if not (av.is_floating_point() and bv.is_floating_point()): + return None + return a, b, bias + + _MUL = (aten.mul.Tensor, aten.mul.Scalar) _SHAPE = (aten.unsqueeze.default,) _HANDLED = (aten.view_as_complex.default,) + _MUL + _SHAPE +def rewrite_aten_view_as_complex(graph, fake_mode) -> int: + """Each component of complex values (view_as_complex, mul, unsqueeze) becomes real [..., 2] pairs; a + component with any other complex op 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} @@ -231,7 +217,7 @@ def _to_real_pairs(graph, fake_mode, component): it reads the pair.""" pair = {} for n in component: - call = _emitter(graph, fake_mode, n) + call = _inserter(graph, fake_mode, n) with graph.inserting_before(n): if n.target is aten.view_as_complex.default: pair[n] = n.args[0] @@ -270,35 +256,50 @@ def _to_real_pairs(graph, fake_mode, component): user.replace_all_uses_with(pair[n]) -def rewrite_aten_view_as_complex(graph, fake_mode) -> int: - """Each component of complex values (view_as_complex, mul, unsqueeze) becomes real [..., 2] pairs; a - component with any other complex op 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("[rewrite_fx_graph] %d complex nodes left to aten: %s", len(component), why) - continue - _to_real_pairs(graph, fake_mode, component) - changed += 1 - return changed +def _inserter(graph, fake_mode, origin): + """call(target, *args, **kwargs): a node at the insert point with its fake value set (nothing after the + device pass sets it) and origin's provenance (_KEPT_META), origin being the node it rewrites.""" + 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) + def call(target, *args, **kwargs): + node = graph.call_function(target, args, kwargs) + for key in _KEPT_META: + if key in origin.meta: + node.meta[key] = origin.meta[key] + if fake_mode is not None: + with fake_mode: + node.meta["val"] = target(*unwrap(args), **unwrap(kwargs)) + return node -REWRITES = (rewrite_aten_histc, rewrite_aten_polar, rewrite_aten_mm_addmm_row, rewrite_aten_view_as_complex) + return call -class _npu_post_grad_pass(CustomGraphModulePass): - """REWRITES in 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 _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 __call__(self, gm: fx.GraphModule) -> None: - fake_mode = _fake_mode(gm.graph) - if sum(rewrite(gm.graph, fake_mode) for rewrite in REWRITES): - gm.graph.eliminate_dead_code() - gm.recompile() - def uuid(self): - return get_hash_for_files((__file__,)) +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() -npu_post_grad_pass = _npu_post_grad_pass() +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/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/misc/test_complex_to_real.py b/tests/ops/misc/test_complex_to_real.py index 0df2ff8f1..1553bb426 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 npu_post_grad_pass +from pytorchsim.frontend.post_grad_pass import pytorchsim_post_grad_pass aten = torch.ops.aten @@ -31,7 +31,7 @@ def _trace(fn, *args): def _unlowered(gm): """The ops of gm Inductor has no lowering for; the device pass runs after decomposition, so any it - emits must lower as they are.""" + inserts must lower as they are.""" from torch._inductor.lowering import lowerings return sorted({str(m.target) for m in gm.graph.nodes if m.op == "call_function" and m.target not in lowerings and m.target.overloadpacket not in lowerings}) @@ -57,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" - npu_post_grad_pass(gm) + pytorchsim_post_grad_pass(gm) gm.recompile() after = _complex_nodes(gm.graph) @@ -87,7 +87,7 @@ def f(x): x = torch.randn(1, 32, 64) gm = _trace(f, x) - npu_post_grad_pass(gm) + 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]}" @@ -109,7 +109,7 @@ def f(x, y): n.meta["stack_trace"] = f"user.py:{n.name}" n.meta["from_node"] = [n.name] before = {n.name for n in gm.graph.nodes} - npu_post_grad_pass(gm) + pytorchsim_post_grad_pass(gm) copied = [n.name for n in gm.graph.nodes if n.name not in before and "from_node" in n.meta] assert not copied, f"from_node copied onto new nodes: {copied}" left = sorted(str(n.target) for n in _complex_nodes(gm.graph)) @@ -127,7 +127,7 @@ def f(a, b): a, b = torch.randn(1, 8, 2), torch.randn(8, 4, 2) gm = _trace(f, a, b) - npu_post_grad_pass(gm) + 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)) @@ -144,7 +144,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)] - npu_post_grad_pass(gm) + 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) 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 ad24d5cca..a56df439a 100644 --- a/tests/ops/misc/test_histc.py +++ b/tests/ops/misc/test_histc.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 npu_post_grad_pass +from pytorchsim.frontend.post_grad_pass import pytorchsim_post_grad_pass aten = torch.ops.aten @@ -28,7 +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; rewrite_fx_graph.rewrite_aten_histc counts it on the device. + # 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 @@ -62,7 +62,7 @@ def test_histc_float_unchanged(device, n=64, bins=8): def _unlowered(gm): """The ops of gm Inductor has no lowering for; the device pass runs after decomposition, so any it - emits must lower as they are.""" + inserts must lower as they are.""" from torch._inductor.lowering import lowerings return sorted({str(m.target) for m in gm.graph.nodes if m.op == "call_function" and m.target not in lowerings and m.target.overloadpacket not in lowerings}) @@ -99,7 +99,7 @@ def test_pass_counts_on_the_device(n=64): ) for name, x, bins, lo, hi in cases: gm = _histc_graph(x, bins, lo, hi) - npu_post_grad_pass(gm) + 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)}" @@ -110,7 +110,7 @@ def test_pass_counts_on_the_device(n=64): 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: - npu_post_grad_pass(_histc_graph(x, 4, lo, hi)) + 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: diff --git a/tests/ops/misc/test_polar.py b/tests/ops/misc/test_polar.py index 8725728af..bcffc9bb7 100644 --- a/tests/ops/misc/test_polar.py +++ b/tests/ops/misc/test_polar.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 npu_post_grad_pass +from pytorchsim.frontend.post_grad_pass import pytorchsim_post_grad_pass def _rope_like(a): @@ -30,7 +30,7 @@ def test_polar_on_transposed(device, n=32): # 'torch.ops.aten.polar.default') # AssertionError: expected size 32==32, stride 32==1 at dim=1 # - # rewrite_fx_graph.rewrite_aten_polar takes the extern call out instead + # 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) @@ -55,7 +55,7 @@ def f(a): def _unlowered(gm): """The ops of gm Inductor has no lowering for; the device pass runs after decomposition, so any it - emits must lower as they are.""" + inserts must lower as they are.""" from torch._inductor.lowering import lowerings return sorted({str(m.target) for m in gm.graph.nodes if m.op == "call_function" and m.target not in lowerings and m.target.overloadpacket not in lowerings}) @@ -66,7 +66,7 @@ def test_pass_leaves_no_polar(n=32): 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) - npu_post_grad_pass(gm) + 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())] From 18140e7f40fd59d1bb45aeabd176b2f5514bc617 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 23 Oct 2026 10:46:05 +0900 Subject: [PATCH 09/12] [Frontend] post_grad_pass makes its nodes through FX's tracer, so FX decides what meta they keep _inserter made each node with graph.call_function and copied a list of meta keys of our own (_KEPT_META: original_aten, stack_trace, nn_module_stack, source_fn_stack, seq_nr) from the node it rewrites. That list restated what torch.fx already decides (torch.fx.proxy._COPY_META_FIELDS plus stack_trace, the fields Inductor's own pattern matcher transfers) and would not follow it. It now makes the node with torch.fx.proxy.GraphAppendingTracer.create_node inside torch.fx.traceback.preserve_node_meta() and set_current_meta(origin), FX's public path: FX copies the rewritten node's provenance fields and stack trace, and records from_node as a fresh [NodeSource(origin, CREATE)]. The node still goes to the graph's insert point; _inserter still sets its fake value. _KEPT_META is gone. No pass name of our own goes in from_node: Inductor runs the pass as custom_backend_passes_npu and its observer names it so. set_current_meta is in torch.fx.traceback's __all__ but marked not backward compatible. test_complex_to_real test_components_are_judged_apart asks that every node the pass makes names the node it replaces in from_node; it fails on the copy loop (from_node []). Graph tests (7) pass; on the npu (run/tc-solo, PTB pinned at defa86b in its own clone) complex, histc and polar pass with no call left to aten, and their kernels are named for the op they came from (fused_histc_*, fused_..._polar_*, fused_mul_*). --- pytorchsim/frontend/post_grad_pass.py | 15 +++++++-------- tests/ops/misc/test_complex_to_real.py | 10 +++++++--- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/pytorchsim/frontend/post_grad_pass.py b/pytorchsim/frontend/post_grad_pass.py index 5e0eb4459..420545ce1 100644 --- a/pytorchsim/frontend/post_grad_pass.py +++ b/pytorchsim/frontend/post_grad_pass.py @@ -7,6 +7,7 @@ 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 @@ -16,8 +17,6 @@ logger = config.setup_logger() -_KEPT_META = ("original_aten", "stack_trace", "nn_module_stack", "source_fn_stack", "seq_nr") - 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 @@ -257,8 +256,8 @@ def _to_real_pairs(graph, fake_mode, component): def _inserter(graph, fake_mode, origin): - """call(target, *args, **kwargs): a node at the insert point with its fake value set (nothing after the - device pass sets it) and origin's provenance (_KEPT_META), origin being the node it rewrites.""" + """call(target, *args, **kwargs): a node at the insert point, 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) @@ -266,11 +265,11 @@ def unwrap(a): return {k: unwrap(v) for k, v in a.items()} return _val(a) + tracer = fx.proxy.GraphAppendingTracer(graph) + def call(target, *args, **kwargs): - node = graph.call_function(target, args, kwargs) - for key in _KEPT_META: - if key in origin.meta: - node.meta[key] = origin.meta[key] + with 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)) diff --git a/tests/ops/misc/test_complex_to_real.py b/tests/ops/misc/test_complex_to_real.py index 1553bb426..6f4fa9ebc 100644 --- a/tests/ops/misc/test_complex_to_real.py +++ b/tests/ops/misc/test_complex_to_real.py @@ -97,7 +97,7 @@ def 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 from_node is left to Inductor's observer.""" + 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))) @@ -110,8 +110,12 @@ def f(x, y): n.meta["from_node"] = [n.name] before = {n.name for n in gm.graph.nodes} pytorchsim_post_grad_pass(gm) - copied = [n.name for n in gm.graph.nodes if n.name not in before and "from_node" in n.meta] - assert not copied, f"from_node copied onto new nodes: {copied}" + 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 n.op == "call_function" and "stack_trace" not in n.meta] From b96db3924650907b869913a749968fff7e81f0ad Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 23 Oct 2026 10:53:24 +0900 Subject: [PATCH 10/12] [Frontend] post_grad_pass finds its nodes with Graph.find_nodes and judges them by target, not by op strings Each rewrite walked every node and compared node.op with "call_function" before its target. histc and polar now iterate graph.find_nodes(op="call_function", target=...), FX's indexed lookup and the one Inductor's own post-grad passes use; it returns the matches in graph order as a list, so erasing as it goes is safe. The GEMV rewrite finds mm and addmm the same way, and _row_times_matrix no longer checks the op. _why_not_real compared n.op with "call_function" and user.op with "output". A placeholder's, an attribute's and the output's target is a string, never in _HANDLED and never view_as_real, so the target test alone refuses them; the two op tests are gone, and the reason names the node's kind and name ("placeholder z_1", "output output reads mul's complex value", "call_function exp reads view_as_complex's complex value"). The graph tests pick call_function nodes by callable(node.target) instead of node.op. Graph tests (7) pass; on the npu (run/tc-solo) complex, histc and polar pass with no call left to aten. --- pytorchsim/frontend/post_grad_pass.py | 25 +++++++++---------------- tests/ops/misc/test_complex_to_real.py | 4 ++-- tests/ops/misc/test_histc.py | 2 +- tests/ops/misc/test_polar.py | 2 +- 4 files changed, 13 insertions(+), 20 deletions(-) diff --git a/pytorchsim/frontend/post_grad_pass.py b/pytorchsim/frontend/post_grad_pass.py index 420545ce1..12511645f 100644 --- a/pytorchsim/frontend/post_grad_pass.py +++ b/pytorchsim/frontend/post_grad_pass.py @@ -43,9 +43,7 @@ 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.""" changed = 0 - for node in list(graph.nodes): - if node.op != "call_function" or node.target is not aten.histc.default: - continue + for node in graph.find_nodes(op="call_function", target=aten.histc.default): x = node.args[0] xv = _val(x) if xv is None: @@ -103,9 +101,7 @@ 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.""" changed = 0 - for node in list(graph.nodes): - if node.op != "call_function" or node.target is not aten.polar.default: - continue + for node in graph.find_nodes(op="call_function", target=aten.polar.default): call = _inserter(graph, fake_mode, node) r, angle = node.args[0], node.args[1] with graph.inserting_before(node): @@ -122,7 +118,8 @@ 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.""" changed = 0 - for node in list(graph.nodes): + for node in (graph.find_nodes(op="call_function", target=aten.mm.default) + + graph.find_nodes(op="call_function", target=aten.addmm.default)): found = _row_times_matrix(node) if found is None: continue @@ -142,11 +139,9 @@ def rewrite_aten_mm_addmm_row(graph, fake_mode) -> int: 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.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: + elif not node.kwargs: bias, a, b = node.args else: return None @@ -198,16 +193,14 @@ def root(n): def _why_not_real(component): - """Why the component has no real-pair form, or None: an op outside _HANDLED, a complex value leaving the - graph, or one read by an op outside _HANDLED and view_as_real.""" + """Why the component has no real-pair form, or None: a node outside _HANDLED (a placeholder or attribute + among them), or a complex value read by anything but _HANDLED and view_as_real (the graph's output too).""" for n in component: - if n.op != "call_function" or n.target not in _HANDLED: + if n.target not in _HANDLED: return f"{n.op} {n.target}" for user in n.users: - if user.op == "output": - return f"{n.target}'s complex value leaves the graph" if user.target is not aten.view_as_real.default and user.target not in _HANDLED: - return f"{user.target} reads {n.target}'s complex value" + return f"{user.op} {user.name} reads {n.name}'s complex value" return None diff --git a/tests/ops/misc/test_complex_to_real.py b/tests/ops/misc/test_complex_to_real.py index 6f4fa9ebc..14fdeddaa 100644 --- a/tests/ops/misc/test_complex_to_real.py +++ b/tests/ops/misc/test_complex_to_real.py @@ -33,7 +33,7 @@ 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 m.op == "call_function" + 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}) @@ -118,7 +118,7 @@ def f(x, y): 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 n.op == "call_function" and "stack_trace" not in n.meta] + 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]) diff --git a/tests/ops/misc/test_histc.py b/tests/ops/misc/test_histc.py index a56df439a..1aef2190d 100644 --- a/tests/ops/misc/test_histc.py +++ b/tests/ops/misc/test_histc.py @@ -64,7 +64,7 @@ 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 m.op == "call_function" + 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}) diff --git a/tests/ops/misc/test_polar.py b/tests/ops/misc/test_polar.py index bcffc9bb7..5e87aff8f 100644 --- a/tests/ops/misc/test_polar.py +++ b/tests/ops/misc/test_polar.py @@ -57,7 +57,7 @@ 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 m.op == "call_function" + 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}) From 45b5db7c02728917eec1a8e38e1a823a1226d9dc Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 23 Oct 2026 10:57:23 +0900 Subject: [PATCH 11/12] [Frontend] post_grad_pass replaces nodes in one place: each rewrite is a build function histc, polar and the GEMV rewrite each repeated the same loop: find the nodes, open graph.inserting_before, build the value, replace the node's uses, erase it, count. _replace(graph, fake_mode, nodes, build) is that loop once; a rewrite gives it the nodes (find_nodes) and build(call, node), which returns the replacement or None to leave the node. _inserter now places each node just before its origin itself, so neither the rewrites nor _to_real_pairs open an insert point. No behaviour change. Graph tests (7) pass; on the npu (run/tc-solo) complex, histc and polar pass with no call left to aten. --- pytorchsim/frontend/post_grad_pass.py | 128 +++++++++++--------------- 1 file changed, 56 insertions(+), 72 deletions(-) diff --git a/pytorchsim/frontend/post_grad_pass.py b/pytorchsim/frontend/post_grad_pass.py index 12511645f..ffb795bac 100644 --- a/pytorchsim/frontend/post_grad_pass.py +++ b/pytorchsim/frontend/post_grad_pass.py @@ -42,21 +42,14 @@ def uuid(self): 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.""" - changed = 0 - for node in graph.find_nodes(op="call_function", target=aten.histc.default): + def build(call, node): x = node.args[0] - xv = _val(x) - if xv is None: + if _val(x) is None: logger.info("[post_grad_pass] histc without a fake value: left to aten") - continue + return None said = dict(zip(("bins", "min", "max"), node.args[1:]), **node.kwargs) - bins, lo, hi = int(said.get("bins", 100)), said.get("min", 0), said.get("max", 0) - with graph.inserting_before(node): - out = _insert_histc(_inserter(graph, fake_mode, node), x, xv, bins, lo, hi) - node.replace_all_uses_with(out) - graph.erase_node(node) - changed += 1 - return changed + 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): @@ -100,41 +93,27 @@ def _insert_histc(call, x, xv, bins, lo, hi): 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.""" - changed = 0 - for node in graph.find_nodes(op="call_function", target=aten.polar.default): - call = _inserter(graph, fake_mode, node) - r, angle = node.args[0], node.args[1] - with graph.inserting_before(node): - pair = _join(call, call(aten.mul.Tensor, r, call(aten.cos.default, angle)), - call(aten.mul.Tensor, r, call(aten.sin.default, angle))) - out = call(aten.view_as_complex.default, pair) - node.replace_all_uses_with(out) - graph.erase_node(node) - changed += 1 - return changed + 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.""" - changed = 0 - for node in (graph.find_nodes(op="call_function", target=aten.mm.default) - + graph.find_nodes(op="call_function", target=aten.addmm.default)): + def build(call, node): found = _row_times_matrix(node) if found is None: - continue - call = _inserter(graph, fake_mode, node) + return None a, b, bias = found - k = int(_val(a).shape[1]) - with graph.inserting_before(node): - column = call(aten.view.default, a, [k, 1]) - out = call(aten.sum.dim_IntList, call(aten.mul.Tensor, column, b), [0], True) - if bias is not None: - out = call(aten.add.Tensor, out, bias) - node.replace_all_uses_with(out) - graph.erase_node(node) - changed += 1 - return changed + 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): @@ -210,37 +189,28 @@ def _to_real_pairs(graph, fake_mode, component): pair = {} for n in component: call = _inserter(graph, fake_mode, n) - 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] - cx, other = (a, b) if _is_complex(a) else (b, a) - if _is_complex(other) or isinstance(other, complex): - pa = pair[cx] - ar = call(aten.select.int, pa, -1, 0) - ai = call(aten.select.int, pa, -1, 1) - if isinstance(other, complex): - br, bi = other.real, other.imag - else: - br = call(aten.select.int, pair[other], -1, 0) - bi = 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)) - pair[n] = _join(call, re, im) + 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] + cx, other = (a, b) if _is_complex(a) else (b, a) + if _is_complex(other) or isinstance(other, complex): + 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: - if isinstance(other, torch.fx.Node): - other = call(aten.unsqueeze.default, other, -1) - pair[n] = call(aten.mul.Tensor, pair[cx], other) + 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)) + pair[n] = _join(call, re, im) + else: + if isinstance(other, fx.Node): + other = call(aten.unsqueeze.default, other, -1) + pair[n] = call(aten.mul.Tensor, pair[cx], other) for n in component: for user in list(n.users): @@ -248,8 +218,21 @@ def _to_real_pairs(graph, fake_mode, component): user.replace_all_uses_with(pair[n]) +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 at the insert point, made through FX's tracer under origin's meta + """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)): @@ -261,7 +244,8 @@ def unwrap(a): tracer = fx.proxy.GraphAppendingTracer(graph) def call(target, *args, **kwargs): - with fx_traceback.preserve_node_meta(), fx_traceback.set_current_meta(origin): + 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: @@ -279,7 +263,7 @@ def _join(call, re, im): 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 + return node.meta.get("val", None) if isinstance(node, fx.Node) else node def _is_complex(node): From 9ff24d3bff6d3aff8cc8dc9b27465b2f1552fee9 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Fri, 23 Oct 2026 11:45:53 +0900 Subject: [PATCH 12/12] [Frontend] post_grad_pass's complex ops are one table, _REAL_PAIR, of each op's real-pair rule What the complex rewrite takes was stated twice: _HANDLED (built from _MUL and _SHAPE) said which ops have a real-pair form, and an if chain in _to_real_pairs said what that form is, so adding an op meant two edits that could disagree. _REAL_PAIR maps each op to its rule (_pair_of_view, _pair_of_unsqueeze, _pair_of_mul); _why_not_real asks whether a node's target is in it and _to_real_pairs calls the rule. _MUL, _SHAPE, _HANDLED and the chain are gone. No behaviour change. Graph tests (7) pass; on the npu (run/tc-solo) complex and polar pass with no call left to aten. --- pytorchsim/frontend/post_grad_pass.py | 79 +++++++++++++++------------ 1 file changed, 45 insertions(+), 34 deletions(-) diff --git a/pytorchsim/frontend/post_grad_pass.py b/pytorchsim/frontend/post_grad_pass.py index ffb795bac..d1d950232 100644 --- a/pytorchsim/frontend/post_grad_pass.py +++ b/pytorchsim/frontend/post_grad_pass.py @@ -132,14 +132,9 @@ def _row_times_matrix(node): return a, b, bias -_MUL = (aten.mul.Tensor, aten.mul.Scalar) -_SHAPE = (aten.unsqueeze.default,) -_HANDLED = (aten.view_as_complex.default,) + _MUL + _SHAPE - - def rewrite_aten_view_as_complex(graph, fake_mode) -> int: - """Each component of complex values (view_as_complex, mul, unsqueeze) becomes real [..., 2] pairs; a - component with any other complex op stays as it is, logged with why. Returns the components rewritten.""" + """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) @@ -172,13 +167,13 @@ def root(n): def _why_not_real(component): - """Why the component has no real-pair form, or None: a node outside _HANDLED (a placeholder or attribute - among them), or a complex value read by anything but _HANDLED and view_as_real (the graph's output too).""" + """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 _HANDLED: + 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 _HANDLED: + 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 @@ -188,29 +183,7 @@ def _to_real_pairs(graph, fake_mode, component): it reads the pair.""" pair = {} for n in component: - call = _inserter(graph, fake_mode, 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] - cx, other = (a, b) if _is_complex(a) else (b, a) - if _is_complex(other) or isinstance(other, complex): - 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)) - pair[n] = _join(call, re, im) - else: - if isinstance(other, fx.Node): - other = call(aten.unsqueeze.default, other, -1) - pair[n] = call(aten.mul.Tensor, pair[cx], other) + pair[n] = _REAL_PAIR[n.target](_inserter(graph, fake_mode, n), n, pair) for n in component: for user in list(n.users): @@ -218,6 +191,44 @@ def _to_real_pairs(graph, fake_mode, component): 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."""