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.

Studio: install the llm-compressor-main shadow from a source archive instead of git (#13132)

Daniel Han50807822f128
diff --git a/studio/backend/tests/test_git_tool.py b/studio/backend/tests/test_git_tool.py
deleted file mode 100644
index 6c7148f2110..00000000000
--- a/studio/backend/tests/test_git_tool.py
+++ /dev/null
@@ -1,194 +0,0 @@
-# SPDX-License-Identifier: AGPL-3.0-only
-# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-
-"""Git is provided lazily by the feature that needs it, never by the installer."""
-
-from __future__ import annotations
-
-import hashlib
-import io
-import zipfile
-
-import pytest
-
-from utils import git_tool
-
-
-def _zip_bytes(entries: dict[str, bytes]) -> bytes:
- buf = io.BytesIO()
- with zipfile.ZipFile(buf, "w") as zf:
- for name, data in entries.items():
- zf.writestr(name, data)
- return buf.getvalue()
-
-
-class _Response(io.BytesIO):
- def __enter__(self):
- return self
-
- def __exit__(self, *exc):
- return False
-
-
-def windows_without_git(monkeypatch, tmp_path):
- monkeypatch.setattr(git_tool, "_IS_WINDOWS", True)
- monkeypatch.setattr(git_tool.shutil, "which", lambda name: None)
- monkeypatch.setattr(git_tool, "studio_root", lambda: tmp_path)
- monkeypatch.setattr(git_tool, "_mingit_flavor", lambda: "64-bit")
- # git.exe cannot run here: a present, non-empty launcher stands in for a working one.
- monkeypatch.setattr(
- git_tool,
- "_git_works",
- lambda exe: git_tool.Path(exe).is_file() and git_tool.Path(exe).read_bytes() == b"MZ",
- )
- return tmp_path
-
-
-def _serve(
- monkeypatch,
- payload: bytes,
- *,
- digest: str | None = None,
-):
- calls = []
- monkeypatch.setitem(
- git_tool._MINGIT_SHA256, "64-bit", digest or hashlib.sha256(payload).hexdigest()
- )
-
- def fake_urlopen(request, timeout = None):
- calls.append(request.full_url)
- return _Response(payload)
-
- monkeypatch.setattr(git_tool.urllib.request, "urlopen", fake_urlopen)
- return calls
-
-
-def test_working_git_on_path_is_used_as_is(monkeypatch):
- monkeypatch.setattr(git_tool.shutil, "which", lambda name: "/usr/bin/git")
- monkeypatch.setattr(git_tool, "_git_works", lambda exe: True)
- monkeypatch.setattr(
- git_tool.urllib.request, "urlopen", lambda *a, **k: pytest.fail("downloaded")
- )
- assert git_tool.ensure_git() is None
-
-
-def test_missing_git_off_windows_explains_how_to_install(monkeypatch):
- monkeypatch.setattr(git_tool, "_IS_WINDOWS", False)
- monkeypatch.setattr(git_tool.shutil, "which", lambda name: None)
- with pytest.raises(git_tool.GitUnavailable, match = "package manager"):
- git_tool.ensure_git()
-
-
-def test_windows_fetches_pinned_mingit_once_into_studio_home(monkeypatch, windows_without_git):
- calls = _serve(monkeypatch, _zip_bytes({"cmd/git.exe": b"MZ", "mingw64/bin/git.exe": b"MZ"}))
- first = git_tool.ensure_git()
- second = git_tool.ensure_git()
- root = windows_without_git / "tools" / f"mingit-{git_tool.MINGIT_VERSION}-64-bit"
- assert first == second == str(root / "cmd")
- assert (root / "cmd" / "git.exe").is_file()
- assert calls == [
- "https://github.com/git-for-windows/git/releases/download/"
- f"{git_tool._MINGIT_TAG}/MinGit-{git_tool.MINGIT_VERSION}-64-bit.zip"
- ]
-
-
-def test_checksum_mismatch_installs_nothing(monkeypatch, windows_without_git):
- _serve(monkeypatch, _zip_bytes({"cmd/git.exe": b"MZ"}), digest = "0" * 64)
- with pytest.raises(git_tool.GitUnavailable, match = "sha256"):
- git_tool.ensure_git()
- assert not any((windows_without_git / "tools").glob("mingit-*"))
-
-
-def test_zip_entry_escaping_its_root_is_refused(monkeypatch, windows_without_git):
- _serve(monkeypatch, _zip_bytes({"cmd/git.exe": b"MZ", "../evil.txt": b"x"}))
- with pytest.raises(git_tool.GitUnavailable, match = "outside its root"):
- git_tool.ensure_git()
- assert not (windows_without_git / "tools" / "evil.txt").exists()
-
-
-def test_offline_windows_without_git_does_not_download(monkeypatch, windows_without_git):
- monkeypatch.setattr(
- git_tool.urllib.request, "urlopen", lambda *a, **k: pytest.fail("downloaded")
- )
- with pytest.raises(git_tool.GitUnavailable, match = "offline"):
- git_tool.ensure_git(allow_download = False)
-
-
-def test_network_error_becomes_git_unavailable(monkeypatch, windows_without_git):
- def boom(*a, **k):
- raise OSError("connection reset")
-
- monkeypatch.setattr(git_tool.urllib.request, "urlopen", boom)
- with pytest.raises(git_tool.GitUnavailable, match = "connection reset"):
- git_tool.ensure_git()
-
-
-def test_with_git_on_path_prepends_for_the_child_only():
- env = {"Path": r"C:\Windows"}
- out = git_tool.with_git_on_path(env, r"C:\s\tools\mingit\cmd")
- assert out["Path"].startswith(r"C:\s\tools\mingit\cmd" + git_tool.os.pathsep)
- assert env == {"Path": r"C:\Windows"}
- assert git_tool.with_git_on_path(env, None) is env
-
-
-def test_llmcompressor_shadow_gets_git_on_the_install_path(monkeypatch, tmp_path):
- from utils import transformers_version as tv
-
- monkeypatch.setattr(tv, "_llmcompressor_shadow_is_valid", lambda: False)
- monkeypatch.setattr(tv, "_llmcompressor_main_disabled", lambda: False)
- monkeypatch.setattr(tv, "_env_offline", lambda: False)
- monkeypatch.setattr(tv, "_VENV_LLMCOMPRESSOR_DIR", str(tmp_path / "shadow"))
- monkeypatch.setattr(git_tool, "ensure_git", lambda **k: "/studio/tools/mingit/cmd")
- seen = []
-
- class _Done:
- returncode = 0
- stdout = ""
-
- def fake_run(cmd, **kwargs):
- env = kwargs["env"]
- seen.append(next(v for k, v in env.items() if k.upper() == "PATH"))
- return _Done()
-
- monkeypatch.setattr(tv.subprocess, "run", fake_run)
- assert tv._ensure_venv_llmcompressor_exists() is True
- assert seen and seen[0].startswith("/studio/tools/mingit/cmd" + git_tool.os.pathsep)
-
-
-def test_llmcompressor_shadow_fails_cleanly_without_git(monkeypatch, tmp_path):
- from utils import transformers_version as tv
-
- monkeypatch.setattr(tv, "_llmcompressor_shadow_is_valid", lambda: False)
- monkeypatch.setattr(tv, "_llmcompressor_main_disabled", lambda: False)
- monkeypatch.setattr(tv, "_env_offline", lambda: False)
- monkeypatch.setattr(tv, "_VENV_LLMCOMPRESSOR_DIR", str(tmp_path / "shadow"))
-
- def no_git(**k):
- raise git_tool.GitUnavailable("Git is required")
-
- monkeypatch.setattr(git_tool, "ensure_git", no_git)
- monkeypatch.setattr(tv.subprocess, "run", lambda *a, **k: pytest.fail("ran an install"))
- assert tv._ensure_venv_llmcompressor_exists() is False
-
-
[email protected](git_tool.os.name != "nt", reason = "runs the real MinGit git.exe")
-def test_real_mingit_runs_on_windows(monkeypatch, tmp_path):
- monkeypatch.setattr(git_tool.shutil, "which", lambda name: None)
- monkeypatch.setattr(git_tool, "studio_root", lambda: tmp_path)
- git_dir = git_tool.ensure_git()
- out = git_tool.subprocess.run(
- [str(git_tool.Path(git_dir) / "git.exe"), "--version"],
- capture_output = True,
- text = True,
- check = True,
- )
- assert git_tool.MINGIT_VERSION.rsplit(".", 1)[0] in out.stdout
-
-
-def test_bundled_git_uses_the_windows_certificate_store():
- env = git_tool.with_git_on_path({"PATH": "x", "GIT_CONFIG_COUNT": "1"}, r"C:\s\mingit\cmd")
- assert env["GIT_CONFIG_COUNT"] == "2"
- assert (env["GIT_CONFIG_KEY_1"], env["GIT_CONFIG_VALUE_1"]) == ("http.sslBackend", "schannel")
- assert "GIT_CONFIG_COUNT" not in git_tool.with_git_on_path({"PATH": "x"}, None)
diff --git a/studio/backend/tests/test_llmcompressor_shadow_source.py b/studio/backend/tests/test_llmcompressor_shadow_source.py
new file mode 100644
index 00000000000..8469aa284c0
--- /dev/null
+++ b/studio/backend/tests/test_llmcompressor_shadow_source.py
@@ -0,0 +1,240 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The llm-compressor-main shadow installs from a checksummed source archive, never git."""
+
+from __future__ import annotations
+
+import io
+import tarfile
+
+import pytest
+
+from utils import transformers_version as tv
+
+
+def _archive_bytes(
+ root = None,
+ files = None,
+ level = 9,
+) -> bytes:
+ root = root or f"llm-compressor-{tv._LLMC_MAIN_SHA}"
+ files = files or {"setup.py": b"from setuptools import setup\n"}
+ buf = io.BytesIO()
+ with tarfile.open(fileobj = buf, mode = "w:gz", compresslevel = level) as tar:
+ for name, data in files.items():
+ info = tarfile.TarInfo(f"{root}/{name}")
+ info.size = len(data)
+ tar.addfile(info, io.BytesIO(data))
+ return buf.getvalue()
+
+
+def _digest(tmp_path, payload: bytes) -> str:
+ archive = tmp_path / "digest.tgz"
+ archive.write_bytes(payload)
+ return tv._archive_content_digest(archive)
+
+
+class _Response(io.BytesIO):
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+
+def shadow(monkeypatch, tmp_path):
+ from utils import utils as studio_utils
+
+ # No ambient proxy: these tests stub urlopen, a proxy opener would reach GitHub for real.
+ monkeypatch.setattr(tv, "_hf_proxy_opener", lambda url: None)
+ monkeypatch.setattr(studio_utils, "hf_proxy_for_endpoint", lambda url = None: None)
+ monkeypatch.setattr(tv, "_llmcompressor_shadow_is_valid", lambda: False)
+ monkeypatch.setattr(tv, "_llmcompressor_main_disabled", lambda: False)
+ monkeypatch.setattr(tv, "_env_offline", lambda: False)
+ monkeypatch.setattr(tv, "_VENV_LLMCOMPRESSOR_DIR", str(tmp_path / "shadow"))
+ return tmp_path
+
+
+def _serve(
+ monkeypatch,
+ tmp_path,
+ payload: bytes,
+ digest: str | None = None,
+):
+ monkeypatch.setattr(tv, "_LLMC_MAIN_ARCHIVE_DIGEST", digest or _digest(tmp_path, payload))
+ monkeypatch.setattr(tv, "_hf_proxy_opener", lambda url: None)
+ urls = []
+
+ def fake_urlopen(request, timeout = None):
+ urls.append(request.full_url)
+ return _Response(payload)
+
+ monkeypatch.setattr(tv.urllib.request, "urlopen", fake_urlopen)
+ return urls
+
+
+def test_installs_the_extracted_source_with_no_git_requirement(monkeypatch, shadow):
+ urls = _serve(monkeypatch, shadow, _archive_bytes())
+ seen = []
+
+ class _Done:
+ returncode = 0
+ stdout = ""
+
+ def fake_run(cmd, **kwargs):
+ source = next(a for a in cmd if a.endswith(f"llm-compressor-{tv._LLMC_MAIN_SHA}"))
+ archival = (tv.Path(source) / ".git_archival.txt").read_text(encoding = "utf-8")
+ seen.append((cmd, archival))
+ return _Done()
+
+ monkeypatch.setattr(tv.subprocess, "run", fake_run)
+ assert tv._ensure_venv_llmcompressor_exists() is True
+ assert urls == [
+ f"https://github.com/vllm-project/llm-compressor/archive/{tv._LLMC_MAIN_SHA}.tar.gz"
+ ]
+ cmd, archival = seen[0]
+ assert not any("git+" in a for a in cmd)
+ assert f"node: {tv._LLMC_MAIN_SHA}" in archival
+ assert f"describe-name: {tv._LLMC_MAIN_DESCRIBE}-g{tv._LLMC_MAIN_SHA[:8]}" in archival
+ assert not list(shadow.glob(".llmc-src-*"))
+
+
+def test_checksum_mismatch_installs_nothing(monkeypatch, shadow):
+ _serve(monkeypatch, shadow, _archive_bytes(), digest = "0" * 64)
+ monkeypatch.setattr(tv.subprocess, "run", lambda *a, **k: pytest.fail("ran an install"))
+ assert tv._ensure_venv_llmcompressor_exists() is False
+
+
+def test_network_error_fails_cleanly(monkeypatch, shadow):
+ def boom(*a, **k):
+ raise OSError("connection reset")
+
+ monkeypatch.setattr(tv.urllib.request, "urlopen", boom)
+ monkeypatch.setattr(tv.subprocess, "run", lambda *a, **k: pytest.fail("ran an install"))
+ assert tv._ensure_venv_llmcompressor_exists() is False
+
+
+def test_content_digest_ignores_compression_order_and_root_name(tmp_path):
+ files = {"a.py": b"a = 1\n", "pkg/b.py": b"b = 2\n"}
+ base = _digest(tmp_path, _archive_bytes(files = files))
+ reordered = dict(reversed(list(files.items())))
+ assert _digest(tmp_path, _archive_bytes("renamed-root", reordered, level = 1)) == base
+ assert _digest(tmp_path, _archive_bytes(files = {**files, "a.py": b"a = 3\n"})) != base
+
+
+def test_the_download_goes_through_the_proxy_aware_opener(monkeypatch, shadow):
+ payload = _archive_bytes()
+ _serve(monkeypatch, shadow, payload)
+ opened = []
+
+ class _Opener:
+ def open(
+ self,
+ request,
+ timeout = None,
+ ):
+ opened.append(request.full_url)
+ return _Response(payload)
+
+ monkeypatch.setattr(tv, "_hf_proxy_opener", lambda url: _Opener())
+ monkeypatch.setattr(
+ tv.urllib.request, "urlopen", lambda *a, **k: pytest.fail("bypassed the proxy")
+ )
+ assert tv._download_llmcompressor_source(shadow).is_dir()
+ assert opened
+
+
+def test_a_socks_proxy_is_used_through_httpx_never_bypassed(monkeypatch, shadow):
+ import httpx
+
+ from utils import utils as studio_utils
+
+ payload = _archive_bytes()
+ _serve(monkeypatch, shadow, payload)
+ monkeypatch.setattr(
+ studio_utils, "hf_proxy_for_endpoint", lambda url = None: "socks5://proxy:1080"
+ )
+ monkeypatch.setattr(
+ tv.urllib.request, "urlopen", lambda *a, **k: pytest.fail("bypassed the socks proxy")
+ )
+ streamed = []
+
+ class _Stream:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ def raise_for_status(self):
+ pass
+
+ def iter_bytes(self, size):
+ yield payload
+
+ def fake_stream(method, url, **kwargs):
+ streamed.append(url)
+ return _Stream()
+
+ monkeypatch.setattr(httpx, "stream", fake_stream)
+ assert tv._download_llmcompressor_source(shadow).is_dir()
+ assert streamed
+
+
+def test_a_socks_proxy_without_socksio_fails_closed_with_the_fix(monkeypatch, shadow):
+ import httpx
+
+ from utils import utils as studio_utils
+
+ monkeypatch.setattr(
+ studio_utils, "hf_proxy_for_endpoint", lambda url = None: "socks5://proxy:1080"
+ )
+ monkeypatch.setattr(
+ tv.urllib.request, "urlopen", lambda *a, **k: pytest.fail("bypassed the socks proxy")
+ )
+
+ def no_socksio(*a, **k):
+ raise ImportError("Using SOCKS proxy, but the 'socksio' package is not installed.")
+
+ monkeypatch.setattr(httpx, "stream", no_socksio)
+ with pytest.raises(RuntimeError, match = "socksio"):
+ tv._download_llmcompressor_source(shadow)
+
+
+def test_pinned_archive_matches_its_checksum(tmp_path):
+ source = tv._download_llmcompressor_source(tmp_path)
+ # Namespace dirs the archive build keeps only via .git_archival.txt.
+ assert (source / "src/llmcompressor/modeling/moe/context.py").is_file()
+ assert (source / ".git_archival.txt").is_file()
+
+
+def test_the_archive_builds_the_whole_package_without_git(tmp_path, monkeypatch):
+ import subprocess
+ import sys
+
+ monkeypatch.setenv("PATH", "") # no git for setuptools_scm to fall back on
+ source = tv._download_llmcompressor_source(tmp_path)
+ target = tmp_path / "site"
+ subprocess.run(
+ [
+ sys.executable,
+ "-m",
+ "pip",
+ "install",
+ "-q",
+ "--no-deps",
+ "--target",
+ str(target),
+ str(source),
+ ],
+ check = True,
+ )
+ package = target / "llmcompressor"
+ assert (package / "modeling" / "moe" / "context.py").is_file()
+ assert (package / "modeling" / "patch").is_dir()
+ version = (package / "version.py").read_text(encoding = "utf-8")
+ assert f"+g{tv._LLMC_MAIN_SHA[:8]}" in version
diff --git a/studio/backend/utils/git_tool.py b/studio/backend/utils/git_tool.py
deleted file mode 100644
index 42e3c68ae74..00000000000
--- a/studio/backend/utils/git_tool.py
+++ /dev/null
@@ -1,144 +0,0 @@
-# SPDX-License-Identifier: AGPL-3.0-only
-# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-
-"""Git on demand for ``git+`` installs. A working system Git is used as is; on Windows a missing one
-is fetched once as portable MinGit into the Studio home (no admin, no winget) and put on the child's
-PATH only. Elsewhere installing Git needs root, so callers get an error with instructions."""
-
-from __future__ import annotations
-
-import hashlib
-import os
-import platform
-import shutil
-import subprocess
-import tempfile
-import urllib.request
-import zipfile
-from pathlib import Path
-from typing import Optional
-
-from filelock import FileLock
-
-from utils.paths.storage_roots import studio_root
-
-# Bump all three together; digests are GitHub's published asset digests for that release.
-MINGIT_VERSION = "2.56.0.2"
-_MINGIT_TAG = "v2.56.0.windows.2"
-_MINGIT_SHA256 = {
- "64-bit": "da35e72aa21c005a5a0d298cfbae110bc1609a815730ea0dde84b01a1b3cd3be",
- "arm64": "38b33dc6024026e3315cf88ab2cfea65205bbd7bb3a8e824bd21c8ad4fe609a7",
-}
-
-
-_IS_WINDOWS = os.name == "nt"
-
-
-class GitUnavailable(RuntimeError):
- pass
-
-
-def _git_works(exe: str) -> bool:
- try:
- return (
- subprocess.run(
- [exe, "--version"],
- stdout = subprocess.DEVNULL,
- stderr = subprocess.DEVNULL,
- timeout = 30,
- ).returncode
- == 0
- )
- except (OSError, subprocess.SubprocessError):
- return False
-
-
-def _mingit_flavor() -> str:
- arch = (
- os.environ.get("PROCESSOR_ARCHITEW6432")
- or os.environ.get("PROCESSOR_ARCHITECTURE")
- or platform.machine()
- )
- return "arm64" if arch.strip().lower() == "arm64" else "64-bit"
-
-
-def _mingit_dir(flavor: str) -> Path:
- return studio_root() / "tools" / f"mingit-{MINGIT_VERSION}-{flavor}"
-
-
-def _mingit_git(root: Path) -> Path:
- return root / "cmd" / "git.exe"
-
-
-def _download_mingit(flavor: str, target: Path) -> None:
- name = f"MinGit-{MINGIT_VERSION}-{flavor}.zip"
- url = f"https://github.com/git-for-windows/git/releases/download/{_MINGIT_TAG}/{name}"
- target.parent.mkdir(parents = True, exist_ok = True)
- with tempfile.TemporaryDirectory(dir = target.parent, prefix = ".mingit-") as tmp:
- archive = Path(tmp) / name
- digest = hashlib.sha256()
- request = urllib.request.Request(url, headers = {"User-Agent": "unsloth-studio"})
- with urllib.request.urlopen(request, timeout = 300) as response, open(archive, "wb") as out:
- while chunk := response.read(1 << 20):
- digest.update(chunk)
- out.write(chunk)
- if digest.hexdigest() != _MINGIT_SHA256[flavor]:
- raise GitUnavailable(f"{name} failed its sha256 check; not installing it")
- staged = Path(tmp) / "mingit"
- with zipfile.ZipFile(archive) as zf:
- base = staged.resolve()
- for member in zf.namelist():
- if not (staged / member).resolve().is_relative_to(base):
- raise GitUnavailable(f"{name} has an entry outside its root: {member}")
- zf.extractall(staged)
- if not _git_works(str(_mingit_git(staged))):
- raise GitUnavailable(f"git from {name} does not run on this machine")
- os.replace(staged, target)
-
-
-def ensure_git(*, allow_download: bool = True) -> Optional[str]:
- """None when Git on PATH works, else a dir to prepend to a child's PATH (Windows MinGit).
- Raises GitUnavailable when Git is missing and cannot be provided here."""
- exe = shutil.which("git")
- if exe and _git_works(exe):
- return None
- if not _IS_WINDOWS:
- raise GitUnavailable(
- "Git is required for this step but is not installed. Install it with your package "
- "manager (for example `sudo apt install git` or `xcode-select --install`) and retry."
- )
- flavor = _mingit_flavor()
- root = _mingit_dir(flavor)
- if _git_works(str(_mingit_git(root))):
- return str(root / "cmd")
- if not allow_download:
- raise GitUnavailable("Git is required for this step and this process is offline.")
- root.parent.mkdir(parents = True, exist_ok = True)
- with FileLock(str(root.parent / ".mingit.lock"), timeout = 600):
- if not _git_works(str(_mingit_git(root))):
- if root.exists():
- shutil.rmtree(root, ignore_errors = True)
- try:
- _download_mingit(flavor, root)
- except GitUnavailable:
- raise
- except Exception as exc: # network, disk, bad zip
- raise GitUnavailable(f"Could not download portable Git (MinGit): {exc}") from exc
- return str(root / "cmd")
-
-
-def with_git_on_path(env: dict, git_dir: Optional[str]) -> dict:
- if not git_dir:
- return env
- env = dict(env)
- key = next((k for k in env if k.upper() == "PATH"), "PATH")
- env[key] = git_dir + os.pathsep + env.get(key, "")
- # MinGit ships no installer config; schannel makes it trust the Windows certificate store.
- try:
- n = int(env.get("GIT_CONFIG_COUNT") or 0)
- except ValueError:
- n = 0
- env[f"GIT_CONFIG_KEY_{n}"] = "http.sslBackend"
- env[f"GIT_CONFIG_VALUE_{n}"] = "schannel"
- env["GIT_CONFIG_COUNT"] = str(n + 1)
- return env
diff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.py
index 92e6855cd99..b5861511553 100644
--- a/studio/backend/utils/transformers_version.py
+++ b/studio/backend/utils/transformers_version.py
@@ -32,6 +32,7 @@ import ast
import importlib
import importlib.util
import json
+import hashlib
import structlog
from loggers import get_logger
import errno
@@ -43,6 +44,9 @@ import stat
import subprocess
import sys
import sysconfig
+import tarfile
+import tempfile
+import urllib.request
import threading
import time
from pathlib import Path
@@ -3738,10 +3742,14 @@ def ensure_latest_transformers_venv(
_LLMC_MAIN_TRANSFORMERS = "5.10.2"
_LLMC_MAIN_SHA = "973c9c539a84dd9efaf74e115ede5ca419704c18"
_LLMC_MAIN_COMPRESSED_TENSORS = "0.17.2a20260702"
-# Installed --no-deps (torch untouched); the full runtime set llm-compressor main needs, pinned.
+# Content digest of GitHub's source archive of _LLMC_MAIN_SHA (_archive_content_digest), and
+# `git describe` of that commit. GitHub keeps an archive's contents stable, not its bytes.
+_LLMC_MAIN_ARCHIVE_DIGEST = "63ccb4f99833e3b24602f18a1e386e6c1127c1a84f7fc4e8ff56336c929138f8"
+_LLMC_MAIN_DESCRIBE = "0.12.0-40"
+# Installed --no-deps (torch untouched) beside llmcompressor's source tree; the full runtime set
+# llm-compressor main needs, pinned.
_VENV_LLMCOMPRESSOR_SPECS = (
f"transformers=={_LLMC_MAIN_TRANSFORMERS}",
- f"llmcompressor @ git+https://github.com/vllm-project/llm-compressor@{_LLMC_MAIN_SHA}",
f"compressed-tensors=={_LLMC_MAIN_COMPRESSED_TENSORS}",
"huggingface-hub==1.21.0",
"hf-xet==1.5.1",
@@ -3808,28 +3816,98 @@ def _ensure_venv_llmcompressor_exists() -> bool:
)
return False
- # llmcompressor is a git+ requirement, and uv / pip shell out to git for it.
- from utils.git_tool import GitUnavailable, ensure_git, with_git_on_path
-
- try:
- git_dir = ensure_git()
- except GitUnavailable as exc:
- logger.error("Cannot provision llm-compressor-main shadow: %s", exc)
- return False
-
logger.warning(
"Provisioning llm-compressor-main shadow at %s (one-time, ~a few hundred MB, no torch) ...",
_VENV_LLMCOMPRESSOR_DIR,
)
shutil.rmtree(_VENV_LLMCOMPRESSOR_DIR, ignore_errors = True)
os.makedirs(_VENV_LLMCOMPRESSOR_DIR, exist_ok = True)
+ with tempfile.TemporaryDirectory(
+ dir = os.path.dirname(_VENV_LLMCOMPRESSOR_DIR), prefix = ".llmc-src-"
+ ) as tmp:
+ try:
+ source = _download_llmcompressor_source(Path(tmp))
+ except Exception as exc: # network, checksum, bad archive
+ logger.error("Cannot provision llm-compressor-main shadow: %s", exc)
+ return False
+ return _install_llmcompressor_shadow(source)
+
+
+def _download_llmcompressor_source(parent: Path) -> Path:
+ """The pinned commit from GitHub's source archive, sha256-checked: no git needed.
+ setuptools_scm lists package files and the version from git. Without an expanded
+ .git_archival.txt an archive build silently drops modeling/moe and modeling/patch
+ (no __init__.py) and has no version, so one is written for the pinned commit.
+ """
+ from utils.llama_cpp_source import safe_extract_tar
+
+ url = f"https://github.com/vllm-project/llm-compressor/archive/{_LLMC_MAIN_SHA}.tar.gz"
+ archive = parent / "llm-compressor.tar.gz"
+ headers = {"User-Agent": "unsloth-studio"}
+ opener = _hf_proxy_opener(url) # honours ALL_PROXY, which plain urlopen ignores for https
+ from utils.utils import hf_proxy_for_endpoint, hf_proxy_usable_by_urllib
+
+ proxy = hf_proxy_for_endpoint(url)
+ if opener is None and not hf_proxy_usable_by_urllib(proxy):
+ # A socks proxy urllib cannot speak: go through it as the Hub client does, never direct.
+ import httpx
+ try:
+ with httpx.stream("GET", url, headers = headers, follow_redirects = True, timeout = 300) as r:
+ r.raise_for_status()
+ with open(archive, "wb") as out:
+ for chunk in r.iter_bytes(1 << 20):
+ out.write(chunk)
+ except ImportError as exc: # httpx needs socksio for socks
+ raise RuntimeError(
+ f"the configured proxy {proxy} needs SOCKS support: install socksio "
+ "(pip install socksio) or set HTTPS_PROXY to an http(s) proxy"
+ ) from exc
+ else:
+ request = urllib.request.Request(url, headers = headers)
+ with (opener.open if opener else urllib.request.urlopen)(request, timeout = 300) as response:
+ with open(archive, "wb") as out:
+ shutil.copyfileobj(response, out, 1 << 20)
+ if _archive_content_digest(archive) != _LLMC_MAIN_ARCHIVE_DIGEST:
+ raise RuntimeError(f"{url} failed its content checksum")
+ safe_extract_tar(archive, parent)
+ source = parent / f"llm-compressor-{_LLMC_MAIN_SHA}"
+ (source / ".git_archival.txt").write_text(
+ f"node: {_LLMC_MAIN_SHA}\ndescribe-name: {_LLMC_MAIN_DESCRIBE}-g{_LLMC_MAIN_SHA[:8]}\n",
+ encoding = "utf-8",
+ )
+ return source
+
+
+def _archive_content_digest(archive: Path) -> str:
+ """sha256 over each file's path and contents, independent of compression, member order and
+ the root directory name."""
+ entries = []
+ with tarfile.open(archive, "r:gz") as tar:
+ for member in tar:
+ rel = member.name.split("/", 1)[1] if "/" in member.name else ""
+ if member.isfile():
+ file_digest = hashlib.sha256()
+ handle = tar.extractfile(member)
+ while chunk := handle.read(1 << 20):
+ file_digest.update(chunk)
+ entries.append(f"f {rel} {file_digest.hexdigest()}")
+ elif member.issym() or member.islnk():
+ entries.append(f"l {rel} {member.linkname}")
+ digest = hashlib.sha256()
+ for entry in sorted(entries):
+ digest.update(entry.encode("utf-8") + b"\n")
+ return digest.hexdigest()
+
+
+def _install_llmcompressor_shadow(source: Path) -> bool:
# Prefer uv then pip; every spec at once, --no-deps, prereleases allowed (compressed-tensors).
base = [
"--target",
_VENV_LLMCOMPRESSOR_DIR,
"--no-deps",
"--prerelease=allow",
+ str(source),
*_VENV_LLMCOMPRESSOR_SPECS,
]
cmds = []
@@ -3855,11 +3933,8 @@ def _ensure_venv_llmcompressor_exists() -> bool:
text = True,
encoding = "utf-8",
errors = "replace",
- env = with_git_on_path(
- utf8_child_env(
- get_hf_cache_paths().child_env(child_env_without_native_path_secret())
- ),
- git_dir,
+ env = utf8_child_env(
+ get_hf_cache_paths().child_env(child_env_without_native_path_secret())
),
**_windows_hidden_subprocess_kwargs(),
)