Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Make precomputed inputs_embeds train under gradient checkpointing (#13088)
Daniel Han8cae9f853f48
diff --git a/tests/test_inputs_embeds_require_grads.py b/tests/test_inputs_embeds_require_grads.pynew file mode 100644index 00000000000..954c54daad2--- /dev/null+++ b/tests/test_inputs_embeds_require_grads.py@@ -0,0 +1,90 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Training on inputs_embeds under reentrant gradient checkpointing (#2178)."""++import pytest++transformers = pytest.importorskip("transformers")++import unsloth # noqa: E402,F401 applies patch_enable_input_require_grads+import torch # noqa: E402+from transformers import LlamaConfig, LlamaForCausalLM # noqa: E402++HOOK_NAME = "make_inputs_embeds_require_grads"+++def _model():+ torch.manual_seed(0)+ config = LlamaConfig(+ hidden_size = 32,+ intermediate_size = 64,+ num_hidden_layers = 2,+ num_attention_heads = 4,+ num_key_value_heads = 4,+ vocab_size = 64,+ )+ model = LlamaForCausalLM(config).float()+ model.requires_grad_(False)+ # Stand-in for a LoRA weight: trainable, inside a checkpointed layer.+ trainable = model.model.layers[0].self_attn.q_proj.weight+ trainable.requires_grad_(True)+ model.gradient_checkpointing_enable(gradient_checkpointing_kwargs = {"use_reentrant": True})+ model.enable_input_require_grads()+ model.train()+ return model, trainable+++def _grad(model, trainable, **inputs):+ trainable.grad = None+ ids = torch.arange(12).reshape(2, 6)+ loss = model(labels = ids, **inputs).loss+ loss.backward()+ return loss.detach(), trainable.grad.clone()+++def test_precomputed_inputs_embeds_match_input_ids():+ model, trainable = _model()+ ids = torch.arange(12).reshape(2, 6)+ loss_ids, grad_ids = _grad(model, trainable, input_ids = ids)+ # F.embedding skips the embedding's own hook, as a precomputed tensor would.+ embeds = torch.nn.functional.embedding(ids, model.get_input_embeddings().weight)+ loss_embeds, grad_embeds = _grad(model, trainable, inputs_embeds = embeds)+ assert torch.equal(loss_ids, loss_embeds)+ assert grad_ids.abs().sum() > 0+ torch.testing.assert_close(grad_embeds, grad_ids)+ assert not embeds.requires_grad and embeds.grad is None+++def test_upstream_projection_still_gets_gradients():+ model, trainable = _model()+ proj = torch.nn.Linear(5, model.config.hidden_size)+ embeds = proj(torch.randn(2, 6, 5))+ _grad(model, trainable, inputs_embeds = embeds)+ assert proj.weight.grad is not None and proj.weight.grad.abs().sum() > 0+++def test_hook_is_registered_once_and_removed_by_disable():+ model, _ = _model()+ model.enable_input_require_grads()++ def count():+ return sum(+ getattr(hook, "__name__", None) == HOOK_NAME+ for module in model.modules()+ for hook in module._forward_pre_hooks.values()+ )++ assert count() == 2 # LlamaForCausalLM and LlamaModel, once each+ model.disable_input_require_grads()+ assert count() == 0+++def test_no_grad_forward_is_untouched():+ model, _ = _model()+ model.eval()+ ids = torch.arange(12).reshape(2, 6)+ embeds = torch.nn.functional.embedding(ids, model.get_input_embeddings().weight)+ with torch.no_grad():+ out = model(inputs_embeds = embeds)+ assert not out.logits.requires_graddiff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.pyindex 171d2c29226..44828cfee61 100644--- a/unsloth/import_fixes.py+++ b/unsloth/import_fixes.py@@ -4975,6 +4975,37 @@ def patch_enable_input_require_grads():return _RequireGrad.apply(output, anchor)output.requires_grad_(True)+ def make_inputs_embeds_require_grads(module, args, kwargs):+ # inputs_embeds skips the embedding hook, so reentrant checkpointing starved the adapters (#2178).+ inputs_embeds = kwargs.get("inputs_embeds")+ if (+ not isinstance(inputs_embeds, torch.Tensor)+ or inputs_embeds.requires_grad+ or not torch.is_grad_enabled()+ or not inputs_embeds.is_floating_point()+ ):+ return None+ if torch.compiler.is_compiling():+ inputs_embeds = _RequireGrad.apply(inputs_embeds, anchor)+ else:+ inputs_embeds = inputs_embeds.detach().requires_grad_(True)+ return args, {**kwargs, "inputs_embeds": inputs_embeds}++ def register_inputs_embeds_hooks(model):+ # Replace, not stack: a repeat enable keeps one hook, and disable can remove it.+ handles = []+ for module in model.modules():+ if not isinstance(module, PreTrainedModel):+ continue+ for key, hook in list(module._forward_pre_hooks.items()):+ if getattr(hook, "__name__", None) == make_inputs_embeds_require_grads.__name__:+ del module._forward_pre_hooks[key]+ module._forward_pre_hooks_with_kwargs.pop(key, None)+ handles.append(+ module.register_forward_pre_hook(make_inputs_embeds_require_grads, with_kwargs = True)+ )+ return handles+# Older transformers hooks a single embedding (huggingface/transformers#41993 added the loop).# wraps keeps inspect.getsource on transformers' source for later source checks.original = PreTrainedModel.enable_input_require_grads@@ -4985,8 +5016,22 @@ def patch_enable_input_require_grads():self._require_grads_hook = self.get_input_embeddings().register_forward_hook(make_inputs_require_grads)+ self._require_grads_hooks = [self._require_grads_hook] + register_inputs_embeds_hooks(+ self+ )++ original_disable = PreTrainedModel.disable_input_require_grads++ # The old disable only removes _require_grads_hook, which would leave the pre-hooks.+ @functools.wraps(original_disable)+ def _patched_single_disable_input_require_grads(self):+ for hook in getattr(self, "_require_grads_hooks", ()):+ hook.remove()+ self._require_grads_hooks = []+ original_disable(self)PreTrainedModel.enable_input_require_grads = _patched_single_enable_input_require_grads+ PreTrainedModel.disable_input_require_grads = _patched_single_disable_input_require_gradsreturn@functools.wraps(original)@@ -5028,7 +5073,7 @@ def patch_enable_input_require_grads():seen_modules.add(embedding_id)hooks.append(input_embeddings.register_forward_hook(make_inputs_require_grads))- self._require_grads_hooks = hooks+ self._require_grads_hooks = hooks + register_inputs_embeds_hooks(self)if hooks:self._require_grads_hook = hooks[0]