Repository navigation
Conversation
…t 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.
…s 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.
… 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_grouped_mm, _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.
…om_pass, and judges complex values per component Five commits of PyTorchSim #433 in one: the rewrites are named by the op they take, run as the npu's device_custom_pass instead of global hooks, the faults a review of that pass found are fixed, and the file is renamed for what it is. Names. decompose_histc/polar -> decompose_aten_histc/polar, 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 became its install_once key, so Inductor's cache key was unchanged. _Chain is _chain. (rewrite_grouped_mm and rewrite_topk are already gone: grouped_mm.py and topk.py take those ops.) device_custom_pass. 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. The pass is that, registered with the npu backend in torch_openreg. 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 it 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. Faults, each reproduced first: - The complex rewrite 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. - 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). The count is now 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. aten.clamp.default, which the count first used, is in Inductor's decomposition table and has no lowering, and this pass runs after decomposition; it uses clamp_max. - 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 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. - The node maker 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 and seq_nr, so kernel names and errors keep the op they came from. from_node is not copied: Inductor's GraphTransformObserver writes it itself (CREATE when the pass makes a node, REPLACE on replace_all_uses_with). - The GEMV rewrite took any dtype: a complex 1 x K mm became a complex mul and sum, which the complex rewrite then refuses, two calls left to aten instead of one. It takes real floating operands only. - The pass recompiled every graph; it recompiles one it changed. Rename. The file is one thing now, so rewrite_fx_graph.py is post_grad_pass.py and the pass is pytorchsim_post_grad_pass (npu names the device, not whose pass it is), 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); 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. 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. 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; both refused ranges); test_polar test_pass_leaves_no_polar; test_complex_to_real runs the whole pass, as Inductor does, plus test_components_are_judged_apart and test_row_mm_stays_real. Each fault test fails on the pass before its fix. The histc, polar and complex scalar graph tests also ask that every op the pass emits has an Inductor lowering. On the npu (run/tc-solo, PTB main defa86b): complex, histc, polar, topk (12 cases) and grouped_mm (5 cases) pass, and their 27 wrappers hold no call left to aten. Squashed from ad69116, 685180f, f7e2012, fd57613, 14a57d2.
…them with Graph.find_nodes, and replaces them in one place Three commits of PyTorchSim #433 in one; the last is no behaviour change. FX's tracer. _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)]. _inserter still sets the 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. find_nodes. 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 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. One place. 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 places each node just before its origin itself, so neither the rewrites nor _to_real_pairs open an insert point. Tests: 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) 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_*). Squashed from 18140e7, b96db39, 45b5db7.
… 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. From 9ff24d3 of PyTorchSim #433.
This was referenced Oct 23, 2026
Merged
Merged
This was referenced Oct 24, 2026
Collaborator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Split out of #433 by @student-Jungmin, author kept on every commit. This is #433's refactor: its 9 refactor commits squashed into 3. Review only the last three commits; the first three are #438, #439 and #440 and drop out when this branch is rebased after they merge.
Commits
register_backend_for_device'sdevice_custom_passinstead of global decompositions and the global post-grad slot; per-component complex judging, histc counted on the device by aten's own rule (int8 > 127 bins fixed), refused histc ranges raised at compile time, real GEMVs only, provenance kept; the file renamedpost_grad_pass.py._REAL_PAIR(9ff24d3). No behaviour change.The full what/why and the author's measurements are in each commit message.
Why f7e2012 and fd57613 are in commit 1, not 3
fd57613 fixes code that f7e2012 adds (
_KEPT_META'sfrom_node,_emit_histc's range), and the rename (14a57d2) and the FX-tracer commit (18140e7) rewrite that same code. Moving f7e2012 to the end would have meant re-authoring the intermediate trees by hand. Keeping the original order, each squashed commit's tree is one that existed in #433 (14a57d2, 45b5db7, 9ff24d3, rebased).Equivalence
#433's head 9ff24d3 rebased onto the current base (one conflict, the
grouped_mm.pydocstring that #418 also touched) and this branch's tip have the same tree:git diffis empty.Tests (functional mode, timing off)
pytorchsim.frontendmodule afterimport torchworks on each branch.Split of #433
#433 (@student-Jungmin, branch
refactor/post-grad-pass) is split into four PRs. #433 itself is left as it is.split/433-complex-scalarpytorchsim-triton-backendsplit/433-npu-topkpytorchsim-triton-backendsplit/433-grouped-mm-fallbackgrouped_mm_fallbacktakesaten._grouped_mm's npu kernel (6886059)pytorchsim-triton-backendsplit/433-post-grad-passpytorchsim-triton-backendThe three feature PRs each apply to the current base on their own, in the pre-refactor file layout (
rewrite_fx_graph.py). #439 and #440 both remove a rewrite fromrewrite_fx_graph.pynext to each other, so whichever merges second needs a trivial rebase; #441 already holds that resolution. Applying #438 → #439 → #440 → #441 gives exactly the tree of #433's head 9ff24d3 rebased onto the current base (git diffempty).🤖 Generated with Claude Code
https://claude.ai/code/session_011cGNfHFySFsi7feZKKvq7e