Skip to content

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

Merged
student-Jungmin merged 11 commits into
pytorchsim-triton-backendfrom
inductor-autotune-retile
Nov 17, 2026
Merged

student-Jungmin merged 11 commits into
pytorchsim-triton-backendfrom
inductor-autotune-retile

Conversation

@student-Jungmin

@student-Jungmin student-Jungmin commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Replaces #537. 10 commits on pytorchsim-triton-backend 2fd9ca0, one per feature. Needs PyTorchSim-Triton-Backend branch mask-resolution-and-triton-backend; the compiler pin is not bumped here yet.

  • A compile that leaves failure.json stopped, even when the compiler exits 0.
  • Every kernel retiles through Inductor's standard autotune path on PTB's Triton backend (generated, template and user kernels; launcher and benchmarker registered through public hooks).
  • The spec reaches the Triton backend in triton_meta as Inductor sets it, not by editing the source.
  • Inductor is attached through its hooks; the patches left name the Inductor lines that leave no public route.
  • Hand-written kernels are offered a config per candidate tile (topk, grouped_mm, megablox, fused attention).
  • Every candidate tile is one Inductor's generated source is correct for (its mask rule, the y-grid condition), down to a floor.
  • The spec states an unsigned tensor's dtype.
  • The bundle writes each kernel file from the source and meta its definition left.
  • test_mllama --image-size; test_llama4 allows 10% of the token rows to take other experts in bf16.

Verification (with the PTB branch above, extension rebuilt)

  • 77 of the 81 CI test units pass, among them BERT, GPT-2, Gemma, Llama 2/3/3.x, Qwen, Yolo, Yolov5, MobileNet, ViT, CLIP, ResNet, SwinV2, ConvNeXt and mllama; test_widen_dtype, test_user_triton_kernel, test_bundle_reuse and test_bundle_where pass after their fixes.
  • DeepSeek V3, Mixtral and Diffusion (UNet) pass end to end on this tree.
  • Llama 4 Scout: every one of its 45 kernels matches on its own (Triton's interpreter, or torch for the mm templates). The model output leaves 10 of 128 token rows apart from the f32 reference. bf16 on the CPU alone leaves 12, because the top-1 router flips near-ties (margin 0.005 in layer 0) and carries them through 4 layers. The PyTorchSim branch raises that test's bound from 5% to 10%.

Known: test_grouped_mm_megablox_large records a Spike fault at K = N = 1024 that predates this branch.

…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, and the roles of their arguments are recorded when they are defined. 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.
… correct for, down to a floor

Inductor drops an axis's mask when numel is a multiple of ITS max block (4096 on x), and for y only within
one y grid (TritonKernel._has_constant_mask). A candidate larger than that, not dividing numel, ran the last
program unmasked past the tensor: MobileNet's 401408-element pointwise wrote one past its tensor (Spike
segfault), and Yolov5's 3 x 409600 copy was launched past the compiled grid. TritonNPUKernel._is_mask_dropped
follows that rule over public facts; on an axis whose mask is dropped a block is cut to numel's largest
power-of-two divisor (not skipped, so the list is never empty), and no tile at all raises instead of yielding
an empty config (Diffusion's bf16 channels-last silu, ynumel 102400 past one y grid, compiled with YBLOCK None).

The spec's grid bounds every candidate: the per-axis maximum over them (_blocks_without_pin), not the last
tile's. Candidates halve down to the lanes instead of stopping at three (CANDIDATE_LIMIT 16 caps multi-axis
products; the hand-written kernels follow through candidate_sizes / candidate_tiles): Llama 4's gather x
sigmoid pointwise overflowed at all three (131072 needs 549408 of 524288; 65536 fits).

Tests: test_candidate_mask (MobileNet's shape, Yolov5's copy, the y axis past one grid), test_candidate_floor,
test_cat_grid_bound (a cat of two masked halves, which PTB's grid_bound now bounds per access; bf16 tolerance
2e-2). Each fails before.
… spells as its signed width

Triton IR has no unsigned pointer (!tt.ptr<i8> for uint8), so PTB read a uint8 input as int8 and the launch
refused it (ShapeMismatch: 'in_ptr0' is torch.uint8, but the binary was compiled for int8). spec_dict now
states the dtype of an unsigned tensor; PTB takes a stated dtype over the IR's. test_widen_dtype (uint8->int32,
uint8->float32) failed before and passes.
… its definition left

scripts/ci/bundle.py copied <kernel>_spec.py and <kernel>_triton.py from the launch's workdir, which the
retile to Inductor's autotune path no longer writes. Every kernel's module text and meta are kept when it is
defined (kernel_metadata.KERNEL_SOURCES: define_kernel for generated and template kernels;
define_user_defined_triton_kernel for user kernels, through user_kernel_source and user_kernel_meta). The
launch meta carries the manifest's scalars ({name, ctype, default}) and the constexprs the Triton backend
built the kernel with; copy_kernel writes the files with compiler_input.write, those constexprs pinned, and
launch_scalars reads the scalars without a default.

test_bundle_reuse (KeyError: 'signature', then FileNotFoundError, before) and test_bundle_where pass. Bundling
attention S=1024 (8 workloads) writes spec files that match validation/pytorchsim's but for the kernel's
newer parameters; a decode and a prefill kernel compile and run on Spike in PTB's tests/run.py as the bundled
ones there do.
…erts in bf16, as the CPU alone does

Llama 4 Scout (4 MoE layers, top-1 of 16 experts) failed with 10 of 128 token rows apart from the f32
reference, 6 allowed (5%). Measured on the CPU without the compiler: bf16 eager leaves 12 of 128 rows apart.
The router picks another expert for 1, 4, 3 and 8 tokens in layers 0-3; in layer 0 the f32 margin between
the first and second expert of the flipped token is 0.005, and later layers flip wider margins because the
earlier flips carried through. Each of the 45 kernels the compile builds matches on its own (Triton's
interpreter, or torch for the mm templates). The bound is now 10%, which the CPU's bf16 run meets.
…sk resolution and the Triton backend hooks this branch calls)
@student-Jungmin
student-Jungmin marked this pull request as ready for review November 17, 2026 08:08
@student-Jungmin
student-Jungmin merged commit 0fde53e into pytorchsim-triton-backend Nov 17, 2026
12 of 15 checks passed
@YWHyuk
YWHyuk deleted the inductor-autotune-retile 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