Skip to content

RoPE cache: a cold build inside a compiled block traces again (no is_inference_mode_enabled under compile) - #14728

Merged
danielhanchen merged 8 commits into
mainfrom
rope-cache-fullgraph
Oct 25, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
rope-cache-fullgraph

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

#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 #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 (#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.

…mode query so it traces without graph breaks
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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-25T09:34:24.432986Z 735c6db 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 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: 1fcba4d510

ℹ️ 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 +2328 to 2329
if torch.compiler.is_compiling() or not torch.is_inference_mode_enabled():
return contextlib.nullcontext()

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 Avoid caching inference tensors during compiled generation

When a cold cache is first built by a torch.compile-wrapped forward running under torch.inference_mode()—for example, compiled generation before GRPO training—this short-circuit returns nullcontext, so _set_cos_sin_cache stores inference tensors. Those tensors persist into the next grad-enabled forward, where autograd/AOTAutograd cannot save the RoPE values for backward, recreating the training failure or compiled-layer fallback that _rope_build_mode was introduced to prevent. The new tests only exercise compilation outside inference mode and therefore miss this combination.

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.

Good catch, this is real. A cold cache built by a compiled forward under torch.inference_mode() stored inference tensors on this branch, and the next grad-enabled forward failed with "Inference tensors cannot be saved for backward" (reproduced with aot_eager on CPU and inductor on GPU, both compiled and eager backward). Wrapping the build in torch.inference_mode(False) while compiling does not help: Dynamo records it, but AOTAutograd drops it, so only the eager backend honored it. Fixed in 2e6c2f7e03 instead: a build done while compiling with grad off flags its device, which stays off the rows-ready fast path and rebuilds on the next grad-enabled read, compiled or eager. Inference reads keep the cache, the steady-state fast path is unchanged, and cold builds inside compiled training blocks still trace with 0 graph breaks under fullgraph. Added tests for llama, gemma and longrope, simulated and under Dynamo; they fail on the previous head and pass now.

… next grad-enabled read

A compiled graph cannot leave inference_mode, so a cold build by compiled generation held
inference tensors that the next training forward could not save for backward. Such a device
is flagged, stays off the rows-ready fast path, and rebuilds once grad is enabled.

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

ℹ️ 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 2766 to 2770
if self._rope_cache_version > 0 and (
rebuild_for_grad
or self._rope_cache_stale(self.multi_gpu_long_cos_cached[device_index], device_index)
):
self._build_rope_cache(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.

P2 Badge Track LongRoPE short and long rebuild states separately

When compiled inference first builds only the short LongRoPE cache, _rope_rebuild_for_grad[device_index] is true because that cache contains inference tensors. If a later eager inference request grows the long cache, this call builds an ordinary long cache and _build_rope_cache clears the same shared flag, while the short cache remains an inference tensor. A subsequent grad-enabled short-sequence forward therefore skips rebuilding the short cache and fails when autograd tries to save its RoPE values. Keep separate short/long dirty flags, or avoid clearing the short-cache state when only the long cache is rebuilt.

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.

Good catch, this was real. The short and long LongRoPE caches shared one per-device rebuild marker, so a compiled inference pass that built only the short cache (inference tensors) followed by an eager long-cache rebuild cleared the marker, and the next grad-enabled short forward served the inference tensors.

Fixed in e3b10b7a: the short cache now has its own _short_rope_rebuild_for_grad marker, and _rope_rebuild_for_grad only tracks the long cache (still checked through _rope_cache_stale). Added test_longrope_long_rebuild_keeps_short_marked_for_training in tests/test_rope_cache_current_device.py, which reproduces that exact sequence; it fails before the change and passes after, and the rest of the file still passes (39 tests).

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: e3b10b7b10

ℹ️ 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 self-assigned this Oct 25, 2026
@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: f815faa1b6

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

# Conflicts:
#	tests/test_rms_rope_compile.py
@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. Nice work!

Reviewed commit: 735c6dbab2

ℹ️ 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 1fe53a8 into main Oct 25, 2026
3 of 30 checks passed
@danielhanchen
danielhanchen deleted the rope-cache-fullgraph branch October 25, 2026 09:38
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