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: resume the Gemma body brace scan from its last end instead of rewalking the open body every token (#16346)
Daniel Han955df7ea0f9a
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 0fb520eace7..04ffcf4eb1f 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -2544,24 +2544,30 @@ def _sniff_text_tool_name(text: str, enabled_names: set) -> str:return ""-def _is_rehearsal_prefix(stripped: str, active_tools: list[dict]) -> bool:+def _is_rehearsal_prefix(+ stripped: str,+ active_tools: list[dict],+ *,+ _names: Optional[list] = None,+) -> bool:"""Execution-class names stream rather than being held; otherwise it mirrors the safetensors loop."""if not stripped or any(ch.isspace() for ch in stripped):return False- for name in _gguf_active_tool_names(active_tools):+ for name in _gguf_active_tool_names(active_tools) if _names is None else _names:# Use the shared gate, which also refuses mcp__* names.- if not _markerless_promotable(name, None):- continue- if stripped == name or f"{name}[ARGS]".startswith(stripped):+ if (stripped == name or f"{name}[ARGS]".startswith(stripped)) and _markerless_promotable(+ name, None+ ):return Truereturn Falsedef _held_rehearsal_tail_len(text: str, active_tools: list[dict]) -> int:"""Holds a trailing bare tool name back while its [ARGS] may still arrive, including a bare-Gemma call:NAME{ prefix that the signal scan misses until its brace."""+ names = _gguf_active_tool_names(active_tools)# A tail longer than every NAME[ARGS] cannot be a prefix, so the scan stops there (CJK has no spaces).limit = max(- (len(name) for name in _gguf_active_tool_names(active_tools) if isinstance(name, str)),+ (len(name) for name in names if isinstance(name, str)),default = 0,) + len("[ARGS]")i = len(text)@@ -2570,11 +2576,11 @@ def _held_rehearsal_tail_len(text: str, active_tools: list[dict]) -> int:i -= 1tail = text[i:]held = (- len(tail) if tail and len(tail) <= limit and _is_rehearsal_prefix(tail, active_tools) else 0- )- return max(- held, held_bare_gemma_tail_len(text, lambda: set(_gguf_active_tool_names(active_tools)))+ len(tail)+ if tail and len(tail) <= limit and _is_rehearsal_prefix(tail, active_tools, _names = names)+ else 0)+ return max(held, held_bare_gemma_tail_len(text, lambda: set(names)))def _should_suppress_forced_no_tool_output(text: str, previous: str = "") -> bool:diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.pyindex 24afe033b50..335ae534297 100644--- a/studio/backend/core/inference/safetensors_agentic.py+++ b/studio/backend/core/inference/safetensors_agentic.py@@ -133,6 +133,7 @@ def _is_rehearsal_prefix(active_tools: list[dict],*,unrestricted: bool = False,+ _names: Optional[list] = None,) -> bool:"""Names that are not markerless-promotable stream as prose rather than being held for a call."""if not stripped or any(ch.isspace() for ch in stripped):@@ -143,11 +144,11 @@ def _is_rehearsal_prefix(name, bracket, _ = stripped.partition("[")# Until '[' lands the name is open: terminal may yet become terminal_logs.return not bracket or _markerless_promotable(name, None)- for name in _active_tool_names(active_tools):+ for name in _active_tool_names(active_tools) if _names is None else _names:# Shared gate, not the built-in three: refuses mcp__* names too, and holding a suffix hides text.- if not _markerless_promotable(name, None):- continue- if stripped == name or f"{name}[ARGS]".startswith(stripped):+ if (stripped == name or f"{name}[ARGS]".startswith(stripped)) and _markerless_promotable(+ name, None+ ):return Truereturn False@@ -159,12 +160,13 @@ def _held_rehearsal_tail_len(unrestricted: bool = False,) -> int:"""Length of a trailing bare tool-name token held while streaming so the name does not leak; also call:NAME{ prefixes, seen only once the brace arrives."""+ names = None if unrestricted else _active_tool_names(active_tools)# Restricted mode: same NAME[ARGS] bound as llama_cpp._held_rehearsal_tail_len.limit = (len(text)if unrestrictedelse max(- (len(name) for name in _active_tool_names(active_tools) if isinstance(name, str)),+ (len(name) for name in names if isinstance(name, str)),default = 0,)+ len("[ARGS]")@@ -178,15 +180,10 @@ def _held_rehearsal_tail_len(len(tail)if tailand len(tail) <= limit- and _is_rehearsal_prefix(tail, active_tools, unrestricted = unrestricted)+ and _is_rehearsal_prefix(tail, active_tools, unrestricted = unrestricted, _names = names)else 0)- return max(- held,- held_bare_gemma_tail_len(- text, lambda: None if unrestricted else _active_tool_names(active_tools)- ),- )+ return max(held, held_bare_gemma_tail_len(text, lambda: names))def _rehearsal_name_start(diff --git a/studio/backend/core/inference/tool_call_parser.py b/studio/backend/core/inference/tool_call_parser.pyindex d0e8d75b833..ec579d9d305 100644--- a/studio/backend/core/inference/tool_call_parser.py+++ b/studio/backend/core/inference/tool_call_parser.py@@ -3160,22 +3160,49 @@ def _parse_gemma_tool_calls(_balanced_brace_end = _tool_healing._balanced_brace_end+# Streaming rescans one growing body per token: saved walks resume at their old end.+_GEMMA_BODY_SCAN_SLOTS = 8+_GEMMA_BODY_SCAN_MIN = 256+_gemma_body_scans: list = [None] * _GEMMA_BODY_SCAN_SLOTS+_gemma_body_scan_next = 0++def _gemma_body_brace_end(text: str, brace_pos: int) -> int | None:"""Closing brace of a Gemma body; quotes hide braces, but a single quote opens only at value start, so apostrophes in prose do not."""+ global _gemma_body_scan_nextif brace_pos >= len(text) or text[brace_pos] != "{":return None+ n = len(text)depth = 0quote = ""prev = ""prev_raw = ""i = brace_pos- n = len(text)+ hit = -1+ for k, entry in enumerate(tuple(_gemma_body_scans)):+ if (+ entry is not None+ and entry[1] == brace_pos+ and entry[2] > i+ and len(entry[0]) <= n+ and text.startswith(entry[0])+ ):+ if entry[3] is not None:+ return entry[3]+ i, depth, quote, prev, prev_raw = entry[2], entry[4], entry[5], entry[6], entry[7]+ hit = k+ break+ start = i+ end = Nonewhile i < n:ch = text[i]if quote:- if ch == "\\" and i + 1 < n:- i += 2- continue+ if ch == "\\":+ if i + 1 < n:+ i += 2+ continue+ # A trailing backslash escapes whatever arrives next: stop before it.+ breakif ch == quote:quote = ""elif ch in "\"'" and (prev in ":{[(,=" or (ch == '"' and prev_raw.isspace())):@@ -3185,12 +3212,20 @@ def _gemma_body_brace_end(text: str, brace_pos: int) -> int | None:elif ch == "}":depth -= 1if depth == 0:- return i+ end = i+ breakif not ch.isspace():prev = chprev_raw = chi += 1- return None+ if i > start and (hit >= 0 or i - start >= _GEMMA_BODY_SCAN_MIN):+ prefix = text if end is None and i == n else text[: (end + 1 if end is not None else i)]+ slot = hit+ if slot < 0:+ slot = _gemma_body_scan_next % _GEMMA_BODY_SCAN_SLOTS+ _gemma_body_scan_next = slot + 1+ _gemma_body_scans[slot] = (prefix, brace_pos, i, end, depth, quote, prev, prev_raw)+ return end_BARE_JSON_NAME_RE = re.compile(r'"name"\s*:\s*"([^"]+)"')diff --git a/studio/backend/tests/data/refactor_guard/ast_inventory.json b/studio/backend/tests/data/refactor_guard/ast_inventory.jsonindex 01c7c710ee5..a5001282933 100644--- a/studio/backend/tests/data/refactor_guard/ast_inventory.json+++ b/studio/backend/tests/data/refactor_guard/ast_inventory.json@@ -1415,6 +1415,12 @@"_GEMMA_BARE_TC_RE": {"kind": "assign"},+ "_GEMMA_BODY_SCAN_MIN": {+ "kind": "assign"+ },+ "_GEMMA_BODY_SCAN_SLOTS": {+ "kind": "assign"+ },"_GEMMA_JSON_NUMBER_RE": {"kind": "assign"},@@ -1699,6 +1705,12 @@"kind": "def","signature": "text: str, brace_pos: int"},+ "_gemma_body_scan_next": {+ "kind": "assign"+ },+ "_gemma_body_scans": {+ "kind": "assign"+ },"_gemma_call_is_anchored": {"decorators": [],"kind": "def",diff --git a/studio/backend/tests/data/refactor_guard/runtime_inventory.json b/studio/backend/tests/data/refactor_guard/runtime_inventory.jsonindex e3df7a48b81..0f7753108b1 100644--- a/studio/backend/tests/data/refactor_guard/runtime_inventory.json+++ b/studio/backend/tests/data/refactor_guard/runtime_inventory.json@@ -46,6 +46,8 @@"_GEMMA_BARE_SENTINEL","_GEMMA_BARE_TC_PREFIX_RE","_GEMMA_BARE_TC_RE",+ "_GEMMA_BODY_SCAN_MIN",+ "_GEMMA_BODY_SCAN_SLOTS","_GEMMA_JSON_NUMBER_RE","_GEMMA_KEY_RE","_GEMMA_QUOTED_VALUE_RE",@@ -130,6 +132,8 @@"_gemma_balanced_brace_end","_gemma_bare_body_arguments","_gemma_body_brace_end",+ "_gemma_body_scan_next",+ "_gemma_body_scans","_gemma_call_is_anchored","_gemma_coerce_scalar","_gemma_parse_array",diff --git a/studio/backend/tests/test_gemma_body_scan_resume.py b/studio/backend/tests/test_gemma_body_scan_resume.pynew file mode 100644index 00000000000..099a55e5a72--- /dev/null+++ b/studio/backend/tests/test_gemma_body_scan_resume.py@@ -0,0 +1,142 @@+# 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 Gemma body brace scan resumes a saved walk of a prefix; every answer must match a fresh walk."""++import random++import pytest++from core.inference import tool_call_parser as tcp+from core.inference import llama_cpp+from core.inference import safetensors_agentic+++def _fresh_scan(text, brace_pos):+ """The walk before the resume cache, kept verbatim as the oracle."""+ if brace_pos >= len(text) or text[brace_pos] != "{":+ return None+ depth = 0+ quote = ""+ prev = ""+ prev_raw = ""+ i = brace_pos+ n = len(text)+ while i < n:+ ch = text[i]+ if quote:+ if ch == "\\" and i + 1 < n:+ i += 2+ continue+ if ch == quote:+ quote = ""+ elif ch in "\"'" and (prev in ":{[(,=" or (ch == '"' and prev_raw.isspace())):+ quote = ch+ elif ch == "{":+ depth += 1+ elif ch == "}":+ depth -= 1+ if depth == 0:+ return i+ if not ch.isspace():+ prev = ch+ prev_raw = ch+ i += 1+ return None++[email protected](autouse = True)+def _empty_cache():+ tcp._gemma_body_scans[:] = [None] * tcp._GEMMA_BODY_SCAN_SLOTS+ yield+ tcp._gemma_body_scans[:] = [None] * tcp._GEMMA_BODY_SCAN_SLOTS+++_PIECES = [+ "{",+ "}",+ '"',+ "'",+ "\\",+ ":",+ ",",+ " ",+ "\n",+ "x" * 300,+ "abc",+ "é",+ "😀",+ "(",+ "=",+ "`",+]+++def _streams(seed, count):+ rng = random.Random(seed)+ for _ in range(count):+ yield "call:write_file{" + "".join(rng.choice(_PIECES) for _ in range(rng.randint(1, 120)))+++def test_every_prefix_matches_a_fresh_walk():+ for text in _streams(0, 100):+ for end in range(len("call:write_file{"), len(text) + 1):+ prefix = text[:end]+ assert tcp._gemma_body_brace_end(prefix, 15) == _fresh_scan(prefix, 15)+++def test_interleaved_and_rewritten_buffers_match_a_fresh_walk():+ rng = random.Random(1)+ texts = list(_streams(2, 40))+ for _ in range(4000):+ text = rng.choice(texts)+ end = rng.randint(16, len(text))+ probe = text[:end]+ if rng.random() < 0.3:+ k = rng.randrange(16, len(probe)) if len(probe) > 16 else 16+ probe = probe[:k] + rng.choice(_PIECES) + probe[k + 1 :]+ assert tcp._gemma_body_brace_end(probe, 15) == _fresh_scan(probe, 15)+++def test_trailing_backslash_inside_a_quote_is_not_saved_past():+ head = 'call:f{content:"' + "y" * 400+ assert tcp._gemma_body_brace_end(head + "\\", 6) is None+ # The backslash escapes the quote that follows, so the body is still open.+ assert tcp._gemma_body_brace_end(head + '\\"}', 6) is None+ assert tcp._gemma_body_brace_end(head + '\\""}', 6) == len(head) + 3+++def test_open_body_scan_is_saved_at_the_end_of_the_text():+ text = 'call:write_file{content:<|"|>' + "a {b " * 200+ assert tcp._gemma_body_brace_end(text, 15) is None+ saved = [e for e in tcp._gemma_body_scans if e is not None and e[1] == 15]+ assert saved and saved[0][2] == len(text)+ grown = text + "c {d "+ assert tcp._gemma_body_brace_end(grown, 15) is None+ saved = [e for e in tcp._gemma_body_scans if e is not None and e[1] == 15]+ assert len(saved) == 1 and saved[0][2] == len(grown)+++def test_held_tail_lengths_unchanged_for_an_open_gemma_body():+ tools = [{"type": "function", "function": {"name": "write_file"}}]+ text = 'Sure. call:write_file{content:<|"|>'+ for i in range(400):+ text += "{" if i % 50 == 0 else "word "+ expect = len(text) - text.index("call:")+ assert llama_cpp._held_rehearsal_tail_len(text, tools) == expect+ assert safetensors_agentic._held_rehearsal_tail_len(text, tools) == expect+++def test_rehearsal_prefix_still_skips_unpromotable_names():+ tools = [+ {"type": "function", "function": {"name": "terminal"}},+ {"type": "function", "function": {"name": "mcp__fs__read"}},+ {"type": "function", "function": {"name": "web_search"}},+ ]+ assert not llama_cpp._is_rehearsal_prefix("termin", tools)+ assert not llama_cpp._is_rehearsal_prefix("mcp__fs", tools)+ assert llama_cpp._is_rehearsal_prefix("web_search[AR", tools)+ assert not safetensors_agentic._is_rehearsal_prefix("terminal", tools)+ assert safetensors_agentic._is_rehearsal_prefix("web_se", tools)+ assert llama_cpp._held_rehearsal_tail_len("try web_se", tools) == len("web_se")+ assert llama_cpp._held_rehearsal_tail_len("try termin", tools) == 0