Repository navigation
Never train with a KV cache, so padding-free rows keep their document boundaries - #13177
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: Didn't find any major issues. Chef's kiss. 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". |
|
With LoRA, auto padding-free and gradient checkpointing off (in both What changed
Same three documents, one step, real checkpoints through
Padded batches and the gradient-checkpointing-on path give identical loss on base and head. After training, The new tests fail 5 of 11 on base and pass 11 of 11 here. Across the 39 related test files, the failing test IDs are identical on base and head (host-only: no CUDA device, missing optional packages). The one red upstream job, Tested on one Linux B200 host. Vision models were not trained, and the |
|
@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: 082c5be1f1
ℹ️ 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".
| from unsloth_zoo.training_utils import disable_use_cache | ||
| disable_use_cache(model) |
There was a problem hiding this comment.
Restore the cache setting while saving trained models
When gradient checkpointing is off and config.use_cache originally starts as true, this unconditional call now leaves the configuration false throughout training. Trainer checkpoint saves and a direct save_pretrained_merged performed after training but before for_inference therefore serialize use_cache: false; after reload the in-memory restoration record is gone, so the resulting model defaults to cacheless generation. Temporarily restore the recorded value while serializing, or disable the cache for training forwards without persisting the changed configuration.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
A saved use_cache: false does not make the reloaded model generate without a cache: generate reads generation_config.use_cache. Saving a config with use_cache=False, reloading and calling generate gives forward lengths [8, 1, 1, 1, 1] on transformers 4.55.4, 4.57.6, 5.2.0, 5.17.0 and 5.19.0, and the default gradient checkpointing path already saved use_cache: false before this change.
A remote-code forward may name packed_seq_lengths but neither use_cache nor **kwargs; the extra key raised TypeError on the first step. Ask the same signature walk the padding-free gate uses, cached on the model; for_training's config-level disable still covers those models.
|
@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: 2f65d14db5
ℹ️ 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".
| takes = getattr(model, "_unsloth_forward_takes_use_cache", None) | ||
| if takes is None: | ||
| from unsloth.trainer import _forward_accepts_packing_kwargs | ||
| takes = _forward_accepts_packing_kwargs(model, "use_cache") |
There was a problem hiding this comment.
Unwrap DeepSpeed before injecting use_cache
With a DeepSpeed-wrapped remote-code model whose underlying forward accepts packed_seq_lengths but not use_cache, this check inspects DeepSpeedEngine.forward(*args, **kwargs) because DeepSpeed is absent from _DELEGATING_MODULE_WRAPPERS, concludes that use_cache is accepted, and injects a keyword that the engine forwards to the fixed underlying signature, causing the packed train/eval step to raise TypeError. The fresh evidence beyond the earlier fixed comment is the still-unhandled DeepSpeed wrapper path; unwrap DeepSpeedEngine.module before deciding whether to add this argument.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
No checkpoint or in-tree forward names packed_seq_lengths without also taking use_cache or **kwargs; the signature gate only keeps that hypothetical shape from crashing, and DeepSpeed on top of it is not a configuration anyone can hit today.
| from unsloth_zoo.training_utils import disable_use_cache | ||
| disable_use_cache(model) |
There was a problem hiding this comment.
Apply cache toggles to the underlying distributed model
When for_training is called with a distributed wrapper rather than the bare checkpoint, this call does not reliably toggle the configuration that the forward reads: disable_use_cache returns immediately for DataParallel/DDP/FSDP wrappers that expose no outer config, while for a DeepSpeed engine it unwraps to .module and stores _unsloth_use_cache_originals there, but for_inference later calls restore_use_cache on the outer engine and cannot find that record. Consequently custom/standalone packed training paths can still run with a cache under the former wrappers, and a DeepSpeed model remains configured cacheless after switching back to inference; unwrap once and pass the same underlying model to both disable and restore.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
for_training and for_inference are bound to the unwrapped model (functools.partial(FastLlamaModel.for_training, model) / FastBaseModel), and the trainer calls self.model.for_training, never the DDP / FSDP / DeepSpeed wrapper, so disable and restore always see the same model.
| from unsloth.models._utils import _forward_takes_use_cache | ||
| if _forward_takes_use_cache(model): | ||
| inputs = {**inputs, "use_cache": False} |
There was a problem hiding this comment.
Disable the config cache during fixed-signature evaluation
For a supported remote-code model whose forward explicitly accepts packed_seq_lengths but not use_cache, this new condition skips the only evaluation-time cache override. for_inference has already restored config.use_cache=True, so if that fixed-signature forward omits the argument when delegating to its language model, the inner model reads the restored config, creates a cache, and drops the packed-sequence mask; packed evaluation loss then silently crosses document boundaries. Avoiding the unsupported keyword is necessary, but this branch must instead temporarily disable the underlying config for the prediction call and restore it afterward.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Same hypothetical shape: no forward names packed_seq_lengths explicitly while omitting use_cache and **kwargs, and on main this exact case raised TypeError in evaluation; every real forward still gets use_cache=False here.
With Unsloth's auto padding-free and gradient checkpointing off, packed documents attend to each other during training on the transformers modeling path (
FastModel/FastBaseModel). The loss and the update are both wrong, silently.Who is affected
FastModel, andFastBaseModelfor vision / omni models).FastLanguageModel's own forward already forcesuse_cache = Falsein training, so it is not affected.Trainer.__init__setsconfig.use_cache = args.use_cache(False), so a model that was never prepared with gradient checkpointing stays correct. A model loaded with it on and trained with it off is affected:from_pretraineddefaults touse_gradient_checkpointing = "unsloth", soget_peft_model(..., use_gradient_checkpointing = False)plusgradient_checkpointing = Falsein the trainer args is enough. The recordeduse_cache = Truecomes back throughfor_inference, and the old re-disable skipped it because checkpointing was off.TRL's
SFTConfigdefaults togradient_checkpointing = True, which hides the bug; a plainTrainingArguments, orgradient_checkpointing = Falseon the config, exposes it.Cause
prepare_model_for_trainingsetsuse_cache = Falseand records the original (unsloth-zoo#715, Restore config use_cache in for_inference after gradient checkpointing prep #6137).__init__ends inmodel.for_inference(), which restoresuse_cache = True.train()callsfor_training(use_gradient_checkpointing = ...), but the re-disable only ran when gradient checkpointing was on. With it off, training runs withuse_cache = True.use_cache = Truebuilds aDynamicCache, and transformers only detects packed sequences fromposition_idswhilepast_key_values is None(masking_utils._preprocess_mask_arguments). So a padding-free row gets one causal mask across all of its documents.The evaluation side already guards this (#3470:
prediction_steppassesuse_cache = Falsefor packed batches). Training had no equivalent.Change
FastLlamaModel.for_trainingandFastBaseModel.for_trainingalways calldisable_use_cache, with or without gradient checkpointing. Training never reads the KV cache, anddisable_use_cacherecords the value it replaces, sofor_inferencestill restores it forgenerate. A model that was never prepared is now recorded on the way in too._unsloth_pre_compute_losspassesuse_cache = Falsefor a batch carryingpacked_seq_lengths, the training twin of the [Feature] Compute WER/CER metrics with Gemma3 #3470 guard, so the mask holds even if something re-enablesconfig.use_cachemid-run. An explicituse_cachein the batch still wins, and the collated batch is not mutated.ImportErroris ignored as before).Verification
Packed vs per-document loss on the same three documents, real checkpoints through
FastModel, LoRA, gradient checkpointing off, after building anSFTTrainer:for_inferencestill restoresuse_cache = True, andgenerateafter training still uses the cache.Full SFT runs (FastModel, LoRA, auto padding-free, gradient checkpointing off in both places): on main the first-step loss is the leaked one (Llama-3.2-1B 4.170, Qwen3-0.6B 6.125), with this PR it is the per-document one (4.677, 5.142), and
config.use_cacheduring training is False instead of True.Tiny-model TRL SFT runs, LoRA r=8, fp32 weights, SGD, uneven lengths, 4 steps. Max |loss diff| / relative difference of the LoRA update against plain TRL + PEFT at the same bs=4:
The remaining difference is Unsloth's default bf16 autocast over fp32 master weights.
Transformers versions
Qwen3-0.6B,
FastModel, LoRA, auto padding-free, 12 steps, main and this PR on the same Colab GPU per version. First-step loss, with the padded (unpacked) run as the reference:With this PR, the loss with checkpointing off matches the loss with it on to the printed digits on every version, and checkpointing-on runs match main within bf16 noise. Step time with checkpointing off is the same or lower (A100: 259 to 272 ms against 273 to 278 ms on main) and peak memory drops from 4.88 to 4.70 GB, since no KV cache is allocated. The 4.55.4 packed loss sits above the padded one on main and on this PR alike: TRL 0.22 does not mask the label at each packed document boundary (TRL 0.23 added
labels[position_ids == 0] = -100), which is separate from this change and fixed in #13324.Speed and memory
Interleaved base / head runs on one exclusive GPU, step time = median after 5 warmup steps:
Peak memory is the same or lower (GC off no longer allocates a KV cache: Llama-3.2-1B 6.29 to 6.22 GB, Qwen3-0.6B 4.94 to 4.74 GB). The extra check in
compute_losscosts about 0.2 us per step.Other training paths are unchanged: base vs head GRPO, DPO, vision SFT, inference smoke and SFT jobs all came back SAME, and the tiny-model regression suite (103 cases on a rented GPU) shows 0 regressions, 0 metric moves.
Tests
tests/test_padding_free_train_use_cache.py(11 cases). The gradient-checkpointing-off, never-prepared andcompute_losscases fail onmain(5 failures) and pass here. Every test file touchingfor_training,for_inference,use_cacheorcompute_lossgives identical failing test IDs onmainand this branch (all host-environment: no CUDA device, nosentence_transformers).