Skip to content

[tunableop] tune a range of sizes of a GEMM's dynamic dim - #201768

Open
ruddhic wants to merge 96 commits into
gh/ruddhic/3/basefrom
gh/ruddhic/3/head
Open

ruddhic wants to merge 96 commits into
gh/ruddhic/3/basefrom
gh/ruddhic/3/head

Conversation

@ruddhic

@ruddhic ruddhic commented Oct 22, 2026 •

Copy link
Copy Markdown

Stack from ghstack (oldest at bottom):

First consumer of the compile-time TunableOp worker, and the whole point of the
"tune" mode: widening what a tuning run records so runtime actually finds it.

A solution is keyed on an exact shape signature, so tuning only the traced shape
leaves runtime missing the moment the dynamic dim differs, which for these models
is almost always. When aten wins the autotune for a GEMM with a single dynamic dim,
this re-benchmarks it across a ladder of sizes of that dim so several signatures
land in the results file.

The ladder covers the GEMM variants TunableOp tunes: mm, addmm, bmm,
baddbmm and _scaled_mm. addmm and baddbmm take the bias first, so the
operands are read from a different position for those two.

The reduction dim K is never bucketed: a solution is only valid for the K it was
tuned at. That guard also rejects attention-style ops where one symbol spans both N
and K, where overriding the symbol would change two dims at once and fabricate
degenerate shapes.

The ladder walks the symbol, not the dim. A dim can be an expression such as
200*s, and stepping the dim itself through powers of two tunes sizes the dim can
never take, since no power of two is a multiple of 200. Walking s and evaluating
the expression yields 400, 800, 1600 ... instead, which are the values that actually
reach the kernel. For a bare-symbol dim the two are identical, so the common case is
unchanged.

The domain is the symbol's declared range, read via shape_env.bound_sympy(s). That
is what the symbol may take at runtime, unlike the traced hint. bound_sympy reasons
over var_to_range alone and ignores guards and runtime asserts, so it can be looser
than the true bound; looser is the safe direction here, since under-covering means a
runtime miss.

The "too small to be worth a tuning job" threshold of 8 is applied to the resulting
dim, not to the symbol. The two are only the same for a bare-symbol dim: for
200*s the smallest symbol values already give substantial GEMMs (s=2 is a dim of
400), so starting the walk at 8 would skip sizes runtime genuinely asks for.

Two ceilings, both anchored to what the model serves

A declared range reports what a symbol MAY take, not what it does, and on these nets
it carries almost no information: every symbol observed reports [2, 2**31-1]. So
the declared bound never binds, and whatever backstop sits behind it becomes the real
ceiling for every GEMM. _TUNABLEOP_MAX_DYN_SYM = 16384 is that backstop, replacing
a pair of constants that each failed in a different direction.

In symbol space, min(declared_hi, max(16384, sym_hint)). A genuinely narrow
declared range still wins; the cap only stops an uninformative one running away. It
is raised to the traced hint so the walk can always reach the size actually served.

In dim space, max(16384, served_dim). The symbol cap alone is not enough,
because it cannot see a multiplier: with s bounded at 16384, a 96*s dim still
reaches 1572864. A flat dim cap is not enough either -- it truncates legitimate
coverage, cutting a GEMM served at 294912 down to 12288. Anchoring the dim ceiling to
the dim's value at the traced hint gives a bound that cannot fall below what the
model actually runs, while still bounding the runaway case.

Each bucket's benchmark request is built by copying the winner's request and
rebuilding its tensor metas at that size, reusing Inductor's meta machinery instead
of reconstructing the GEMM by hand. Substituting the symbol into each size expression
is also what keeps an expression dim on values it can take, and it scales every other
dim built from the same symbol consistently. Deriving the strides the same way is not
safe: a stride expression is not a size-product formula in the dynamic symbol, so
substituting into a bare-symbol batch stride collapses it to that value instead of
value * inner_dims, producing overlapping metas whose backing buffers are far smaller
than the kernel will address. Strides are therefore recomputed dense in the tensor's
own fill order, taken from the traced real-size strides where outer dims genuinely
have the largest strides; taking the order from the overridden strides could reorder
dims and silently turn a plain GEMM into a transposed one.

Each bucket is a separate worker job, so a fault costs one size and restarts the
worker rather than killing the compile. The whole GEMM shares one deadline and skips
the remainder once it is spent; each submission is given the entire remaining budget
rather than a per-bucket slot.

The traced shape goes first, then the rest largest-first. The per-GEMM budget is
spent in order, so whichever end is walked last is the end dropped when it runs out.
Ascending order sacrificed the sizes nearest the shape actually served while
faithfully keeping 8, 16 and 32 -- observed on a K=39160 GEMM whose ladder stopped at
256 with the traced dim at 3072. Pure largest-first has the opposite failure: it can
spend the whole budget on the biggest sizes -- the likeliest to fault -- before
reaching the one size runtime is known to ask for.

The ladder can be turned off. TORCHINDUCTOR_AUTOTUNE_TUNABLEOP_LADDER=0 stops
it. At this commit Inductor then submits no tuning at all: the traced shape is covered
only by TunableOp's own in-process path, which needs PYTORCH_TUNABLEOP_ENABLED set in
the compiling process. The ladder is nearly all of the tuning cost -- on the heavier
nets the difference between minutes and hours -- and it exists so that cost can be
skipped, and so what the ladder actually buys can be measured by diffing runtime
misses with and without it.

A log.debug line per bucket records its wall time and status. It is the only
record of what a bucket costs when it succeeds, since the existing logs report
failures only, and that curve is what any future per-bucket budget would have to be
sized against.

One behaviour change outside the ladder itself.

A ladder bucket that times out or crashes is retried at most
_TUNABLEOP_MAX_BUCKET_ATTEMPTS (2) times per process, then left alone. Without the
cap a reproducibly hanging rung is never recorded, so every identical layer retries
it on a fresh per-GEMM budget and spends it before reaching the rungs that work.

Note that tuning happens while lowering, so a warm FxGraphCache serves the graph and
the ladder never runs: a tune pass has to start from a cold cache, or set
force_disable_caches. #201769 lifts that constraint with a tune-mode bypass in
CacheabilityValidator.

Inert unless autotune_tunableop_mode is set to "tune"; it defaults to "off", so no
existing compile changes behaviour.

Differential Revision: D116493595

Differential Revision: D116493595

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:

This PR adds a "ladder" to TunableOp's compile-time "tune" mode: when an aten
GEMM with exactly one dynamic symbol wins autotune, Inductor re-tunes it at a
range of values of that symbol, so that more shape signatures end up in the
results file. Recommendation: Approve. Last round's only blocking finding (the
addmm_dtype fixture) is fixed, and every remaining point is non-blocking.

Findings (6):

[minor] torch/_inductor/tunableop.py:557
fp32-output dtype variants use budget but record nothing (non-blocking; carried
over, not answered). With fp16/bf16 inputs and an fp32 output, `mm_dtype`,
`bmm_dtype` and `addmm_dtype` (ROCm) dispatch to `gemm`/`bgemm<scalar_t, float>`
or the non-Lt `launchGemmCublas<scalar_t, float>` path. Those paths skip
TunableOp (`CUDABlas.cpp:980, :993, :1563, :1576`, "TODO: Support tuning").
Every ladder bucket for these GEMMs still runs in the worker and spends per-GEMM
budget without adding a row. `kernel/mm.py:645` and `bmm.py:361` create the
`_dtype` choices whenever `out_dtype` is passed, even when it equals the input
dtype, and that case does tune. So filter in `maybe_range_pretune` on
reduced-precision input with fp32 output instead of removing the choice names.

[minor] torch/_inductor/tunableop.py:990
Two warnings repeat once per GEMM (non-blocking; carried over). The "stopped
after %d/%d sizes" message logs at WARNING whenever the budget is at least 60 s
(`tunableop.py:988-997`). Buckets cut by the budget never reach `seen`, so
identical layers warn again. The `log.warning(..., exc_info=True)` on a failed
bmreq rebuild (`tunableop.py:910-915`) returns before the memo, so it also fires
on every repeat. Follow the dedup pattern in `_warn_fault_once`
(`tunableop.py:90-95`).

[minor] torch/_inductor/tunableop.py:637
`_is_densely_packed` reimplements an existing helper (non-blocking). It infers
the stride order, rebuilds dense strides and compares them while skipping size-1
dims. `torch._prims_common._is_non_overlapping_and_dense_or_false(sizes,
strides)` already does this, and Inductor already uses it
(`codegen/cpp_wrapper_cpu_array_ref.py:11`). For concrete hints the results
match in every case the comments call out: the padded `[s,256]/[300,1]` operand,
rowwise `scale_b` `[1,N]/[1,1]`, column-major operands and stride-0 dims. They
differ only for numel 0, which backed hints of at least 2 never reach. Suggested
fix: `return _is_non_overlapping_and_dense_or_false(real_sizes, real_strides)`.

[minor] test/inductor/test_tunableop_pretune.py:498
No CI job this PR triggers runs the `addmm_dtype` fix (non-blocking). The test
is `skipIf(torch.version.hip is None)`, and the PR's labels trigger no ROCm test
job: `pull.yml` only builds ROCm, `inductor.yml`/`torchtitan.yml` have no ROCm
jobs, and `inductor-rocm-mi200/mi300` need `ciflow/inductor-rocm-*`. That is how
last round's fixture bug went unnoticed. Nothing in `maybe_range_pretune` is
HIP-specific for this choice apart from its membership in
`_TUNABLEOP_GEMM_CHOICES`, which is read at call time. Suggested fix: patch
`tunableop._TUNABLEOP_GEMM_CHOICES | {"addmm_dtype"}` and drop the HIP skip,
ideally by adding `addmm_dtype` to `test_bias_first_ops_read_the_right_operands`
(line 192) so operand shapes are also checked. This also removes a
build-dependent skip from a `GENERIC` class (`test/REVIEW.md` Rule 3).
Alternatively, add a `ciflow/inductor-rocm-mi300` label.

(2 more not shown, see the review run)

Reviewed commit: d51a80b (NOT the current head 60c457d)

Review run

🐛 Report a bad review

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/201768

Note: Links to docs will display an error until the docs builds have been completed.

❌ 1 Unclassified Failure

As of commit 60c457d with merge base 836c141 (image):

UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@linux-foundation-easycla

linux-foundation-easycla Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

@pytorch-bot

pytorch-bot Bot commented Oct 22, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
@github-actions
github-actions Bot dismissed stale reviews from themself November 7, 2026 02:51

Withdrawn: the automated review of d51a80b found nothing blocking.

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request meta-exported module: inductor ready for review Automated review passed, ready for a final review by a maintainer.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants