Skip to content

[Refactor 8/8] postgrad/ by op family; comment and fallback cleanup; verify golden fix; CI runs the new tests; histc min == max - #456

Closed
student-Jungmin wants to merge 61 commits into
refactor/r441-7-simulatorfrom
refactor/r441-8-cleanup
Closed

student-Jungmin wants to merge 61 commits into
refactor/r441-7-simulatorfrom
refactor/r441-8-cleanup

Conversation

@student-Jungmin

Copy link
Copy Markdown
Collaborator

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

Part 8 of 8 of the frontend refactor, split so each part reviews on its own. Stacked on #455 (refactor/r441-7-simulator); review only this PR's commits.

What

post_grad_pass/ becomes postgrad/, one module per op family (histc, gemm, convolution, complex). Mid-function comments go or move into docstrings. except Exception that hid why a value was missing goes. Verify fix, CI additions and histc are below.

Behavior change

  • Verify: the per-kernel CPU golden ran in-place ops on the real inputs (_to_cpu returned a CPU tensor itself) and failed on Inductor's reinplaced foreach. test_mlp's Optimizer case therefore failed under TORCHSIM_FUNCTIONAL_VERIFY_PER_KERNEL=1. It now copies, and reads a reinplaced op as the argument it wrote; pinned by test_verify_golden.
  • histc over a floating input with min == max is left to aten, which refuses a range that is not finite; before, the rewrite returned wrong bins for a NaN or an inf. Integral inputs stay on the device. Pinned in test_histc.
  • template_kernel_configs no longer falls back to the generic configs, unlogged, when optimization_hint raises.
  • CI: test_conv_decomposition, test_conv_transpose, test_zero_length_gemm and test_custom_fused_kernel join the allowlist and the matrix; test_device_interface, test_module_form and test_verify_golden join the matrix.

Commits

  • 02486da [Frontend] post_grad_pass is a package, one module per op family
  • c3f1b19 [Frontend] post_grad_pass/ is postgrad/
  • 635f96f [Cleanup] Comments inside function bodies go, or move into the docstring
  • 0325424 [Cleanup] No except Exception that hides why a value is missing
  • 87739df [Verify] The CPU golden runs on copies of the inputs, and reads a reinplaced foreach as what it wrote
  • 2fd809d [CI] Run the tests this branch added
  • 7af199a [Frontend] histc over a floating input with min == max is left to aten

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.
…a stated fallback and counts

A rewrite of one op is a function registered through npu_rewrite on Inductor's
PatternMatcherPass (the form Inductor's own post-grad passes take): its pattern
and extra_check pick the nodes, and it returns plain torch code that Inductor
traces into the node's place (Match.replace_by_example), or a Decline, which
leaves the node and logs where it runs instead: Inductor's own kernel, or an
extern aten call on the CPU, outside the simulator. CALLS counts each rewrite's
rewritten and fallback nodes.

- histc and the 1 x K row times a matrix (mm, plain addmm) are patterns; their
  replacements are torch code, not hand-built nodes, so _replace goes.
- polar is a rule in _REAL_PAIR, (abs*cos, abs*sin): Inductor's pattern matcher
  skips nodes with a complex output, and polar only makes a complex value.
- The pass sets the graph's fake mode for tracing (V.set_fake_mode), which a
  caller outside Inductor, like the tests, does not.

test_complex_to_real, test_histc, test_polar and test_row_matmul pass; replaced
nodes keep the original node's stack trace.
…rites, not lowering patches

Both were lowering wrappers rebuilding the graph in Inductor IR; both are graph
rewrites of one op, so they are npu_rewrite patterns now, their replacements
plain torch code: transposed_conv (the input spread by the stride and padded,
the weight's channels swapped per group, flipped and spread by the dilation, then
a direct convolution) and zero_length_gemm (zeros of the output for mm, bmm,
addmm and baddbmm with an empty output, or K = 0 and no bias). lowering.py keeps
what is lowering: recording a conv's groups for the heuristic, the grouped conv
grid, and the conv decompositions, which stay before AOTAutograd so a backward
is derived from them (in post-grad the backward graph already holds
convolution_backward, which runs as an extern call on the CPU).

A 1-D transposed conv now runs: the lowering wrapper never matched it and it
fell to aten (convolution_overrideable not implemented). Helpers one rewrite uses
are its inner functions (histc's counts; the complex components, their judge and
their rewrite).

New tests: test_conv_transpose (2-D stride and output_padding, groups with
dilation, 1-D, batchless, and the graph after the pass) and test_zero_length_gemm
(mm, bmm, addmm with M, N or K zero, and the graph). conv2d, group_conv, matmul,
bmm, row_matmul, histc, complex_to_real, polar, patch_scope and addmm_residual
pass.
…ce tests are inductor/device.py

device_interface.py (Dynamo's device interfaces), triton_gpu.py (GPU_TYPES,
the one patch), device_codegen.py (scheduling,
wrapper, post-grad pass), device_op_overrides.py, choices.py (NPUChoices) and
template_heuristics.py, each named after the PyTorch registry it fills;
__init__.install() runs them in order, the device interface first. is_npu and
is_lowering_npu are tests, not registrations, read by autotune/ and the patches:
they are inductor/device.py. No behavior change.
…kernel_kwargs hook, not a constructor override

TritonNPUKernel.__init__ pinned blocks so every kernel Inductor made would hold
them; Inductor's own hook for a fixed config, InductorChoices.triton_kernel_kwargs,
sits where it makes them (create_kernel_choices), the kernel it emits and the
one its fusion benchmark times alike. NPUChoices answers it with pinned_blocks.

The only kernels made past that hook are combo kernels' parts, and npu makes
none: FOREACH is off, and combo_kernels is now set False with the reason (a
combo kernel picks its tensors by program id, which a TOG cannot time). So
kernel_metadata's combo_grid and _writes' sub-kernel walk go.

The same seven kernels (pointwise, softmax, column sum, layer norm, mm with a
reduction epilogue, a bf16 mean) get the same names and blocks before and after;
reduction_tiling, tuned_blocks_on_hit, cache_identity, patch_scope, reduce,
softmax, layernorm, pointwise, matmul_reduction, bmm_reduction and
custom_fused_kernel pass.
…user_kernel, as Inductor's own files are

scheduling.py keeps TritonNPUKernel, TritonNPUScheduling and _tile_source;
wrapper.py takes TritonNPUWrapperCodegen (Inductor's codegen/wrapper.py
counterpart); user_kernel.py takes a model's own Triton kernels' meta and compile
call (user_kernel_meta, user_kernel_compile, _user_kernel_writes). Moved as they
were.
…el's own: kernel_metadata.compile_call

define_kernel wrote the source between ''' quotes, so a ''' or a backslash in it
would have changed it before the compiler saw it; user_kernel_compile wrote it
as a literal. Both render compile_call's line now, the source as a literal.
…PE; bits from torch, no combo signature

- _DTYPE is TOKEN_DTYPE (Triton token -> torch name), public: user_kernel reads it.
- tiling's _DTYPE_BITS goes; an element's bits are torch's itemsize for its name.
- _signature_from_argdefs and its torch-dtype -> token table go: they rebuilt the
  signature of a combo kernel, which npu no longer makes. A kernel with no
  triton_meta now has untyped arguments, which compiler_input refuses by name.
(simulator/functional.py's numpy carriers are another fact and stay.)
…ogged, an untimed fusion is warned

- _buffer_numel: a layout that is not static is logged and has no span; a
  stride it could not read no longer becomes the product of the shape, which
  under-counts a gapped layout.
- collect_meta's numels catch what a symbolic size raises, not every error.
- benchmark_codegened_module warns before it scores a module it did not write
  as infinite (its fusion loses).
- verify.enabled reads the config without swallowing its errors.
Six files of 13 to 88 lines, all wiring and no decisions, read better as one:
registration/__init__.py is registration.py again (its history follows), each
file's install() a _register_<registry>() beside what it registers. No
behavior change.
…e section comment each, as registration does
…ir form

post_grad_pass records its rewrites in REWRITES as they register. The test
fails when a rewrite is missing from the module docstring's list (or out of
registration order) or has no section comment naming it, and when
registration's install() does not call every _register_* function in file
order, one has no section comment, or the docstring's list has a line short.
It reads the modules with ast and tokenize and needs no device. CLAUDE.md and
the post-grad guides state the form.
…under timing/; the next commit splits them by tool
… split out; the build's meta.json is compiler_input's

- functional/spike.py: Spike as this environment runs it (its spike and pk) through
  the compiler's launcher (runtime/spike.py, 14fb0ae), under the kernel object's
  run options; functional/__init__ keeps run(), tensors <-> .raw and replay.
- timing/gem5.py: gem5 over the cycle binary and the tables from its dumps;
  timing/__init__ keeps run(), run_togsim, write_cycle_tables and the
  per-launch files. CycleSimulator, a class around one function, is _simulate.
- store_meta and load_tuned_blocks, the build's meta.json a cache hit reads its
  tuned blocks from, are backend/compiler_input.py's, not timing's.
Docstrings list each package's parts.
…rs call (run, launch, run_cycle_binary); reorder only
- togsim.py imported numpy it no longer uses and set its logger between
  imports; get_core_freq had no caller.
- gem5.py's _GEM5_SIGNAL sits above _gem5_failure, which reads it.
…ves the frontend's tables

The frontend kept a copy of contract/kernel_object.py's NP_DTYPE (_NP_CARRIER),
and it had drifted: it carried fp8, and bool as numpy bool where the contract has
int8. functional's carriers now read the contract itself, so a dtype the compiler
adds needs no frontend edit, and one it lacks is refused by name.
kernel_metadata.TOKEN_DTYPE drops fp8 to match; fp8 comes back with the
compiler's own entries. bool's bits are the same either way (one byte, viewed,
never converted).
post_grad_pass.py held the pass, its rewrite form and every rewrite in one file. It is now
post_grad_pass/: __init__.py keeps the pass, PATTERNS, CALLS, REWRITES, register_rewrite,
fallback_route and the shared fake_value, and imports the families in registration order:
histc.py (histc), gemm.py (mm_row, addmm_row, gemm_zero_length), convolution.py
(convolution_transposed, convolution_1d) and complex.py (complex_real_pairs and its _REAL_PAIR
rules). The package docstring lists every rewrite by module, in that order.

Code moves unchanged, except: _val is fake_value and _count is count, since the family modules
import them; the pass's uuid hashes every module of the package, not one file; and
gemm_zero_length now registers before the convolutions (it follows addmm_row in gemm.py). They
match different targets, and mm_row and addmm_row still register before gemm_zero_length on the
same mm and addmm nodes.

test_module_form reads the section comment of each rewrite in whichever module defines it. The
guides (docs/post_grad_rewrite*.md) say where a new rewrite goes. test_histc, test_polar,
test_complex_to_real, test_conv_transpose, test_zero_length_gemm, test_conv_decomposition and
test_module_form pass.
The package of post-grad rewrites is named for the stage it runs at; the pass object
(pytorchsim_post_grad_pass), its log tag and CALLS keep their names. A rename: paths in the docs,
guides and test comments follow.
togsim.py's step-by-step comments, its commented-out Popen pipes and its trailing comments go, and
a bare except around closing the command FIFO is BrokenPipeError (the reader already exited; its
status is what shutdown reports). device_synchronize's docstring loses a timestamp it does not take.
The explanations worth keeping move into docstrings: verify's golden interpreter and its trace mode,
config's TORCHSIM_TARGET, and the generated spec's kernel() and reference(). config's logger,
functional's raw read and template_timing lose comments that restate the code.
generated_kernel_blocks reads a node's dtype with Inductor's maybe_get_dtype and skips only a read
whose name Inductor does not know (KeyError), not every exception. template_kernel_configs no longer
falls back to the generic configs, unlogged, when optimization_hint raises: that hint takes the
unbacked fallback itself and raises only for a complex size. verify catches the NotImplementedError
of an IR node with no mutation names and the RuntimeError of a missing buffer, as Inductor raises
them. test_matmul, test_softmax and test_layernorm pass; test_mlp under per-kernel verify fails its
Optimizer case as before this change (the golden of the foreach Adam graph fails either way).
…nplaced foreach as what it wrote

Inductor reinplaces Adam's functional _foreach_add into _foreach_add_, which returns nothing,
and leaves the getitems that read its result. The golden interpreter indexed that None and gave up
for the graph, after the in-place op had already run on the inputs: _to_cpu returned a CPU tensor
itself, not a copy, so the real optimizer state stepped twice and test_mlp's Optimizer case failed
under TORCHSIM_FUNCTIONAL_VERIFY_PER_KERNEL=1 (max abs diff 2.6e-4) while it passes without it.

_to_cpu now always copies, and an op whose schema marks its first argument written and that
returns None is that argument. test_verify_golden pins both on a hand-built graph (it fails before
this change); test_mlp under per-kernel verify passes 10/10, all 8 goldens computed.
test_conv_decomposition, test_conv_transpose, test_zero_length_gemm and test_custom_fused_kernel
emit kernels (17, 12, 2 and 5 here) and pass, so they join the allowlist and the matrix;
test_device_interface, test_module_form and test_verify_golden emit none and join the matrix only,
with the other system tests. Without this none of them gated a PR.
With min == max the range comes from the values. aten refuses one that is not finite (a NaN or an
inf in the input); the rewrite counted on it and returned wrong bins without a word. The rewrite now
declines that case, logged and counted as a fallback, so aten counts it and refuses as it does. An
integral input has no NaN or inf and stays on the device. MoE's histc gives its range and is not
affected. test_histc pins the finite, NaN and inf cases.
@student-Jungmin

Copy link
Copy Markdown
Collaborator Author

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

@student-Jungmin
student-Jungmin deleted the refactor/r441-8-cleanup 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