Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: prequant fingerprint check on a thread pool, zero-copy (13x faster first load verify) (#16879)
Daniel Han2a6d891c58e2
diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.pyindex f8bafc0afae..59b10acf924 100644--- a/studio/backend/core/inference/diffusion_prequant.py+++ b/studio/backend/core/inference/diffusion_prequant.py@@ -1287,14 +1287,19 @@ _FINGERPRINT_PAYLOAD: dict = {}-def _packed_bytes(tensor: Any, torch: Any) -> bytes:- """``tensor``'s raw bytes via ``view(torch.uint8)``, exact for dtypes numpy cannot represent."""+def _packed_view(tensor: Any, torch: Any) -> Any:+ """``tensor``'s raw bytes as a zero-copy buffer (``view(torch.uint8)``), exact for dtypes numpy cannot represent."""t = tensor.detach().contiguous()if t.dim() == 0:t = t.reshape(1)if t.dtype is not torch.uint8:t = t.view(torch.uint8)- return t.cpu().numpy().tobytes()+ return memoryview(t.cpu().numpy().reshape(-1))+++def _packed_bytes(tensor: Any, torch: Any) -> bytes:+ """``tensor``'s raw bytes via ``view(torch.uint8)``, exact for dtypes numpy cannot represent."""+ return _packed_view(tensor, torch).tobytes()def _hash_packed_payload(tensor: Any, digest: Any, torch: Any) -> bool:@@ -1313,7 +1318,7 @@ def _hash_packed_payload(tensor: Any, digest: Any, torch: Any) -> bool:return Falsehashed = Truecontinue- digest.update(_packed_bytes(value, torch))+ digest.update(_packed_view(value, torch))hashed = Truereturn hashed@@ -1324,23 +1329,13 @@ def packed_weight_fingerprint(state_dict: Any, *, select: Any = None) -> dict:import torch- modules: dict = {}- skipped: list = []- items = state_dict.items() if hasattr(state_dict, "items") else ()- for key, tensor in items:- if key != "weight" and not str(key).endswith(".weight"):- continue- if select is not None and not select(str(key)):- continue+ def _digest(tensor: Any) -> Optional[str]:digest = hashlib.md5()- try:- covered = _hash_packed_payload(tensor, digest, torch)- except Exception: # noqa: BLE001 -- an unreadable payload is uncovered, never a raise- covered = False- if covered:- modules[key] = digest.hexdigest()- else:- skipped.append(key)+ if not _hash_packed_payload(tensor, digest, torch):+ return None+ return digest.hexdigest()++ modules, skipped = _digest_weights(state_dict, select, _digest)return {"algo": FINGERPRINT_ALGO,"count": len(modules),@@ -1423,19 +1418,25 @@ def _all_zero(value: Any, torch: Any) -> bool:return False-def _canonical_bytes(role: str, value: Any, torch: Any) -> bytes:- """Version-stable bytes: ``q`` as stored; others flattened to float32 (exact for stored scales) / int64 zero point."""+def _canonical_parts_of(role: str, value: Any, torch: Any) -> tuple:+ """(head, zero-copy payload) of ``_canonical_bytes``: hashing them in turn gives the same digest without the copies."""t = value.detach()if role == "q":head = f"q:{str(t.dtype).replace('torch.', '')}:{tuple(t.shape)}".encode("utf-8")- return head + _packed_bytes(t, torch)+ return head, _packed_view(t, torch)t = t.reshape(-1)if role in _ZERO_POINT_ROLES:t = t.to(torch.int64)elif t.is_floating_point() and t.dtype is not torch.float64:t = t.to(torch.float32)head = f"{role}:{str(t.dtype).replace('torch.', '')}:{t.numel()}".encode("utf-8")- return head + _packed_bytes(t, torch)+ return head, _packed_view(t, torch)+++def _canonical_bytes(role: str, value: Any, torch: Any) -> bytes:+ """Version-stable bytes: ``q`` as stored; others flattened to float32 (exact for stored scales) / int64 zero point."""+ head, payload = _canonical_parts_of(role, value, torch)+ return head + payload.tobytes()def canonical_weight_digest(tensor: Any) -> Optional[str]:@@ -1452,27 +1453,67 @@ def canonical_weight_digest(tensor: Any) -> Optional[str]:value = parts.get(role)if value is None or (role in _ZERO_POINT_ROLES and _all_zero(value, torch)):continue- digest.update(_canonical_bytes(role, value, torch))+ head, payload = _canonical_parts_of(role, value, torch)+ digest.update(head)+ digest.update(payload)return digest.hexdigest()-def canonical_weight_fingerprint(state_dict: Any, *, select: Any = None) -> dict:- modules: dict = {}- skipped: list = []+# Weights hashed at once by the fingerprint check: md5 (over 2 KiB) and the torch casts release the GIL, so threads+# scale until memory bandwidth does. ``UNSLOTH_PREQUANT_FINGERPRINT_THREADS`` overrides (1 = serial).+FINGERPRINT_THREADS_ENV = "UNSLOTH_PREQUANT_FINGERPRINT_THREADS"+_FINGERPRINT_THREADS_DEFAULT = 8+++def _fingerprint_threads() -> int:+ import os++ raw = str(os.environ.get(FINGERPRINT_THREADS_ENV, "")).strip()+ try:+ wanted = int(raw) if raw else _FINGERPRINT_THREADS_DEFAULT+ except ValueError:+ wanted = _FINGERPRINT_THREADS_DEFAULT+ return max(1, min(wanted, os.cpu_count() or 1))+++def _digest_weights(state_dict: Any, select: Any, digest_of: Any) -> tuple:+ """({fqn: digest}, [uncovered fqns]) over the ``.weight`` entries ``select`` keeps, in state-dict order.++ ``digest_of`` returns None for an uncovered weight; a raise counts as uncovered. Runs on a thread pool."""items = state_dict.items() if hasattr(state_dict, "items") else ()- for key, tensor in items:- if key != "weight" and not str(key).endswith(".weight"):- continue- if select is not None and not select(str(key)):- continue+ picked = [+ (key, tensor)+ for key, tensor in items+ if (key == "weight" or str(key).endswith(".weight"))+ and (select is None or select(str(key)))+ ]++ def _one(tensor: Any) -> Optional[str]:try:- value = canonical_weight_digest(tensor)+ return digest_of(tensor)except Exception: # noqa: BLE001 -- an unreadable payload is uncovered, never a raise- value = None+ return None++ tensors = [tensor for _key, tensor in picked]+ threads = min(_fingerprint_threads(), len(picked))+ if threads > 1:+ from concurrent.futures import ThreadPoolExecutor+ with ThreadPoolExecutor(max_workers = threads, thread_name_prefix = "prequant-fp") as pool:+ values = list(pool.map(_one, tensors))+ else:+ values = [_one(tensor) for tensor in tensors]+ modules: dict = {}+ skipped: list = []+ for (key, _tensor), value in zip(picked, values):if value is None:skipped.append(key)else:modules[key] = value+ return modules, skipped+++def canonical_weight_fingerprint(state_dict: Any, *, select: Any = None) -> dict:+ modules, skipped = _digest_weights(state_dict, select, canonical_weight_digest)return {"algo": CANONICAL_FINGERPRINT_ALGO,"count": len(modules),diff --git a/studio/backend/tests/test_prequant_fingerprint_threads.py b/studio/backend/tests/test_prequant_fingerprint_threads.pynew file mode 100644index 00000000000..9db85765ac4--- /dev/null+++ b/studio/backend/tests/test_prequant_fingerprint_threads.py@@ -0,0 +1,87 @@+# 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 canonical fingerprint is the same whether the weights are hashed serially or on the thread pool, and the+zero-copy digest equals md5 over ``_canonical_bytes`` (the recorded md5-canonical-v2 bytes)."""++from __future__ import annotations++import hashlib++import pytest++torch = pytest.importorskip("torch")+torchao_quant = pytest.importorskip("torchao.quantization")++from core.inference import diffusion_prequant as dp # noqa: E402+++def _int8_state_dict(n = 6, d = 512):+ from core.inference.diffusion_transformer_quant import _make_quant_config++ torch.manual_seed(0)+ model = torch.nn.Sequential(+ *[torch.nn.Linear(d, d, bias = False, dtype = torch.bfloat16) for _ in range(n)]+ )+ torchao_quant.quantize_(model, _make_quant_config("int8"))+ return model.state_dict()+++def test_threaded_fingerprint_equals_serial(monkeypatch):+ sd = _int8_state_dict()+ monkeypatch.setenv(dp.FINGERPRINT_THREADS_ENV, "1")+ serial = dp.canonical_weight_fingerprint(sd)+ monkeypatch.setenv(dp.FINGERPRINT_THREADS_ENV, "4")+ threaded = dp.canonical_weight_fingerprint(sd)+ assert serial["count"] == 6 and not serial["skipped"]+ assert threaded == serial+ assert list(threaded[dp.CANONICAL_FINGERPRINT_KEY]) == list(+ serial[dp.CANONICAL_FINGERPRINT_KEY]+ )+++def test_threaded_packed_v1_fingerprint_equals_serial(monkeypatch):+ sd = _int8_state_dict()+ monkeypatch.setenv(dp.FINGERPRINT_THREADS_ENV, "1")+ serial = dp.packed_weight_fingerprint(sd)+ monkeypatch.setenv(dp.FINGERPRINT_THREADS_ENV, "4")+ threaded = dp.packed_weight_fingerprint(sd)+ assert serial["count"] == 6 and not serial["skipped"]+ assert threaded == serial+++def test_fingerprint_runs_on_the_pool(monkeypatch):+ import threading++ sd = _int8_state_dict(n = 4, d = 256)+ seen = set()+ real = dp.canonical_weight_digest++ def _spy(tensor):+ seen.add(threading.current_thread().name)+ return real(tensor)++ monkeypatch.setattr(dp, "canonical_weight_digest", _spy)+ monkeypatch.setenv(dp.FINGERPRINT_THREADS_ENV, "2")+ dp.canonical_weight_fingerprint(sd)+ assert seen and all(name.startswith("prequant-fp") for name in seen)+++def test_streamed_digest_equals_canonical_bytes():+ sd = _int8_state_dict(n = 1)+ weight = next(v for k, v in sd.items() if k.endswith(".weight"))+ parts = dp._canonical_parts(weight)+ ref = hashlib.md5()+ for role in dp._CANONICAL_ROLE_ORDER:+ value = parts.get(role)+ if value is None or (role in dp._ZERO_POINT_ROLES and dp._all_zero(value, torch)):+ continue+ ref.update(dp._canonical_bytes(role, value, torch))+ assert dp.canonical_weight_digest(weight) == ref.hexdigest()++[email protected]("raw, want", [("1", 1), ("bogus", None), ("", None)])+def test_thread_count_env(monkeypatch, raw, want):+ monkeypatch.setenv(dp.FINGERPRINT_THREADS_ENV, raw)+ got = dp._fingerprint_threads()+ assert got >= 1 and (want is None or got == want)