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.

Fix num_items_in_batch GA for Gemma4 (#4998)

Datta Nimmaturi4328d0b4f691
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index d8fe92739a6..96675eeaf09 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -2108,11 +2108,14 @@ def patch_gradient_accumulation_fix(Trainer):
"def __init__", "def _unsloth___init__", 1
)
- # Force else branch
- init_function = re.sub(
- r'if[\s]+hasattr\(\s*unwrapped_model\s*,\s*"accepts_loss_kwargs"\s*\)\s*:',
- 'if hasattr(unwrapped_model, "accepts_loss_kwargs") and False:',
- init_function,
+ # Respect an inner wrapped model's explicit accepts_loss_kwargs flag before inferring from forward(**kwargs).
+ # https://github.com/unslothai/unsloth/issues/4982 Gemma4ForConditionalGeneration had issues with grad_acc
+ init_function = init_function.replace(
+ "self.model_accepts_loss_kwargs = unwrapped_model.accepts_loss_kwargs\n else:",
+ "self.model_accepts_loss_kwargs = unwrapped_model.accepts_loss_kwargs\n"
+ ' elif hasattr(getattr(unwrapped_model, "model", None), "accepts_loss_kwargs"):\n'
+ " self.model_accepts_loss_kwargs = unwrapped_model.model.accepts_loss_kwargs\n"
+ " else:",
)
exec(init_function, globals())
Trainer.__init__ = _unsloth___init__