Skip to content

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.

Hybrid packing: install the varlen forward as a bound method so accelerate's unwrap keeps it (#13721)

Daniel Hanac9d4104b37e
diff --git a/tests/utils/test_packing.py b/tests/utils/test_packing.py
index e2b1fd6258d..c9003da304d 100644
--- a/tests/utils/test_packing.py
+++ b/tests/utils/test_packing.py
@@ -443,6 +443,34 @@ def test_patch_hybrid_varlen_active_and_idempotent(monkeypatch):
assert scan_orig.calls[-1] is None
+def test_patch_hybrid_varlen_survives_accelerate_unwrap(monkeypatch):
+ # TRL runs accelerate's extract_model_from_parallel(keep_fp32_wrapper = False) every step
+ # after a mixed-precision prepare_model; it rebinds the forward it finds with
+ # MethodType(forward, model). A plain-function wrapper then got the model positionally:
+ # "PeftModelForCausalLM.forward() got multiple values for argument 'input_ids'".
+ from types import MethodType
+ from accelerate.utils import extract_model_from_parallel
+ from accelerate.utils.operations import convert_outputs_to_fp32
+
+ monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
+ model = _ShimHybridModel()
+ assert patch_hybrid_linear_attention_varlen(model) is True
+ assert list(inspect.signature(model.forward).parameters)[:3] == [
+ "input_ids",
+ "position_ids",
+ "packed_seq_lengths",
+ ]
+ # Accelerator.prepare_model with native AMP (accelerate/accelerator.py).
+ model._original_forward = model.forward
+ if hasattr(model.forward, "__func__"):
+ model.forward = MethodType(convert_outputs_to_fp32(model.forward.__func__), model)
+ else:
+ model.forward = convert_outputs_to_fp32(model.forward)
+ model = extract_model_from_parallel(model, keep_fp32_wrapper = False)
+ out = model(input_ids = torch.zeros(1, 6, dtype = torch.long), use_cache = False)
+ assert out.shape == (1, 6)
+
+
def test_patch_hybrid_varlen_torch_fallback_fail_closed(monkeypatch):
monkeypatch.setenv("UNSLOTH_EXPERIMENTAL_HYBRID_PACKING", "1")
model = _ShimHybridModel()
diff --git a/unsloth/utils/packing.py b/unsloth/utils/packing.py
index bf4011e3e8b..bdeb0791c0e 100644
--- a/unsloth/utils/packing.py
+++ b/unsloth/utils/packing.py
@@ -16,6 +16,7 @@ from __future__ import annotations
import copy
import inspect
+import types
import logging
import os
import sys
@@ -1458,8 +1459,12 @@ def patch_hybrid_linear_attention_varlen(model) -> bool:
except (TypeError, ValueError):
forward_sig = None
- @wraps(forward_orig)
- def forward_with_varlen(*args, **kwargs):
+ # A bound method with no __wrapped__: accelerate's unwrap_model(keep_fp32_wrapper = False),
+ # run by TRL every step, rebinds the forward it finds with MethodType(forward, model), which
+ # passes the model as input_ids to a plain function. The self check covers a double bind.
+ def forward_with_varlen(self, *args, **kwargs):
+ if args and args[0] is self:
+ args = args[1:]
try:
bound = dict(kwargs)
if forward_sig is not None and args:
@@ -1506,7 +1511,18 @@ def patch_hybrid_linear_attention_varlen(model) -> bool:
)
return out
- model.forward = forward_with_varlen
+ for attribute in ("__name__", "__qualname__", "__doc__", "__module__"):
+ try:
+ setattr(forward_with_varlen, attribute, getattr(forward_orig, attribute))
+ except Exception:
+ pass
+ if forward_sig is not None:
+ # Bound below, so callers see forward_orig's parameters once `self` is dropped.
+ self_param = inspect.Parameter("self", inspect.Parameter.POSITIONAL_ONLY)
+ forward_with_varlen.__signature__ = forward_sig.replace(
+ parameters = [self_param, *forward_sig.parameters.values()]
+ )
+ model.forward = types.MethodType(forward_with_varlen, model)
model._unsloth_varlen_forward_wrapped = True
_wrap_generate_clears_varlen(model, hybrid_modules)