Skip to content

[Refactor 3/8] NPUDeviceInterface, tiling and blocks in one place, registration.py - #451

Closed
student-Jungmin wants to merge 28 commits into
refactor/r441-2-fused-kernelfrom
refactor/r441-3-registration
Closed

student-Jungmin wants to merge 28 commits into
refactor/r441-2-fused-kernelfrom
refactor/r441-3-registration

Conversation

@student-Jungmin

Copy link
Copy Markdown
Collaborator

Draft: waiting for verification (CI and the validation reports) before review.

Part 3 of 8 of the frontend refactor, split so each part reviews on its own. Stacked on #450 (refactor/r441-2-fused-kernel); review only this PR's commits.

What

NPUDeviceInterface's SM count is the machine's vector lanes. Driver and openreg leftovers go. tiling.py moves to frontend/. A kernel's blocks are computed in one place (blocks_for). registration.py holds everything npu registers and patches only what has no hook.

Behavior change

The core count is read from the machine file. An unread machine file is refused instead of silently giving 1.

Commits

  • a3ba1ea [Dynamo] NPUDeviceInterface: the SM count is the machine's vector lanes, and only what Inductor reads
  • 4ed9506 [Repo] No driver or openreg leftovers: the package and codegen docstrings, NPUDeviceOpOverrides
  • 10c6104 [Inductor] The core count is read, not guessed: no silent 1 when the machine file is unread
  • 9b56525 [Frontend] The DeviceInterface is inductor/device_interface.py; frontend/dynamo is gone
  • 4709602 [Inductor] template_grid and combo_grid live in kernel_metadata, their only reader
  • f3ca352 [Frontend] tiling.py is frontend/tiling.py: the machine's block and tile sizes, read by Inductor and the dispatcher
  • ef33eb3 [Inductor] blocks.py holds an Inductor kernel's blocks; choices.py only Inductor's choice hooks
  • 6070680 [Inductor] A kernel's blocks are computed in one place, blocks_for, with no silent fallback
  • 2558b22 [Inductor] registration.py holds everything npu registers: the device interface and op overrides join it
  • 798792f [Inductor] registration patches only what has no hook: no cpu override stand-ins

Checked locally

On the whole stack, part 8's tip 7af199a, with PTB 814c416 (contains the pin 1b1e060) and TOGSim b9c9519:

  • system: test_module_form, test_device_interface, test_verify_golden, test_togsim_exit, test_togsim_result, test_patch_scope, test_cache_identity, test_attribute_sources, test_eager, and test_select (TIMING_MODE=1): all pass.
  • ops: test_add 5/5, test_matmul 11/11, test_histc, test_topk, test_conv_transpose 5/5, test_custom_fused_kernel: all pass.

No cycle numbers here: nothing in this part is meant to change a kernel's cycles. The CI validation report is the check.

…uctor's hooks, its selection, npu as a Triton GPU

