Skip to content

[Backend] Kernels retile through Inductor's standard autotune path on PTB's Triton backend - #537

Closed
student-Jungmin wants to merge 11 commits into
pytorchsim-triton-backendfrom
pending-1116
Closed

student-Jungmin wants to merge 11 commits into
pytorchsim-triton-backendfrom
pending-1116

Conversation

@student-Jungmin

Copy link
Copy Markdown
Collaborator

Eleven frontend and backend commits on top of pytorchsim-triton-backend, listed oldest first:

  • [Backend] A compile that leaves failure.json stopped, even when the compiler exits 0
  • [Backend] Every kernel retiles through Inductor's standard autotune path on PTB's Triton backend
  • [Backend] The spec reaches the Triton backend in triton_meta as Inductor sets it, not by editing the source
  • [Frontend] Inductor is attached through its hooks; the patches left name the lines that leave no public route
  • [Backend] Hand-written kernels are offered a config per candidate tile: topk, grouped_mm, megablox, fused attention
  • [Test] test_mllama --image-size: the vision tower at a size Spike finishes
  • [Frontend] Candidate tiles divide the numel of an axis whose mask Inductor dropped
  • [Frontend] Candidate tiles go down to a floor, not three
  • [Test] test_cat_grid_bound: a cat of two masked halves is refused by the compiler's grid rule (blocked on liveness.grid_bound)
  • [Test] test_cat_grid_bound passes now that PTB's grid_bound reads each access's last live program; bf16 tolerance 2e-2
  • [Frontend] A candidate tile is cut to the axis's power-of-two divisor only where Inductor really drops the mask

This needs PTB pending-1116 (PSAL-POSTECH/PyTorchSim-Triton-Backend), whose Triton backend these commits launch through.

03dacb8 removes the refusal of user-defined Triton kernels that carry configs. Before it, kernels launched with num_warps were refused as autotuned, which covered most Liger-Kernel ops.

Not yet verified on this branch: the system tests have not been run on this exact branch. The PR stays a draft until they have.

…ompiler exits 0

Since PTB #260 (342f8fe7) the compiler exits 0 when a kernel file stops exactly where its
expect_stop declares, after writing failure.json. run_pipeline read failure.json only on a
non-zero exit, so a borrowed PTB case declared blocked at binary (tile_spad_over_budget.py,
SPAD_OVERFLOW 786432 > 524288 bytes/lane) came back as compiled, and
tests/system/test_compiler_failure.py failed with "... compiled". Inductor's kernels declare no
stop, so their runs are unchanged; the compiler clears failure.json at the start of every run.

Measured in torchsim-test:2fd9ca08: test_compiler_failure.py fails before, passes after;
tests/ops/elementwise/test_add.py passes.
…ath on PTB's Triton backend

Generated kernels: TritonNPUKernel puts tiling.candidate_blocks in inductor_meta and
registered npu codegen heuristics (pointwise, reduction) turn them into configs; a
dynamic graph's kernels take their candidates over the size hints. Templates: the mm
heuristics hand the choices a select-time spec and GEMM_CANDIDATES tiles; a choice that
overflows is dropped at precompile, and can_fuse_vertical refuses a template fusion
whose kernel does not fit. User-defined kernels are Inductor's own
async_compile.triton, their spec added to the launch kwargs Inductor turns into
backend_options. PTB's backend raises OutOfResources for a config that does not fit
and autotune drops it.

Launch: backend/launcher.py is registered with driver.set_launcher (Spike, TOGSim) and
backend/config_pick.py with register_benchmarker (first compiled config in functional
mode, TOGSim cycles in timing mode). Spike takes the launch grid; PTB builds a binary
again for extents it was not built for. The wrapper names each call argument's buffer
(torchsim_call), so launch.json and tog_tensor_addrs.txt keep their names; copy nodes'
TOGs reach the workdir. In timing mode a template's choices are ranked by Inductor's
benchmark_choices through the npu benchmarker (time_choices, its pool, cut and memo are
gone). Inductor's compile pool is no longer forced to one thread (BERT seq 128: about
125 s -> 81 s). assert_indirect_indexing stays on. The depthwise conv is offered a
config per candidate block.

Removed: torchsim_compile, retile.py, codecache.py, the make_precompile_fn and
pick_config patches, the triton_kernel_kwargs pin, kernel_metadata.compile_call.

Tests: test_candidate_overflow, test_depthwise_candidate_overflow,
test_dynamic_shape_spike, test_launch_record (addrs file), test_parallel_compile,
test_indirect_index_assert, test_select (rewritten to read what each compile built);
test_togsim_result, test_graph_prefetch(_xla), test_compiler_failure,
test_attention_causal_cycles and npuwattch follow the new path.
…tor sets it, not by editing the source

TritonNPUKernel.triton_meta is a property whose setter adds backend_options when
Inductor assigns the finished dict (triton.py:7338), so it does not depend on when the
body is built (codegen_body also runs from SIMDKernel.disable_reduction, simd.py:806,
before triton_meta exists). A template kernel is seeded with TemplateTritonMeta, whose
update (made by TritonTemplateKernel.jit_lines at render time, after the epilogue is
fused, select_algorithm.py:932-935) adds them: the templates that need it are
Inductor's own instances, and giving them our kernel class would mean assigning
TritonTemplate.kernel_type on them. apply_spec_to_source and its call sites are gone.

test_standard_attachments.SpecInRenderedMeta fails on the source edit. mllama's vision
tower (image 112) is the case the setter fixes over a codegen_body hook.
…ame the lines that leave no public route

Removed:
- AlgorithmSelectorCache.__call__ and benchmark_choices are no longer replaced:
  benchmark_epilogue_fusion is on only when timing mode autotunes, the TIMED mark is a
  feedback saver, an external tile that does not compile is refused by a preprocessing
  function, the untimed-autotune warning is the benchmarker's.
- The aten.convolution lowering is no longer wrapped (groups are read off
  V.graph.current_node), and Inductor's conv2d/conv3d grid functions are left alone.
- NPUChoices is a module-level class, without the __module__/__qualname__ rename.

Kept, each docstring naming the Inductor lines:
- generate_example_value: select_algorithm.py:5995 calls it as a staticmethod and
  input_gen_fns (:4046) turns multi-template off.
- The conv templates' grid attribute: kernel/conv.py names conv2d_template at its call
  site and passes no grid.
- GPU_TYPES.append("npu"): a plain list (utils.py:107) with no registry, read by is_gpu.
- The scatter reinplace check: reinplace.inplaceable_ops (reinplace.py:379) has no
  registration API.
- time_module, the epilogue-fusion benchmark: Inductor's harness subtracts a timing of
  clone_args (triton.py:8340-8349) that launches nothing, which the npu benchmarker
  answers inf, so every fusion would compare against -inf.

test_standard_attachments (SelectionAndConvAreInductors, ConvGroupsOutsideLowering);
test_patch_scope's conv grid test reads conv2d_template.grid.
…e: topk, grouped_mm, megablox, fused attention

autotuned(kernel, configs) wraps a kernel with one triton.Config per dict of
constexprs; tiling.candidate_sizes takes a floor and candidate_tiles halves several
blocks together, each held at its floor. Each config carries what its block sets
(padding, masks), so they follow the block.
- topk: XBLOCK and its halves; a row stays whole.
- grouped_mm: the machine's top three (BN, BK) mm tiles; BM stays the lanes; KP and
  the N grid follow the config.
- megablox grouped_mm: torch_xla's TM (the visit table is counted in it); BN and BK
  halved together down to the lanes.
- fused attention prefill: BQ and BKV halved together (LP, SP, QROWS, KEYS ride along);
  decode and paged decode: the KV step down to the register rows (SP, KV0, KEYS).
- sort is not offered candidates: D fixes the block of four kernels and the merge
  launches Python schedules, which autotune cannot keep in agreement (Sort.plan).

Tests (tests/small_machine.py gives a tpuv6e with a smaller scratchpad; tpuv3_32x32 has
no matrix unit): test_topk_candidate_overflow, test_grouped_mm_candidate_overflow,
test_grouped_mm_megablox_candidate_overflow, test_attention_candidate_overflow,
test_attention_paged_candidate_overflow: the first config raises OutOfResources, a
smaller one compiles, values match the CPU; each dies with NoTritonConfigsError before.
test_grouped_mm_megablox_large records a failure present before this change: K = N =
1024 stops Spike in the output's zero-fill kernel.
…ishes

The full 560 image is 6404 vision tokens; its fused attention did not finish on
Spike in an hour. --image-size 112 (288 tokens, the same layers) runs in ~5 min.
…uctor dropped

Inductor drops an axis's mask when numel divides max_block (Triton's 4096) while the offered XBLOCKs reach
524288, so the last program ran past the tensor (MobileNet 401408 segfault). TritonNPUKernel._get_candidates now
offers, on an axis whose numel is a multiple of the kernel's public max_block, only blocks dividing numel.
Rejected: raising max_block to the largest candidate through a TritonKernel.max_block override keeps large tiles
but puts a mask back on every such kernel, and MobileNet's constant_pad_nd kernel then fails in PTB with
MaskedBoxBeforeTensor (pad mask x xmask over 3 axes). FixedTritonConfig pins one tile and pinned_blocks has no caller.
The spec's pinned blocks are the smallest per axis over the candidates, so its grid bounds each candidate's (a (1,2)
tile does not bound (2,1): Yolov5's 3 x 409600 copy was refused).
Tests: test_candidate_mask (segfault / grid refused on HEAD).
Llama 4's gather x sigmoid (xnumel 655360) overflowed at 524288, 262144 and 131072 (549408 > 524288) and fit at
65536: NoTritonConfigsError. tiling.candidate_blocks halves down while the tile holds the lanes (cap
CANDIDATE_LIMIT = 16); candidate_sizes floors at 2 and candidate_tiles at its floors, up to the same cap, so
topk, megablox, attention, depthwise_conv and grouped_mm follow through the shared helpers. The first-tile
estimate is unchanged (precompile drops overflowing tiles). Test: test_candidate_floor (unit check red on HEAD;
the gather itself fits at 65536 in this tree).
…the compiler's grid rule (blocked on liveness.grid_bound)

Yolov5 triton_poi_fused_add_cat_convolution_silu_5 (xnumel 1638400): the rule reads the first half's clamp (819200 / XBLOCK programs) as the grid, so the launch of 25 is refused (bound 13). Fails identically on HEAD (4 refused, bound 2): not caused by the candidate changes.
…h access's last live program; bf16 tolerance 2e-2
… only where Inductor really drops the mask

The mask filter read an axis as unmasked whenever numel was a multiple of its max block, missing Inductor's
y-grid condition (_has_constant_mask: a y axis without z keeps its mask past get_max_y_grid()). Diffusion's
bf16 channels-last silu (ynumel 102400) had every candidate filtered away and compiled with the empty config,
so YBLOCK was None ('NoneType' object has no attribute 'type'). _is_mask_dropped follows the rule over public
facts, a dropped axis's block is cut to numel's largest power-of-two divisor instead of the tile being
skipped, and no tile at all raises. test_candidate_mask.test_y_past_one_grid_keeps_its_mask fails before.
@student-Jungmin

Copy link
Copy Markdown
Collaborator Author

Replaced by #539, the same work with the later commits, squashed per feature.

@YWHyuk
YWHyuk deleted the pending-1116 branch November 19, 2026 05:29
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.

1 participant