Skip to content

Packed metadata: keep the tensor path under torch.compile, fall back to pageable copies - #15199

Merged
danielhanchen merged 2 commits into
mainfrom
dh/s6-fix-packing-compile
Oct 25, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
dh/s6-fix-packing-compile

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

#15133 removed a host sync from get_packed_info_from_kwargs by reading the packed lengths back once as a host tuple (tuple(lengths.tolist())) and staging host lengths through one pinned non_blocking copy. Two side effects:

  1. Under a user torch.compile(..., dynamic = True) the host tuple specializes the graph on the number of segments, so every new segment count is a recompile. CPU repro over 12 segment counts (3 to 14): 4 graphs before Remove hidden host-device syncs from per-step training paths #15133, 12 after, and the recompile limit is hit.
  2. staged.pin_memory() runs inside the traced region on a cold compile and cannot be traced (aten._pin_memory is not implemented for the tracing tensors). Pinning also had no fallback when host memory cannot be pinned (pinned memory limit, WSL), here and in the DDP present mask in rl.py.

Change

  • unsloth/utils/packing.py: when torch.compiler.is_compiling(), get_packed_info_from_kwargs takes the pre-Remove hidden host-device syncs from per-step training paths #15133 tensor path (device lengths, device cumsum, lengths.max().item()), with no pin_memory and no host tuple. The downstream mask helpers then find no cached host lengths and take their existing route. The eager path is unchanged, so the sync removal from Remove hidden host-device syncs from per-step training paths #15133 stays.
  • _pinned_to_device: pinned non_blocking copy, or a plain pageable copy when pin_memory() raises.
  • unsloth/models/rl.py _unsloth_average_gradients: the same fallback for the DDP present mask.

Tests

tests/utils/test_packing_host_sync.py (CPU):

  • compile with dynamic = True over 12 segment counts traces at most 4 graphs and returns the right values;
  • while compiling, the returned lengths / cu_seqlens / max equal the old device-derived values and no host tuple is cached;
  • _pinned_to_device returns the same tensor when pin_memory raises.
before (main) after
test_packing_host_sync.py 3 failed, 8 passed, 2 skipped (CUDA only) 11 passed, 2 skipped
packing, attention mask, hybrid packing, GRPO DDP average suites 195 passed, 7 skipped

GPU (Colab T4, torch 2.11.0+cu130). Each case ran in a fresh process so the compile cache starts cold, with the same probe on the packing.py from main and from this branch:

case main this branch
cold torch.compile (default), 12 segment counts, fwd + bwd fails: NYI: aten._pin_memory.default passes, 4 graphs
cold torch.compile(dynamic = True), same fails: NYI: aten._pin_memory.default passes, 3 graphs
eager, pin_memory raising RuntimeError passes, same cu_seqlens / max
eager, host lengths, syncs under set_sync_debug_mode("warn") 0 0

The last row shows the eager path from #15133 still makes no sync.

Not covered

  • The rl.py DDP fallback has no test of its own (it needs CUDA params plus a process group). It is the same three-line try / except as _pinned_to_device.
  • A real pinned memory limit (as opposed to a pin_memory that raises) was not reproduced.

…to pageable copies

Under a user torch.compile(dynamic=True) the host tuple of packed lengths
specialized the graph on the segment count, and pin_memory cannot be
traced. While compiling, use the device tensor path again. When pinning
host memory fails, copy from pageable memory instead of raising.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 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-25T04:26:50.822064Z 8e5761b 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. 🚀

Reviewed commit: 8e5761bf6f

ℹ️ 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 25, 2026
…wrap test _decode_graphs (#15209)

## Summary

Two merges left `Repo tests (CPU, rest)` red on main (for example on
#15199, base `0705fa58`):

1. **#15174 (tensor parallelism v2)** reads
`model.safetensors.index.json` with a bare `open()` at
`unsloth/models/tp_native.py:1636` and `:1660`, and its new test does
the same at `tests/test_tp_native_oracle.py:697`. #15185 (padded batches
vs padding-free) added `tests/test_padding_choice.py:267` with a bare
`read_text()`. The two encoding guards flag all four:

```
tests/test_runtime_text_encoding.py::test_shipping_code_names_an_encoding
  ['unsloth/models/tp_native.py:1660: open()', 'unsloth/models/tp_native.py:1636: open()']
tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding
  ['tests/test_padding_choice.py:267: read_text()', 'tests/test_tp_native_oracle.py:697: open()']
```

The two `tp_native.py` sites are product code, and the guard is right
about them: a checkpoint index read under a non-UTF-8 Windows locale can
fail or mis-decode.

2. **#15188 (decode graphs on by default for RL)** wrapped
`unsloth_unwrap_model_for_generation`'s generate in
`_decode_graphs.rl_generation()` and calls
`_decode_graphs.release_for_training(model)` on the way back to
training. `tests/test_ppo_trainer_patches.py` lifts that function out of
`rl.py` with `ast` and never gave it `_decode_graphs`, so both unwrap
tests stop with `NameError: name '_decode_graphs' is not defined`.

## Change

- `tp_native.py`, `test_tp_native_oracle.py`, `test_padding_choice.py`:
`encoding = "utf-8"` on the four reads.
- `test_ppo_trainer_patches.py`: the lifted function gets a
`_decode_graphs` whose `rl_generation` is the real scope from
`unsloth/models/_decode_graphs.py` (loaded by file path), with entering
it and `release_for_training` recorded in the existing `calls` list. The
PPO-policy test now asserts the full order: `for_inference`,
`rl_generation`, `release_for_training`, `for_training`. The plain-model
test asserts generation happens inside the scope before the release.

## Verification

- On main: the two encoding guards fail and both unwrap tests raise
`NameError`. With this change the encoding guards give `25 passed`, and
`test_ppo_trainer_patches.py`, `test_padding_choice.py` and
`test_tp_native_oracle.py` give `114 passed, 4 skipped`.
- Sabotage, each against `rl.py`:
1. generate outside `_decode_graphs.rl_generation()`: both unwrap tests
fail
  2. no `release_for_training` before training: both unwrap tests fail
-
`tests/test_tp_native_gloo.py::test_tp2_x_fsdp2_dp2_matches_one_process`
(5 cases) passes on main locally.
@danielhanchen
danielhanchen merged commit 18380d9 into main Oct 25, 2026
35 of 37 checks passed
@danielhanchen
danielhanchen deleted the dh/s6-fix-packing-compile branch October 25, 2026 06:01
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