Skip to content

Studio: probe the regional diffusion compile on ROCm instead of refusing it - #13774

Merged
danielhanchen merged 26 commits into
mainfrom
studio-diffusion-rocm-regional-compile
Oct 15, 2026
Merged

danielhanchen merged 26 commits into
mainfrom
studio-diffusion-rocm-regional-compile

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

Problem

Diffusion on ROCm never takes the regional torch.compile. supports_default_torch_compile is hard-coded to not is_rocm, so every speed tier runs the denoiser eagerly on AMD.

The refusal dates from inductor's pooled buffers (memory_planning): inductor::_alloc_from_pool returned views that AOTAutograd rejected at the first call. Studio now compiles diffusion with memory_planning off, and CUDA graphs are already gated off on ROCm separately. So that original reason no longer applies.

Change

  • New module diffusion_rocm_compile.py. The first time a compiling tier asks on ROCm, it compiles one small transformer block the way the default tier compiles: dynamic=True, fullgraph=True, no CUDA graphs, memory_planning off. The block is LayerNorm with modulation, QKV, SDPA and a GELU MLP. It is run at two sequence lengths and checked against eager. The result is cached per device for the process.
  • On failure: if the probe fails to build, does not run, gives non-finite output or disagrees with eager, the model stays eager as before. A warning says why.
  • Wiring: the probe is called from compile_eligible and the auto-optimiser's compile_ineligible_reason. ROCm device targets now report supports_default_torch_compile unless the kill switch is set.
  • Switches: UNSLOTH_DIFFUSION_ROCM_COMPILE=0 never compiles on ROCm; =1 skips the probe.
  • Unchanged: CUDA graphs stay off on ROCm, and nothing changes for CUDA.

Results

AMD Strix Halo (Radeon 8060S, gfx1151), Linux, torch 2.11.0+rocm7.13.0. Base is main at 9f606d6, run on the same machine in the same job.

End to end at 1024 px, speed tier default, 5 images per setting. The A/A spread is between two identical eager runs:

model eager (s/image) compiled (s/image) change A/A spread LPIPS vs eager
FLUX.2-klein-4B 8.32 7.88 -5.3% 0.4% or less 0.015
Z-Image-Turbo 21.81 20.66 -5.3% 0.4% or less 0.030
  • An earlier run on the same machine agreed: klein -5.0%, Z-Image -4.7%.
  • Rerun on the final head (f265df0) against its merge base, same machine and job: klein 8.26 to 7.83 s/image (0.95x, LPIPS 0.016), Z-Image 21.69 to 20.55 s/image (0.95x, LPIPS 0.030); kill-switch A/A runs within 0.5%.
  • compiled appears in the applied speed settings only on this PR. It does not appear on main, or on this PR with the kill switch set.
  • Costs: the first render is slower (+9.1 s klein, +4.2 s Z-Image), and each process pays a one-time ~3.7 s probe. The first-render cost pays back after about 4 images on Z-Image and about 21 on klein.
  • Old failure gone: the _alloc_from_pool failure did not reproduce with memory_planning on or off.
  • Block-level speed: at sequence length 4096 the compiled block ran in 54 ms against 107 ms eager.

Tests

  • New cases in tests/test_diffusion_speed.py and tests/test_diffusion_device.py cover:
    • the kill switch and the forced setting;
    • a failing probe keeping the model eager;
    • CUDA targets never consulting the probe.
  • Those two files: 247 passed.
  • 19 broader diffusion and video test files: 2436 passed, 11 skipped on both main and this branch.

Not covered

  • Hardware: no discrete RDNA2, RDNA3, RDNA4 or CDNA (MI300) card. The probe checks that compile works and is correct, not that it is faster, so a card where compile is slower would still compile; UNSLOTH_DIFFUSION_ROCM_COMPILE=0 turns it off.
  • Windows ROCm was not run. Without a working Triton the probe fails and the model stays eager.
  • Not measured: the max tier (max-autotune), Qwen-Image, and video models.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 14, 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-15T02:52:39.193092Z 159cd66 Manual request
🔒 Security Review ⚠️ Failed 2026-10-14T21:40:49.378043Z 34f6119 PR opened
ℹ️ 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.

@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: c20efa7347

ℹ️ 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".

return False
dtype = getattr(target, "dtype", None)
if _is_bfloat16(dtype):
return True

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 Defer the ROCm compile probe until after GPU eviction

On ROCm this predicate is also called from pre-eviction capability paths, including _pipeline_quant_uncompilable_reason() during assert_precision_available() and dense_quant_host_capable() from the polled /api/system route. Running the new compiling probe here allocates on a GPU that may still contain the resident model; a transient OOM is caught and cached as False for the process, so a subsequent explicit torchao load can be rejected as uncompilable even though the pending eviction would have made enough room. Keep these preflight/status checks non-allocating and run or cache the real probe only once the load owns a freed GPU.

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.

Fixed in 104e08f. The route preflight, the planned-seed check and the /api/system capability poll now only read the ROCm probe result (unprobed counts as eligible, a recorded failure does not); only the loader and the speed optims, which run on the evicted card, run it. An OOM result is no longer cached.

Comment on lines +38 to +39
def rocm_compile_allowed() -> bool:
return rocm_compile_setting() != "off"

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 Honor the ROCm kill switch in the GGUF compile path

When UNSLOTH_DIFFUSION_ROCM_COMPILE=0, this helper disables regional eligibility, but apply_speed_optims() handles GGUF default through _gguf_dequant_compilable() before calling compile_eligible() and installs a torch.compiled dequantizer anyway; the max fallback does the same when the block compile is disabled. Consequently the documented setting that “never compiles on ROCm” still compiles GGUF workloads, so installations using it to avoid a broken ROCm compiler remain exposed unless they discover and set a separate GGUF-specific switch.

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.

Fixed in 104e08f. UNSLOTH_DIFFUSION_ROCM_COMPILE=0 now also stops the GGUF dequant compile on ROCm, in both the default arm and the max fallback, and the autoopt plan no longer reports the dequant compile in that case.

Comment on lines +375 to +376
if not rocm_compile_probe_passes(target):
return False

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 Skip the probe for ROCm targets that cannot become eligible

On a ROCm card where rocm_bf16_supported() selects float16, this call still runs the allocating bf16 compilation probe before the dtype decision. The subsequent _fp16_compile_capable() always returns False for backend == "rocm", so such a target can never compile regardless of the probe result; it nevertheless pays the multi-second probe cost (and may attempt unsupported bf16 kernels) during each process's first eligibility check. Perform the dtype/backend rejection before invoking the ROCm probe.

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.

Fixed in 104e08f. compile_eligible and compile_ineligible_reason now reject on dtype first, so a ROCm fp16 target returns the dtype reason without running the probe.

…ll switch for GGUF

Preflight and the polled status route read the probe result instead of running it, so nothing allocates before eviction; the loader probes. An OOM probe is not cached. ROCm fp16 is rejected before probing. UNSLOTH_DIFFUSION_ROCM_COMPILE=0 also stops the GGUF dequant compile.
@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: 104e08f1be

ℹ️ 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 7553 to 7555
pipeline_quant_uncompilable = _pipeline_quant_uncompilable_reason(
target, fam, speed_mode, model_kind = kind
target, fam, speed_mode, model_kind = kind, probe = True
)

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 Skip the probe when pipeline quantization is disabled

For a ROCm pipeline loaded with speed_mode="off" and an unset/default transformer-quant request, the earlier normalization rewrites transformer_quant to "off", but this unconditional call still passes probe=True. Because the helper only short-circuits for eager, the load pays the allocating, multi-second compile probe even though the quantization branch below is skipped and the off speed tier will never compile; gate this evaluation on an engaged quantization request or move it inside that branch.

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.

Fixed in 335a48b. The loader now runs the compile check, and with it the ROCm probe, only inside the engaged pipeline-quant branch, so a load with quantization off never pays for it.

@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: 335a48bcb6

ℹ️ 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".



def compile_eligible(target: Any, *, is_gguf: bool, family: Any) -> bool:
def compile_eligible(target: Any, *, is_gguf: bool, family: Any, probe: bool = True) -> bool:

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 Defer the ROCm probe with the deferred speed profile

On a bf16 ROCm dense load where speed_mode is omitted and quantization is off, the pre-existing speed_deferred check at diffusion.py:7798-7804 calls this function without probe=False. Consequently the new default runs the allocating, roughly 3.7-second compile probe during model load even when the session never reaches the third generation where compilation is supposed to engage; a transient OOM here also disables deferred compilation for the entire load. Use the cached/non-allocating eligibility result when deciding whether to arm the deferred profile, and let _engage_deferred_profile() perform the real probe.

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.

Fixed in 383322f. The deferred profile now arms from the non-probing read, and _engage_deferred_profile runs the real ROCm probe only when it engages.

and is_gguf
and on_cuda
and getattr(family, "supports_torch_compile", True)
and not ds.rocm_compile_switched_off(target)

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 Apply the ROCm kill switch to the dequant plan step

With UNSLOTH_DIFFUSION_ROCM_COMPILE=0 on a ROCm GGUF load, this condition correctly stops describing the regional compile as replaced by dequant compilation, but build_plan() still unconditionally marks compiled_dequant as attempted for every CUDA GGUF target at lines 210-214. Runtime now declines that step through _gguf_dequant_compilable(), so the plan and audit lose parity and report the generic “not applicable” reason instead of the kill switch. Fresh evidence in the final tree is that the compiled_dequant predicate remains bool(is_gguf and on_cuda) despite the earlier thread stating that the autoopt plan was fixed.

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.

Fixed in 383322f. build_plan now declines compiled_dequant on ROCm under UNSLOTH_DIFFUSION_ROCM_COMPILE=0 and names the switch as the reason, matching _gguf_dequant_compilable.

Comment on lines +7562 to +7564
pipeline_quant_uncompilable = _pipeline_quant_uncompilable_reason(
target, fam, speed_mode, model_kind = kind, probe = True
)

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 Skip the probe for native ROCm quantization

On a bf16 ROCm pipeline load with an explicit int8/fp8 request that resolves to native_scheme, especially with speed unset or off, this unconditional probe=True call still performs the allocating compile probe. The result is immediately discarded by the native_scheme is not None or native_offload_scheme is not None branch at lines 7573-7577, and native quantization is deliberately excluded from the later rule that forces a compiling speed tier, so such loads pay the multi-second probe and GPU allocation without using regional compilation. Only probe when the non-native torchao path actually requires compilation.

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.

Fixed in 383322f. The loader skips the compile check, and so the probe, when the request resolves to a native scheme, since that path never reads the result.

Comment on lines +88 to +90
# An OOM says the card was busy, not that the compiler is broken: ask again next load.
if ok or "OutOfMemoryError" not in why:
_result[index] = (ok, why)

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 Avoid retrying an OOM probe within the same load

When the ROCm probe raises OutOfMemoryError, leaving _result empty makes every later eligibility check immediately run the full probe again, rather than retrying on the next load as the comment says. A compiling image load can call compile_eligible() once for the compile cache, again while building the autoopt plan, and again from apply_speed_optims(), so a busy card can suffer several consecutive compiles/OOMs during one request. Preserve a load-scoped failed result or otherwise suppress retries until the next load 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.

Fixed in 383322f. An OOM probe result is now held for the rest of the load, so later checks reuse it, and it is dropped at the next image or video load so the probe can retry.

Comment on lines +51 to +52
with _lock:
hit = _result.get(_index(device))

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 Keep non-probing status reads non-blocking

While one thread runs the multi-second probe, rocm_block_compile_probe() holds _lock around the entire compilation at lines 78-91, so this supposedly non-probing read blocks until compilation finishes. A concurrent polled /api/system request or preflight check can therefore stall for the full probe duration even though its contract is only to inspect an existing result; return None while a probe is in progress or move compilation outside the result lock with an in-progress sentinel.

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.

Fixed in 383322f. The non-probing read no longer takes the probe lock, so status and preflight reads return right away while a probe is running.

…atus paths

The deferred speed profile arms from the non-probing read, native quant skips the compile check, an OOM probe is held for the load and retried at the next, status reads no longer wait on a running probe, and the autoopt plan declines compiled_dequant under UNSLOTH_DIFFUSION_ROCM_COMPILE=0.
@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: 383322ffcc

ℹ️ 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 386 to +387
if _is_bfloat16(dtype):
return True
return rocm_compile_probe_passes(target, probe = probe)

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 Skip the regional probe for default GGUF loads

On a bf16 ROCm GGUF load using the default speed tier, the compile-cache gate at diffusion.py:7984-7990 calls compile_eligible(..., is_gguf=True), but this function discards is_gguf and now runs the allocating regional-block probe here. The default GGUF path later compiles only the dequantizer via _gguf_dequant_compilable(), which does not depend on this probe, so every fresh process unnecessarily pays the multi-second probe and may skip the dequant compile-cache context if that unrelated probe fails or OOMs. Preserve the GGUF distinction in this gate or use a non-probing/runtime-availability check for the default GGUF cache path.

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.

Fixed in 8fc68a2. The compile-cache gate now uses the non-probing read for GGUF on the default tier, since that tier only compiles the dequantizer; GGUF max and dense loads still run the probe.

Comment on lines +98 to +100
# An OOM says the card was busy, not that the compiler is broken: held for this load, retried at the next.
if not ok and "OutOfMemoryError" in why:
_transient.add(index)

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 Preserve wrapped OOMs as transient probe failures

When a probe OOM surfaces as RuntimeError("HIP out of memory") or as an OutOfMemoryError_ wrapped by BackendCompilerFailed, _probe() flattens it to a string that may contain neither the exact case-sensitive text OutOfMemoryError nor the nested cause, so this check caches the failure permanently instead of clearing it at the next load. Fresh evidence beyond the prior OOM-retry thread is the existing diffusion_batched.is_oom_error() implementation and tests, which explicitly document both of these compiler OOM forms and walk the cause chain; classify the exception before flattening it or reuse that helper.

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.

Fixed in 8fc68a2. _probe now classifies the exception with diffusion_batched.is_oom_error() before flattening it, so a bare HIP out of memory or an OOM wrapped in a compiler error is held only for the current load and retried at the next.

@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: 8fc68a2319

ℹ️ 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".

target,
is_gguf = gguf_transformer,
family = fam,
probe = not (gguf_transformer and effective_speed == SPEED_DEFAULT),

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 Decouple the GGUF cache gate from regional probe failures

On a ROCm process where an earlier dense/max load permanently recorded a failed regional probe, a later default-tier GGUF load still fails this gate: probe=False only avoids running the probe, while rocm_compile_probe_passes() returns false for the cached result. The GGUF default path nevertheless installs its independent compiled dequantizer, so compile_cache.begin() is skipped and its GGUF bundle cannot be loaded or saved. Fresh evidence beyond the resolved thread is that the final non-probing path still honors rocm_block_compile_known(...) is False; gate this case with the dequant-specific eligibility predicate instead.

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.

Fixed in 8dc7ba3. On ROCm the compile-cache gate for GGUF on the default tier now uses _gguf_dequant_compilable, the same check apply_speed_optims uses, so a regional probe failure from an earlier load no longer drops the dequant cache context. The CUDA gate is unchanged.

Comment on lines +85 to +86
if not getattr(getattr(torch, "version", None), "hip", None):
return True, "not ROCm"

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 Probe ROCm wheels that omit the HIP version field

On AMD SDK/Radeon wheels that identify ROCm only through the +rocm version tag, utils/hardware/hardware.py sets IS_ROCM and video targets enter this helper as ROCm, but torch.version.hip is intentionally unset. This branch therefore reports a successful “not ROCm” result without compiling anything, causing default video speed profiles to attempt the previously refused regional compile; a broken compiler is then discovered only during the first denoise, after the load has advertised compilation and potentially quantized the transformer. Use the repository's rocm_bf16.is_rocm_torch() detection or trust the already-resolved ROCm target instead.

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.

Fixed in 8dc7ba3. The probe now detects ROCm with the existing rocm_bf16.is_rocm_torch(), which also reads the +rocm tag in torch.version, so AMD SDK / Radeon wheels without torch.version.hip run the real probe instead of passing as not ROCm.

@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: 8dc7ba3b66

ℹ️ 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".

vendor = "amd" if is_rocm else "nvidia",
supports_model_cpu_offload = True,
supports_default_torch_compile = not is_rocm,
supports_default_torch_compile = (not is_rocm) or _rocm_compile_allowed(),

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 Detect tag-only ROCm before enabling compilation

On AMD SDK/Radeon wheels where torch.version.hip is unset and ROCm is identified by the +rocm version tag, _resolve_device_target() reconstructs every image target through this function, so is_rocm is false and this line enables compilation unconditionally. The target is then labeled backend="cuda", bypassing both the new ROCm probe and UNSLOTH_DIFFUSION_ROCM_COMPILE=0; a broken ROCm compiler can therefore be reached during image generation despite the kill switch. Fresh evidence beyond the resolved probe-detection thread is this separate reconstruction path, which still relies only on torch.version.hip; use the repository's tag-aware ROCm detection here as well.

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.

Fixed in 9304de3. diffusion_device_target_from_torch_device now detects ROCm with the existing rocm_bf16.is_rocm_torch(), so tag-only ROCm wheels rebuild a ROCm target and go through the probe and UNSLOTH_DIFFUSION_ROCM_COMPILE.

Comment on lines +61 to +63
for index in list(_transient):
_result.pop(index, None)
_transient.discard(index)

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 Serialize the load reset with an in-flight probe

If another image or video load begins while the previous load's multi-second probe is still running, this unlocked reset sees no transient entry and returns; the old probe can then publish its OOM result after the new-load boundary. When the new load reaches its post-eviction compile check, rocm_block_compile_probe() reuses that cached failure instead of retrying on the now-free GPU, so compilation remains disabled for the entire replacement load. Fresh evidence beyond the resolved OOM-retry thread is that image and video have separate backend locks while both call this global reset, and start_load() neither takes _lock nor uses a load epoch to distinguish a late probe result.

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.

Fixed in 9304de3. Each load start now bumps an epoch counter, and an OOM from a probe that began before the latest load start is returned to its caller but not cached, so the replacement load probes again.

Comment on lines +69 to +70
index = torch.cuda.current_device() if device is None else torch.device(device).index
return torch.cuda.current_device() if index is None else index

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 Preserve integer GPU ordinals when indexing the probe

On a multi-GPU ROCm host using an older supported PyTorch build, callers pass target.ordinal here as a bare integer, but torch.device(device) does not accept that constructor form—the PyTorch 2.4 constructor parser accepts a device or a type plus index. The resulting exception is swallowed and _index() returns 0, so a load explicitly assigned to GPU 1 probes and caches GPU 0 instead; heterogeneous cards or different free-memory states can therefore either disable compilation unnecessarily or let an unprobed target reach the real compile. Handle integer ordinals directly, and reserve the fallback for genuinely unreadable inputs.

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.

Fixed in 9304de3. _index() now returns an integer ordinal as-is instead of passing it to torch.device(), so GPU 1 is probed and cached as GPU 1; the fallback to 0 is kept only for inputs it cannot read.

@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: 9304de3d2d

ℹ️ 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 +61 to +67
def start_load() -> None:
"""A load boundary: an OOM probe from the previous load may be retried now."""
global _epoch
_epoch += 1
for index in list(_transient):
_result.pop(index, None)
_transient.discard(index)

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 transient probe failures for direct loads

When a ROCm probe OOM is cached in _transient, it is cleared only when start_load() is called from begin_load(). Both backends also support direct DiffusionBackend.load_pipeline() / VideoBackend.load_pipeline() calls, which bypass that call, so after one such load hits an OOM every subsequent direct load reuses the stale failure and never retries even after the GPU has been freed. Move the load-boundary reset into the direct load path as well, while avoiding a double reset for loads launched through begin_load().

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.

Fixed in 9511004. Direct load_pipeline() calls on both backends now reset held OOM probe results themselves (image in the _account_owned_load wrapper, video at the top of load_pipeline), while loads started by begin_load pass their token and still reset only once.

@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: 9511004f06

ℹ️ 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 +8003 to +8006
if gguf_transformer
and effective_speed == SPEED_DEFAULT
and getattr(target, "backend", None) == "rocm"
else compile_eligible(target, is_gguf = gguf_transformer, family = fam)

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 Keep the cache open for the GGUF max fallback

When a ROCm GGUF load requests max and the regional compile probe fails, this condition falls through to compile_eligible(...) and skips compile_cache.begin(). The speed layer later handles that exact case by installing the independent compiled dequantizer as its fallback, so its bundle is neither loaded nor saved and every load pays the compile again. Use the dequant predicate for the max tier when regional compilation is unavailable, as is already done for the default tier.

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.

Fixed in 83a4976. On ROCm, a GGUF max load whose regional compile is refused now keeps the compile cache open through _gguf_dequant_compilable, the same check as the speed layer's dequant fallback, so its bundle is loaded and saved.

dev = torch.device("cuda", index)
dtype = torch.bfloat16
gen = torch.Generator(device = "cpu").manual_seed(0)
block = _Block().to(device = dev, dtype = dtype).eval()

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 Preserve the process RNG while constructing the probe block

Whenever the automatic ROCm probe runs, _Block() initializes its Linear and LayerNorm parameters from the process-global CPU generator, so the capability check advances global RNG state even though the probe inputs use a private generator. A caller that seeds or snapshots the default torch RNG before initiating a load can therefore receive different later samples solely because this probe ran; construct the block inside a restored/forked RNG context or initialize its parameters from a private generator as well.

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.

Fixed in 83a4976. The probe block is now built inside torch.random.fork_rng(devices=[]), so its parameter init no longer advances the process CPU RNG.

@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: 8d4c2c0a65

ℹ️ 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 +124 to +126
if not ok and "OutOfMemoryError" in why:
if memo is not None:
memo[index] = (ok, why)

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 Memoize OOMs during deferred profile engagement

When a bf16 ROCm dense load defers compilation until the third generation, _engage_deferred_profile() runs after the decorated load_pipeline() scope has exited, so memo is None here. If its initial compile_eligible() probe OOMs, the failure is therefore discarded; execution continues into run_speed_layer(), whose plan and apply phases can each invoke the full probe again during the same generation. This can cause three consecutive compile/OOM stalls on an already resident model, and a later successful retry may enable compilation without the cache context skipped by the first failure. Give deferred engagement its own probe scope so one OOM is retained for that operation.

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.

Fixed in a125e73. _engage_deferred_profile now runs in its own probe scope (the same rocm_probe_load_scoped used by load_pipeline), so an OOM in its first eligibility check is held for the rest of that engagement and plan and apply reuse it instead of probing again; a later engagement or load still retries.

@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: a125e737f1

ℹ️ 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 +113 to +116
if index in _result:
return _result[index]
if memo is not None and index in memo:
return memo[index]

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 Honor the load-local OOM before global probe successes

When overlapping image/video loads target the same ROCm device, load A can memoize a transient probe OOM, then load B can successfully probe and populate _result; A's next eligibility check returns B's global success before consulting its own OOM memo. A may consequently enter the regional compile after its cache context was skipped, causing another compile/OOM stall on the busy card. Fresh evidence beyond the resolved load-scoped-OOM comments is this lookup order, which allows a concurrent success to override the current load's failure; check memo first so its answer remains authoritative for that load.

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.

Fixed in f2005a8. The probe now checks the current load's OOM before the process-wide result, so another load's later success can no longer send this load into a regional compile it already found the card too busy for.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: f2005a811f

ℹ️ 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

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: d33ffc23a9

ℹ️ 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".

dtype = getattr(target, "dtype", None)
if ds._is_bfloat16(dtype):
return None
return None if ds.rocm_compile_probe_passes(target) else rocm_failed

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 Check compile candidates before probing ROCm

For a bf16 ROCm load at the default or max tier whose pipeline has no compile candidate—or whose profiles all return a compile decline—build_plan() runs the allocating, multi-second probe here before lines 187–198 determine that regional compilation cannot be attempted. Such unsupported or generic pipelines can therefore stall or hit a pointless transient OOM; defer the probe until the candidate/profile checks pass and propagate that decline to the speed primitive.

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.

Fixed in e16d95c. build_plan now reads only a recorded probe result while it checks the model, and runs the probe last, once there is a compile candidate and the profiles do not all decline. When the model itself declines on a ROCm dense load, the plan passes a family view with supports_torch_compile off to the speed primitive, so compile_eligible returns before probing there as well. GGUF loads keep their dequant compile path untouched. Covered by test_rocm_probe_waits_for_a_compilable_model (no probe call from either the plan or the primitive) and test_rocm_probe_still_runs_for_a_compilable_model.

if not is_rocm_torch(torch):
return True, "not ROCm"
index = _index(device)
memo = _load_oom.get()

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 Serialize probes per device instead of process-wide

On a multi-GPU ROCm host, concurrent image/video loads probing different ordinals are unnecessarily serialized because this single process-wide lock is held for the entire multi-second compilation. The backends can load on separate cards concurrently, so an unrelated probe on GPU 0 delays a load on GPU 1 despite sharing no result or device resources; use per-index synchronization (or an in-progress entry keyed by index) so only duplicate probes for the same card wait.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Oct 15, 2026 •

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.

