Skip to content

Add opt-in optimizer state CPU offload (UNSLOTH_OFFLOAD_OPTIMIZER_STATE=1) - #13882

Merged
danielhanchen merged 11 commits into
mainfrom
dh/opt-state-offload
Oct 16, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
dh/opt-state-offload

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Full fine-tuning and large-rank LoRA keep the whole optimizer state on the GPU through forward, backward and update. This adds an opt-in mode that keeps the state in pinned host memory between steps and brings it to the GPU only for the update. It does this one chunk at a time, sized by UNSLOTH_OFFLOAD_OPTIMIZER_STATE_CHUNK_MB (default 1024). Weights and gradients stay on the GPU. The design follows prime-rl's state-only offload, with chunked updates added.

It works through torch optimizer step hooks. Torch AdamW (default, foreach, fused) and bitsandbytes 8-bit optimizers therefore work unchanged with accelerate, GradScaler, gradient accumulation, grad clipping and LR schedulers. Checkpoints save the host copies, and a resumed run moves the loaded state back to the host right away. Paged bitsandbytes optimizers and DeepSpeed are left alone. With the variable unset, nothing is imported or wrapped.

On a T4 (fp16), full fine-tuning Qwen2.5-0.5B at batch size 4:

  • Peak allocated memory goes from 9443 to 5347 MiB with adamw_torch, and from 6685 to 4953 MiB with adamw_8bit.
  • Step time rises from about 0.60 s to 1.25 s and from 0.52 s to 0.82 s; that is the cost of the PCIe copies.
  • Losses match the run without offload exactly at every step, including after resuming from a checkpoint.

A new test covers the opt-in wiring on CPU. On GPU it checks exact step and checkpoint parity for four optimizer kinds, and a memory bound for the chunked step.

Not covered: FSDP2 / DDP / multi-GPU, GRPO and DPO end to end (SFT only), transformers 4.57.6 / TRL 0.22.2 / torch 2.6, and the Kaggle T4 run (these numbers are from Colab T4 and L4).

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 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-15T21:01:49.025265Z 7fdd997 Manual request
🔒 Security Review ⚠️ Failed 2026-10-15T16:13:59.256845Z d96d167 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

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 ⚠️ Failed 2026-10-15T16:13:55.517378Z d96d167 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.

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

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

if getattr(trainer, "is_deepspeed_enabled", False):
print("Unsloth: UNSLOTH_OFFLOAD_OPTIMIZER_STATE is ignored under DeepSpeed (use its offload_optimizer).")
return False
create_scheduler = trainer.create_scheduler

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 Handle prebuilt optimizer and scheduler pairs

When a user supplies Trainer(..., optimizers=(optimizer, scheduler)), Transformers bypasses create_scheduler; therefore this wrapper is never entered and no offload hooks are installed, despite the environment variable being enabled. The feature silently leaves all optimizer state on the accelerator and can still OOM in this supported configuration. Install immediately when both objects already exist, or also hook a lifecycle method that always runs after optimizer preparation. Transformers optimizer documentation

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.

Transformers still calls create_scheduler when optimizers=(optimizer, scheduler) is passed. In 5.17, _inner_training_loop calls self.create_scheduler(num_training_steps=max_steps) every time, and the if self.lr_scheduler is None check is inside create_scheduler; in 4.57.6, create_optimizer_and_scheduler runs on both the delayed and non-delayed paths and always calls create_scheduler. The wrapper calls the original create_scheduler first and then offloads trainer.optimizer whether or not a scheduler was built, so a user-supplied pair is offloaded too.

…ad nested state objects and layer-wise optimizers, size amsgrad state

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…entum, restore only active state for one chunk, run step hooks once, offload list state (LBFGS)

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…k, keep loaded state on the host, skip the bitsandbytes first step move to device after a resume

[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: 31ba6fe6b2

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


torch.optim.Optimizer._process_value_according_to_param_policy = staticmethod(_host_policy)
try:
result = load_state_dict(state_dict, *args, **kwargs)

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 Keep bitsandbytes checkpoint state on the host during load

When resuming a non-paged bitsandbytes optimizer through the usual load_state_dict(state) call, this invokes the captured bitsandbytes loader with its default move_to_device=True. That custom loader does not use the patched PyTorch policy; it moves every quantization-state tensor to the parameter device before returning, so the complete state can OOM before offloader.offload() runs. Fresh evidence beyond the addressed PyTorch loader is bitsandbytes' separate load_state_dict, which performs these device transfers itself; pass move_to_device=False for this loader or otherwise transform its input before invoking it.

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.

bitsandbytes' load_state_dict cast() keeps state1 / state2 where they were loaded (it only casts floating tensors to the parameter dtype); move_to_device only applies to non_castable_tensor_keys, the quantization maps and absmax, which are a small fraction of the state (bitsandbytes/optim/optimizer.py). The wrapper then offloads those on the next offload pass, so the full state is never resident on load.

Comment on lines +234 to +238
if chunk and size + nbytes > self.chunk_bytes:
chunks.append(chunk)
chunk, size = [], 0
chunk.append(p)
size += nbytes

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 Enforce the chunk bound for oversized parameters

When one parameter's optimizer state is larger than UNSLOTH_OFFLOAD_OPTIMIZER_STATE_CHUNK_MB, it is still appended as a single chunk. Restoring that chunk therefore materializes the entire oversized state on the accelerator, and if it is the only active parameter the single-chunk path restores it for the outer step as well. Large embedding or output tensors can thus exceed the advertised bound and OOM despite choosing a smaller limit; split such state further or explicitly reject/report a limit below the largest parameter state.

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.

The chunk unit is one parameter: torch and bitsandbytes optimizers step a parameter's whole state at once, so a parameter whose state alone exceeds the limit gets a chunk of its own, which is the smallest the step can use. The limit bounds how many parameters are restored together, as documented.

Comment on lines +312 to +314
self.steps += 1
devices, self.pending = self.pending, set()
self.finish(devices | self.offload())

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 Run state offload after all optimizer post-hooks

When a local post-hook is registered after offload installation, or when any global optimizer post-hook is present, this hook runs first and moves the state to CPU before those hooks execute. A later hook that reads a moment together with CUDA parameters then fails with a device mismatch, while one that replaces a state tensor with a CUDA tensor leaves that tensor resident between steps because no offload pass follows it. Fresh evidence beyond the prior hook-count and pre-hook-order fixes is PyTorch's ordering of local post-hooks followed by global post-hooks; arrange for the offload to occur only after those external hooks have completed.

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.

The Trainer, accelerate and PEFT register no optimizer step post hooks; a user post hook that reads optimizer state on the device is outside what this opt-in supports, and moving the offload after arbitrary later hooks would leave the state resident for any hook that never finishes the step.

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

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

_host_policy
)
try:
result = load_state_dict(state_dict, *args, **kwargs)

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 Keep Q-GaLore projectors on CPU during resume

When resuming a Q-GaLore optimizer, this invokes its custom loader before offloading anything; QGaLoreAdamW8bit.load_state_dict reconstructs every saved projector with device = p.device (unsloth/optimizers/q_galore_adamw.py:138-142), bypassing the patched PyTorch state policy. All projector matrices therefore materialize on the accelerator simultaneously, so a large-rank checkpoint can OOM before the later offloader.offload() call is reached. Fresh evidence beyond the addressed generic PyTorch loader is this custom projector reconstruction path; construct these projectors on the host and record their eventual parameter device for chunked restoration.

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.

Q-GaLore resume is outside what this option targets (torch and bitsandbytes optimizer state). The projectors are low-rank matrices, much smaller than the moments the offload exists for, and they are offloaded on the first offload pass after load.

Comment on lines +257 to +258
moments = 3 if third else 2
nbytes = moments * max(p.element_size(), 4) * p.numel()

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 Skip fictitious chunks for stateless SGD

When this option is used with torch.optim.SGD(momentum=0), the optimizer state remains empty permanently, but every parameter is nevertheless estimated as having two FP32 moments. A sufficiently large model is therefore split into many chunks on every update even though there is no state to transfer, and each chunk invokes the complete SGD step() implementation, repeatedly scanning every parameter group and turning the update into roughly O(number of chunks × number of parameters) CPU work. Detect state-free SGD groups, or otherwise derive the uninitialized estimate from the optimizer configuration rather than always assuming two moments.

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.

State offload with an optimizer that keeps no state has nothing to offload, so there is no reason to enable it there. The extra cost in that misconfiguration is CPU-side loop overhead, not a correctness issue.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 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. Breezy!

Reviewed commit: 7fdd997a2a

ℹ️ 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 e539ad5 into main Oct 16, 2026
@danielhanchen
danielhanchen deleted the dh/opt-state-offload branch October 16, 2026 05:18
danielhanchen added a commit that referenced this pull request Oct 16, 2026
…ice (#13982)

## Summary

`Repo tests (CPU, studio)` fails on every PR based on main since #13882
(for example #13960 and #13962):

```
tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe
E   AssertionError: these skip guards read a probe tests/_zoo_aggressive_cuda_spoof.py patches to True process-wide, ...
E   assert not ['test_optimizer_state_offload.py:139: torch.cuda.is_available()', ...]
```

#13882 added `tests/test_optimizer_state_offload.py` with seven
`@pytest.mark.skipif(not torch.cuda.is_available(), ...)` guards. The
CUDA spoof the zoo tests install patches `torch.cuda.is_available` to
True for the whole process. When this file shares a session with them on
a CPU runner, its CUDA cases un-skip and fail. The repo-wide guard
caught this before it could flake. The product change is fine; the
guards are what is wrong.

## Change

Gate those seven cases on `has_real_cuda()` from
`tests/_shared/real_accelerator.py`, the same probe the other CUDA-only
tests use (#13936, #13937). It checks for a real device rather than the
patchable `is_available`. The CPU cases in the file are unchanged.

## Testing

- `tests/python/test_accelerator_skip_guards.py` +
`tests/test_optimizer_state_offload.py` on CPU: 40 passed, 15 skipped.
- With the original file restored, the guard test fails again (1 failed,
23 passed), naming the same seven lines.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 19, 2026
…resuming (unslothai#14155)

## Summary

With the opt-in `UNSLOTH_OFFLOAD_OPTIMIZER_STATE=1` (unslothai#13882) and sharded
parameters (DTensor, FSDP2), resuming from a checkpoint loses track of
the optimizer state that `load_state_dict` places on the host. The load
policy records the loaded value by `id()` of the DTensor, but
`offload()` looks DTensor state up by its local shard. So the next
`optimizer.step()` never moves that state back and fails with a cuda:0
vs cpu device mismatch.

The load policy now also records the DTensor's local shard. Plain
tensors are unchanged, and with the flag off nothing changes because the
module is only used when the flag is on.

## Tests (GPU)

- New `test_load_state_dict_tracks_dtensor_state_on_host` (DTensor
params on a 2-rank mesh with a fake process group): it runs offload, a
step, a deepcopied checkpoint and a resume into a fresh optimizer. It
then checks that the step after resume is bitwise equal to an optimizer
that never stopped.
- `tests/test_optimizer_state_offload.py`: 1 failed / 36 passed on main,
37 passed here.

Not run here: a real multi-GPU FSDP2 resume through accelerate.
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