Skip to content

[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
pytorchsim-triton-backendfrom
frontend/topk-kernel
Closed

student-Jungmin wants to merge 1 commit into
pytorchsim-triton-backendfrom
frontend/topk-kernel

Conversation

@student-Jungmin

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

Copy link
Copy Markdown
Collaborator

torch.topk on 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_topk turned aten.topk into K rounds of amax, first index and mask, followed by cat. Inductor fused the rounds into one kernel, but it lowered the cat of 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:

  • 2 contiguous stores instead of 16: 94,331 -> 81,815 cycles.
  • 16 contiguous stores: 93,388 cycles.

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.py takes the route attention takes, through torch.library only. It registers aten::topk's npu kernel at AutogradPrivateUse1 and PrivateUse1, and calls torchsim::topk, a triton_op.
    • The kernel puts a row on each lane and runs the same rounds. It gathers the K values and indices of its rows in registers and stores each once.
    • topk_plan is the one gate. The kernel takes the last dim of a floating input whose row fits spad_budget. A program takes vector_lanes rows, 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.
    • Declined calls and eager calls run the rounds as aten ops. A declined call is logged with its reason.
    • Backward scatters the values' gradient to the indices, which is aten's topk backward.
    • rewrite_topk is removed, since no aten.topk on the npu reaches the post-grad graph any more.
  • tests/ops/sort/test_topk.py pins the routes and the values against a stable CPU sort. It joins the allowlist and the workflow matrix. The cases:
    • a whole number of programs and a ragged one
    • a row length that is not a power of two
    • smallest
    • bf16
    • ties go to the first index
    • a dim that is not the last (rounds)
    • the gradient
    • eager and inference_mode (eager and compiled)
    • one launch counted per call

Checked

  • tests/ops/sort/test_topk.py: all 13 cases pass on this branch, with Spike on.
  • The allowlisted model tests that call topk pass locally: test_deepseek_v3_base, test_qwen, test_mistral, test_llama4 and test_yolo. They ran on a tree with the same topk code.
  • The kernel has no vector register spills.

Numbers

These were measured on PyTorchSim-Triton-Backend main 7fb7195, with TOGSim 601fa78 and configs/tpuv6e.yml. I ran its validation/vector harness locally, because CI cannot time topk until the bundle carries it:

TOGSim ÷ measured:

T before (Inductor rounds, b6a18ad) after
1 2.399 0.731
8 4.485 1.026
32 3.285 1.008
128 1.563 0.964
256 1.737 0.919
512 1.771 0.950
1024 1.848 0.962
2048 1.894 0.971
4096 1.919 0.978
8192 1.935 0.978
geomean 2.160 0.945
within ±10% 0 / 10 9 / 10

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_ns in 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%.

…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 YWHyuk closed this Oct 22, 2026
@YWHyuk
YWHyuk deleted the frontend/topk-kernel branch October 23, 2026 03:05
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.
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