Skip to content

Attention dispatch: route long SDPA training calls through automatic saved-attention GC replay - #18488

Merged
danielhanchen merged 2 commits into
mainfrom
mg-saved-attention-auto
Nov 19, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
mg-saved-attention-auto

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Needs unslothai/unsloth-zoo#2619, which adds the automatic saved-attention mode and its memory budget. This PR makes run_attention route long training calls through it. With an unsloth_zoo that lacks the automatic mode, or with UNSLOTH_GC_SAVE_ATTENTION=0, nothing changes.

Summary

With use_gradient_checkpointing = "unsloth", UNSLOTH_GC_SAVE_ATTENTION=1 lets the checkpoint replay reuse each layer's attention output instead of recomputing it. That is up to +16% tokens/s at long context, but it is opt-in because the kept outputs cost VRAM. With the variable unset, Unsloth now uses it automatically, in a conservative way:

  • only when unsloth_zoo enables the automatic mode for this GPU: T4 and A100 from 8K, L4 from 16K, off on every other GPU, on ROCm and on CPU;
  • only for training calls on the SDPA backend, with no packing (seq_info) and no PrefixGrouper, whose query length is at or above that threshold;
  • only while unsloth_zoo's per-device budget has room for the kept outputs. It learns the run's own peak without resetting the user's peak stats, keeps nothing until a step of that size has been measured, and keeps part of the layers when memory is short.

Shorter calls, other backends and =0 take the plain call exactly as today: a shape check in Python, with no graph break and no extra work. =1 / offload keep their current behaviour (every training call, no budget).

Setting run_attention training calls
unset / auto routed only when q_len >= threshold, SDPA, unpacked, and unsloth_zoo enabled the mode for this GPU
0 never routed (today's behaviour)
1 / offload always routed (unchanged)

Numbers

Colab, Qwen3-4B LoRA r=16, batch 1, SDPA. Each arm runs in its own process, interleaved on one VM, 3 runs per arm. Tokens/s comes from the median step, and the spread is (max - min) / median, with the base spread as the A/A noise. Full tables and method are in the zoo PR.

GPU Seq today tok/s (A/A spread) auto vs today =0 vs today
A100 40GB bf16 4K 5989 (0.3%) -0.2% (not routed) -0.2%
A100 40GB bf16 8K 5299 (0.5%) +7.3% -0.0%
A100 40GB bf16 16K 4157 (0.2%) +11.1% -0.2%
A100 40GB bf16 32K 2843 (0.1%) +15.9% +0.1%
T4 fp16 4-bit 4K 575 (8.1%) +1.0% (not routed) -0.9%
T4 fp16 4-bit 8K 455 (0.4%) +10.1% -0.2%
T4 fp16 4-bit 16K 306 (0.0%) +15.1% -0.0%
L4 bf16 8K 1236 (6.9%) not routed (threshold 16K; +2.1% when routed, inside noise) -2.5%
L4 bf16 16K 965 (0.5%) +10.1% -0.0%

Near-full memory: a ballast tensor leaves base little headroom. A100 at 32K: auto keeps 15 to 17 of 36 layers per step, +5.7%, no OOM. T4 at 16K: 17 to 19 of 36 layers, +6.6%, no OOM. L4 at 16K: 15 to 18 of 36 layers, +3.6%, no OOM. =1 runs out of memory in its first step in all three cases.

Changes

  • unsloth/utils/attention_dispatch.py: _load_saved_attention() returns (call, min_seq). An explicit setting gives (saved_attention_call, None) and routes every training call, as before. Automatic mode gives the threshold from unsloth_zoo.saved_attention.save_attention_auto_min_seq(). An unsloth_zoo without that function gives (None, None). run_attention checks _auto_saves_attention(config, context) only when automatic mode is on.

  • tests/test_attention_dispatch_saved_attention.py:

    • routing on a measured GPU, plus the kill switch (0, false) and unmeasured GPU / ROCm off;
    • the explicit setting routing every call, and an older unsloth_zoo (no automatic mode) staying off;
    • only long unpacked SDPA calls routed (no xformers, no packed calls, nothing below the threshold);
    • an end-to-end CPU run through run_attention and the Unsloth checkpoint: the first step measured, the second reused, grads equal.

    These fail on the base commit and pass here (45 passed together with the zoo tests).

Tests

  • tests/test_attention_dispatch_saved_attention.py and the zoo's tests/test_gc_saved_attention.py: 45 passed on CPU. The CUDA tests pass on a B200 (47 passed).
  • The other attention tests in tests/test_*attention*.py: 202 passed, 198 skipped. The same 2 failures in test_flash_attention_sub_config_fallback.py happen on the base commit too.
  • B200, tiny Llama / Qwen3 LoRA through FastLanguageModel, block compile on, fp32 and bf16, 3 steps. Auto engaged at a low test threshold vs =0: identical losses, LoRA grads equal in fp32 (rel. diff 0), and in bf16 inside the =0 vs =0 spread. Auto with the threshold above the sequence: 0 graph breaks and 2 graphs, the same as =0.

Not proven

  • Other GPUs (sm86, H100, B200, RTX 50 / G4) stay off until measured. L4 stays off below 16K.
  • FlashAttention 2, xformers, packed batches, FlexAttention and context parallel keep today's path in automatic mode.
  • Multi-GPU and other models were not timed. AMD CI was not run: the mode is off on ROCm by construction.

… calls

With UNSLOTH_GC_SAVE_ATTENTION unset, training attention calls of at least
the threshold length on the SDPA backend (unpacked) go through
unsloth_zoo's saved_attention_call when unsloth_zoo enables its automatic
mode for this GPU; shorter calls keep the plain traceable call. An
unsloth_zoo without the automatic mode, ROCm, CPU and =0 keep today's path.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-19T15:17:23.148168Z 717f4cc Manual request
ℹ️ About Codex in GitHub

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

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

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

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 717f4cc427

ℹ️ 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 added a commit that referenced this pull request Nov 19, 2026
## Summary

`pinned-symbol matrix (vLLM, TRL, PEFT, ST, bitsandbytes, transformers)`
fails on `main` for every PR (seen on #18488, which only touches
attention dispatch):

```
FAILED tests/version_compat/test_peft_conversion_symbol_backfill.py::test_the_fused_snapshot_matches_upstream
E   AssertionError: fused MoE types missing from the snapshot: ['sarvam_mla']
```

## Root cause

Not a change in this repo. transformers `main` added `"sarvam_mla":
"qwen2_moe"` to `src/transformers/conversion_mapping.py`.
`unsloth/import_fixes.py` keeps a snapshot of that map
(`_PEFT_MOE_CONVERSION_PATTERNS`) for PEFT versions where the live map
is gone, and `test_the_fused_snapshot_matches_upstream` is the canary
that fetches the upstream file and fails when a fused MoE alias is
missing from the snapshot. It did its job: `sarvam_mla` has no "moe" in
its name, so without the entry the stand-in would silently miss it.

## Changes

- `unsloth/import_fixes.py`: add `"sarvam_mla": "qwen2_moe"` to
`_PEFT_MOE_CONVERSION_PATTERNS`, next to the other upstream aliases,
with a dated note like the existing ones.

## Testing

- `pytest tests/version_compat/test_peft_conversion_symbol_backfill.py`:
69 passed.
- The canary fetched the live upstream map in both arms (not skipped):
passes with this change, fails without it with the error above.
@danielhanchen
danielhanchen merged commit a8cad8c into main Nov 19, 2026
@danielhanchen
danielhanchen deleted the mg-saved-attention-auto branch November 19, 2026 16:56
FiditeNemini pushed a commit to FiditeNemini/unsloth-zoo that referenced this pull request Nov 19, 2026
…uences, within a device memory budget (unslothai#2619)

## Summary

`UNSLOTH_GC_SAVE_ATTENTION=1` (unslothai#2571) keeps each layer's attention
output and logsumexp from the first pass, so the gradient checkpoint
replay skips the attention forward. It is faster at long context, but it
is opt-in because the kept outputs cost VRAM: 9.1 GiB at 32K on
Qwen3-4B, which could turn a run that fits today into an OOM.

This PR adds an automatic mode, used when the variable is unset (or
`=auto`). It turns on only where it was measured faster, and it keeps
outputs only while they fit in the memory the run is not using:

| Setting | Behaviour |
|---|---|
| unset / `auto` (new default) | automatic: measured GPUs, long SDPA
calls, memory budget |
| `0` | off: exactly today's behaviour (no routing, no frames, no
patching) |
| `1` / `offload` | unchanged: every call kept, no budget |

On Qwen3-4B LoRA (batch 1), automatic vs today: A100 +7.3% / +11.1% /
+15.9% tokens/s at 8K / 16K / 32K; T4 +10.1% / +15.1% at 8K / 16K; L4
+10.0% at 16K. With almost no free VRAM it keeps part of the outputs: no
OOM, still +5.7% (A100), +6.6% (T4) and +3.6% (L4). In the same setup
`=1` runs out of memory.

The Unsloth side (routing only long SDPA calls) is in
unslothai/unsloth#18488. Without it this PR changes nothing: frames are
only created once a caller turns the automatic mode on.

## Gate

`save_attention_auto_min_seq()` returns the query length from which a
caller should route training attention calls through
`saved_attention_call`, or `None` when the automatic mode is off. The
mode is off when:

- the setting is anything other than unset / `auto`;
- the run is on ROCm (its SDPA kernels are not intercepted) or has no
CUDA;
- the GPU's compute capability is not in the measured table: sm75 (T4)
from 8K, sm80 (A100) from 8K, sm89 (L4) from 16K.

When it returns a length, it also marks the mode active, and from then
on `UnslothCheckpointFunction` gives checkpointed calls an automatic
frame. `UNSLOTH_GC_SAVE_ATTENTION_MIN_SEQ` overrides the length (used by
the tests).

## Memory budget

Each automatic frame asks a per-device budget before it keeps a call's
outputs:

- **The run's own peak.** This is learnt from the allocator's running
peak (`allocated_bytes.all.peak`), read without resetting it, so the
user's peak memory statistics are left alone. The kept bytes only change
inside these hooks, and every hook reads the peak first. So a new peak
is charged with exactly the bytes that were kept while it was reached,
and the learnt peak never includes our own outputs. Without this, the
budget would shrink every step until nothing was kept. A reset of the
peak stats by the user is handled: the lower reading is charged the same
way, and the learnt peak only grows.
- **Capacity.** Free memory plus this process's reserved memory, capped
by `torch.cuda.set_per_process_memory_fraction`. It is read with
`mem_get_info` only while nothing is kept: at the first kept layer of a
step, or once per layer in a step that keeps nothing.
- **Rule.** A call is kept only while `kept + this call <= capacity -
margin - learnt peak`, with margin = max(1 GiB, 6% of capacity).
Otherwise it is recomputed as today and counted as `declined_budget`.
Partial keeping gives a proportional gain.
- **Unmeasured sizes.** Nothing is kept for a call larger than any call
already seen through a whole step (counted as `declined_unmeasured`).
The first step therefore keeps nothing, and a longer batch later in a
run keeps nothing until its own peak has been seen.
- **Release.** A frame's bytes are released when its replay starts (the
replay would allocate them anyway), or when the frame is dropped without
a backward.

Per routed layer, the cost is one or two allocator-stat reads in the
first pass and one at the replay of a kept layer. Nothing is added to
the non-checkpointed or inference paths.

Counters in `SAVED_ATTENTION_STATS`: `stored`, `reused`,
`declined_budget`, `declined_unmeasured`, `kept_bytes`.

## Numbers

Colab, Qwen3-4B LoRA r=16 on all linear layers, batch 1, random tokens,
AdamW, SDPA attention. torch 2.14.1, transformers 5.18.0, unsloth /
unsloth_zoo installed at the base commits, with this branch applied as a
patch for the head arms. Each arm runs in its own process, interleaved
on one VM (base, auto, kill, =1, then repeated). Tokens/s comes from the
median timed step: 3 warmup + 5 timed steps, or 2 + 3 on T4. Spread =
(max - min) / median over the runs of that arm, and the base spread is
the A/A noise. `kill` is this branch with `=0`.

| GPU | Seq | base tok/s (A/A spread) | auto (spread) vs base | kill vs
base | `=1` vs base | peak alloc GiB base / auto | auto stored / reused
per step |
|---|---|---|---|---|---|---|---|
| A100 40GB bf16 | 4K | 5989 (0.3%, n=3) | 5975 (0.3%) -0.2% | -0.2% |
+3.6% | 8.73 / 8.73 | 0 / 0 (below threshold) |
| A100 40GB bf16 | 8K | 5299 (0.5%, n=3) | 5689 (0.2%) +7.3% | -0.0% |
+7.3% | 9.45 / 11.59 | 36 / 36 |
| A100 40GB bf16 | 16K | 4157 (0.2%, n=3) | 4621 (0.1%) +11.1% | -0.2% |
+11.1% | 10.89 / 15.45 | 36 / 36 |
| A100 40GB bf16 | 32K | 2843 (0.1%, n=3) | 3295 (0.1%) +15.9% | +0.1% |
+16.0% | 14.12 / 22.70 | 36 / 36 |
| T4 fp16 4-bit | 4K | 575 (8.1%, n=3) | 581 (5.9%) +1.0% | -0.9% |
+5.4% (n=1) | 4.55 / 4.55 | 0 / 0 (below threshold) |
| T4 fp16 4-bit | 8K | 455 (0.4%, n=3) | 501 (1.6%) +10.1% | -0.2% |
+9.5% (n=1) | 5.27 / 7.41 | 36 / 36 |
| T4 fp16 4-bit | 16K | 306 (0.0%, n=3) | 353 (0.1%) +15.1% | -0.0% |
+15.2% (n=1) | 6.71 / 11.27 | 36 / 36 |
| L4 bf16 | 4K | 1487 (10.1%, n=3) | 1424 (5.5%) -4.3% | -7.0% | +0.5% |
8.73 / 8.73 | 0 / 0 (below threshold) |
| L4 bf16 | 8K | 1236 (6.9%, n=3) | 1262 (3.7%) +2.1% | -2.5% | +2.7% |
9.45 / 11.59 | 36 / 36 (shipped: not routed, see below) |
| L4 bf16 | 16K | 965 (0.5%, n=3) | 1062 (0.3%) +10.1% | -0.0% | +9.9% |
10.89 / 15.45 | 36 / 36 |

The L4 auto arm ran with an 8K threshold, before the 16K threshold was
set from these numbers. Its 8K row (+2.1%) is inside L4's A/A noise
(6.9%), so L4 starts at 16K. At 4K, L4's `kill` and auto arms run
exactly today's code and still differ from base by -7.0% and -4.3%: that
is L4's run-to-run noise at short lengths. Below each threshold, auto
runs the same code as today: the A100 and T4 4K rows are inside A/A.
Every auto step after the first stored and reused all 36 layers. The
first step at each new length declined all 36 (`declined_unmeasured`).
Losses stay inside the A/A run-to-run difference. The largest |loss
diff| from the first base run, over every length, is 0.0019 for auto
against 0.0025 for the other base and kill runs on A100, and 0.00031
against 0.00038 on T4. The near-full runs give 0.0009 and 0.0003.

### Near-full memory

A ballast tensor leaves only margin + 40% of what `=1` would keep above
base's own peak. Same VM, interleaved.

| GPU | Seq | base tok/s (n=2) | auto tok/s (n=2) vs base | auto kept
per step | auto peak alloc GiB / card | `=1` |
|---|---|---|---|---|---|---|
| A100 40GB | 32K | 2860 | 3025 +5.7% | 15 to 17 of 36 layers (19 to 21
`declined_budget`) | 37.00 / 39.5 | OOM in step 1 |
| T4 | 16K | 289 | 308 +6.6% | 17 to 19 of 36 layers (17 to 19
`declined_budget`) | 13.58 / 14.6 | OOM in step 1 |
| L4 | 16K | 971 (n=1) | 1007 +3.6% | 15 to 18 of 36 layers (18 to 21
`declined_budget`) | 20.72 / 22.0 | OOM in step 1 |

The second L4 near-full base run stalled on Colab (the VM stopped
printing), so L4 near-full has one base run. The L4 main-matrix A/A at
16K is 0.5%.

## Tests

- `tests/test_gc_saved_attention.py` (CPU; the allocator is faked where
needed):
- the first step keeps nothing, then every layer is kept and reused,
with grads equal to today's GC;
  - with room for 2 of 3 layers, exactly 2 are kept per step;
  - with no headroom, nothing is kept;
  - the learnt peak excludes the kept bytes across 4 steps (no ratchet);
  - a call longer than any measured one keeps nothing;
- frames need a routing caller, and `0` / `false` / `off` and `1` keep
their modes;
- the per-GPU thresholds, plus off on unmeasured GPUs (sm86, sm90,
sm100, sm120), ROCm, no CUDA, `0`, `1` and `offload`.

On the base commit the new tests fail (21 failed, 6 errors); on this
branch 45 pass with the unsloth tests.
- CUDA: the same automatic test with the real allocator (bf16, 3 steps:
3 declined as unmeasured, then 6 stored / 6 reused, the learnt peak at
or above the base run's peak, peak stats never reset). It passes on a
B200 together with the existing CUDA tests (47 passed).
- B200, tiny Llama and Qwen3 through `FastLanguageModel` with LoRA,
block compile and `use_gradient_checkpointing = "unsloth"`, bsz 2 x
1024, 3 steps. Arms: kill switch, kill switch again (A/A), auto engaged
at a 256 threshold (compute capability added for the test), and auto
with a threshold above the sequence. The worst LoRA grad rel. diff vs
the kill switch:

| Model | dtype | A/A | auto (stored / reused) | auto, threshold above
seq |
|---|---|---:|---:|---:|
| Llama | fp32 | 0 | 0 (4 / 4) | 0 |
| Qwen3 | fp32 | 0 | 0 (4 / 4) | 0 |
| Llama | bf16 | 2.1e-5 | 0 (4 / 4) | 1.0e-3 |
| Qwen3 | bf16 | 1.7e-3 | 1.9e-3 (4 / 4) | 1.9e-3 |

Losses are identical in every arm. Graph breaks: 0 for the kill switch
and for auto above the threshold (2 graphs each, the same as today).
Auto engaged adds 10 graph breaks, one per routed call.

## Not proven

- L4 below 16K, and every GPU outside the table (sm86 consumer Ampere,
H100 sm90, B200 sm100, RTX 50 / G4 sm120): automatic mode stays off
there. On A100, 4K would also gain (+3.6% with `=1`), but T4 and L4 at
4K are inside noise, so the threshold stays at 8K.
- FlashAttention 2 / xformers backends, packed (varlen) batches and
FlexAttention: the Unsloth side routes only unpacked SDPA calls, so
these keep today's path.
- The budget assumes a run's peak does not grow for calls no larger than
ones already measured. A workload whose peak jumps for another reason
(for example a much larger vocabulary chunk, or another process
allocating on the same GPU mid-step) still has only the margin as a
cushion.
- Multi-GPU (DDP / FSDP) and other models were not timed.
- ROCm stays off by construction. AMD CI was not run for this change.
Stanley00 pushed a commit to stanley-fork/unsloth that referenced this pull request Nov 20, 2026
…qa floor, block SDPA cache tag (unslothai#18631)

Follow-up fixes for unslothai#18488, unslothai#18453, unslothai#18462, found while re-checking the
PRs merged on 2026-11-19. One commit per fix; every fix has a test that
fails on main and passes here.

| Fix | Follows up | Severity |
|---|---|---|
| Attention dispatch: automatic saved attention only inside Unsloth's
checkpoint | unslothai#18488 | P2 |
| ROCm SDPA self-check: no enable_gqa on torch without it | unslothai#18453 | P2
|
| Block SDPA align guard: cache tag also under the override | unslothai#18462 |
P2 |

## Tests (this branch vs main `54af93780b`, CPU)

- New and changed tests: main 8 failed / 16 passed, this branch 24
passed. Each test loads the code of its own tree.
- Neighbouring suites on this branch: attention dispatch, ROCm SDPA
check and block SDPA guard suites: 61 passed, 5 skipped.
- `prepush_gate.py` passes.

## Attention dispatch: automatic saved attention only inside Unsloth's
checkpoint (follows up unslothai#18488)

#### Summary

Follow-up to unslothai#18488. With `UNSLOTH_GC_SAVE_ATTENTION` unset, automatic
saved attention now routes a long training call only where a
saved-attention frame can exist. That means under Unsloth's smart
checkpoint (`use_gradient_checkpointing = "unsloth"`) and, when the call
is traced, only inside Unsloth's own compiled block.

#### What broke

unslothai#18488 routes every unpacked SDPA training call at or above the
threshold through `unsloth_zoo.saved_attention.saved_attention_call`.
The zoo creates frames only inside `UnslothCheckpointFunction` (zoo
`gradient_checkpointing.py:2074`). With `use_gradient_checkpointing =
True` or `False`, `apply_unsloth_gradient_checkpointing` unpatches it,
so no frame ever exists. `saved_attention_call` is
`@torch.compiler.disable`d and with no frame it just runs the plain
call. Inside a compiled decoder block (per-block compile is on by
default for FastLanguageModel on torch >= 2.11), each long attention
call therefore becomes a graph break that saves nothing. Under a user's
`torch.compile(..., fullgraph=True)` it raises `Unsupported: Skip
calling torch.compiler.disable()'d function`.

This only happens where zoo turns on automatic mode: T4 and A100 from 8K
tokens, L4 from 16K.

#### Repro (CPU, automatic mode simulated with a threshold of 16,
32-token call, no smart checkpoint)

| arm | default compile | `fullgraph=True` |
|---|---|---|
| automatic mode off (before unslothai#18488) | 0 graph breaks | compiles |
| main | 3 graph break records (`Skip calling torch.compiler.disable()'d
function`), no frame active | `Unsupported` |
| this branch | 0 graph breaks | compiles |

#### Fix

`_auto_saves_attention` now also requires
`_saved_attention_frames_possible()`:

- `torch.utils.checkpoint.CheckpointFunction` is
`UnslothCheckpointFunction`. Dynamo cannot read a Function class's name,
so this read goes through `_constant_probe`. The patch is installed at
`get_peft_model` / load time, before any trace.
- When traced, `unsloth.models._block_compile._IN_COMPILED_REGION[0]`
must be set. That flag marks Unsloth's own block (`fullgraph=False`,
where a break is legal) and not a user's compile. zoo's sequence tiling
reads the same flag.

- In automatic mode the setting must still be `auto` when the call is
made. `UNSLOTH_GC_SAVE_ATTENTION=0` set after `import unsloth` stops
zoo's frames (`new_saved_attention_frame`), but before this change it
did not stop the routing, so it still produced a graph break per layer
inside Unsloth's own block.

The explicit `=1` / `offload` setting (min_seq None) is unchanged.

#### Tests

New `tests/test_attention_dispatch_saved_attention_scope.py` (CPU):
- automatic mode routes only under the smart checkpoint;
- a user's compile has 0 graph breaks with and without the smart
checkpoint, and `fullgraph=True` compiles;
- inside Unsloth's block under the smart checkpoint the call is still
routed;
- the explicit setting still routes;
- `UNSLOTH_GC_SAVE_ATTENTION=0` / `false` set after import stops routing
and leaves 0 graph breaks inside Unsloth's block.

`tests/test_attention_dispatch_saved_attention.py`: the two
automatic-mode routing tests now install `UnslothCheckpointFunction`, as
a real "unsloth" run does.

Command (per worktree, unsloth_zoo main on `PYTHONPATH`): `python -m
pytest -o addopts= -m "not server and not native_mxc" -p
no:cacheprovider -q
tests/test_attention_dispatch_saved_attention_scope.py
tests/test_attention_dispatch_saved_attention.py`. Each arm imports its
own tree.

| arm | result |
|---|---|
| main (635532f) | 6 failed, 14 passed |
| this branch | 20 passed |

Wider suites (`tests/*attention*.py`, `tests/test_sdpa*.py`,
`tests/utils/test_rocm_sdpa_check.py`): main 2 failed / 255 passed / 302
skipped. This branch: 2 failed / 261 passed / 302 skipped. The same two
failures in `test_flash_attention_sub_config_fallback.py` show up on
main.

#### Not proven here

- No GPU run. Step time for `use_gradient_checkpointing = True` at 8K on
an A100 or T4 (main vs this branch) needs a real card. The
smart-checkpoint path is unchanged, so unslothai#18488's measured gains still
apply.
- Layers that "unsloth" checkpointing leaves unwrapped (frozen bottom
layers skipped by unslothai#18442) still reach the routed call with no frame.
This change does not cover them.

## ROCm SDPA self-check: no enable_gqa on torch without it (follows up
unslothai#18453)

#### Summary

Follow-up to unslothai#18453. On torch 2.4, the declared floor, the ROCm SDPA
self-check refused AOTriton flash for every Unsloth attention call on an
RDNA GPU. The kernel was never the cause: the check sent an argument
that torch 2.4 does not have.

#### What broke

The flash child in `unsloth/utils/rocm_sdpa_check.py` runs a
`segments_gqa` case that calls `F.scaled_dot_product_attention(...,
enable_gqa=True)`. torch added `enable_gqa` in 2.5. On 2.4 the call
raises `TypeError: scaled_dot_product_attention() got an unexpected
keyword argument 'enable_gqa'`. The child records any exception other
than "No available kernel" or out of memory as a failed kernel case, so
the report says `ok: false` and `rocm_sdpa_verdict` refuses flash for
that device. Unsloth itself never passes `enable_gqa` when SDPA lacks it
(`SDPA_HAS_GQA` in `attention_dispatch.py`), so no real call can reach
that layout there.

#### Repro (CPU)

The real child script runs in a subprocess. CUDA calls are mapped to CPU
(torch's CPU flash kernel, which is correct), and
`F.scaled_dot_product_attention` is replaced by one that rejects
`enable_gqa`, as torch 2.4's operator does.

| arm | flash child report |
|---|---|
| main (635532f) | `ok: false`, ran 8, every failure is `segments_gqa
...: unexpected keyword argument 'enable_gqa'` |
| this branch | `ok: true`, ran 4 (expanded K / V segments, fp16 and
bf16, head dims 64 and 128) |

#### Fix

When `enable_gqa` is not in `F.scaled_dot_product_attention.__doc__`,
the child drops the `segments_gqa` case. That is the same test
`attention_dispatch` uses. The expanded K / V and masked cases still
run, so a broken kernel is still refused.

#### Tests

New `tests/utils/test_rocm_sdpa_check_no_gqa.py` (CPU). Command (per
worktree): `python -m pytest -o addopts= -m "not server and not
native_mxc" -p no:cacheprovider -q
tests/utils/test_rocm_sdpa_check_no_gqa.py
tests/utils/test_rocm_sdpa_check.py`. Each arm imports its own tree.

| arm | result |
|---|---|
| main | 1 failed, 24 passed, 2 skipped |
| this branch | 25 passed, 2 skipped |

#### Not proven here

- No ROCm torch 2.4 hardware run, and no claim about which RDNA archs
torch 2.4 offers AOTriton flash on. Where it does not offer flash, this
change makes no difference.
- torch >= 2.5 keeps the `segments_gqa` case unchanged.

## Block SDPA align guard: cache tag also under the override (follows up
unslothai#18462)

#### What broke

unslothai#18462 adds the cache tag `unsloth/efficient-backward-guard` so that
graphs compiled without the efficient-backward guard are not served
again. The patched SDPA lowering is not part of the FX / AOT cache key.
`UNSLOTH_BLOCK_SDPA_ALIGN_GUARD=1` returned before adding that tag.

On CUDA torch < 2.14, a run with the override therefore has the same
cache key as a run of the same Unsloth version from before the tag
existed. The version string is 2026.11.7 both before and after unslothai#18462.
That older run compiled the efficient backward without the guard. A user
who set the override as the workaround for the `attn_bias is not
correctly aligned` fault, and kept it after updating, keeps being served
the faulting backward from a warm cache. The PR's own evidence notes the
override was not a reliable workaround once a failing run had warmed the
cache.

#### Fix

`unsloth/models/_block_compile.py`, `_sdpa_alignment_without_guard`:
under the override on an affected torch, add the same cache tag before
returning. The lowering stays stock as before. Torch 2.14+ and ROCm are
unchanged.

#### Tests

New `tests/test_block_sdpa_align_guard_override_cache_tag.py` (CPU, no
compile): with the override set, the lowering must stay untouched. The
tag must be added exactly once on an affected torch and not on 2.14+.
The test loads `_block_compile.py` from its own tree and asserts it.

| Arm | Result |
|---|---|
| main | 1 failed (`torch_lt_2_14`), 2 passed |
| this branch | 3 passed on torch 2.14.1; on torch 2.4.1 (no
`cache_key_tag`) the tag tests skip with that reason |

`tests/test_block_sdpa_efficient_backward_guard.py` passes on both arms.

#### Not covered

No warm-cache GPU run of the fault itself.

## Not proven here

Step time and memory of long-sequence SFT with and without automatic
saved attention; ROCm hardware (gfx1151 / gfx942) for the self-check;
torch 2.14 on GPU for the align guard.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant