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
Keep frozen BatchNorm running stats fixed during LoRA training (#12319)
Daniel Han48f6f6322de0
diff --git a/tests/test_frozen_norm_running_stats.py b/tests/test_frozen_norm_running_stats.pynew file mode 100644index 00000000000..a908323b187--- /dev/null+++ b/tests/test_frozen_norm_running_stats.py@@ -0,0 +1,149 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Frozen BatchNorm / InstanceNorm keep their running stats through LoRA training."""++import copy+import inspect+import pickle++import pytest++pytest.importorskip("torch")+import torch # noqa: E402+from torch import nn # noqa: E402++peft = pytest.importorskip("peft")+U = pytest.importorskip("unsloth.models._utils")+vision = pytest.importorskip("unsloth.models.vision")+FastBaseModel = vision.FastBaseModel+TRAIN = U._unsloth_train_if_needed+++class _Tiny(nn.Module):+ def __init__(self):+ super().__init__()+ self.conv = nn.Conv1d(4, 4, 1)+ self.norm = nn.BatchNorm1d(4)+ self.inorm = nn.InstanceNorm1d(4, affine = True, track_running_stats = True)+ self.proj = nn.Linear(4, 4)++ def forward(self, x):+ h = self.inorm(self.norm(self.conv(x)))+ return self.proj(h.transpose(1, 2))+++def _lora(modules_to_save = None):+ torch.manual_seed(0)+ cfg = peft.LoraConfig(+ r = 2, lora_alpha = 4, target_modules = ["proj"], modules_to_save = modules_to_save+ )+ return peft.get_peft_model(_Tiny(), cfg)+++def _stats(model):+ return {n: b.detach().clone() for n, b in model.named_buffers() if "running" in n}+++def _moved(before, after):+ return sorted(n for n in before if not torch.equal(before[n], after[n]))+++def _train_step(model):+ x = torch.randn(3, 4, 8) * 5 + 2+ model(x).float().pow(2).mean().backward()+++def _norms(model):+ return [+ m+ for m in model.modules()+ if isinstance(m, (nn.modules.batchnorm._BatchNorm, nn.modules.instancenorm._InstanceNorm))+ ]+++def test_trainer_step_keeps_frozen_norm_stats(monkeypatch):+ monkeypatch.delenv("UNSLOTH_FREEZE_NORM_RUNNING_STATS", raising = False)+ model = _lora()+ assert not any(p.requires_grad for m in _norms(model) for p in m.parameters())+ before = _stats(model)+ TRAIN(model)+ _train_step(model)+ assert model.training+ assert all(not m.training for m in _norms(model))+ assert _moved(before, _stats(model)) == []+ assert any(p.grad is not None for n, p in model.named_parameters() if "lora_" in n)+ FastBaseModel.for_inference(model)+ assert all(not m.training for m in model.modules())+ FastBaseModel.for_training(model)+ model.train()+ _train_step(model)+ assert all(not m.training for m in _norms(model))+ assert _moved(before, _stats(model)) == []+++def test_trainable_norm_still_updates(monkeypatch):+ monkeypatch.delenv("UNSLOTH_FREEZE_NORM_RUNNING_STATS", raising = False)+ torch.manual_seed(0)+ model = _Tiny()+ before = _stats(model)+ TRAIN(model)+ _train_step(model)+ assert all(m.training for m in _norms(model))+ assert set(_moved(before, _stats(model))) == set(before)+++def test_unfreezing_later_restores_train_mode(monkeypatch):+ monkeypatch.delenv("UNSLOTH_FREEZE_NORM_RUNNING_STATS", raising = False)+ model = _lora()+ TRAIN(model)+ norm = model.base_model.model.norm+ assert not norm.training+ for p in norm.parameters():+ p.requires_grad_(True)+ model.train()+ assert norm.training+++def test_modules_to_save_norm_trains(monkeypatch):+ monkeypatch.delenv("UNSLOTH_FREEZE_NORM_RUNNING_STATS", raising = False)+ model = _lora(modules_to_save = ["norm"])+ TRAIN(model)+ wrapper = model.base_model.model.norm+ trained = wrapper.modules_to_save["default"]+ before = trained.running_mean.clone()+ _train_step(model)+ assert trained.training+ assert not torch.equal(before, trained.running_mean)+++def test_opt_out_env_restores_old_behaviour(monkeypatch):+ monkeypatch.setenv("UNSLOTH_FREEZE_NORM_RUNNING_STATS", "0")+ model = _lora()+ before = _stats(model)+ TRAIN(model)+ _train_step(model)+ assert all(m.training for m in _norms(model))+ assert set(_moved(before, _stats(model))) == set(before)+++def test_eval_state_dict_copy_and_pickle_unaffected(monkeypatch):+ monkeypatch.delenv("UNSLOTH_FREEZE_NORM_RUNNING_STATS", raising = False)+ model = _lora()+ keys = set(model.state_dict())+ TRAIN(model)+ assert set(model.state_dict()) == keys+ model.eval()+ assert all(not m.training for m in model.modules())+ clone = copy.deepcopy(model)+ clone.train()+ assert all(not m.training for m in _norms(clone))+ assert clone.base_model.model.norm.train.args[0] is clone.base_model.model.norm+ restored = pickle.loads(pickle.dumps(clone))+ restored.train()+ assert all(not m.training for m in _norms(restored))+++def test_post_patch_model_installs_the_guard():+ src = inspect.getsource(FastBaseModel.post_patch_model)+ assert "_unsloth_freeze_norm_running_stats(model)" in srcdiff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 780fa4f6a47..6c055053365 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -4646,6 +4646,7 @@ def _unsloth_train_if_needed(model):and _unsloth_wrappees_are_in_train_mode(model)):return model+ _unsloth_freeze_norm_running_stats(model)model.train()try:model._unsloth_train_mode_asserted = True@@ -4654,6 +4655,39 @@ def _unsloth_train_if_needed(model):return model+_UNSLOTH_RUNNING_STAT_NORMS = (+ torch.nn.modules.batchnorm._BatchNorm,+ torch.nn.modules.instancenorm._InstanceNorm,+)+++def _unsloth_norm_stats_are_frozen(module):+ """Running-stat norm with all own params frozen. UNSLOTH_FREEZE_NORM_RUNNING_STATS=0 opts out."""+ if os.environ.get("UNSLOTH_FREEZE_NORM_RUNNING_STATS", "1") == "0":+ return False+ if not getattr(module, "track_running_stats", False):+ return False+ params = list(module.parameters(recurse = False))+ return len(params) > 0 and not any(p.requires_grad for p in params)+++def _unsloth_norm_train(module, mode = True):+ if mode and _unsloth_norm_stats_are_frozen(module):+ mode = False+ return type(module).train(module, mode)+++def _unsloth_freeze_norm_running_stats(model):+ """Keep frozen running-stat norms in eval (LoRA never saves their buffers); rechecked per train() call."""+ if not isinstance(model, torch.nn.Module):+ return model+ for module in model.modules():+ if isinstance(module, _UNSLOTH_RUNNING_STAT_NORMS) and "train" not in module.__dict__:+ # partial, not a bound method, so deepcopy / pickle still work.+ module.train = functools.partial(_unsloth_norm_train, module)+ return model++def _unsloth_cache_reuses_one_config(cache):"""Whether this autotuner cache answers every key with its one stored config.diff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex 0d180e69958..3200fa793f7 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -117,6 +117,7 @@ from ._utils import (_cast_text_only_prequantized_params,_select_moe_detection_targets,set_task_config_attr,+ _unsloth_freeze_norm_running_stats,)from ._utils import *from ._remote_code_buffers import restore_remote_code_non_persistent_buffers@@ -4198,6 +4199,7 @@ class FastBaseModel:if full_finetuning:# prepare_model_for_training re-enabled every parameter, a kept wrapper's siblings too._freeze_unused_siblings(model)+ _unsloth_freeze_norm_running_stats(model)_model_type = getattr(getattr(model, "config", None), "model_type", "") or ""if not use_reentrant and not any(x in _model_type.lower() for x in ("gemma3n", "gemma4")):# _set_gradient_checkpointing() binds torch's checkpoint as a default argument, bypassing the patch above.