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: walk GGUF tokenizer string arrays through one buffer (#15593)
Daniel Han14710d0f6523
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 94ebbf0bbb5..d9ccd917a29 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -2661,6 +2661,7 @@ _MISS = object()# GGUF unsigned value-type id -> byte width (uint8, uint16, uint32, uint64)._GGUF_UINT_WIDTHS = {0: 1, 2: 2, 4: 4, 10: 8}+_GGUF_MARKUP_FIRST_BYTES = frozenset(b"<[")@contextlib.contextmanager@@ -18099,7 +18100,8 @@ class LlamaCppBackend:if elem_sz is not None:f.seek(elem_sz * alen, 1)elif atype == 8:- for _ in range(alen):+ from utils.models.gguf_metadata import skip_gguf_strings+ for _ in range(alen - skip_gguf_strings(f, alen)):slen = struct.unpack("<Q", f.read(8))[0]f.seek(slen, 1)else:@@ -18120,9 +18122,16 @@ class LlamaCppBackend:if atype == 8: # STRING: kept only for the delimiter-shaped entries (#7066).from core.inference.chat_template_helpers import delimiter_shaped_tokens+ from utils.models.gguf_metadata import take_gguf_strings_by_first_byte+ done, raws = take_gguf_strings_by_first_byte(f, alen, _GGUF_MARKUP_FIRST_BYTES)kept: list = []- for _ in range(alen):+ for raw in raws:+ try:+ kept.append(raw.decode("utf-8"))+ except UnicodeDecodeError:+ continue+ for _ in range(alen - done):n = struct.unpack("<Q", f.read(8))[0]raw = f.read(n)# Only <...> / [...] entries are kept, so skip decoding the rest; UTF-8 makes the first bytediff --git a/studio/backend/tests/test_gguf_metadata.py b/studio/backend/tests/test_gguf_metadata.pyindex 3c07e3443e1..08714ef3139 100644--- a/studio/backend/tests/test_gguf_metadata.py+++ b/studio/backend/tests/test_gguf_metadata.py@@ -641,10 +641,13 @@ class _CountingFile:def __init__(self, handle) -> None:self._handle = handleself.operations = 0+ self.furthest = 0def read(self, size = -1):self.operations += 1- return self._handle.read(size)+ data = self._handle.read(size)+ self.furthest = max(self.furthest, self._handle.tell())+ return datadef seek(self,@@ -652,7 +655,9 @@ class _CountingFile:whence = 0,):self.operations += 1- return self._handle.seek(offset, whence)+ pos = self._handle.seek(offset, whence)+ self.furthest = max(self.furthest, pos)+ return posdef __enter__(self):return self@@ -661,8 +666,14 @@ class _CountingFile:return self._handle.__exit__(*exc_info)-def _count_header_operations(monkeypatch, path: Path, read) -> int:- """File operations ``read`` performs against ``path``. Other files are untouched."""+def _count_header_operations(+ monkeypatch,+ path: Path,+ read,+ measure = "operations",+) -> int:+ """File operations ``read`` performs against ``path`` (or, with ``measure="furthest"``, the+ furthest offset it reached). Other files are untouched."""import builtinsreal_open = builtins.open@@ -681,6 +692,8 @@ def _count_header_operations(monkeypatch, path: Path, read) -> int:read(str(path))finally:monkeypatch.undo()+ if measure == "furthest":+ return max(counter.furthest for counter in counters)return sum(counter.operations for counter in counters)@@ -705,9 +718,18 @@ def test_architecture_read_stops_before_a_large_tokenizer_array(tmp_path: Path,whole.write_bytes(p.read_bytes())targeted_ops = _count_header_operations(monkeypatch, targeted, read_gguf_architecture)- whole_ops = _count_header_operations(monkeypatch, whole, read_gguf_general_metadata)+ reach = tmp_path / "reach.gguf"+ reach.write_bytes(p.read_bytes())+ targeted_reach = _count_header_operations(+ monkeypatch, reach, read_gguf_architecture, measure = "furthest"+ )+ whole_reach = _count_header_operations(+ monkeypatch, whole, read_gguf_general_metadata, measure = "furthest"+ )assert targeted_ops < 10, targeted_ops- assert whole_ops > 20000, whole_ops+ # The whole-header read walks the 20000-entry array (one buffered pass); the targeted one stops before it.+ assert targeted_reach < 1024, targeted_reach+ assert whole_reach > 20000 * 8, whole_reachdef test_architecture_is_stripped_and_absent_values_are_none(tmp_path: Path):diff --git a/studio/backend/tests/test_gguf_string_walk.py b/studio/backend/tests/test_gguf_string_walk.pynew file mode 100644index 00000000000..a238186c7eb--- /dev/null+++ b/studio/backend/tests/test_gguf_string_walk.py@@ -0,0 +1,234 @@+# 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 buffered GGUF string-array walkers must leave the stream exactly where the old+one-read-per-entry loops did, and hand back the same entries, for every array shape."""++from __future__ import annotations++import io+import random+import struct++import pytest++from core.inference.llama_cpp import LlamaCppBackend+from utils.models.gguf_metadata import (+ _STRING_SCAN_CHUNK,+ _STRING_SCAN_MAX,+ _skip_gguf_value,+ skip_gguf_strings,+ take_gguf_strings_by_first_byte,+)+++def _entry(raw: bytes) -> bytes:+ return struct.pack("<Q", len(raw)) + raw+++def _random_entries(rng: random.Random, n: int) -> list[bytes]:+ out = []+ for _ in range(n):+ x = rng.random()+ if x < 0.03:+ out.append(b"")+ elif x < 0.15:+ out.append(rng.choice([b"<|im_start|>", b"[INST]", b"<think>"]))+ elif x < 0.2:+ out.append(b"<" + bytes(rng.randrange(256) for _ in range(rng.randrange(4))))+ elif x < 0.21:+ out.append(b"y" * rng.choice([255, 4095, 70000]))+ else:+ out.append(bytes(rng.choice(b"abc \xc4\xa0") for _ in range(rng.randrange(1, 9))))+ return out+++def _array_cases() -> list[tuple[str, bytes, int]]:+ rng = random.Random(0)+ cases = []+ for n in (0, 1, 5, 3000, 60000):+ body = b"".join(_entry(e) for e in _random_entries(rng, n))+ cases.append((f"n{n}", body + b"TAIL", n))+ if body:+ for cut in (1, 7, len(body) // 2, len(body) - 3):+ cases.append((f"n{n}_cut{cut}", body[:cut], n))+ big = [b"a", b"<" + b"z" * _STRING_SCAN_MAX, b"<" + b"z" * (_STRING_SCAN_MAX - 1), b"b"]+ cases.append(("over_scan_max", b"".join(_entry(e) for e in big) + b"TAIL", len(big)))+ straddle = [b"x" * (_STRING_SCAN_CHUNK - 20), b"<straddles the chunk end>", b"[ok]"]+ cases.append(("straddle", b"".join(_entry(e) for e in straddle) + b"TAIL", len(straddle)))+ for bad in ((1 << 30) + 1, 1 << 40, (1 << 64) - 1):+ body = _entry(b"<a>") + struct.pack("<Q", bad) + _entry(b"<b>")+ cases.append((f"bad_len_{bad}", body, 3))+ return cases+++CASES = _array_cases()+++def _old_gm_skip(f, alen: int) -> bool:+ for _ in range(alen):+ slen_bytes = f.read(8)+ if len(slen_bytes) < 8:+ return False+ slen = struct.unpack("<Q", slen_bytes)[0]+ if slen > 1 << 30:+ return False+ f.seek(slen, 1)+ return True+++def _old_llama_skip(f, alen: int) -> None:+ for _ in range(alen):+ slen = struct.unpack("<Q", f.read(8))[0]+ f.seek(slen, 1)+++def _old_llama_take(f, alen: int) -> list:+ kept = []+ for _ in range(alen):+ n = struct.unpack("<Q", f.read(8))[0]+ raw = f.read(n)+ if raw[:1] != b"<" and raw[:1] != b"[":+ continue+ try:+ kept.append(raw.decode("utf-8"))+ except UnicodeDecodeError:+ continue+ return kept+++def _outcome(fn, f, *args):+ try:+ result = ("ok", fn(f, *args))+ except Exception as e: # noqa: BLE001 -- the exception type is part of the contract+ result = ("raised", type(e))+ return result, f.tell()+++def _streams(data: bytes, tmp_path):+ path = tmp_path / "array.bin"+ path.write_bytes(data)+ return [lambda: io.BytesIO(data), lambda: open(path, "rb")]++[email protected]("name,data,count", CASES, ids = [c[0] for c in CASES])+def test_gguf_metadata_skip_matches_entry_loop(name, data, count, tmp_path):+ header = struct.pack("<IQ", 8, count)+ for opener in _streams(header + data, tmp_path):+ with opener() as old, opener() as new:+ assert _outcome(_skip_gguf_value, new, 9) == _outcome(+ lambda f: _old_gm_skip(f, struct.unpack("<IQ", f.read(12))[1]), old+ )++[email protected]("name,data,count", CASES, ids = [c[0] for c in CASES])+def test_llama_skip_and_read_match_entry_loop(name, data, count, tmp_path):+ header = struct.pack("<IQ", 8, count)+ for opener in _streams(header + data, tmp_path):+ with opener() as old, opener() as new:+ want = _outcome(lambda f: _old_llama_skip(f, struct.unpack("<IQ", f.read(12))[1]), old)+ assert _outcome(LlamaCppBackend._gguf_skip_value, new, 9) == want+ with opener() as old, opener() as new:+ old.seek(12)+ new.seek(12)+ from core.inference.chat_template_helpers import delimiter_shaped_tokens++ want = _outcome(lambda f: delimiter_shaped_tokens(_old_llama_take(f, count)), old)+ assert _outcome(LlamaCppBackend._gguf_read_array_value, new, 8, count) == want++[email protected]("name,data,count", CASES, ids = [c[0] for c in CASES])+def test_take_returns_every_matching_entry_in_order(name, data, count):+ f = io.BytesIO(data)+ done, kept = take_gguf_strings_by_first_byte(f, count, frozenset(b"<["))+ ref = io.BytesIO(data)+ want = []+ for _ in range(done):+ n = struct.unpack("<Q", ref.read(8))[0]+ raw = ref.read(n)+ if raw[:1] in (b"<", b"["):+ want.append(raw)+ assert kept == want+ assert f.tell() == ref.tell()+++def test_walk_reads_in_chunks_not_per_entry():+ data = b"".join(_entry(b"tok%d" % i) for i in range(50000))++ class CountingReader(io.BytesIO):+ reads = 0++ def read(self, *args):+ CountingReader.reads += 1+ return super().read(*args)++ f = CountingReader(data)+ assert skip_gguf_strings(f, 50000) == 50000+ assert f.tell() == len(data)+ assert CountingReader.reads < 10+++class _ForwardOnly(io.BytesIO):+ """Skips ahead but cannot seek back, like a pipe that discards; reports that honestly."""++ def seekable(self):+ return False++ def seek(+ self,+ offset,+ whence = 0,+ ):+ target = (+ offset+ if whence == 0+ else self.tell() + offset+ if whence == 1+ else len(self.getvalue()) + offset+ )+ if target < self.tell():+ raise io.UnsupportedOperation("cannot seek back")+ return super().seek(offset, whence)+++class _NoSeekableMethod:+ """read / seek / tell without seekable(), as mmap.mmap was before Python 3.13."""++ def __init__(self, data):+ self._f = io.BytesIO(data)+ self.read, self.seek, self.tell = self._f.read, self._f.seek, self._f.tell+++def test_streams_that_cannot_rewind_skip_entry_by_entry():+ data = b"".join(_entry(e) for e in (b"<a>", b"b", b"[c]")) + b"TAIL"+ for make in (_ForwardOnly, _NoSeekableMethod):+ f = make(data)+ assert skip_gguf_strings(f, 3) == 0+ assert f.tell() == 0+ f = make(data)+ assert take_gguf_strings_by_first_byte(f, 3, frozenset(b"<[")) == (0, [])+ assert f.tell() == 0+ # The callers' own loops still walk the whole array and stop at the tail.+ f = make(data)+ for _ in range(3 - skip_gguf_strings(f, 3)):+ (n,) = struct.unpack("<Q", f.read(8))+ f.seek(n, 1)+ assert f.read() == b"TAIL"+ assert LlamaCppBackend._gguf_read_array_value(make(data), 8, 3) == (+ LlamaCppBackend._gguf_read_array_value(io.BytesIO(data), 8, 3)+ )+++def test_non_seekable_stream_reads_entry_by_entry():+ data = b"".join(_entry(e) for e in (b"<a>", b"b", b"[c]"))++ class NoSeek(io.BytesIO):+ def seekable(self):+ return False++ f = NoSeek(data)+ assert take_gguf_strings_by_first_byte(f, 3, frozenset(b"<[")) == (0, [])+ assert f.tell() == 0+ assert LlamaCppBackend._gguf_read_array_value(NoSeek(data), 8, 3) == (+ LlamaCppBackend._gguf_read_array_value(io.BytesIO(data), 8, 3)+ )diff --git a/studio/backend/utils/models/gguf_metadata.py b/studio/backend/utils/models/gguf_metadata.pyindex 5b25658e09c..5ee369fbef3 100644--- a/studio/backend/utils/models/gguf_metadata.py+++ b/studio/backend/utils/models/gguf_metadata.py@@ -358,6 +358,108 @@ _FIXED_VTYPE_SIZES: Dict[int, int] = {12: 8,}+_U64_AT = struct.Struct("<Q").unpack_from+_STRING_SCAN_CHUNK = 1 << 18+# Longer entries are left to the caller's own per-entry loop, which owns the length checks.+_STRING_SCAN_MAX = 1 << 20+++def _can_rewind(f) -> bool:+ """False for forward-only streams and ``mmap`` before 3.13: the walks seek back after reading ahead."""+ seekable = getattr(f, "seekable", None)+ try:+ return bool(seekable()) if callable(seekable) else False+ except Exception: # noqa: BLE001 -- unknown wrapper: take the per-entry path+ return False+++def skip_gguf_strings(f, count: int) -> int:+ """Skip up to ``count`` GGUF strings (u64 length + bytes) through one buffer; return how many,+ with ``f`` at the next. Stops at an entry over 1 MiB, a length cut short by EOF, or a stream+ that cannot rewind, so the caller's per-entry loop handles the rest exactly as before."""+ if not _can_rewind(f):+ return 0+ unpack = _U64_AT+ buf = b""+ size = pos = done = 0+ while True:+ i = done+ try:+ for i in range(done, count):+ n = unpack(buf, pos)[0]+ if n > _STRING_SCAN_MAX:+ break+ pos += 8 + n+ else:+ i = count+ except struct.error: # length field not in the buffer+ pass+ done = i+ if done == count or pos + 8 <= size:+ break+ # The buffer ends at the file position; refill from buf[pos].+ if pos >= size:+ if pos > size:+ f.seek(pos - size, 1)+ buf = f.read(_STRING_SCAN_CHUNK)+ else:+ buf = buf[pos:] + f.read(_STRING_SCAN_CHUNK)+ pos = 0+ size = len(buf)+ if size < 8:+ break+ f.seek(pos - size, 1)+ return done+++def take_gguf_strings_by_first_byte(+ f, count: int, first_bytes: frozenset[int]+) -> Tuple[int, list[bytes]]:+ """``skip_gguf_strings`` that returns ``(entries read, raw entries whose first byte is in+ first_bytes)``; also stops at an entry cut short by EOF, leaving ``f`` at it."""+ kept: list[bytes] = []+ if not _can_rewind(f):+ return 0, kept+ unpack = _U64_AT+ keep = kept.append+ buf = b""+ size = pos = done = 0+ eof = False+ while True:+ i = done+ try:+ for i in range(done, count):+ n = unpack(buf, pos)[0]+ end = pos + 8 + n+ if end > size or n > _STRING_SCAN_MAX:+ break+ if n and buf[pos + 8] in first_bytes:+ keep(buf[pos + 8 : end])+ pos = end+ else:+ i = count+ except struct.error: # length field not in the buffer+ pass+ progressed = i > done+ done = i+ if done == count:+ break+ if pos + 8 <= size and unpack(buf, pos)[0] > _STRING_SCAN_MAX:+ break+ if eof and not progressed:+ break+ # pos never passes size here; refill with at least the whole next entry.+ want = _STRING_SCAN_CHUNK+ if pos + 8 <= size:+ want = max(want, 8 + unpack(buf, pos)[0])+ more = f.read(want)+ eof = len(more) < want+ buf = buf[pos:] + more+ pos = 0+ size = len(buf)+ f.seek(pos - size, 1)+ return done, kept+def _skip_gguf_value(f, vtype: int) -> bool:"""Advance past one GGUF value. ``f.seek(.., 1)`` past EOF is legal on a regular file, so truncation is caught on the next read; return False only for unknown types or sanity-bound overflow."""@@ -378,7 +480,7 @@ def _skip_gguf_value(f, vtype: int) -> bool:if alen > 1 << 30:return Falseif atype == 8:- for _ in range(alen):+ for _ in range(alen - skip_gguf_strings(f, alen)):slen_bytes = f.read(8)if len(slen_bytes) < 8:return False