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
Never import sentencepiece on Windows (#10593)
Daniel Han7a87857ae439
diff --git a/studio/backend/main.py b/studio/backend/main.pyindex f0565217d97..f651f8399c3 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -235,6 +235,16 @@ if _STUDIO_ROOT_RESOLVED != _LEGACY_STUDIO_ROOT:# lazy submodule imports and the DiffusionGemma runner don't trip the install guard.os.environ.setdefault("UNSLOTH_IS_PRESENT", "1")+# Same rule as unsloth/__init__.py, reached through Studio's own copy because this parent must+# not import unsloth: that runs unsloth/__init__.py, whose GPU branch pulls torch, Triton,+# transformers and the model stack into a long-lived process that exists to stay light, and can+# open a competing GPU context. Before anything imports transformers, which reads sentencepiece+# availability during its own import. UNSLOTH_DISABLE_SENTENCEPIECE=0 opts out.+from utils.sentencepiece_guard import disable_sentencepiece_on_windows as _no_sentencepiece++_no_sentencepiece()+del _no_sentencepiece+import hashlibimport ipaddressimport mimetypesdiff --git a/studio/backend/utils/native_path_leases.py b/studio/backend/utils/native_path_leases.pyindex 564cf4f1bc6..15ed307ca7a 100644--- a/studio/backend/utils/native_path_leases.py+++ b/studio/backend/utils/native_path_leases.py@@ -143,6 +143,19 @@ def run_without_native_path_secret(function_name, environment, *args = argsfor key, value in environment.items():os.environ[key] = value++ # Before the entrypoint module below, not after: a spawned child inherits no sys.modules, and+ # every worker here imports transformers (fast-path hooks, version activation) long before it+ # imports unsloth. A sentinel installed after that import leaves transformers saying+ # sentencepiece is available while importing it fails, which sends tokenizer loads into the+ # dummy-class path and its unguarded `import sentencepiece as spm`.+ try:+ from utils.sentencepiece_guard import disable_sentencepiece_on_windows+ disable_sentencepiece_on_windows()+ except Exception:+ pass++ if isinstance(target, str):target = getattr(importlib.import_module(target), function_name)return target(*args, **kwargs)diff --git a/studio/backend/utils/sentencepiece_guard.py b/studio/backend/utils/sentencepiece_guard.pynew file mode 100644index 00000000000..9c6ff25823a--- /dev/null+++ b/studio/backend/utils/sentencepiece_guard.py@@ -0,0 +1,60 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Studio's spelling of the Windows sentencepiece rule in unsloth/import_fixes.py.++Studio cannot reach that one by importing unsloth: that runs unsloth/__init__.py, whose GPU+branch pulls torch, Triton, transformers and the model stack into processes built to stay+light, and can open a competing GPU context. So the rule lives here, stdlib only, importable+at the very top of any Studio process. tests/test_windows_no_sentencepiece.py drives both+spellings through the same cases.+"""++import os+import sys++DISABLE_SENTENCEPIECE_VARIABLE = "UNSLOTH_DISABLE_SENTENCEPIECE"+_TRUTHY = frozenset({"1", "true", "yes", "on"})+_FALSY = frozenset({"0", "false", "no", "off"})+++def sentencepiece_should_be_disabled():+ """Windows by default, every other platform only when asked.++ An unrecognised value falls back to the platform default rather than raising: this runs at+ the top of a process, where a typo in an environment variable must not be fatal.+ """+ value = (os.environ.get(DISABLE_SENTENCEPIECE_VARIABLE) or "").strip().lower()+ if value in _TRUTHY:+ return True+ if value in _FALSY:+ return False+ return sys.platform == "win32"+++def disable_sentencepiece_on_windows():+ """Make ``import sentencepiece`` fail the way an uninstalled package does.++ On Windows the compiled extension is never handed to the loader, so a code integrity+ policy has no file to refuse and the user gets no Bad Image dialog; a probe to find out+ whether this machine would refuse it is itself that dialog. A ``None`` entry is CPython's+ documented sentinel and makes the import raise ImportError, the ordinary "not installed"+ state.++ Must run before transformers is imported, which reads availability during its own import.+ Once transformers is in sys.modules this declines rather than installing a sentinel it has+ already contradicted. Returns True only when this call is what made it absent.+ """+ if not sentencepiece_should_be_disabled():+ return False+ if "sentencepiece" in sys.modules:+ # Already imported by something earlier, or already disabled by an earlier call.+ # Replacing a live module would break whoever is holding it.+ return sys.modules["sentencepiece"] is None+ if "transformers" in sys.modules:+ # Too late, and installing it anyway would be worse than doing nothing: transformers+ # has already cached "installed", so the sentinel would only make the two disagree and+ # a tokenizer that loads today would start raising ModuleNotFoundError.+ return False+ sys.modules["sentencepiece"] = None+ return Truediff --git a/tests/test_windows_no_sentencepiece.py b/tests/test_windows_no_sentencepiece.pynew file mode 100644index 00000000000..c4d09cef1a4--- /dev/null+++ b/tests/test_windows_no_sentencepiece.py@@ -0,0 +1,334 @@+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""On Windows, sentencepiece is never imported.++The point is not that transformers reports it unavailable, it is that the compiled extension+is never handed to the Windows loader. A code integrity policy refuses by reputation, one file+at a time, and the refusal is a Bad Image dialog: any probe that asks whether this machine+would refuse the file has already produced the thing being avoided.+"""++import importlib.util+import os+import re+import subprocess+import sys+import textwrap+import types+from pathlib import Path++import pytest++REPO = Path(__file__).resolve().parents[1]+if str(REPO) not in sys.path:+ sys.path.insert(0, str(REPO))++from unsloth.import_fixes import ( # noqa: E402+ DISABLE_SENTENCEPIECE_VARIABLE,+ disable_sentencepiece_on_windows,+ sentencepiece_should_be_disabled,+)++BACKEND = REPO / "studio" / "backend"+MAIN = BACKEND / "main.py"+GUARD = BACKEND / "utils" / "sentencepiece_guard.py"+++def _studio_guard():+ """Studio's copy, loaded by path so the test needs nothing else from the backend tree."""+ spec = importlib.util.spec_from_file_location("studio_sentencepiece_guard", GUARD)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module++[email protected](autouse = True)+def _clean(monkeypatch):+ monkeypatch.delenv(DISABLE_SENTENCEPIECE_VARIABLE, raising = False)+ # The rule declines once transformers is imported, and the test session has imported it.+ # Removed here so each test states its own starting point; the one test that wants it+ # present puts it back.+ monkeypatch.delitem(sys.modules, "transformers", raising = False)+ yield+++ "platform,expected", [("win32", True), ("linux", False), ("darwin", False)]+)+def test_the_default_is_windows_only(platform, expected, monkeypatch):+ """WSL reports linux and is deliberately in the second group: App Control does not enforce+ over ELF binaries in the guest, so there is no extension for it to refuse there."""+ monkeypatch.setattr(sys, "platform", platform)+ assert sentencepiece_should_be_disabled() is expected++[email protected]("value", ["1", "true", "YES", " On ", "TRUE"])+def test_a_truthy_flag_disables_on_any_platform(value, monkeypatch):+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.setenv(DISABLE_SENTENCEPIECE_VARIABLE, value)+ assert sentencepiece_should_be_disabled() is True++[email protected]("value", ["0", "false", "NO", " off "])+def test_a_falsy_flag_opts_windows_back_in(value, monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setenv(DISABLE_SENTENCEPIECE_VARIABLE, value)+ assert sentencepiece_should_be_disabled() is False++[email protected]("value", ["maybe", "2", "", " ", "disable"])+def test_an_unrecognised_value_is_the_platform_default(value, monkeypatch):+ """This runs at the top of the process. A typo in an environment variable must not be+ fatal, and must not silently mean the opposite of what was typed."""+ monkeypatch.setenv(DISABLE_SENTENCEPIECE_VARIABLE, value)+ monkeypatch.setattr(sys, "platform", "win32")+ assert sentencepiece_should_be_disabled() is True+ monkeypatch.setattr(sys, "platform", "linux")+ assert sentencepiece_should_be_disabled() is False+++def test_it_installs_the_sentinel_and_the_import_then_fails_like_an_absent_package(monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.delitem(sys.modules, "sentencepiece", raising = False)++ assert disable_sentencepiece_on_windows() is True+ assert sys.modules["sentencepiece"] is None++ with pytest.raises(ImportError):+ # ModuleNotFoundError, which is an ImportError, so every `try/except ImportError`+ # already in transformers handles it as "not installed".+ import sentencepiece # noqa: F401+++def test_nothing_happens_off_windows(monkeypatch):+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.delitem(sys.modules, "sentencepiece", raising = False)+ assert disable_sentencepiece_on_windows() is False+ assert "sentencepiece" not in sys.modules+++def test_an_already_imported_sentencepiece_is_left_alone(monkeypatch):+ """Replacing a live module would break whoever is holding a reference to it, and by this+ point the extension has already loaded, so there is nothing left to prevent."""+ sentinel = object()+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setitem(sys.modules, "sentencepiece", sentinel)+ assert disable_sentencepiece_on_windows() is False+ assert sys.modules["sentencepiece"] is sentinel+++def test_it_declines_once_transformers_is_imported(monkeypatch):+ """Installing it late is worse than not installing it at all.++ transformers reads availability from find_spec during its own import and caches it, so a+ sentinel added afterwards only makes the two disagree: it reports the package available+ and the import then fails. Measured on 4.57.6, unsloth/gemma-2-2b-it loads with the rule+ applied in time and without the rule at all, and raises ModuleNotFoundError with the rule+ applied afterwards. Whoever imported transformers first keeps the ordinary behaviour.+ """+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.delitem(sys.modules, "sentencepiece", raising = False)+ monkeypatch.setitem(sys.modules, "transformers", types.ModuleType("transformers"))++ assert disable_sentencepiece_on_windows() is False+ assert "sentencepiece" not in sys.modules++ studio = _studio_guard()+ monkeypatch.setattr(+ studio,+ "sys",+ types.SimpleNamespace(platform = "win32", modules = {"transformers": object()}),+ )+ assert studio.disable_sentencepiece_on_windows() is False+ assert "sentencepiece" not in studio.sys.modules+++def test_a_sentinel_installed_in_time_survives_a_later_transformers_import(monkeypatch):+ """The late check must not undo the ordinary case, where the rule ran first and+ transformers was imported after it."""+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setitem(sys.modules, "sentencepiece", None)+ monkeypatch.setitem(sys.modules, "transformers", types.ModuleType("transformers"))+ assert disable_sentencepiece_on_windows() is True+ assert sys.modules["sentencepiece"] is None+++def test_calling_it_twice_is_stable(monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.delitem(sys.modules, "sentencepiece", raising = False)+ assert disable_sentencepiece_on_windows() is True+ assert disable_sentencepiece_on_windows() is True+ assert sys.modules["sentencepiece"] is None+++def test_the_studio_parent_applies_the_same_rule_without_importing_unsloth():+ """Studio's parent must not import unsloth: that runs unsloth/__init__.py, whose GPU branch+ pulls torch, Triton, transformers and the model stack into a long-lived process built to+ stay light, and can open a competing GPU context. So it calls Studio's own copy instead."""+ source = MAIN.read_text(encoding = "utf-8")+ assert "from unsloth.import_fixes import" not in source+ assert "import unsloth\n" not in source++ marker = source.index('os.environ.setdefault("UNSLOTH_IS_PRESENT", "1")')+ guard = source.index("from utils.sentencepiece_guard import")+ assert guard > marker++ # Real import statements only. Matching the bare word finds the surrounding comments,+ # which say nothing about execution order.+ imports = [+ m.start()+ for m in re.finditer(r"^\s*(?:import transformers|from transformers)", source, re.M)+ ]+ assert not imports or guard < min(imports), (+ "the sentinel must be installed before anything imports transformers, which reads "+ "sentencepiece availability during its own import"+ )+++ "platform,env,expect_disabled",+ [+ ("win32", None, True),+ ("win32", "0", False),+ ("linux", None, False),+ ("linux", "1", True),+ ],+)+def test_the_two_spellings_agree(platform, env, expect_disabled, monkeypatch):+ """The package helper and Studio's copy, driven through the same cases. Compared by+ behaviour rather than by source text, which would pass on two implementations that had+ quietly stopped agreeing."""+ monkeypatch.setattr(sys, "platform", platform)+ if env is None:+ monkeypatch.delenv(DISABLE_SENTENCEPIECE_VARIABLE, raising = False)+ else:+ monkeypatch.setenv(DISABLE_SENTENCEPIECE_VARIABLE, env)+ assert sentencepiece_should_be_disabled() is expect_disabled++ studio = _studio_guard()+ monkeypatch.setattr(studio.sys, "platform", platform)+ assert studio.DISABLE_SENTENCEPIECE_VARIABLE == DISABLE_SENTENCEPIECE_VARIABLE+ assert studio.sentencepiece_should_be_disabled() is expect_disabled++ # A stub sys, because the real one already has sentencepiece imported by the test session,+ # and the rule correctly declines to replace a live module. Running it against the real+ # sys.modules would test the fixture, not the rule.+ monkeypatch.setattr(studio, "sys", types.SimpleNamespace(platform = platform, modules = {}))+ assert studio.disable_sentencepiece_on_windows() is expect_disabled+ assert (studio.sys.modules.get("sentencepiece", "absent") is None) is expect_disabled+++def _run_shared_entrypoint(tmp_path, env):+ """Drive the workers' shared spawn entrypoint against a stand-in worker module.++ The stand-in records, at its own module scope, what the interpreter looked like when the+ entrypoint imported it. That is the moment under test: the real worker modules import+ transformers from there onwards.+ """+ (tmp_path / "sentencepiece_entrypoint_probe.py").write_text(+ textwrap.dedent(+ """+ import os, sys+ AT_IMPORT = sys.modules.get("sentencepiece", "absent") is None+ ENV = os.environ.get("UNSLOTH_STUDIO_SP_PROBE")++ def report():+ print("SENTINEL AT IMPORT", AT_IMPORT)+ print("ENV APPLIED", ENV)+ """+ ),+ encoding = "utf-8",+ )+ program = textwrap.dedent(+ f"""+ import sys+ sys.path.insert(0, {str(BACKEND)!r})+ sys.path.insert(0, {str(tmp_path)!r})+ from utils.native_path_leases import run_without_native_path_secret+ assert "sentencepiece" not in sys.modules, sys.modules["sentencepiece"]+ run_without_native_path_secret(+ "sentencepiece_entrypoint_probe", "report", {{"UNSLOTH_STUDIO_SP_PROBE": "yes"}}+ )+ """+ )+ return subprocess.run(+ [sys.executable, "-c", program],+ capture_output = True,+ text = True,+ timeout = 300,+ env = env,+ )+++def test_the_shared_worker_entrypoint_installs_it_before_the_worker_module(tmp_path):+ """Every Studio worker is a spawned interpreter that inherits no sys.modules, and each one+ imports transformers (version activation, fast-path hooks) long before it imports unsloth.+ A sentinel installed after that leaves transformers reporting sentencepiece available while+ importing it fails, which breaks tokenizer loads that work either without the rule or with+ it applied in time. So the shared entrypoint installs it before the worker module."""+ out = _run_shared_entrypoint(tmp_path, {**os.environ, DISABLE_SENTENCEPIECE_VARIABLE: "1"})+ assert "SENTINEL AT IMPORT True" in out.stdout, (out.stdout, out.stderr[-2000:])+ # The captured cache environment still lands first: the rule reads the environment.+ assert "ENV APPLIED yes" in out.stdout, (out.stdout, out.stderr[-2000:])+++def test_the_shared_worker_entrypoint_leaves_it_alone_when_not_asked(tmp_path):+ """The same entrypoint where the rule does not apply: off Windows and without the flag, a+ worker still gets the real package."""+ env = {k: v for k, v in os.environ.items() if k != DISABLE_SENTENCEPIECE_VARIABLE}+ out = _run_shared_entrypoint(tmp_path, env)+ expected = "SENTINEL AT IMPORT " + str(sys.platform == "win32")+ assert expected in out.stdout, (out.stdout, out.stderr[-2000:])+++ __import__("importlib.util", fromlist = ["util"]).find_spec("transformers") is None,+ reason = "transformers is not installed",+)+def test_transformers_reports_it_absent_and_never_loads_the_extension():+ """The whole point, end to end, in a clean interpreter.++ transformers derives availability from find_spec, which finds the sentinel and answers+ False on its own, so nothing here monkey patches is_sentencepiece_available. That matters:+ a flag that lies while the package is still importable is a different and worse state, and+ on 4.52 through 4.57 it sends tokenizer_class_from_name into a fallback that imports the+ slow tokenizer module and reaches its unguarded `import sentencepiece as spm`.+ """+ program = textwrap.dedent(+ """+ import sys, warnings+ warnings.filterwarnings("ignore")+ sys.modules["sentencepiece"] = None+ import transformers+ from transformers.utils import import_utils+ loaded = [m for m in sys.modules+ if m == "sentencepiece" or m.startswith("sentencepiece.")]+ alive = [m for m in loaded if sys.modules[m] is not None]+ print("AVAILABLE", import_utils.is_sentencepiece_available())+ print("ALIVE", alive)+ """+ )+ out = subprocess.run(+ [sys.executable, "-c", program],+ capture_output = True,+ text = True,+ timeout = 600,+ )+ assert "AVAILABLE False" in out.stdout, (out.stdout, out.stderr[-2000:])+ assert "ALIVE []" in out.stdout, (+ "the compiled extension must never be loaded",+ out.stdout,+ out.stderr[-2000:],+ )diff --git a/unsloth/__init__.py b/unsloth/__init__.pyindex e1956b82c16..5c04c3a3d63 100644--- a/unsloth/__init__.py+++ b/unsloth/__init__.py@@ -16,6 +16,17 @@ import os, importlib.util, platform, sysos.environ["UNSLOTH_IS_PRESENT"] = "1"+# Before transformers, which reads sentencepiece availability during its own import. On Windows+# the extension is never imported at all: a code integrity policy can refuse it by reputation,+# and any probe to find out whether this machine will is itself the refusal the user sees. See+# import_fixes.disable_sentencepiece_on_windows; UNSLOTH_DISABLE_SENTENCEPIECE=0 opts out.+try:+ from .import_fixes import disable_sentencepiece_on_windows as _no_sentencepiece+ _no_sentencepiece()+ del _no_sentencepiece+except Exception:+ pass+# Transformers 4.x imports TensorFlow / Flax merely because they are installed (processing_utils# -> image_transforms); it reads these variables once at its own import, so they have to land# first. An explicit opt-in still wins, and 5.x ignores all of this.diff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.pyindex 8cf8b8d175b..120dce37047 100644--- a/unsloth/import_fixes.py+++ b/unsloth/import_fixes.py@@ -6269,3 +6269,79 @@ def fix_dill_module_by_value_pickling():"site-packages tree.")return True+++# Windows refuses sentencepiece's compiled extension on some machines. Smart App Control and+# App Control for Business judge by reputation, one file at a time, so a freshly published+# unsigned .pyd can be refused on a machine where everything else loads. The user sees a Bad+# Image dialog naming the file, and transformers keeps saying the package is available,+# because it decides that from find_spec and installed metadata and loads nothing.+#+# There is no way to ask whether this machine will refuse the file that does not involve+# handing the file to the loader, which is the thing being avoided: a probe IS the dialog. So+# on Windows the extension is simply never imported.+DISABLE_SENTENCEPIECE_VARIABLE = "UNSLOTH_DISABLE_SENTENCEPIECE"+_SENTENCEPIECE_TRUTHY = frozenset({"1", "true", "yes", "on"})+_SENTENCEPIECE_FALSY = frozenset({"0", "false", "no", "off"})+++def sentencepiece_should_be_disabled():+ """Whether to make sentencepiece absent in this process.++ Windows by default; every other platform only when asked. WSL reports ``linux`` and is+ treated as the Linux box it is, since App Control does not enforce over ELF binaries in+ the guest.++ An unrecognised value falls back to the platform default rather than raising. This runs at+ the very top of the process, where a typo in an environment variable must not be fatal.+ """+ value = (os.environ.get(DISABLE_SENTENCEPIECE_VARIABLE) or "").strip().lower()+ if value in _SENTENCEPIECE_TRUTHY:+ return True+ if value in _SENTENCEPIECE_FALSY:+ return False+ return sys.platform == "win32"+++def disable_sentencepiece_on_windows():+ """Make ``import sentencepiece`` fail the way an uninstalled package does.++ A ``None`` entry in ``sys.modules`` is CPython's documented sentinel for this: the import+ raises ``ModuleNotFoundError`` (an ``ImportError``, so every ``try/except ImportError`` in+ transformers already handles it) and nothing on disk is opened, so the compiled extension+ is never handed to the Windows loader and there is no dialog to see.++ Deliberately NOT a monkey patch of ``is_sentencepiece_available``. transformers derives+ that from ``find_spec``, which now finds the sentinel and answers False on its own, so the+ process is in the ordinary "sentencepiece was never installed" configuration rather than a+ state where the flag and the package disagree. That distinction is load bearing: on+ transformers 4.52 through 4.57 a flag that lies sends ``tokenizer_class_from_name`` into a+ fallback that imports the slow tokenizer module and reaches its unguarded+ ``import sentencepiece as spm``, which is the loader error this is meant to prevent.++ Must run before transformers is imported, since transformers reads availability during+ its own import. Once transformers is in sys.modules this declines rather than installing a+ sentinel it has already contradicted. Returns True only when this call is what made it+ absent.+ """+ if not sentencepiece_should_be_disabled():+ return False+ if "sentencepiece" in sys.modules:+ # Already imported by something earlier, or already disabled by an earlier call.+ # Replacing a live module here would break whoever is holding it.+ return sys.modules["sentencepiece"] is None+ if "transformers" in sys.modules:+ # Too late, and installing it anyway would be worse than doing nothing. transformers+ # has already read availability from find_spec and cached "installed", so the sentinel+ # would only produce the disagreement described above, and a tokenizer that loads+ # today would start raising ModuleNotFoundError. Whoever imported transformers first+ # keeps the ordinary behaviour.+ return False+ sys.modules["sentencepiece"] = None+ if UNSLOTH_ENABLE_LOGGING:+ logger.info(+ "Unsloth: sentencepiece is not imported on Windows, so a code integrity policy "+ "cannot refuse its extension. Models needing it will say so. Set "+ f"{DISABLE_SENTENCEPIECE_VARIABLE}=0 to import it again."+ )+ return True