Skip to content

Cover explicit RoPE position ids and compute the starting cache on CPU - #13976

Merged
danielhanchen merged 5 commits into
mainfrom
dh/rope-cache-bounds
Oct 16, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
dh/rope-cache-bounds

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Follow-up to #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 #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 #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).

LlamaModel_fast_forward built only max(seq_length_with_past, max_seq_length)
rows of the cos/sin cache after #13855, but explicit position_ids (offsets,
generate, packing) may index any row below max_position_embeddings. A
tiny Llama with 131072 positions and position_ids starting at 40000 now
returned NaN logits. When position_ids are passed the model forward builds
max_position_embeddings rows again, as before #13855, still only on the
device that reads them. Without position_ids the short cache is kept.

The starting cache is computed on CPU again, as the eager __init__ build
did, so loading paths that move inv_freq to an accelerator do not raise
the first forward's peak memory or change its values. Growth still
computes on inv_freq's device.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 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-16T08:53:35.719165Z 738758f Manual request
🔒 Security Review ⚠️ Failed 2026-10-16T07:23:21.819069Z 7501212 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 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: 7501212b1f

ℹ️ 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
if position_ids is not None:
# Explicit positions (offsets, generate, packing) can index any row below
# max_position_embeddings; bounding them needs a host sync, so build them all as before.
rope_rows = max(rope_rows, self.config.max_position_embeddings)

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 Preserve LongRoPE's short branch for short explicit positions

When self.rotary_emb is LongRopeRotaryEmbedding, a short forward with explicit positions inside the pretrained window now raises rope_rows to the configured maximum (for example, 128K versus an original 4K window). The subsequent get_cached(rope_rows, ...) therefore selects the long-factor cache solely because this allocation bound exceeds original_max_position_embeddings, changing the positional embeddings for otherwise short inputs. Keep the materialization bound separate from the actual sequence/position length used to select LongRoPE's short or long 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.

Valid, fixed in e462529: the forward now keeps the number of rows to build (rope_rows, max_position_embeddings when position_ids are passed) separate from the length passed to get_cached (rope_len, the same expression as before), so LongRoPE picks its short or long factors exactly as it did. Test: test_model_forward_position_ids_keep_longrope_short_factors.

Explicit position_ids raise the rows built to max_position_embeddings,
but get_cached also used that bound as the length, so LongRoPE took its
long factors for short inputs. The model forward now builds rope_rows
and passes the batch length (seq_length_with_past or max_seq_length) to
get_cached, as before position_ids widened the build.

[skip ci]
@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: e462529ec7

ℹ️ 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 Outdated
)
position_embeddings = self.rotary_emb.get_cached(rope_rows, hidden_states.device.index)
# rope_rows only sizes the build; LongRoPE picks its short or long factors from rope_len.
position_embeddings = self.rotary_emb.get_cached(rope_len, hidden_states.device.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.

P1 Badge Select LongRoPE cache using explicit positions

When LongRopeRotaryEmbedding receives explicit position_ids beyond original_max_position_embeddings while seq_length_with_past and self.max_seq_length remain within that boundary, this requests the short-factor cache using rope_len. That cache contains only the original pretrained window, so an offset such as position 40000 can index past it instead of using the already-materialized long cache, producing invalid rotary embeddings or out-of-bounds kernel behavior. Use the effective explicit position extent to select the LongRoPE branch while retaining the short branch for positions wholly inside the pretrained window.

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.

Valid, fixed in 0e23844. transformers decides this the same way (longrope_frequency_update uses torch.max(position_ids) + 1 and pays that sync every forward), so only for LongRoPE with explicit position_ids inside the original window the forward now uses max(position_ids) + 1 to pick the branch; every other model keeps the sync free path, and under compile it takes the long cache instead of reading back. Test compares offset positions 40000 against Phi3RotaryEmbedding.

With explicit position_ids past original_max_position_embeddings while the
batch length stays inside it, LongRoPE read its short cache, which has no
rows there. transformers' longrope_frequency_update picks the factors from
torch.max(position_ids) + 1 and syncs on that comparison. The model
forward now does the same, only for LongRoPE with position_ids and a
batch length inside the original window. Every other model, and LongRoPE
without position_ids, stays sync-free. While tracing it takes the long
cache instead of calling .item().

[skip ci]
@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: 0e2384468f

ℹ️ 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 Outdated
# sync it pays too; other models and LongRoPE without position_ids stay sync-free.
if torch.compiler.is_compiling():
# No graph break: rope_rows spans max_position_embeddings, so never index the short cache.
rope_len = rope_rows

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 Preserve short LongRoPE factors under compilation

When torch.compile traces a LongRoPE model with explicit positions inside original_max_position_embeddings, this assignment replaces the short effective length with rope_rows, which spans the larger configured maximum, so get_cached always selects the long-factor cache. Consequently, compiled short-context training or inference silently uses different rotary embeddings from eager execution and Transformers. Fresh evidence after the earlier short-branch fix is this new is_compiling() path; it should retain runtime short/long selection rather than unconditionally choosing the long cache.

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.

Valid, fixed in ba7beb4: under compile the LongRoPE choice stays a tensor (position_ids.max() + 1 > original, no .item()) and the table rows inside the original window come from torch.where(use_long, long, short), so compiled short-context runs keep the short factors like eager and transformers; the eager path keeps the exact check. Test runs start positions 0 and 40000 under a no-sync guard and matches eager.

Comment thread unsloth/models/llama.py Outdated
Comment on lines +2361 to +2362
if getattr(self, "_rope_cache_version", 0) > 0:
inv_freq = self.inv_freq

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 first expanded cache build on CPU

For any model whose configured maximum exceeds the initial 4 * 8192 cache floor, the first forward calls _grow_rope_cache before any cache has been materialized, incrementing _rope_cache_version to 1. This condition therefore immediately switches that first build back to the accelerator, so the intended first-forward peak-memory reduction is skipped for long-context models; with explicit positions, the temporary frequency and embedding tensors can span the entire configured context and cause an avoidable OOM. Track whether a cache has actually been built rather than treating every positive growth version as a subsequent build.

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.

Valid, fixed in ba7beb4: a dedicated _rope_cache_cpu_version records the size of the first real build, so a first forward that grows past the 32768 row floor before any cache exists is still computed on CPU; later growth computes on inv_freq's device as before. Test: test_first_grown_cache_is_computed_on_cpu.

…n CPU

Under torch.compile, LongRoPE with explicit position_ids took the long
cache even for positions inside the original window. It now picks per
row with torch.where on max(position_ids) + 1 > the original window,
computed as a tensor: rows below the window come from the short or long
cache, rows past it from the long cache, so neither branch reads past the
short cache and nothing calls .item(). Eager keeps the exact check.

A configured max above the 4 * 8192 floor grows the size on the first
forward before any cache exists, which sent the first build to the
accelerator. The cache now records the size version of its first build
and computes every build of that version on CPU; later growth still
computes on inv_freq's device.

[skip ci]
@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: ba7beb4791

ℹ️ 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 Outdated
Comment on lines +1449 to +1453
torch.cat(
(torch.where(use_long, long_cos[:original], short_cos), long_cos[original:])
),
torch.cat(
(torch.where(use_long, long_sin[:original], short_sin), long_sin[original:])

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 rebuilding full LongRoPE tables on every compiled forward

When torch.compile handles a LongRoPE model with explicit positions and a configured context beyond the original window, these torch.cat calls materialize new rope_rows × dim cosine and sine tables on every forward, even though both source tables are cached. Since the resulting tensors are passed to the opaque torch.ops.unsloth.rope_embedding_qk operator, this allocation cannot be fused into the eventual position gather; long-context configurations can therefore add hundreds of MiB of transient accelerator memory and substantial copying per step. Select the short/long factors after gathering position_ids, or teach the RoPE operator to consume both caches without assembling full hybrid tables.

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.

Agreed, the in-graph hybrid tables were not worth their per-forward cost. Fixed in 738758f by removing that branch: under compile the forward now takes the same exact max(position_ids) + 1 check as eager (one graph break, only for LongRoPE with explicit positions inside the original window), and get_cached returns the cached short or long table with no new allocation. Unsloth does not compile this forward, so the graph break is not on any default path; the test checks compiled and eager pick the same factors at start positions 0 and 40000.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@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: 738758fa32

ℹ️ 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 Oct 16, 2026
…13994)

## Summary

`Repo tests (CPU, studio)` fails on PRs based on main since #13979 (for
example #13976):

```
tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe
E   assert not ['test_optimizer_state_offload.py:590: torch.cuda.is_available()']
```

#13979 added a new CUDA case to `tests/test_optimizer_state_offload.py`
with the `torch.cuda.is_available()` guard, the same pattern #13982
replaced in that file. The zoo tests' CUDA spoof patches `is_available`
to True for the whole process, so on a CPU runner that case un-skips and
fails. The guard test caught it first. The product fix in #13979 is
fine; only the new guard is wrong.

## Change

That case now uses `has_real_cuda()` like the other seven in the file.
The file already imports it.

## Testing

- `tests/python/test_accelerator_skip_guards.py` +
`tests/test_optimizer_state_offload.py` on CPU: 41 passed, 17 skipped.
- On main without this change, the guard test fails on line 590 as
above.
@danielhanchen
danielhanchen merged commit 815829f into main Oct 16, 2026
@danielhanchen
danielhanchen deleted the dh/rope-cache-bounds branch October 16, 2026 11:47
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 19, 2026
…othai#14206)

## Summary

unslothai#13976 made the RoPE cache lazy and built the first cache on CPU, even
when the first forward had already grown it past 4 * 8192 rows. That
happens on every model with more than 32K positions
(`max_position_embeddings`), e.g. any 128K-context model. Two effects on
the default path compared with the last release, which built grown
caches on the GPU:

- **cos / sin differ.** The CPU build rounds differently: 188 fp16 and
16 bf16 entries differ from the release, some in rows below 2048.
- **The first forward is slower:** about 0.15 to 0.5 s at 128K positions
and 1.2 to 1.6 s at 1M.

Grown sizes are built on `inv_freq`'s device again, as the eager
`extend_rope_embedding` did; the starting size is still built on CPU, as
the eager `__init__` did. The build now fills the output 32768 rows at a
time, so its fp32 temporaries no longer scale with the cache size. Rows
are bit-identical to the one-shot build.

Measured on one B200 (last release / main / this PR):

| | release | main | this PR |
|---|---|---|---|
| cos / sin rows vs release (fp16, bf16; 32K / 128K / 1M; with and
without `position_ids`) | - | differ in 128K and 1M cells |
bit-identical in all 12 cells |
| peak build memory at 128K | | 128 MiB | 136.5 MiB |
| peak build memory at 1M | 2084 MiB | 1024 MiB | 588 MiB |
| first-forward cache build at 1M | ms | 1.2 to 1.6 s | ms |

The larger cache when `position_ids` are passed (generation prefill,
packing) is the out-of-bounds fix from unslothai#13976 and is kept; its test
still passes. The cache is still built only on the GPU that uses it.

## Tests

`tests/test_rope_cache_current_device.py`: the new
`test_first_grown_cache_is_computed_on_inv_freq_device` fails on main
and passes here; it replaces the test that asserted the CPU build. Six
chunk-equality tests are added and pass on both. 24 passed.

## Not covered here

- No end-to-end long-context generate or training run; the comparison is
at the cache level.
- torch 2.13 only.
oobabooga pushed a commit to oobabooga/unsloth that referenced this pull request Oct 19, 2026
…Cohere, Granite and FalconH1 (unslothai#14199)

## Summary

The RoPE cache is built lazily, with only the rows asked for. unslothai#13976
fixed Llama's decode loop for explicit `position_ids` past the KV length
(for example after left padding or a prefill without `position_ids`).
Gemma2, Cohere, Granite and FalconH1 have their own decode loops and
still read cos / sin at the KV length, so a position past the cached
rows hit a CUDA index-out-of-bounds assert.

Each of the four decode loops now computes the rows one step needs once,
with a new helper `_decode_rotary_seq_len` in `llama.py`: the larger of
the KV length and the highest explicit position + 1. It then passes that
value to every layer. Attention only extends the cache and reads the
larger table when the position is past the KV length; otherwise it makes
exactly the same calls as before.

Cost: one `.item()` host sync per decode step, the same one Llama's loop
already pays. It is skipped entirely (zero syncs) when the cache built
at load already covers `max_position_embeddings`, which holds for any
model with 32768 or fewer positions, such as Gemma2 (8192). Nothing is
computed per layer.

## Tests

`tests/test_decode_offset_rope_model_loops.py` uses tiny models with
`max_position_embeddings = 40960`. It prefills 4 tokens without
`position_ids`, then decodes at position 35000.

| | Gemma2 | Cohere | Granite | FalconH1 | sync helper |
|---|---|---|---|---|---|
| main | index out of bounds | index out of bounds | index out of bounds
| index out of bounds | fails |
| this PR | pass | pass | pass | pass | pass |

For normal decoding, logits are bitwise equal to main:
- Gemma2: checked through `generate` at batch 1 and 2, on both the
one-sync and the zero-sync path.
- Cohere, Granite, FalconH1: checked with a direct decode loop.

`tests/test_rope_cache_current_device.py` needs a one line update for
the new argument; all 23 tests in the two files pass on GPU.

## Not covered here

- In practice the crash reaches users only through Gemma2 configs with
more than 32768 positions. `FastLanguageModel` does not route Cohere,
Granite or FalconH1 to these decode loops, so they are only reached
through their patchers directly.
- No T4, ROCm, 4-bit or torch.compile graph-break run; torch 2.13 /
transformers 5.17 only (FalconH1 also on 4.57.6).
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