Repository navigation
Studio: pick ROCm flash attention by a whole-block timing probe instead of a model table - #13792
Conversation
… probe, not a family table auto on ROCm with a verified flash_attn now yields a candidate that apply_attention_backend resolves by timing one synthetic DiT block (LayerNorm, QKV, attention, out proj, 4x MLP) at the loaded model's attention geometry with native SDPA vs flash_attn, admitting flash only when it is at least 3% faster and the block output matches (rel L1 <= 2e-2). Cached per (device, dtype, geometry). Replaces the flux.2-klein / gfx11 table. Kill switch UNSLOTH_DIFFUSION_ROCM_FLASH=auto|0|1 (0: auto never picks flash; 1: verified is enough, no timing).
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. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4bd4ab8756
ℹ️ 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".
| continue | ||
| if not counts: | ||
| return None | ||
| return max(counts.items(), key = lambda kv: kv[1])[0] |
There was a problem hiding this comment.
Probe every attention geometry before enabling flash
For a pipeline containing multiple attention geometries, this selects only the most frequent tuple and discards the rest, but apply_attention_backend subsequently installs flash on every denoiser. A less-common geometry—such as one in a secondary transformer_2/unconditional_transformer or a minority attention block—can therefore be unsupported, inaccurate, or slower while the common geometry admits flash; the existing on-card check only exercises its fixed tiny shape and will not catch that, so the failure can surface during generation. Probe all geometries that will receive the backend (and include them in the cache decision), or decline automatic flash for heterogeneous pipelines.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 295baef. The probe now collects every distinct (hidden, heads, head_dim) among the attention modules of every denoiser (transformer_2 and minority blocks included), times each one, and admits flash only if all of them win with matching output. Each geometry has its own cache entry keyed on (device, dtype, hidden, heads, head_dim); the first losing geometry ends the check, and its cached answer keeps later loads native without timing again. Covered by test_every_attention_geometry_is_timed, a two-DiT pipeline where the minority geometry is timed and its loss keeps the load native.
| F.gelu(F.linear(F.layer_norm(x2, (hidden,)), w_fc1), approximate = "tanh"), w_fc2 | ||
| ) | ||
|
|
||
| arms = {"native": native, "flash": lambda q, k, v: flash_attn_func(q, k, v)} |
There was a problem hiding this comment.
Reject auto flash for masked attention paths
When a newly eligible model reaches attention with a non-null mask, this maskless synthetic call can admit flash even though the pinned Diffusers 0.41 backend explicitly raises on attn_mask (Diffusers source). This is reachable, for example, for HunyuanVideo 1.5 batches whose prompts retain mixed padding: _HunyuanNullMaskProcessor deliberately delegates those calls to the stock masked processor, so an otherwise successful load now fails during generation. The automatic probe must account for masked calls or keep such pipelines on native/varlen attention.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 295baef. Engaging flash on ROCm (auto, UNSLOTH_DIFFUSION_ROCM_FLASH=1, or an explicit request) now installs a dispatch guard on diffusers' flash backend, the same guard the FA4 path already uses: any call that carries an attn_mask is routed to native SDPA instead of reaching the FA2 kernel, which raises on masks. A HunyuanVideo 1.5 mixed-padding batch going through the stock masked processor therefore runs native for those calls and flash for the maskless ones. If the diffusers registry is not where we expect and the guard cannot be installed, auto stays native. On main, auto flash was limited to the flux.2-klein family table, so no masked family could reach it before this PR. Covered by test_auto_flash_engages_only_with_the_mask_guard and test_rocm_flash_guard_routes_masked_calls_to_native.
…sked calls native auto flash on ROCm is now admitted only when every distinct (hidden, heads, head_dim) among the attention modules of every denoiser DiT (transformer_2 and minority blocks included) wins the whole-block timing, each cached per (device, dtype, geometry). Engaging flash on ROCm (auto, =1, or an explicit request) installs a dispatch guard on diffusers' flash backend, the same one FA4 uses, so a call with attn_mask (e.g. a HunyuanVideo 1.5 mixed-padding batch) runs native SDPA instead of raising; if the registry cannot be guarded, auto stays native.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 000454dad6
ℹ️ 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".
| continue | ||
| try: | ||
| for module in modules(): | ||
| heads = getattr(module, "heads", None) |
There was a problem hiding this comment.
Recognize
num_heads when collecting attention geometries
When loading Krea 2 on ROCm, every Krea2Attention module is skipped because it exposes num_heads, not heads (Diffusers v0.41.0 source). Consequently _dit_attention_geometries() returns no geometry and _rocm_flash_block_admitted() always rejects the candidate, so auto can never select flash for this supported pipeline even when the kernel passes the probe and is faster. Fall back to num_heads (and account for both naming conventions) when reading these modules.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 5e9dd27. Geometry collection now falls back to num_heads when a module has no integer heads attribute, so Krea2Attention (num_heads, to_q of hidden x hidden) yields its (hidden, heads, head_dim) and is timed like the others. Covered by test_num_heads_attention_modules_are_measured.
|
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". |
The auto ROCm flash admission timed one synthetic DiT block on every load of a geometry, and only kept the answer in memory. The verdict now persists as JSON under the Studio cache (diffusion_rocm_flash/), the same pattern as the INT8 GEMM latency gate: one file per toolchain, keyed by card name + gfx arch, torch, HIP, flash_attn version, install path and backend (CK or Triton), the probe version and a hash of the timer source; entries per dtype, geometry and token count. A restart reads the stored timings and re-derives the decision without timing. A probe error is never stored, a torn or mismatched file is re-timed, writes are locked and atomic (temp file + os.replace), and an unwritable cache only costs the timing. UNSLOTH_DIFFUSION_ROCM_FLASH=0|1 never reads or writes the file. UNSLOTH_DIFFUSION_ROCM_FLASH_CACHE_DIR moves 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: 043f42d287
ℹ️ 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".
| f"flash_attn{fa_version}", | ||
| os.path.dirname(os.path.realpath(fa.__file__)), | ||
| backend, |
There was a problem hiding this comment.
Fingerprint rebuilt flash-attn binaries in the cache key
When a user rebuilds the DAO ROCm package from a different commit or with different compiler flags but installs it at the same location, its reported version and these three key fields commonly remain unchanged. After restart, _rocm_flash_geometry_admitted() therefore reuses the previous timing verdict without exercising the new geometry-specific kernel; the small import-time probe only covers a fixed 64-wide shape, so a newly slower or broken target-shape kernel can still be selected for generation. Include a fingerprint or mtime of the loaded CK/Triton extension (or a source/build revision) so replacing a custom build forces re-timing.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in aeae265. The persisted key now includes a fingerprint (path, size and mtime_ns) of the flash_attn files this process actually loaded: flash_attn, flash_attn.flash_attn_interface and the module bound to flash_attn_interface.flash_attn_gpu (the CK .so, or every .py beside the Triton backend). Before the extension is loaded, the spec origin of flash_attn_2_cuda is used. It only calls stat. The CK vs Triton label now follows flash_attn_interface.USE_TRITON_ROCM when present, so the interface's own CK-to-Triton fallback is keyed correctly. The probe version is bumped, so verdicts already on disk are re-timed. Tests: test_rebuilt_flash_attn_binary_changes_the_key (CK and Triton, content or mtime) and test_rebuilt_flash_attn_binary_forces_retiming.
| F.gelu(F.linear(F.layer_norm(x2, (hidden,)), w_fc1), approximate = "tanh"), w_fc2 | ||
| ) | ||
|
|
||
| arms = {"native": native, "flash": lambda q, k, v: flash_attn_func(q, k, v)} |
There was a problem hiding this comment.
Exercise the Diffusers flash wrapper in the admission probe
For a manually installed ROCm build whose flash_attn_func(q, k, v) works but whose signature is incompatible with the pinned Diffusers wrapper, this direct call admits flash even though generation fails. The actual _flash_attention backend additionally passes keywords such as dropout_p, softmax_scale, causal, window_size, and return_attn_probs; neither this timing call nor the earlier tiny probe verifies that integration. Run the flash arm through dispatch_attention_fn(..., backend=FLASH) (with the installed mask guard) so API drift is rejected during admission rather than on the first generation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in aeae265. Both timing arms now go through dispatch_attention_fn(q, k, v, attn_mask=None, dropout_p=0.0, is_causal=False, backend=...), native and FLASH, with Studio's mask guard installed first, so the flash arm takes exactly the generation path (diffusers attention_dispatch.py passes dropout_p, softmax_scale, causal, window_size and return_attn_probs). The accuracy run, warm-ups and timed runs all use that path. Tests: test_block_timer_runs_on_cpu_shapes checks every flash call went through the diffusers wrapper with its keywords and through the guard; test_flash_attn_rejecting_the_diffusers_arguments_is_not_admitted checks a flash_attn_func(q, k, v) without those keywords stays native and nothing is recorded or written to disk.
| heads = getattr(module, "heads", None) | ||
| if not isinstance(heads, int) or isinstance(heads, bool): | ||
| # Krea 2 (and other newer diffusers attention classes) name it num_heads. | ||
| heads = getattr(module, "num_heads", None) |
There was a problem hiding this comment.
Keep masked-only Krea 2 attention on native
Fresh evidence from the pinned pipeline_krea2.py and Krea2Transformer2DModel.forward shows that the pipeline always passes prompt_embeds_mask, which becomes a non-null mask for the text-fusion and transformer-block attention calls. This new num_heads fallback lets Krea 2 pass geometry admission and be reported/tagged as flash, but _rocm_flash_reroute_reason() then sends every actual attention call back to native. Consequently users pay the multi-second probe and see a false flash status without receiving any acceleration; masked-only pipelines should remain native (or be evaluated with a mask-capable backend) instead of being admitted by the unmasked synthetic probe.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in aeae265, from the observed call pattern rather than a Krea 2 special case. Which calls carry a mask is only visible once the model runs, so the guard now counts calls the flash kernel actually takes next to the existing reroute counts. When auto admits flash, apply_attention_backend adds forward hooks to each DiT and compares the counts across one eager forward. If flash ran, the hooks are removed. If every call was rerouted for its mask, the DiT is switched to native, its flash tag is cleared, and its class (keyed with the diffusers version) is saved to masked_only.json in the probe cache folder, so later loads of that class skip the probe and report native. Compiled or graphed forwards are not counted, and the hooks remove themselves after 3 forwards with no eager attention calls. The first load of a masked-only class still pays the probe once; the status recorded at load is corrected in the DiT tag and the log after the first forward. Tests: test_masked_only_model_is_not_kept_on_flash[True/False], test_mixed_mask_model_stays_flash and test_explicit_flash_is_not_watched.
| for slot, rec in data.get("verdicts", {}).items(): | ||
| if isinstance(rec, dict) and all( | ||
| k in rec for k in ("native_ms", "flash_ms", "rel_l1", "finite") | ||
| ): | ||
| out[str(slot)] = rec |
There was a problem hiding this comment.
Reject malformed cached verdict values before using them
A syntactically valid but corrupted cache record is accepted as long as these four keys exist, even if values such as native_ms, flash_ms, or tokens are strings or nested objects. _rocm_flash_wins() catches its conversion error and returns false, but _log_rocm_flash_verdict() then converts the same values with float()/int() outside any fallback and aborts the model load instead of re-running the probe. Validate the field types and finiteness here, treating any invalid record as a cache miss.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in aeae265. _rocm_flash_record_ok validates records read from disk and fresh probe results: finite must be a bool, native_ms and flash_ms finite numbers above 0 (bools rejected), tokens a positive int, rel_l1 finite and non-negative (NaN only when finite is false), admitted a bool when present, and geometry positive ints. Any invalid record is a cache miss and is re-timed; an implausible fresh result is not stored and stays native. _log_rocm_flash_verdict formats values defensively and cannot raise. Tests: test_malformed_cached_record_is_retimed (23 cases: strings, nested objects, NaN, inf, negatives, zero, bools, wrong geometry, missing fields), test_non_finite_probe_verdict_is_stored_and_reused, test_implausible_probe_timing_is_native_and_not_stored and test_verdict_log_never_raises.
…ild, validates cached verdicts - The block timing runs both arms through diffusers' dispatch_attention_fn (flash behind Studio's mask guard), so a flash_attn_func that rejects the arguments diffusers passes is rejected at admission. Probe version 2: old stored verdicts are re-timed. - The persisted verdict key includes size and mtime_ns of the loaded flash_attn kernel files (CK extension or the Triton backend sources), so a rebuild in place re-times. The CK vs Triton label follows flash_attn_interface.USE_TRITON_ROCM. - Every cached field is type and range checked; a malformed record is a cache miss and the verdict log never raises. - A model whose attention calls all carry a mask never runs the flash kernel: after its first forward it is switched to native, untagged and remembered, so later loads skip the probe and stay native. [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: aeae2652ff
ℹ️ 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".
| elif routed > 0: | ||
| done() | ||
| _remember_rocm_flash_masked(key) | ||
| try: |
There was a problem hiding this comment.
Avoid blacklisting input-dependent masked calls
Fresh evidence in this revision is that the observed result is persisted by DiT class/version even though mask usage can vary per invocation. For HunyuanVideo 1.5, a mixed-padding batch takes the stock masked path, so its first forward records this key and permanently switches the DiT to native; a later single/unpadded batch would take _HunyuanNullMaskProcessor with attn_mask=None but can no longer use flash, and future loads of the same class are rejected before probing. Only remember this decision when mask usage is an invariant of the model, rather than after one input-dependent forward.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e152d66. The one-forward watcher, its permanent switch to native and masked_only.json are removed, and no cross-load memory is kept, since a mask being an invariant of a pipeline cannot be proven reliably. Masked calls still go native one by one and unmasked calls go flash, so a model whose mask depends on the input (HunyuanVideo 1.5 padded vs unpadded) keeps flash for its unmasked calls on every load. A masked-only model pays the 4096 probe once, after which the verdict is cached. Test: test_mixed_mask_model_keeps_flash_for_unmasked_calls_across_loads.
| ROCM_FLASH_ENV = "UNSLOTH_DIFFUSION_ROCM_FLASH" # auto (timed) | 0 (auto never picks flash) | 1 (verified is enough) | ||
| ROCM_FLASH_MIN_GAIN = 0.03 | ||
| ROCM_FLASH_BLOCK_TOL = 2e-2 # block output rel L1 (bf16 rounding ~1e-3) | ||
| ROCM_FLASH_PROBE_TOKENS = 4096 # 1024^2 image DiT sequence |
There was a problem hiding this comment.
Probe the sequence lengths the backend will serve
When the loaded pipeline generates anything other than this assumed 1024px image shape, the persisted admission verdict still comes exclusively from a batch-1, 4096-token self-attention block. Token counts depend on architecture, requested width/height, and video frame count—the Hunyuan path in this file documents production sequences around 50k tokens—so a flash win or successful launch at 4096 does not establish either performance or kernel viability for the actual calls, yet the backend remains pinned for the whole load. Include representative sequence/query-key lengths in admission or restrict automatic selection to workloads covered by the probe.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e152d66. Calls are now gated per sequence-length bucket (powers of two from 1024 to 32768, by the longer of query and key). Load still times the 4096 bucket per geometry; any other bucket is timed, for both speed and accuracy, the first time an uncompiled call of that length arrives, and persisted in the same cache. A failed bucket probe (for example an OOM) keeps that bucket native for the rest of the process without retrying every call, and an untimed bucket runs native during compile tracing or CUDA graph capture. Explicit flash requests and UNSLOTH_DIFFUSION_ROCM_FLASH=1 are not gated. Tests: test_unprobed_long_bucket_does_not_inherit_the_4096_verdict (a 27k-token call is timed in its own bucket and runs native there while 4608 tokens stays flash), test_length_buckets, test_bucket_probe_error_stays_native_without_retrying_every_call, test_unprobed_bucket_under_capture_runs_native_untimed, test_bucket_verdicts_persist, test_symbolic_length_never_specialises and test_explicit_flash_is_not_length_gated.
| ref = block(native).float() | ||
| got = block(arms["flash"]).float() | ||
| rel = float((got - ref).abs().mean() / ref.abs().mean().clamp_min(1e-12)) | ||
| finite = bool(torch.isfinite(got).all()) |
There was a problem hiding this comment.
Compare attention outputs before admitting flash
When a ROCm kernel is incorrect only at the target geometry, the fixed tiny kernel probe can pass and this check can still admit it because got and ref are compared only after adding the identical input residual and passing both through the same FFN/residual path. With random 4096-token attention the attention contribution can be small relative to that common residual, so even a severely wrong attention result can remain below the 2% block-relative threshold and be cached as safe, after which real generations use the faulty kernel. Compare the raw attention outputs for each geometry (and use the block only for timing), or retain an end-to-end accuracy gate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e152d66. The accuracy check now feeds the same q, k, v into native SDPA and into flash, both through diffusers' dispatch_attention_fn, and admits flash only if the attention output's relative L1 error is at most 2e-2 and its largest absolute error over the largest absolute output is at most 5e-2. The synthetic block is used only for timing (its difference is kept as block_rel_l1 for diagnostics). The probe version is bumped and records without the new field are rejected, so every stored verdict is re-timed. Tests: test_wrong_attention_is_rejected_though_the_block_would_pass (a flash returning attention 20% too large at a real DiT shape moves the block output about 1.7%, which the old check accepted; attention rel L1 is 0.20 and it is now rejected) and test_max_abs_error_alone_rejects.
| dit.set_attention_backend(ATTN_NATIVE) | ||
| except Exception as exc: # noqa: BLE001 - the guard keeps routing it native anyway | ||
| _warn(logger, ATTN_NATIVE, exc) | ||
| try: | ||
| setattr(dit, ATTENTION_BACKEND_ATTR, None) | ||
| except Exception: # noqa: BLE001 |
There was a problem hiding this comment.
Update load state when the watcher falls back
Fresh evidence in this revision is that this fallback clears only the DiT's tag, while both loaders have already copied the returned "flash" value into their load state and resolved record before any forward occurs. After a masked-only first forward switches the module to native, status responses and request diagnostics therefore continue reporting flash, and video residency calibration is keyed as flash despite measuring native execution. Propagate the observed fallback to the owning state/resolved record, or defer publishing the engaged backend until the watcher has decided.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e152d66. Hooks on each DiT count the calls that ran flash and the calls rerouted to native with their reason, and a new sync_attention_state sets the owning state's attention_backend from those counts (flash if any call ran flash, otherwise native) and updates the resolved record's value and reason, for example 'ROCm flash_attn on 12 of 20 attention calls; the rest ran native SDPA (attn_mask: 8)'. It runs in image generate() before the recipe is built, at the start of video generate() before the residency calibration key is computed, and in both status() methods. Compiled and graphed calls are not counted, so status keeps the load-time value until an uncompiled call has run. Test: test_reported_backend_follows_what_ran (masked-only, unmasked and mixed runs).
…reported from what ran - Accuracy compares the raw attention output (flash vs native SDPA through the same diffusers dispatch path): rel L1 plus max abs error over max abs output. The block is used for timing only, so a wrong attention the residual and FFN would hide is rejected. - Calls are gated per power-of-two sequence length bucket (1024 to 32768, by the longer of query and key). The load times the 4096 bucket; any other bucket is timed on its first eager call and persisted like the load verdict. An untimed bucket runs native under compile or graph capture, and a dynamic-shape compile never reads the length. - The masked-only memory is removed. Masked calls keep running native call by call and unmasked ones flash; a per-DiT tally of what ran drives the reported backend, the resolved record, recipes and the video calibration key (sync_attention_state). - Probe version 3: older stored verdicts are re-timed. [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: e152d663a8
ℹ️ 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".
| if native == 0: | ||
| return "flash", "ROCm flash_attn on every attention call" | ||
| if flash == 0: | ||
| return None, f"ROCm flash_attn admitted, but every attention call ran native SDPA ({why})" | ||
| return "flash", ( | ||
| f"ROCm flash_attn on {flash} of {flash + native} attention calls; the rest ran native SDPA ({why})" |
There was a problem hiding this comment.
Reset the execution tally for each generation
Fresh evidence in the replacement reporting logic is that each hook adds deltas to a lifetime tally, while this function reports flash whenever that tally contains any flash call. After one unmasked generation uses flash, a later masked-only generation therefore still reports flash in status and image recipes, and video residency remains keyed as flash even though every call in the current run used native SDPA. Reset or snapshot the tallies at each generation boundary so the decision reflects the run being reported.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 61dce01. A new begin_attention_run(state) marks the generation boundary: it settles the load state on what the previous run executed, then zeroes the per-model attention tally, so status, the image recipe and the video calibration key describe one run rather than a lifetime total. Image generate() calls it right after the active state is published (the existing sync before the recipe then reports this run), and video generate() calls it at the start, before the residency calibration key is computed. Tests: test_each_generation_reports_its_own_calls (a flash run, then a masked-only run reporting native with attn_mask: 2, then flash again) and test_both_generate_paths_mark_the_generation_boundary (AST check of both generate functions).
| hiddens = _ROCM_FLASH_GATED.get(shape) | ||
| if not hiddens: | ||
| return None |
There was a problem hiding this comment.
Scope length gating to the auto-selected pipeline
After any auto-selected model registers a geometry, _ROCM_FLASH_GATED retains it process-wide and this lookup applies it to every later ROCm flash call with the same device, dtype, head count, and head dimension. Consequently, loading another model with an explicit attention_backend=flash or UNSLOTH_DIFFUSION_ROCM_FLASH=1 can still benchmark or reroute its calls to native if an earlier auto model shared that shape, contradicting the intended timing bypass. Associate the gate with the active DiT/load or explicitly disable stale gates for forced selections.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 61dce01. The process-wide _ROCM_FLASH_GATED registry is gone. An auto admission stores its gate on the DiTs it admitted, and that DiT's forward hooks make the gate active only while that DiT runs (the post hook uses always_call=True, so a forward that raises never leaves it active). Every apply_attention_backend call clears the gate first, so re-applying explicit flash disarms it. A model loaded with explicit flash or UNSLOTH_DIFFUSION_ROCM_FLASH=1 is never timed, gated or rerouted by length, whichever model loaded first. Tests: test_explicit_flash_is_never_length_gated (both load orders, both kinds of explicit selection), test_reapplying_explicit_flash_disarms_the_gate and test_failed_forward_does_not_leave_its_gate_active.
| def _rocm_flash_bucket(tokens: int) -> int: | ||
| """Largest power of two <= tokens, clamped to [ROCM_FLASH_MIN_BUCKET, ROCM_FLASH_MAX_BUCKET].""" | ||
| tokens = max(int(tokens), 1) | ||
| return max(ROCM_FLASH_MIN_BUCKET, min(ROCM_FLASH_MAX_BUCKET, 1 << (tokens.bit_length() - 1))) |
There was a problem hiding this comment.
Probe lengths above the 32768-token cap
Fresh evidence after the sequence-length fix is that every call above 32768 tokens is still mapped to a synthetic 32768-token probe; the tests explicitly include the roughly 50k-token production case. A ROCm flash build can pass or outperform native at 32768 yet fail, run out of workspace, become inaccurate, or lose at the actual 50k length, after which the guard launches that untested kernel during generation. Preserve the actual long length in the admission key/probe, or route lengths beyond the validated maximum to native.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 61dce01. Buckets are now open-ended powers of two (1024, 2048, ... 65536, 131072 and beyond, no cap); each call goes to the bucket of the longer of its query and key, which is timed once at its lower edge on first use and stored like the load-time verdict, so nothing maps to a capped bucket. A failed probe, out of memory included, keeps that bucket native for the process without retrying every call. Buckets from 16384 tokens up use fewer warm-up and timed runs. Under compile or graph capture an untimed bucket runs native, and the bucket is computed with comparisons only so a dynamic-shape compile guards the bucket's range rather than one exact length. Tests: test_50k_call_runs_flash_only_if_its_own_bucket_admitted_it (50k native when its bucket loses, 70k flash when its own bucket wins, 140k native when its probe fails), test_length_buckets, test_symbolic_length_guards_the_bucket_not_the_length and test_unprobed_bucket_under_capture_runs_native_untimed.
…kets, per-run tally - The length gate lives on the DiT an auto load admitted and is active only while that DiT runs (its forward hooks, the post hook also after a forward that raised). A model loaded with explicit flash or UNSLOTH_DIFFUSION_ROCM_FLASH=1 is never gated, whichever loaded first, and re-applying a non-auto backend disarms it. - Buckets are open ended powers of two (1024, 2048, ..., 65536, ...): a 50k or 140k call is timed in its own bucket, never in a capped one. Buckets from 16384 time fewer runs. - The bucket is computed with comparisons only, so a dynamic-shape compile guards the bucket range instead of the exact length, and an untimed bucket runs native under compile or graph capture. - begin_attention_run marks the generation boundary in image and video generate: the state settles on the previous run, then the per-DiT tally restarts, so status, recipes and the video calibration key describe one run, not a lifetime mix.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 61dce01b7b
ℹ️ 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".
| # (thread ident, gate) of the DiT forward running now; the ident is checked on eager calls. | ||
| _ROCM_FLASH_ACTIVE: list = [None] |
There was a problem hiding this comment.
Store active ROCm gates per thread
When image and video DiTs execute concurrently on separate render threads, this process-wide singleton is overwritten by whichever pre-hook runs last. The thread-id check then makes the other thread see no active gate, and either post-hook can clear or restore stale state while the other forward is still running, so both models can bypass their per-length admission and launch flash on an unprobed shape; their execution tallies are also cross-contaminated. Keep the active gate in thread-local/context-local storage rather than a single global slot.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in bf612c3. The process-wide active-gate slot is replaced by threading.local storage holding the running DiT's length gate, its route tally and the probing flag, set and restored by that DiT's forward hooks with nesting supported (threading.local attribute reads trace under fullgraph=True, so compiled regions gain no graph break). Test: test_route_tallies_are_per_thread runs an auto-gated masked forward and an explicit flash forward on two threads held inside their DiTs together by a barrier; each DiT's tally gets only its own calls and each thread sees only its own gate.
| def _note_rocm_flash_ran() -> None: | ||
| if not _compiling() and not getattr(_ROCM_FLASH_PROBING, "active", False): | ||
| _ROCM_FLASH_RAN[0] += 1 |
There was a problem hiding this comment.
Record routes taken by compiled attention graphs
When a speed profile compiles the DiT, this condition suppresses the flash counter during tracing, while _note_reroute similarly suppresses native reroutes; subsequent graph replays execute without re-entering these Python counters. Fresh evidence in this revision is therefore that a compiled masked or untimed-length graph can run entirely on native SDPA while rocm_flash_ran() remains empty and the load-time flash value persists in status, recipes, and video calibration. Capture the resolved route while constructing the graph or otherwise publish execution metadata at the compiled-call boundary.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in bf612c3 with the honest option rather than trace-time recording: one compiled graph can serve many lengths and mask patterns, so attributing a trace-time route to every replay could report the wrong thing. Compiled and graphed calls are not counted; when a generation counts none, the status keeps flash with the reason that per-call routing is not tracked for compiled or graphed attention (masked calls and lengths flash does not serve run native SDPA). Nothing that matters reads the report: the memory guard uses the conservative attention_may_run_native answer and the calibration key uses the engaged backend, and under compile an untimed length bucket already runs native. Test: test_compiled_run_reports_routing_untracked.
| # ROCm flash: a generation boundary. The calibration key below follows what the last run executed, | ||
| # and this run's attention tally starts at zero. | ||
| begin_attention_run(state, logger) |
There was a problem hiding this comment.
Retag video calibration with the current run's backend
For eager video runs whose mask usage changes between requests, this boundary synchronizes the previous run and then clears the tally, so the calibration key created later uses the previous run's backend. Fresh evidence after the reporting fix is that the video path never calls sync_attention_state or retags attention_backend after pipe(**kwargs) and before record_request_peak; consequently a masked-native run after a flash run records its peak under flash, and the following flash run records under native, allowing residency sizing to reuse a peak measured for the wrong kernel. Synchronize and retag the calibration key immediately before recording the completed request.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in bf612c3 with a routing-independent key rather than a per-run retag. The residency fit has to choose its key before a request runs, while the request's routing (masks, lengths) is only known afterwards, so a per-run key cannot help the lookup. The calibration key now always uses the engaged backend, and since record_request_peak keeps the maximum peak per key and work size, the stable key covers the heaviest route once each route has run instead of sizing a native run from a flash-only key. The status badge is still updated right after the pipeline call and before record_request_peak. Test: test_each_generation_reports_its_own_calls (flash, masked-native, flash: each badge reports its own run while the calibration key's backend stays the engaged one).
| f"torch{torch.__version__}", | ||
| f"hip{getattr(torch.version, 'hip', None)}", | ||
| f"flash_attn{fa_version}", | ||
| os.path.dirname(os.path.realpath(fa.__file__)), | ||
| backend, | ||
| f"build{_flash_attn_build_fingerprint()}", |
There was a problem hiding this comment.
Invalidate verdicts when the Diffusers path changes
Fresh evidence after switching the probe to Diffusers' dispatch path is that this persisted key fingerprints torch, HIP, and flash-attn but not the Diffusers version or attention-dispatch implementation. After a Studio update changes the pinned Diffusers wrapper while leaving flash-attn and the local timer source unchanged, an admitted cached record bypasses the probe entirely; incompatible wrapper arguments or changed behavior therefore surface during generation even though a fresh probe would reject them. Include the Diffusers version or a fingerprint of its flash dispatch implementation in this key.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in bf612c3. The persisted key now includes the diffusers version and a hash of the source of dispatch_attention_fn and the registered FLASH backend (with Studio's guard unwrapped, so installing the guard does not change it). Older records simply miss and are re-timed. Test: test_diffusers_dispatch_change_retimes (a changed FLASH wrapper changes the key and forces re-timing; the guard around the unchanged function does not).
| # ROCm flash: a generation boundary, so the recipe and status describe this run's attention calls. | ||
| begin_attention_run(state, logger) |
There was a problem hiding this comment.
Keep reported routing out of the next image memory guard
Fresh evidence in the image path is that this boundary leaves state.attention_backend describing the previous run—or the load-time flash choice on the first run—before the activation guard later passes that field to _quadratic_attention. On a ROCm device whose native SDPA is math-only, a masked-only pipeline such as Krea can therefore be treated as fused because the load admitted flash, even though every current call is rerouted to native; the guard then omits the quadratic score-matrix budget and can allow the enormous allocation it is meant to refuse. Preserve the actually engaged backend separately from reporting, or conservatively account for native masked calls before running the guard.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in bf612c3. state.attention_backend now keeps the backend engaged at load and the per-run route count is only a status report, so nothing that sizes memory reads it. _quadratic_attention no longer treats an engaged flash backend as fused when ROCm flash can hand calls to native SDPA: a new attention_may_run_native(pipe) answers from configuration, never from a past run (true for any DiT whose flash calls go through the ROCm guard, auto or explicit, since masked calls are rerouted either way), and the guard then budgets the quadratic score matrix whenever native SDPA on that card is math-only. Test: test_memory_guard_budgets_quadratic_when_flash_can_hand_calls_to_native (a Krea-like pipe on auto-admitted flash budgets the quadratic term; a flash pipe without ROCm routing does not).
…guard and key conservative - The attention route tally is a status report only: report_attention_run updates the resolved attention badge after each generation (image before the recipe, video before the request peak is recorded). state.attention_backend stays the engaged backend, so recipes, the video calibration key and compile caches never follow a per-run report. - The image activation guard budgets the quadratic score matrix when ROCm flash can hand calls to native SDPA (masked calls, lengths it does not serve), via attention_may_run_native, instead of trusting the flash pick. - The active length gate and route tally live in thread-local storage set by the DiT forward hooks, so concurrent image and video forwards never see each other's. - Compiled or graphed attention is not counted; the badge then says per-call routing is not tracked. - The persisted verdict key includes the diffusers version and a hash of dispatch_attention_fn and the registered FLASH backend (unwrapped from Studio's guard). [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: bf612c3ff6
ℹ️ 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".
| for geometry in geometries: | ||
| if not _rocm_flash_geometry_admitted(device, dtype, geometry, logger): | ||
| return False |
There was a problem hiding this comment.
Seed the admitted bucket before compiled execution
When an auto-selected load starts directly in the default or max speed profile, the load-time 4096-token probe succeeds here but records its result only in ROCM_FLASH_ADMISSIONS; _ROCM_FLASH_BUCKETS remains empty. Fresh evidence in this revision is that the subsequent lazy Dynamo trace cannot benchmark an empty bucket because _rocm_flash_length_reason() returns "untimed length" while compiling, so the graph permanently captures native SDPA even for the same 4096 bucket that was already admitted. Seed the corresponding bucket entries from each successful load-time probe so compiled auto loads can actually use the selected flash backend.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a359bb7. Every determined verdict (the load-time probe, a stored verdict read from disk, an in-memory hit, a lazy bucket probe) now also fills the per-call bucket table under the same length key, so a traced call in an admitted bucket uses flash instead of untimed length; buckets not timed before tracing still run native under compile and are timed on their first uncompiled call. For context, in the current tree Studio does not compile the denoiser on ROCm in any speed profile (DiffusionDeviceTarget sets supports_default_torch_compile = not is_rocm, and compile_eligible gates both the default and max branches of apply_speed_optims) and CUDA graphs are refused on ROCm, so this keeps the path correct if ROCm compile is enabled later. Test: test_compiled_auto_load_runs_flash_at_the_admitted_bucket (fresh probe and verdict read from disk: a traced 4608-token call runs flash, a traced 9000-token call stays native).
| bucket = max(_rocm_flash_bucket(seq), _rocm_flash_bucket(kv)) | ||
| keys = [(device, shape[1], hidden, shape[2], shape[3], bucket) for hidden in sorted(hiddens)] |
There was a problem hiding this comment.
Preserve query and key lengths in admission probes
For rectangular cross-attention, this collapses the query and key lengths into one bucket and _time_rocm_flash_block() then probes square self-attention at that single length. This is exercised by video paths such as Wan's block.attn2(n, encoder_hidden_states, ...), where the long video query and short text key have very different costs; a square 16k×16k probe can admit flash because native attention dominates there even though the actual ~27k×text call is slower or encounters a shape-specific kernel problem. Key and cache the query/key buckets separately and probe the rectangular geometry that will run.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a359bb7. Calls are bucketed by the pair (query bucket, key bucket), powers of two from 256 tokens up, open-ended, and a rectangular pair is timed as real cross-attention (queries from the image stream, keys and values from a context of the key length); stored slots, records (kv_tokens) and the in-memory caches carry the key length. The smallest bucket is lowered to 256 so short text keys get their own buckets. Tests: test_cross_attention_is_not_decided_by_a_square_probe (a 27k x 512 call is timed as 16384 x 512, loses and runs native, while square 16k self-attention keeps flash) and test_rectangular_probe_runs_on_cpu.
| for dit in _attention_dits(getattr(state, "pipe", None)): | ||
| if isinstance(getattr(dit, ROCM_FLASH_TALLY_ATTR, None), dict): | ||
| try: | ||
| setattr(dit, ROCM_FLASH_TALLY_ATTR, {}) |
There was a problem hiding this comment.
Include named H3 partitions in run accounting
For a MiniMax-H3 reference workflow, apply_attention_backend() receives a _NamedDiTView and installs the ROCm routing hooks on pipe.transformer_ref, but generation calls this function with the real pipe. _attention_dits() only enumerates transformer, transformer_2, and unconditional_transformer, so the reference partition's tally is neither reset here nor found later by report_attention_run(); masked or otherwise rerouted H3 runs therefore leave the status badge at its load-time flash value. Pass the active denoiser view or include named workflow partitions when resetting and reporting.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a359bb7. When the ROCm flash hooks are installed, each hooked DiT is recorded on the pipe (a _NamedDiTView writes through to the real pipe, so pipe.transformer_ref is recorded too), and reset, report and attention_may_run_native iterate that record plus anything _attention_dits still sees, so no hooked partition can be missed. Test: test_named_partition_is_in_run_accounting uses video.py's real _NamedDiTView on a pipe with only transformer_ref; the partition is memory-guarded, a masked run reports native, and the next boundary resets its tally.
…es the shape, draws on device; explicit flash needs its guard [skip ci]
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
…host already imported
…l takes its bucket verdict at trace time
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 62c3bab798
ℹ️ 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".
| tuple, frozenset | ||
| ] = {} # (device, dtype, heads, head_dim) -> the full geometries sharing it | ||
| for geometry in geometries: |
There was a problem hiding this comment.
Keep runtime gates tied to the calling geometry
When a DiT contains self- and cross-attention modules with the same (heads, head_dim) but different hidden or context widths, this union places every geometry behind the same runtime gate. _rocm_flash_length_reason() then requires all of those geometry verdicts for each call, so a losing cross-attention probe can reroute a self-attention call to native even when the self-attention geometry wins, and vice versa. Preserve the calling module's geometry instead of grouping solely by the projected head shape.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing this one. Grouping by (heads, head_dim) means a call uses flash only when every geometry in its group won its timing, so it can lose a speedup but never runs flash for a geometry that lost or was inexact. Doing better needs the calling module, and the guard only sees the projected q / k / v, where the hidden and context widths are gone.
| try: | ||
| if not sdpa_math_only(target): | ||
| return False |
There was a problem hiding this comment.
Validate native SDPA for the rerouted call geometry
When ROCm flash reroutes a masked or unsupported call, sdpa_math_only(target) reflects only the fixed tiny, unmasked capability probe rather than the real request's mask, head dimension, and sequence length. A fused SDPA backend can pass that probe but reject the actual call—this change already accounts for that possibility in _native_sdpa_fused_serves() for synthetic probes—causing native dispatch to fall back to math while this function returns False; the image activation guard then omits the quadratic score matrix and can admit a request that allocates many GiB and OOMs. Check fused eligibility for the actual generation geometry or conservatively budget the native fallback.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing this here. When flash is engaged and some calls may run native, _quadratic_attention budgets memory with the same sdpa_math_only(target) probe the merge base uses for every native load, so a rerouted call is budgeted exactly as on main. A fused kernel that passes the probe but refuses the real masked or long call is a gap main already has for all native loads; it belongs in a separate change to sdpa_math_only.
…other backend [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. 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". |
[skip ci]
…t through importlib [skip ci]
… is not installed
…rds (#14479) ## Summary Enables the diffusion multi-GPU layer split (#14412) on ROCm. Until now the planner declined every ROCm host with `ROCm (layer split is CUDA only)`. With this change a denoiser that does not fit one card is cut across discrete ROCm GPUs, on Linux and on Windows, the same way it already is on CUDA. Integrated GPUs and APUs (unified memory) decline with a clear reason, and every ROCm-specific gate is scoped to ROCm only, so nothing changes on CUDA. `UNSLOTH_DIFFUSION_LAYER_SPLIT=0` still turns the split off (as does `UNSLOTH_DIFFUSION_MULTIGPU=0`). ## What changed `studio/backend/core/inference/diffusion_layer_split_plan.py` - The blanket ROCm decline is gone. On ROCm, `_rocm_discrete_secondaries` runs Studio's existing APU classifier on each card (`utils.hardware._rocm_props_unified_status`: the driver's integrated flag, then the gfx target). A unified primary declines with `unified memory: cuda:N is an integrated GPU (APU) sharing system memory, so cutting the denoiser across cards frees no memory`. A unified secondary is dropped, and if that leaves no secondary the split declines with the same reason. - New `note_unified_primary`: when `refine_plan_for_multigpu` stops on a unified-memory plan, ROCm now records the unified reason in `status()["multi_gpu"]["layer_split"]`, so a two-APU selection is no longer silent. On CUDA this stays a silent no-op, same as before. - Attention backends: on ROCm, native SDPA keeps every card. ROCm `flash` (flash_attn, #13792) and `aiter` only keep secondaries with the primary's exact gfx target. `flash` must also pass its own probe on each secondary (`_rocm_flash_attn_runs` for that card and the denoiser's dtype), the same probe the primary passes at load. The CUDA branch (`_PRIMARY_ARCH_BACKENDS` compared by compute capability) is unchanged. - `_is_rocm` now also detects AMD SDK / Radeon wheels, which leave `torch.version.hip` unset. `studio/backend/core/inference/diffusion_multigpu.py` - `make_selection` on ROCm no longer orders gfx targets as if they were CUDA capabilities. Before, a 7900 XTX `(11, 0)` primary dropped an MI300 `(9, 4)` secondary. Now a secondary is kept when it can run the primary's load dtype: if the primary has native bf16, a card that only emulates bf16 (RDNA1/2, GCN, Vega per `rocm_bf16`) is dropped. The CUDA path is untouched. - `refine_plan_for_multigpu` calls `note_unified_primary` on its existing unified-memory early return. It still returns the plan unchanged. ### Review follow-ups - `utils/hardware`: the APU arch set now names every target LLVM's AMDGPUUsage table types as APU (gfx1153 Krackan Point 2, gfx1033, gfx1035, gfx1036, gfx1013, gfx90c, gfx902, gfx909, gfx801, gfx810), so an APU whose runtime leaves `is_integrated` unset no longer reads as discrete. The device-name fallback (no arch attributes, no flag) also matches 820M, 8040S, 780M / 760M / 740M, 680M / 660M and 610M as whole tokens, so discrete mobile names such as RX 7600M stay discrete. - Native SDPA on ROCm: each secondary runs the existing per-device SDPA probe at the model dtype. A math-only card beside a fused primary gets no blocks (math SDPA builds the full score matrix the plan never priced on that card). - Component split: a second denoiser (for example Wan's `transformer_2`) moves to a ROCm secondary only if that card passes the same per-card backend gate; otherwise both denoisers stay on the primary and only the text encoder / VAE move. Already ROCm-safe on main, audited and left alone: - Per-card CUDA graphs and block graphs: `backend != "cuda"` is off on ROCm. - int8 GEMM and fused int8 / QKV records: `_split_cards` and `resident_cuda_cards` return nothing on HIP. - Cross-card copies: the boundary does plain `tensor.to(device)`. There are no custom streams or events in the split path. - Memory probes: `trusted_mem_get_info(ordinal)` already caps the free figure on Windows ROCm, per card. - Compile: per-block regional compile on each card. The ROCm compile probe is keyed per device. ## Tests - `tests/test_diffusion_layer_split_plan.py`: 8 new tests. They run Studio's real classifiers (`_rocm_props_unified_status`, `rocm_bf16`) over faked device properties: - two discrete ROCm cards plan exactly the split CUDA plans; - two APUs decline with the unified reason; - a unified-memory plan records the reason on ROCm and stays silent on CUDA; - a discrete primary skips an APU secondary; - the kill switch on ROCm; - mixed arch selection (7900 XTX + MI300 both kept, RDNA2 dropped under a bf16 primary); - mixed arch native SDPA splits, while flash / aiter stay on the primary's gfx target and flash probes the secondary; - the Windows ROCm WDDM free cap on secondary budgets. - The ROCm decline test is now `test_rocm_discrete_splits_and_explicit_modes_and_legacy_cpu_offload_keep_the_plan`. - The fixtures in the plan, order and multigpu suites pin `_rocm_torch`, so the CUDA-shaped tests behave the same on a ROCm host. - CPU sweep over every diffusion / video / multigpu / layer split / rocm test file, base vs head: 18780 vs 18788 passed. The 340 failing / erroring test IDs are the same on both sides (local environment issues, present on base). ## AMD CI evidence (gfx1151, Linux, device multiplier) One batched GPU job on the Strix Halo runner, torch ROCm (HIP 7.13), `--spoof-devices 2` (3 HIP devices, 2 of them phantom), base = main `a74da3f321`, head = main + this change, same runner and seeds. | cell | base (main) | head | |---|---|---| | tiny FLUX.1 pipeline, forced split, discrete spoof | declines `ROCm (layer split is CUDA only)` | split on cuda:0 + cuda:1, 2 calls / 10 hand-offs, bit-identical to one card | | tiny Qwen-Image pipeline | declines | split, 2 / 6, bit-identical | | tiny Wan transformer | declines | split, 1 / 8, bit-identical | | tiny Wan, three cards selected | declines | split on [0, 1], bit-identical | | same models, this host as it is (gfx1151 APU) | declines (CUDA only) | declines `unified memory: cuda:0 is an integrated GPU (APU) ...` | | FLUX.2-klein-4B, 512 px, 4 steps, forced split vs one card | declines | blocks 0-11 on cuda:0, 12-24 on cuda:1, 4 calls / 156 hand-offs, bit-identical; 0.585-0.590 vs 0.580-0.585 s/step (phantom card, wiring only) | | compiled split (`compile_repeated_blocks(fullgraph=True)`), tiny FLUX.1 / Qwen-Image / Wan, prompts 2-4 | n/a | bit-identical to one card, 0 new graphs, 0 graph breaks | | compiled split, FLUX.2-klein-4B | n/a | not proven: Triton's HIP launcher raised `invalid device ordinal` (101) for the phantom ordinal while precompiling. The multiplier only wraps the HIP calls torch makes, so this is the spoof, not the split; it needs a real second card | | kill switch `UNSLOTH_DIFFUSION_LAYER_SPLIT=0` | no split | no split, nothing recorded | | head's layer split / multi-GPU test files | 38 passed, 176 errors (the head's tests need the head's API) | 212 passed, 1 skipped, 1 failed | The one head failure, `test_execution_device_reports_the_primary_of_a_split_pipeline`, is the runner's diffusers failing to import in the test process (`Failed to import diffusers.pipelines.pipeline_utils`), and the skip is the same import. Both pass on the CPU sweep above. ## What the spoof cannot prove The device multiplier shows extra HIP ordinals that are the same physical gfx1151. So this run proves wiring: selection, planning, placement, the boundary hand-offs, bit identity, and compile with zero recompiles. It does not prove: - real multi-GPU memory relief (the "cards" share one pool); - cross-card copy bandwidth or stream behaviour over a real PCIe / xGMI link; - any s/step figure (recorded, but phantom); - the compiled split of a real model (blocked by the spoof above); - mixed gfx targets on one host; - ROCm flash_attn or AITER on a secondary; - the Windows ROCm path on real hardware. gfx1151 is an APU, so reaching the discrete branch at all required a Studio-layer spoof in the harness: the memory kind reported as discrete, and the per-card unified classifier answering discrete. The unmodified host takes the unified decline, which is the intended behaviour on this hardware. ## For a tester with two or more discrete AMD GPUs ```bash # 1. CPU and two-card unit tests from the PR checkout cd studio/backend python -m pytest -q tests/test_diffusion_layer_split_plan.py tests/test_diffusion_layer_split_order.py \ tests/test_diffusion_multigpu.py tests/test_diffusion_layer_split_cuda.py tests/test_diffusion_multigpu_cuda.py # 2. Forced split on a model one card holds: Studio, select both GPUs, load FLUX.2-klein-4B with UNSLOTH_DIFFUSION_LAYER_SPLIT=force unsloth studio # then check the log for "diffusion.layer_split: ... split cuda:0: N blocks ..., cuda:1: M blocks ..." and the # model status multi_gpu.layer_split (cards [0, 1], live.calls > 0), and that the image matches a run with # UNSLOTH_DIFFUSION_LAYER_SPLIT=0 (same seed) # 3. Real need: a model larger than one card (FLUX.2-dev bf16 on 2x 24 GB), default settings: # status shows layer_split engaged instead of an offload policy, and s/step beats the one-card offload run # 4. Mixed cards (for example 7900 XTX + MI300 or RDNA3 + RDNA4): the status shows which cards were used, and # with flash_attn installed the split stays on cards of the primary's gfx target rocm-smi --showproductname; python -c "import torch; print([torch.cuda.get_device_properties(i).gcnArchName for i in range(torch.cuda.device_count())])" ``` --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…r bucket, and gate the CFG replica too (#14869) ## 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`.
Problem
On ROCm, Studio's
autoattention picks flash_attn only for FLUX.2-klein on gfx11, via a hard-coded model family table. Every other model keeps torch SDPA (AOTriton), even when a working flash_attn build is installed and faster for that model's shapes. On a Strix Halo (gfx1151) with the Dao-AILab flash_attn CK build installed, Z-Image stays on SDPA although flash_attn is about 1.9x faster on its attention.Change
studio/backend/core/inference/diffusion_attention.pyautonow makes flash a candidate instead of deciding by model name. TheROCM_AUTO_FLASH_FAMILIES/ gfx11 table is removed.apply_attention_backendreads the loaded model's attention geometry (to_qwidth andheads) and times one synthetic DiT block at 4096 tokens: native SDPA vs flash_attn, 2 warm-up then 5 interleaved timed runs.ROCM_FLASH_ADMISSIONS. A probe error falls back to native and is retried on the next load. The probe costs about 1 to 4 s on the first load of a geometry.diffusion_rocm_flash/probe_<hash>.json), keyed by device and gfx arch, torch and HIP versions, flash_attn version, path and backend, the probe version and the timer source. A restart reads it instead of timing again; any change to that toolchain re-times.UNSLOTH_DIFFUSION_ROCM_FLASH_CACHE_DIRmoves the folder. A probe error is never persisted.UNSLOTH_DIFFUSION_ROCM_FLASH=auto|0|1:0meansautonever picks flash,1skips the timing. An explicitflashrequest is honored either way.Results
Radeon 8060S (gfx1151), torch 2.11.0+rocm7.13.0, flash_attn CK build (Dao-AILab
1fc0221183,GPU_ARCHS=gfx1151). Base ismainin the same CI job. 1024 px, median of 5 images.ROCM_FLASH=0ROCM_FLASH=0mainthrough the family table; this PR reaches the same choice through the probe.mainignores the kill switch.flash 47.32 ms vs native 55.77 ms, rel L1 1.00e-03, Z-Imageflash 57.78 ms vs native 67.03 ms, rel L1 9.87e-04.Final head, same card (run on this PR's head vs the merge base
6c3bd1625, all PR files checked against the head), median of the new-prompt renders; ratios are auto vs native within this PR:Attention and block microbenchmarks on the same card (bf16, head_dim 128):
Tests
tests/test_diffusion_attention_rocm_flash.pyis rewritten for the candidate path: timing admission and rejection, caching, kill switch, probe error fallback, missing geometry, and a CPU run of the block timer.11 attention / ROCm test files on CPU:
main372 passed, 23 skipped; this PR 375 passed, 23 skipped.Persistence on the gfx1151 runner: the first process timed 9 (geometry, bucket) slots and wrote one cache file whose key carries the native SDPA baseline (
sdpafem,aotriton-exp1); a second process made 0 timer calls, read every verdict from disk, made the same choices and left the file untouched. Forcing flash on or off timed nothing and wrote nothing.Not covered
rocm[devel]from pip) benefit.Update: compiled denoiser on ROCm
Main now compiles the denoiser's blocks on ROCm (#13774, regional compile behind an on-card probe). Before this update, every traced attention call of an auto-gated DiT ran native SDPA. So on current main the PR still engaged flash at load but never ran it. Measured on gfx1151 after merging main: Z-Image auto 20.20 s vs native 20.17 s, Wan2.2-5B 33 frames auto 144.33 s vs native 145.67 s. The status badge also said flash.
What changed:
torch.compiler.assume_constant_result, so tracing gains no graph break and no guard on the verdict tables.Compiled DiT block on gfx1151 (torch 2.11.0+rocm7.13.0, flash_attn CK, bf16,
torch.compile(dynamic=False), 0 graph breaks on both arms):End to end on the same card. Base is main
b25007f48(compiled denoiser), head is this branch at32de65443, same CI job, 1024 px, median of the new-prompt renders:ROCM_FLASH=0compiledin speed_optims). No compile fallback was logged.