Skip to content

[Frontend] Refactor rewrite_fx_graph into post_grad_pass, the npu's device_custom_pass - #433

Closed
student-Jungmin wants to merge 12 commits into
pytorchsim-triton-backendfrom
refactor/post-grad-pass
Closed

student-Jungmin wants to merge 12 commits into
pytorchsim-triton-backendfrom
refactor/post-grad-pass

Conversation

@student-Jungmin

@student-Jungmin student-Jungmin commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

Refactor of pytorchsim/frontend/rewrite_fx_graph.py, now pytorchsim/frontend/post_grad_pass.py: the npu's post-grad rewrites as one Inductor device_custom_pass, with the faults a review of the old file found fixed and pinned by tests.

What changes

Where the rewrites hook in. The old file put histc and polar in Inductor's global decomposition table (every device's compile took them, CPU's included) and chained its passes onto config.post_grad_custom_post_pass with its own gate and chain. pytorchsim_post_grad_pass is a CustomGraphModulePass registered as register_backend_for_device("npu", ..., device_custom_pass=...): Inductor runs it on npu graphs only, after its own post-grad passes, and puts its uuid (a hash of the file) in the FX cache key. Removed: register_decomposition, the post-grad hook chain (_Chain, install_once, npu_only, is_npu_graph, install).

What it rewrites (in this order):

op rewrite
aten.histc counted on the device with aten's own bin rule for every dtype and range (was: only an integral input whose bins are its values; anything else an extern call)
aten.polar view_as_complex of the contiguous pair (abs*cos, abs*sin)
1 x K mm / addmm of real floating operands broadcast multiply and sum over K
complex values (view_as_complex, mul, unsqueeze) [..., 2] real pairs, judged per connected component (_REAL_PAIR is the one table of each op's rule)

Moved out of the file. topk is #396's torch.library kernel (its commit is in this branch, see below). transformers::grouped_mm_fallback (what transformers calls instead of aten._grouped_mm when the weight is not bf16) is registered to the same entry as aten._grouped_mm (#412), so the dense rewrite, every expert's mm over every row, is gone.

Faults fixed, each with a test that fails on the commit before its fix:

  • a complex Python scalar was broadcast over the real pair (z * (1+2j) came out complex64 and wrong)
  • one complex op the pass cannot rewrite left every complex node of the graph complex, silently; now only its own component stays, logged with why
  • int8 histc with more than 127 bins wrapped its iota and counted values outside the range (6 counts where aten gives 3)
  • aten.clamp, used by the new histc count, has no Inductor lowering (the pass runs after decomposition); the graph tests now ask that every op the pass makes has a lowering
  • new nodes kept no provenance; they are now made through fx.proxy.GraphAppendingTracer under fx.traceback.set_current_meta(origin), so FX copies the rewritten node's meta and records from_node
  • a complex 1 x K mm was turned into complex mul + sum (two calls left to aten instead of one)
  • a histc range aten refuses (max must be larger than min) divided by zero or counted nothing; it is refused at compile time

Clean-ups: names say the op they take (rewrite_aten_histc, ...), snake case throughout, Graph.find_nodes instead of comparing node.op strings, one _replace loop for the node-replacing rewrites, the file reads top-down (the pass first, its rewrites below in run order).

Private API

register_backend_for_device and torch._inductor.custom_graph_pass are under torch._inductor; they are Inductor's extension point for an out-of-tree device and there is no public path for a device post-grad pass. fx.traceback.set_current_meta is in torch.fx.traceback.__all__ but marked not backward compatible.

Known open

With min == max the histc range comes from the data; 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.

Depends on

Tests

Graph tests (no device): test_complex_to_real (5), test_histc test_pass_counts_on_the_device (7 cases plus two refused ranges, torch.equal to aten), test_polar test_pass_leaves_no_polar.

On the npu, functional mode, the same commits before their rebase onto 069878a, PTB defa86b: test_complex_to_real (5), test_histc (3), test_polar (3), test_topk (12), test_grouped_mm (5, the new fallback case among them) pass, and their wrappers hold no call left to aten (the float histc that used to go to the CPU included). On this branch (c7307f2) at its pin, PTB 1b35878: the same five pass (complex 5, histc 3, polar 3, topk 12, grouped_mm 5 cases), and their 27 wrappers hold no call left to aten.

No default changes. No numbers: this is a refactor and fix of the frontend's graph rewrites, not a timing change.

Rebased onto 8967db2 (after #435) with no conflicts.

🤖 Generated with Claude Code

https://claude.ai/code/session_01UnJWSTNtd6944XAzy4bhk5

…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.
… 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.
…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_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.
…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.
…unts 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.
…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.
…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.
…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_*).
…udges 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.
…s 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.
… 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.
@YWHyuk

YWHyuk commented Oct 23, 2026

Copy link
Copy Markdown
Collaborator

This PR's history is split into four draft PRs on new branches (this branch and this PR are left untouched; authorship is kept on every commit):

Applying #438 → #439 → #440 → #441 gives exactly the tree of 9ff24d3 rebased onto the current pytorchsim-triton-backend (git diff empty). Details in #441.

@YWHyuk

YWHyuk commented Oct 23, 2026

Copy link
Copy Markdown
Collaborator

Closing in favour of the split: #438 (complex scalar product), #439 (npu topk), #440 (grouped_mm_fallback), #441 (post_grad_pass refactor). Stacked together they give this branch's tree on the current base; authorship is kept.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants