Skip to content

Studio ROCm: keep stored flash-attention verdicts from recompiling per bucket, and gate the CFG replica too - #14869

Merged
danielhanchen merged 5 commits into
mainfrom
fix-rocm-flash-bucket-recompile
Oct 23, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
fix-rocm-flash-bucket-recompile

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

Two follow-ups to the ROCm auto flash gate from #13792.

  1. Bucket recompiles. A traced attention call computed its power-of-two timing bucket with a loop over the symbolic query length, so every bucket edge became a guard. A prompt whose length crossed into a neighbouring bucket recompiled the DiT even when both buckets had the same verdict and were already timed (stored on disk from an earlier session). With dynamic=True and Studio's dynamic text inputs, joint-attention models change sequence length with prompt length at a fixed resolution, so this can hit the 2nd and later prompts (for example Qwen-Image at 720x1280: 3600 image tokens plus a long prompt crosses 4096).
  2. CFG replica bypass. The gate is thread-local state set by root forward hooks. build_replica clears the copy's root hooks and _ReplicaWorker runs the copy on another thread, so the gate was never set there and the replica ran flash at sizes the source had rejected (the source ran native).

Fix

  • diffusion_attention.py: the traced path asks a constant-marked helper (_rocm_flash_traced_segments) for the query-length axis as segments: a run of neighbouring buckets with the same known verdict is one segment, an untimed bucket is its own. The traced code compares the length only against segment ends, so it guards only where the route changes or an untimed bucket starts. Known verdicts come from memory, this load's admissions or the stored timings (_rocm_flash_geometry_admitted(..., stored_only = True)), never a new probe. Untimed buckets are timed at trace time exactly as before. Self / joint attention (keys as long as queries) walks one axis; cross attention keeps its key bucket as before.
  • diffusion_multigpu.py / diffusion_attention.py: build_replica calls track_rocm_flash_replica, which gives the replica its own gate hooks and the source's gate re-keyed to the replica's card, so its buckets are judged (and timed when unknown) on that card.

Tests

CPU only, stub attention kernels, real torch.compile(dynamic = True, fullgraph = True), torch 2.12.1.

Per-prompt cumulative graph counts, lengths 4352, 9000, 17000, 5000, 9500, all buckets already timed:

Case main this PR
all buckets flash 1, 2, 3, 3, 3 1, 1, 1, 1, 1
8192 bucket native 1, 2, 3, 3, 3 1, 2, 3, 3, 3 (route really changes)
fresh, nothing timed beyond 4096 1, 2, 3, 3, 3 1, 2, 3, 3, 3 (each new bucket must be timed)

Routes match the eager path in every case. CFG replica at 9000 tokens with the 8192 bucket rejected: source native, replica flash on main; source native, replica native on this PR.

  • New test_compiled_lengths_across_known_buckets_guard_only_where_the_route_changes[False] and test_cfg_replica_keeps_the_rocm_flash_gate_on_its_worker_thread fail on main and pass here; the [True] case and the existing test_compiled_dynamic_lengths_recompile_per_bucket_not_per_length pass on both.
  • test_diffusion_attention_rocm_flash.py: 187 passed.
  • Attention, CFG and multi-GPU suites (17 files): 623 passed, 11 skipped, 2 failed; both failures (test_an_imported_old_kernels_is_not_papered_over, test_execution_device_reports_the_primary_of_a_split_pipeline) fail identically on main.

Not covered

  • No AMD hardware ran. Kernels are stubs; no ROCm flash speed, accuracy or real compiled run was measured.
  • The first visit to an untimed bucket still recompiles, since the bucket must be timed before its route is known.
  • A replica on a different card times its own buckets on first use; that live probe was not run on real multi-GPU ROCm.
  • Z-Image's run_pair still declines CFG pairing when root hooks are present, so with ROCm auto flash it stays serial (perf only, unchanged).
  • mark_dynamic ranges spanning an untimed bucket edge still raise ConstraintViolationError; Studio does not call mark_dynamic.

…kets and gates CFG replicas

A traced attention call now guards its query length only on the edges where the
known route changes (or an untimed bucket starts), so prompt lengths that cross a
power-of-two bucket with the same stored verdict reuse the compiled graph instead
of recompiling. Known verdicts come from memory, this load's admissions or the
persisted timings, never a new probe.

A CFG replica is built with its root hooks cleared and runs on its own worker
thread, so the thread-local gate was never set there and its calls ran flash at
sizes the source had rejected. build_replica now gives the replica its own hooks
and the source's gate keyed to the replica's card.
@danielhanchen danielhanchen self-assigned this Oct 23, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-23T03:53:32.177920Z 2d896e6 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c783eaf5ce

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

) # the copied handles point at the source's hooks
except Exception: # noqa: BLE001
return
_hook_rocm_flash_dit(replica)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reset the replica’s deferred buckets between generations

When a secondary-card timing probe is deferred because the live forward leaves insufficient memory, _hook_rocm_flash_dit records that bucket in the replica's private deferred set. The replica is not included in the pipe's _rocm_flash_dits registry, so begin_attention_run resets only the source DiT's set; every later generation on this replica therefore returns "timing deferred" without retrying the probe and permanently uses native attention for that bucket. Register the replica for lifecycle resets or otherwise clear/share its deferred state at each generation boundary.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: the CFG replica outlives a generation but was not in the pipe's registry, so a bucket deferred on it was never retried. Live replicas are now tracked weakly on their source DiT and reset with it in begin_attention_run, with a test that defers on the first generation and re-probes on the next.

The CFG replica is kept across generations but was not in the pipe's
ROCm flash registry, so begin_attention_run never cleared its deferred
set and a bucket deferred once stayed native forever on the replica.
Track live replicas weakly on their source DiT and reset them with it.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2e68565d21

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

pass
for source in _rocm_flash_dits(getattr(state, "pipe", None)):
replicas = getattr(source, _ROCM_FLASH_REPLICAS_ATTR, None)
for dit in [source, *(list(replicas) if isinstance(replicas, weakref.WeakSet) else ())]:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include CFG replica routes in the final tally

When CFG parallel sends branches to the secondary card and that card has a different bucket verdict, these hooks record those calls in the replica's independent tally, but rocm_flash_ran() aggregates only _rocm_flash_dits(pipe), which contains the source DiTs and not their weakly tracked replicas. Consequently, a generation where the source uses flash while the replica routes to native can still be reported as “flash_attn on every attention call”; include the live replicas when aggregating the generation report, as is already done here when resetting their state.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: the replica's routes landed on its own tally, which the generation report never read, so a native replica branch could still be reported as flash on every call. The report now sums the source DiTs and their live replicas (the same set begin_attention_run resets), with a test where the source runs flash and the replica native.

Comment on lines +2179 to +2180
gate = {(card, *shape[1:]): found for shape, found in gate.items()}
setattr(replica, ROCM_FLASH_GATE_ATTR, gate or None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Refresh replica gates when the backend is reapplied

If a kept pipe builds its replica under ROCm auto flash and later reapplies explicit flash (or switches UNSLOTH_DIFFUSION_ROCM_FLASH to forced mode), apply_attention_backend() clears the source's gate but _track_rocm_flash_calls() leaves existing replicas untouched. Because this line installs a snapshot of the old auto gate, subsequent secondary-card branches continue routing rejected buckets to native even though the newly requested mode is ungated; propagate backend reapplications to live replicas or invalidate the replica.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not reachable in Studio: the only place a kept pipe has its backend reapplied is the deferred speed profile, and that path calls invalidate_cfg_replica right after it, so the next guided step rebuilds the replica from the source and copies the new gate (or none). The UNSLOTH_DIFFUSION_ROCM_FLASH mode is read when the backend is applied at load, so changing it mid-session does not reapply anything either. Every other apply_attention_backend call runs at load time, before any replica exists.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bfde231600

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1053 to +1057
with _ROCM_FLASH_GATE_LOCK:
while bucket < _ROCM_FLASH_SEGMENT_LIMIT:
ok = _rocm_flash_bucket_known(
device, dtype, geometries, bucket, kv_bucket or bucket, b_bucket
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Cache absent verdicts while building traced segments

When ROCm auto mode compiles a normal DiT and its disk cache contains only the few buckets previously used, this loop revisits every absent bucket for every traced attention call. Because _rocm_flash_bucket_known() caches only found verdicts, each miss calls _rocm_flash_geometry_admitted() again, which recomputes the toolchain fingerprint and reparses the same JSON cache; scanning up to the segment limit therefore multiplies filesystem and fingerprint work across all transformer blocks and can substantially increase compile latency. Cache the loaded verdict table or memoize absent slots for the current toolchain/baseline.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed: a stored-only lookup that found nothing recomputed the toolchain key and re-read the JSON cache, once per absent bucket per traced call. Absent slots are now remembered after their first stored-only lookup (cleared with the other verdicts when the SDPA baseline moves, and dropped as soon as the bucket is timed), so tracing reads the store once per slot; a test counts the reads.

) # the copied handles point at the source's hooks
except Exception: # noqa: BLE001
return
_hook_rocm_flash_dit(replica)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Remove replica hooks before dropping the replica

When CFG invalidates or rebuilds a replica, this hook installation can keep the entire old model alive: the replica owns its pre-hook, while that hook captures the replica strongly through the dit = dit default argument. CfgParallelRouter.drop_replica() only clears its reference and does not remove these handles, so the resulting cycle can retain all secondary-card parameters until a nondeterministic cyclic-GC pass; an immediate rebuild can consequently fail the free-memory check or OOM even though the old replica was nominally dropped. Explicitly remove the replica hooks during teardown or make the hook refer to its _module argument/a weak reference.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: the pre-hook's default argument held the DiT, and the DiT's hook dict holds the hook, so a dropped replica stayed alive until a cyclic collection. The hook now uses the module it is called on and captures nothing, so dropping the replica frees it by reference counting; a test hooks a module and checks it is freed with the cyclic collector disabled.

…egments read each absent stored verdict once

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 2d896e6d13

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 1f55767 into main Oct 23, 2026
2 of 34 checks passed
@danielhanchen
danielhanchen deleted the fix-rocm-flash-bucket-recompile branch October 23, 2026 04:56
danielhanchen added a commit that referenced this pull request Oct 27, 2026
…y length on the key length (#15458)

#14869 added `joint = kv == seq` to `_rocm_flash_length_reason` in
`studio/backend/core/inference/diffusion_attention.py`, to tell self /
joint attention (one length symbol) from cross attention. In a traced
graph, cross attention has independent query and key length symbols, and
evaluating that comparison makes Dynamo install a guard on it, for
example `L['q'].size()[1] != 6000`. Two things follow:

- Cross attention whose query length crosses the key length recompiles
even though the routing bucket is unchanged.
- A query length marked dynamic over a range that spans the key length
fails with `ConstraintViolationError`.

The traced path now asks `statically_known_true(kv == seq)`. Self /
joint attention shares one symbol, so it is still treated as joint, and
cross attention no longer gets a guard. `statically_known_true` is
resolved outside tracing when the dispatch guard installs, and is used
only when this torch's Dynamo traces it in graph (torch 2.10, 2.13,
2.14). On torch 2.6, Dynamo cannot trace it, so the direct comparison
stays there, guard included. The stored-bucket reuse for self attention
from #14869 depends on that comparison.

Cross attention, key length 6000, query lengths 5000 / 6000 / 7000 /
5500 (same admitted bucket), `torch.compile(dynamic=True,
fullgraph=True)`, kernels stubbed, CPU:

| torch | check | before #14869 | main | this PR |
|---|---|---|---|---|
| 2.13 | cumulative graphs | 1, 1, 1, 1 | 1, 2, 2, 2 | 1, 1, 1, 1 |
| 2.13 | query marked dynamic [4500, 7500], key static | compiles |
`ConstraintViolationError` | compiles |
| 2.14 | cumulative graphs | 1, 1, 1, 1 | 1, 2, 2, 2 | 1, 1, 1, 1 |
| 2.14 | marked dynamic | compiles | `ConstraintViolationError` |
compiles |

Two tests in `test_diffusion_attention_rocm_flash.py` cover both checks.
They are skipped on a torch whose Dynamo cannot trace
`statically_known_true`. The file gives 2 failed, 191 passed on main and
193 passed with this PR (torch 2.13). Nothing here ran on ROCm hardware.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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