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.

Parse the downloaded model mapper instead of exec'ing it (#9777)

Daniel Han8e3dd63bfcc4
diff --git a/.github/workflows/security-audit.yml b/.github/workflows/security-audit.yml
index fff0c639312..c3a493192fd 100644
--- a/.github/workflows/security-audit.yml
+++ b/.github/workflows/security-audit.yml
@@ -76,6 +76,16 @@ on:
- 'scripts/scan_packages.py'
- 'scripts/scan_packages_baseline.json'
- 'tests/security/**'
+ # The production code the security suites protect. Without these, a PR touching
+ # only `loader_utils.py` skipped this job entirely - the always-running light
+ # workflow ignores those three suites - so the tests ran for the first time on
+ # the push event, after the regression had already merged.
+ - 'unsloth/models/loader_utils.py'
+ - 'unsloth/models/mapper.py'
+ - 'unsloth/models/_custom_dtype.py'
+ - 'unsloth/models/loader.py'
+ - 'unsloth/models/vision.py'
+ - 'unsloth/models/_utils.py'
- '.github/workflows/security-audit.yml'
push:
branches: [main]
diff --git a/.github/workflows/workflow-trigger-lint.yml b/.github/workflows/workflow-trigger-lint.yml
index 42adcc96d72..8ede082a5b3 100644
--- a/.github/workflows/workflow-trigger-lint.yml
+++ b/.github/workflows/workflow-trigger-lint.yml
@@ -164,5 +164,96 @@ jobs:
tests/studio/test_windows_small_checks_stay_on_their_image.py \
tests/studio/test_windows_ui_lanes_are_isolated.py \
tests/studio/test_workflow_guards_run_unfiltered.py \
- tests/security
+ tests/security \
+ --ignore=tests/security/test_custom_dtype_no_eval.py \
+ --ignore=tests/security/test_custom_dtype_wire_format.py \
+ --ignore=tests/security/test_mapper_probe_no_exec.py \
+ --ignore=tests/security/test_inherited_custom_dtype_is_neutralized.py
+
+ # The four security suites the job above has to --ignore. That job installs four
+ # packages on purpose and these import torch and transformers, so they were
+ # excluded there and named by no other job: a repository-wide search of workflow
+ # pytest commands finds nothing else running them. They were therefore not running
+ # in CI at all, which makes a regression in the hardening they cover mergeable
+ # behind a green tick.
+ #
+ # In THIS workflow rather than security-audit.yml, which is where the job first
+ # landed. `tests/studio/test_short_job_absorption.py` states the rule: the security
+ # suites run here now, and a second runner for the same work in security-audit.yml
+ # is the duplication that rule exists to stop. This job is not that duplication -
+ # it runs the four files the other job cannot - and it inherits this workflow's
+ # unfiltered `on.pull_request`, which is a wider trigger than the one it had.
+ #
+ # CPU torch from the dedicated index. These suites never touch a device - they
+ # parse source, stub `requests` and read env vars - so the CPU wheel is the whole
+ # dependency and it keeps the job to a couple of minutes.
+ security-regression-suites:
+ name: security suites (torch-dependent)
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ steps:
+ - name: Harden runner (egress block)
+ uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0
+ with:
+ egress-policy: block
+ disable-sudo: true
+ # PyPI plus the CPU torch index, and GitHub for the checkout. These tests
+ # are network-free themselves; `tests/security/conftest.py` blocks sockets
+ # for the duration, so nothing here is dialed once pytest starts.
+ allowed-endpoints: >
+ api.github.com:443
+ github.com:443
+ codeload.github.com:443
+ objects.githubusercontent.com:443
+ pypi.org:443
+ files.pythonhosted.org:443
+ download.pytorch.org:443
+ download-r2.pytorch.org:443
+
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: '3.12'
+
+ - name: Install CPU torch + transformers
+ run: |
+ python -m pip install --quiet --upgrade pip
+ python -m pip install --quiet \
+ --index-url https://download.pytorch.org/whl/cpu \
+ --extra-index-url https://pypi.org/simple \
+ torch
+ # unsloth-zoo as well. All three suites import `unsloth.models`, which runs
+ # `unsloth/__init__.py`, and that raises ImportError outright when the zoo
+ # distribution is absent - `UNSLOTH_ZOO_DISABLE_GPU_INIT` does not bypass it.
+ # Without this the job would fail during collection rather than run.
+ # Triton as well. `unsloth/_gpu_init.py` imports it unconditionally, and the
+ # CPU torch wheel does not supply it - only the CUDA wheels pull
+ # pytorch-triton in. `UNSLOTH_ALLOW_CPU=1` bypasses device probing, not that
+ # import, so without this the job fails during collection and none of the
+ # four suites run. `consolidated-tests-ci.yml` installs it for the same
+ # reason on the same kind of runner.
+ python -m pip install --quiet transformers peft pytest unsloth-zoo triton
+
+ # Named one by one, not as a directory. The point of this job is those three
+ # files, and pyproject.toml sets testpaths = ["tests/security"], so a bare
+ # pytest here would silently widen into the suites the light runner already
+ # covers and the failure of THIS job would stop meaning what it says.
+ # `ubuntu-latest` has no accelerator, and every one of these files imports
+ # `unsloth.models`, which reaches `get_device_type()`. `UNSLOTH_ALLOW_CPU=1` is
+ # this repo's documented flag for importing on a driverless host, and it is what
+ # the rest of the CPU CI already uses. `UNSLOTH_ZOO_DISABLE_GPU_INIT` is not a
+ # substitute: it is a zoo flag, and against the released zoo this job installs it
+ # skips the init that binds `DEVICE_TYPE`, so `compiler.py` fails to import.
+ - name: Run the torch-dependent security suites
+ env:
+ UNSLOTH_ALLOW_CPU: '1'
+ run: |
+ python -m pytest -q \
+ tests/security/test_custom_dtype_no_eval.py \
+ tests/security/test_custom_dtype_wire_format.py \
+ tests/security/test_mapper_probe_no_exec.py \
+ tests/security/test_inherited_custom_dtype_is_neutralized.py
diff --git a/tests/security/test_custom_dtype_no_eval.py b/tests/security/test_custom_dtype_no_eval.py
new file mode 100644
index 00000000000..85bd1faa773
--- /dev/null
+++ b/tests/security/test_custom_dtype_no_eval.py
@@ -0,0 +1,149 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""`UNSLOTH_FORCE_CUSTOM_DTYPE` is a five field string, two of whose fields are code.
+
+`vision.py` used to `eval` the dtype fields and `exec` the code fields straight out of
+the environment. Two changes are pinned: the dtype fields go through a fixed table, and
+the code fields run only when this process set the variable. Defence in depth rather
+than a privilege boundary, but the code path is gone either way.
+"""
+
+import ast
+import pathlib
+import re
+
+import pytest
+import torch
+
+from unsloth.models._custom_dtype import (
+ DTYPE_ALIASES,
+ register_custom_dtype,
+ resolve_dtype,
+ trusted_custom_dtype,
+)
+
+
+LOADER = pathlib.Path(__import__("unsloth.models.loader", fromlist = ["x"]).__file__).read_text(
+ encoding = "utf-8"
+)
+
+
+def _shipped_values():
+ """Read out of loader.py rather than copied, so the test cannot drift."""
+ tree = ast.parse(LOADER)
+ values = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ function = node.func
+ if not (isinstance(function, ast.Name) and function.id == "register_custom_dtype"):
+ continue
+ try:
+ values.append(ast.literal_eval(node.args[0]))
+ except (ValueError, IndexError):
+ pytest.fail(f"register_custom_dtype called with a non-literal at line {node.lineno}")
+ return values
+
+
+def test_the_producers_were_all_found():
+ values = _shipped_values()
+ assert len(values) >= 6, values
+ assert LOADER.count('os.environ["UNSLOTH_FORCE_CUSTOM_DTYPE"] =') == 0, (
+ "a producer still writes the variable directly, so its code fields would be "
+ "dropped as untrusted"
+ )
+
+
+# --- every shipped dtype field must resolve ----------------------------------
+
+
[email protected]("value", _shipped_values())
+def test_shipped_dtype_fields_resolve(value):
+ """A false rejection here breaks loading one of the six model families."""
+ checker, dtype, bnb_compute_dtype, custom_datatype, execute_code = value.split(";", 4)
+ assert resolve_dtype(dtype) is None or isinstance(resolve_dtype(dtype), torch.dtype)
+ assert resolve_dtype(bnb_compute_dtype) is None or isinstance(
+ resolve_dtype(bnb_compute_dtype), torch.dtype
+ )
+
+
[email protected]("value", _shipped_values())
+def test_shipped_dtype_fields_match_the_old_eval(value):
+ """The table must return exactly what `eval(field)` returned."""
+ _, dtype, bnb_compute_dtype, _, _ = value.split(";", 4)
+ for field in (dtype, bnb_compute_dtype):
+ reference = eval(field, {"torch": torch})
+ assert resolve_dtype(field) is reference, field
+
+
+# --- a dtype field is no longer an expression --------------------------------
+
+
+ "payload",
+ [
+ "__import__('os').system('touch /tmp/pwned')",
+ "torch.float16 if __import__('os') else None",
+ "open('/etc/passwd').read()",
+ "exec('x=1')",
+ "torch.cuda.synchronize()",
+ "[].__class__",
+ "torch.float8_e4m3fn", # a real dtype, but not one this channel supports
+ ],
+)
+def test_hostile_dtype_field_rejected(payload):
+ with pytest.raises(ValueError, match = "unsupported dtype"):
+ resolve_dtype(payload)
+
+
+def test_table_covers_only_dtypes():
+ for key, value in DTYPE_ALIASES.items():
+ assert value is None or isinstance(value, torch.dtype), key
+
+
+# --- the code fields are only ours -------------------------------------------
+
+
+def test_a_value_we_set_is_trusted(monkeypatch):
+ monkeypatch.delenv("UNSLOTH_FORCE_CUSTOM_DTYPE", raising = False)
+ value = _shipped_values()[0]
+ register_custom_dtype(value)
+ got, trusted = trusted_custom_dtype()
+ assert got == value
+ assert trusted
+
+
+def test_an_inherited_value_is_not_trusted(monkeypatch):
+ """The case that matters: the variable arrives from outside this process."""
+ payload = "all;None;None;pass;import os; os.system('touch /tmp/pwned')"
+ monkeypatch.setenv("UNSLOTH_FORCE_CUSTOM_DTYPE", payload)
+ got, trusted = trusted_custom_dtype()
+ assert got == payload # dtype fields still readable
+ assert not trusted # code fields are not
+
+
+def test_an_inherited_value_that_mimics_ours_is_still_not_trusted(monkeypatch):
+ """Trust is on the exact string we set, so a near miss does not qualify."""
+ value = _shipped_values()[0] + " "
+ monkeypatch.setenv("UNSLOTH_FORCE_CUSTOM_DTYPE", value)
+ _, trusted = trusted_custom_dtype()
+ assert not trusted
+
+
+def test_unset_is_empty(monkeypatch):
+ monkeypatch.delenv("UNSLOTH_FORCE_CUSTOM_DTYPE", raising = False)
+ assert trusted_custom_dtype() == ("", False)
+
+
+# --- vision.py no longer evaluates the fields --------------------------------
+
+
+def test_vision_does_not_eval_the_dtype_fields():
+ source = pathlib.Path(__import__("unsloth.models.vision", fromlist = ["x"]).__file__).read_text(
+ encoding = "utf-8"
+ )
+ assert "eval(_dtype)" not in source
+ assert "eval(_bnb_compute_dtype)" not in source
+ # The remaining exec is the code field, and it is gated.
+ assert re.search(r"if _code_is_trusted:", source), "the code fields lost their gate"
diff --git a/tests/security/test_custom_dtype_wire_format.py b/tests/security/test_custom_dtype_wire_format.py
new file mode 100644
index 00000000000..1be7d152177
--- /dev/null
+++ b/tests/security/test_custom_dtype_wire_format.py
@@ -0,0 +1,145 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""`UNSLOTH_FORCE_CUSTOM_DTYPE` is parsed by two separately released packages.
+
+Both do `value.split(";", 4)` and assert at least four separators, and they ship on
+their own schedules, so changing the layout on one side breaks the other on skew. The
+hardening changed how the fields are INTERPRETED, not what they are; this pins the
+count, the positions, and the direction of the trust decision.
+"""
+
+from __future__ import annotations
+
+import ast
+import pathlib
+import re
+
+import pytest
+
+from unsloth.models._custom_dtype import register_custom_dtype, trusted_custom_dtype
+
+
+LOADER = pathlib.Path(__import__("unsloth.models.loader", fromlist = ["x"]).__file__).read_text(
+ encoding = "utf-8"
+)
+
+
+def _shipped_values() -> list[str]:
+ tree = ast.parse(LOADER)
+ values = []
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
+ if node.func.id == "register_custom_dtype":
+ values.append(ast.literal_eval(node.args[0]))
+ return values
+
+
[email protected]("value", _shipped_values())
+def test_every_shipped_value_has_five_fields(value):
+ """Both readers do split(";", 4) after asserting count(";") >= 4."""
+ assert value.count(";") >= 4
+ fields = value.split(";", 4)
+ assert len(fields) == 5
+
+
[email protected]("value", _shipped_values())
+def test_field_positions_are_unchanged(value):
+ """checker, dtype, bnb_compute_dtype, custom_datatype, execute_code."""
+ checker, dtype, bnb_compute_dtype, _custom, _execute = value.split(";", 4)
+ assert checker in ("all", "float16", "torch.float16"), checker
+ for field in (dtype, bnb_compute_dtype):
+ assert re.fullmatch(r"(None|torch\.\w+)", field.strip()), field
+
+
+def test_zoo_reader_still_parses_what_unsloth_writes():
+ """unsloth_zoo is imported rather than copied, so a layout change there fails."""
+ import unsloth_zoo.compiler as zoo_compiler
+
+ source = pathlib.Path(zoo_compiler.__file__).read_text(encoding = "utf-8")
+ assert (
+ 'custom_datatype.count(";") >= 4' in source
+ ), "unsloth_zoo changed how it validates UNSLOTH_FORCE_CUSTOM_DTYPE"
+ assert (
+ 'custom_datatype.split(";", 4)' in source
+ ), "unsloth_zoo changed the field split for UNSLOTH_FORCE_CUSTOM_DTYPE"
+
+ from unsloth_zoo.utils import _get_dtype
+
+ import torch
+
+ checked = 0
+ for value in _shipped_values():
+ _, dtype, _, _, _ = value.split(";", 4)
+ name = dtype.strip().removeprefix("torch.")
+ resolved = _get_dtype(name)
+ # The oracle is torch, not the value under test. Deriving `expected` from
+ # `resolved` made this assertion tautological for every non-None dtype, so a
+ # separately released unsloth_zoo that started resolving `float16` to the
+ # wrong thing would still have passed.
+ if dtype.strip() == "None":
+ expected = None
+ else:
+ expected = getattr(torch, name)
+ assert isinstance(expected, torch.dtype), (name, expected)
+ checked += 1
+ assert resolved == expected, (name, resolved, expected)
+ assert checked, "no non-None dtype was checked, so this proves nothing"
+
+
+def test_trust_decision_is_on_the_value_we_set(monkeypatch):
+ """Identical layout, different provenance. The two halves use different strings on
+ purpose, since the registry is never cleared."""
+ template = _shipped_values()[0]
+ checker, dtype, bnb, custom, execute = template.split(";", 4)
+
+ inherited = ";".join([checker, dtype, bnb, custom, "import os; os.system('x')"])
+ monkeypatch.setenv("UNSLOTH_FORCE_CUSTOM_DTYPE", inherited)
+ value, trusted = trusted_custom_dtype()
+ assert value == inherited # dtype fields still readable
+ assert not trusted # code fields are not
+
+ ours = ";".join([checker, dtype, bnb, custom, "pass # only this test sets this"])
+ register_custom_dtype(ours)
+ value, trusted = trusted_custom_dtype()
+ assert value == ours
+ assert trusted
+
+
+def test_unset_variable_leaves_custom_datatype_as_none():
+ """`trusted_custom_dtype()` returns "" when unset, and "" is not None: `vision.py`
+ gates on `is not None`, so nearly every model would walk itself to `exec("")`."""
+ import unsloth.models.vision as vision
+
+ source = pathlib.Path(vision.__file__).read_text(encoding = "utf-8")
+ bound = set()
+ for node in ast.walk(ast.parse(source)):
+ if not isinstance(node, ast.Assign):
+ continue
+ value = node.value
+ if not (isinstance(value, ast.Call) and isinstance(value.func, ast.Name)):
+ continue
+ if value.func.id != "trusted_custom_dtype":
+ continue
+ for target in node.targets:
+ if isinstance(target, ast.Tuple):
+ bound.update(e.id for e in target.elts if isinstance(e, ast.Name))
+
+ assert bound, "trusted_custom_dtype() is no longer assigned in vision.py"
+ assert "custom_datatype" not in bound, (
+ "the raw value must not be bound to `custom_datatype`, which is gated on "
+ "`is not None` further down"
+ )
+ assert "if custom_datatype is not None:" in source, "the consumer this test protects has moved"
+
+
+def test_unset_variable_reads_as_empty_and_untrusted(monkeypatch):
+ monkeypatch.delenv("UNSLOTH_FORCE_CUSTOM_DTYPE", raising = False)
+ assert trusted_custom_dtype() == ("", False)
+
+
+def test_no_producer_bypasses_the_registry():
+ """A direct os.environ write would set the variable without registering it, so
+ its own code fields would then be dropped as untrusted."""
+ assert 'os.environ["UNSLOTH_FORCE_CUSTOM_DTYPE"]' not in LOADER
+ assert "os.environ['UNSLOTH_FORCE_CUSTOM_DTYPE']" not in LOADER
diff --git a/tests/security/test_inherited_custom_dtype_is_neutralized.py b/tests/security/test_inherited_custom_dtype_is_neutralized.py
new file mode 100644
index 00000000000..6a2c9d6a714
--- /dev/null
+++ b/tests/security/test_inherited_custom_dtype_is_neutralized.py
@@ -0,0 +1,212 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""An inherited `UNSLOTH_FORCE_CUSTOM_DTYPE` must be harmless to EVERY reader.
+
+`unsloth_zoo==2026.8.15`, which this package's floor resolves to, still `eval`s the
+dtype field, and a version floor cannot fix an already resolved install, so the VALUE
+is rewritten at import. The old reader is reproduced as the one line that matters,
+`eval(field)`. Imported inside each test, for the four-package runner.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+
+import pytest
+
+_ENV_KEY = "UNSLOTH_FORCE_CUSTOM_DTYPE"
+_HOSTILE = 'all;__import__("os").system("touch {marker}");None;;'
+
+
+def _import_with(value, marker = None):
+ """Imports the module in a fresh process with `value` inherited, returns the env."""
+ environment = dict(os.environ)
+ environment[_ENV_KEY] = value.format(marker = marker) if marker else value
+ program = (
+ "import unsloth.models._custom_dtype as module, os;"
+ f"print(repr(os.environ.get({_ENV_KEY!r})))"
+ )
+ finished = subprocess.run(
+ [sys.executable, "-c", program],
+ env = environment,
+ capture_output = True,
+ text = True,
+ timeout = 600,
+ )
+ assert finished.returncode == 0, finished.stderr[-2000:]
+ return finished.stdout.strip().splitlines()[-1]
+
+
+def test_a_hostile_dtype_field_cannot_reach_an_eval(tmp_path):
+ """The field the older zoo reader evaluates is a dtype NAME afterwards, or None."""
+ from unsloth.models._custom_dtype import DTYPE_ALIASES
+
+ marker = tmp_path / "pwned"
+ seen = _import_with(_HOSTILE, marker = marker)
+ assert not marker.exists(), "importing the module ran the inherited code"
+
+ value = seen.strip("'\"")
+ field = value.split(";", 4)[1]
+ assert field.strip() in DTYPE_ALIASES, field
+ # What the unhardened `unsloth_zoo==2026.8.15` does with that field, verbatim.
+ assert eval(field) is None # noqa: S307 - the point of the test
+ assert not marker.exists()
+
+
+def test_the_code_fields_of_an_inherited_value_are_emptied(monkeypatch):
+ from unsloth.models._custom_dtype import neutralize_inherited_custom_dtype
+
+ monkeypatch.setenv(_ENV_KEY, "all;torch.float16;torch.float16;custom;import os")
+ sanitized = neutralize_inherited_custom_dtype()
+ checker, dtype, bnb, custom, execute = sanitized.split(";", 4)
+ assert (custom, execute) == ("", "")
+ # The dtype fields of a well formed value still apply: that is what they already
+ # did, and the five fields stay because both packages assert on the count.
+ assert (checker, dtype, bnb) == ("all", "torch.float16", "torch.float16")
+ assert sanitized.count(";") == 4
+
+
+def test_an_unknown_dtype_name_becomes_none(monkeypatch):
+ from unsloth.models._custom_dtype import neutralize_inherited_custom_dtype
+
+ monkeypatch.setenv(_ENV_KEY, "all;os.system('x');None;;")
+ sanitized = neutralize_inherited_custom_dtype()
+ assert sanitized.split(";", 4)[1] == "None"
+
+
+def test_a_malformed_inherited_value_is_removed(monkeypatch):
+ """Both readers assert on the separator count, so it can only crash a run."""
+ from unsloth.models._custom_dtype import neutralize_inherited_custom_dtype
+
+ monkeypatch.setenv(_ENV_KEY, "not-even-close")
+ assert neutralize_inherited_custom_dtype() == ""
+ assert _ENV_KEY not in os.environ
+
+
+def test_a_value_this_process_registered_is_untouched(monkeypatch):
+ from unsloth.models._custom_dtype import (
+ neutralize_inherited_custom_dtype,
+ register_custom_dtype,
+ trusted_custom_dtype,
+ )
+
+ monkeypatch.delenv(_ENV_KEY, raising = False)
+ ours = "all;torch.float16;torch.float16;pass # only this test;pass # only this test"
+ register_custom_dtype(ours)
+ assert neutralize_inherited_custom_dtype() == ours
+ assert trusted_custom_dtype() == (ours, True)
+
+
+ "value",
+ [
+ "all;torch.bfloat16;None;;",
+ "float16;torch.float16;torch.float16;;",
+ ],
+)
+def test_neutralizing_is_idempotent(value, monkeypatch):
+ from unsloth.models._custom_dtype import neutralize_inherited_custom_dtype
+
+ monkeypatch.setenv(_ENV_KEY, value)
+ once = neutralize_inherited_custom_dtype()
+ monkeypatch.setenv(_ENV_KEY, once)
+ assert neutralize_inherited_custom_dtype() == once
+
+
+def test_the_module_neutralizes_on_import():
+ """A caller that never touches the function is still protected."""
+
+ import ast
+ import pathlib
+
+ import unsloth.models._custom_dtype as module
+
+ source = pathlib.Path(module.__file__).read_text(encoding = "utf-8")
+ called = [
+ node
+ for node in ast.parse(source).body
+ if isinstance(node, ast.Expr)
+ and isinstance(node.value, ast.Call)
+ and getattr(node.value.func, "id", "") == "neutralize_inherited_custom_dtype"
+ ]
+ assert called, "the module no longer neutralizes an inherited value on import"
+
+
+def test_the_compiler_entry_point_neutralizes_again():
+ """A value set AFTER import must not reach the older `unsloth_zoo` reader, so it
+ is sanitized again at `unsloth_compile_transformers`."""
+
+ import ast
+ import pathlib
+
+ import unsloth.models._utils as module
+
+ source = pathlib.Path(module.__file__).read_text(encoding = "utf-8")
+ tree = ast.parse(source)
+ wrappers = [
+ node
+ for node in tree.body
+ if isinstance(node, ast.FunctionDef) and node.name == "unsloth_compile_transformers"
+ ]
+ assert wrappers, "unsloth_compile_transformers is gone"
+ called = [
+ node
+ for node in ast.walk(wrappers[0])
+ if isinstance(node, ast.Call)
+ and getattr(node.func, "id", "") == "neutralize_inherited_custom_dtype"
+ ]
+ assert called, "the compiler entry point no longer re-neutralizes an inherited value"
+
+
+def test_a_value_set_after_import_is_still_neutralized(monkeypatch):
+ """End to end through the entry point, with the compilation itself disabled."""
+
+ from unsloth.models._utils import unsloth_compile_transformers
+
+ hostile = 'all;__import__("os").environ["UNSLOTH_TEST_MARKER"] = "1";None;;print(1)'
+ monkeypatch.setenv(_ENV_KEY, hostile)
+ monkeypatch.delenv("UNSLOTH_TEST_MARKER", raising = False)
+
+ # `disable = True` returns before any compilation, which is all this needs: the
+ # sanitizing runs first.
+ unsloth_compile_transformers(
+ dtype = None,
+ model_name = "unsloth/tiny",
+ model_types = ["llama"],
+ disable = True,
+ )
+
+ sanitized = os.environ[_ENV_KEY]
+ assert sanitized.count(";") == 4, sanitized
+ checker, dtype, bnb, custom, code = sanitized.split(";", 4)
+ assert dtype == "None" and bnb == "None", sanitized
+ assert custom == "" and code == "", sanitized
+ assert "UNSLOTH_TEST_MARKER" not in os.environ
+
+
+def test_a_shorthand_alias_is_written_back_canonically(monkeypatch):
+ """`eval("fp16")` is a NameError in the older zoo reader, so preserving the field
+ verbatim was only safe for the spellings that happen to be evaluable."""
+ import torch
+ from unsloth.models._custom_dtype import (
+ neutralize_inherited_custom_dtype,
+ resolve_dtype,
+ )
+
+ monkeypatch.setenv(_ENV_KEY, "all;fp16;bf16;;")
+ assert neutralize_inherited_custom_dtype() == "all;torch.float16;torch.bfloat16;;"
+ # And each canonical spelling is one the legacy reader's `eval` can evaluate.
+ _checker, dtype, compute, _code, _execute = os.environ[_ENV_KEY].split(";", 4)
+ for field in (dtype, compute):
+ assert eval(field, {"torch": torch}) is resolve_dtype(field)
+
+
+def test_an_empty_dtype_field_stays_empty(monkeypatch):
+ """An unset field already reads as None to both readers; it is not rewritten."""
+ from unsloth.models._custom_dtype import neutralize_inherited_custom_dtype
+
+ monkeypatch.setenv(_ENV_KEY, "all;;;;")
+ assert neutralize_inherited_custom_dtype() == "all;;;;"
diff --git a/tests/security/test_mapper_probe_no_exec.py b/tests/security/test_mapper_probe_no_exec.py
new file mode 100644
index 00000000000..a73e1afd2b6
--- /dev/null
+++ b/tests/security/test_mapper_probe_no_exec.py
@@ -0,0 +1,854 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""`_get_new_mapper` used to `exec` an HTTPS response body: arbitrary code execution
+inside an ordinary model load, gated only on transport integrity. It now
+`literal_eval`s the `__INT_TO_FLOAT_MAPPER` dict and derives the five tables with the
+INSTALLED `build_mappers`, so a hostile body can still change what the probe reports,
+which was always true, but can no longer run."""
+
+import builtins
+import pathlib
+import re
+import types
+from contextlib import contextmanager
+
+import pytest
+
+from unsloth.models import loader_utils
+from unsloth.models.mapper import build_mappers
+
+
+REAL_MAPPER = open(
+ __import__("pathlib").Path(loader_utils.__file__).with_name("mapper.py"),
+ encoding = "utf-8",
+).read()
+
+
+class _Response:
+ """The streaming half of `requests.Response`: a fake offering only `.text` would
+ let the byte cap and the by-hand redirect following regress silently."""
+
+ def __init__(
+ self,
+ text,
+ status_code = 200,
+ headers = None,
+ ):
+ self.encoding = "utf-8"
+ self.status_code = status_code
+ self.headers = headers or {}
+ self._body = text.encode("utf-8")
+ self._read = False
+
+ def iter_content(self, chunk_size = 1):
+ yield self._body
+
+ @property
+ def raw(self):
+ """`read1` returns what ONE socket read produced, so the deadline is checked
+ between reads rather than only between whole chunks."""
+ return self
+
+ def read1(self, amount = -1):
+ if self._read:
+ return b""
+ self._read = True
+ return self._body
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exception):
+ return False
+
+
+@contextmanager
+def _serving(body, monkeypatch):
+ """Makes the probe's `requests.get` return `body`."""
+ import requests
+
+ monkeypatch.setattr(requests, "get", lambda *a, **k: _Response(body))
+ if not hasattr(requests, "compat"):
+ monkeypatch.setattr(requests, "compat", types.SimpleNamespace(urljoin = lambda b, u: u))
+ yield
+
+
+def no_dynamic_execution(monkeypatch):
+ """Records any exec/eval reached during the probe. RECORDS rather than raises,
+ since the probe's bare except would swallow an AssertionError."""
+ calls = []
+
+ def _forbidden(name):
+ def _record(*args, **kwargs):
+ calls.append(name)
+ raise AssertionError(f"_get_new_mapper called {name}()")
+
+ return _record
+
+ monkeypatch.setattr(builtins, "exec", _forbidden("exec"))
+ monkeypatch.setattr(builtins, "eval", _forbidden("eval"))
+ return calls
+
+
+MARKER = "/tmp/unsloth_mapper_probe_marker"
+
+PAYLOADS = [
+ f"import os; os.system('touch {MARKER}')\n__INT_TO_FLOAT_MAPPER = {{}}\n",
+ f"__INT_TO_FLOAT_MAPPER = {{}}\nimport os\nos.system('touch {MARKER}')\n",
+ f"open({MARKER!r}, 'w').close()\n__INT_TO_FLOAT_MAPPER = {{}}\n",
+ "__INT_TO_FLOAT_MAPPER = __import__('os').environ\n",
+ "class X:\n def __init__(self): __import__('os').getpid()\n__INT_TO_FLOAT_MAPPER = X()\n",
+]
+
+
[email protected]("payload", PAYLOADS)
+def test_payload_in_the_response_is_never_executed(payload, monkeypatch, tmp_path):
+ import os
+
+ if os.path.exists(MARKER):
+ os.remove(MARKER)
+
+ with _serving(payload, monkeypatch):
+ result = loader_utils._get_new_mapper()
+
+ assert not os.path.exists(MARKER), "the fetched body executed"
+ assert len(result) == 5
+ assert all(isinstance(table, dict) for table in result)
+
+
+def test_probe_does_not_call_exec_or_eval(no_dynamic_execution, monkeypatch):
+ """Stronger than the marker: asserting only the returned shape would also hold
+ for the old implementation, whose bare except ate the fixture's AssertionError."""
+ with _serving(REAL_MAPPER, monkeypatch):
+ result = loader_utils._get_new_mapper()
+ assert no_dynamic_execution == [], f"the probe reached {no_dynamic_execution}"
+ # And it did the WORK, rather than falling into the except and returning empties.
+ assert len(result) == 5
+ assert all(result[:3]), "the probe returned nothing, so it proved nothing"
+
+
+def test_a_body_that_is_not_python_is_survivable(monkeypatch):
+ for body in ("", "<html>404</html>", "\x00\x01\x02", "def "):
+ with _serving(body, monkeypatch):
+ assert loader_utils._get_new_mapper() == ({}, {}, {}, {}, {})
+
+
+def test_a_body_without_the_source_table_returns_nothing(monkeypatch):
+ with _serving("SOMETHING_ELSE = {'a': 1}\n", monkeypatch):
+ assert loader_utils._get_new_mapper() == ({}, {}, {}, {}, {})
+
+
+def test_a_deeply_nested_body_is_survivable(monkeypatch):
+ """`ast.parse` builds the whole tree first, so deep nesting raises RecursionError,
+ which is not a ValueError. This pins that the bare except keeps catching it."""
+ body = "__INT_TO_FLOAT_MAPPER = " + "[" * 20000 + "]" * 20000
+ with _serving(body, monkeypatch):
+ assert loader_utils._get_new_mapper() == ({}, {}, {}, {}, {})
+
+
+def _byte_cap():
+ """The cap as the probe actually spells it, so lowering it cannot desync this."""
+ source = pathlib.Path(loader_utils.__file__).read_text(encoding = "utf-8")
+ match = re.search(r"^\s*byte_cap = ([0-9_]+)$", source, re.MULTILINE)
+ assert match is not None, "the mapper probe no longer has a byte cap"
+ return int(match.group(1).replace("_", ""))
+
+
+def test_an_oversized_body_is_not_parsed_at_all(monkeypatch):
+ """The size cap: `requests`' timeout is per-read, so a body can be any size."""
+ cap = _byte_cap()
+ body = "__INT_TO_FLOAT_MAPPER = {'a' : ('b',)}\n" + ("# padding\n" * (cap // 10 + 1))
+ assert len(body) > cap
+ with _serving(body, monkeypatch):
+ assert loader_utils._get_new_mapper() == ({}, {}, {}, {}, {})
+
+
+def test_the_cap_bounds_parse_cost_not_just_download_size():
+ """Short statements are the dense case: several AST nodes each, so the cap is set
+ from what the PARSE can afford rather than what the network can."""
+ cap = _byte_cap()
+ assert cap <= 2_000_000, (
+ f"a {cap} byte cap admits roughly {cap // 4} short statements, which is a "
+ f"memory blow-up in ast.parse rather than a bounded read"
+ )
+
+
+def test_the_real_mapper_is_far_below_the_cap():
+ assert len(REAL_MAPPER) < _byte_cap() / 2
+
+
+def test_real_mapper_body_reproduces_the_installed_tables(monkeypatch):
+ """Serving the installed mapper.py back must reproduce the installed tables."""
+ with _serving(REAL_MAPPER, monkeypatch):
+ result = loader_utils._get_new_mapper()
+
+ from unsloth.models import mapper
+
+ expected = (
+ mapper.INT_TO_FLOAT_MAPPER,
+ mapper.FLOAT_TO_INT_MAPPER,
+ mapper.MAP_TO_UNSLOTH_16bit,
+ mapper.FLOAT_TO_FP8_BLOCK_MAPPER,
+ mapper.FLOAT_TO_FP8_ROW_MAPPER,
+ )
+ assert result == expected
+ assert len(result[0]) > 100, "the probe returned an empty table"
+
+
+def test_a_newer_table_is_picked_up(monkeypatch):
+ """The probe's actual job: report a mapping the installed tables do not have."""
+ body = (
+ "__INT_TO_FLOAT_MAPPER = {\n"
+ " 'unsloth/some-new-model-bnb-4bit': ('unsloth/some-new-model',),\n"
+ "}\n"
+ )
+ with _serving(body, monkeypatch):
+ int_to_float, float_to_int, _, _, _ = loader_utils._get_new_mapper()
+
+ assert int_to_float["unsloth/some-new-model-bnb-4bit"] == "unsloth/some-new-model"
+ assert float_to_int["unsloth/some-new-model"] == "unsloth/some-new-model-bnb-4bit"
+
+
+def test_an_annotated_source_table_is_still_read(monkeypatch):
+ """A harmless `__INT_TO_FLOAT_MAPPER: dict = {...}` upstream would otherwise
+ return five empty tables with nothing looking broken."""
+ plain = REAL_MAPPER
+ annotated = plain.replace(
+ "__INT_TO_FLOAT_MAPPER = ",
+ "__INT_TO_FLOAT_MAPPER: dict = ",
+ 1,
+ )
+ assert annotated != plain, "the table is no longer spelled as a plain assignment"
+
+ with _serving(plain, monkeypatch):
+ expected = loader_utils._get_new_mapper()
+ with _serving(annotated, monkeypatch):
+ got = loader_utils._get_new_mapper()
+
+ assert any(expected), "the unannotated form produced nothing, so this proves nothing"
+ assert got == expected
+
+
+def test_a_mutation_that_never_runs_is_not_read(monkeypatch):
+ """The probe reads what the fetched module INSTALLS, not what it contains: a
+ fabricated mapping raises the upgrade notice for a name that does not exist."""
+ dead = REAL_MAPPER + (
+ "\n"
+ "if False:\n"
+ " _add_with_lower(MAP_TO_UNSLOTH_16bit, 'vendor/never', 'unsloth/never')\n"
+ " FLOAT_TO_FP8_ROW_MAPPER['vendor/never-fp8'] = 'unsloth/never-fp8-row'\n"
+ "\n"
+ "def _helper():\n"
+ " FLOAT_TO_FP8_ROW_MAPPER['vendor/inside-a-def'] = 'unsloth/inside-a-def'\n"
+ )
+
+ with _serving(REAL_MAPPER, monkeypatch):
+ expected = loader_utils._get_new_mapper()
+ with _serving(dead, monkeypatch):
+ got = loader_utils._get_new_mapper()
+
+ assert any(expected), "the real mapper produced nothing, so this proves nothing"
+ assert got == expected, "a mutation that never executes was read as installed"
+
+ for table in got:
+ assert not any("never" in str(key) for key in table)
+ assert not any("inside-a-def" in str(key) for key in table)
+
+
+def test_a_deferred_lambda_body_is_not_read(monkeypatch):
+ """A `lambda` is an expression, so the one attached to an assignment SEEDED the
+ walk even though the walk refuses to descend into one it meets as a child."""
+ dead = REAL_MAPPER + (
+ "\n"
+ "unused = lambda: FLOAT_TO_FP8_ROW_MAPPER.update("
+ "{'vendor/in-a-lambda': 'unsloth/in-a-lambda'})\n"
+ "also_unused = [lambda: FLOAT_TO_FP8_ROW_MAPPER.update("
+ "{'vendor/in-a-listed-lambda': 'unsloth/in-a-listed-lambda'})]\n"
+ )
+
+ with _serving(REAL_MAPPER, monkeypatch):
+ expected = loader_utils._get_new_mapper()
+ with _serving(dead, monkeypatch):
+ got = loader_utils._get_new_mapper()
+
+ assert any(expected), "the real mapper produced nothing, so this proves nothing"
+ assert got == expected, "a lambda body was read as installed"
+ for table in got:
+ assert not any("lambda" in str(key) for key in table)
+
+
+def test_an_alias_added_inside_the_builder_is_read(monkeypatch):
+ """`build_mappers` is called at import, so its body runs. The aliases that cannot
+ be derived from the source table live in there, and the installed builder cannot
+ know one a newer mapper.py adds."""
+ lines = REAL_MAPPER.splitlines(True)
+ for index, line in enumerate(lines):
+ if line.startswith("def build_mappers("):
+ insert = index + 1
+ break
+ else:
+ raise AssertionError("build_mappers is gone from the shipped mapper")
+ added = "".join(
+ lines[:insert]
+ + [' _add_with_lower(MAP_TO_UNSLOTH_16bit, "vendor/new", "unsloth/new")\n']
+ + lines[insert:]
+ )
+ with _serving(added, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ assert any(
+ table.get("vendor/new") == "unsloth/new" for table in tables if isinstance(table, dict)
+ ), "an alias added inside the builder was dropped"
+
+
+def test_a_table_cleared_after_the_builder_stays_cleared(monkeypatch):
+ """Installed where the call RUNS: a rebind written after it leaves the table
+ empty, and reapplying the aliases at the end reported support that is not there."""
+ lines = REAL_MAPPER.splitlines(True)
+ insert = next(i for i, line in enumerate(lines) if line.startswith("def build_mappers(")) + 1
+ added = (
+ "".join(
+ lines[:insert]
+ + [' _add_with_lower(MAP_TO_UNSLOTH_16bit, "vendor/late", "unsloth/late")\n']
+ + lines[insert:]
+ )
+ + "\nMAP_TO_UNSLOTH_16bit = {}\n"
+ )
+ with _serving(added, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ for table in tables:
+ assert not any("vendor/late" in str(key) for key in table)
+
+
+def test_a_builder_that_is_never_called_is_not_read(monkeypatch):
+ """A `def` that nothing calls runs nothing, which is the rule everywhere here."""
+ uncalled = REAL_MAPPER.replace(
+ "= build_mappers(__INT_TO_FLOAT_MAPPER)", "= ({}, {}, {}, {}, {})"
+ )
+ # The `def` line names it too, so the CALL is what has to be gone.
+ assert "= build_mappers(" not in uncalled
+ lines = uncalled.splitlines(True)
+ insert = next(i for i, line in enumerate(lines) if line.startswith("def build_mappers(")) + 1
+ uncalled = "".join(
+ lines[:insert]
+ + [' _add_with_lower(MAP_TO_UNSLOTH_16bit, "vendor/dead", "unsloth/dead")\n']
+ + lines[insert:]
+ )
+ with _serving(uncalled, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ for table in tables:
+ assert not any("vendor/dead" in str(key) for key in table)
+
+
+def test_a_branch_that_does_run_is_still_read(monkeypatch):
+ """The exclusion is about DEAD code, not about conditionals in general."""
+ live = REAL_MAPPER + (
+ "\n"
+ "if True:\n"
+ " FLOAT_TO_FP8_ROW_MAPPER['vendor/live-fp8'] = 'unsloth/live-fp8-row'\n"
+ )
+ with _serving(live, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ assert any(
+ "vendor/live-fp8" in table for table in tables if isinstance(table, dict)
+ ), "a live branch's mutation was dropped"
+
+
+def test_a_builder_called_only_in_dead_code_adds_nothing(monkeypatch):
+ """`if False: build_mappers(...)` installs nothing, so neither does the probe. The call was located by a raw walk, which sees unreachable and deferred code, and the builder's aliases were then applied by the fallback at the end even though the execution-order walk had correctly left the call out. That fabricated support the fetched mapper does not have, and a lookup for such a name raises the upgrade-only `NotImplementedError`."""
+ dead = REAL_MAPPER.replace("= build_mappers(__INT_TO_FLOAT_MAPPER)", "= ({}, {}, {}, {}, {})")
+ assert "= build_mappers(" not in dead
+ lines = dead.splitlines(True)
+ insert = next(i for i, line in enumerate(lines) if line.startswith("def build_mappers(")) + 1
+ dead = "".join(
+ lines[:insert]
+ + [' _add_with_lower(MAP_TO_UNSLOTH_16bit, "vendor/fabricated", "unsloth/fabricated")\n']
+ + lines[insert:]
+ )
+ dead += "\nif False:\n build_mappers(__INT_TO_FLOAT_MAPPER)\n"
+ with _serving(dead, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ for table in tables:
+ assert not any("vendor/fabricated" in str(key) for key in table)
+
+
+def test_a_mutation_below_an_unconditional_continue_is_not_installed(monkeypatch):
+ """`continue` ends the suite exactly as `break` does."""
+ unreachable = REAL_MAPPER + (
+ "\n"
+ "while True:\n"
+ " continue\n"
+ " FLOAT_TO_FP8_ROW_MAPPER['vendor/dead-continue'] = 'unsloth/dead-row'\n"
+ )
+ with _serving(unreachable, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ for table in tables:
+ assert not any("vendor/dead-continue" in str(key) for key in table)
+
+
+def test_a_helper_call_spelled_with_keywords_is_read(monkeypatch):
+ """`_add_with_lower(mapper = ..., key = ..., value = ...)` adds the same alias. Requiring three positional arguments dropped it, so the probe answered "no newer support" for a model the newer mapper really does map."""
+ keyworded = REAL_MAPPER + (
+ "\n"
+ '_add_with_lower(mapper = MAP_TO_UNSLOTH_16bit, key = "vendor/kw", '
+ 'value = "unsloth/kw")\n'
+ )
+ with _serving(keyworded, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ assert any(
+ "vendor/kw" in table for table in tables if isinstance(table, dict)
+ ), "a keyword-spelled helper call was dropped"
+
+
+def test_a_helper_call_that_binds_one_parameter_twice_is_skipped(monkeypatch):
+ """It raises rather than adding anything, so the probe adds nothing either."""
+ doubled = REAL_MAPPER + (
+ "\n"
+ '_add_with_lower(MAP_TO_UNSLOTH_16bit, "vendor/twice", mapper = MAP_TO_UNSLOTH_16bit)\n'
+ )
+ with _serving(doubled, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ for table in tables:
+ assert not any("vendor/twice" in str(key) for key in table)
+
+
+def test_a_builder_call_inside_a_lambda_does_not_run_the_builder(monkeypatch):
+ """A deferred call to `build_mappers` is not a call: walking the parent statement
+ descended back into the deferred children the yield had excluded."""
+ lines = REAL_MAPPER.splitlines(True)
+ insert = next(i for i, line in enumerate(lines) if line.startswith("def build_mappers(")) + 1
+ deferred = (
+ "".join(
+ lines[:insert]
+ + [' _add_with_lower(MAP_TO_UNSLOTH_16bit, "vendor/deferred", "unsloth/deferred")\n']
+ + lines[insert:]
+ ).replace("= build_mappers(__INT_TO_FLOAT_MAPPER)", "= ({}, {}, {}, {}, {})")
+ + "\nunused = lambda: build_mappers(__INT_TO_FLOAT_MAPPER)\n"
+ )
+ assert "= build_mappers(__INT_TO_FLOAT_MAPPER)" not in deferred.replace(
+ "unused = lambda: build_mappers(__INT_TO_FLOAT_MAPPER)", ""
+ )
+ with _serving(deferred, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ for table in tables:
+ assert not any("vendor/deferred" in str(key) for key in table)
+
+
+def test_the_source_table_is_read_where_the_builder_runs(monkeypatch):
+ """A source table rebound AFTER the builder ran is not what the module exports."""
+ rebound = REAL_MAPPER + (
+ '\n__INT_TO_FLOAT_MAPPER = {"vendor/rebound-bnb-4bit": ("vendor/rebound",)}\n'
+ )
+
+ with _serving(REAL_MAPPER, monkeypatch):
+ expected = loader_utils._get_new_mapper()
+ with _serving(rebound, monkeypatch):
+ got = loader_utils._get_new_mapper()
+
+ assert any(expected), "the real mapper produced nothing, so this proves nothing"
+ assert got == expected, "a rebind after the builder call was read as the source"
+ for table in got:
+ assert not any("rebound" in str(key) for key in table)
+
+
+def test_a_source_table_rebound_before_the_builder_is_the_one_read(monkeypatch):
+ """The other half: the last binding BEFORE the call still wins. `__INT_TO_FLOAT_MAPPER = {}` followed by the real table is the shape this rule was written for, and it has to keep reading the real one."""
+ lines = REAL_MAPPER.splitlines(True)
+ start = next(i for i, line in enumerate(lines) if line.startswith("__INT_TO_FLOAT_MAPPER"))
+ emptied = "".join(lines[:start] + ["__INT_TO_FLOAT_MAPPER = {}\n"] + lines[start:])
+
+ with _serving(REAL_MAPPER, monkeypatch):
+ expected = loader_utils._get_new_mapper()
+ with _serving(emptied, monkeypatch):
+ got = loader_utils._get_new_mapper()
+
+ assert any(expected)
+ assert got == expected, "an earlier empty binding was read instead of the real one"
+
+
+def test_a_source_table_extended_before_the_builder_is_read(monkeypatch):
+ """`.update({...})` is an ordinary way to extend the table before it is handed
+ over, and the entries have to reach `build_mappers`."""
+ lines = REAL_MAPPER.splitlines(True)
+ insert = next(i for i, line in enumerate(lines) if line.startswith("def build_mappers("))
+ extended = "".join(
+ lines[:insert]
+ + [
+ "__INT_TO_FLOAT_MAPPER.update(" '{"vendor/added-bnb-4bit": ("vendor/added",)})\n',
+ '__INT_TO_FLOAT_MAPPER["vendor/keyed-bnb-4bit"] = ("vendor/keyed",)\n',
+ ]
+ + lines[insert:]
+ )
+ with _serving(extended, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ joined = " ".join(str(sorted(table)) for table in tables)
+ assert "vendor/added" in joined, "an update before the builder was dropped"
+ assert "vendor/keyed" in joined, "a subscript assignment before the builder was dropped"
+
+
+def test_a_source_mutation_after_the_builder_is_not_read(monkeypatch):
+ """The other direction: the builder was handed what existed when it ran."""
+ late = REAL_MAPPER + (
+ '\n__INT_TO_FLOAT_MAPPER.update({"vendor/late-bnb-4bit": ("vendor/late",)})\n'
+ )
+ with _serving(REAL_MAPPER, monkeypatch):
+ expected = loader_utils._get_new_mapper()
+ with _serving(late, monkeypatch):
+ got = loader_utils._get_new_mapper()
+ assert any(expected)
+ assert got == expected, "a mutation after the builder call was read as the source"
+
+
+def test_a_direct_entry_survives_an_empty_source_table(monkeypatch):
+ """A row-only FP8 entry cannot be expressed through the source table at all, so
+ returning early on an empty one left every direct mutation unread."""
+ emptied = REAL_MAPPER.replace(
+ "= build_mappers(__INT_TO_FLOAT_MAPPER)", "= build_mappers({})"
+ ) + ('\nFLOAT_TO_FP8_ROW_MAPPER["vendor/only-fp8"] = "unsloth/only-fp8-row"\n')
+ with _serving(emptied, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ assert any(
+ table.get("vendor/only-fp8") == "unsloth/only-fp8-row"
+ for table in tables
+ if isinstance(table, dict)
+ ), "a direct entry was dropped because the source table was empty"
+
+
+def test_a_body_that_installs_nothing_still_reports_nothing(monkeypatch):
+ """And the guard the early return used to give is kept, decided from the result."""
+ for body in ("", "x = 1\n", "__INT_TO_FLOAT_MAPPER = {}\n"):
+ with _serving(body, monkeypatch):
+ assert loader_utils._get_new_mapper() == ({}, {}, {}, {}, {}), body
+
+
+def test_a_source_entry_deleted_before_the_builder_is_gone(monkeypatch):
+ """`del __INT_TO_FLOAT_MAPPER[...]` removes it from what the builder is handed,
+ so replaying only the additions reported a model the newer mapper had dropped."""
+ lines = REAL_MAPPER.splitlines(True)
+ insert = next(i for i, line in enumerate(lines) if line.startswith("def build_mappers("))
+ with _serving(REAL_MAPPER, monkeypatch):
+ expected = loader_utils._get_new_mapper()
+ victim = next(iter(expected[0]))
+
+ removed = "".join(
+ lines[:insert] + [f"del __INT_TO_FLOAT_MAPPER[{victim!r}]\n"] + lines[insert:]
+ )
+ with _serving(removed, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+
+ assert victim in expected[0], "the fixture picked a name the probe never reported"
+ assert victim not in tables[0], "a deleted source entry was still reported"
+
+
+def test_deleting_the_whole_source_table_leaves_nothing_to_read(monkeypatch):
+ """`del __INT_TO_FLOAT_MAPPER` unbinds it, so the builder is handed nothing."""
+ lines = REAL_MAPPER.splitlines(True)
+ insert = next(i for i, line in enumerate(lines) if line.startswith("def build_mappers("))
+ removed = "".join(lines[:insert] + ["del __INT_TO_FLOAT_MAPPER\n"] + lines[insert:])
+ with _serving(removed, monkeypatch):
+ assert loader_utils._get_new_mapper() == ({}, {}, {}, {}, {})
+
+
+def test_an_exported_entry_deleted_by_the_fetched_mapper_is_gone(monkeypatch):
+ """`del FLOAT_TO_INT_MAPPER["vendor/base"]` removes the alias on import."""
+ with _serving(REAL_MAPPER, monkeypatch):
+ expected = loader_utils._get_new_mapper()
+ victim = next(iter(expected[1]))
+ removed = REAL_MAPPER + f"\ndel FLOAT_TO_INT_MAPPER[{victim!r}]\n"
+ with _serving(removed, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ assert victim in expected[1], "the fixture picked a name the probe never reported"
+ assert victim not in tables[1], "a deleted exported entry was still reported"
+
+
+def test_an_addition_below_a_return_in_the_builder_is_not_read(monkeypatch):
+ """Nothing after an unconditional `return` in that suite runs."""
+ lines = REAL_MAPPER.splitlines(True)
+ insert = next(i for i, line in enumerate(lines) if line.startswith("def build_mappers(")) + 1
+ dead = "".join(
+ lines[:insert]
+ + [
+ " if True:\n return ({}, {}, {}, {}, {})\n",
+ ' _add_with_lower(MAP_TO_UNSLOTH_16bit, "vendor/dead", "unsloth/dead")\n',
+ ]
+ + lines[insert:]
+ )
+ with _serving(dead, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ for table in tables:
+ assert not any("vendor/dead" in str(key) for key in table)
+
+
+def test_the_builder_call_that_binds_the_exports_is_the_one_read(monkeypatch):
+ """A validation call over a dummy table before the real one is not the source."""
+ lines = REAL_MAPPER.splitlines(True)
+ insert = next(
+ i
+ for i, line in enumerate(lines)
+ if line.rstrip().endswith("= build_mappers(__INT_TO_FLOAT_MAPPER)")
+ )
+ while insert > 0 and not lines[insert - 1].rstrip().endswith((")", ":", "}", "]")):
+ insert -= 1
+ dummied = "".join(
+ lines[:insert]
+ + [
+ 'DUMMY_SOURCE = {"vendor/dummy-bnb-4bit": ("vendor/dummy",)}\n',
+ "_checked = build_mappers(DUMMY_SOURCE)\n",
+ ]
+ + lines[insert:]
+ )
+ with _serving(REAL_MAPPER, monkeypatch):
+ expected = loader_utils._get_new_mapper()
+ with _serving(dummied, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ assert any(expected)
+ for table in tables:
+ assert not any(
+ "vendor/dummy" in str(key) for key in table
+ ), "the dummy call was read as the one that populates the exports"
+ assert tables == expected
+
+
+def test_the_last_export_producing_call_is_the_one_read(monkeypatch):
+ """Rebuilding the exports twice leaves the SECOND result installed. Reading the first invented support the second build removed and dropped what it added, either way through the upgrade-only NotImplementedError."""
+ lines = REAL_MAPPER.splitlines(True)
+ insert = (
+ next(
+ i
+ for i, line in enumerate(lines)
+ if line.rstrip().endswith("= build_mappers(__INT_TO_FLOAT_MAPPER)")
+ )
+ + 1
+ )
+ rebuilt = "".join(
+ lines[:insert]
+ + [
+ 'SECOND_SOURCE = {"vendor/second-bnb-4bit": ("vendor/second",)}\n',
+ "(\n"
+ " INT_TO_FLOAT_MAPPER,\n"
+ " FLOAT_TO_INT_MAPPER,\n"
+ " MAP_TO_UNSLOTH_16bit,\n"
+ " FLOAT_TO_FP8_BLOCK_MAPPER,\n"
+ " FLOAT_TO_FP8_ROW_MAPPER,\n"
+ ") = build_mappers(SECOND_SOURCE)\n",
+ ]
+ + lines[insert:]
+ )
+ with _serving(rebuilt, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ assert any(
+ "vendor/second" in str(key) for table in tables for key in table
+ ), "the second build was ignored"
+
+
+def test_an_addition_after_a_returning_loop_is_not_read(monkeypatch):
+ """`while True: return` ends the function, so nothing written below it runs."""
+ lines = REAL_MAPPER.splitlines(True)
+ insert = next(i for i, line in enumerate(lines) if line.startswith("def build_mappers(")) + 1
+ dead = "".join(
+ lines[:insert]
+ + [
+ " while True:\n return ({}, {}, {}, {}, {})\n",
+ ' _add_with_lower(MAP_TO_UNSLOTH_16bit, "vendor/after-loop", "unsloth/after-loop")\n',
+ ]
+ + lines[insert:]
+ )
+ with _serving(dead, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ for table in tables:
+ assert not any("vendor/after-loop" in str(key) for key in table)
+
+
+def test_an_addition_after_a_breaking_loop_is_still_read(monkeypatch):
+ """The other direction: `break` leaves the LOOP, and the rest of the body runs."""
+ lines = REAL_MAPPER.splitlines(True)
+ insert = next(i for i, line in enumerate(lines) if line.startswith("def build_mappers(")) + 1
+ live = "".join(
+ lines[:insert]
+ + [
+ " while True:\n break\n",
+ ' _add_with_lower(MAP_TO_UNSLOTH_16bit, "vendor/after-break", "unsloth/after-break")\n',
+ ]
+ + lines[insert:]
+ )
+ with _serving(live, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ assert any(
+ table.get("vendor/after-break") == "unsloth/after-break"
+ for table in tables
+ if isinstance(table, dict)
+ ), "an addition after a loop that only breaks was dropped"
+
+
+def test_a_mutation_between_two_builder_calls_is_replayed(monkeypatch):
+ """Up to the SELECTED call: a validation call above a mutation of the source
+ table made the probe stop early and build the exports from stale data."""
+ lines = REAL_MAPPER.splitlines(True)
+ insert = next(
+ i
+ for i, line in enumerate(lines)
+ if line.rstrip().endswith("= build_mappers(__INT_TO_FLOAT_MAPPER)")
+ )
+ while insert > 0 and not lines[insert - 1].rstrip().endswith((")", ":", "}", "]")):
+ insert -= 1
+ staged = "".join(
+ lines[:insert]
+ + [
+ "_checked = build_mappers(__INT_TO_FLOAT_MAPPER)\n",
+ '__INT_TO_FLOAT_MAPPER.update({"vendor/between-bnb-4bit": ("vendor/between",)})\n',
+ ]
+ + lines[insert:]
+ )
+ with _serving(staged, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ assert any(
+ "vendor/between" in str(key) for table in tables for key in table
+ ), "a mutation between the validation call and the real one was dropped"
+
+
+def test_builder_aliases_land_at_the_export_producing_call(monkeypatch):
+ """Where the exports are BUILT: applying them at the first builder call put them
+ above a rebind written between the two, which wiped them."""
+ lines = REAL_MAPPER.splitlines(True)
+ body = next(i for i, line in enumerate(lines) if line.startswith("def build_mappers(")) + 1
+ added = (
+ lines[:body]
+ + [' _add_with_lower(MAP_TO_UNSLOTH_16bit, "vendor/late-alias", "unsloth/late-alias")\n']
+ + lines[body:]
+ )
+ insert = next(
+ i
+ for i, line in enumerate(added)
+ if line.rstrip().endswith("= build_mappers(__INT_TO_FLOAT_MAPPER)")
+ )
+ while insert > 0 and not added[insert - 1].rstrip().endswith((")", ":", "}", "]")):
+ insert -= 1
+ staged = "".join(
+ added[:insert]
+ + [
+ "_checked = build_mappers(__INT_TO_FLOAT_MAPPER)\n",
+ "MAP_TO_UNSLOTH_16bit = {}\n",
+ ]
+ + added[insert:]
+ )
+ with _serving(staged, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ assert any(
+ table.get("vendor/late-alias") == "unsloth/late-alias"
+ for table in tables
+ if isinstance(table, dict)
+ ), "the builder's aliases were applied before a rebind that wiped them"
+
+
+_EXPORT_BUILD = (
+ "(\n"
+ " INT_TO_FLOAT_MAPPER,\n"
+ " FLOAT_TO_INT_MAPPER,\n"
+ " MAP_TO_UNSLOTH_16bit,\n"
+ " FLOAT_TO_FP8_BLOCK_MAPPER,\n"
+ " FLOAT_TO_FP8_ROW_MAPPER,\n"
+ ") = build_mappers(__INT_TO_FLOAT_MAPPER)\n"
+)
+
+
+def _above_the_builder(lines):
+ """The index of the line that opens the export-producing assignment."""
+ insert = next(
+ i
+ for i, line in enumerate(lines)
+ if line.rstrip().endswith("= build_mappers(__INT_TO_FLOAT_MAPPER)")
+ )
+ while insert > 0 and not lines[insert - 1].rstrip().endswith((")", ":", "}", "]")):
+ insert -= 1
+ return insert
+
+
+def test_a_rebuild_drops_a_mutation_made_before_it(monkeypatch):
+ """The second build REPLACES the tables, so an entry added between the two goes."""
+ lines = REAL_MAPPER.splitlines(True)
+ insert = _above_the_builder(lines)
+ staged = "".join(
+ lines[:insert]
+ + [
+ _EXPORT_BUILD,
+ 'FLOAT_TO_FP8_ROW_MAPPER["vendor/stale"] = "unsloth/stale-row"\n',
+ ]
+ + lines[insert:]
+ )
+ with _serving(staged, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ assert not any(
+ "vendor/stale" in table for table in tables if isinstance(table, dict)
+ ), "a mutation the later rebuild replaced was still reported as installed"
+
+
+def test_a_mutation_above_a_class_shadow_still_counts(monkeypatch):
+ """The shadow starts where the class binds the name, not at the suite's first line."""
+ lines = REAL_MAPPER.splitlines(True)
+ staged = "".join(
+ lines
+ + [
+ "class _Late:\n",
+ ' FLOAT_TO_FP8_ROW_MAPPER["vendor/live"] = "unsloth/live-row"\n',
+ " FLOAT_TO_FP8_ROW_MAPPER = {}\n",
+ ]
+ )
+ with _serving(staged, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ assert any(
+ table.get("vendor/live") == "unsloth/live-row"
+ for table in tables
+ if isinstance(table, dict)
+ ), "an entry installed before the class bound the name was dropped"
+
+
+# How mapper.py looks on any release older than `build_mappers`: the five exports are
+# initialised empty and filled by a module-scope loop the installed builder reproduces.
+_NO_BUILDER_MAPPER = (
+ '__INT_TO_FLOAT_MAPPER = {"vendor/x-bnb-4bit": ("vendor/x",)}\n'
+ "INT_TO_FLOAT_MAPPER = {}\n"
+ "FLOAT_TO_INT_MAPPER = {}\n"
+ "MAP_TO_UNSLOTH_16bit = {}\n"
+ "FLOAT_TO_FP8_BLOCK_MAPPER = {}\n"
+ "FLOAT_TO_FP8_ROW_MAPPER = {}\n"
+ "for key, values in __INT_TO_FLOAT_MAPPER.items():\n"
+ " INT_TO_FLOAT_MAPPER[key] = values[0]\n"
+)
+
+
+def test_a_mapper_without_a_builder_still_reports_its_models(monkeypatch):
+ """The empty initialisers above a fill loop are not the module clearing the
+ tables: reading them as clears emptied all five and the upgrade notice died."""
+ with _serving(_NO_BUILDER_MAPPER, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ assert any(table for table in tables), "the probe reported no models at all"
+ assert any(
+ "vendor/x" in str(key) or "vendor/x" in str(value)
+ for table in tables
+ if isinstance(table, dict)
+ for key, value in table.items()
+ ), "the source table's entry did not reach the exported tables"
+
+
+def test_a_nonempty_rebind_still_replaces_the_table(monkeypatch):
+ """Only the EMPTY literal is an initialiser; a real one still replaces."""
+ staged = _NO_BUILDER_MAPPER + 'INT_TO_FLOAT_MAPPER = {"vendor/only": "unsloth/only"}\n'
+ with _serving(staged, monkeypatch):
+ tables = loader_utils._get_new_mapper()
+ assert tables[0] == {"vendor/only": "unsloth/only"}, tables[0]
+
+
+def test_the_upgrade_notice_fires_for_a_model_only_the_newer_mapper_knows(monkeypatch):
+ """End to end: an unmapped name plus a newer mapper that maps it must raise."""
+ staged = REAL_MAPPER.replace(
+ "__INT_TO_FLOAT_MAPPER = \\\n{\n",
+ "__INT_TO_FLOAT_MAPPER = \\\n{\n"
+ ' "vendor/brand-new-bnb-4bit": ("vendor/brand-new",),\n',
+ 1,
+ )
+ assert staged != REAL_MAPPER, "the source table header moved"
+ monkeypatch.setattr(loader_utils, "_env_says_offline", lambda: False)
+ with _serving(staged, monkeypatch):
+ with pytest.raises(NotImplementedError, match = "not supported in your current"):
+ loader_utils.get_model_name("vendor/brand-new", load_in_4bit = True)
diff --git a/tests/security/test_security_suite_stays_import_light.py b/tests/security/test_security_suite_stays_import_light.py
new file mode 100644
index 00000000000..0e9e0eaa948
--- /dev/null
+++ b/tests/security/test_security_suite_stays_import_light.py
@@ -0,0 +1,727 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""`workflow-trigger-lint.yml` runs `tests/security` on a four-package runner.
+
+That job has no paths filter, and keeping it cheap is what lets it stay unfiltered, so
+a file there may not import anything in HEAVY at module scope unless the workflow
+`--ignore`s it. The failure is quiet: under `-n 4` xdist does not abort on a collection
+error, so the job stays green while that file's tests stop running entirely.
+"""
+
+import ast
+import pathlib
+import re
+
+import yaml
+
+
+HEAVY = {"torch", "transformers", "numpy", "unsloth", "unsloth_zoo", "peft", "trl"}
+
+_HERE = pathlib.Path(__file__).resolve().parent
+_REPO = _HERE.parent.parent
+_WORKFLOW = _REPO / ".github" / "workflows" / "workflow-trigger-lint.yml"
+
+
+def _constant_truth(test):
+ """True/False for a statically decidable condition, else None."""
+ if isinstance(test, ast.Constant):
+ return bool(test.value)
+ if isinstance(test, ast.UnaryOp) and isinstance(test.op, ast.Not):
+ inner = _constant_truth(test.operand)
+ return None if inner is None else not inner
+ return None
+
+
+def _own_expressions(node):
+ """Every expression node belonging to `node` itself, not to a body it holds.
+ Lambdas are pruned by EXPANSION, since a lambda DEFAULT really does load."""
+
+ def _expansion(current):
+ if isinstance(current, ast.Lambda):
+ arguments = current.args
+ return arguments.defaults + [d for d in arguments.kw_defaults if d is not None]
+ return list(ast.iter_child_nodes(current))
+
+ pending = [child for child in _expansion(node) if isinstance(child, ast.expr)]
+ while pending:
+ current = pending.pop()
+ yield current
+ for child in _expansion(current):
+ if isinstance(child, ast.expr):
+ pending.append(child)
+
+
+def _module_level_statements(body):
+ """Statements that run at import time, including inside module-level control flow.
+ Function bodies are excluded; a CLASS body is not, since it runs at import."""
+ for node in body:
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ # The BODY is deferred; decorators, defaults, annotations and bases are
+ # evaluated at import. Wrapped in an `Expr` for the walker below.
+ for part in _definition_time_expressions(node):
+ yield ast.Expr(value = part)
+ if isinstance(node, ast.ClassDef):
+ yield from _module_level_statements(node.body)
+ continue
+ yield node
+ if isinstance(node, ast.If) and isinstance(node.test, (ast.Constant, ast.UnaryOp)):
+ decided = _constant_truth(node.test)
+ if decided is not None:
+ # `if False: import torch` never runs, so it needs no ignore entry.
+ yield from _module_level_statements(node.body if decided else node.orelse)
+ continue
+ for field in ("body", "orelse", "finalbody", "handlers"):
+ for child in getattr(node, field, []) or []:
+ if isinstance(child, ast.ExceptHandler):
+ yield from _module_level_statements(child.body)
+ elif isinstance(child, ast.stmt):
+ yield from _module_level_statements([child])
+ # `match` keeps its suites under `cases`, not under the fields above.
+ for case in getattr(node, "cases", []) or []:
+ yield from _module_level_statements(case.body)
+
+
+def _definition_time_expressions(node):
+ """The parts of a `def`/`class` header that run at import time."""
+ yield from node.decorator_list
+ if isinstance(node, ast.ClassDef):
+ yield from node.bases
+ for keyword in node.keywords:
+ yield keyword.value
+ return
+ arguments = node.args
+ yield from arguments.defaults
+ yield from (default for default in arguments.kw_defaults if default is not None)
+ for argument in (
+ *arguments.posonlyargs,
+ *arguments.args,
+ *arguments.kwonlyargs,
+ arguments.vararg,
+ arguments.kwarg,
+ ):
+ if argument is not None and argument.annotation is not None:
+ yield argument.annotation
+ if node.returns is not None:
+ yield node.returns
+
+
+# Helpers that load with no `ast.Import` node, and the module each is imported FROM,
+# since a rename makes the spelling at the call site insufficient.
+_LOADER_ORIGINS = {
+ "import_module": "importlib",
+ "__import__": "builtins",
+ "importorskip": "pytest",
+}
+
+
+_ALIAS_ROUNDS = 8
+
+
+_ALIAS_SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)
+
+
+def _scope_bindings(scope):
+ """The import and assignment nodes written directly in this scope, not `ast.walk`:
+ a nested `def`'s bindings belong to that scope rather than to this one."""
+ found = []
+ pending = list(ast.iter_child_nodes(scope))
+ while pending:
+ current = pending.pop()
+ if isinstance(current, _ALIAS_SCOPES):
+ continue
+ if isinstance(current, (ast.ImportFrom, ast.Assign)):
+ found.append(current)
+ pending.extend(ast.iter_child_nodes(current))
+ return found
+
+
+def _settled_aliases(bindings, inherited):
+ """Names bound to one of those helpers, by `from <origin> import <helper> as
+ <alias>` or `alias = <helper>`. Nothing else is guessed at."""
+ # alias -> the helper it NAMES, so a renamed `import_module` is not read as a
+ # renamed `importorskip`. Last binding wins, and a binding to a non-loader takes
+ # the name out. Repeated until settled, for a chain written out of order.
+ aliases: dict = dict(inherited)
+ for _round in range(_ALIAS_ROUNDS):
+ previous = aliases
+ aliases = dict(inherited)
+ for node in sorted(
+ bindings,
+ key = lambda child: (getattr(child, "lineno", 0), getattr(child, "col_offset", 0)),
+ ):
+ if isinstance(node, ast.ImportFrom):
+ if node.level:
+ continue
+ for alias in node.names:
+ bound = alias.asname or alias.name
+ if _LOADER_ORIGINS.get(alias.name) == node.module:
+ aliases[bound] = alias.name
+ else:
+ aliases.pop(bound, None)
+ continue
+ if len(node.targets) != 1 or not isinstance(node.targets[0], ast.Name):
+ continue
+ target, value = node.targets[0], node.value
+ held = None
+ if isinstance(value, ast.Attribute):
+ owner = value.value.id if isinstance(value.value, ast.Name) else None
+ if _LOADER_ORIGINS.get(value.attr) == owner:
+ held = value.attr
+ elif isinstance(value, ast.Name):
+ if value.id in _LOADER_ORIGINS:
+ held = value.id
+ elif value.id in previous:
+ held = previous[value.id]
+ if held is None:
+ aliases.pop(target.id, None)
+ else:
+ aliases[target.id] = held
+ if aliases == previous:
+ break
+ return aliases
+
+
+def _alias_scopes(tree):
+ """One alias table per lexical scope, each built on its enclosing one: a file-wide
+ table let a binding in one function decide how an unrelated call was read."""
+ scopes: dict = {}
+
+ def visit(scope, inherited):
+ table = _settled_aliases(_scope_bindings(scope), inherited)
+ scopes[id(scope)] = table
+ # A class body's names are invisible to its methods.
+ handed_down = inherited if isinstance(scope, ast.ClassDef) else table
+ pending = list(ast.iter_child_nodes(scope))
+ while pending:
+ current = pending.pop()
+ if isinstance(current, _ALIAS_SCOPES):
+ visit(current, handed_down)
+ continue
+ pending.extend(ast.iter_child_nodes(current))
+
+ visit(tree, {})
+ return scopes
+
+
+def _loader_aliases(tree):
+ """The module-scope alias table, for callers that read module level only."""
+ return _alias_scopes(tree)[id(tree)]
+
+
+def _loader_call_names(call, loaders):
+ """The module names a dynamic loader call names outright, else an empty list.
+ Literal arguments only, positionally or by the keyword each helper documents."""
+ if not isinstance(call, ast.Call):
+ return []
+ function = call.func
+ attribute = (
+ function.attr
+ if isinstance(function, ast.Attribute)
+ else (function.id if isinstance(function, ast.Name) else "")
+ )
+ if attribute not in _LOADER_ORIGINS and attribute not in loaders:
+ return []
+ candidates = list(call.args[:1])
+ for keyword in call.keywords:
+ if keyword.arg in ("modname", "name"):
+ candidates.append(keyword.value)
+ return [
+ first.value
+ for first in candidates
+ if isinstance(first, ast.Constant) and isinstance(first.value, str)
+ ]
+
+
+def _is_importorskip(call, loaders):
+ """Whether a call is `pytest.importorskip`, under any recorded spelling."""
+ function = call.func
+ attribute = (
+ function.attr
+ if isinstance(function, ast.Attribute)
+ else (function.id if isinstance(function, ast.Name) else "")
+ )
+ return _is_pytest_skip(attribute, loaders)
+
+
+def _is_pytest_skip(attribute, loaders) -> bool:
+ """Whether this callee is `pytest.importorskip`, under any recorded spelling."""
+ if attribute == "importorskip":
+ return True
+ return loaders.get(attribute) == "importorskip"
+
+
+def _module_level_heavy_imports(path):
+ """Top-level import names only. An import inside a function is paid lazily."""
+ tree = ast.parse(path.read_text(encoding = "utf-8"))
+ loaders = _loader_aliases(tree)
+ found = set()
+ for node in _module_level_statements(tree.body):
+ names = []
+ if isinstance(node, ast.Import):
+ names = [alias.name for alias in node.names]
+ elif isinstance(node, ast.ImportFrom):
+ names = [node.module or ""] if node.level == 0 else []
+ else:
+ # `importorskip` SKIPS the whole file during collection at module scope.
+ for call in _own_expressions(node):
+ names.extend(_loader_call_names(call, loaders))
+ for name in names:
+ root = name.split(".")[0]
+ if root in HEAVY:
+ found.add(root)
+ return found
+
+
+def _body_level_heavy_imports(path):
+ """Heavy dependencies a test BODY imports unconditionally. A body-level
+ `importorskip` skips only that test, so unlike at module scope it does not count."""
+ tree = ast.parse(path.read_text(encoding = "utf-8"))
+ scopes = _alias_scopes(tree)
+ module_loaders = scopes[id(tree)]
+ found = set()
+ for node in ast.walk(tree):
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ # This body's OWN table; another function's `load` says nothing about it.
+ loaders = scopes.get(id(node), module_loaders)
+ skipped = _guarded_roots(node, loaders)
+ for child in ast.walk(node):
+ names = []
+ if isinstance(child, ast.Import):
+ names = [alias.name for alias in child.names]
+ elif isinstance(child, ast.ImportFrom) and not child.level:
+ names = [child.module or ""]
+ elif isinstance(child, ast.Call):
+ if not _is_importorskip(child, loaders):
+ names = _loader_call_names(child, loaders)
+ for name in names:
+ root = name.split(".")[0]
+ if root in HEAVY and root not in skipped:
+ found.add(root)
+ return found
+
+
+def _reaches_a_heavy_dependency(statement, loaders):
+ """Whether a statement loads a heavy dependency, however it spells the load."""
+ for child in ast.walk(statement):
+ names = []
+ if isinstance(child, ast.Import):
+ names = [alias.name for alias in child.names]
+ elif isinstance(child, ast.ImportFrom) and not child.level:
+ names = [child.module or ""]
+ elif isinstance(child, ast.Call) and not _is_importorskip(child, loaders):
+ names = _loader_call_names(child, loaders)
+ if any(name.split(".")[0] in HEAVY for name in names):
+ return True
+ return False
+
+
+def _guarded_roots(node, loaders):
+ """Roots this body skips on before it does anything else with them. Only an
+ UNCONDITIONAL top-level call counts, since one inside an `if` may not run."""
+ roots = set()
+ for statement in node.body:
+ held = None
+ if isinstance(statement, ast.Expr):
+ held = statement.value
+ elif isinstance(statement, ast.Assign):
+ held = statement.value
+ elif isinstance(statement, ast.AnnAssign):
+ held = statement.value
+ if not isinstance(held, ast.Call):
+ # An import ABOVE the guard is reached first, so the scan stops here.
+ if _reaches_a_heavy_dependency(statement, loaders):
+ break
+ continue
+ call = held
+ function = call.func
+ attribute = (
+ function.attr
+ if isinstance(function, ast.Attribute)
+ else (function.id if isinstance(function, ast.Name) else "")
+ )
+ # The alias's ORIGIN decides: an importlib alias lives in `loaders` too.
+ if not _is_pytest_skip(attribute, loaders):
+ # The same stop, for calls: a non-guard call may be the load itself.
+ if _reaches_a_heavy_dependency(statement, loaders):
+ break
+ continue
+ candidates = list(call.args[:1])
+ for keyword in call.keywords:
+ if keyword.arg == "modname":
+ candidates.append(keyword.value)
+ for first in candidates:
+ if isinstance(first, ast.Constant) and isinstance(first.value, str):
+ roots.add(first.value.split(".")[0])
+ return roots
+
+
+def _needs_the_heavy_runner(path):
+ """Either kind of import: one breaks collection there, the other breaks the run."""
+ return _module_level_heavy_imports(path) | _body_level_heavy_imports(path)
+
+
+def _ignored_by_the_workflow():
+ text = _WORKFLOW.read_text(encoding = "utf-8")
+ return {
+ pathlib.PurePosixPath(m).name
+ for m in re.findall(r"--ignore=(tests/security/[\w./-]+\.py)", text)
+ }
+
+
+def test_the_workflow_still_runs_the_security_suite():
+ """Guards the guard: if the step stops naming the suite, the rest is vacuous."""
+ assert _WORKFLOW.exists(), _WORKFLOW
+ assert "tests/security" in _WORKFLOW.read_text(encoding = "utf-8")
+
+
+def test_heavy_imports_are_declared_to_the_light_runner():
+ ignored = _ignored_by_the_workflow()
+ offenders = {}
+ # conftest.py and __init__.py too: no per-file --ignore can cover them.
+ support = [p for p in (_HERE / "conftest.py", _HERE / "__init__.py") if p.exists()]
+ for path in sorted(_HERE.glob("test_*.py")) + support:
+ heavy = _module_level_heavy_imports(path)
+ if heavy and (path.name not in ignored or path in support):
+ offenders[path.name] = sorted(heavy)
+ assert not offenders, (
+ "these tests/security files import a runtime dependency at module scope but "
+ f"are not in the workflow's --ignore list, so they will error during collection "
+ f"on the four-package runner and then silently not run: {offenders}. Either "
+ "move the import inside the test, or add --ignore for the file in "
+ ".github/workflows/workflow-trigger-lint.yml."
+ )
+
+
+def test_the_ignore_list_has_no_stale_entries():
+ """An ignore for a file that no longer needs it hides the file for no reason."""
+ stale = []
+ for name in sorted(_ignored_by_the_workflow()):
+ path = _HERE / name
+ if not path.exists():
+ stale.append(f"{name} (no such file)")
+ elif not _needs_the_heavy_runner(path):
+ stale.append(f"{name} (no longer imports anything heavy)")
+ assert not stale, f"drop these from --ignore: {stale}"
+
+
+def test_a_body_level_heavy_import_also_needs_the_redirect():
+ """The light runner RUNS these tests, so a body import is red there too."""
+ sample = _HERE / "test_inherited_custom_dtype_is_neutralized.py"
+ if not sample.exists():
+ pytest.skip("the suite this pins has moved")
+ assert not _module_level_heavy_imports(sample), "module scope should stay clean"
+ assert _body_level_heavy_imports(sample), "its bodies do import a heavy dependency"
+ assert sample.name in _ignored_by_the_workflow()
+
+
+def test_the_guard_is_not_vacuous():
+ """The list must actually be non-empty, or the two tests above prove nothing."""
+ ignored = _ignored_by_the_workflow()
+ assert ignored, "the workflow names no --ignore, so this suite is not being checked"
+ with_heavy = [path.name for path in _HERE.glob("test_*.py") if _needs_the_heavy_runner(path)]
+ assert with_heavy, "no file imports a heavy dep, so the ignore list should be empty"
+
+
+def test_a_renamed_loader_helper_is_still_recognised(tmp_path):
+ """Recognised by the name it was IMPORTED under, not the spelling at the call."""
+ spellings = {
+ "aliased importlib helper": 'from importlib import import_module as load\ntorch = load("torch")\n',
+ "aliased builtin": 'from builtins import __import__ as bring\ntorch = bring("torch")\n',
+ "aliased importorskip": 'from pytest import importorskip as need\ntorch = need("torch")\n',
+ }
+ for description, source in spellings.items():
+ sample = tmp_path / "sample.py"
+ sample.write_text(source)
+ assert _module_level_heavy_imports(sample) == {"torch"}, description
+
+
+def test_an_assignment_alias_of_a_loader_is_still_recognised(tmp_path):
+ """`load = importlib.import_module` is the same helper under another name."""
+ spellings = {
+ "attribute assignment": 'import importlib\nload = importlib.import_module\ntorch = load("torch")\n',
+ "importorskip by assignment": 'import pytest\nneed = pytest.importorskip\ntorch = need("torch")\n',
+ "chained through an import alias": 'from importlib import import_module as first\nsecond = first\ntorch = second("torch")\n',
+ }
+ for description, source in spellings.items():
+ sample = tmp_path / "sample.py"
+ sample.write_text(source)
+ assert _module_level_heavy_imports(sample) == {"torch"}, description
+
+
+def test_a_body_that_skips_first_does_not_redirect_the_file(tmp_path):
+ """`importorskip` then `import` never reaches the import on the light runner; the
+ third case pins that a guard which may not run does not count."""
+ cases = {
+ 'import pytest\n\n\ndef t():\n pytest.importorskip("torch")\n import torch\n': set(),
+ 'from pytest import importorskip as need\n\n\ndef t():\n need("torch")\n import torch\n': set(),
+ 'import pytest\n\n\ndef t():\n if 0:\n pytest.importorskip("torch")\n import torch\n': {
+ "torch"
+ },
+ "def t():\n import torch\n": {"torch"},
+ }
+ for source, expected in cases.items():
+ sample = tmp_path / "sample.py"
+ sample.write_text(source)
+ assert _body_level_heavy_imports(sample) == expected, source
+
+
+def test_a_guard_after_the_import_does_not_count(tmp_path):
+ """The light runner reaches the import first and fails there."""
+ cases = {
+ 'import pytest\n\n\ndef t():\n import torch\n pytest.importorskip("torch")\n': {
+ "torch"
+ },
+ 'import pytest\n\n\ndef t():\n pytest.importorskip("torch")\n import torch\n': set(),
+ 'import pytest\n\n\ndef t():\n x = 1\n pytest.importorskip("torch")\n import torch\n': set(),
+ }
+ for source, expected in cases.items():
+ sample = tmp_path / "sample.py"
+ sample.write_text(source)
+ assert _body_level_heavy_imports(sample) == expected, source
+
+
+def test_a_dynamic_import_inside_a_body_also_needs_the_redirect(tmp_path):
+ """A body can load a dependency with no `Import` node at all; `importorskip` is
+ still exempt, since it skips that one test rather than erroring."""
+ cases = {
+ 'import importlib\n\n\ndef t():\n importlib.import_module("torch")\n': {"torch"},
+ 'from importlib import import_module\n\n\ndef t():\n import_module("torch")\n': {
+ "torch"
+ },
+ 'def t():\n __import__("torch")\n': {"torch"},
+ 'import importlib\n\n\ndef t():\n importlib.import_module(name = "torch")\n': {"torch"},
+ 'import pytest\n\n\ndef t():\n pytest.importorskip("torch")\n': set(),
+ "import importlib\n\n\ndef t():\n importlib.import_module(picked)\n": set(),
+ }
+ for source, expected in cases.items():
+ sample = tmp_path / "sample.py"
+ sample.write_text(source)
+ assert _body_level_heavy_imports(sample) == expected, source
+
+
+def test_a_renamed_importlib_alias_is_not_a_skip_guard(tmp_path):
+ """Both helpers can be renamed, and only the pytest one suppresses the dep."""
+ cases = {
+ 'from importlib import import_module as load\n\n\ndef t():\n load("torch")\n': {"torch"},
+ 'from pytest import importorskip as load\n\n\ndef t():\n load("torch")\n': set(),
+ 'from importlib import import_module as load\n\n\ndef t():\n load("torch")\n import torch\n': {
+ "torch"
+ },
+ }
+ for source, expected in cases.items():
+ sample = tmp_path / "sample.py"
+ sample.write_text(source)
+ assert _body_level_heavy_imports(sample) == expected, source
+
+
+def test_every_ignored_suite_runs_somewhere_else():
+ """An --ignore must be a redirect, not a deletion: each ignored file has to be
+ named by some workflow that is not the ignoring one."""
+ ignored = _ignored_by_the_workflow()
+ assert ignored, "no suite is ignored any more, so this guard has nothing to check"
+
+ # By STEP: the redirect job sits in this same workflow.
+ elsewhere = {}
+ for path in sorted(_WORKFLOW.parent.glob("*.yml")):
+ document = yaml.safe_load(path.read_text(encoding = "utf-8")) or {}
+ for job in (document.get("jobs") or {}).values():
+ for step in (job or {}).get("steps") or []:
+ command = str((step or {}).get("run", ""))
+ for name in ignored:
+ if name in command and f"--ignore=tests/security/{name}" not in command:
+ elsewhere.setdefault(name, []).append(path.name)
+
+ missing = sorted(name for name in ignored if name not in elsewhere)
+ assert not missing, (
+ f"ignored by {_WORKFLOW.name} and run by no other step: {missing}. "
+ f"An --ignore has to move a suite to a job that can install its "
+ f"dependencies, not drop it out of CI."
+ )
+
+
+def _redirect_workflow() -> pathlib.Path:
+ """The workflow file whose steps run the ignored suites."""
+ ignored = _ignored_by_the_workflow()
+ for path in sorted(_WORKFLOW.parent.glob("*.yml")):
+ document = yaml.safe_load(path.read_text(encoding = "utf-8")) or {}
+ for job in (document.get("jobs") or {}).values():
+ for step in (job or {}).get("steps") or []:
+ command = str((step or {}).get("run", ""))
+ if any(
+ name in command and f"--ignore=tests/security/{name}" not in command
+ for name in ignored
+ ):
+ return path
+ raise AssertionError("no workflow step runs the ignored suites")
+
+
+def test_the_redirect_job_is_triggered_by_what_it_protects():
+ """A job that only runs after the merge is not a gate: if the redirect workflow's
+ path filter omits the code the suites cover, a PR touching it skips the job."""
+ host = _redirect_workflow()
+ document = yaml.safe_load(host.read_text(encoding = "utf-8")) or {}
+ triggers = document.get(True, document.get("on")) or {}
+ on_pull_request = triggers.get("pull_request") if isinstance(triggers, dict) else None
+ if not (
+ isinstance(on_pull_request, dict)
+ and (on_pull_request.get("paths") or on_pull_request.get("paths-ignore"))
+ ):
+ return
+ text = host.read_text(encoding = "utf-8")
+
+ # Taken from the suites, so adding a module to one cannot leave this stale.
+ protected = set()
+ for name in sorted(_ignored_by_the_workflow()):
+ path = _HERE / name
+ if not path.exists():
+ continue
+ for node in ast.walk(ast.parse(path.read_text(encoding = "utf-8"))):
+ if isinstance(node, ast.ImportFrom) and node.module:
+ if node.module == "unsloth.models":
+ protected.update(f"{alias.name}.py" for alias in node.names)
+ elif node.module.startswith("unsloth.models."):
+ protected.add(node.module.split(".")[-1] + ".py")
+ elif isinstance(node, ast.Import):
+ for alias in node.names:
+ if alias.name.startswith("unsloth.models."):
+ protected.add(alias.name.split(".")[-1] + ".py")
+ # `__import__("unsloth.models.loader", ...)` too: a suite reads it so.
+ if isinstance(node, ast.Call) and node.args:
+ function = node.func
+ name = (
+ function.attr
+ if isinstance(function, ast.Attribute)
+ else (function.id if isinstance(function, ast.Name) else "")
+ )
+ if name in ("__import__", "import_module"):
+ first = node.args[0]
+ if isinstance(first, ast.Constant) and isinstance(first.value, str):
+ if first.value.startswith("unsloth.models."):
+ protected.add(first.value.split(".")[-1] + ".py")
+
+ assert protected, "the ignored suites no longer import unsloth.models, so this is vacuous"
+ missing = sorted(name for name in protected if f"unsloth/models/{name}" not in text)
+ assert not missing, (
+ f"{host.name} runs the suites that cover these modules but is not "
+ f"triggered by changes to them: {missing}. A PR touching only that code would "
+ f"skip the job and the suites would run only after merge."
+ )
+
+
+def test_a_lambda_body_is_not_a_module_level_import(tmp_path):
+ """A `lambda` runs when it is CALLED, and collection never calls this one."""
+ spellings = {
+ "assigned lambda": 'import pytest\nunused = lambda: pytest.importorskip("torch")\n',
+ "lambda in a list": 'import pytest\nunused = [lambda: pytest.importorskip("torch")]\n',
+ "lambda returning a lambda": (
+ 'import pytest\nunused = lambda: (lambda: pytest.importorskip("torch"))\n'
+ ),
+ "default of a lambda inside a lambda body": (
+ "import pytest\n" 'unused = lambda: (lambda x = pytest.importorskip("torch"): x)\n'
+ ),
+ }
+ for description, source in spellings.items():
+ sample = tmp_path / "sample.py"
+ sample.write_text(source)
+ assert _module_level_heavy_imports(sample) == set(), description
+
+
+def test_a_lambda_default_is_still_a_module_level_import(tmp_path):
+ """The half of a lambda that is NOT deferred: a default is evaluated where the
+ lambda is written, so it loads torch during collection."""
+ spellings = {
+ "positional default": 'import pytest\nunused = lambda x = pytest.importorskip("torch"): x\n',
+ "keyword-only default": (
+ 'import pytest\nunused = lambda *, x = pytest.importorskip("torch"): x\n'
+ ),
+ "lambda as another lambda's default": (
+ "import pytest\n"
+ 'unused = lambda x = (lambda y = pytest.importorskip("torch"): y): x\n'
+ ),
+ }
+ for description, source in spellings.items():
+ sample = tmp_path / "sample.py"
+ sample.write_text(source)
+ assert _module_level_heavy_imports(sample) == {"torch"}, description
+
+
+def test_a_later_assignment_replaces_an_imported_alias(tmp_path):
+ """`load` stops being a skip guard once it is assigned the real importer. An alias recorded from an import could never be replaced, so a call through the reassigned name was still read as a pytest skip and the file stayed on the runner where that call fails."""
+ sample = tmp_path / "sample.py"
+ sample.write_text(
+ "from pytest import importorskip as load\n"
+ "import importlib\n"
+ "load = importlib.import_module\n"
+ "def test_it():\n"
+ ' torch = load("torch")\n'
+ )
+ assert _body_level_heavy_imports(sample) == {"torch"}
+
+
+def test_an_imported_alias_still_wins_where_it_is_written_last(tmp_path):
+ """The other direction: source order decides, so the import can replace too."""
+ sample = tmp_path / "sample.py"
+ sample.write_text(
+ "import importlib\n"
+ "load = importlib.import_module\n"
+ "from pytest import importorskip as load\n"
+ "def test_it():\n"
+ ' load("torch")\n'
+ " import torch\n"
+ )
+ assert _body_level_heavy_imports(sample) == set()
+
+
+def test_an_assigned_skip_guard_still_guards(tmp_path):
+ """`torch = pytest.importorskip("torch")` skips exactly as the bare call does."""
+ sample = tmp_path / "sample.py"
+ sample.write_text(
+ "import pytest\n"
+ "def test_it():\n"
+ ' torch = pytest.importorskip("torch")\n'
+ " from torch import nn\n"
+ " assert nn is not None\n"
+ )
+ assert _body_level_heavy_imports(sample) == set()
+
+
+def test_an_import_before_the_assigned_guard_is_still_reported(tmp_path):
+ """Order still decides: an import above the guard is reached first."""
+ sample = tmp_path / "sample.py"
+ sample.write_text(
+ "import pytest\n"
+ "def test_it():\n"
+ " from torch import nn\n"
+ ' torch = pytest.importorskip("torch")\n'
+ " assert nn is not None\n"
+ )
+ assert _body_level_heavy_imports(sample) == {"torch"}
+
+
+def test_a_dynamic_load_before_the_guard_is_still_reported(tmp_path):
+ """A dynamic load above the skip is reached first, exactly as an `import` is."""
+ sample = tmp_path / "sample.py"
+ sample.write_text(
+ "import importlib\n"
+ "import pytest\n"
+ "def test_it():\n"
+ ' importlib.import_module("torch")\n'
+ ' pytest.importorskip("torch")\n'
+ )
+ assert _body_level_heavy_imports(sample) == {"torch"}
+
+
+def test_a_local_alias_does_not_reclassify_another_scope(tmp_path):
+ """A binding inside one function must not relabel a call in an unrelated one."""
+ sample = tmp_path / "sample.py"
+ sample.write_text(
+ "from importlib import import_module as load\n"
+ "def test_it():\n"
+ ' load("torch")\n'
+ "def helper():\n"
+ " from pytest import importorskip as load\n"
+ ' return load("torch")\n'
+ )
+ assert _body_level_heavy_imports(sample) == {"torch"}
diff --git a/tests/test_new_mapper_fetched_fp8.py b/tests/test_new_mapper_fetched_fp8.py
index bdd1b241fa8..903f5eee887 100644
--- a/tests/test_new_mapper_fetched_fp8.py
+++ b/tests/test_new_mapper_fetched_fp8.py
@@ -1,26 +1,14 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-"""Regression tests for what ``_get_new_mapper`` hands back to the upgrade probe.
-
-``test_new_mapper_no_global_leak.py`` serves the repo's own ``mapper.py`` as both installed
-and fetched source, so it cannot tell a fetched table from a fresh copy of the installed one.
-Two gaps it misses:
-
-1. The probe must answer for an fp8 repo only the FETCHED mapper knows, so an extra ``"8"``
- entry is spliced into the fetched source only. Isolating the exec without returning the
- fetched fp8 tables would silently drop the fp8 half of the upgrade check.
-2. The probe must survive a fetched ``mapper.py`` with no fp8 tables (anything older, or a
- future rename): reading them with ``[]`` raises ``KeyError`` into the bare ``except``,
- taking the 4bit half, the probe's whole purpose, down with it.
-
-Both of the above only reach the block table. The last two tests take the row branch, which
-``load_in_fp8 = True`` plus ``UNSLOTH_HAS_FBGEMM`` selects ahead of block: deleting that branch,
-or dropping ``_resolve_with_mappers``' ``fp8_row`` argument so it falls back to the installed
-table, both leave every other test here green.
-
-``loader_utils`` imports torch, so ast-extract the resolvers and run them against a stubbed
-``requests``, as in ``tests/test_bad_mappings_redirect.py``.
+"""What ``_get_new_mapper`` hands back to the upgrade probe.
+
+``test_new_mapper_no_global_leak.py`` serves the repo's own ``mapper.py`` as both the
+installed and the fetched source, so it cannot tell the two apart. Two gaps: an fp8
+repo only the FETCHED mapper knows, and a fetched file with no fp8 tables at all, where
+reading them with ``[]`` raises ``KeyError`` and takes the 4bit half down with it.
+
+The last two tests take the ROW branch, which nothing else here covers.
"""
import ast
@@ -42,6 +30,12 @@ _ANCHOR = ' "unsloth/Kimi-K2-Instruct-BF16" : ('
_ROW_ONLY = "zeta-org/Zeta-9B-Row-Only-FP8"
+def _loader_utils_globals():
+ """The real loader_utils module globals, for anything the stand-in needs verbatim."""
+ import unsloth.models.loader_utils as loader_utils
+ return vars(loader_utils)
+
+
def _mapper_source():
with open(os.path.join(_MODELS, "mapper.py"), encoding = "utf-8") as f:
return f.read()
@@ -70,9 +64,43 @@ def _without_fp8_tables(source):
)
+class _FakeRaw:
+ """`read1` over a fixed list of chunks, returning b"" at the end."""
+
+ def __init__(self, chunks):
+ self._chunks = iter(chunks)
+
+ def read1(self, amount = -1):
+ return next(self._chunks, b"")
+
+
class _FakeResponse:
- def __init__(self, text):
- self.text = text
+ """The streaming half of `requests.Response`: the probe caps while READING and
+ follows redirects by hand, so a fake without status and headers hides both."""
+
+ def __init__(
+ self,
+ text,
+ chunks = None,
+ status_code = 200,
+ headers = None,
+ ):
+ self.encoding = "utf-8"
+ self.status_code = status_code
+ self.headers = headers or {}
+ self._chunks = chunks if chunks is not None else [text.encode("utf-8")]
+ self._raw = None
+
+ def iter_content(self, chunk_size = 1):
+ yield from self._chunks
+
+ @property
+ def raw(self):
+ """`read1` returns what ONE socket read produced, so the deadline is checked
+ between reads. `iter_content` is kept so the fake matches the real object."""
+ if self._raw is None:
+ self._raw = _FakeRaw(self._chunks)
+ return self._raw
def __enter__(self):
return self
@@ -81,9 +109,16 @@ class _FakeResponse:
return False
-def _install_fake_requests(monkeypatch, text):
+def _install_fake_requests(
+ monkeypatch,
+ text,
+ chunks = None,
+):
module = types.ModuleType("requests")
- module.get = lambda url, timeout = None: _FakeResponse(text)
+ module.compat = types.SimpleNamespace(urljoin = lambda base, url: url)
+ module.get = lambda url, timeout = None, stream = False, allow_redirects = True: (
+ _FakeResponse(text, chunks)
+ )
monkeypatch.setitem(sys.modules, "requests", module)
@@ -99,6 +134,11 @@ def _load_resolver(installed_source):
"""Stand-in for loader_utils' module globals, built from `installed_source`."""
from unsloth_zoo.utils import Version
+ # loader_utils imports this from .mapper; _get_new_mapper derives the fetched tables
+ # with it, so the stand-in globals need it or the probe NameErrors into its own bare
+ # except and returns empty tables.
+ from unsloth.models.mapper import build_mappers
+
mapper_ns = {}
exec(compile(installed_source, "mapper.py", "exec"), mapper_ns)
@@ -108,6 +148,10 @@ def _load_resolver(installed_source):
"MAP_TO_UNSLOTH_16bit": mapper_ns["MAP_TO_UNSLOTH_16bit"],
"FLOAT_TO_FP8_BLOCK_MAPPER": mapper_ns["FLOAT_TO_FP8_BLOCK_MAPPER"],
"FLOAT_TO_FP8_ROW_MAPPER": mapper_ns["FLOAT_TO_FP8_ROW_MAPPER"],
+ "build_mappers": build_mappers,
+ # Imported from loader_utils rather than rebuilt, so a new helper added there
+ # cannot silently drop out of this stand-in and make the probe look broken.
+ "_MAPPER_HELPERS": _loader_utils_globals()["_MAPPER_HELPERS"],
"SUPPORTS_FOURBIT": True,
"transformers_version": Version("4.57.6"),
"Version": Version,
@@ -206,3 +250,34 @@ def test_probe_answers_for_a_row_only_repo_the_fetched_mapper_knows(monkeypatch)
)
assert namespace["FLOAT_TO_FP8_ROW_MAPPER"] is installed_row
+
+
+def test_a_fetched_mapper_that_uses_update_still_installs_its_entries(monkeypatch):
+ """`.update({...})` adds entries exactly as the subscript spelling does; both are
+ asserted, so this cannot pass by the probe reading neither."""
+ installed = _mapper_source()
+ namespace = _load_resolver(installed)
+
+ both = installed + (
+ f"\nFLOAT_TO_FP8_ROW_MAPPER.update({{{_ROW_ONLY.lower()!r}: {_NEW_ROW!r}}})\n"
+ f"FLOAT_TO_FP8_ROW_MAPPER[{_NEW_OFFICIAL.lower()!r}] = {_NEW_ROW!r}\n"
+ )
+ _install_fake_requests(monkeypatch, both)
+
+ fetched = namespace["_get_new_mapper"]()
+ row_table = fetched[4]
+ assert row_table.get(_ROW_ONLY.lower()) == _NEW_ROW, f"update() entry missing: {row_table}"
+ assert row_table.get(_NEW_OFFICIAL.lower()) == _NEW_ROW, f"subscript entry missing: {row_table}"
+
+
+def test_update_on_a_name_the_probe_does_not_export_is_ignored(monkeypatch):
+ """The receiver has to name one of the five tables, or nothing is read from it."""
+ installed = _mapper_source()
+ namespace = _load_resolver(installed)
+
+ _install_fake_requests(
+ monkeypatch,
+ installed + f"\nSOMETHING_ELSE.update({{{_ROW_ONLY.lower()!r}: {_NEW_ROW!r}}})\n",
+ )
+ fetched = namespace["_get_new_mapper"]()
+ assert _ROW_ONLY.lower() not in fetched[4]
diff --git a/tests/test_new_mapper_no_global_leak.py b/tests/test_new_mapper_no_global_leak.py
index 5ec00fba5ac..4c85386cfb4 100644
--- a/tests/test_new_mapper_no_global_leak.py
+++ b/tests/test_new_mapper_no_global_leak.py
@@ -1,26 +1,14 @@
-"""Regression test for ``_get_new_mapper`` leaking into ``loader_utils`` globals.
-
-``get_model_name`` calls ``_get_new_mapper()`` whenever a name misses the local
-tables, purely to answer "would a newer Unsloth support this?". It fetches
-``mapper.py`` from GitHub main, prefixes the three mappers it wants with
-``NEW_``, and ``exec``s the result into ``globals()``.
-
-The slice starts at ``__INT_TO_FLOAT_MAPPER``, so it also carries
-``FLOAT_TO_FP8_BLOCK_MAPPER``/``FLOAT_TO_FP8_ROW_MAPPER`` and the two
-``_add_*`` helpers, and those names are NOT renamed. Exec'ing into
-``globals()`` therefore rebinds the FP8 tables that ``loader_utils`` imported
-from the installed ``mapper``, so every later ``get_model_name(...,
-load_in_fp8 = ...)`` in the process resolves through GitHub main's table
-instead of the installed one. The probe is supposed to read, not to swap the
-installed mappings out from under the caller.
-
-``loader_utils`` imports torch, so ast-extract ``_get_new_mapper`` and run it
-against a stubbed ``requests`` rather than importing unsloth (which needs a GPU).
+"""``_get_new_mapper`` must not leak into ``loader_utils`` globals.
+
+It used to ``exec`` the fetched ``mapper.py`` into ``globals()`` with only three names
+prefixed ``NEW_``, so the unrenamed FP8 tables REBOUND the installed ones for the rest
+of the process. The probe is supposed to read, not to swap the mappings out.
"""
import ast
import os
import sys
+import time
import types
_MODELS = os.path.join(os.path.dirname(__file__), os.pardir, "unsloth", "models")
@@ -32,6 +20,14 @@ def _mapper_source():
def _extract_get_new_mapper(namespace):
+ # loader_utils imports this from .mapper, so the stand-in module globals need it
+ # too. Without it the probe raises NameError into its own bare except and hands
+ # back empty tables, which looks exactly like "the fetch did not run".
+ from unsloth.models.mapper import build_mappers
+ import unsloth.models.loader_utils as loader_utils
+
+ namespace.setdefault("build_mappers", build_mappers)
+ namespace.setdefault("_MAPPER_HELPERS", loader_utils._MAPPER_HELPERS)
with open(os.path.join(_MODELS, "loader_utils.py"), encoding = "utf-8") as f:
tree = ast.parse(f.read())
for node in tree.body:
@@ -41,9 +37,51 @@ def _extract_get_new_mapper(namespace):
raise AssertionError("_get_new_mapper not found in loader_utils.py")
+class _FakeRaw:
+ """`read1` over a fixed list of chunks, returning b"" at the end."""
+
+ def __init__(self, chunks):
+ self._chunks = iter(chunks)
+
+ decode_content = False
+
+ def read1(self, amount = -1):
+ # The probe must ASK for decoding; `requests` only enables it inside
+ # `iter_content`, so a raw read of a gzip response would hand compressed bytes
+ # to `ast.parse`.
+ if not self.decode_content:
+ return b"not-decoded"
+ return next(self._chunks, b"")
+
+
class _FakeResponse:
- def __init__(self, text):
- self.text = text
+ """The streaming half of `requests.Response`: the probe caps while READING and
+ follows redirects by hand, so a fake without status and headers hides both."""
+
+ def __init__(
+ self,
+ text,
+ chunks = None,
+ status_code = 200,
+ headers = None,
+ raw = None,
+ ):
+ self.encoding = "utf-8"
+ self.status_code = status_code
+ self.headers = headers or {}
+ self._chunks = chunks if chunks is not None else [text.encode("utf-8")]
+ self._raw = raw
+
+ def iter_content(self, chunk_size = 1):
+ yield from self._chunks
+
+ @property
+ def raw(self):
+ """`read1` returns what ONE socket read produced, so the deadline is checked
+ between reads. `iter_content` is kept so the fake matches the real object."""
+ if self._raw is None:
+ self._raw = _FakeRaw(self._chunks)
+ return self._raw
def __enter__(self):
return self
@@ -52,9 +90,16 @@ class _FakeResponse:
return False
-def _install_fake_requests(monkeypatch, text):
+def _install_fake_requests(
+ monkeypatch,
+ text,
+ chunks = None,
+):
module = types.ModuleType("requests")
- module.get = lambda url, timeout = None: _FakeResponse(text)
+ module.compat = types.SimpleNamespace(urljoin = lambda base, url: url)
+ module.get = lambda url, timeout = None, stream = False, allow_redirects = True: (
+ _FakeResponse(text, chunks)
+ )
monkeypatch.setitem(sys.modules, "requests", module)
@@ -97,3 +142,127 @@ def test_get_new_mapper_leaves_no_helpers_behind(monkeypatch):
leaked = set(namespace) - before
assert not leaked, f"_get_new_mapper leaked {sorted(leaked)} into its module globals"
+
+
+def test_the_byte_cap_stops_the_read_instead_of_measuring_it_afterwards(monkeypatch):
+ """A cap applied after `requests.get` returns measures what is already in memory;
+ this pins it to the READ, where the probe stops pulling chunks."""
+ served = []
+
+ def endless():
+ while True:
+ served.append(1)
+ if len(served) > 5_000: # the probe should have stopped long before this
+ raise AssertionError("the probe kept reading past its cap")
+ yield b"x" * 65_536
+
+ _install_fake_requests(monkeypatch, "", chunks = endless())
+ get_new_mapper = _extract_get_new_mapper({})
+
+ assert get_new_mapper() == ({}, {}, {}, {}, {})
+ # The cap at 64KB a chunk is a few dozen chunks; anything near the guard above means the
+ # cap is not being enforced while reading.
+ assert len(served) < 200, len(served)
+
+
+def test_a_redirect_body_is_bounded_too(monkeypatch):
+ """`requests` drains an intermediate 3xx body inside `get`, before `stream=True`
+ hands anything to the caller, so a redirect was a way around the cap and the
+ deadline. The probe follows redirects itself for that reason; this pins it."""
+ served = []
+
+ def endless():
+ while True:
+ served.append(1)
+ if len(served) > 5_000:
+ raise AssertionError("the probe kept reading a redirect body past its cap")
+ yield b"x" * 65_536
+
+ # A redirect body must not be read at all, so `served` should stay empty.
+
+ module = types.ModuleType("requests")
+ module.compat = types.SimpleNamespace(urljoin = lambda base, url: url)
+ module.get = lambda url, timeout = None, stream = False, allow_redirects = True: (
+ _FakeResponse(
+ "",
+ chunks = endless(),
+ status_code = 302,
+ headers = {"location": "https://example.invalid/next"},
+ )
+ )
+ monkeypatch.setitem(sys.modules, "requests", module)
+
+ get_new_mapper = _extract_get_new_mapper({})
+ assert get_new_mapper() == ({}, {}, {}, {}, {})
+ assert not served, len(served)
+
+
+def test_a_redirect_loop_ends(monkeypatch):
+ """A peer that redirects forever must not keep the probe going forever."""
+ hops = []
+
+ module = types.ModuleType("requests")
+ module.compat = types.SimpleNamespace(urljoin = lambda base, url: url)
+
+ def get(
+ url,
+ timeout = None,
+ stream = False,
+ allow_redirects = True,
+ ):
+ hops.append(url)
+ assert len(hops) < 50, "the probe followed redirects without a hop limit"
+ return _FakeResponse("", status_code = 302, headers = {"location": url})
+
+ module.get = get
+ monkeypatch.setitem(sys.modules, "requests", module)
+
+ get_new_mapper = _extract_get_new_mapper({})
+ assert get_new_mapper() == ({}, {}, {}, {}, {})
+
+
+def test_a_trickled_body_ends_at_the_deadline_not_at_the_chunk_size(monkeypatch):
+ """The per-read check, which is what makes the deadline reachable at all.
+
+ `iter_content` yields only once a whole chunk has ARRIVED and the socket timeout is
+ per read, so the old loop's clock reaches 131_072 seconds before the first check.
+ """
+ clock = {"now": 0.0}
+
+ class _Trickling:
+ """One byte per read at two seconds each, endlessly."""
+
+ encoding = "utf-8"
+ status_code = 200
+ headers: dict = {}
+
+ def iter_content(self, chunk_size = 1):
+ while True:
+ clock["now"] += 2.0 * chunk_size
+ yield b"x" * chunk_size
+
+ @property
+ def raw(self):
+ return self
+
+ def read1(self, amount = -1):
+ clock["now"] += 2.0
+ return b"x"
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ module = types.ModuleType("requests")
+ module.compat = types.SimpleNamespace(urljoin = lambda base, url: url)
+ module.get = lambda url, timeout = None, stream = False, allow_redirects = True: (_Trickling())
+ monkeypatch.setitem(sys.modules, "requests", module)
+ monkeypatch.setattr(time, "monotonic", lambda: clock["now"])
+
+ get_new_mapper = _extract_get_new_mapper({})
+ assert get_new_mapper() == ({}, {}, {}, {}, {})
+ # A 10s deadline at 2s a read is a handful of reads. A chunked loop would not look
+ # at the clock until 65_536 of them had gone by.
+ assert clock["now"] < 60, clock["now"]
diff --git a/unsloth/models/_custom_dtype.py b/unsloth/models/_custom_dtype.py
new file mode 100644
index 00000000000..5df5b719efe
--- /dev/null
+++ b/unsloth/models/_custom_dtype.py
@@ -0,0 +1,131 @@
+# 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/>.
+
+"""`UNSLOTH_FORCE_CUSTOM_DTYPE` carries executable code in two of its five fields.
+
+Every value unsloth ships is a literal in `models/loader.py` and both readers run in
+the process that set it, so a value this process did not set has no legitimate source
+and its code fields are dropped rather than executed. The wire format is unchanged,
+since `unsloth_zoo` parses the same five fields on its own release schedule.
+"""
+
+__all__ = [
+ "register_custom_dtype",
+ "trusted_custom_dtype",
+ "neutralize_inherited_custom_dtype",
+ "resolve_dtype",
+ "DTYPE_ALIASES",
+]
+
+import os
+
+import torch
+
+# A table instead of `eval`, so the field NAMES a dtype rather than being an
+# arbitrary expression.
+DTYPE_ALIASES = {
+ "None": None,
+ "none": None,
+ "": None,
+ "torch.float16": torch.float16,
+ "torch.bfloat16": torch.bfloat16,
+ "torch.float32": torch.float32,
+ "torch.float64": torch.float64,
+ "float16": torch.float16,
+ "bfloat16": torch.bfloat16,
+ "float32": torch.float32,
+ "float64": torch.float64,
+ "fp16": torch.float16,
+ "bf16": torch.bfloat16,
+ "fp32": torch.float32,
+}
+
+# `unsloth_zoo==2026.8.15`, which this package's floor resolves to, still `eval`s the
+# dtype field, and `eval("fp16")` is a NameError. So a field this package accepts is
+# canonicalised to the one spelling both readers evaluate.
+_CANONICAL_DTYPE_NAMES = {
+ None: "None",
+ torch.float16: "torch.float16",
+ torch.bfloat16: "torch.bfloat16",
+ torch.float32: "torch.float32",
+ torch.float64: "torch.float64",
+}
+
+_ENV_KEY = "UNSLOTH_FORCE_CUSTOM_DTYPE"
+
+# Values this process set. Not cleared: a model can be loaded more than once.
+_REGISTERED = set()
+
+
+def resolve_dtype(text):
+ """Maps a dtype field of `UNSLOTH_FORCE_CUSTOM_DTYPE` onto a torch dtype"""
+ key = str(text).strip()
+ if key not in DTYPE_ALIASES:
+ raise ValueError(
+ f"Unsloth: `{_ENV_KEY}` names an unsupported dtype `{key}`.\n"
+ f"Supported: {sorted(x for x in DTYPE_ALIASES if x)}"
+ )
+ return DTYPE_ALIASES[key]
+
+
+def register_custom_dtype(value):
+ """Sets `UNSLOTH_FORCE_CUSTOM_DTYPE` and records it as ours"""
+ _REGISTERED.add(value)
+ os.environ[_ENV_KEY] = value
+ return value
+
+
+def neutralize_inherited_custom_dtype():
+ """Rewrites an INHERITED `UNSLOTH_FORCE_CUSTOM_DTYPE` so no reader can evaluate it.
+
+ `unsloth_zoo==2026.8.15`, which this package's floor resolves to, still `eval`s the
+ dtype field. The five fields stay: both packages assert on the separator count.
+ """
+ value = os.environ.get(_ENV_KEY, "")
+ if value == "" or value in _REGISTERED:
+ return value
+ if value.count(";") < 4:
+ # Both readers assert on the layout, so this can only crash an unrelated run.
+ os.environ.pop(_ENV_KEY, None)
+ return ""
+ checker, dtype, bnb_compute_dtype, _custom_datatype, _execute_code = value.split(";", 4)
+
+ def named(field):
+ # Empty is what an unset field already looks like to both readers.
+ key = field.strip()
+ if key == "":
+ return ""
+ if key not in DTYPE_ALIASES:
+ return "None"
+ return _CANONICAL_DTYPE_NAMES.get(DTYPE_ALIASES[key], "None")
+
+ # Emptied rather than removed, for the same reason.
+ sanitized = ";".join([checker, named(dtype), named(bnb_compute_dtype), "", ""])
+ os.environ[_ENV_KEY] = sanitized
+ return sanitized
+
+
+def trusted_custom_dtype():
+ """Returns (value, code_is_trusted); False means honour the dtype fields and drop
+ the two code fields."""
+ value = os.environ.get(_ENV_KEY, "")
+ if value == "":
+ return "", False
+ return value, value in _REGISTERED
+
+
+# On import, before either package reads the variable.
+neutralize_inherited_custom_dtype()
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index ab2d041674b..bf6e654d2ce 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -3625,6 +3625,13 @@ def unsloth_compile_transformers(
return_logits = False,
unsloth_force_compile = False,
):
+ # Again here, not only at import: a dotenv or config loader can populate
+ # `UNSLOTH_FORCE_CUSTOM_DTYPE` after this package was imported, and the compiler
+ # below reaches the older `unsloth_zoo` reader that still `eval`s the dtype field.
+ # Idempotent, so a registered or already sanitized value is unchanged.
+ from ._custom_dtype import neutralize_inherited_custom_dtype
+
+ neutralize_inherited_custom_dtype()
if Version(torch_version) < Version("2.4.0"):
print(
"="
diff --git a/unsloth/models/loader.py b/unsloth/models/loader.py
index d276550b03a..c26b7bc52ae 100644
--- a/unsloth/models/loader.py
+++ b/unsloth/models/loader.py
@@ -26,6 +26,7 @@ from ._utils import (
# _is_sdpa_excluded (in _utils) can honor it without a loader -> _utils cycle.
DISABLE_SDPA_MODEL_NAMES,
)
+from ._custom_dtype import register_custom_dtype
from .granite import FastGraniteModel
from .llama import FastLlamaModel, logger, _vllm_will_load_weights
from .mistral import FastMistralModel
@@ -1720,7 +1721,7 @@ class FastModel(FastBaseModel):
"Unsloth: Gemma 3N only works on transformers >= 4.53.0" + LATEST
)
os.environ["UNSLOTH_DISABLE_STATIC_GENERATION"] = "1"
- os.environ["UNSLOTH_FORCE_CUSTOM_DTYPE"] = (
+ register_custom_dtype(
"float16;torch.float16;torch.float16;"
"if name.endswith('norm'): "
"module._pre_set_compute_dtype = torch.float32\n"
@@ -1756,7 +1757,7 @@ class FastModel(FastBaseModel):
elif "csm" in model_types_all:
os.environ["UNSLOTH_COMPILE_DISABLE"] = "partial" # Inference is too slow
os.environ["UNSLOTH_DISABLE_STATIC_GENERATION"] = "1" # Sesame fails
- os.environ["UNSLOTH_FORCE_CUSTOM_DTYPE"] = (
+ register_custom_dtype(
"all;torch.float32;torch.float16;"
"if name.endswith(('_proj', 'fc1', 'fc2', 'codebook', 'head')): module.to(torch.float16)"
";"
@@ -1775,7 +1776,7 @@ class FastModel(FastBaseModel):
elif "falcon_h1" in model_types_all:
# Falcon must use float32 Triton ie TRITON_F32_DEFAULT = 'ieee'
# since Mamba kernels error out on using lower precision
- os.environ["UNSLOTH_FORCE_CUSTOM_DTYPE"] = (
+ register_custom_dtype(
"float16;torch.float32;torch.float16;"
"if name.endswith(('q_proj', 'k_proj', 'v_proj', 'o_proj', 'gate_proj', 'up_proj', 'down_proj', 'head')): module.to(torch.float16)"
";"
@@ -1784,7 +1785,7 @@ class FastModel(FastBaseModel):
elif "nemotron_h" in model_types_all:
# NemotronH (hybrid Mamba-2 + Transformer) uses same Mamba kernels as Falcon-H1
# Mamba kernels need float32 Triton precision
- os.environ["UNSLOTH_FORCE_CUSTOM_DTYPE"] = (
+ register_custom_dtype(
"float16;torch.float32;torch.float16;"
"if name.endswith(('q_proj', 'k_proj', 'v_proj', 'o_proj', 'gate_proj', 'up_proj', 'down_proj', 'head')): module.to(torch.float16)"
";"
@@ -1799,7 +1800,7 @@ class FastModel(FastBaseModel):
if not (load_in_4bit and _bnb_compatible_quant):
# Only upcast MoE biases for MXFP4, not BnB
# Set norms to float32 since anyways they get upcasted to float32
- os.environ["UNSLOTH_FORCE_CUSTOM_DTYPE"] = (
+ register_custom_dtype(
"all;None;None;"
"x = 'gate_up_proj_bias'\n"
"if hasattr(module, x): "
@@ -1814,7 +1815,7 @@ class FastModel(FastBaseModel):
else:
# Set down projection compute dtype to be float32 for float16 machines
# Set norms to float32 since anyways they get upcasted to float32
- os.environ["UNSLOTH_FORCE_CUSTOM_DTYPE"] = (
+ register_custom_dtype(
"torch.float16;torch.bfloat16;torch.float16;"
"if ('down_projs' in name) and hasattr(module, 'weight') and "
"torch.amax(dequantize_module_weight(module)) >= 0:"
diff --git a/unsloth/models/loader_utils.py b/unsloth/models/loader_utils.py
index 6900d586e72..8dc3e743e51 100644
--- a/unsloth/models/loader_utils.py
+++ b/unsloth/models/loader_utils.py
@@ -29,8 +29,20 @@ from .mapper import (
MAP_TO_UNSLOTH_16bit,
FLOAT_TO_FP8_BLOCK_MAPPER,
FLOAT_TO_FP8_ROW_MAPPER,
+ build_mappers,
+ _add_with_lower,
+ _add_lower_only,
)
+# The alias helpers a fetched mapper.py may call, resolved to the INSTALLED
+# implementations. `_get_new_mapper` reads such calls as data: it takes the table and
+# the two literal strings out of the AST and applies them with these, so the fetched
+# text never supplies behaviour.
+_MAPPER_HELPERS = {
+ "_add_with_lower": _add_with_lower,
+ "_add_lower_only": _add_lower_only,
+}
+
# https://github.com/huggingface/transformers/pull/26037 allows 4 bit loading!
from transformers import __version__ as transformers_version
from unsloth.models._utils import TorchAOConfig
@@ -501,40 +513,547 @@ def __get_model_name(
def _get_new_mapper():
try:
import requests
+ import time
new_mapper = (
"https://raw.githubusercontent.com/unslothai/unsloth/main/unsloth/models/mapper.py"
)
- with requests.get(new_mapper, timeout = 3) as new_mapper:
- new_mapper = new_mapper.text
- new_mapper = new_mapper[new_mapper.find("__INT_TO_FLOAT_MAPPER") :]
- new_mapper = (
- new_mapper.replace("INT_TO_FLOAT_MAPPER", "NEW_INT_TO_FLOAT_MAPPER")
- .replace("FLOAT_TO_INT_MAPPER", "NEW_FLOAT_TO_INT_MAPPER")
- .replace("MAP_TO_UNSLOTH_16bit", "NEW_MAP_TO_UNSLOTH_16bit")
- )
+ # Capped WHILE reading, since `requests.get` buffers the whole body first, and
+ # the deadline is total because `timeout` is per-read.
+ byte_cap = 1_000_000
+ deadline = time.monotonic() + 10
+ chunks, total = [], 0
+ # Redirects by hand: `requests` drains each intermediate body inside `get`.
+ url = new_mapper
+ for _ in range(5):
+ response = requests.get(url, timeout = 3, stream = True, allow_redirects = False)
+ with response:
+ location = (
+ response.headers.get("location")
+ if (300 <= response.status_code < 400)
+ else None
+ )
+ if location is not None:
+ if time.monotonic() > deadline:
+ return {}, {}, {}, {}, {}
+ else:
+ # `read1`: the timeout is per SOCKET READ, so a trickling peer
+ # resets it forever and the deadline is never reached.
+ raw = response.raw
+ # `requests` only decompresses inside `iter_content`.
+ try:
+ raw.decode_content = True
+ except AttributeError:
+ pass
+ read_once = getattr(raw, "read1", None)
+ while True:
+ if time.monotonic() > deadline:
+ return {}, {}, {}, {}, {}
+ if read_once is not None:
+ chunk = read_once(65_536)
+ else:
+ # Older urllib3 has no `read1`; one byte returns as promptly.
+ chunk = raw.read(1)
+ if not chunk:
+ break
+ chunks.append(chunk)
+ total += len(chunk)
+ if total > byte_cap:
+ return {}, {}, {}, {}, {}
+ encoding = response.encoding or "utf-8"
+ if location is None:
+ break
+ url = requests.compat.urljoin(url, location)
+ else:
+ return {}, {}, {}, {}, {}
+ new_mapper = b"".join(chunks).decode(encoding, errors = "replace")
+ # Never exec the response: that is arbitrary code execution inside every
+ # `from_pretrained` that hits an unmapped name. Only `__INT_TO_FLOAT_MAPPER` is
+ # data, and the tables are returned rather than written into this module.
+ import ast
+
+ # `ast.parse` builds the whole tree before any literal-only check runs, so this
+ # is no defence against exhaustion (python/cpython#95588); the byte cap above is.
+ tree = ast.parse(new_mapper)
+ # Every module-level literal dict, in source order; chosen below.
+ literal_bindings = []
+ for index, node in enumerate(tree.body):
+ # `AnnAssign` too, or an annotation upstream turns the probe off silently.
+ if isinstance(node, ast.AnnAssign):
+ targets = [node.target.id] if isinstance(node.target, ast.Name) else []
+ value = node.value
+ elif isinstance(node, ast.Assign):
+ targets = [t.id for t in node.targets if isinstance(t, ast.Name)]
+ value = node.value
+ else:
+ continue
+ if value is None or not targets:
+ continue
+ try:
+ literal = ast.literal_eval(value)
+ except Exception:
+ continue
+ if not isinstance(literal, dict):
+ continue
+ for name in targets:
+ literal_bindings.append((index, name, literal))
+
+ def _binding_at(name, before):
+ """What `name` holds when the statement at index `before` runs.
+
+ The last assignment BEFORE that point: a rebind after the builder ran must
+ not be read back over what the builder actually saw.
+ """
+ found = None
+ for index, bound, literal in literal_bindings:
+ if bound == name and (before is None or index <= before):
+ found = literal
+ return found
+
+ # Statements that really RUN at import: `ast.walk` reaches into function bodies
+ # and dead branches, which would fabricate a mapping. Local, because the tests
+ # run this body in a bare namespace.
+ def _constant_truth(test):
+ """True/False for a statically decidable condition, else None.
+
+ `not True` is a UnaryOp, so it fell through and its body was read as run.
+ """
+ if isinstance(test, ast.Constant):
+ return bool(test.value)
+ if isinstance(test, ast.UnaryOp) and isinstance(test.op, ast.Not):
+ inner = _constant_truth(test.operand)
+ return None if inner is None else not inner
+ return None
- # Exec into a throwaway namespace, never globals(). The slice also carries
- # FLOAT_TO_FP8_BLOCK_MAPPER / FLOAT_TO_FP8_ROW_MAPPER, the _add_* helpers
- # and the builder's loop variables, so exec'ing into globals() would swap
- # the FP8 tables this module imported from the installed mapper for the
- # ones on GitHub main. This is only a probe for "would a newer Unsloth
- # support this name?", so it must not change what the installed version
- # resolves; the fetched FP8 tables are returned for the probe to use
- # instead of being written over the installed ones.
- namespace = {}
- exec(new_mapper, namespace)
- return (
- namespace["NEW_INT_TO_FLOAT_MAPPER"],
- namespace["NEW_FLOAT_TO_INT_MAPPER"],
- namespace["NEW_MAP_TO_UNSLOTH_16bit"],
- # .get, not []: these two come from the fetched file under its own names (unlike
- # the NEW_ names above, renamed here), so an older or renamed mapper.py would
- # KeyError into the bare except and take the 4bit half of the probe down too.
- # {} is safe: the probe runs only after the installed tables already missed.
- namespace.get("FLOAT_TO_FP8_BLOCK_MAPPER", {}),
- namespace.get("FLOAT_TO_FP8_ROW_MAPPER", {}),
+ def _iterates_nothing(iterable):
+ if isinstance(iterable, (ast.Tuple, ast.List, ast.Set)):
+ return not iterable.elts
+ if isinstance(iterable, ast.Dict):
+ return not iterable.keys
+ if isinstance(iterable, ast.Constant):
+ # An empty literal iterates nothing; a nonempty one keeps its body.
+ return isinstance(iterable.value, (str, bytes)) and not iterable.value
+ return False
+
+ def _class_bound(statement):
+ # A class binding makes every LATER mutation a class attribute.
+ targets = []
+ if isinstance(statement, ast.Assign):
+ targets = statement.targets
+ elif isinstance(statement, ast.AnnAssign):
+ targets = [statement.target]
+ return {target.id for target in targets if isinstance(target, ast.Name)}
+
+ def _executed_nodes(
+ body,
+ shadowed = frozenset(),
+ class_body = False,
+ ):
+ # What ENDED the suite: `"return"` leaves the function, `True` the suite.
+ for statement in body:
+ if class_body:
+ # Only the statements ABOVE it still see the module global.
+ shadowed = shadowed | _class_bound(statement)
+ if isinstance(statement, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ if isinstance(statement, (ast.Break, ast.Continue, ast.Return)):
+ return "return" if isinstance(statement, ast.Return) else True
+ if isinstance(statement, ast.ClassDef):
+ # A class body, unlike a function body, RUNS at import.
+ yield from _executed_nodes(statement.body, shadowed, class_body = True)
+ continue
+ if isinstance(statement, ast.If) and _constant_truth(statement.test) is not None:
+ # Undecidable tests keep their body.
+ branch = statement.body if _constant_truth(statement.test) else statement.orelse
+ ended = yield from _executed_nodes(branch, shadowed)
+ if ended:
+ return ended
+ continue
+ if isinstance(statement, ast.While) and _constant_truth(statement.test) is not None:
+ if _constant_truth(statement.test):
+ ended = yield from _executed_nodes(statement.body, shadowed)
+ if ended == "return":
+ return ended
+ else:
+ ended = yield from _executed_nodes(statement.orelse, shadowed)
+ if ended:
+ return ended
+ continue
+ if isinstance(statement, ast.For) and _iterates_nothing(statement.iter):
+ ended = yield from _executed_nodes(statement.orelse, shadowed)
+ if ended:
+ return ended
+ continue
+ for field in ("body", "orelse", "finalbody"):
+ children = getattr(statement, field, None)
+ if isinstance(children, list):
+ yield from _executed_nodes(children, shadowed)
+ for handler in getattr(statement, "handlers", []) or []:
+ yield from _executed_nodes(handler.body, shadowed)
+ # Only the non-suite parts; a `Lambda` is excluded at the seed too.
+ pending = [
+ child
+ for child in ast.iter_child_nodes(statement)
+ if not isinstance(
+ child,
+ (
+ ast.stmt,
+ ast.excepthandler,
+ ast.FunctionDef,
+ ast.AsyncFunctionDef,
+ ast.ClassDef,
+ ast.Lambda,
+ ),
+ )
+ ]
+ yield statement, shadowed
+ while pending:
+ current = pending.pop()
+ yield current, shadowed
+ for child in ast.iter_child_nodes(current):
+ if isinstance(
+ child,
+ (
+ ast.FunctionDef,
+ ast.AsyncFunctionDef,
+ ast.ClassDef,
+ ast.Lambda,
+ ),
+ ):
+ continue
+ if isinstance(child, (ast.stmt, ast.excepthandler)):
+ continue
+ pending.append(child)
+
+ # The aliases a newer mapper.py adds live inside `build_mappers`, which the
+ # installed builder cannot know.
+ def _calls_the_builder(node):
+ """Whether this executed node IS the `build_mappers(...)` call.
+
+ The node itself, not `ast.walk` over it: walking the parent statement
+ descended back into the deferred children the yield had excluded, so
+ `unused = lambda: build_mappers(...)` counted as a call.
+ """
+ return (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "build_mappers"
+ )
+
+ builder_body = []
+ # From the EXECUTED nodes, with the statement each runs in: a source table
+ # rebound after the call is not what the module exports.
+ exported_names = (
+ "INT_TO_FLOAT_MAPPER",
+ "FLOAT_TO_INT_MAPPER",
+ "MAP_TO_UNSLOTH_16bit",
+ "FLOAT_TO_FP8_BLOCK_MAPPER",
+ "FLOAT_TO_FP8_ROW_MAPPER",
)
+
+ def _binds_the_exports(statement):
+ """Whether this statement assigns one of the exported tables."""
+ if isinstance(statement, ast.AnnAssign):
+ targets = [statement.target]
+ elif isinstance(statement, ast.Assign):
+ targets = statement.targets
+ else:
+ return False
+ bound = set()
+ for target in targets:
+ if isinstance(target, (ast.Tuple, ast.List)):
+ bound |= {
+ element.id for element in target.elts if isinstance(element, ast.Name)
+ }
+ elif isinstance(target, ast.Name):
+ bound.add(target.id)
+ return bool(bound.intersection(exported_names))
+
+ builder_call = None
+ builder_index = None
+ first_call = None
+ # A call that ASSIGNS the exports replaces all five; the fallback binds nothing.
+ builder_rebinds = False
+ for index, statement in enumerate(tree.body):
+ calls = [
+ node for node, _shadowed in _executed_nodes([statement]) if _calls_the_builder(node)
+ ]
+ if not calls:
+ continue
+ if first_call is None:
+ first_call = (calls[0], index)
+ # The LAST call that BINDS the exports; a validation call may run first.
+ if _binds_the_exports(statement):
+ builder_call, builder_index = calls[0], index
+ builder_rebinds = True
+ if builder_call is None and first_call is not None:
+ builder_call, builder_index = first_call
+ builder_called = builder_call is not None
+ if builder_called:
+ for statement in tree.body:
+ if isinstance(statement, ast.FunctionDef) and statement.name == "build_mappers":
+ builder_body = statement.body
+ break
+
+ # The table the builder was HANDED, read where the call runs.
+ source_name = "__INT_TO_FLOAT_MAPPER"
+ source_table = None
+ if builder_call is not None:
+ argument = None
+ if builder_call.args:
+ argument = builder_call.args[0]
+ else:
+ for keyword in builder_call.keywords:
+ if keyword.arg is not None:
+ argument = keyword.value
+ break
+ if isinstance(argument, ast.Name):
+ source_name = argument.id
+ elif argument is not None:
+ try:
+ literal = ast.literal_eval(argument)
+ except Exception:
+ literal = None
+ if isinstance(literal, dict):
+ source_table = literal
+
+ def _source_before_the_builder(name):
+ """The source table as the builder receives it, mutations included.
+
+ `.update({...})` and subscript assignment are ordinary ways to extend it
+ before it is handed over; the mutation pass below reads only the EXPORTED
+ tables. In execution order, and only up to the call.
+ """
+ current = None
+ for node, _shadowed in _executed_nodes(tree.body):
+ # The SELECTED call, by identity, so two alike calls are told apart.
+ if node is builder_call or (builder_call is None and _calls_the_builder(node)):
+ break
+ if isinstance(node, (ast.Assign, ast.AnnAssign)):
+ if node.value is None:
+ continue
+ targets = [node.target] if isinstance(node, ast.AnnAssign) else node.targets
+ for target in targets:
+ if isinstance(target, ast.Name) and target.id == name:
+ try:
+ literal = ast.literal_eval(node.value)
+ except Exception:
+ continue
+ if isinstance(literal, dict):
+ current = dict(literal)
+ elif (
+ isinstance(target, ast.Subscript)
+ and isinstance(target.value, ast.Name)
+ and target.value.id == name
+ and current is not None
+ ):
+ try:
+ current[ast.literal_eval(target.slice)] = ast.literal_eval(
+ node.value
+ )
+ except Exception:
+ continue
+ elif isinstance(node, ast.Delete):
+ for target in node.targets:
+ if isinstance(target, ast.Name) and target.id == name:
+ # Empty, not None: unbound must not fall back.
+ current = {}
+ elif (
+ isinstance(target, ast.Subscript)
+ and isinstance(target.value, ast.Name)
+ and target.value.id == name
+ and current is not None
+ ):
+ try:
+ current.pop(ast.literal_eval(target.slice), None)
+ except Exception:
+ continue
+ elif (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr == "update"
+ and isinstance(node.func.value, ast.Name)
+ and node.func.value.id == name
+ and current is not None
+ and len(node.args) == 1
+ and not node.keywords
+ ):
+ try:
+ additions = ast.literal_eval(node.args[0])
+ except Exception:
+ continue
+ if isinstance(additions, dict):
+ current.update(additions)
+ return current
+
+ if source_table is None and builder_call is not None:
+ source_table = _source_before_the_builder(source_name)
+ if source_table is None:
+ source_table = _binding_at(source_name, builder_index)
+
+ # Not the end of the probe: a row-only FP8 repo cannot be expressed through the
+ # source table at all. A body that adds nothing is reported so, at the end.
+ empty_base = not source_table
+ tables = build_mappers(source_table or {})
+ # Restored at the call below, which REPLACES all five tables.
+ built = [dict(table) for table in tables]
+
+ # Literal subscript, literal value, nothing called.
+ by_name = {
+ "INT_TO_FLOAT_MAPPER": tables[0],
+ "FLOAT_TO_INT_MAPPER": tables[1],
+ "MAP_TO_UNSLOTH_16bit": tables[2],
+ "FLOAT_TO_FP8_BLOCK_MAPPER": tables[3],
+ "FLOAT_TO_FP8_ROW_MAPPER": tables[4],
+ }
+
+ # Only the helper CALLS: the builder binds its own `INT_TO_FLOAT_MAPPER = {}`,
+ # which the whole-name rule below would read as a clear.
+ builder_additions = [
+ (node, shadowed)
+ for node, shadowed in _executed_nodes(builder_body)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id in _MAPPER_HELPERS
+ ]
+ # In EXECUTION order, so a rebind after the call still empties the table.
+ # `rebuilt` stands where the build assigns the exports; matched by identity.
+ rebuilt = object()
+ ordered = []
+ for node, shadowed in _executed_nodes(tree.body):
+ ordered.append((node, shadowed))
+ # At the call that populates the EXPORTS, not at an earlier one.
+ if node is builder_call or (builder_call is None and _calls_the_builder(node)):
+ if builder_rebinds:
+ ordered.append((rebuilt, frozenset()))
+ ordered.extend(builder_additions)
+ builder_additions = []
+ ordered.extend(builder_additions)
+ for node, shadowed in ordered:
+ if node is rebuilt:
+ for table, original in zip(tables, built):
+ table.clear()
+ table.update(original)
+ elif isinstance(node, (ast.Assign, ast.AnnAssign)):
+ # An annotated subscript assigns as the plain form does; a bare one
+ # binds nothing.
+ if isinstance(node, ast.AnnAssign):
+ if node.value is None:
+ continue
+ targets = [node.target]
+ else:
+ targets = node.targets
+ for target in targets:
+ if isinstance(target, ast.Name):
+ # A whole-name assignment REPLACES the exported table.
+ table = by_name.get(target.id)
+ if table is None or target.id in shadowed:
+ continue
+ try:
+ replacement = ast.literal_eval(node.value)
+ except ValueError:
+ continue
+ if isinstance(replacement, dict):
+ if not replacement and not builder_called:
+ # An INITIALISER, not a clear: a mapper.py with no
+ # `build_mappers` writes `X = {}` and fills all five
+ # from a module-scope loop the installed builder
+ # reproduces. Reading it as a clear emptied every
+ # table and the upgrade notice stopped firing.
+ continue
+ table.clear()
+ table.update(replacement)
+ continue
+ if not isinstance(target, ast.Subscript):
+ continue
+ if not isinstance(target.value, ast.Name):
+ continue
+ if target.value.id in shadowed:
+ continue
+ table = by_name.get(target.value.id)
+ if table is None:
+ continue
+ try:
+ table[ast.literal_eval(target.slice)] = ast.literal_eval(node.value)
+ except ValueError:
+ continue
+ pass
+ elif isinstance(node, ast.Delete):
+ for target in node.targets:
+ if isinstance(target, ast.Name):
+ table = by_name.get(target.id)
+ if table is not None and target.id not in shadowed:
+ table.clear()
+ continue
+ if not isinstance(target, ast.Subscript):
+ continue
+ if not isinstance(target.value, ast.Name):
+ continue
+ if target.value.id in shadowed:
+ continue
+ table = by_name.get(target.value.id)
+ if table is None:
+ continue
+ try:
+ table.pop(ast.literal_eval(target.slice), None)
+ except ValueError:
+ continue
+ elif (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr == "update"
+ ):
+ # Only a named receiver and a literal mapping; the keyword form cannot
+ # express keys with a slash.
+ if not isinstance(node.func.value, ast.Name):
+ continue
+ if node.func.value.id in shadowed:
+ continue
+ table = by_name.get(node.func.value.id)
+ if table is None or len(node.args) != 1 or node.keywords:
+ continue
+ try:
+ additions = ast.literal_eval(node.args[0])
+ except ValueError:
+ continue
+ if isinstance(additions, dict):
+ table.update(additions)
+ elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
+ # An alias not derivable from the source table, applied with the
+ # INSTALLED helper from literal arguments only.
+ helper = _MAPPER_HELPERS.get(node.func.id)
+ if helper is None:
+ continue
+ supplied = dict(zip(("mapper", "key", "value"), node.args))
+ for keyword in node.keywords:
+ if keyword.arg not in ("mapper", "key", "value"):
+ supplied = None
+ break
+ if keyword.arg in supplied:
+ supplied = None
+ break
+ supplied[keyword.arg] = keyword.value
+ if supplied is None or set(supplied) != {"mapper", "key", "value"}:
+ continue
+ destination = supplied["mapper"]
+ key, value = supplied["key"], supplied["value"]
+ if not isinstance(destination, ast.Name):
+ continue
+ if destination.id in shadowed:
+ continue
+ table = by_name.get(destination.id)
+ if table is None:
+ continue
+ try:
+ helper(table, ast.literal_eval(key), ast.literal_eval(value))
+ except ValueError:
+ continue
+ pass
+ pass
+ if empty_base and tables == build_mappers({}):
+ # Nothing on top of the empty base, so the body carried no mapping at all.
+ return {}, {}, {}, {}, {}
+ return tables
except:
return {}, {}, {}, {}, {}
@@ -549,8 +1068,7 @@ def _resolve_with_mappers(
fp8_block = None,
fp8_row = None,
):
- # fp8_block/fp8_row default to the installed tables; the newer-mapper probe passes the
- # fetched ones so it can answer for new FP8 repos without rebinding the installed ones.
+ # The probe passes the FETCHED fp8 tables, without rebinding the installed ones.
return __get_model_name(
model_name = model_name,
load_in_4bit = load_in_4bit,
diff --git a/unsloth/models/mapper.py b/unsloth/models/mapper.py
index 2a5b48fce6b..71095b796db 100644
--- a/unsloth/models/mapper.py
+++ b/unsloth/models/mapper.py
@@ -1393,13 +1393,6 @@ __INT_TO_FLOAT_MAPPER = \
),
}
-INT_TO_FLOAT_MAPPER = {}
-FLOAT_TO_INT_MAPPER = {}
-MAP_TO_UNSLOTH_16bit = {}
-FLOAT_TO_FP8_BLOCK_MAPPER = {}
-FLOAT_TO_FP8_ROW_MAPPER = {}
-
-
def _add_with_lower(mapper, key, value):
if key is None:
return
@@ -1412,61 +1405,94 @@ def _add_lower_only(mapper, key, value):
return
mapper[key.lower()] = value
-for key, values in __INT_TO_FLOAT_MAPPER.items():
- block, row = None, None
- if type(values) is dict:
- assert "16" in values
- float16_values = values["16"]
- # Float8 and other quantized types
- if "8" in values:
- float8_values = values["8"]
- assert len(float8_values) == 3
- official, block, row = float8_values
- _add_lower_only(FLOAT_TO_FP8_BLOCK_MAPPER, key, block)
- _add_lower_only(FLOAT_TO_FP8_ROW_MAPPER, key, row)
- _add_lower_only(FLOAT_TO_FP8_BLOCK_MAPPER, official + "-dynamic", block)
- _add_lower_only(FLOAT_TO_FP8_ROW_MAPPER, official, row)
- _add_lower_only(FLOAT_TO_FP8_ROW_MAPPER, official + "-dynamic", row)
- for k in float8_values + float16_values:
- _add_lower_only(FLOAT_TO_FP8_BLOCK_MAPPER, k, block)
- _add_lower_only(FLOAT_TO_FP8_ROW_MAPPER, k, row)
- if float8_values[1] is not None and float8_values[1].startswith("unsloth"):
+def build_mappers(__INT_TO_FLOAT_MAPPER):
+ """ Derives the five lookup tables from the one source table.
+
+ A function rather than module-level statements so `loader_utils._get_new_mapper`
+ can run it over a *newer* `__INT_TO_FLOAT_MAPPER` parsed out of the mapper.py on
+ GitHub main. That probe used to `exec` the fetched file; going through here means
+ the fetched text only ever supplies data, and the derivation is this installed
+ version's code.
+ """
+ INT_TO_FLOAT_MAPPER = {}
+ FLOAT_TO_INT_MAPPER = {}
+ MAP_TO_UNSLOTH_16bit = {}
+ FLOAT_TO_FP8_BLOCK_MAPPER = {}
+ FLOAT_TO_FP8_ROW_MAPPER = {}
+
+ for key, values in __INT_TO_FLOAT_MAPPER.items():
+ block, row = None, None
+ if type(values) is dict:
+ assert "16" in values
+ float16_values = values["16"]
+ # Float8 and other quantized types
+ if "8" in values:
+ float8_values = values["8"]
+ assert len(float8_values) == 3
+ official, block, row = float8_values
+ _add_lower_only(FLOAT_TO_FP8_BLOCK_MAPPER, key, block)
+ _add_lower_only(FLOAT_TO_FP8_ROW_MAPPER, key, row)
+ _add_lower_only(FLOAT_TO_FP8_BLOCK_MAPPER, official + "-dynamic", block)
+ _add_lower_only(FLOAT_TO_FP8_ROW_MAPPER, official, row)
+ _add_lower_only(FLOAT_TO_FP8_ROW_MAPPER, official + "-dynamic", row)
+ for k in float8_values + float16_values:
+ _add_lower_only(FLOAT_TO_FP8_BLOCK_MAPPER, k, block)
+ _add_lower_only(FLOAT_TO_FP8_ROW_MAPPER, k, row)
+
+ if float8_values[1] is not None and float8_values[1].startswith("unsloth"):
+ for value in float8_values:
+ if value is not None:
+ _add_with_lower(MAP_TO_UNSLOTH_16bit, value, float8_values[1])
+
for value in float8_values:
if value is not None:
- _add_with_lower(MAP_TO_UNSLOTH_16bit, value, float8_values[1])
+ FLOAT_TO_INT_MAPPER[value] = key
+ FLOAT_TO_INT_MAPPER[value.lower()] = key.lower()
+ values = float16_values
+ INT_TO_FLOAT_MAPPER[key] = values[0]
+
+ for value in values:
+ FLOAT_TO_INT_MAPPER[value] = key
+
+ # Map to Unsloth version for 16bit versions
+ if len(values) == 2:
+ if values[0].startswith("unsloth"):
+ _add_with_lower(MAP_TO_UNSLOTH_16bit, values[1], values[0])
+ _add_with_lower(MAP_TO_UNSLOTH_16bit, block, values[0])
+ _add_with_lower(MAP_TO_UNSLOTH_16bit, row, values[0])
+ elif len(values) == 3:
+ # Dynamic Unsloth quantization
+ if values[0].startswith("unsloth"):
+ _add_with_lower(MAP_TO_UNSLOTH_16bit, values[1], values[0])
+ _add_with_lower(MAP_TO_UNSLOTH_16bit, values[2], values[0])
+ _add_with_lower(MAP_TO_UNSLOTH_16bit, block, values[0])
+ _add_with_lower(MAP_TO_UNSLOTH_16bit, row, values[0])
+ pass
- for value in float8_values:
- if value is not None:
- FLOAT_TO_INT_MAPPER[value] = key
- FLOAT_TO_INT_MAPPER[value.lower()] = key.lower()
- values = float16_values
- INT_TO_FLOAT_MAPPER[key] = values[0]
+ # Get lowercased
+ lowered_key = key.lower()
+ INT_TO_FLOAT_MAPPER[lowered_key] = values[0].lower()
- for value in values:
- FLOAT_TO_INT_MAPPER[value] = key
+ for value in values:
+ FLOAT_TO_INT_MAPPER[value.lower()] = lowered_key
- # Map to Unsloth version for 16bit versions
- if len(values) == 2:
- if values[0].startswith("unsloth"):
- _add_with_lower(MAP_TO_UNSLOTH_16bit, values[1], values[0])
- _add_with_lower(MAP_TO_UNSLOTH_16bit, block, values[0])
- _add_with_lower(MAP_TO_UNSLOTH_16bit, row, values[0])
- elif len(values) == 3:
- # Dynamic Unsloth quantization
- if values[0].startswith("unsloth"):
- _add_with_lower(MAP_TO_UNSLOTH_16bit, values[1], values[0])
- _add_with_lower(MAP_TO_UNSLOTH_16bit, values[2], values[0])
- _add_with_lower(MAP_TO_UNSLOTH_16bit, block, values[0])
- _add_with_lower(MAP_TO_UNSLOTH_16bit, row, values[0])
- pass
+ _add_with_lower(MAP_TO_UNSLOTH_16bit, "google/gemma-4-26B-A4B", "unsloth/gemma-4-26B-A4B")
+ _add_with_lower(MAP_TO_UNSLOTH_16bit, "LiquidAI/LFM2.5-1.2B-Instruct", "unsloth/LFM2.5-1.2B-Instruct")
- # Get lowercased
- lowered_key = key.lower()
- INT_TO_FLOAT_MAPPER[lowered_key] = values[0].lower()
+ return (
+ INT_TO_FLOAT_MAPPER,
+ FLOAT_TO_INT_MAPPER,
+ MAP_TO_UNSLOTH_16bit,
+ FLOAT_TO_FP8_BLOCK_MAPPER,
+ FLOAT_TO_FP8_ROW_MAPPER,
+ )
- for value in values:
- FLOAT_TO_INT_MAPPER[value.lower()] = lowered_key
-_add_with_lower(MAP_TO_UNSLOTH_16bit, "google/gemma-4-26B-A4B", "unsloth/gemma-4-26B-A4B")
-_add_with_lower(MAP_TO_UNSLOTH_16bit, "LiquidAI/LFM2.5-1.2B-Instruct", "unsloth/LFM2.5-1.2B-Instruct")
+(
+ INT_TO_FLOAT_MAPPER,
+ FLOAT_TO_INT_MAPPER,
+ MAP_TO_UNSLOTH_16bit,
+ FLOAT_TO_FP8_BLOCK_MAPPER,
+ FLOAT_TO_FP8_ROW_MAPPER,
+) = build_mappers(__INT_TO_FLOAT_MAPPER)
diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py
index 6abf5a0c396..16d46051bcb 100644
--- a/unsloth/models/vision.py
+++ b/unsloth/models/vision.py
@@ -43,6 +43,7 @@ from ._utils import (
set_task_config_attr,
)
from ._utils import *
+from ._custom_dtype import resolve_dtype, trusted_custom_dtype
from .loader_utils import (
DEFAULT_DEVICE_MAP,
OFFLOAD_EMBEDDING_AUTO,
@@ -1142,11 +1143,13 @@ class FastBaseModel:
# Check for custom data-types
custom_datatype = None
correct_dtype = None
- if os.environ.get("UNSLOTH_FORCE_CUSTOM_DTYPE", "") != "":
- custom_datatype = os.environ["UNSLOTH_FORCE_CUSTOM_DTYPE"]
- assert custom_datatype.count(";") >= 4
+ # `custom_datatype` has to stay None when unset: the consumer below tests
+ # `is not None` and would walk every module of every model to `exec("")`.
+ _raw_custom_dtype, _code_is_trusted = trusted_custom_dtype()
+ if _raw_custom_dtype != "":
+ assert _raw_custom_dtype.count(";") >= 4
checker, _dtype, _bnb_compute_dtype, _custom_datatype, execute_code = (
- custom_datatype.split(";", 4)
+ _raw_custom_dtype.split(";", 4)
)
# Allow custom dtypes on all runs
allow_all_runs = checker == "all"
@@ -1155,15 +1158,27 @@ class FastBaseModel:
dtype == torch.float16 or os.environ.get("UNSLOTH_FORCE_FLOAT32", "0") == "1"
)
if allow_all_runs or allow_float16_runs:
- if eval(_dtype) is not None:
- dtype = eval(_dtype)
- if eval(_bnb_compute_dtype) is not None:
- bnb_compute_dtype = eval(_bnb_compute_dtype)
+ # A table lookup, not eval: these fields NAME a dtype.
+ _resolved_dtype = resolve_dtype(_dtype)
+ if _resolved_dtype is not None:
+ dtype = _resolved_dtype
+ _resolved_bnb_compute_dtype = resolve_dtype(_bnb_compute_dtype)
+ if _resolved_bnb_compute_dtype is not None:
+ bnb_compute_dtype = _resolved_bnb_compute_dtype
correct_dtype = bnb_compute_dtype
- custom_datatype = _custom_datatype
- # Execute code as well
- if len(execute_code.strip()) != 0:
- exec(execute_code)
+ # The last two fields are code, run only when this process set the
+ # variable; an inherited environment picks dtypes but injects nothing.
+ if _code_is_trusted:
+ custom_datatype = _custom_datatype
+ # Execute code as well
+ if len(execute_code.strip()) != 0:
+ exec(execute_code)
+ else:
+ logger.warning(
+ "Unsloth: Ignoring the code in `UNSLOTH_FORCE_CUSTOM_DTYPE` "
+ "because it was not set by Unsloth."
+ )
+ custom_datatype = None
else:
custom_datatype = None
correct_dtype = None