inductor_patches.py held four kinds of patch in one file. They are now:

  choices.py     NPUChoices (config.inductor_choices_class, Inductor's documented
                 hook for a custom InductorChoices), its conv tile table, and the
                 mm/bmm/addmm/baddbmm heuristics (register_template_heuristic, its
                 per-device registry); pinned_blocks and its helpers
  selection.py   how a template's config is picked: TOGSim cycles in timing mode,
                 the offered order otherwise, recorded picks. Inductor's hooks take
                 the recording (add_preprocessing_fn, add_feedback_saver); it has
                 none for timing a choice, so four AlgorithmSelectorCache methods
                 are still replaced, each falling back to Inductor's off npu
  triton_gpu.py  npu in GPU_TYPES, which Inductor has no hook for; is_npu and
                 lowering_npu
  inductor_patches.py  the lowering patches with no hook (transposed conv, a
                 grouped conv's grid, a zero-length GEMM), npu's conv
                 decompositions, and install(), which applies everything

npu's conv tile table reads the lane count when it is asked rather than once, so a
TOGSimulator(config_path=...) block gets its machine's lanes. install()'s mid-body
comment is _configure_inductor's docstring. No other behaviour change.

References follow: inductor_hooks (pinned_blocks), the tiling.py comment,
test_patch_scope (is_npu), test_reduction_tiling, .claude/CLAUDE.md.
…s with a Triton kernel of their own

frontend/ held topk.py and grouped_mm.py beside post_grad_pass.py and
inductor_patches.py with nothing in their names to say what they are. Both
register an op's npu kernel through torch.library and launch a Triton kernel
of ours as a triton_op (torchsim::topk, torchsim::grouped_mm), which is not
what post_grad_pass does (rewrite into aten ops Inductor lowers). They are
frontend/triton_ops/topk.py and frontend/triton_ops/grouped_mm.py now, and
triton_ops.install() registers them; inductor_patches calls it. attention.py,
the same kind, moves in the next commit.

References follow: inductor_patches.install, the imports in test_topk and
test_grouped_mm, post_grad_pass's docstring, .claude/CLAUDE.md. No behaviour
change. On the npu (run/tc-solo): test_topk (12 cases) and test_grouped_mm
(5 cases) pass.
…opk and grouped_mm

attention.py registers SDPA's overrideable op's npu kernel through torch.library
and launches our fused prefill and decode Triton kernels, the same kind of file
as triton_ops/topk.py and triton_ops/grouped_mm.py, so it joins them;
triton_ops.install() registers it first, as inductor_patches did, and
inductor_patches now calls triton_ops.install() alone.

References follow: topk's _fits import, test_fused_sdpa's two imports, the
comment in device/csrc/aten/native/Extra.cpp (a path only, no rebuild), the
post_grad_pass docstring, .claude/CLAUDE.md. No behaviour change.

Branches with unmerged commits on frontend/attention.py (sdpa-fused-kernel,
frontend-prefill-splash-block) will meet this rename when they merge.

On the npu (run/tc-solo): test_fused_sdpa passes its 11 cases with the same
lines as before the move, and test_topk its 12.
…ve, imports follow

A move only, so every file keeps its history (git log --follow, blame): each
file below is renamed with its content unchanged but for the import paths
that name the new places.

  frontend/triton_ops/{__init__,attention,grouped_mm,topk}.py  -> frontend/dispatcher/
  frontend/{post_grad_pass,choices,selection}.py                -> frontend/inductor/
  frontend/triton_gpu.py                                        -> frontend/inductor/registration.py
  frontend/inductor_patches.py                                  -> frontend/inductor/lowering.py
  codegen/{__init__,kernel_metadata,tiling,verify}.py           -> frontend/inductor/codegen/
  codegen/inductor_hooks.py                                     -> frontend/inductor/codegen/scheduling.py

dispatcher/ holds the ops registered at the npu dispatch keys (torch.library),
inductor/ what npu plugs into Inductor. frontend/inductor/__init__.py is empty
here; the next commit gives each layer its install().

test_patch_scope passes on the npu (run/tc-1b35878, PTB 1b35878).
…Inductor's registrations live in inductor/

pytorchsim.frontend.install() plugs npu into every layer once: dynamo/
(DeviceInterface), inductor/ (backend and patches), dispatcher/ (ops with a
Triton kernel of their own). torch_openreg calls it and nothing else of the
frontend.

  dynamo/device_interface.py   was device/torch_openreg/openreg/
                               extension_device_interface.py; its
                               register_interface_for_device call moves from
                               openreg._lazy_init into its install()
  inductor/device_op_overrides.py  was device/torch_openreg/openreg/
                               extension_device_op_overrides.py; its two
                               registrations at import are its install()
  inductor/registration.py     npu as an Inductor backend in one place: the
                               GPU_TYPES patch it held, the
                               register_backend_for_device call that sat in
                               torch_openreg/__init__.py, and the op overrides
  inductor/__init__.py         install(): registration, choices, lowering,
                               selection, then _configure_inductor (from
                               inductor_patches.install)
  inductor/lowering.py         its own patches only

Every Inductor registration npu makes is now under frontend/inductor/, and
device/ holds the PrivateUse1 device alone. Two inline comments the moved files
carried are docstrings. No behaviour change.

On the npu (run/tc-1b35878, PTB 1b35878): test_patch_scope, test_complex_to_real,
test_topk, test_grouped_mm, test_fused_sdpa, test_group_conv and test_eager pass.
It listed a model's aten ops and, on a crash, read the traceback text for the
op it died in. It has not changed since the MLIR route (2026-08-13), it finds
crashes but not the silent CPU fallbacks a wrapper's extern calls show, and
coverage is the CI sweep's (scripts/ci/triton_route_sweep.py). The places that
named it follow: .claude/CLAUDE.md, and test_mllama's docstring paragraph and
comment, whose assert already says what the comment did.
…_result is check_result

The module held one function, the result check every test shares, under a
name that said neither (a private underscore, a generic utils). It is
result_check.py now; the name stays unique on sys.path, which the module's
docstring explains (ultralytics ships a top-level tests package). The function
is check_result: test_result began with test_, so pytest would have collected
it, imported into 71 files, as a test of its own. Its printed lines are
unchanged (|<name> Test Passed| / Failed), which the CI sweep reads.

The 71 test files that import it change their import line and calls only;
.claude/CLAUDE.md names the new file. test_pointwise keeps its own local
function. test_histc and test_add pass on the npu through the renamed helper.
…ter the frontend

A move only, so every file keeps its history: pytorchsim/driver/{__init__,
autotune,codecache,compiler_bridge,compiler_input,select}.py are
pytorchsim/backend/, content unchanged but for the paths that name it. It pairs
with frontend/ (what plugs into torch.compile); backend/ hands a kernel to
PyTorchSim-Triton-Backend and launches what it built, simulator/ runs it.

References follow in pytorchsim, tests, scripts and .claude/CLAUDE.md
(pytorchsim.driver, pytorchsim/driver, driver/<file> paths; "driver" for
Triton's or the compiler's C driver is left alone).

On the npu (run/tc-1b35878, PTB 1b35878): test_add, test_cache_identity,
test_tuned_blocks_on_hit and test_grouped_mm pass. test_select (its timed case
needs a TOGSim Simulator this toolchain did not build) and test_compiler_failure
(PTB 1b35878 compiles tile_spad_over_budget, which the test expects refused)
fail the same way on the commit before this one.
…kernel's plan is held to

attention's _fits and _lane_bytes become fits_scratchpad and lane_bytes, and the
_p2 that attention and topk each defined becomes next_pow2, in one place; topk no
longer imports a private helper from attention. No change in behavior.
…r own Triton kernel; topk first

A subclass states the ops it takes, kernels(), plan() (blocks or a Decline),
launch() (whose annotations after `plan` are the triton_op's schema) and an aten
reference; install() registers every op the same way: the npu kernel at
AutogradPrivateUse1 and PrivateUse1, eager calls to the reference (counted),
compiled calls the plan declines -- or that need a gradient the kernel has no
backward for -- to the reference with a log line, the rest to the triton_op,
whose own npu eager kernel is the reference. `routed` counts each kernel's
launches and the eager reference calls.

topk is TopK on it; topk.ROUTED is TOPK.routed, and the eager route is now
"reference" (was "rounds"), so test_topk says so. test_fused_kernel pins the
routing on a toy op: eager, compiled, declined, gradient without a backward,
compiled under inference_mode.

grouped_mm and attention still route by hand; they move next.
…._grouped_mm and transformers' fallback

bias and out_dtype become triton_op arguments that plan() declines, so both ops
are one call (A, B, offs, bias, out_dtype) and one route. The gradient decline is
the base's (no backward). An eager call is now counted as "reference".
test_grouped_mm reads GROUPED_MM.routed instead of re-observing the kernel's
launches (which replaced the base's observer), and pins the eager and grad routes.
…aps a kernel's result to the op's

The overrideable op returns nine outputs, the kernel one, so CustomFusedKernel
gains outputs(op, result, *args) (identity by default), applied on every route.
The mask and dropout become triton_op arguments that plan() declines; the scale
is made explicit in arguments(); the plan's blocks are read inside the triton_op
instead of passed as its arguments. fused_plan returns a Decline saying why in
place of None, so each declined compiled call logs its reason. The eager route
is "reference" (was "math"), and test_fused_sdpa says so.
…a fused op is added

CLAUDE.md's layout table and "adding a new op" named triton_ops/, inductor_hooks.py
and the flat frontend files; post_grad_pass and dispatcher docstrings too.
…rence

It is what runs wherever the kernel does not (eager, a declined call, the
triton_op's own eager kernel), which PyTorch calls a fallback; "reference" read
as the expected value the tests compare against. The route counted for eager
calls is "fallback" too, and the tests say so.
…ount under `calls`

`takes` holds the OpOverload (torch.ops.aten.topk.default), so a misspelt op fails
at import; transformers' grouped_mm_fallback stays a qualified name, since
transformers defines it only once imported, after install. kernels() is the
tuple of jit kernels and each launch counts under the kernel's own name, so no
route label repeats a kernel; attention's plan holds the kernel it launches and
launch picks by identity, not by the string "decode". `routed` is `calls`, and
the modules' ROUTED aliases are gone: the tests read TOPK.calls,
GROUPED_MM.calls and FUSED_SDPA.calls.
When an op needs one, how a call is routed, each member of CustomFusedKernel,
a whole worked example (run on the npu: compiled, eager and declined routes
as stated), registering it, testing its routes through `calls`, the rules a
kernel is reviewed against, and the patterns attention and grouped_mm use.
CLAUDE.md's "adding a new op" points to it.
… class every fused op inherits

Its test is test_custom_fused_kernel.py. Imports, docstrings, CLAUDE.md and the
fused-kernel guides name the new path; no code changes.
…es, and only what Inductor reads

Counted on add, sum, mm and a bf16 softmax compiled on the npu, Dynamo and
Inductor read the device properties once (multi_processor_count, the rest by
getattr with a default), the compute capability, availability, Triton and bf16
support; nothing else.

- multi_processor_count is config.CONFIG_MACHINE.vector_lanes (128 on v6e, the
  value it had as a literal). Inductor's template gate (is_big_gpu, at least 68)
  and its split-reduction heuristics read it.
- get_device_properties asserted device.type == "extension_device", so "npu:0"
  raised; it filled a cache from torch.cuda and returned a class whose 20
  annotated fields had no values. It now returns one NPUDeviceProperties for any
  spelling of the device.
- get_compute_capability is 0, not 36: no CUDA capability, and torchsim_compile
  does not read the value Triton's compile metadata carries.
- is_bf16_supported's docstring said the compiler refuses bf16; it does not.
- ExtensionDeviceInterface is NPUDeviceInterface, Worker defers to torch.npu.

torch._dynamo.device_interface has no public counterpart for registering a
device's interface. test_device_interface pins the SM count for every device
spelling and the answers above.
…ings, NPUDeviceOpOverrides

pytorchsim's docstring named codegen and driver, which are frontend/inductor/codegen
and backend now; codegen's named inductor_hooks.py (scheduling.py) and said the route
is registered at device import (frontend/inductor/registration.py registers it).
ExtensionDeviceOpOverrides, openreg's example name, is NPUDeviceOpOverrides.
…machine file is unread

_num_cores swallowed any error reading num_cores and returned 1, which turns off
the reduction-split rule for multi-core machines without a word. Every TOGSim
machine file states num_cores, so a failure to read it now raises.
…end/dynamo is gone

Its registry is Dynamo's, but every read of it on the npu path is Inductor's
(DeviceProperties, is_big_gpu, the Triton and bf16 checks); Dynamo reads one only
to trace streams and events, which npu does not have. registration.install()
registers it first, and frontend is dispatcher/ and inductor/.
…r only reader

They read Inductor's kernel objects and V.graph; tiling.py is left with the block and
tile sizes a machine takes, and no Inductor import. Moved as they were.
…ile sizes, read by Inductor and the dispatcher

It holds no Inductor object any more, and the dispatcher (custom_fused_kernel,
grouped_mm) imported it from inside inductor/codegen. Moved as it was; imports,
docstrings and CLAUDE.md name the new path.
…ly Inductor's choice hooks

pinned_blocks, _kept_axis_contiguous and _elem_args read Inductor's scheduler nodes
to call tiling.fixed_config_for; scheduling pinned through choices for them, and
choices was half block pinning. Moved as they were.
…ith no silent fallback

Pinning (TritonNPUKernel), the persistent-reduction choice and the compile
metadata each called tiling.fixed_config_for with their own inputs: the metadata
recomputed a kernel's blocks without the contiguous-axis hint when it held none,
and the persistence check swallowed any error into reduction_block_for. All three
now call blocks.blocks_for (a template's or combo kernel's metadata, which has no
scheduler nodes, still reads its numels and args alone).

- pinned_blocks logs a tiling whose numels are not static and returns None; an
  error from fixed_config_for raises instead of becoming "no blocks".
- should_use_persistent_reduction logs a reduction whose rows are not static
  before using reduction_block_for; any other error raises.
- _elem_args takes each dtype's width from torch (itemsize), not a table that
  read every dtype it lacked (fp8 among them) as 32 bits.

18 tests run on the npu (reductions, softmax, layer/batch norm, pointwise,
matmul/bmm and their reduction fusions, conv, cache identity, tuned blocks,
widen dtype, masked non-dividing): all pass.
… interface and op overrides join it

NPUDeviceInterface (with NPUDeviceProperties) and NPUDeviceOpOverrides existed only
to be registered, by registration.py; device_interface.py and device_op_overrides.py
are folded into it as they were. No behavior change.
…e stand-ins

- has_triton() and triton_hash_with_backend() are upstream's (938b276): npu's
  DeviceInterface and the torchsim driver answer them.
- cpu's device op overrides: torch 2.14 registers its own devices' behind a flag,
  not on an empty table, so npu registering first no longer hides cpu's.
- lowering_npu catches what "no graph" and "no device" raise (AttributeError,
  RuntimeError), not every error; is_npu reads a device string with torch.device.

test_device_interface pins has_triton being upstream's and True, npu a GPU type,
cpu keeping Inductor's overrides, and is_npu on every device spelling.
@student-Jungmin

Copy link
Copy Markdown
Collaborator Author

Folded into #450: the refactor is now 5 PRs, each one commit of its part's final state.

@student-Jungmin
student-Jungmin deleted the refactor/r441-3-registration branch October 24, 2026 07:33
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