Repository navigation
Studio ROCm: keep stored flash-attention verdicts from recompiling per bucket, and gate the CFG replica too - #14869
Conversation
…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.
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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]
|
@codex review |
There was a problem hiding this comment.
💡 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 ())]: |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| gate = {(card, *shape[1:]): found for shape, found in gate.items()} | ||
| setattr(replica, ROCM_FLASH_GATE_ATTR, gate or None) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…on report [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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 | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…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>
Problem
Two follow-ups to the ROCm auto flash gate from #13792.
dynamic=Trueand 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).build_replicaclears the copy's root hooks and_ReplicaWorkerruns 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_replicacallstrack_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:
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.
test_compiled_lengths_across_known_buckets_guard_only_where_the_route_changes[False]andtest_cfg_replica_keeps_the_rocm_flash_gate_on_its_worker_threadfail on main and pass here; the[True]case and the existingtest_compiled_dynamic_lengths_recompile_per_bucket_not_per_lengthpass on both.test_diffusion_attention_rocm_flash.py: 187 passed.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
run_pairstill declines CFG pairing when root hooks are present, so with ROCm auto flash it stays serial (perf only, unchanged).mark_dynamicranges spanning an untimed bucket edge still raiseConstraintViolationError; Studio does not callmark_dynamic.