Skip to content

Build RoPE cos/sin caches only on the device that uses them - #13855

Merged
danielhanchen merged 8 commits into
mainfrom
dh/rope-cache-current-device
Oct 16, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
dh/rope-cache-current-device

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Unsloth's rotary classes (LlamaRotaryEmbedding and its scaled subclasses, LongRope, Gemma) built their cos/sin cache for every visible GPU in __init__ and again on every growth. LlamaModel_fast_forward also grew the cache to max_position_embeddings on its first forward. Under torchrun, every rank therefore allocated the full table on every GPU, and opened a CUDA context on each peer. For a 1M-context model that is 512 MiB of fp16 cos/sin per GPU per rank.

The cache is now built per device the first time that device reads it, and only with the rows callers ask for. That is the larger of this batch's length and max_seq_length, rounded up to the existing 8192 step, and never below the 32768 rows the cache used to start with. current_rope_size and the cache dtype still change exactly as before, and each row depends only on its position, so values are bit-identical. Devices that were built before a growth rebuild lazily on their next read. get_cached, extend_rope_embedding and forward keep their signatures. extend_rope_embedding gains an optional materialize_len. Gemma2's attention now reads the cache through get_cached instead of indexing the per-device list.

On Kaggle T4x2 (2-rank torchrun, a Llama-shaped model with 1M max positions, LoRA under DDP, 3 repeats per arm):

  • each process's memory on its own GPU drops from 1642 to 458 MiB;
  • its memory on the peer GPU drops from 1454 to 142 MiB;
  • the loss is identical at every step.

The remaining peer allocation comes from the gradient checkpointing buffers in unsloth-zoo, not from RoPE (unslothai/unsloth-zoo#1776 makes those lazy per device). On one GPU, loss, gradient norm and greedy generation are bitwise identical to main for Llama and Gemma2, and torch.compile graph breaks are unchanged.

tests/test_rope_cache_current_device.py runs the classes on CPU with a fake 4-device count. It fails on main and passes here.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 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-16T00:51:32.194829Z f379eb0 Manual request
🔒 Security Review ⚠️ Failed 2026-10-15T14:07:04.652895Z 76da785 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 76da7851f3

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

CI triage for this PR (run on base 90ac3b7):

danielhanchen added a commit that referenced this pull request Oct 15, 2026
…13887)

`Repo tests (CPU, rest)` is red on main since #13828 (e1cdbf4) and on
every PR based on it (e.g. #13855):

```
FAILED tests/test_formatter_fixed_point.py::test_every_tracked_python_file_is_already_formatted
these tracked files are not a fixed point of the ruff-format-with-kwargs hook, so pre-commit.ci will fail the next PR that edits them:
    tests/test_triton_fp_fusion.py
    Fix: python scripts/run_ruff_format.py tests/test_triton_fp_fusion.py
```

#13828 added that test with one generator expression over the 100-column
limit. This is the output of `python scripts/run_ruff_format.py
tests/test_triton_fp_fusion.py` with the pinned ruff 0.6.9, nothing
else: the one `any(...)` call is split over four lines. No logic change.

Verification:
- `tests/test_formatter_fixed_point.py` (ruff 0.6.9): fails on main as
above, 16 passed with this change.
- `tests/test_triton_fp_fusion.py`: 2 passed, 2 skipped (no GPU), same
as before.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@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: 5d2bd834ee

ℹ️ 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 thread unsloth/models/llama.py
Comment on lines +2250 to +2251
# Built per device on first use, not for every visible GPU here.
self._init_rope_cache_state(torch.get_default_dtype())

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 trace-stable initialization for rotary caches

When a rotary module is passed to torch.jit.trace before its first forward, the initial trace takes the cache-building path and records the arange/outer-product/trigonometric operations, while trace verification runs against the now-populated cache and takes a different path, causing the default trace consistency check to report differing graphs. The removed eager initialization explicitly existed to support torch.jit.trace; initialize only the active device before tracing or otherwise make lazy initialization trace-stable without restoring peer-device allocations.

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.

Nothing in Unsloth traces the rotary module with torch.jit.trace, and the traced call would be the module forward on a fixed device, which now builds its rows on first use exactly like the first eager call. Restoring eager per-device construction for that case would bring back the all-GPU allocation this PR removes, so I am leaving this as is.

Comment thread unsloth/models/llama.py
self.rotary_emb.extend_rope_embedding(hidden_states, self.config.max_position_embeddings)
# max_position_embeddings still sets the cache size and dtype as before, but only the rows
# this batch (or the declared max_seq_length) can index are built, on this device only.
rope_rows = max(seq_length_with_past, getattr(self, "max_seq_length", None) or 0)

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 Size the lazy cache for explicit position IDs

When a caller supplies a short chunk with absolute position_ids larger than both seq_length_with_past and the configured max_seq_length, this materializes too few rows even though those IDs can still be below config.max_position_embeddings. The attention path subsequently indexes the returned cos/sin tensors with those explicit IDs, so positions beyond the materialized range raise an out-of-bounds error; the previous full-config cache covered them. Include position_ids.max() + 1 in rope_rows when explicit IDs are present.

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.

The rows built cover max(seq_length_with_past, max_seq_length), which is every position a batch shaped within the configured max_seq_length can index, including generation (seq_length_with_past includes the cache). Explicit position ids beyond both would also be beyond what the model was set up for, and reading position_ids.max() would add a device sync to every forward.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

…2 / Cohere decode past max_seq_length)

[skip ci]
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 69e0718090

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

…evice count the removed eager init used to satisfy
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: a03aeb3918

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

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: f379eb063b

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

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 16, 2026
unslothai#13976)

Follow-up to unslothai#13855.

**1. Explicit position ids past the lazily built cache**

`LlamaModel_fast_forward` now builds `max(seq_length_with_past,
max_seq_length)` rows of the cos/sin cache, but
explicit `position_ids` (offsets, generate prefill, packing) can index
any row below
`max_position_embeddings`, and the RoPE kernel gathers without a bounds
check. A tiny Llama with 131072 positions,
`max_seq_length = 2048` and `position_ids` starting at 40000 returns NaN
logits on main; with this change the
logits match the transformers reference.

When `position_ids` is passed, the model forward builds
`max_position_embeddings` rows again, as before unslothai#13855,
still only on the device that reads them, so the multi-GPU saving stays.
Bounding the positions exactly would need
a host sync per forward, so it is not done. Without `position_ids` the
short cache is kept.

**2. Starting cache computed on CPU again**

Before unslothai#13855 `__init__` computed the starting cache on CPU. Built
lazily, it was computed wherever loading had
moved `inv_freq` (CUDA on transformers 4.57.6), which raised the first
forward's peak memory (about 16 MiB to
64 MiB for 32768 rows at head dim 128) and changed cos/sin rounding.
`_set_cos_sin_cache` now computes on CPU
until the cache first grows, and on `inv_freq`'s device afterwards,
matching the old behaviour in both cases.

**Tests**

`tests/test_rope_cache_current_device.py` gains three tests: explicit
offset positions through the real model
forward block, the short cache without `position_ids`, and the starting
cache computed on CPU. Two fail on main
and all pass here; the existing RoPE, formatter and encoding tests pass
(72 passed, 2 skipped).
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 19, 2026
…he KV length (unslothai#14156)

## Summary

unslothai#13855 made the RoPE cache lazy: it only builds the rows that are asked
for. `Qwen3Attention_fast_forward_inference` sized the cache read by the
KV length only. A decode step at an explicit position past the KV length
therefore indexed past the built rows and hit a CUDA device-side assert.
For example: a prefill without `position_ids`, then a hand-made decode
at position >= 32768. Base (before unslothai#13855) returned finite logits.
Normal `generate` is not affected.

The model-level decode loop already computes `rotary_seq_len =
max(kv_seq_len, position_ids.max() + 1)` once per step and passes it to
every layer. Qwen3 attention now sizes the RoPE extension and read from
it, so this adds no host sync. Without `rotary_seq_len` the previous
sizing is used.

## Tests

- New `tests/test_qwen3_decode_offset_rope.py` (tiny Qwen3, GPU): decode
at an explicit position past the lazily built rows. It fails on main
with the device-side assert and passes here.

Not fixed here: Gemma2, Cohere, Granite and FalconH1 read the cache the
same way. Their model-level loops do not compute `rotary_seq_len`, so a
fix there needs one host sync per decode step. Those are left for a
follow-up.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Oct 22, 2026
…mpiled decoder block (#14584)

The per-device RoPE cache is built lazily since #13855.
In GRPO without vLLM the first model call is TRL's HF
generate, which runs under `torch.inference_mode()`, so cos / sin (and
`inv_freq`) become inference tensors. The
first training forward passes them into the compiled decoder block;
AOTAutograd cannot save inference tensors for
backward, so the block raises `Inference tensors cannot be saved for
backward` and every layer falls back to the
stock forward for the rest of training:

```
Unsloth: Qwen3DecoderLayer block compile failed (Inference tensors cannot be saved for backward ...); keeping the stock forward for this layer.
```

The cache is now built under `torch.inference_mode(False)` +
`torch.no_grad()` when inference mode is on (no
change otherwise), also for LongRope's short cache copy. Values are
bitwise identical.

Tests: 5 new CPU tests in `tests/test_rope_cache_current_device.py` (4
fail on main). Tiny Qwen3 GRPO LoRA and
QLoRA, tiny Llama GRPO: 0 fallbacks (main: 2), compiled block engaged,
per-step grad norms bitwise equal to main,
0 graph breaks, 0 recompiles. SFT unchanged. Qwen3-0.6B GRPO step time
on L4 unchanged within noise (generation
dominates).

### Not covered
- GRPO with vLLM (not affected by reasoning: HF generate is not used
there); speed on longer sequences / bigger models (at 0.6B / 256 tokens
generation is 94% of the step); Gemma / LongRope end to end (unit tests
only); transformers 4.57.6 / TRL floor at runtime.
danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Oct 25, 2026
…inference_mode_enabled under compile) (unslothai#14728)

unslothai#14584 made the lazy per-device RoPE cache build outside
`inference_mode`, so a cache first built during `generate` stays
trainable. It asks `torch.is_inference_mode_enabled()` on every build,
and Dynamo cannot trace that call ("torch.is_inference_mode_enabled() is
not supported"). When a compiled region builds a device's cache first,
the call becomes a graph break, and an error under `fullgraph=True`.
That happens with a `device_map` split, where the outer forward warms
only the first device, or an attention path that reads the cache itself
(Mistral, Qwen3, Cohere, Gemma 2, Falcon-H1). The resumed frames then
break again on `torch.device(...)`.

Fix: `_rope_build_mode` returns a null context while compiling.
Unsloth's compiled decoder blocks only run in training, outside
`inference_mode`, so the escape is not needed there. Eager builds keep
unslothai#14584's behaviour exactly.

Measured on one B200, torch 2.11.0, attention-style block compiled with
`dynamic=True`, cache cold on the first call, lengths 64 / 80 / 96 /
127:

| Tree | default compile | fullgraph=True |
|---|---|---|
| aa0b22b (unslothai#13855, lazy cache) | 0 graph breaks, 2 graphs | pass |
| main | 7 graph breaks, 7 graphs | Unsupported:
is_inference_mode_enabled |
| this branch | 0 graph breaks, 2 graphs | pass |

With the cache already warm, as the outer forward leaves it on
single-GPU runs, main and this branch both trace in one graph per shape
bucket, so single-GPU training is unchanged.

Tests:
-
`tests/test_rope_cache_current_device.py::test_cold_build_under_compile_never_asks_for_inference_mode`
(CPU, Llama / Gemma / LongRoPE): fails on main, passes here. The
existing inference-mode trainability tests still pass.
-
`tests/test_rms_rope_compile.py::test_rope_cache_cold_build_traces_without_graph_breaks`
(GPU, default and fullgraph): a cold build inside a compiled function,
no graph break, matches eager.

---------

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant