Skip to content

Keep a modules_to_save copy on the card it was loaded onto - #10034

Merged
danielhanchen merged 5 commits into
mainfrom
fix/offload-frozen-module-keeps-device
Aug 31, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
fix/offload-frozen-module-keeps-device

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

What breaks

Continued pretraining puts embed_tokens and lm_head in target_modules, so PEFT wraps each one in a ModulesToSaveWrapper. llama.py then calls _offload_frozen_module_for_training to move the trainable copy onto the accelerator and offload the frozen original to CPU, passing DEVICE_TYPE_TORCH:

_offload_frozen_module_for_training(model.get_input_embeddings(),  DEVICE_TYPE_TORCH)
_offload_frozen_module_for_training(model.get_output_embeddings(), DEVICE_TYPE_TORCH)

DEVICE_TYPE_TORCH is the bare string "cuda", and a bare "cuda" carries no index:

>>> torch.device("cuda").index is None
True
>>> torch.zeros(2).to("cuda").device
device(type='cuda', index=0)

The helper then did:

module.modules_to_save.default.to(device = device_type, dtype = new_dtype, non_blocking = True)

So on a model the loader split across cards, a copy sitting on cuda:1 was moved to cuda:0 while the rest of its layer stayed on cuda:1, and the forward then mixed devices. The destination was decided by the current CUDA device rather than by the placement the loader chose, so it ignored hf_device_map entirely.

Why it was not noticed

Single-GPU runs cannot see it. There cuda:0 is where the copy already is, so the move is a no-op and every existing test passes. It needs a second card and embed_tokens or lm_head in target_modules, which is the continued-pretraining recipe specifically, not the ordinary LoRA one.

The fix

Keep the index the copy already has when it is on the right kind of device. A copy still on cpu or meta has no index to keep and is moved exactly as before, so the single-GPU path is byte for byte unchanged.

Tests

tests/test_offload_frozen_module_device.py, 13 tests.

Twelve drive the real helper with a stub that records the device it is handed rather than allocating. That is deliberate rather than a shortcut: the case under test is a second card, and recording the argument tests the decision on any box, including CI runners with no GPU. The thirteenth allocates for real, is skipped without CUDA, and covers only the no-regression direction, which one card is enough for.

Mutation tested by restoring device = device_type. Three tests fail, including the one that names the regression:

FAILED test_a_copy_on_the_second_card_stays_on_the_second_card
FAILED test_a_copy_on_the_third_card_stays_on_the_third_card
FAILED test_a_copy_on_the_first_card_is_unchanged

Also covered so the fix cannot quietly drop the behaviour around it: float16 is still promoted to float32 for Tesla T4 (#1200), bfloat16 is left alone, only the trainable copy gets requires_grad, the frozen original still goes to CPU, offload_device = None still leaves it in place, and a module with no modules_to_save is still untouched.

Scope

Found while investigating #9995 and deliberately kept out of it, since that PR is about dispatch hooks and this is about a placement decision. The two are independent and neither depends on the other.

I do not have a two-card box to hand, so the multi-card behaviour here is asserted through the recorded device argument and the source, not measured on two GPUs. The single-card no-regression direction is measured.

Continued pretraining puts `embed_tokens` and `lm_head` in `target_modules`,
so PEFT wraps each in a `ModulesToSaveWrapper` and
`_offload_frozen_module_for_training` moves the trainable copy onto the
accelerator. It was passed `DEVICE_TYPE_TORCH`, the bare string "cuda", and a
bare "cuda" carries no index:

    >>> torch.device("cuda").index is None
    True
    >>> torch.zeros(2).to("cuda").device
    device(type='cuda', index=0)

So on a model the loader split across cards, a copy sitting on cuda:1 was
moved to cuda:0 while the rest of its layer stayed behind, and the forward
then mixed devices. Single-GPU runs never saw it, because there cuda:0 is
where the copy already was.

Keep the index the copy already has when it is on the right kind of device.
A copy still on cpu or meta has none to keep and is moved as before, so the
single-GPU path is unchanged.
@danielhanchen
danielhanchen requested a review from Datta0 as a code owner August 31, 2026 01:29

@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: c8ab7b4c7b

ℹ️ 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 +204 to +206
target_device = module.modules_to_save.default.weight.device
if target_device.type != torch.device(device_type).type:
target_device = device_type

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 the device captured before disk offload

With the default use_gradient_checkpointing="unsloth", lines 3631-3643 first replace each trained embedding/head with a CPU module loaded from disk, and PEFT consequently creates modules_to_save.default on CPU. This branch therefore falls back to the same bare "cuda" destination as before, losing the original indexed placement already captured in input_embeddings_device/output_embeddings_device; when (for example) lm_head was mapped to cuda:1, continued pretraining still moves its trainable copy to the current card and can fail with mixed-device tensors. The helper needs the saved pre-offload device (or equivalent device-map placement), and the tests should exercise this default offload path.

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.

Correct, and the fix as it stood did not reach the default path. Confirmed in the source: with use_gradient_checkpointing = "unsloth", offload_input_embeddings / offload_output_embeddings run at lines 3632-3643, before _get_peft_model, so PEFT builds modules_to_save.default on CPU. A CPU copy has no index to preserve, so the helper fell straight back to the bare "cuda" and a head mapped to cuda:1 still had its trainable copy moved to cuda:0.

Fixed in 2ea2523. input_embeddings_device and output_embeddings_device were already captured at lines 3625-3629, immediately above that offload, and then discarded at the call sites; they are now passed through as original_device. The order is copy device, then the recorded device, then the bare type, so a copy that still carries an index keeps it, a model loaded on CPU is still moved onto the accelerator, and the two call sites that have nothing to record are unchanged.

Tests are 20 now. Seven cover this path specifically, including a copy rebuilt on CPU with cuda:1 recorded, a recorded cpu device that must not pin the copy to cpu, and an AST guard that both continued-pretraining call sites actually pass original_device, since a helper that supports it while the callers drop it is exactly the bug you found. Mutation tested both ways: removing original_device from a call site fails the AST guard, and making the helper ignore it fails three placement tests.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Aug 31, 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-08-31T01:59:19.440104Z 14c6f0b 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.

pre-commit-ci Bot and others added 3 commits August 31, 2026 01:34
The previous commit preserved the index the trainable copy already carried,
which is not enough on the DEFAULT path. With
`use_gradient_checkpointing = "unsloth"`, `offload_input_embeddings` and
`offload_output_embeddings` run before `_get_peft_model`, so PEFT builds
`modules_to_save.default` on CPU. A CPU copy has no index to preserve, so the
helper fell back to the bare "cuda" exactly as before and a head mapped to
cuda:1 still had its trainable copy moved to cuda:0.

llama.py already records the real placement in `input_embeddings_device` and
`output_embeddings_device`, captured immediately above that offload, and then
threw it away. Pass it through and use it when the copy itself no longer
carries one.

Order is copy device, then the recorded device, then the bare type, so a copy
that still has an index keeps it, a model loaded on CPU is still moved onto the
accelerator, and the two call sites with nothing to record are unchanged.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 205d2229e1

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

68 comment lines to 38. Drops docstrings that only restated the test name and
condenses the module docstring to the mechanism. Comments only, verified by
comparing the ASTs with docstrings stripped.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 14c6f0b5c6

ℹ️ 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 97c7ef6 into main Aug 31, 2026
41 of 42 checks passed
@danielhanchen
danielhanchen deleted the fix/offload-frozen-module-keeps-device branch August 31, 2026 02:54
danielhanchen added a commit that referenced this pull request Aug 31, 2026
* Name the encoding when the offload test reads llama.py

main is red on Repo tests (CPU):

  FAILED tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding
  offenders: tests/test_offload_frozen_module_device.py:40, :254

#10034 added that file with two bare read_text() calls, and its own CI caught
them. It merged at 02:54:14 on head 14c6f0b; the fix I pushed to that branch
landed a few minutes later and so is not in the squash. Same change, against main.

The gate is right and the reads were wrong. Both read unsloth/models/llama.py, a
checked-in source file, with the platform default encoding, which is cp1252 on
Windows. Latent rather than live: llama.py is 177,788 bytes and currently all
ASCII, so nothing breaks today. Failing at the point the read is added is exactly
what the gate is for -- otherwise this surfaces months from now, on Windows only,
when someone puts a non-ASCII character in llama.py.

test_source_read_encoding and the file's own 20 tests pass: 21 passed.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: danielhanchen <[email protected]>
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