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
Stop the GGUF header and the chat detail polls from filling the log (#10040)
Daniel Han256db9702528
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 1de303273f8..5434b4eddc9 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -2063,11 +2063,40 @@ def _extract_reasoning_effort_levels(chat_template: str) -> list:]+# Headers already described in the log, keyed on identity rather than name so a rebuilt+# GGUF at the same path is described again. Bounded; a dropped entry only re-logs once.+_GGUF_METADATA_LOGGED: "dict[tuple, bool]" = {}+_GGUF_METADATA_LOGGED_MAX = 32+_GGUF_METADATA_LOGGED_LOCK = threading.Lock()+++def _note_gguf_metadata_read(gguf_path: str) -> bool:+ """True the first time this exact file is read, False for repeats.++ Falls open when the file cannot be stat'd: an unidentifiable read is better logged+ than silently swallowed.+ """+ try:+ st = os.stat(gguf_path)+ key = (os.path.abspath(gguf_path), st.st_size, st.st_mtime_ns)+ except Exception:+ return True+ with _GGUF_METADATA_LOGGED_LOCK:+ if key in _GGUF_METADATA_LOGGED:+ return False+ _GGUF_METADATA_LOGGED[key] = True+ while len(_GGUF_METADATA_LOGGED) > _GGUF_METADATA_LOGGED_MAX:+ # Insertion-ordered, so this drops the oldest.+ del _GGUF_METADATA_LOGGED[next(iter(_GGUF_METADATA_LOGGED))]+ return True++def detect_reasoning_flags(chat_template: Optional[str],model_identifier: Optional[str] = None,*,log_source: Optional[str] = None,+ log_level: str = "info",) -> dict:"""Classify a chat template's reasoning and tool-calling capabilities.@@ -2094,6 +2123,9 @@ def detect_reasoning_flags(return flagstpl = chat_templateprefix = f"{log_source}: " if log_source else ""+ # The GGUF sniffer re-derives these several times per request and the lines say the+ # same thing every time, so it asks for debug after the first read of a file.+ _log = logger.debug if log_level == "debug" else logger.info# 'none' is this style's disable sentinel, not an effort level: the off# switch is enable_thinking=false, and the Think menu already hides it.@@ -2123,14 +2155,14 @@ def detect_reasoning_flags(flags["supports_reasoning"] = Trueflags["reasoning_style"] = "enable_thinking_effort"flags["reasoning_effort_levels"] = effort_levels- logger.info(+ _log(f"{prefix}model supports reasoning "f"(enable_thinking + reasoning_effort: {effort_levels})")elif "enable_thinking" in tpl:flags["supports_reasoning"] = Trueflags["reasoning_style"] = "enable_thinking"- logger.info(f"{prefix}model supports reasoning (enable_thinking)")+ _log(f"{prefix}model supports reasoning (enable_thinking)")elif "reasoning_effort" in tpl:# gpt-oss / Harmony use reasoning_effort# ("low" | "medium" | "high"), not a boolean. Inkling maps a wider@@ -2145,7 +2177,7 @@ def detect_reasoning_flags(scanned = _extract_reasoning_effort_levels(tpl)if "low" in scanned and "high" in scanned:flags["reasoning_effort_levels"] = scanned- logger.info(+ _log(f"{prefix}model supports reasoning "f"(reasoning_effort: {flags['reasoning_effort_levels'] or 'default levels'})")@@ -2154,7 +2186,7 @@ def detect_reasoning_flags(normalized_id = (model_identifier or "").lower()if "deepseek" in normalized_id:flags["supports_reasoning"] = True- logger.info(f"{prefix}model supports reasoning (DeepSeek thinking)")+ _log(f"{prefix}model supports reasoning (DeepSeek thinking)")# Hardcoded <think> tags or reasoning_content in the template mean# thinking is always on (no toggle).@@ -2162,7 +2194,7 @@ def detect_reasoning_flags(if ("<think>" in tpl and "</think>" in tpl) or "reasoning_content" in tpl:flags["supports_reasoning"] = Trueflags["reasoning_always_on"] = True- logger.info(f"{prefix}model always reasons (<think> tags in template)")+ _log(f"{prefix}model always reasons (<think> tags in template)")# preserve_thinking: independent kwarg on some Qwen templates that# keeps historical <think> blocks in prior assistant turns.@@ -2172,11 +2204,11 @@ def detect_reasoning_flags(# used by Qwen3.6 and Gemma 4. Keep the product override family-scoped:# other templates that happen to expose the same kwarg stay off.flags["preserve_thinking_default"] = bool(_QWEN38_MODEL_RE.search(model_identifier or ""))- logger.info(f"{prefix}model supports preserve_thinking")+ _log(f"{prefix}model supports preserve_thinking")if any(marker in tpl for marker in _TOOL_TEMPLATE_MARKERS):flags["supports_tools"] = True- logger.info(f"{prefix}model supports tool calling")+ _log(f"{prefix}model supports tool calling")return flags@@ -12744,15 +12776,23 @@ class LlamaCppBackend:# architecture" rather than "the read stopped early" -- what the preflight needs.self._gguf_header_parsed = kv_complete+ # Ten call sites reach this, each via its own throwaway probe, and one+ # estimate-memory POST walks the header 3-5 times: 140 of 296 log lines+ # over a 20s four-tab session. The facts are identical every time, so only+ # the first read of a given file says them out loud.+ first_read = _note_gguf_metadata_read(gguf_path)+ level = "info" if first_read else "debug"+ log_at = logger.info if first_read else logger.debugif self._context_length:- logger.info(f"GGUF metadata: context_length={self._context_length}")+ log_at(f"GGUF metadata: context_length={self._context_length}")if self._chat_template:- logger.info(f"GGUF metadata: chat_template={len(self._chat_template)} chars")+ log_at(f"GGUF metadata: chat_template={len(self._chat_template)} chars")# Detect thinking/reasoning support from chat template.flags = detect_reasoning_flags(self._chat_template,self._model_identifier,log_source = "GGUF metadata",+ log_level = level,)self._supports_reasoning = flags["supports_reasoning"]self._reasoning_style = flags["reasoning_style"]diff --git a/studio/backend/loggers/handlers.py b/studio/backend/loggers/handlers.pyindex f1d1d14f84e..7b7a8226c85 100644--- a/studio/backend/loggers/handlers.py+++ b/studio/backend/loggers/handlers.py@@ -84,6 +84,9 @@ _QUIET_POLL_PATHS = {# otherwise emit nothing at all."/api/inference/images/load-progress","/api/inference/video/load-progress",+ # Templated; matched through normalize_poll_path. See _TEMPLATED_POLL_PATHS.+ "/api/chat/threads/{id}",+ "/api/chat/threads/{id}/forks",}# The pure-liveness subset of _QUIET_POLL_PATHS. Every one of these answers the same# question ("the server is up and answering"), and the SPA fires them together in one@@ -180,6 +183,29 @@ _CHAT_LIST_PATHS = {"/api/chat/threads","/api/chat/projects",}+# Templated paths. The sets above match EXACTLY, which #7087 chose so detail reads kept+# their access line; what changed is that streaming now drives these two on a loop (25 and+# 21 lines, 34% of the access log, over a 20s four-tab session). So they get a heartbeat+# rather than silence: the first of each window logs with its real path, the rest drop.+_CHAT_THREAD_DETAIL = "/api/chat/threads/{id}"+_CHAT_THREAD_FORKS = "/api/chat/threads/{id}/forks"+_TEMPLATED_POLL_PATHS = frozenset({_CHAT_THREAD_DETAIL, _CHAT_THREAD_FORKS})+# One id segment, no slashes: a deeper path such as /threads/{id}/messages/{mid} must NOT+# collapse into the detail bucket, since a message read is a different question.+_CHAT_THREAD_PATH_RE = re.compile(r"^/api/chat/threads/(?!$)[^/]+(/forks)?$")+++def normalize_poll_path(path: str) -> str:+ """Collapse a per-resource id so a templated path can join a suppression class.++ Used for classification and the de-duplication bucket only; the emitted line still+ carries the real path. One bucket across ids is deliberate, as with the liveness+ group: four tabs polling four threads are still one question.+ """+ m = _CHAT_THREAD_PATH_RE.match(path)+ if m is None:+ return path+ return _CHAT_THREAD_FORKS if m.group(1) else _CHAT_THREAD_DETAIL# The log viewer polls these while reading the very file this middleware writes,@@ -284,10 +310,12 @@ class LoggingMiddleware:# /api/inference/audio/stt/status?model=... extends the downloaded check to a# custom repo, so it keeps its own identity rather than joining the bucket.is_liveness = path in _LIVENESS_POLL_PATHS and not query+ # Bucketed by template, so four tabs polling four threads share one heartbeat.+ norm = normalize_poll_path(path) if not query else pathif path in _WATCHDOG_POLL_PATHS:# Zeroed along with the quiet window, so --verbose still logs every probe.window_ms = _WATCHDOG_POLL_DEDUP_MS if _QUIET_POLL_DEDUP_MS > 0 else 0- elif is_liveness or path in _QUIET_POLL_PATHS:+ elif is_liveness or norm in _QUIET_POLL_PATHS:window_ms = _QUIET_POLL_DEDUP_MSelse:window_ms = _ACCESS_LOG_DEDUP_MS@@ -296,7 +324,7 @@ class LoggingMiddleware:# The liveness group shares one bucket, so a burst of them logs once, not once# per path. Only the query-less form joins it, so a parameterized call still# gets its own status and latency line.- key = _LIVENESS_DEDUP_KEY if is_liveness else (method, path, query, status_code)+ key = _LIVENESS_DEDUP_KEY if is_liveness else (method, norm, query, status_code)last = self._last_log.get(key)if last is not None and (now - last) * 1000.0 < window_ms:return Truediff --git a/studio/backend/tests/log_budget/policy.py b/studio/backend/tests/log_budget/policy.pyindex c39bd297126..b521bd662da 100644--- a/studio/backend/tests/log_budget/policy.py+++ b/studio/backend/tests/log_budget/policy.py@@ -40,6 +40,12 @@ def watchdog_paths(handlers) -> frozenset:return frozenset(getattr(handlers, "_WATCHDOG_POLL_PATHS", frozenset()))+def _normalize(handlers, path: str) -> str:+ """The middleware's templated-path collapse, absent on older revisions."""+ fn = getattr(handlers, "normalize_poll_path", None)+ return fn(path) if fn else path++def classify(handlers, path: str) -> str:"""Which suppression rule owns ``path``. Most specific first.@@ -63,7 +69,8 @@ def classify(handlers, path: str) -> str:return WATCHDOGif path in handlers._LIVENESS_POLL_PATHS:return LIVENESS- if path in handlers._QUIET_POLL_PATHS:+ # The middleware's own normaliser, so classification cannot drift from run time.+ if _normalize(handlers, path) in handlers._QUIET_POLL_PATHS:return QUIETreturn NORMAL@@ -113,4 +120,5 @@ def bucket_of(handlers, path: str) -> str:"""if classify(handlers, path) == LIVENESS:return "\x00liveness"- return path+ # Templated paths share one bucket for the same reason: one question, one line.+ return _normalize(handlers, path)diff --git a/studio/backend/tests/log_budget/session.py b/studio/backend/tests/log_budget/session.pyindex 5d6825dd63e..9689ed78818 100644--- a/studio/backend/tests/log_budget/session.py+++ b/studio/backend/tests/log_budget/session.py@@ -86,6 +86,12 @@ BUSY_POLLS: dict[str, tuple[float, str]] = {# to the log being watched."/api/settings/debug/logs": (3.0, "declared"),"/api/settings/debug/logs/sources": (3.0, "declared"),+ # Chat detail reads, driven by the streaming persistence loop rather than a timer, so+ # busy-only. Measured over four tabs on Qwen3.8-27B UD-Q4_K_XL: thread reads 0.57s+ # apart, fork reads 0.40s apart, aggregated per template because a template shares one+ # bucket. Rounded to the replay's 0.5s tick, the nearest value it can poll on.+ "/api/chat/threads/{id}": (0.5, "measured"),+ "/api/chat/threads/{id}/forks": (0.5, "measured"),# Training panels, live only while a run is going."/api/train/status": (2.0, "declared"),"/api/train/metrics": (2.0, "declared"),@@ -133,8 +139,13 @@ KNOWN_UNCLASSIFIED_POLLS: frozenset[str] = frozenset()## Re-measure and ratchet again whenever a suppression rule changes. An envelope carrying# the old number after a fix has stopped guarding anything.+#+# Busy rose from 260 to 325 for an ACCOUNTING change, not a volume regression.+# /api/chat/threads/{id} and its /forks sibling sat in the `normal` class, in no scenario,+# so the envelope never saw them: modelled over the busy window, 675 lines. A heartbeat+# class brings them in at 59. The number goes up because they are finally being counted.STEADY_IDLE_LINE_ENVELOPE = 1170-BUSY_LINE_ENVELOPE = 260+BUSY_LINE_ENVELOPE = 325# One-shot requests the app makes once on startup. Present so the boot window is not# mistaken for steady state, and so a mutation record and a failure record exist to assertdiff --git a/studio/backend/tests/test_gguf_metadata_log_volume.py b/studio/backend/tests/test_gguf_metadata_log_volume.pynew file mode 100644index 00000000000..23f53c531a5--- /dev/null+++ b/studio/backend/tests/test_gguf_metadata_log_volume.py@@ -0,0 +1,116 @@+# 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 GGUF header block says the same things about the same file every time.++Ten call sites reach ``_read_gguf_metadata`` and one ``POST /api/inference/estimate-memory``+walks the header three to five times: 140 of 296 log lines over a 20s four-tab session.+These tests pin both halves of the fix: repeats are demoted, and demoting them does not+change what is detected.+"""++from __future__ import annotations++import logging++import pytest++from core.inference import llama_cpp++[email protected](autouse = True)+def _clear_seen():+ llama_cpp._GGUF_METADATA_LOGGED.clear()+ yield+ llama_cpp._GGUF_METADATA_LOGGED.clear()+++def _gguf(+ tmp_path,+ name = "m.gguf",+ body = b"x" * 64,+):+ p = tmp_path / name+ p.write_bytes(body)+ return str(p)+++def test_only_the_first_read_of_a_file_speaks_up(tmp_path):+ path = _gguf(tmp_path)+ assert llama_cpp._note_gguf_metadata_read(path) is True+ for _ in range(10):+ assert llama_cpp._note_gguf_metadata_read(path) is False+++def test_a_changed_file_is_described_again(tmp_path):+ """Keyed on identity, not name: a rebuilt GGUF at the same path is worth stating."""+ path = _gguf(tmp_path)+ assert llama_cpp._note_gguf_metadata_read(path) is True+ import os+ import time++ time.sleep(0.01)+ with open(path, "wb") as fh:+ fh.write(b"y" * 128)+ os.utime(path, None)+ assert llama_cpp._note_gguf_metadata_read(path) is True+++def test_an_unstattable_path_still_logs(tmp_path):+ """Fails open: an unidentifiable read is better said out loud than swallowed."""+ assert llama_cpp._note_gguf_metadata_read(str(tmp_path / "gone.gguf")) is True+++def test_the_cache_is_bounded(tmp_path):+ for i in range(llama_cpp._GGUF_METADATA_LOGGED_MAX + 5):+ llama_cpp._note_gguf_metadata_read(_gguf(tmp_path, f"m{i}.gguf"))+ assert len(llama_cpp._GGUF_METADATA_LOGGED) <= llama_cpp._GGUF_METADATA_LOGGED_MAX+++TEMPLATE = (+ "{% if enable_thinking %}<think>{% endif %}"+ "{% if preserve_thinking %}keep{% endif %}"+ # The literal the tool detector actually looks for, not a paraphrase.+ "{% if tools %}{{ tools }}{% endif %}"+)+++def test_debug_level_moves_the_capability_lines_off_info(monkeypatch):+ """Asserted against the logger itself: structlog bypasses caplog, so a caplog test+ would pass while the lines still went to info."""+ seen: list[tuple[str, str]] = []+ for level in ("info", "debug"):+ monkeypatch.setattr(+ llama_cpp.logger,+ level,+ lambda msg, *a, _lv = level, **k: seen.append((_lv, str(msg))),+ )++ llama_cpp.detect_reasoning_flags(TEMPLATE, "qwen3.8", log_source = "GGUF metadata")+ first = list(seen)+ seen.clear()+ llama_cpp.detect_reasoning_flags(+ TEMPLATE, "qwen3.8", log_source = "GGUF metadata", log_level = "debug"+ )+ repeat = list(seen)++ assert [lv for lv, _ in first] == ["info"] * len(+ first+ ) and first, "the first read must still describe the model at info"+ assert repeat, "a repeat must still be logged, just not at info"+ assert [lv for lv, _ in repeat] == ["debug"] * len(repeat)+ # Same facts, different level: nothing is lost, only demoted.+ assert [m for _, m in first] == [m for _, m in repeat]+++def test_the_level_does_not_change_what_is_detected():+ """A capability that disappears when the line is demoted would be a regression+ hiding behind a quieter log."""+ loud = llama_cpp.detect_reasoning_flags(TEMPLATE, "qwen3.8", log_source = "GGUF metadata")+ quiet = llama_cpp.detect_reasoning_flags(+ TEMPLATE, "qwen3.8", log_source = "GGUF metadata", log_level = "debug"+ )+ assert loud == quiet+ assert loud["supports_reasoning"] is True+ assert loud["supports_preserve_thinking"] is True+ assert loud["supports_tools"] is Truediff --git a/studio/backend/tests/test_logging_middleware.py b/studio/backend/tests/test_logging_middleware.pyindex 6c1ff25935f..8cf26351520 100644--- a/studio/backend/tests/test_logging_middleware.py+++ b/studio/backend/tests/test_logging_middleware.py@@ -741,3 +741,93 @@ def test_verbose_off_by_default_keeps_the_polls_quiet(logs):for path in ("/api/inference/load-progress", "/api/hub/download-progress"):_run(LoggingMiddleware(_status_app(200))(_http_scope(path), _noop_receive, _drop))assert logs.events == []+++# ── templated chat detail polls ──+def test_chat_thread_detail_polls_heartbeat_instead_of_one_line_each(logs, monkeypatch):+ """Streaming drives these on a loop: 25 thread and 21 fork reads in 20s over one+ four-tab session, 34% of the access log."""+ monkeypatch.setattr(hmod, "_ACCESS_LOG_DEDUP_MS", 0)+ monkeypatch.setattr(hmod, "_QUIET_POLL_DEDUP_MS", 60000)++ mw = LoggingMiddleware(_status_app(200))+ for _ in range(12):+ _run(mw(_http_scope("/api/chat/threads/abc123"), _noop_receive, _drop))+ _run(mw(_http_scope("/api/chat/threads/abc123/forks"), _noop_receive, _drop))++ paths = _paths_logged(logs)+ assert paths == ["/api/chat/threads/abc123", "/api/chat/threads/abc123/forks"], paths+++def test_four_tabs_share_one_bucket_per_template(logs, monkeypatch):+ """Four tabs polling four different threads ask one question. Keying the bucket on the+ real path would emit four lines per window."""+ monkeypatch.setattr(hmod, "_ACCESS_LOG_DEDUP_MS", 0)+ monkeypatch.setattr(hmod, "_QUIET_POLL_DEDUP_MS", 60000)++ mw = LoggingMiddleware(_status_app(200))+ for tab in ("t1", "t2", "t3", "t4"):+ for _ in range(5):+ _run(mw(_http_scope(f"/api/chat/threads/{tab}"), _noop_receive, _drop))++ # One line, and it names a real thread rather than the template.+ assert _paths_logged(logs) == ["/api/chat/threads/t1"], _paths_logged(logs)+++def test_message_reads_are_not_collapsed_into_the_detail_bucket(logs, monkeypatch):+ """A message read is a different question from "is it still streaming", so the+ normaliser must not reach it (#7087)."""+ monkeypatch.setattr(hmod, "_ACCESS_LOG_DEDUP_MS", 0)+ monkeypatch.setattr(hmod, "_QUIET_POLL_DEDUP_MS", 60000)++ deeper = (+ "/api/chat/threads/abc/messages",+ "/api/chat/threads/abc/messages/m1",+ "/api/chat/threads/abc/messages/m1/forks",+ )+ mw = LoggingMiddleware(_status_app(200))+ for path in deeper:+ for _ in range(3):+ _run(mw(_http_scope(path), _noop_receive, _drop))++ for path in deeper:+ assert hmod.normalize_poll_path(path) == path+ assert _paths_logged(logs).count(path) == 3, _paths_logged(logs)+++def test_the_thread_list_is_untouched_by_the_normaliser():+ """The list path is handled by _CHAT_LIST_PATHS and must not be dragged into the+ heartbeat class by a trailing-segment rule."""+ assert hmod.normalize_poll_path("/api/chat/threads") == "/api/chat/threads"+ assert hmod.normalize_poll_path("/api/chat/threads/") == "/api/chat/threads/"+++def test_a_failing_thread_poll_still_logs(logs, monkeypatch):+ monkeypatch.setattr(hmod, "_ACCESS_LOG_DEDUP_MS", 0)+ monkeypatch.setattr(hmod, "_QUIET_POLL_DEDUP_MS", 60000)++ bad = LoggingMiddleware(_status_app(404))+ for _ in range(3):+ _run(bad(_http_scope("/api/chat/threads/gone"), _noop_receive, _drop))+ assert len(_paths_logged(logs)) == 3+++def test_thread_mutations_still_log(logs, monkeypatch):+ monkeypatch.setattr(hmod, "_ACCESS_LOG_DEDUP_MS", 0)+ monkeypatch.setattr(hmod, "_QUIET_POLL_DEDUP_MS", 60000)++ mw = LoggingMiddleware(_status_app(200))+ for _ in range(3):+ _run(mw(_http_scope("/api/chat/threads/abc", method = "PATCH"), _noop_receive, _drop))+ assert len(_paths_logged(logs)) == 3+++def test_verbose_restores_every_thread_poll_line(logs, monkeypatch):+ monkeypatch.setattr(hmod, "_ACCESS_LOG_DEDUP_MS", 0)+ monkeypatch.setattr(hmod, "_QUIET_POLL_DEDUP_MS", 0)+ monkeypatch.setattr(hmod, "_VERBOSE_ACCESS_LOG", True)++ mw = LoggingMiddleware(_status_app(200))+ for _ in range(3):+ _run(mw(_http_scope("/api/chat/threads/abc"), _noop_receive, _drop))+ assert len(_paths_logged(logs)) == 3diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex c8b06de5fc8..e25853ce588 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -3954,7 +3954,9 @@ class ModelConfig:verified_gguf = (identifier, variant, verified_file, sizes)display_name = f"{identifier.split('/')[-1]} ({variant})"- logger.info(+ # Debug: from_identifier is re-resolved on every validate, estimate and+ # load. The load path announces the model it actually starts.+ logger.debug(f"Detected remote GGUF repo '{identifier}', "f"variant={variant}, vision={has_vision}")