Skip to content

[Bug] Studio video: Wan2.2-TI2V-5B requests 71 GB on a 16 GB card: SDPA falls back to the math kernel on ROCm gfx1200 #8225

Closed

Description

@LeoBorcherding

Summary

A 3.4 GB video model fails on a 16 GB GPU by requesting a single 66.54 GiB allocation. The card isn't undersized and the model isn't too big: attention runs on the math kernel, which materialises the full N×N score matrix, because neither flash nor memory-efficient SDPA has a working kernel on this ROCm build.

attention, mem-efficient kernel  ▏                                       0.67 GB
model weights (Q4_K_M)           ██                                      3.40 GB
allocated at failure             █████                                   9.09 GB
GPU capacity                     ████████                               15.92 GB  <- ceiling
attention, SDPA math fallback    ████████████████████████████████████   71.44 GB  <- 4.5x the card

Environment

GPU AMD Radeon RX 9060 XT 16 GB (15.92 GB visible), gfx1200
torch 2.11.0+rocm7.13.0, hip 7.13.99004, HIP SDK 7.1
OS Windows 11
Studio main @ 6fd4e9a2a

Reproduction

Load unsloth/Wan2.2-TI2V-5B-GGUF (Q4_K_M, 3.4 GB), duration 5.0s / 121 frames, generate.

01:54:37  video.loaded: unsloth/Wan2.2-TI2V-5B-GGUF (wan2.2-ti2v-5b, gguf, offload=model, quant=off)
01:55:50  video.generate_failed: CUDA out of memory. Tried to allocate 66.54 GiB.
          GPU 0 has a total capacity of 15.92 GiB of which 5.97 GiB is free.

Dies ~70 s in, at attention_dispatch.py:3334 _native_attention → scaled_dot_product_attention.

The number decodes exactly

Scores are B × heads × N² × bytes. Config: num_attention_heads = 24, patch_size = [1,2,2], VAE spatial 16 / temporal 4.

66.54 GiB = 71,443,046,400 B  ÷ 24 heads ÷ 4 bytes  ->  N² = 744,198,400  ->  N = 27,280 tokens

27,280 = 40 × 22 × 31, i.e. 1280×704 at 121 frames. (Inferred, not logged; any W×H with (W/32)*(H/32) = 880 fits.)

4 bytes/element is the tell. Flash and memory-efficient attention are O(N) in working set and never materialise the matrix. Only the math backend allocates it.

Root cause

Probed in the Studio venv:

flash_sdp_enabled True | mem_efficient_sdp_enabled True | math_sdp_enabled True

FLASH    FAIL: No available kernel. Aborting execution.
MEM_EFF  FAIL: No available kernel. Aborting execution.
MATH     OK

UserWarning: Flash attention has been runtime disabled.
UserWarning: Memory Efficient attention has been runtime disabled.
UserWarning: Flash Efficient attention on Current AMD GPU is still experimental.
             Enable it with TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1

The *_sdp_enabled flags all report True, so nothing warns, but both kernels are runtime-disabled and dispatch degrades silently to math.

Meanwhile select_attention_backend (studio/backend/core/inference/diffusion_attention.py:142) leaves the default in place on any non-NVIDIA device:

# auto
if speed_active and _is_cuda_nvidia(target) and _cudnn_attention_supported():
    return "_native_cudnn"
return None          # ROCm lands here -> diffusers default "native" -> math kernel

On NVIDIA, falling through to native is safe because flash/mem-efficient sit underneath. On gfx1200 there is nothing underneath, so "leave the default" means "materialise N²". Any Wan generation past a small token count will do this, and it isn't reachable by lowering settings a notch.

Fix direction

1. Make auto prefer aiter on ROCm. The alias and its ROCm guard already exist in the same function, reachable today only by explicit request:

if backend == "aiter":
    if getattr(target, "device", None) == "cuda" and not _is_cuda_nvidia(target):
        return backend
    return None

Mirroring the cuDNN-on-NVIDIA upgrade for AITER-on-ROCm is a few lines in the auto branch. Needs confirming that AITER is installed and functional on gfx1200 first.

2. Fail fast when only the math backend exists. Probe the SDPA backends at load and, if only math is viable, either refuse with an explanation or cap resolution/frames to what N² actually fits, rather than spending 70 s to reach a guaranteed OOM.

3. Try TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 in the Studio environment. If AOTriton's kernels come up on gfx1200 the allocation disappears rather than shrinks. Untested here.

Two smaller problems this exposed

Expected

A 3.4 GB Q4_K_M model should generate 5 s of video on a 16 GB card.

Activity

  1. changed the title [-][Bug] Studio video: Wan2.2-TI2V-5B requests 71 GB on a 16 GB card — SDPA falls back to the math kernel on ROCm gfx1200[/-] [+][Bug] Studio video: Wan2.2-TI2V-5B requests 71 GB on a 16 GB card: SDPA falls back to the math kernel on ROCm gfx1200[/+] on Aug 9, 2026
  2. self-assigned this
    on Aug 9, 2026
  3. danielhanchen commented on Aug 9, 2026

    @danielhanchen
    Member

    Thanks Leo, this is a very good report and the arithmetic holds up.

    I have no gfx1200 here, so I want to be exact about what I could and could not check.

    What I confirmed. The decode is right. 4 bytes per element is the tell, and math is the only backend that materialises the matrix. More usefully, your point about the flags is the part that matters most: flash_sdp_enabled() and mem_efficient_sdp_enabled() report the user toggle, not whether a kernel exists, so they answer True on a build with no kernel and the dispatch degrades to math in silence. I reproduced that mechanism here on NVIDIA by picking a head_dim the fused kernels will not serve. All three flags still say True, flash, mem-efficient and cuDNN each raise No available kernel. Aborting execution., and the same "runtime disabled" warnings appear. Different cause, identical failure mode, and it means the condition is detectable without guessing.

    What I shipped, in #8233:

    • A real probe. Run a 4 KB attention under each SDPA backend and record what actually executes, rather than reading the flags. When select_attention_backend leaves the diffusers default in place and nothing sub-quadratic runs, Studio now says so at load, naming the quadratic cost, instead of letting it appear 70 seconds later as an allocation size.
    • The generation parameters on failure. video.generate_failed logged the exception and nothing else, which is why you had to divide 66.54 GiB by the head count to recover the shape. It now logs the resolved request next to the failure: the snapped width, height, frames, fps, steps, guidance, seed, device and offload policy. Prompt lengths rather than prompt text. An allocator failure on a math-only device also gets the diagnosis attached, so the next one of these arrives already explained.

    What I deliberately did not ship.

    • auto preferring aiter on ROCm. You flagged yourself that this needs AITER confirmed working on gfx1200 first, and I cannot confirm it. Shipping an untestable kernel selection is how the current silent fallback got there. If you can run import aiter in the Studio venv and report back, that is the missing piece and it is a few lines.
    • A hard refusal or a resolution cap. Small shapes run fine on math, and a cap needs per-family token math I cannot validate on the hardware where it would fire. The load-time warning is the fail-fast I am confident in: seconds instead of 70. Happy to be argued out of this.
    • TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1. Untested by you and untestable by me. If you try it, please say whether the allocation disappears or merely shrinks, since those imply different fixes.

    Still open. Your second smaller point is the real one and I have not fixed it: the pre-load VRAM check sizes weights and not peak, and attention is not in it at all. That is the same shape as #8220 and it wants its own change.

    One correction to my own scope. #8233 does not make your model generate. On gfx1200 it will still take the math path and still OOM at that resolution. What it does is tell you why, at load, and leave a log a report can be written from. The kernel fix needs someone with the card.

  4. charlesericwilson-portfolio commented on Aug 31, 2026

    @charlesericwilson-portfolio

    Additional reproduction: Qwen2.5-Coder-14B QLoRA training on 2× gfx1201 R9700 — SDPA math fallback causes 21.32 GiB allocation

    I am seeing what appears to be the same underlying ROCm SDPA fallback problem during actual LLM QLoRA training with Unsloth.

    Hardware

    • 2× AMD AI PRO R9700
    • 32 GB VRAM per GPU
    • gfx1201
    • Ubuntu 24.04.4 LTS

    Software

    • System ROCm: 7.2.4
    • PyTorch: 2.11.0 ROCm 7.2
    • transformers: 4.57.6
    • accelerate: 1.6.0
    • peft: 0.20.0
    • bitsandbytes: 0.49.2
    • Unsloth SFT / QLoRA
    • Python 3.12

    Model / training configuration

    Model:

    Qwen2.5-Coder-14B-Instruct

    Training:

    • 4-bit QLoRA
    • BF16 compute
    • LoRA r=128
    • LoRA alpha=128
    • LoRA targets: q/k/v/o/gate/up/down projections
    • max sequence length: 6000
    • per-device batch size: 2
    • gradient accumulation: 16
    • effective batch size: 32
    • 2 GPUs visible to Unsloth
    • model loaded with device_map="balanced"
    • Unsloth gradient checkpointing enabled

    The model is successfully sharded across both GPUs.

    Immediately before training, VRAM usage reported by PyTorch is approximately:

    • GPU 0: 4.68 GiB allocated / 5.44 GiB reserved
    • GPU 1: 6.77 GiB allocated / 7.78 GiB reserved

    Therefore this does not appear to be a model-weight capacity problem.

    Failure

    The OOM occurs during the first real attention forward:

    LlamaDecoderLayer_fast_forward
        -> self_attn
    
    LlamaAttention_fast_forward
        -> run_attention(
               config=config,
               context=context,
               Q=Q,
               K=K,
               V=V
           )
    
    unsloth/utils/attention_dispatch.py:596
        -> scaled_dot_product_attention(Q, K, V, **kwargs)
    
    torch.OutOfMemoryError:
    CUDA out of memory.
    Tried to allocate 21.32 GiB.
    
    GPU 0 total capacity: 31.86 GiB
    GPU 0 free at failure: 3.47 GiB
    PyTorch allocated: 27.78 GiB
    

    Why I believe this is SDPA math fallback

    Flash Attention itself works on this hardware/software stack.

    I separately tested an 8192-token BF16 Qwen-style GQA Flash Attention forward/backward workload on both gfx1201 GPUs successfully.

    The failure only appears when running the real attention call through Unsloth's attention_dispatch.py.

    The 21.32 GiB allocation also has the expected magnitude for materializing quadratic attention intermediates at approximately 6000 tokens.

    For comparison, I previously encountered the same problem on an older ROCm/Unsloth environment at 8192 tokens. That failure attempted an approximately 40 GiB allocation.

    Scaling that previous allocation quadratically:

    40 GiB × (6000 / 8192)^2 ≈ 21.46 GiB
    

    The current observed allocation is:

    21.32 GiB
    

    This strongly suggests that the current training call is again reaching the math SDPA backend and materializing the attention matrix rather than using fused Flash Attention.

    Packing appears relevant

    Current Unsloth output explicitly reports:

    Unsloth: Packing train dataset...
    Unsloth: Packing eval dataset...
    Unsloth: Packing enabled - training is >2x faster and uses less VRAM!
    

    The original 3971 training examples become 1397 packed examples.

    In my previous investigation of this problem on an older ROCm stack, I traced the failure through Unsloth's packed-attention handling.

    Packed sequence metadata caused Unsloth to construct an attention mask. The resulting SDPA invocation was no longer Flash eligible and PyTorch fell back to the math implementation.

    Removing the packed metadata prevented the catastrophic OOM, but that workaround made training unusably slow, so it was not a practical fix.

    Previous known-good behavior

    This workload is known to fit these GPUs.

    On these same two R9700 cards I have previously:

    • trained this 14B model at substantially longer context lengths
    • run this dataset around 12K maximum context
    • QLoRA-trained a 32B model

    The current 14B / 6000-token workload therefore should have substantial VRAM headroom when fused attention is being used.

    Suspected problem

    The likely failure path appears to be:

    Unsloth packed attention
            ↓
    attention_dispatch.py
            ↓
    SDPA arguments/mask make Flash backend ineligible
            ↓
    PyTorch scaled_dot_product_attention
            ↓
    ROCm silently selects math SDPA
            ↓
    full quadratic attention intermediates
            ↓
    21.32 GiB single allocation
            ↓
    OOM
    

    It would be extremely useful if Unsloth could either:

    1. keep packed LLM training on a ROCm-compatible fused attention backend on gfx1201, or
    2. detect when the call would fall back to math SDPA and fail with an explicit diagnostic rather than allowing an enormous quadratic allocation.

    I can provide the complete traceback if useful.

  5. charlesericwilson-portfolio commented on Aug 31, 2026

    @charlesericwilson-portfolio

    Update: root cause identified; additional multi-GPU AITER issue found

    Qwen2.5-Coder-14B QLoRA training on 2× gfx1201 R9700 — SDPA math fallback causes 21.32 GiB allocation

    I was able to narrow this down further and need to correct part of my original diagnosis.

    The ~21.32 GiB allocation was indeed coming from the packed SDPA/MATH fallback, but the reason Unsloth was entering that path was that flash_attn was not installed in this environment.

    Runtime inspection showed:

    HAS_FLASH_ATTENTION: False
    HAS_XFORMERS: False
    packed backend: sdpa
    

    After building FlashAttention 2.8.4 for ROCm using the Triton AMD backend, Unsloth correctly changed its dispatch to:

    HAS_FLASH_ATTENTION: True
    HAS_XFORMERS: False
    packed backend: flash_varlen
    dense backend: flash_dense
    

    I then tested flash_attn_varlen_func directly on an AMD Radeon AI PRO R9700 (gfx1201) using BF16, 40 Q heads / 8 KV heads, head_dim=128, causal attention, multiple packed sequence lengths totaling 6000 tokens, and forward + backward.

    That test passed successfully, with approximately 0.715 GiB peak allocated memory through backward.

    However, running the actual model sharded across two R9700s exposed a second issue in AITER's Triton FlashAttention implementation.

    When execution reached an attention layer on GPU1, AITER failed with:

    AssertionError: Device mismatch: Kernel will launch on cuda:0, but tensors are on cuda:1
    

    The relevant forward code obtains the current device with:

    current_device = torch.cuda.current_device()
    assert q.is_cuda and q.device.index == current_device

    but does not first establish the device context from the input tensor.

    The same pattern exists in the backward implementation.

    For testing, I added the following immediately before torch.cuda.current_device() in both the forward and backward paths:

    if q.is_cuda:
        torch.cuda.set_device(q.device)

    I then deliberately reproduced the problematic condition in isolation:

    current device BEFORE: 0
    Q device: cuda:1
    

    With the device guard applied, varlen FlashAttention correctly switched the launch context to GPU1 and completed both forward and backward:

    current device AFTER forward: 1
    out: torch.Size([6000, 40, 128]) cuda:1
    forward finite: True
    q grad finite: True
    k grad finite: True
    v grad finite: True
    GPU1 DEVICE-GUARD TEST PASSED
    

    The real packed QLoRA training run is now progressing without the previous catastrophic allocation. VRAM has remained stable so far.

    So the updated failure chain appears to be:

    flash_attn unavailable
        -> Unsloth packed backend = SDPA
        -> explicit packed attention mask
        -> ROCm fused SDPA unavailable for that call
        -> MATH fallback
        -> quadratic attention allocation / OOM
    

    After enabling FlashAttention:

    Unsloth packed backend = flash_varlen
        -> AITER Triton FlashAttention
        -> multi-GPU current-device mismatch
    

    The latter appears to be a separate multi-GPU device-context issue in the AITER Triton backend.

    I'll update again after the full training run has had enough time to establish stability.

    Thanks to everyone who looked into the original report.

    Clarification on the device-context workaround: this only addresses the case where Q/K/V/output are already correctly colocated on the same GPU, but PyTorch's current device still points to a different GPU.

    For example, my failing case was effectively:

    Q/K/V/output: cuda:1
    torch.cuda.current_device(): cuda:0
    

    The test workaround was to add the following immediately before the existing torch.cuda.current_device() check in both the AITER Triton FlashAttention forward and backward implementations:

    if q.is_cuda:
        torch.cuda.set_device(q.device)

    This makes the kernel launch context follow the GPU that already owns the attention tensors.

    It does not address a situation where Q, K, V, or the other tensors required by a single attention operation are themselves distributed across different GPUs. AITER's existing same-device assertions remain intact and should still reject that case.

    So this should be considered a workaround for a stale/missing device-context switch during model-sharded execution, not a general fix for arbitrary cross-device attention.

  6. LeoBorcherding commented on Sep 25, 2026

    @LeoBorcherding
    CollaboratorAuthor

    Fixed by #8821 (in v0.1.811-beta and later). Unsloth Studio's backend now turns on PyTorch's AOTriton attention kernels on the RX 9060 XT (gfx1200) and the other cards AOTriton marks experimental, so Wan attention no longer drops to the math kernel that asked for 66 GiB. On #8323's branch the same switch cut attention memory 67x on this card. #8233 added the load-time warning when only the math kernel exists, and logs the resolution, frames and steps when a video fails.

    Not done here: the pre-load VRAM check still sizes weights, not peak activations (same shape as #8220), and auto still doesn't pick AITER on ROCm.

    @charlesericwilson-portfolio, your gfx1201 case is a separate one: R9700 already has the fast kernels, and what you hit was flash_attn not being installed, then a device-context bug inside AITER's Triton flash attention on the second GPU. That last one belongs upstream in ROCm/aiter. If you still see a math fallback with flash_attn installed, a new issue with the traceback would be the right place.

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions