Repository navigation
[Frontend] Refactor rewrite_fx_graph into post_grad_pass, the npu's device_custom_pass (split from #433) - #459
Closed
student-Jungmin wants to merge 3 commits into
Closed
student-Jungmin wants to merge 3 commits into
student-Jungmin wants to merge 3 commits into
Conversation
…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.
Collaborator
Author
|
Folded into the refactor's part 1, #449, which now starts from pytorchsim-triton-backend and carries these commits' changes; closing. |
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.
Supersedes #441, rebased onto #458 (
rebase/433-grouped-mm-fallback, itself on dd80d8c). Review only this PR's three commits; they are the same three commits and author as #441's last three.#438 and #439 are merged, so their commits are dropped here.
rewrite_fx_graph.py's rename topost_grad_pass.pymet only a docstring line upstream changed, and the file is taken as the rename makes it. Against #441's tree the only difference is #443's: contract.py (kernel object format 8) and the compiler pin.Run at this branch's tip at PTB 522042a (the pin): test_add 5/5, test_matmul 11/11, test_grouped_mm 6/6, test_topk, test_eager, test_patch_scope 8/8, test_cache_identity, test_histc 3/3, test_polar 3/3, test_complex_to_real 5/5, test_eager_to_compile_recursion, test_row_matmul 4/4 pass.
Original description (#441):
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