Skip to content

Never train with a KV cache, so padding-free rows keep their document boundaries - #13177

Merged
danielhanchen merged 7 commits into
mainfrom
fix-lora-padding-free-use-cache
Oct 12, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
fix-lora-padding-free-use-cache

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 10, 2026 •

Copy link
Copy Markdown
Member

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

  • Models trained through the transformers modeling forward (FastModel, and FastBaseModel for vision / omni models). FastLanguageModel's own forward already forces use_cache = False in training, so it is not affected.
  • Padding-free or packed batches (auto padding-free is on by default for SFT).
  • Training with gradient checkpointing off:
    • transformers 4.x: any run with gradient checkpointing off.
    • transformers 5.x: Trainer.__init__ sets config.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_pretrained defaults to use_gradient_checkpointing = "unsloth", so get_peft_model(..., use_gradient_checkpointing = False) plus gradient_checkpointing = False in the trainer args is enough. The recorded use_cache = True comes back through for_inference, and the old re-disable skipped it because checkpointing was off.

TRL's SFTConfig defaults to gradient_checkpointing = True, which hides the bug; a plain TrainingArguments, or gradient_checkpointing = False on the config, exposes it.

Cause

  1. prepare_model_for_training sets use_cache = False and records the original (unsloth-zoo#715, Restore config use_cache in for_inference after gradient checkpointing prep #6137).
  2. Every Unsloth trainer __init__ ends in model.for_inference(), which restores use_cache = True.
  3. train() calls for_training(use_gradient_checkpointing = ...), but the re-disable only ran when gradient checkpointing was on. With it off, training runs with use_cache = True.
  4. A training forward with use_cache = True builds a DynamicCache, and transformers only detects packed sequences from position_ids while past_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_step passes use_cache = False for packed batches). Training had no equivalent.

Change

  • FastLlamaModel.for_training and FastBaseModel.for_training always call disable_use_cache, with or without gradient checkpointing. Training never reads the KV cache, and disable_use_cache records the value it replaces, so for_inference still restores it for generate. A model that was never prepared is now recorded on the way in too.
  • _unsloth_pre_compute_loss passes use_cache = False for a batch carrying packed_seq_lengths, the training twin of the [Feature] Compute WER/CER metrics with Gemma3 #3470 guard, so the mask holds even if something re-enables config.use_cache mid-run. An explicit use_cache in the batch still wins, and the collated batch is not mutated.
  • An older unsloth-zoo without the helper keeps today's behaviour (ImportError is ignored as before).

Verification

Packed vs per-document loss on the same three documents, real checkpoints through FastModel, LoRA, gradient checkpointing off, after building an SFTTrainer:

model per-document packed, main packed, this PR
Llama-3.2-1B-Instruct 11.013392 10.560 11.013391
Qwen3-0.6B 12.017673 11.383 12.017674

for_inference still restores use_cache = True, and generate after 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_cache during 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:

model main this PR this PR, 2x2 and 1x4 vs 4x1 (update)
Llama 9.7e-4 / 0.92 2.8e-5 / 5.9e-3 2.5e-3, 3.8e-3
Qwen3 1.7e-3 / 1.2 6.7e-6 / 2.1e-2 3.8e-3, 7.0e-3
Mistral 5.8e-3 / 0.80 8.2e-5 / 6.0e-3 2.4e-3, 2.6e-3
Qwen2 1.9e-3 / 0.85 9.5e-6 / 2.7e-2 1.9e-3, 1.1e-2

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:

transformers case main this PR padded
4.55.4, 4.56.2, 4.57.6 checkpointing off throughout 6.037, 5.933, 5.937 (cache built) 5.768, 5.639, 5.639 5.641, 5.639, 5.641
4.57.6, 5.2.0, 5.10.4, 5.17.0, 5.19.0 on at load, off in training 5.949, 5.937, 5.937, 5.937, 5.937 (cache built) 5.639 on every version 5.641
5.2.0 to 5.19.0 (18 releases) checkpointing off throughout 5.638 to 5.639 identical to main 5.639 to 5.641

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:

run main this PR main vs main (noise)
Llama-3.2-1B FastModel, GC fully off, 6 pairs 89.3 ms 90.0 ms 89.3 vs 96.6 ms
Qwen3-0.6B FastModel, GC fully off 147 to 160 ms 144 to 156 ms
Qwen3-4B, default GC (ratio head / base) 1.007, 0.971
Gemma-3, default GC (ratio head / base) 0.999, 1.021

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_loss costs 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 and compute_loss cases fail on main (5 failures) and pass here. Every test file touching for_training, for_inference, use_cache or compute_loss gives identical failing test IDs on main and this branch (all host-environment: no CUDA device, no sentence_transformers).

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 10, 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 ⚠️ Failed 2026-10-11T23:16:51.989308Z 259cdf8 New commits
ℹ️ 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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 10, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 6d75dfd8fc

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

@Etherll

Etherll commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator

With LoRA, auto padding-free and gradient checkpointing off (in both get_peft_model and the trainer config), packed documents no longer attend to each other during training on 513e5bbc.

What changed

  • Trainer setup turned the KV cache back on, and training only switched it off again when gradient checkpointing was on. A packed row then trained under one causal mask spanning all of its documents, so the loss was wrong. for_training now always disables the cache and packed batches pass use_cache=False into compute_loss, so the packed loss matches the per-document (padded) loss again.

Same three documents, one step, real checkpoints through FastModel + LoRA on one GPU:

model padded packed, base f5aff582 packed, this head
Llama-3.2-1B-Instruct 1.2689 2.2097 1.2694
Qwen3-0.6B 1.2301 2.2641 1.2311

Padded batches and the gradient-checkpointing-on path give identical loss on base and head. After training, for_inference restores use_cache and generate still uses a KV cache. The floor versions (transformers 4.57.6, TRL 0.29.1, unsloth_zoo 2026.10.3) give the same result.

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, GRPO fake-run (CPU spoof, TRL latest), fails with the same 12 ORPO/CPO tokenize_row failures on main, so it is unrelated. Fork CI on this exact head is still running: Etherll#226.

Tested on one Linux B200 host. Vision models were not trained, and the FastLanguageModel path is covered by the unit tests only.

@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: 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".

Comment thread unsloth/models/llama.py
Comment on lines +4721 to +4722
from unsloth_zoo.training_utils import disable_use_cache
disable_use_cache(model)

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 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 👍 / 👎.

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.

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.
@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: 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".

Comment thread unsloth/models/_utils.py
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")

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 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 👍 / 👎.

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.

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.

Comment thread unsloth/models/llama.py
Comment on lines +4721 to +4722
from unsloth_zoo.training_utils import disable_use_cache
disable_use_cache(model)

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 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 👍 / 👎.

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.

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.

Comment thread unsloth/models/rl.py
Comment on lines +287 to +289
from unsloth.models._utils import _forward_takes_use_cache
if _forward_takes_use_cache(model):
inputs = {**inputs, "use_cache": False}

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 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 👍 / 👎.

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.

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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@danielhanchen
danielhanchen merged commit 323932b into main Oct 12, 2026
@danielhanchen
danielhanchen deleted the fix-lora-padding-free-use-cache branch October 12, 2026 05:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants