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: render thinking blocks for safetensors inference with prefilled <think> templates (#6816)
Michael Han5c2e53606e51
diff --git a/studio/backend/core/inference/chat_template_helpers.py b/studio/backend/core/inference/chat_template_helpers.pyindex dfd4c1c0bc3..897db8262df 100644--- a/studio/backend/core/inference/chat_template_helpers.py+++ b/studio/backend/core/inference/chat_template_helpers.py@@ -12,6 +12,43 @@ import jsonimport loggingfrom typing import Optional+_THINK_OPEN = "<think>"+_THINK_CLOSE = "</think>"+++def detect_think_prefill(prompt: Optional[str], special_tokens = None) -> str:+ """Return the trailing open ``<think>`` prefill of a rendered prompt.++ Reasoning templates (Qwen3.6, DeepSeek-R1-style) end the generation+ prompt with ``<think>\\n`` so the model starts reasoning immediately.+ Because that opening tag is part of the *prompt*, skip_prompt streaming+ never emits it, and the frontend's ``<think>``/``</think>`` parser shows+ the reasoning as plain text instead of a thinking block. (The GGUF path+ is unaffected: llama-server's reasoning parser returns+ ``reasoning_content``, which gets re-wrapped in think tags.)++ Returns the exact prompt tail to re-emit at the start of the generated+ stream (e.g. ``"<think>\\n"``), or ``""`` when the prompt does not end+ with an open think block, including the ``enable_thinking=False`` case+ where templates prefill an already-closed ``<think>\\n\\n</think>``.++ ``special_tokens`` is the tokenizer's special-token list. If ``</think>``+ is one, the streamer's skip_special_tokens strips the model's closing tag,+ so re-emitting the open would leave an unclosed block that swallows the+ answer. In that case return ``""`` and fall back to plain text.+ """+ if not prompt:+ return ""+ open_idx = prompt.rfind(_THINK_OPEN)+ if open_idx == -1:+ return ""+ tail = prompt[open_idx:]+ if _THINK_CLOSE in tail or tail.strip() != _THINK_OPEN:+ return ""+ if special_tokens and _THINK_CLOSE in set(special_tokens):+ return ""+ return tail+logger = logging.getLogger(__name__)diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.pyindex 167706f7019..7e69e051240 100644--- a/studio/backend/core/inference/inference.py+++ b/studio/backend/core/inference/inference.py@@ -1178,13 +1178,22 @@ class InferenceBackend:add_special_tokens = False,return_tensors = "pt",).to(model.device)+ prompt_text = input_textelse:# Text-only path for a vision modelformatted_prompt = self.format_chat_prompt(messages, system_prompt)inputs = raw_tokenizer(formatted_prompt, return_tensors = "pt").to(model.device)+ prompt_text = formatted_prompt# Stream with TextIteratorStreamer + background threadtry:+ from core.inference.chat_template_helpers import detect_think_prefill++ # Re-emit an open <think> prefill swallowed by skip_prompt (see+ # generate_stream).+ think_prefix = detect_think_prefill(+ prompt_text, getattr(raw_tokenizer, "all_special_tokens", None)+ )from transformers import TextIteratorStreamerimport threading@@ -1233,7 +1242,11 @@ class InferenceBackend:thread = threading.Thread(target = generate_fn)thread.start()- output = ""+ output = think_prefix+ # Emit the prefilled <think> before the first token so the block+ # renders during prompt prefill (which can take seconds).+ if think_prefix:+ yield think_prefixfrom queue import Emptygeneration_complete = False@@ -1467,6 +1480,16 @@ class InferenceBackend:from transformers import TextIteratorStreamerimport threading+ from core.inference.chat_template_helpers import detect_think_prefill++ # skip_prompt swallows an open <think> prefilled by the template;+ # re-emit it so the frontend can render the thinking block.+ # gpt-oss emits its own tags via HarmonyTextStreamer.+ think_prefix = (+ ""+ if self._is_gpt_oss_model()+ else detect_think_prefill(prompt, getattr(tokenizer, "all_special_tokens", None))+ )# gpt-oss models: HarmonyTextStreamer parses the multi-channel# harmony protocol into <think> tags@@ -1550,7 +1573,11 @@ class InferenceBackend:thread = threading.Thread(target = generate_fn)thread.start()- output = ""+ output = think_prefix+ # Emit the prefilled <think> before the first token so the block+ # renders during prompt prefill (which can take seconds).+ if think_prefix:+ yield think_prefixfrom queue import Emptygeneration_complete = Falsediff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.pyindex d84baa278de..6287b184a63 100644--- a/studio/backend/core/inference/mlx_inference.py+++ b/studio/backend/core/inference/mlx_inference.py@@ -485,6 +485,7 @@ class MLXInferenceBackend:from core.inference.chat_template_helpers import (apply_chat_template_for_generation,+ detect_think_prefill,render_with_native_template_fallback,)@@ -518,6 +519,15 @@ class MLXInferenceBackend:hf_token = model_info.get("hf_token"),)+ # An open <think> prefilled by the template lives in the prompt, not+ # the generated tokens; re-emit it so the frontend renders the block.+ think_prefix = detect_think_prefill(+ prompt, getattr(self._tokenizer, "all_special_tokens", None)+ )+ # Emit it before the first token so the block renders during prefill.+ if think_prefix:+ yield think_prefix+sampler = make_sampler(temp = temperature,top_p = top_p,@@ -570,7 +580,7 @@ class MLXInferenceBackend:token_ids,skip_special_tokens = True,)- yield cumulative+ yield think_prefix + cumulativeif cancel_event and cancel_event.is_set():break@@ -634,7 +644,13 @@ class MLXInferenceBackend:# mlx_vlm's stream_generate handles pixel_values (None for text-only)images = [image] if image is not None else None- cumulative = ""+ from core.inference.chat_template_helpers import detect_think_prefill++ # Re-emit an open <think> prefill from the prompt (see _generate_text).+ cumulative = detect_think_prefill(prompt, getattr(chat_target, "all_special_tokens", None))+ # Emit it before the first token so the block renders during prefill.+ if cumulative:+ yield cumulativelogger.info("VLM generating: prompt_len=%d, has_image=%s",len(prompt),diff --git a/studio/backend/tests/test_think_prefill_reemit.py b/studio/backend/tests/test_think_prefill_reemit.pynew file mode 100644index 00000000000..300ff927764--- /dev/null+++ b/studio/backend/tests/test_think_prefill_reemit.py@@ -0,0 +1,89 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""+Unit tests for detect_think_prefill.++Reasoning templates (Qwen3.6-style) end the generation prompt with an open+``<think>\\n`` so the model starts reasoning immediately. skip_prompt+streaming drops that opening tag, so the safetensors/MLX paths must re-emit+it for the frontend's <think> parser to render a thinking block.+"""++import os+import sys++_backend = os.path.join(os.path.dirname(__file__), "..")+sys.path.insert(0, _backend)++from core.inference.chat_template_helpers import detect_think_prefill+++QWEN_PROMPT = "<|im_start|>user\nHi!<|im_end|>\n<|im_start|>assistant\n"+++def test_open_think_prefill_reemitted():+ """Qwen3.6-style enable_thinking=True prompt tail: <think>\\n."""+ assert detect_think_prefill(QWEN_PROMPT + "<think>\n") == "<think>\n"+++def test_bare_open_think_prefill_reemitted():+ """Prefill without trailing newline still detected."""+ assert detect_think_prefill(QWEN_PROMPT + "<think>") == "<think>"+++def test_closed_think_prefill_not_reemitted():+ """enable_thinking=False prefills a closed, empty think block."""+ assert detect_think_prefill(QWEN_PROMPT + "<think>\n\n</think>\n\n") == ""+++def test_prompt_without_think_untouched():+ """Non-reasoning templates produce no prefix."""+ assert detect_think_prefill(QWEN_PROMPT) == ""+++def test_historical_think_blocks_ignored():+ """A closed think block in a prior assistant turn (preserve_thinking)+ must not trigger re-emission when the generation tail is plain."""+ prompt = (+ "<|im_start|>user\nHi!<|im_end|>\n"+ "<|im_start|>assistant\n<think>\nprior reasoning\n</think>\n\nHello!<|im_end|>\n"+ "<|im_start|>user\nAgain?<|im_end|>\n<|im_start|>assistant\n"+ )+ assert detect_think_prefill(prompt) == ""+++def test_historical_blocks_plus_open_prefill():+ """Prior closed blocks plus a fresh open prefill: only the tail matters."""+ prompt = (+ "<|im_start|>assistant\n<think>\nprior\n</think>\n\nHello!<|im_end|>\n"+ "<|im_start|>assistant\n<think>\n"+ )+ assert detect_think_prefill(prompt) == "<think>\n"+++def test_content_after_open_tag_not_reemitted():+ """If non-whitespace follows the tag it is not a plain prefill."""+ assert detect_think_prefill(QWEN_PROMPT + "<think>\npartial reasoning") == ""+++def test_empty_and_none_prompts():+ assert detect_think_prefill("") == ""+ assert detect_think_prefill(None) == ""+++def test_guard_suppresses_when_close_tag_is_special():+ """If </think> is a special token, skip_special_tokens strips the model's+ close tag, so re-emitting the open would leave an unclosed block. Guard off."""+ specials = ["<|im_end|>", "<think>", "</think>"]+ assert detect_think_prefill(QWEN_PROMPT + "<think>\n", specials) == ""+++def test_guard_emits_when_think_not_special():+ specials = ["<|im_end|>", "<|endoftext|>"]+ assert detect_think_prefill(QWEN_PROMPT + "<think>\n", specials) == "<think>\n"+++def test_guard_default_and_empty_keep_emitting():+ assert detect_think_prefill(QWEN_PROMPT + "<think>\n", None) == "<think>\n"+ assert detect_think_prefill(QWEN_PROMPT + "<think>\n", []) == "<think>\n"