From 953a5d3a633a09b2025773feaf1bf4d4264c2efc Mon Sep 17 00:00:00 2001 From: SIDDARTHA REDDY <75976672+SIDDARTHAREDDY8@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:43:18 -0500 Subject: [PATCH] Fix PEFT LoRA adapters not training with gradient checkpointing (#178) Signed-off-by: SIDDARTHA REDDY <75976672+SIDDARTHAREDDY8@users.noreply.github.com> --- src/train.py | 11 +- src/trainer/utils.py | 19 +++ tests/test_lora_gradient_checkpointing.py | 175 ++++++++++++++++++++++ 3 files changed, 204 insertions(+), 1 deletion(-) create mode 100644 tests/test_lora_gradient_checkpointing.py diff --git a/src/train.py b/src/train.py index 9cc6abcb5..e9d0e918d 100644 --- a/src/train.py +++ b/src/train.py @@ -4,7 +4,7 @@ from model import get_model from trainer import load_trainer from evals import get_evaluators -from trainer.utils import seed_everything +from trainer.utils import maybe_enable_input_require_grads, seed_everything @hydra.main(version_base=None, config_path="../configs", config_name="train.yaml") @@ -20,6 +20,15 @@ def main(cfg: DictConfig): assert model_cfg is not None, "Invalid model yaml passed in train config." model, tokenizer = get_model(model_cfg) + # With gradient checkpointing enabled, PEFT LoRA adapters inside the + # transformer blocks receive no gradient unless the model inputs + # require grad (see #178): checkpointing skips the backward pass through + # a block whose inputs do not require grad, so only lm_head trains. + gradient_checkpointing = ( + cfg.get("trainer", {}).get("args", {}).get("gradient_checkpointing", False) + ) + maybe_enable_input_require_grads(model, gradient_checkpointing) + # Load Dataset data_cfg = cfg.data data = get_data( diff --git a/src/trainer/utils.py b/src/trainer/utils.py index 11d2f8490..a3fa22fac 100644 --- a/src/trainer/utils.py +++ b/src/trainer/utils.py @@ -14,6 +14,25 @@ def seed_everything(seed=42): torch.backends.cudnn.benchmark = False +def maybe_enable_input_require_grads(model, gradient_checkpointing: bool) -> None: + """Enable input requires-grad hooks when gradient checkpointing is on. + + Gradient checkpointing skips the backward pass through a checkpointed + block when none of its inputs requires grad. For PEFT LoRA models the + hidden states entering the transformer blocks do not require grad, so + the LoRA adapters inside those blocks never receive a gradient and stay + at their zero initialization; only lm_head (outside the checkpointed + blocks) trains. Calling ``model.enable_input_require_grads()`` registers + a hook that makes the embedding outputs require grad, restoring gradient + flow into the checkpointed blocks. See #178. + + This is a no-op when gradient checkpointing is off or when the model + does not expose ``enable_input_require_grads``. + """ + if gradient_checkpointing and hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + + def compute_kl_divergence(model, target_model, inputs): with torch.no_grad(): ref_outputs = target_model(**inputs) diff --git a/tests/test_lora_gradient_checkpointing.py b/tests/test_lora_gradient_checkpointing.py new file mode 100644 index 000000000..83818ac2d --- /dev/null +++ b/tests/test_lora_gradient_checkpointing.py @@ -0,0 +1,175 @@ +"""Regression test for #178: LoRA adapters must train with gradient checkpointing. + +With gradient checkpointing enabled and no ``enable_input_require_grads()`` +hook, the LoRA adapters inside the checkpointed transformer blocks receive +no gradient and stay at their zero initialization; only the lm_head adapter +(outside the checkpointed blocks) trains. The fix in ``src/train.py`` calls +``maybe_enable_input_require_grads`` whenever gradient checkpointing is on. + +Note: pinned transformers 5.5.4 auto-registers that hook inside +``gradient_checkpointing_enable()``, so the failure is masked on the +standard Trainer path. The bug still bites on stacks where checkpointing is +enabled without that hook (older transformers, non-Trainer flows, custom +model handlers), which the ``manual`` setup below reproduces: it enables +checkpointing through ``_set_gradient_checkpointing`` instead of +``gradient_checkpointing_enable()``. + +Run with: python tests/test_lora_gradient_checkpointing.py +""" + +import sys +import unittest +from functools import partial +from pathlib import Path + +import torch +from torch.utils.checkpoint import checkpoint +from transformers import LlamaConfig, LlamaForCausalLM + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) +from trainer.utils import maybe_enable_input_require_grads # noqa: E402 + + +def tiny_llama(): + config = LlamaConfig( + vocab_size=100, + hidden_size=32, + intermediate_size=64, + num_hidden_layers=2, + num_attention_heads=4, + num_key_value_heads=4, + ) + return LlamaForCausalLM(config) + + +def lora_model(manual_checkpointing=False): + """Tiny LoRA model with gradient checkpointing enabled, as in #178. + + With ``manual_checkpointing``, checkpointing is enabled through the + internal setter, bypassing transformers' auto-registration of the + input-requires-grad hook, i.e. the state the reporter was in. + """ + from peft import LoraConfig, get_peft_model + + base = tiny_llama() + config = LoraConfig( + r=4, + lora_alpha=8, + target_modules=["q_proj", "v_proj", "lm_head"], + ) + model = get_peft_model(base, config) + model.config.use_cache = False + if manual_checkpointing: + model._set_gradient_checkpointing( + enable=True, + gradient_checkpointing_func=partial(checkpoint, use_reentrant=True), + ) + else: + model.gradient_checkpointing_enable() + return model + + +def lora_b_params(model): + return {name: param for name, param in model.named_parameters() if "lora_B" in name} + + +def backward_once(model): + torch.manual_seed(0) + ids = torch.randint(1, 100, (2, 8)) + batch = {"input_ids": ids, "attention_mask": torch.ones_like(ids), "labels": ids} + model(**batch).loss.backward() + + +def grad_is_missing(param): + return param.grad is None or float(param.grad.norm()) == 0.0 + + +class LoraGradientCheckpointingTests(unittest.TestCase): + def setUp(self): + torch.manual_seed(0) + try: + import peft # noqa: F401 + except ImportError: + self.skipTest("peft is not installed") + + def test_transformer_lora_adapters_get_no_gradient_without_fix(self): + # Pins the failure mode of #178 in the hook-absent state: the + # adapters in the checkpointed blocks get no gradient while lm_head + # still does. + model = lora_model(manual_checkpointing=True) + backward_once(model) + params = lora_b_params(model) + self.assertEqual(len(params), 5) # q/v of 2 layers + lm_head + for name, param in params.items(): + if "lm_head" in name: + self.assertFalse( + grad_is_missing(param), + f"{name} should still receive a gradient without the fix", + ) + else: + self.assertTrue( + grad_is_missing(param), + f"{name} must have no gradient without the fix (#178)", + ) + + def test_lora_adapters_train_with_checkpointing_after_fix(self): + # The reporter's check from #178: after one training step with + # checkpointing on, every lora_B must have moved from zero init. + model = lora_model(manual_checkpointing=True) + maybe_enable_input_require_grads(model, gradient_checkpointing=True) + params = lora_b_params(model) + self.assertEqual(len(params), 5) + for name, param in params.items(): + self.assertEqual( + float(param.detach().norm()), 0.0, f"{name} is not zero-init" + ) + + backward_once(model) + for name, param in params.items(): + self.assertFalse( + grad_is_missing(param), f"{name} received no gradient (#178)" + ) + + optimizer = torch.optim.SGD( + [p for p in model.parameters() if p.requires_grad], lr=0.5 + ) + optimizer.step() + for name, param in params.items(): + self.assertGreater( + float(param.detach().norm()), + 0.0, + f"{name} did not move from zero init after a training step", + ) + + def test_lora_adapters_train_with_pinned_transformers(self): + # Under the pinned transformers, gradient_checkpointing_enable() + # already registers the hook; the train.py fix must keep the + # reporter's check green there too (and stay a harmless no-op + # on top of the hook transformers registered). + model = lora_model(manual_checkpointing=False) + maybe_enable_input_require_grads(model, gradient_checkpointing=True) + backward_once(model) + params = lora_b_params(model) + self.assertEqual(len(params), 5) + for name, param in params.items(): + self.assertFalse( + grad_is_missing(param), f"{name} received no gradient (#178)" + ) + + def test_helper_is_noop_without_checkpointing(self): + calls = [] + + class FakeModel: + def enable_input_require_grads(self): + calls.append(True) + + maybe_enable_input_require_grads(FakeModel(), gradient_checkpointing=False) + self.assertEqual(calls, []) + + def test_helper_is_noop_without_the_method(self): + # Plain models without enable_input_require_grads must not break. + maybe_enable_input_require_grads(object(), gradient_checkpointing=True) + + +if __name__ == "__main__": + unittest.main()