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
Faster import unsloth and from_pretrained: fewer GC passes, skip regexes that cannot match (#15560)
Daniel Han89a8443df007
diff --git a/tests/test_device_helpers.py b/tests/test_device_helpers.pyindex 600d2498980..ae57f791235 100644--- a/tests/test_device_helpers.py+++ b/tests/test_device_helpers.py@@ -262,11 +262,11 @@ def test_model_call_sites_use_shared_cache_dispatch():assert "torch.cuda.current_device()" not in gemma_sourceassert "get_current_device()" in gemma_sourceassert "torch.cuda.empty_cache()" not in gemma_source- assert "clean_gpu_cache()" in gemma_source+ assert "collect_garbage(after = clean_gpu_cache)" in gemma_sourceassert "torch.cuda.empty_cache()" not in gemma2_source- assert "clean_gpu_cache()" in gemma2_source+ assert "collect_garbage(after = clean_gpu_cache)" in gemma2_sourceassert "torch.cuda.empty_cache()" not in granite_source- assert "clean_gpu_cache()" in granite_source+ assert "collect_garbage(after = clean_gpu_cache)" in granite_source# Keyed off cuda alone, the load-retry flush and the optimizer fence were no-ops on NPU / XPU.assert "torch.cuda.empty_cache()" not in loader_utils_sourceassert "torch.xpu.empty_cache()" not in loader_utils_sourcediff --git a/tests/test_gc_collect_garbage.py b/tests/test_gc_collect_garbage.pynew file mode 100644index 00000000000..a5d2c4b9a3a--- /dev/null+++ b/tests/test_gc_collect_garbage.py@@ -0,0 +1,196 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++"""Model loading's repeated full gc.collect() passes stop only after a pass that really ran and found nothing.++CPython's gc.collect() returns 0 without collecting while another thread's collection is in progress, so a+plain `collected == 0` check can end the loop before any pass ran and leave the garbage it was meant to free.+The release sites call unsloth/_gc_passes.collect_garbage, which also checks the full-collection stats.+CPU only: the helper is loaded on its own and the release statements are sliced out of the sources with ast."""++from __future__ import annotations++import ast+import gc as real_gc+import importlib.util+import threading+from pathlib import Path++import pytest++ROOT = Path(__file__).resolve().parents[1] / "unsloth"+# file -> number of release sites (load, get_peft_model, patch_peft_model, post_patch)+SITES = {+ "models/vision.py": 5,+ "models/llama.py": 4,+ "models/gemma.py": 1,+ "models/gemma2.py": 1,+ "models/granite.py": 1,+}+++def _load_helper():+ path = ROOT / "_gc_passes.py"+ if not path.exists():+ return None+ spec = importlib.util.spec_from_file_location("_gc_passes_under_test", path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def _is_collect(node):+ return (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "collect"+ and getattr(node.func.value, "id", None) == "gc"+ )+++def _is_helper_call(node):+ return (+ isinstance(node, ast.Expr)+ and isinstance(node.value, ast.Call)+ and getattr(node.value.func, "id", None) == "collect_garbage"+ )+++def _release_statements(rel):+ tree = ast.parse((ROOT / rel).read_text(encoding = "utf-8"))+ found = []+ for node in ast.walk(tree):+ if _is_helper_call(node):+ found.append(node)+ elif isinstance(node, ast.For) and any(_is_collect(c) for c in ast.walk(node)):+ found.append(node)+ return sorted(found, key = lambda n: n.lineno)+++CASES = [+ pytest.param(rel, i, id = f"{rel}:{i}") for rel, count in SITES.items() for i in range(count)+]++[email protected]("rel,count", list(SITES.items()))+def test_every_release_site_uses_the_helper(rel, count):+ statements = _release_statements(rel)+ assert len(statements) == count+ assert all(_is_helper_call(s) for s in statements), [s.lineno for s in statements]+ for s in statements:+ assert [k.arg for k in s.value.keywords] == ["after"]+ assert getattr(s.value.keywords[0].value, "id", None) == "clean_gpu_cache"++[email protected]("rel,index", CASES)+def test_a_pass_skipped_for_another_threads_collection_does_not_end_it(rel, index):+ # Thread A is inside a collection, blocked in a finalizer, when the release starts. Its first+ # gc.collect() returns 0 without collecting; stopping there would leave our garbage behind.+ statement = _release_statements(rel)[index]+ code = compile(ast.Module([statement], []), rel, "exec")+ helper = _load_helper()+ started, release = threading.Event(), threading.Event()++ class Slow:+ def __init__(self):+ self.me = self++ def __del__(self):+ started.set()+ release.wait(30)++ class Ours:+ def __init__(self):+ self.me = self++ flushes = []++ def clean_gpu_cache():+ # Thread A finishes during the first flush, between our first and second pass.+ release.set()+ a.join(30)+ flushes.append(1)++ namespace = {"gc": real_gc, "clean_gpu_cache": clean_gpu_cache}+ if helper is not None:+ namespace["collect_garbage"] = helper.collect_garbage+ was_enabled = real_gc.isenabled()+ real_gc.disable()+ a = threading.Thread(target = real_gc.collect)+ try:+ real_gc.collect()+ Slow()+ a.start()+ assert started.wait(30)+ for _ in range(5):+ Ours()+ exec(code, namespace)+ # Skipped, then found ours, then quiet; the cache is flushed after each.+ assert len(flushes) == 3+ assert not any(type(o) is Ours for o in real_gc.get_objects())+ finally:+ release.set()+ a.join(30)+ if was_enabled:+ real_gc.enable()+++class _FakeGC:+ """`script` items: an int or None is what a pass that runs returns; "skip" returns 0 without collecting."""++ def __init__(+ self,+ script,+ callbacks = (),+ ):+ self.script = iter(script)+ self.callbacks = list(callbacks)+ self.stats = {"collections": 0, "collected": 0, "uncollectable": 0}+ self.calls = 0++ def get_stats(self):+ return [{}, {}, dict(self.stats)]++ def collect(self):+ self.calls += 1+ result = next(self.script)+ if result == "skip":+ return 0+ self.stats["collections"] += 1+ self.stats["collected"] += result or 0+ return result+++ "script,expected",+ [+ ([5, 0, 7], 2),+ ([0, 9, 9], 1),+ ([4, 2, 1], 3),+ ([None, None, None], 3), # gc.collect swapped for `lambda: None`+ (["skip", 0, 9], 2),+ (["skip", "skip", "skip"], 3),+ ],+)+def test_collect_garbage_stops_after_a_pass_that_ran_and_found_nothing(+ monkeypatch, script, expected+):+ helper = _load_helper()+ assert helper is not None+ gc = _FakeGC(script)+ monkeypatch.setattr(helper, "gc", gc)+ order = []+ helper.collect_garbage(+ before = lambda: order.append("before"), after = lambda: order.append("after")+ )+ assert gc.calls == expected+ assert order == ["before", "after"] * expected+++def test_collect_garbage_keeps_every_pass_with_gc_callbacks(monkeypatch):+ helper = _load_helper()+ assert helper is not None+ gc = _FakeGC([0, 0, 0], callbacks = [print])+ monkeypatch.setattr(helper, "gc", gc)+ helper.collect_garbage()+ assert gc.calls == 3diff --git a/tests/test_import_gc_threshold.py b/tests/test_import_gc_threshold.pynew file mode 100644index 00000000000..59f2aaa652f--- /dev/null+++ b/tests/test_import_gc_threshold.py@@ -0,0 +1,199 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.+#+# This program is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU Affero General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with this program. If not, see <https://www.gnu.org/licenses/>.+"""`import unsloth` raises the GC threshold for its own imports and hands the caller's back."""++import ast+import gc+import importlib+import importlib.machinery+import importlib.util+import pathlib+import sys+import types++import pytest++_UNSLOTH = pathlib.Path(__file__).resolve().parents[1] / "unsloth"+++def import_gc():+ spec = importlib.util.spec_from_file_location(+ "_unsloth_import_gc_under_test", _UNSLOTH / "_import_gc.py"+ )+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ original = gc.get_threshold()+ try:+ yield module+ finally:+ gc.set_threshold(*original)+ sys.meta_path[:] = [+ f for f in sys.meta_path if not isinstance(f, module._RestoreAfterFailedImport)+ ]+++def _stored(*thresholds):+ """What gc.get_threshold() reports for these: Python 3.14's incremental GC keeps no threshold2."""+ before = gc.get_threshold()+ gc.set_threshold(*thresholds)+ try:+ return gc.get_threshold()+ finally:+ gc.set_threshold(*before)+++def test_raise_then_restore_returns_the_callers_thresholds(import_gc):+ gc.set_threshold(700, 11, 12)+ import_gc.raise_gc_threshold()+ assert gc.get_threshold() == _stored(import_gc.IMPORT_THRESHOLD, 11, 12)+ import_gc.restore_gc_threshold()+ assert gc.get_threshold() == _stored(700, 11, 12)+ # Idempotent: a second restore has nothing to undo.+ import_gc.restore_gc_threshold()+ assert gc.get_threshold() == _stored(700, 11, 12)+++def test_a_failed_import_retry_still_restores_the_first_thresholds(import_gc):+ gc.set_threshold(700, 11, 12)+ import_gc.raise_gc_threshold()+ # The first `import unsloth` raised before its restore; the retry raises again.+ import_gc.raise_gc_threshold()+ import_gc.restore_gc_threshold()+ assert gc.get_threshold() == _stored(700, 11, 12)+++def test_a_threshold_changed_after_a_failed_import_is_the_new_original(import_gc):+ gc.set_threshold(700, 11, 12)+ import_gc.raise_gc_threshold()+ gc.set_threshold(900, 11, 12)+ import_gc.raise_gc_threshold()+ import_gc.restore_gc_threshold()+ assert gc.get_threshold() == _stored(900, 11, 12)++[email protected]("threshold", [0, 200_000])+def test_disabled_or_higher_thresholds_are_left_alone(import_gc, threshold):+ gc.set_threshold(threshold, 11, 12)+ import_gc.raise_gc_threshold()+ assert gc.get_threshold() == _stored(threshold, 11, 12)+ import_gc.restore_gc_threshold()+ assert gc.get_threshold() == _stored(threshold, 11, 12)+++def test_a_threshold_set_during_the_import_is_kept(import_gc):+ gc.set_threshold(700, 11, 12)+ import_gc.raise_gc_threshold()+ gc.set_threshold(5000, 11, 12)+ import_gc.restore_gc_threshold()+ assert gc.get_threshold() == _stored(5000, 11, 12)+++def test_generations_1_and_2_changed_during_the_import_are_kept(import_gc):+ gc.set_threshold(700, 11, 12)+ import_gc.raise_gc_threshold()+ gc.set_threshold(import_gc.IMPORT_THRESHOLD, 20, 30)+ import_gc.restore_gc_threshold()+ assert gc.get_threshold() == _stored(700, 20, 30)+++def _in_flight(name):+ module = types.ModuleType(name)+ sys.modules[name] = module+ return module+++def test_a_failed_import_is_restored_by_the_next_import(import_gc):+ gc.set_threshold(700, 11, 12)+ module = _in_flight("_unsloth_gc_probe_pkg")+ import_gc.raise_gc_threshold(module)+ # Still in flight: imports during it keep the raised threshold.+ with pytest.raises(ModuleNotFoundError):+ importlib.import_module("_unsloth_gc_missing_one")+ assert gc.get_threshold()[0] == import_gc.IMPORT_THRESHOLD+ # The import raised: the package left sys.modules; the next import gives the threshold back.+ del sys.modules["_unsloth_gc_probe_pkg"]+ with pytest.raises(ModuleNotFoundError):+ importlib.import_module("_unsloth_gc_missing_two")+ assert gc.get_threshold() == _stored(700, 11, 12)+ # Inert until the next raise / restore removes it outside finder iteration.+ assert import_gc._hook.module is None+++def test_the_restoring_import_still_reaches_the_next_finder(import_gc):+ # sys.meta_path is iterated live: a hook removing itself would skip BuiltinImporter here.+ gc.set_threshold(700, 11, 12)+ module = _in_flight("_unsloth_gc_probe_builtin")+ import_gc.raise_gc_threshold(module)+ hook_at = sys.meta_path.index(import_gc._hook)+ builtin_at = sys.meta_path.index(importlib.machinery.BuiltinImporter)+ sys.meta_path.insert(hook_at + 1, sys.meta_path.pop(builtin_at))+ del sys.modules["_unsloth_gc_probe_builtin"]+ saved = sys.modules.pop("_string", None)+ try:+ importlib.import_module("_string")+ finally:+ if saved is not None:+ sys.modules["_string"] = saved+ sys.meta_path.insert(builtin_at, sys.meta_path.pop(hook_at + 1))+ assert gc.get_threshold() == _stored(700, 11, 12)+++def test_a_retry_after_a_failed_import_rearms_and_then_removes_the_hook(import_gc):+ gc.set_threshold(700, 11, 12)+ import_gc.raise_gc_threshold(_in_flight("_unsloth_gc_probe_retry"))+ del sys.modules["_unsloth_gc_probe_retry"]+ with pytest.raises(ModuleNotFoundError):+ importlib.import_module("_unsloth_gc_missing_three")+ module = _in_flight("_unsloth_gc_probe_retry")+ try:+ import_gc.raise_gc_threshold(module)+ assert gc.get_threshold()[0] == import_gc.IMPORT_THRESHOLD+ with pytest.raises(ModuleNotFoundError):+ importlib.import_module("_unsloth_gc_missing_four")+ assert gc.get_threshold()[0] == import_gc.IMPORT_THRESHOLD+ import_gc.restore_gc_threshold()+ finally:+ sys.modules.pop("_unsloth_gc_probe_retry", None)+ assert gc.get_threshold() == _stored(700, 11, 12)+ assert not any(isinstance(f, import_gc._RestoreAfterFailedImport) for f in sys.meta_path)+++def test_a_successful_import_removes_the_hook(import_gc):+ gc.set_threshold(700, 11, 12)+ module = _in_flight("_unsloth_gc_probe_ok")+ try:+ import_gc.raise_gc_threshold(module)+ assert any(isinstance(f, import_gc._RestoreAfterFailedImport) for f in sys.meta_path)+ import_gc.restore_gc_threshold()+ finally:+ sys.modules.pop("_unsloth_gc_probe_ok", None)+ assert gc.get_threshold() == _stored(700, 11, 12)+ assert not any(isinstance(f, import_gc._RestoreAfterFailedImport) for f in sys.meta_path)+++def test_init_raises_first_and_restores_last():+ body = ast.parse((_UNSLOTH / "__init__.py").read_text(encoding = "utf-8")).body+ calls = [+ node.value.func.id+ for node in body+ if isinstance(node, ast.Expr)+ and isinstance(node.value, ast.Call)+ and isinstance(node.value.func, ast.Name)+ ]+ assert calls[0] == "_raise_gc_threshold"+ assert calls[-1] == "_restore_gc_threshold"+ assert isinstance(body[-1], ast.Delete) and body[-1].targets[0].id == "_restore_gc_threshold"diff --git a/unsloth/__init__.py b/unsloth/__init__.pyindex 17631606177..9b23c0cb492 100644--- a/unsloth/__init__.py+++ b/unsloth/__init__.py@@ -11,6 +11,12 @@import os, importlib.util, platform, sys+# Restored at the end of this file.+from ._import_gc import raise_gc_threshold as _raise_gc_threshold++_raise_gc_threshold(sys.modules.get(__name__))+del _raise_gc_threshold+os.environ["UNSLOTH_IS_PRESENT"] = "1"# Opt into ROCm AOTriton kernels torch still gates as experimental; setdefault keeps an explicit "0".@@ -1761,3 +1767,8 @@ try:del _fix_dillexcept Exception:pass++from ._import_gc import restore_gc_threshold as _restore_gc_threshold++_restore_gc_threshold()+del _restore_gc_thresholddiff --git a/unsloth/_gc_passes.py b/unsloth/_gc_passes.pynew file mode 100644index 00000000000..bee14eed883--- /dev/null+++ b/unsloth/_gc_passes.py@@ -0,0 +1,37 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++"""Full gc.collect() passes that stop once a pass that really ran finds nothing. Imports only gc."""++import gc++__all__ = ["collect_garbage"]+++def collect_garbage(+ passes = 3,+ before = None,+ after = None,+):+ """Up to `passes` full gc.collect() passes, `before` / `after` run around each.++ Stops after a pass that ran and found nothing. Keeps going while gc.callbacks are registered (they+ may drop references) or when the gen 2 stats do not show one more empty collection (CPython returns 0+ without collecting while another thread is collecting).+ """+ for _ in range(passes):+ if before is not None:+ before()+ seen = gc.get_stats()[2]+ found = gc.collect()+ ran = gc.get_stats()[2]+ if after is not None:+ after()+ if (+ found == 0+ and not gc.callbacks+ and ran["collections"] == seen["collections"] + 1+ and ran["collected"] == seen["collected"]+ and ran["uncollectable"] == seen["uncollectable"]+ ):+ breakdiff --git a/unsloth/_import_gc.py b/unsloth/_import_gc.pynew file mode 100644index 00000000000..707d844ec85--- /dev/null+++ b/unsloth/_import_gc.py@@ -0,0 +1,77 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++"""Raise the gen 0 GC threshold while `import unsloth` runs: torch / transformers / trl allocate+~700k long-lived objects, so the default triggers full collections that find almost nothing.+A failed import leaves sys.modules; a meta path hook then restores it on the next import."""++import gc+import sys++IMPORT_THRESHOLD = 100_000+_saved = None+++class _RestoreAfterFailedImport:+ """Never finds anything; once `import unsloth` is no longer in flight, gives the threshold back."""++ __slots__ = ("module", "name")++ def __init__(self, module):+ self.arm(module)++ def arm(self, module):+ self.module = module+ self.name = module.__name__++ def find_spec(+ self,+ name,+ path = None,+ target = None,+ ):+ module = self.module+ if module is not None and sys.modules.get(self.name) is not module:+ # Not removed here: sys.meta_path is iterated live, removal skips the next finder.+ self.module = None+ restore_gc_threshold(remove_hook = False)+ return None+++_hook = None+++def raise_gc_threshold(module = None):+ global _saved, _hook+ current = gc.get_threshold()+ if _saved is not None and current[0] == IMPORT_THRESHOLD:+ pass # Still raised by an earlier attempt that failed.+ # 0 means automatic collection is off; a higher threshold was chosen on purpose.+ elif current[0] == 0 or current[0] >= IMPORT_THRESHOLD:+ _saved = None+ return+ else:+ _saved = current[0]+ gc.set_threshold(IMPORT_THRESHOLD, *current[1:])+ if module is not None:+ if _hook is None:+ _hook = _RestoreAfterFailedImport(module)+ sys.meta_path.insert(0, _hook)+ else:+ _hook.arm(module)+++def restore_gc_threshold(remove_hook = True):+ global _saved, _hook+ if remove_hook:+ hook, _hook = _hook, None+ if hook is not None:+ try:+ sys.meta_path.remove(hook)+ except ValueError:+ pass+ saved, _saved = _saved, None+ # Leave it alone if something changed it during the import; generations 1 and 2 are the caller's.+ current = gc.get_threshold()+ if saved is not None and current[0] == IMPORT_THRESHOLD:+ gc.set_threshold(saved, *current[1:])diff --git a/unsloth/models/gemma.py b/unsloth/models/gemma.pyindex eec1ff58ede..7a12649f13e 100644--- a/unsloth/models/gemma.py+++ b/unsloth/models/gemma.py@@ -11,6 +11,7 @@from .llama import *from .llama import _get_rope_theta, _LazyDeviceScratch, _PerDeviceRopeCache+from .._gc_passes import collect_garbagefrom ._utils import __version__from ._utils import move_to_device, per_layer_device, embedding_applies_scalefrom ._utils import refresh_moved_layer_devices@@ -406,9 +407,5 @@ class FastGemmaModel(FastLlamaModel):if not hasattr(module, "variance_epsilon"):module.variance_epsilon = module.eps # Gemma doesn't use variance_epsilon- import gc-- for _ in range(3):- gc.collect()- clean_gpu_cache()+ collect_garbage(after = clean_gpu_cache)return model, tokenizerdiff --git a/unsloth/models/gemma2.py b/unsloth/models/gemma2.pyindex 42ba79055af..3b435404094 100644--- a/unsloth/models/gemma2.py+++ b/unsloth/models/gemma2.py@@ -18,6 +18,7 @@ from .llama import (_gqa_decode_values,_LazyDeviceScratch,)+from .._gc_passes import collect_garbagefrom ._utils import __version__from ._utils import move_to_device, per_layer_device, refresh_moved_layer_devices, DEVICE_TYPEfrom unsloth_zoo.utils import _get_dtype, Version@@ -701,9 +702,5 @@ class FastGemma2Model(FastLlamaModel):if not hasattr(module, "variance_epsilon"):module.variance_epsilon = module.eps # Gemma doesn't use variance_epsilon- import gc-- for _ in range(3):- gc.collect()- clean_gpu_cache()+ collect_garbage(after = clean_gpu_cache)return model, tokenizerdiff --git a/unsloth/models/granite.py b/unsloth/models/granite.pyindex ccbc49ad37e..9fdfe9a0be4 100644--- a/unsloth/models/granite.py+++ b/unsloth/models/granite.py@@ -11,6 +11,7 @@from .llama import *import os+from .._gc_passes import collect_garbagefrom ._utils import __version__from ._utils import move_to_device, per_layer_device, refresh_moved_layer_devicesfrom unsloth_zoo.utils import _get_dtype, Version@@ -609,9 +610,5 @@ class FastGraniteModel(FastLlamaModel):module.short_cos_cached = module.short_cos_cached.to(correct_dtype)module.short_sin_cached = module.short_sin_cached.to(correct_dtype)- import gc-- for _ in range(3):- gc.collect()- clean_gpu_cache()+ collect_garbage(after = clean_gpu_cache)return model, tokenizerdiff --git a/unsloth/models/llama.py b/unsloth/models/llama.pyindex 536459b8fe5..54238f11501 100644--- a/unsloth/models/llama.py+++ b/unsloth/models/llama.py@@ -13,7 +13,6 @@# limitations under the License.import torch-import gcimport contextlibimport mathimport functools@@ -118,6 +117,7 @@ try:except ImportError:# Older unsloth_zoo: fall back to reading the config fields directly.detect_logit_transforms = None+from .._gc_passes import collect_garbagefrom ..device_type import (xpu_keeps_explicit_bf16,xpu_vllm_refuses_bf16,@@ -5100,17 +5100,13 @@ class FastLlamaModel:print("Unsloth: Offloading input_embeddings to disk to save VRAM")offload_input_embeddings(model, temporary_location)- for _ in range(3):- gc.collect()- clean_gpu_cache()+ collect_garbage(after = clean_gpu_cache)if train_lm_head:print("Unsloth: Offloading output_embeddings to disk to save VRAM")offload_output_embeddings(model, temporary_location)- for _ in range(3):- gc.collect()- clean_gpu_cache()+ collect_garbage(after = clean_gpu_cache)from .lora_init import fast_lora_init, record_fast_pissa@@ -5227,9 +5223,7 @@ class FastLlamaModel:# Prevent Transformers Trainer from auto-wrapping Unsloth LoRA models in DP._mark_unsloth_disable_data_parallel(model)- for _ in range(3):- gc.collect()- clean_gpu_cache()+ collect_garbage(after = clean_gpu_cache)patch_peft_fast_inference(model)@@ -5474,9 +5468,7 @@ class FastLlamaModel:if hasattr(internal_model, "_saved_temp_tokenizer"):internal_model._saved_temp_tokenizer.padding_side = "right"- for _ in range(3):- gc.collect()- clean_gpu_cache()+ collect_garbage(after = clean_gpu_cache)patch_peft_fast_inference(model)diff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex 1c8ffb1cdfe..71a07651f18 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -136,21 +136,25 @@ def _strip_vllm_weight_loads(function, source, trainer_file):return sourceif trainer_file == "online_dpo_trainer" and function in _ONLINE_DPO_VLLM_SYNC_FUNCTIONS:return source- source = re.sub(- r"(\n[\s]{4,}).+?model_executor\.driver_worker.+?\n",- r"\n\1pass\n",- source,- )- source = re.sub(- r"(\n[\s]{4,}).+?load_weights\(.+?\n",- r"\n\1pass\n",- source,- )- source = re.sub(- r"\.state_dict\(\)",- r"",- source,- )+ # Each pattern needs its literal; the line-anchored scans are slow on long sources.+ if "model_executor.driver_worker" in source:+ source = re.sub(+ r"(\n[\s]{4,}).+?model_executor\.driver_worker.+?\n",+ r"\n\1pass\n",+ source,+ )+ if "load_weights(" in source:+ source = re.sub(+ r"(\n[\s]{4,}).+?load_weights\(.+?\n",+ r"\n\1pass\n",+ source,+ )+ if ".state_dict()" in source:+ source = re.sub(+ r"\.state_dict\(\)",+ r"",+ source,+ )return source@@ -2517,6 +2521,9 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):# TRL 0.26+: resolve thin wrappers (trl.trainer shims forwarding to trl.experimental) to their parent class, and only when that parent really lives in a trl.experimental module._trainer_resolved_module = None+ _trainer_src = _config_src = None+ _trainer_src_of = RLTrainer+ _config_src_of = RLConfigtry:_trainer_src = inspect.getsource(RLTrainer)_trainer_module = inspect.getmodule(RLTrainer)@@ -2556,8 +2563,13 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):except Exception:pass- old_RLTrainer_source = inspect.getsource(RLTrainer)- old_RLConfig_source = inspect.getsource(RLConfig)+ # Reuse the probe reads above unless they failed or the class was swapped for its parent.+ if _trainer_src is None or RLTrainer is not _trainer_src_of:+ _trainer_src = inspect.getsource(RLTrainer)+ old_RLTrainer_source = _trainer_src+ if _config_src is None or RLConfig is not _config_src_of:+ _config_src = inspect.getsource(RLConfig)+ old_RLConfig_source = _config_srcif _trainer_resolved_module is not None:all_imports = dir(_trainer_resolved_module)@@ -3683,7 +3695,12 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):)RLTrainer_extras = patch_functions(- RLTrainer, trainer_file, RLTrainer_name, all_imports, imports+ RLTrainer,+ trainer_file,+ RLTrainer_name,+ all_imports,+ imports,+ RLTrainer_source = old_RLTrainer_source,)if RLTrainer_extras is None:RLTrainer_extras = f"_Unsloth{RLTrainer_name} = {RLTrainer_name}"@@ -4100,7 +4117,14 @@ def _allow_list_train_dataset(function, source, trainer_file):return source-def patch_functions(RLTrainer, trainer_file, RLTrainer_name, all_imports, imports):+def patch_functions(+ RLTrainer,+ trainer_file,+ RLTrainer_name,+ all_imports,+ imports,+ RLTrainer_source = None,+):init = inspect.getsource(RLTrainer.__init__)old_init = init@@ -4289,7 +4313,8 @@ def patch_functions(RLTrainer, trainer_file, RLTrainer_name, all_imports, importinit = init.replace(vllm_part, new_vllm_part)functions = dir(RLTrainer)- RLTrainer_source = inspect.getsource(RLTrainer)+ if RLTrainer_source is None:+ RLTrainer_source = inspect.getsource(RLTrainer)functions = [x for x in functions if f"def {x}" in RLTrainer_source]changed = {diff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex 4277cd36913..1cb6f3501db 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -391,6 +391,7 @@ try:from huggingface_hub.utils import get_tokenexcept:from huggingface_hub.utils._token import get_token+from .._gc_passes import collect_garbagefrom ..device_type import (xpu_keeps_explicit_bf16,xpu_vllm_refuses_bf16,@@ -4518,9 +4519,7 @@ class FastBaseModel:for jj, (name, module) in enumerate(model.named_modules()):exec(custom_datatype)cast_mixed_linear_inputs(model, torch_dtype)- for _ in range(3):- gc.collect()- clean_gpu_cache()+ collect_garbage(after = clean_gpu_cache)tokenizer_name = model_name if tokenizer_name is None else tokenizer_name# The loader resolves this (caller's adapter repo vs resolved base model); the fallback below covers a direct call.@@ -4898,9 +4897,7 @@ class FastBaseModel:tokenizer = tokenizer,float32_mixed_precision = float32_mixed_precision,)- for _ in range(3):- gc.collect()- clean_gpu_cache()+ collect_garbage(after = clean_gpu_cache)# Saving restores sentencepiece assets from the repo name alone, which carries no branch. Stamped here, not per processor branch, so a fallback cannot lose it._mark_loaded_revision(tokenizer, _tokenizer_revision)model = _mark_forced_float32(model, do_forced_float32)@@ -5203,9 +5200,7 @@ class FastBaseModel:"Unsloth: LoRA finetuning for Llama 3.2 aka mllama models is not supported with fast_inference!")- for _ in range(3):- gc.collect()- clean_gpu_cache()+ collect_garbage(after = clean_gpu_cache)max_seq_length = model.max_seq_length# Passing loftq_config = None gives an error.loftq_config = validate_loftq_config(@@ -5428,9 +5423,7 @@ class FastBaseModel:use_gradient_checkpointing = use_gradient_checkpointing,)skip_checkpointing(model, checkpoint_skip_layers)- for _ in range(3):- gc.collect()- clean_gpu_cache()+ collect_garbage(after = clean_gpu_cache)patch_saving_functions(model, vision = True)patch_peft_fast_inference(model)@@ -5609,9 +5602,7 @@ class FastBaseModel:# Prevent Transformers Trainer from auto-wrapping Unsloth LoRA models in DP._mark_unsloth_disable_data_parallel(model, disable = not full_finetuning)- for _ in range(3):- gc.collect()- clean_gpu_cache()+ collect_garbage(after = clean_gpu_cache)model.for_training = functools.partial(FastBaseModel.for_training, model)model.for_inference = functools.partial(FastBaseModel.for_inference, model)m = model