Repository navigation
[Frontend] topk on the npu is one Triton kernel that stores its values and indices once each - #396
Closed
student-Jungmin wants to merge 1 commit into
Closed
student-Jungmin wants to merge 1 commit into
student-Jungmin wants to merge 1 commit into
Conversation
…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.
YWHyuk
pushed a commit
that referenced
this pull request
Oct 23, 2026
…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.
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.
torch.topkon the npu becomes one Triton kernel. It stores its values once and its indices once, instead of one DMA per round and per output.Why
rewrite_topkturnedaten.topkinto K rounds of amax, first index and mask, followed bycat. Inductor fused the rounds into one kernel, but it lowered thecatof 2K reductions into 2K column views of the outputs. For k = 8 that is a kernel with 16 output pointers, and TOGSim sees 16 DMAs per program.On the T 8192 router kernel's TOG, with nothing else changed:
So the cost is the number of DMAs, not the stride. Every other kernel of the compiler's validation bundle has a single output.
What changes
pytorchsim/frontend/topk.pytakes the route attention takes, throughtorch.libraryonly. It registersaten::topk's npu kernel at AutogradPrivateUse1 and PrivateUse1, and callstorchsim::topk, atriton_op.topk_planis the one gate. The kernel takes the last dim of a floating input whose row fitsspad_budget. A program takesvector_lanesrows, and rows past the end are masked. A call with fewer rows therefore keeps the same layout instead of spreading the row over the lanes.rewrite_topkis removed, since noaten.topkon the npu reaches the post-grad graph any more.tests/ops/sort/test_topk.pypins the routes and the values against a stable CPU sort. It joins the allowlist and the workflow matrix. The cases:Checked
tests/ops/sort/test_topk.py: all 13 cases pass on this branch, with Spike on.test_deepseek_v3_base,test_qwen,test_mistral,test_llama4andtest_yolo. They ran on a tree with the same topk code.Numbers
These were measured on PyTorchSim-Triton-Backend main 7fb7195, with TOGSim 601fa78 and
configs/tpuv6e.yml. I ran itsvalidation/vectorharness locally, because CI cannot time topk until the bundle carries it:scripts/ci/bundle.pywith the topk suite ([CI] The bundle builds topk for the compiler's measured router rows, at f32 #395).topk_blockpallas_t_lanes, PyTorchSim's rounds as one Pallas kernel with a row on each lane.TOGSim ÷ measured:
Open
T 1 is on the fast side (0.73), and the cause is on the measured side. The v6e T 1 time, 2.0 µs, is the kernel (1.01 µs) plus two output relayout copies (0.97 µs). XLA adds those copies at the program boundary: the reference kernel writes (K, T) = [8, 1], and XLA lays out the program's result column-major.
No single output shape avoids such copies at every T. Compiled for v6e, a variant that writes [T, K] has no copy at T 1 and 8, but gets two copies at T 128 and above, and XLA overrides a row-major result layout requested through
out_shardings.Against the kernel time alone (
kernel_nsin the archive), T 1 is 1.468 / 1.014 = 1.45. That number is on the slow side: this kernel runs a full lane-wide tile for one row (T 1 1.47 µs, T 8 1.54 µs), while the v6e kernel at T 1 takes 0.49 µs less than at T 8. For T ≥ 8 the kernel time and the module time less lead-in agree within 0.3%.