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 importing unsloth.models._utils twice in a process survive (#9793)
Daniel Hanb372132b9e82
diff --git a/tests/vllm_compat/test_extended_module_imports.py b/tests/vllm_compat/test_extended_module_imports.pyindex bf974c9d3fc..314667f3dc9 100644--- a/tests/vllm_compat/test_extended_module_imports.py+++ b/tests/vllm_compat/test_extended_module_imports.py@@ -165,11 +165,17 @@ def test_unsloth_core_module_imports_under_spoof(modname: str):sys.modules.pop(modname, None)try:importlib.import_module(modname)- except OSError as e:- # "could not get source code": editable-install + frozen sub-import- # quirk, not symbol drift. Skip rather than false-fail.- pytest.skip(f"{modname} env issue: {e!s}")except Exception as e:+ # OSError("could not get source code") used to be skipped here as an+ # "editable-install + frozen sub-import quirk". It was not an+ # environment quirk: popping the module and importing it again is+ # exactly the second import that unsloth/models/_utils.py could not+ # survive, because it read the source of BitsAndBytesConfig.__init__+ # and then replaced that __init__ with an exec'd function having no+ # source. The skip meant _utils, loader, loader_utils and+ # rl_replacements were silently uncovered here, and the bug it hid+ # broke any test file that imported unsloth after this one ran in the+ # same worker. Failing is the point of the case, so it fails now.pytest.fail(f"{modname} failed to import under CUDA spoof: " f"{type(e).__name__}: {str(e)[:300]}")@@ -214,10 +220,11 @@ def test_unsloth_rl_replacements_dispatch_populated():except Exception as e:pytest.skip(f"`import unsloth` failed under spoof: {e}")sys.modules.pop("unsloth.models.rl_replacements", None)- try:- rl = importlib.import_module("unsloth.models.rl_replacements")- except OSError as e:- pytest.skip(f"env issue importing rl_replacements: {e!s}")+ # Not wrapped in a skip-on-OSError any more: see the note in+ # test_unsloth_core_module_imports_under_spoof. The OSError that used to be+ # skipped here was unsloth's re-import bug, not the environment, and+ # skipping it left this case asserting nothing.+ rl = importlib.import_module("unsloth.models.rl_replacements")funcs = getattr(rl, "RL_FUNCTIONS", None)if funcs is None:pytest.skip("RL_FUNCTIONS attribute not present (architecture changed; check)")diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 15815fbe988..ab2d041674b 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -2804,21 +2804,60 @@ from transformers.utils.quantization_config import (QuantizationMethod,)-BitsAndBytesConfig__init__ = inspect.getsource(BitsAndBytesConfig.__init__)-BitsAndBytesConfig__init__ = re.sub(- r"if[\s]{1,}kwargs\:[\s]{1,}.+?\n",- "",- BitsAndBytesConfig__init__,- flags = re.MULTILINE,-)-BitsAndBytesConfig__init__ = BitsAndBytesConfig__init__.split("\n")-length_spaces = len(re.match(r"[\s]{1,}", BitsAndBytesConfig__init__[0]).group(0))-BitsAndBytesConfig__init__ = "\n".join(x[length_spaces:] for x in BitsAndBytesConfig__init__)-BitsAndBytesConfig__init__ = BitsAndBytesConfig__init__.replace(- "__init__",- "_BitsAndBytesConfig__init__",-)-exec(BitsAndBytesConfig__init__, globals())+# Importing this module twice in one process must not raise.+#+# This block reads BitsAndBytesConfig.__init__'s source, rewrites it, and (at+# the bottom of the section) installs the result over the original. The+# replacement is built with exec(), so it has no file on disk. On a SECOND+# import, inspect.getsource() is therefore handed our own exec'd function,+# linecache finds nothing to read for it, and the import dies with+#+# OSError: could not get source code+#+# taking every later `from unsloth...` in that process with it. Anything that+# drops unsloth from sys.modules and imports it again reaches this: on a clean+# tree, `pytest tests/vllm_compat/test_extended_module_imports.py+# tests/python/test_vision_lora_targeting.py` is 30 failures, and it is only+# luck of the xdist scheduling that a full run does not usually pair them.+#+# The patch is idempotent by nature -- when it has already run, the wanted end+# state is the one already in place -- so recognising our own handiwork and+# standing down is the fix. The marker is set on the function rather than+# tracked in a module global because a re-import gets fresh globals but the same+# transformers class object.+_bnb_init = BitsAndBytesConfig.__init__++if getattr(_bnb_init, "__unsloth_patched__", False):+ # Already installed by an earlier import of this module. Keep it.+ _BitsAndBytesConfig__init__ = _bnb_init+else:+ try:+ BitsAndBytesConfig__init__ = inspect.getsource(_bnb_init)+ except (OSError, TypeError):+ # Someone else replaced __init__ with something sourceless. Leaving+ # theirs alone is strictly better than failing the import.+ BitsAndBytesConfig__init__ = None++ if BitsAndBytesConfig__init__ is None:+ _BitsAndBytesConfig__init__ = _bnb_init+ else:+ BitsAndBytesConfig__init__ = re.sub(+ r"if[\s]{1,}kwargs\:[\s]{1,}.+?\n",+ "",+ BitsAndBytesConfig__init__,+ flags = re.MULTILINE,+ )+ BitsAndBytesConfig__init__ = BitsAndBytesConfig__init__.split("\n")+ length_spaces = len(re.match(r"[\s]{1,}", BitsAndBytesConfig__init__[0]).group(0))+ BitsAndBytesConfig__init__ = "\n".join(+ x[length_spaces:] for x in BitsAndBytesConfig__init__+ )+ BitsAndBytesConfig__init__ = BitsAndBytesConfig__init__.replace(+ "__init__",+ "_BitsAndBytesConfig__init__",+ )+ exec(BitsAndBytesConfig__init__, globals())+ _BitsAndBytesConfig__init__.__unsloth_patched__ = Trueif DEVICE_COUNT == 1 and int(os.environ.get("WORLD_SIZE", "1")) <= 1:from accelerate.utils.dataclasses import DistributedType