Partly addressed in fe9a0f1. A card that already has a recorded answer (or this load's own OOM result) is now read before the lock, so a load on GPU 1 with a known result never waits behind a probe running on GPU 0; covered by test_rocm_probe_answer_is_read_without_waiting_for_another_probe. The probe itself stays serialized process-wide on purpose: it runs inside inductor_cfg.patch and torch._dynamo.config.patch, which save and restore process-global config, so two probes on different cards running at once could interleave those save and restore pairs and leave memory_planning or suppress_errors patched for the rest of the process. The remaining wait is bounded: one probe per card per process, about 3 to 4 s on gfx1151.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: fe9a0f1845

ℹ️ 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 gguf_transformer
and effective_speed == SPEED_DEFAULT
and getattr(target, "backend", None) == "rocm"
else compile_eligible(target, is_gguf = gguf_transformer, family = fam)

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 Check compile candidates before probing for the cache

On a bf16 ROCm dense image load at default or max whose loaded pipeline has no denoiser compile candidate—or whose profiles all decline compilation—this cache gate calls compile_eligible() with its default probe=True before run_speed_layer()/build_plan() inspects the model. Such a pipeline therefore still pays the allocating, multi-second probe and can hit a pointless transient OOM even though no regional compile will be installed. Fresh evidence beyond the resolved build_plan() thread is that this earlier load-time compile-cache predicate remains an unconditional probing call; check the model candidate/profile first or keep this gate non-probing until that decision is available.

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.

Fixed in 159cd66. Both compile-cache gates (load time and the deferred profile engagement) now go through _compile_cache_wanted. On a dense ROCm load it first checks eligibility without probing, then asks build_plan whether the compiled step will be attempted, and build_plan runs the probe last, only after a compile candidate exists and the profiles do not all decline. NVIDIA and GGUF loads keep the previous predicate. Covered by test_compile_cache_gate_skips_the_rocm_probe_for_a_model_with_nothing_to_compile.

Comment on lines +183 to +184
with torch.random.fork_rng(devices = []):
block = _Block()

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 Avoid restoring global RNG across concurrent threads

When another thread consumes the default CPU generator while this probe constructs _Block, fork_rng() snapshots the process-global state and restores that old snapshot on exit, erasing the other thread's RNG advancement and allowing subsequent random values to repeat. Studio permits overlapping backend work, so even though the probe itself no longer advances the final RNG state, it can corrupt another load or generation's randomness. Fresh evidence beyond the resolved RNG-state thread is this restore race with concurrent consumers; initialize the probe parameters from a private generator rather than rewinding the shared generator.

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.

Fixed in 159cd66. The probe block is now built on the meta device and its parameters are filled from the probe's private generator, so the shared CPU generator is never read, snapshotted or restored and a concurrent load or generation keeps its draws. Covered by test_rocm_probe_never_rewinds_the_shared_rng, which runs the probe end to end on CPU with fork_rng made to fail and checks the global RNG state is unchanged.

…g to compile; build the probe block from a private generator
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 159cd660fb

ℹ️ 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 71cfcb9 into main Oct 15, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-rocm-regional-compile branch October 15, 2026 10:26
danielhanchen added a commit that referenced this pull request Oct 20, 2026
…ad of a model table (#13792)

## Problem

On ROCm, Studio's `auto` attention 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.py`

- On ROCm, when flash_attn is installed and passes the existing on-card
check, `auto` now makes flash a candidate instead of deciding by model
name. The `ROCM_AUTO_FLASH_FAMILIES` / gfx11 table is removed.
- At load, `apply_attention_backend` reads the loaded model's attention
geometry (`to_q` width and `heads`) and times one synthetic DiT block at
4096 tokens: native SDPA vs flash_attn, 2 warm-up then 5 interleaved
timed runs.
- Flash is admitted only if it is at least 3% faster, the output is
finite, and the block output matches SDPA within rel L1 2e-2. Otherwise
native SDPA stays.
- The decision is cached per (device, dtype, geometry) and recorded in
`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.
- The verdict is also persisted on disk under Studio's cache root
(`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_DIR` moves the folder. A probe error
is never persisted.
- `UNSLOTH_DIFFUSION_ROCM_FLASH=auto|0|1`: `0` means `auto` never picks
flash, `1` skips the timing. An explicit `flash` request is honored
either way.
- NVIDIA paths and explicit backend requests are unchanged.

## Results

Radeon 8060S (gfx1151), torch 2.11.0+rocm7.13.0, flash_attn CK build
(Dao-AILab `1fc0221183`, `GPU_ARCHS=gfx1151`). Base is `main` in the
same CI job. 1024 px, median of 5 images.

| cell | main s/img | this PR s/img | ratio | attention (this PR) |
LPIPS vs native |
|---|---|---|---|---|---|
| FLUX.2-klein native (A/A) | 8.35 / 8.36 | 8.35 / 8.33 | 1.00 | native
| 0.0000 |
| FLUX.2-klein auto | 7.46 | 7.48 | 1.00 | flash | 0.0168 |
| FLUX.2-klein auto, `ROCM_FLASH=0` | 7.45 | 8.36 | 1.12 | native |
0.0000 |
| Z-Image native (A/A) | 21.57 / 21.60 | 21.68 / 21.66 | 1.00 | native |
0.0000 |
| Z-Image auto | 21.69 | **19.52** | **0.90** | flash | 0.0234 |
| Z-Image auto, `ROCM_FLASH=0` | 21.70 | 21.64 | 1.00 | native | 0.0000
|

- FLUX.2-klein already picked flash on `main` through the family table;
this PR reaches the same choice through the probe. `main` ignores the
kill switch.
- Probe decisions from the logs: klein `flash 47.32 ms vs native 55.77
ms, rel L1 1.00e-03`, Z-Image `flash 57.78 ms vs native 67.03 ms, rel L1
9.87e-04`.
- A/A spread is under 1.2% on both models.

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:

| cell | native s/img | auto s/img | ratio | attention after generation
| LPIPS vs native |
|---|---|---|---|---|---|
| Z-Image 1024 | 21.37 | **19.12** | **0.90** | flash on every call |
0.0234 |
| Z-Image, second process | | 19.20 | 0.90 | flash, verdicts read from
disk | 0.0234 |
| Wan2.2-5B 33 frames | 166.12 | **145.56** | **0.88** | flash on 120 of
240 calls | 0.0380 |
| Wan2.2-5B 49 frames | 271.39 | **216.18** | **0.80** | flash on 120 of
240 calls | 0.0455 |

- Native vs native on this PR agrees within 0.8%; the merge base's own
native Wan cells drifted about 6% between each other, so the ratios are
taken within this PR.
- Wan's self-attention buckets admit flash (8192 tokens: 102.4 vs 132.1
ms, timed lazily about 4 s into the first 49-frame generation); its
cross-attention against the text tokens gains under 3% (70.1 vs 72.0 ms)
and stays native, which is why half the calls run flash and the LPIPS
dropped from 0.048 to 0.038 with the speedup kept.
- Direct probe of the Wan layer shape, every bucket admitted: 16k tokens
262 vs 617 ms, 32k and 64k likewise. The first call in a new long bucket
pays the timing once (22 s at 32k, about 2 minutes at 64k, mostly the
native side), then the verdict is cached on disk.
- Studio does not compile the denoiser on ROCm in the default speed
mode, so every call ran eager; no call was routed native for being
traced or for deferred timing.
- The status reason now reads "verified ROCm flash attention" at load
and reports the per-run split after generation (it showed the NVIDIA
cuDNN text before).

Attention and block microbenchmarks on the same card (bf16, head_dim
128):

| shape | SDPA attention ms | flash_attn CK ms | SDPA block ms |
flash_attn CK block ms |
|---|---|---|---|---|
| klein 1024 (24 heads, 4608 tokens) | 16.17 | 8.29 (1.95x) | 65.9 |
57.9 (1.14x) |
| Z-Image 1024 (30 heads, 4352 tokens) | 17.96 | 9.14 (1.96x) | 76.1 |
70.0 (1.09x) |
| Wan2.2-5B 704x1280x121 (24 heads, 27280 tokens) | 2402 | 306 (7.84x) |
2706 | 584 (4.63x) |

- Accuracy against an fp32 reference: flash_attn CK mean abs error
9.3e-05, SDPA 8.8e-05. The Z-Image LPIPS of 0.023 is trajectory
divergence between two kernels of equal accuracy.

## Tests

- `tests/test_diffusion_attention_rocm_flash.py` is 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: `main` 372 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

- Studio's installer does not install flash_attn on ROCm, so default
installs see no change. Only users who built flash_attn (about 11
minutes with `rocm[devel]` from pip) benefit.
- The deferral path (no room for an in-forward probe) never fired on
this large-memory APU; it is covered by unit tests only.
- No compiled ROCm path was exercised, since Studio does not compile on
ROCm by default.
- The flash_attn Triton AMD build was measured in the microbenchmark
only (1.56x to 1.60x on images).
- Only gfx1151 was run. No RDNA3 / RDNA4 discrete cards, CDNA, Windows
ROCm, or fp16 pipelines.
- FLUX.1, Qwen-Image and SDXL were not run end to end; the probe now
decides for them too.

## 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:

- A traced call now gets its (batch, query, key) bucket verdict once, at
trace time, and the answer is baked into the graph.
- The lookup (and a probe if the bucket is untimed) runs in plain Python
through `torch.compiler.assume_constant_result`, so tracing gains no
graph break and no guard on the verdict tables.
- Bucket edges are compared symbolically. A dynamic length guards on its
bucket range, not its exact value: a length inside a bucket reuses the
graph, and only a new bucket recompiles.
- If the probe has no room beside the live forward, that graph runs
native.
- A CUDA / HIP graph capture still runs native.
- The in-memory verdict key now keeps geometry, query length, key length
and batch in separate fields. A cross-attention geometry whose context
width equals a bucket edge could otherwise alias a narrower geometry at
rectangular lengths.
- Two test fixes: the toolchain key test accepts the native path
separator (Windows), and it no longer reads a real flash_attn build the
host has already imported (the gfx1151 runner).

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):

| shape | native compiled ms | flash compiled ms | ratio |
|---|---|---|---|
| Z-Image 1024 (30 heads, 4352 tokens) | 75.51 | 65.99 | 0.874 |
| Wan2.2-5B 33f self (24 heads, 7920 tokens) | 147.82 | 111.78 | 0.756 |
| Wan2.2-5B 33f cross (7920 x 512) | 77.19 | 73.70 | 0.955 |
| Wan2.2-5B 49f self (11440 tokens) | 294.35 | 178.07 | 0.605 |

End to end on the same card. Base is main `b25007f48` (compiled
denoiser), head is this branch at `32de65443`, same CI job, 1024 px,
median of the new-prompt renders:

| cell | main s/img | this PR s/img | ratio | LPIPS vs native (same
state) |
|---|---|---|---|---|
| Z-Image native (A/A) | 20.62 / 20.49 | 20.48 / 20.54 | 1.00 | 0.016
(compile noise floor) |
| Z-Image auto | 20.50 | **18.37** | **0.90** | 0.031 |
| Z-Image auto, second process (verdicts from disk) | 20.50 | **18.43**
| **0.90** | 0.033 |
| Z-Image auto, `ROCM_FLASH=0` | 20.56 | 20.47 | 1.00 | 0.010 |
| Wan2.2-5B 33 frames native (A/A) | 147.65 / 149.26 | 145.56 / 145.31 |
0.99 | 0.000 |
| Wan2.2-5B 33 frames auto | 145.27 | **122.63** | **0.84** | 0.046 |
| Wan2.2-5B 49 frames native | 243.14 | 241.24 | 0.99 | ref |
| Wan2.2-5B 49 frames auto | 242.42 | **185.92** | **0.77** | 0.051 |

- Every head cell ran compiled (`compiled` in speed_optims). No compile
fallback was logged.
- The buckets not timed at load were timed at trace time inside the
first generation: Z-Image text 256, Wan cross-attention 4096 x 512, Wan
8192 self and cross. Wan's cross-attention won this time (36.07 vs 38.02
ms, 5.1%, above the 3% bar), where the earlier eager run had it at 2.2%.
- Persistence on the card: 21/21 checks pass. The PR tests on the card:
183 passed.
- A re-apply that picks another backend (the deferred speed pass) now
takes the ROCm flash tracking off that pipe: hooks, per-run tally and
tracked DiTs, so the status badge and the memory guard stop reading it
as flash.

---------

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant