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.

Core: per-user fp8 cache, SyntheticDataKit binds vLLM to loopback (#14460)

Daniel Han4be4f79324f2
diff --git a/tests/test_fp8_cache_private_dir.py b/tests/test_fp8_cache_private_dir.py
new file mode 100644
index 00000000000..f7a88f622b3
--- /dev/null
+++ b/tests/test_fp8_cache_private_dir.py
@@ -0,0 +1,132 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+"""The `load_in_fp8` artifact is reused by name and loaded with the caller's trust_remote_code,
+so on a shared /tmp another account could plant it first. Nothing is downloaded or loaded."""
+
+from __future__ import annotations
+
+import hashlib
+import os
+import types
+
+import pytest
+
+loader_utils = pytest.importorskip("unsloth.models.loader_utils")
+
+posix_only = pytest.mark.skipif(not hasattr(os, "getuid"), reason = "POSIX ownership")
+
+
+class _Quantizing(Exception):
+ pass
+
+
+def shared_tmp(monkeypatch, tmp_path):
+ import transformers
+
+ monkeypatch.setattr(
+ transformers.AutoConfig,
+ "from_pretrained",
+ classmethod(lambda cls, *a, **k: types.SimpleNamespace(architectures = ["LlamaForCausalLM"])),
+ )
+
+ def reached(*a, **k):
+ raise _Quantizing
+
+ monkeypatch.setattr(transformers.AutoModelForCausalLM, "from_pretrained", reached)
+ monkeypatch.setattr(loader_utils, "_get_torchao_fp8_config", lambda mode: None)
+ monkeypatch.setattr(transformers, "TorchAoConfig", lambda cfg: None)
+ shared = tmp_path / "shared"
+ shared.mkdir()
+ monkeypatch.setattr(loader_utils.tempfile, "gettempdir", lambda: str(shared))
+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "local"))
+ return shared
+
+
+def _quantize(name = "org/model"):
+ try:
+ return loader_utils._offline_quantize_to_fp8(name, "row")
+ except _Quantizing:
+ return None
+
+
+def test_a_directory_planted_at_the_shared_name_is_not_loaded(shared_tmp):
+ name = "org/model"
+ planted = shared_tmp / (
+ "model-fp8-row-" + hashlib.sha256(name.encode("utf-8")).hexdigest()[:12]
+ )
+ planted.mkdir()
+ (planted / "config.json").write_text('{"auto_map": {"AutoModelForCausalLM": "evil.Model"}}')
+ result = _quantize(name)
+ assert result is None or os.path.realpath(result) != os.path.realpath(planted)
+
+
+@posix_only
+def test_the_cache_root_is_private(shared_tmp):
+ _quantize()
+ root = loader_utils._private_fp8_cache_dir()
+ info = os.lstat(root)
+ assert info.st_uid == os.getuid()
+ assert info.st_mode & 0o777 == 0o700
+
+
+@posix_only
+def test_a_loose_root_of_ours_is_tightened(shared_tmp):
+ root = shared_tmp / ("unsloth-fp8-%d" % os.getuid())
+ root.mkdir()
+ os.chmod(root, 0o777)
+ loader_utils._private_fp8_cache_dir()
+ assert os.lstat(root).st_mode & 0o777 == 0o700
+
+
+@posix_only
+def test_a_root_owned_by_another_account_is_refused(shared_tmp, monkeypatch):
+ other = os.getuid() + 1
+ (shared_tmp / ("unsloth-fp8-%d" % other)).mkdir(mode = 0o700)
+ monkeypatch.setattr(loader_utils.os, "getuid", lambda: other)
+ with pytest.raises(RuntimeError, match = "symlink or owned"):
+ _quantize()
+
+
+@posix_only
+def test_a_symlinked_root_is_refused(shared_tmp):
+ target = shared_tmp / "elsewhere"
+ target.mkdir(mode = 0o700)
+ os.symlink(target, shared_tmp / ("unsloth-fp8-%d" % os.getuid()))
+ with pytest.raises(RuntimeError, match = "symlink or owned"):
+ _quantize()
+
+
+@posix_only
+def test_a_writable_artifact_inside_our_root_is_refused(shared_tmp):
+ _quantize()
+ root = loader_utils._private_fp8_cache_dir()
+ name = "org/model"
+ artifact = os.path.join(
+ root, "model-fp8-row-" + hashlib.sha256(name.encode("utf-8")).hexdigest()[:12]
+ )
+ os.mkdir(artifact)
+ os.chmod(artifact, 0o777)
+ with pytest.raises(RuntimeError, match = "world-writable"):
+ _quantize(name)
+
+
+def test_our_own_artifact_is_still_reused(shared_tmp):
+ root = loader_utils._private_fp8_cache_dir()
+ name = "org/model"
+ artifact = os.path.join(
+ root, "model-fp8-row-" + hashlib.sha256(name.encode("utf-8")).hexdigest()[:12]
+ )
+ os.mkdir(artifact, 0o700)
+ first = _quantize(name)
+ assert first == artifact
+
+
+def test_without_posix_owners_the_root_is_not_in_a_shared_temp(shared_tmp, monkeypatch):
+ # TEMP can be shared on Windows and there is no owner check, so a name derived from
+ # USERNAME there could be pre-created by another account.
+ monkeypatch.delattr(loader_utils.os, "getuid", raising = False)
+ monkeypatch.setenv("USERNAME", "victim")
+ (shared_tmp / "unsloth-fp8-victim").mkdir()
+ root = os.path.realpath(loader_utils._private_fp8_cache_dir())
+ assert not root.startswith(os.path.realpath(shared_tmp))
+ assert root.startswith(os.path.realpath(os.environ["LOCALAPPDATA"]))
diff --git a/tests/test_synthetic_vllm_port.py b/tests/test_synthetic_vllm_port.py
index d09c056feb5..e3cd687ef0d 100644
--- a/tests/test_synthetic_vllm_port.py
+++ b/tests/test_synthetic_vllm_port.py
@@ -63,6 +63,9 @@ def test_check_vllm_status_queries_the_given_port(monkeypatch):
assert urls == ["http://localhost:8123/metrics", "http://localhost:8000/metrics"]
+_REAL_AWAIT_METRICS = SyntheticDataKit._await_metrics_endpoint
+
+
def _built_kit(monkeypatch, tmp_path, **kwargs):
"""Run __init__ with the model download, vLLM and the waits stubbed out."""
import transformers
@@ -115,3 +118,35 @@ def test_server_and_config_follow_a_moved_default(monkeypatch, tmp_path, busy_po
assert kit.port != busy_port
assert argv[argv.index("--port") + 1] == str(kit.port)
assert f'api_base: "http://localhost:{kit.port}/v1"' in config
+
+
+def test_server_binds_loopback_by_default(monkeypatch, tmp_path):
+ _kit, argv, _config = _built_kit(monkeypatch, tmp_path, port = 8123)
+ # vLLM's own default is every interface, and the server runs with no API key.
+ assert argv[argv.index("--host") + 1] == "127.0.0.1"
+
+
+def test_a_wider_bind_is_opt_in(monkeypatch, tmp_path):
+ _kit, argv, _config = _built_kit(monkeypatch, tmp_path, port = 8123, host = "0.0.0.0")
+ assert argv[argv.index("--host") + 1] == "0.0.0.0"
+ assert argv.count("--host") == 1
+
+
+ "host, client",
+ [
+ ("127.0.0.1", "localhost"),
+ ("0.0.0.0", "localhost"),
+ ("::1", "[::1]"),
+ ("192.168.1.20", "192.168.1.20"),
+ ],
+)
+def test_the_kit_reaches_its_own_bind_address(monkeypatch, tmp_path, host, client):
+ kit, _argv, config = _built_kit(monkeypatch, tmp_path, port = 8123, host = host)
+ assert f'api_base: "http://{client}:8123/v1"' in config
+ seen = []
+ monkeypatch.setattr(
+ SyntheticDataKit, "check_vllm_status", staticmethod(lambda *a: seen.append(a) or True)
+ )
+ _REAL_AWAIT_METRICS(kit)
+ assert seen == [(8123, client)]
diff --git a/tests/test_synthetic_vllm_startup_failure.py b/tests/test_synthetic_vllm_startup_failure.py
index 111b1a6d7ee..f7be74fcd00 100644
--- a/tests/test_synthetic_vllm_startup_failure.py
+++ b/tests/test_synthetic_vllm_startup_failure.py
@@ -317,7 +317,7 @@ def test_the_metrics_wait_is_bounded_by_time_not_by_attempts(monkeypatch):
calls = {"n": 0}
- def stalled_check(port = 8000):
+ def stalled_check(port = 8000, host = "localhost"):
calls["n"] += 1
clock["now"] += 5.0
return False
@@ -379,7 +379,7 @@ def test_the_metrics_wait_accepts_an_unbounded_timeout():
"""Same arithmetic, same fix, pinned so the helper is not left half done."""
calls = {"n": 0}
- def check(port = 8000):
+ def check(port = 8000, host = "localhost"):
calls["n"] += 1
return calls["n"] >= 3
diff --git a/unsloth/dataprep/synthetic.py b/unsloth/dataprep/synthetic.py
index c68f41782c7..137b472ceb7 100644
--- a/unsloth/dataprep/synthetic.py
+++ b/unsloth/dataprep/synthetic.py
@@ -202,6 +202,15 @@ def _port_is_free(port):
return True
+def _client_host(host):
+ """Host the kit itself connects to: localhost for IPv4 loopback and wildcard binds, else the bind address."""
+ if host in ("0.0.0.0", "127.0.0.1", "localhost"):
+ return "localhost"
+ if host in ("::", "::1"):
+ return "[::1]"
+ return f"[{host}]" if ":" in host else host
+
+
def _pick_vllm_port(port):
"""`port` as given, else 8000, else a free port when 8000 is taken (Studio in the Unsloth Docker image)."""
if port is not None:
@@ -220,6 +229,7 @@ def _pick_vllm_port(port):
class SyntheticDataKit:
# Kept as the class default so kits built without __init__ still have a port.
port = 8000
+ client_host = "localhost"
def __init__(
self,
@@ -231,9 +241,11 @@ class SyntheticDataKit:
token = None,
timeout = 1200,
port = None,
+ host = "127.0.0.1",
**kwargs,
):
assert type(model_name) is str
+ assert type(host) is str and host
assert type(max_seq_length) is int
assert type(gpu_memory_utilization) is float
assert type(float8_kv_cache) is bool
@@ -294,10 +306,14 @@ class SyntheticDataKit:
# Picked here, not before the model download, so a released fallback port is not left free for minutes.
self.port = _pick_vllm_port(port)
+ self.client_host = _client_host(host)
subprocess_commands = [
"vllm",
"serve",
str(model_name),
+ # vLLM listens on every interface by default and this server has no API key.
+ "--host",
+ host,
"--port",
str(self.port),
]
@@ -369,11 +385,11 @@ class SyntheticDataKit:
is ten minutes, not the hundred the message promises.
"""
deadline = _deadline(timeout)
- while not self.check_vllm_status(self.port):
+ while not self.check_vllm_status(self.port, self.client_host):
if deadline is not None and time.monotonic() >= deadline:
self._fail_vllm_server(
"printed its readiness line but never answered "
- f"http://localhost:{self.port}/metrics (waited {timeout:g} seconds)"
+ f"http://{self.client_host}:{self.port}/metrics (waited {timeout:g} seconds)"
)
time.sleep(poll_interval)
@@ -426,7 +442,7 @@ class SyntheticDataKit:
f"Unsloth: the vLLM server behind SyntheticDataKit "
f"{what_happened}.\n"
f"Nothing after this point can work: `synthetic-data-kit` reaches "
- f"the model over http://localhost:{self.port}/v1, so ingest/create/"
+ f"the model over http://{self.client_host}:{self.port}/v1, so ingest/create/"
f'save-as would each report "VLLM server not available", write '
f"no file, and leave the failure to surface as a FileNotFoundError "
f"much later on.\n"
@@ -457,10 +473,10 @@ class SyntheticDataKit:
)
@staticmethod
- def check_vllm_status(port = 8000):
+ def check_vllm_status(port = 8000, host = "localhost"):
try:
# requests has no default timeout, so a stalled server hung here.
- response = requests.get(f"http://localhost:{port}/metrics", timeout = 5)
+ response = requests.get(f"http://{host}:{port}/metrics", timeout = 5)
return response.status_code == 200
except requests.exceptions.RequestException:
# ConnectionError alone let a read timeout escape as a stray traceback out of the readiness loop.
@@ -601,6 +617,7 @@ class SyntheticDataKit:
.replace("{cleanup_batch_size}", str(cleanup_batch_size))
.replace("{cleanup_temperature}", str(cleanup_temperature))
.replace("{port}", str(self.port))
+ .replace("{host}", self.client_host)
)
with open("synthetic_data_kit_config.yaml", "w", encoding = "utf-8") as f:
diff --git a/unsloth/dataprep/synthetic_configs.py b/unsloth/dataprep/synthetic_configs.py
index 301e14fbe03..e487cd11a8a 100644
--- a/unsloth/dataprep/synthetic_configs.py
+++ b/unsloth/dataprep/synthetic_configs.py
@@ -32,7 +32,7 @@ paths:
# VLLM server configuration
vllm:
- api_base: "http://localhost:{port}/v1" # Base URL for VLLM API
+ api_base: "http://{host}:{port}/v1" # Base URL for VLLM API
port: {port} # Port for VLLM server
model: "{model_name}" # Default model to use
max_retries: 3 # Number of retries for API calls
diff --git a/unsloth/models/loader_utils.py b/unsloth/models/loader_utils.py
index f9791a4a318..42a1f5beab5 100644
--- a/unsloth/models/loader_utils.py
+++ b/unsloth/models/loader_utils.py
@@ -1859,6 +1859,49 @@ def get_model_name(
return new_model_name
+def _refuse_unless_private(path, what):
+ """On POSIX, refuse a path that is a symlink, not ours, or writable by group/other."""
+ import stat
+
+ if not hasattr(os, "getuid"):
+ return
+ info = os.lstat(path)
+ if stat.S_ISLNK(info.st_mode) or info.st_uid != os.getuid():
+ raise RuntimeError(
+ f"Unsloth: refusing {what} that is a symlink or owned by another user: {path}"
+ )
+ if stat.S_IMODE(info.st_mode) & 0o022:
+ raise RuntimeError(
+ f"Unsloth: refusing a group- or world-writable {what} "
+ f"(mode {stat.S_IMODE(info.st_mode):04o}): {path}"
+ )
+
+
+def _private_fp8_cache_dir():
+ """Per-user 0700 root for fp8 artifacts. The shared /tmp lets another account pre-create
+ a predictable artifact name and have it loaded (with trust_remote_code) as this user."""
+ if hasattr(os, "getuid"):
+ directory = os.path.join(tempfile.gettempdir(), "unsloth-fp8-%d" % os.getuid())
+ else:
+ # No owner check on Windows, and TEMP can be shared (services, build agents), so use the
+ # profile's LocalAppData, which Windows ACLs to this account.
+ base = os.environ.get("LOCALAPPDATA") or os.path.join(
+ os.path.expanduser("~"), "AppData", "Local"
+ )
+ directory = os.path.join(base, "unsloth", "fp8-cache")
+ os.makedirs(directory, mode = 0o700, exist_ok = True)
+ if hasattr(os, "getuid"):
+ info = os.lstat(directory)
+ # exist_ok does not apply mode, so tighten one of ours; anyone else's is refused below.
+ if not os.path.islink(directory) and info.st_uid == os.getuid() and info.st_mode & 0o077:
+ try:
+ os.chmod(directory, 0o700)
+ except OSError:
+ pass
+ _refuse_unless_private(directory, "an fp8 cache directory")
+ return directory
+
+
def _offline_quantize_to_fp8(
model_name: str,
fp8_mode: str,
@@ -1904,7 +1947,7 @@ def _offline_quantize_to_fp8(
text_config = candidate
is_vlm = False
- temp_dir = tempfile.gettempdir()
+ temp_dir = _private_fp8_cache_dir()
# Cache text-only and full-VLM artifacts separately so neither reuses the other (#5816).
cache_name = model_name.split("/")[-1] + "-fp8-" + fp8_mode
# The basename alone would let org-a/model and org-b/model share one artifact.
@@ -1919,6 +1962,8 @@ def _offline_quantize_to_fp8(
cache_name += "-text-only"
new_model_name = os.path.join(temp_dir, cache_name)
print(f"Unsloth: Quantizing '{model_name}' to fp8, using model_name='{new_model_name}' instead")
+ if os.path.lexists(new_model_name):
+ _refuse_unless_private(new_model_name, "a cached fp8 artifact")
if not os.path.isdir(new_model_name):
from ._utils import _apply_text_only_key_mapping