Skip to content

RoPE: compile stock positions without full-context caches - #16182

Merged
danielhanchen merged 12 commits into
mainfrom
dh/fix-stock-rope-compile
Nov 11, 2026
Merged

danielhanchen merged 12 commits into
mainfrom
dh/fix-stock-rope-compile

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Problem and change

After Unsloth patches the rotary classes, a stock Transformers model created in the same process calls rotary_emb(x, position_ids). Reading int(position_ids.max()) to size its cache breaks compilation and fails with fullgraph=True.

Compiled stock calls now calculate cosine and sine for the requested positions directly. This removes the scalar host read, avoids full-context cache allocation, and handles positions beyond the configured cache extent.

Llama keeps a pristine CPU frequency snapshot outside registered buffers, so compilation does not enter Transformers' configuration initialization or consume a frequency buffer replaced during loading. Gemma snapshots its CPU FP32 timescales and scaling factor before widening the arithmetic. A precomputed FP64 reciprocal avoids slow runtime division on CPU and CUDA/ROCm; other accelerator backends retain FP32. Non-power-of-two scaling factors keep eager rounding. The fast seq_len/get_cached routes and LongRoPE's length-dependent factor selection retain their existing behavior.

Validation

  • The focused CPU suite passes with Transformers 4.57.6 and 5.22.1 (57 passed, four GPU-only skips), and the accelerator-guard corpus brings the local total to 81 passing tests. Tests cover dynamic full-graph capture, backward gradients, cache-boundary positions, scaled configurations, and corrupted registered buffers.
  • The original compiler tests fail on the merge base. Fourteen additional cases fail on the submitted implementation and pass with the fixes.
  • CUDA Inductor checks pass in FP32 and FP16 on T4/L4 hardware, including head dimension 128, positions through 131071, and scaling factor 1.3. The committed GPU cases also pass on PyTorch 2.6/CUDA 12.4/Triton 3.2 and PyTorch 2.15/CUDA 13.2/Triton 3.9. A tiny randomly initialized Llama passes full-graph forward/backward with maximum parameter-gradient difference 8.94e-08 against eager execution.
  • The current-head switchboard reports NO_REGRESSION for standard SFT, inference, and regression smoke. The scoped Linux, macOS, and Windows staging jobs are green.
  • Matched tiny-model inference measurements use one exclusive T4, fresh processes and compile caches, three baseline controls, and three ABBA rounds. These measurements apply to the tiny stock-model test, not production-sized model speedups.

Targeted reproductions use random tiny model weights. LongRoPE's stock-call scalar read remains outside this change because its factor selection depends on the requested length.

The 128K Gemma rotary call remains about 15% slower than its paired baseline on T4. Two independent tiny-model prefill comparisons, with three and six ABBA rounds, find no model-throughput regression beyond baseline variation; all recorded greedy outputs match, and peak allocated memory consistently falls from 522.46 to 394.46 MiB. These results are specific to the tested random one-layer Gemma and do not establish production-sized performance. Final AMD validation on Radeon 8060S is CONFIRMED on the exact final head: all six merge-base cases fail compilation, while all six head and integration cases pass, with maximum FP32 error 5.96e-08, exact FP16 outputs, and matching input gradients. The final two-T4 placement check passes all 12 cases, including inputs on GPU1 while GPU0 is current. Broad integration CI has unrelated baseline failures reproduced on upstream main without this PR.

…ost read

A plain transformers model built after Unsloth patched the rotary classes calls rotary_emb(x, position_ids). That call read int(position_ids.max()) to size the lazy cache, which is a graph break under torch.compile and a data-dependent guard error under fullgraph=True. While tracing, the call now indexes the whole current cache instead: rows depend only on their position, so the values are unchanged. LongRoPE still reads the length, since it picks its factors from it.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 30, 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-11T10:17:15.406920Z ebf7268 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[bot]

This comment was marked as resolved.

…dings

The traced stock call indexed only the current cache, which starts at 32768 rows, so on a model with a larger max_position_embeddings a compiled call at position 32768 or later (a long prompt, or decode crossing the boundary) indexed past it. A traced call now sizes the cache to max_position_embeddings before indexing, as the fast model forward already does for explicit positions, still without a host read.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 30, 2026
@danielhanchen danielhanchen self-assigned this Nov 2, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: f7f60d6678

ℹ️ 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 to Etherll/unsloth that referenced this pull request Nov 3, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 3939b51b7d

ℹ️ 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 Nov 3, 2026
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Nov 3, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 8f2f13f397

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

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 9d36e2cfda

ℹ️ 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 to Etherll/unsloth that referenced this pull request Nov 3, 2026
@unslothai unslothai deleted a comment from danielhanchen Nov 3, 2026
@unslothai unslothai deleted a comment from danielhanchen Nov 3, 2026
@unslothai unslothai deleted a comment from danielhanchen Nov 3, 2026
@unslothai unslothai deleted a comment from danielhanchen Nov 3, 2026
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Nov 3, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 9728ba7786

ℹ️ 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 danielhanchen Nov 3, 2026
@unslothai unslothai deleted a comment from danielhanchen Nov 3, 2026
@danielhanchen danielhanchen changed the title RoPE: compiled stock-model calls index the cache without a host read RoPE: compile stock positions without full-context caches Nov 3, 2026
danielhanchen added a commit that referenced this pull request Nov 3, 2026
…as benign timing (#16526)

## Summary

`workflow-trigger lint` is red on main since #16422 (`1a951a93d6`). Its
"Workflow guard suites" step fails on unrelated PRs. In the last hour
that was the staging runs for #16423, #16182 and #16523:

```
tests/studio/test_backend_ci_parallel_isolation.py::test_every_tight_elapsed_bound_is_isolated
AssertionError: these backend tests compare clock-derived values and still run under -n 4 ...:
{'test_hf_download_fallback_and_kill.py': ['...:32 one duration against another'],
 'test_hf_download_reclaim_race.py': ['...:113 one duration against another'],
 'test_hf_download_ref_concurrency.py': ['...:72 one duration against another']}
```

All three sites are the same poll loop, which waits for a child process
to touch a `ready` file:

```python
deadline = time.monotonic() + 20   # 10 in test_hf_download_ref_concurrency.py
while not (tmp_path / "ready").exists():
    assert child.poll() is None, child.communicate()
    assert time.monotonic() < deadline, "worker did not reach the transfer barrier"
    time.sleep(0.01)
```

Being descheduled under `-n 4` only delays a poll; it cannot make the
condition false. The guard casts a deliberately wide net, and its
message names this exact case: a poll deadline goes in `BENIGN_TIMING`
as `(file, enclosing function)` with a reason. The tests and #16422's
download logic are fine; those entries were just never added.

## Change

`tests/studio/test_backend_ci_parallel_isolation.py`: three
`BENIGN_TIMING` entries under one reason comment. Each names the
function that holds the loop:
- `_wait_for_transfer`
- `test_gguf_reclaim_preserves_publication_and_active_peer`
- `test_peer_completion_survives_an_older_process`

I checked each of those functions: its only uses of `time.` are this
deadline, the comparison and the `sleep`, so the entries hide no other
timing check.

## Testing

- `tests/studio/test_backend_ci_parallel_isolation.py`:
- main: `test_every_tight_elapsed_bound_is_isolated` fails with the
error above;
  - this branch: 43 passed.
- No product or workflow file changes.
danielhanchen added a commit that referenced this pull request Nov 3, 2026
…16530)

## Summary

Since #16422 (`1a951a93d6`), `(Python 3.13, rest)` fails on unrelated
PRs. On staging CI it hit #16423, #16182 and #16523 in the last hour,
and it reproduces on current main:

```
studio/backend/tests/test_scoped_download_worker.py::test_offline_scoped_download_fails_when_the_files_are_not_on_disk
studio/backend/tests/test_scoped_download_worker.py::test_offline_scoped_download_passes_when_every_file_is_present
studio/backend/tests/test_scoped_download_worker.py::test_a_dangling_symlink_does_not_count_as_present
hub/workers/hf_download.py:476: in _pinned_snapshot_download
E   OSError: Cannot resolve an immutable revision for black-forest-labs/FLUX.1-dev; retry when metadata is available
```

#16422 made every download pin an immutable commit. When metadata is
unreachable, `_pinned_snapshot_download` takes the commit from the Hub
cache's `refs/main` and refuses when there is none, rather than letting
`snapshot_download` hand back whatever folder is there. That is the
point of #16422, and I left it alone.

These tests' `offline` fixture predates it. It returns a bare tmp
`snapshot` dir and never puts a `refs/main` in the Hub cache, so every
case now stops at "no revision to pin" before reaching what it checks:
an incomplete copy, a complete copy, a dangling blob symlink. A real
offline user with a previously downloaded model has `refs/main` and its
`snapshots/<commit>`, so nothing changes for them.

## Change

`studio/backend/tests/test_scoped_download_worker.py` only:
- The fixture points `huggingface_hub.constants.HF_HUB_CACHE` at a tmp
dir. It writes `refs/main` and returns `snapshots/<commit>` there, the
layout an earlier download leaves behind.
- The three existing tests and their assertions are unchanged.
- New `test_offline_with_no_cached_revision_refuses_before_downloading`:
with no metadata and no `refs/main`, the worker raises the "immutable
revision" `OSError` and never calls `snapshot_download`. This pins
#16422's refusal, so the fixture change cannot hide a regression there.

## Testing

- `tests/test_scoped_download_worker.py`:
  - main: 3 failed, 1 passed (the error above);
  - this branch: 5 passed.
- Sabotage: with the offline missing-file refusal in
`_download_scoped_snapshot` disabled, the incomplete-copy and
dangling-symlink tests fail, so they still guard what they were written
for.
- `tests/test_hf_download*.py` plus this file: 102 passed.
danielhanchen added a commit that referenced this pull request Nov 3, 2026
## Summary

`Repo tests (CPU, rest-2)` is red on main since #16415 (`bf38ae0ac6`).
On staging CI it hit #16423, #16182 and #16523 in the last hour:

```
tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding
AssertionError: 1 file reads in the test trees touch a checked-in file with the platform default encoding,
so they break on Windows as soon as that file gains a non-ASCII byte. Pass encoding = "utf-8":
['tests/test_multi_lora_cold_compile_cpu.py:33: read_text()']
```

#16415's new test parses a checked-in source file with
`path.read_text()`. On Windows that decodes with the ANSI codepage, so
it breaks as soon as the source file gains a non-ASCII byte. The guard
is right.

## Change

`tests/test_multi_lora_cold_compile_cpu.py`: `read_text()` becomes
`read_text(encoding = "utf-8")`. Nothing else changes.

## Testing

- `tests/test_source_read_encoding.py` and
`tests/test_multi_lora_cold_compile_cpu.py`:
  - main: the encoding guard fails as above;
  - this branch: 20 passed.
danielhanchen added a commit that referenced this pull request Nov 3, 2026
…o pair (#16532)

## Summary

Since #16157 (`95aae40bb4`), three installer tests fail on main. On
staging CI, `Repo tests (CPU, studio-install)` failed on #16423, #16182
and #16523 in the last hour:

```
tests/studio/install/test_ca_trust_floor.py::test_the_full_pass_raises_the_floor_in_both_modes[no-torch-update]
tests/python/test_no_torch_filtering.py::TestInstallPythonStackSubprocessMock::test_update_path_intel_macos_still_skips_overrides
tests/python/test_no_torch_filtering.py::TestInstallPythonStackSubprocessMock::test_update_path_intel_macos_still_skips_triton
studio/install_python_stack.py:10044: in _desktop_unsloth_spec
E   RuntimeError: Could not resolve a compatible unsloth / unsloth-zoo pair for no-torch mode
```

#16157 makes every no-torch install pin a compatible Unsloth / Zoo pair,
read from wheel metadata by `_no_torch_pair`, and refuse when none
resolves. That is deliberate, and its own tests cover it with real
offline wheels. The refusal can only trigger when the feed cannot serve
Unsloth's metadata, and then the no-deps install would fail anyway, so I
left the product as it is.

All three failing tests run `install_python_stack()` through
`TestInstallPythonStackSubprocessMock._capture_install`, which mocks
every `subprocess.run` to return 0 and write nothing. The pair probe
then finds no installed metadata and returns `None`, so every no-torch
update path through this harness now stops before reaching what the test
checks: the CA trust floor, and the Intel macOS override and triton
skips.

## Change

`tests/python/test_no_torch_filtering.py`: `_capture_install` also
patches `ips._no_torch_pair` to return a resolved pair, modelling a feed
that serves one, as a real index does. No assertion changes. The pair
logic itself stays covered by
`tests/python/test_desktop_unsloth_spec_no_deps_pair.py`, which runs the
real probe against real wheels.

## Testing

- `tests/python/test_no_torch_filtering.py`,
`tests/studio/install/test_ca_trust_floor.py`,
`tests/python/test_install_python_stack.py` and
`tests/python/test_desktop_unsloth_spec_no_deps_pair.py`:
  - main: 3 failed, with the error above;
  - this branch: 423 passed, 3 skipped.
@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: ebf7268989

ℹ️ 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 6b01508 into main Nov 11, 2026
@danielhanchen
danielhanchen deleted the dh/fix-stock-rope-compile branch November 11, 2026 11:29
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