Repository navigation
Add opt-in optimizer state CPU offload (UNSLOTH_OFFLOAD_OPTIMIZER_STATE=1) - #13882
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
There was a problem hiding this comment.
💡 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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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]
…entum, restore only active state for one chunk, run step hooks once, offload list state (LBFGS) [skip ci]
…k, keep loaded state on the host, skip the bitsandbytes first step move to device after a resume [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| if chunk and size + nbytes > self.chunk_bytes: | ||
| chunks.append(chunk) | ||
| chunk, size = [], 0 | ||
| chunk.append(p) | ||
| size += nbytes |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| self.steps += 1 | ||
| devices, self.pending = self.pending, set() | ||
| self.finish(devices | self.offload()) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…ize the AdEMAMix double moment before the first step
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| moments = 3 if third else 2 | ||
| nbytes = moments * max(p.element_size(), 4) * p.numel() |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…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.
…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.
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:
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).