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
Preserve reasoning across turns for Qwen3.x (#7289)
Matthias Hille2829dc364e30
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex a6bab9ef9ae..4a1a1d60e9e 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -8646,16 +8646,32 @@ class LlamaCppBackend:cmd.extend(["--chat-template-file", self._chat_template_file.name])logger.info(f"Using custom chat template file: {self._chat_template_file.name}")- # Default thinking mode for reasoning models. Qwen3.5/3.6 below- # 9B disable thinking by default; 9B+ enable it. Always-on- # templates ignore the kwarg, so skip.+ # Default thinking mode for reasoning models. The Qwen3.5 Small tier+ # (0.8B, 2B, 4B, 9B) ships with reasoning off by default and the rest of+ # the family has it on; the templates are byte-identical across sizes, so+ # this tier split only exists as a launch flag. Always-on templates ignore+ # the kwarg, so skip.if self._supports_reasoning and not self._reasoning_always_on:thinking_default = Truemid = (model_identifier or "").lower()if "qwen3.5" in mid or "qwen3.6" in mid:- size_val = _extract_model_size_b(mid)- if size_val is not None and size_val < 9:- thinking_default = False+ # extract_model_size_b prefers MoE active params, reading+ # 35B-A3B as 3B. Match total params instead: scan segments+ # right to left so the size nearest the leaf beats a size-like+ # parent dir, and keep its \s* / M-suffix spellings.+ size_re = r"(?:^|[-_.])(\d+\.?\d*)\s*([bm])(?:$|[-_.])"+ size_match = None+ for seg in reversed(mid.replace("\\", "/").split("/")):+ size_match = re.search(size_re, seg)+ if size_match:+ break+ if size_match:+ size_b = float(size_match.group(1))+ if size_match.group(2) == "m":+ size_b /= 1000.0+ # <= 9, not < 9: 9B is the top of the Small tier, so it is off too.+ if size_b <= 9:+ thinking_default = Falseself._reasoning_default = thinking_defaultreasoning_kw = self._reasoning_kwargs(thinking_default)# preserve_thinking is an independent kwarg. Default it OFFdiff --git a/studio/backend/tests/test_qwen_thinking_size_gate.py b/studio/backend/tests/test_qwen_thinking_size_gate.pynew file mode 100644index 00000000000..50cd3989426--- /dev/null+++ b/studio/backend/tests/test_qwen_thinking_size_gate.py@@ -0,0 +1,111 @@+# 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 Qwen3.5/3.6 thinking-default size gate in llama_cpp.py's launch path.++The gate is inline in _build_command with no seam, so the whole block is sliced out of the+source and exec'd here: that way a change to its control flow, not just its regex, is+caught. Keep this in sync with the two frontend mirrors.+"""++import re+import textwrap+from pathlib import Path++import pytest++_SRC = Path(__file__).resolve().parent.parent / "core" / "inference" / "llama_cpp.py"+_START = 'mid = (model_identifier or "").lower()'+_END = "thinking_default = False"+++def _gate_source() -> str:+ lines = _SRC.read_text(encoding = "utf-8").splitlines()+ start = next(i for i, line in enumerate(lines) if line.strip() == _START)+ end = next(i for i, line in enumerate(lines[start:], start) if line.strip() == _END)+ return textwrap.dedent("\n".join(lines[start : end + 1]))+++_GATE = compile(_gate_source(), str(_SRC), "exec")+++def _thinking_default_off(model_identifier: str) -> bool:+ scope = {"re": re, "model_identifier": model_identifier, "thinking_default": True}+ exec(_GATE, scope)+ return scope["thinking_default"] is False+++ "model_id",+ [+ "unsloth/Qwen3.5-35B-A3B-GGUF",+ "unsloth/Qwen3.6-35B-A3B-MTP-GGUF",+ "unsloth/Qwen3.5-122B-A10B-GGUF",+ ],+)+def test_moe_total_params_win_over_active_params(model_id):+ # extract_model_size_b() prefers A3B and reads 35B-A3B as 3B, which turned thinking off+ # on a medium-tier model.+ assert _thinking_default_off(model_id) is False+++ "model_id",+ [+ "unsloth/Qwen3.5-4B-GGUF",+ "unsloth/Qwen3.5-0.8B-GGUF",+ # 9B is a small-tier model: unsloth ships it with reasoning off by default.+ "unsloth/Qwen3.5-9B-GGUF",+ # Directory identifiers: auto-switch passes a snapshot dir, scan folders a quant subdir.+ "/models/Qwen3.5-4B-GGUF/UD-Q4_K_XL",+ "/c/models--unsloth--Qwen3.5-4B-GGUF/snapshots/bfc15c3",+ "C:\\models\\Qwen3.5-4B.gguf",+ "unsloth/Qwen3.5-4B/",+ "C:\\models\\Qwen3.5-4B\\",+ ],+)+def test_sub_9b_turns_thinking_off(model_id):+ assert _thinking_default_off(model_id) is True+++ "model_id",+ [+ "/models/8bit/qwen3.6-27b.gguf",+ "/models/8b/qwen3.6-27b.gguf",+ # Directory identifier, so there is no file name to prefer: the segment nearest+ # the leaf has to win instead.+ "/models/8b/Qwen3.5-35B-A3B/UD-Q4_K_XL",+ "/models/4b/Qwen3.6-27B-GGUF/snapshots/bfc15c3",+ ],+)+def test_size_like_directory_does_not_shadow_the_real_size(model_id):+ assert _thinking_default_off(model_id) is False+++ "model_id",+ ["unsloth/Qwen3-4B-GGUF", "unsloth/gemma-4-12b-it-GGUF", "unsloth/Qwen3.5-9.5B-GGUF", ""],+)+def test_other_models_are_never_gated(model_id):+ assert _thinking_default_off(model_id) is False+++ "model_id", ["Qwen3.5-4 B-GGUF", "unsloth/Qwen3.5-800M-GGUF", "unsloth/Qwen3.5-4 B"]+)+def test_spacing_and_millions_match_extract_model_size_b(model_id):+ # extract_model_size_b allows \s* before the unit and converts an M suffix to billions.+ # The inline matcher replaces it only for the MoE total-vs-active fix, so it has to keep+ # reading the same spellings.+ assert _thinking_default_off(model_id) is True+++ "quant",+ ["Q4_K_M", "Q3_K_M", "IQ3_M", "UD-Q4_K_XL", "Q8_0", "BF16", "MXFP4"],+)+def test_quant_subdirs_never_read_as_a_size(quant):+ # The M suffix is the risk here: a quant name is the leaf segment, so it is scanned first.+ assert _thinking_default_off(f"unsloth/Qwen3.5-35B-A3B-GGUF/{quant}") is False+ assert _thinking_default_off(f"unsloth/Qwen3.5-4B-GGUF/{quant}") is Truediff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.tsindex f32cb4536e5..c6148d76a60 100644--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts@@ -1102,14 +1102,29 @@ export function useChatModelRuntime() {presetSource: useChatRuntimeStore.getState().activePresetSource,}),);- // Qwen3.5/3.6 small models (0.8B, 2B, 4B, 9B) disable thinking by default+ // Qwen3.5/3.6 small models (0.8B, 2B, 4B, 9B) disable thinking by default.+ // Anchored regex: first "Xb" / "X.Xb" after start-of-string or+ // [-_/.] so the version literal in "qwen3.5" / "qwen3.6" doesn't+ // match first, and for "Qwen3.5-35B-A3B" the result is 35 (total+ // params), not 3 (MoE active params).let reasoningDefault = loadResponse.supports_reasoning ?? false;if (reasoningDefault) {const mid = modelId.toLowerCase();if (mid.includes("qwen3.5") || mid.includes("qwen3.6")) {- const sizeMatch = mid.match(/(\d+\.?\d*)\s*b/);- if (sizeMatch && parseFloat(sizeMatch[1]) < 9) {- reasoningDefault = false;+ // Scan path segments right to left so the size nearest the leaf+ // wins over a size-like parent dir; trailing boundary stops "8bit".+ const sizeRe = /(?:^|[-_.])(\d+\.?\d*)\s*([bm])(?:$|[-_.])/;+ const sizeMatch = mid+ .replace(/\\/g, "/")+ .split("/")+ .reduceRight<RegExpMatchArray | null>(+ (found, seg) => found ?? seg.match(sizeRe),+ null,+ );+ if (sizeMatch) {+ const size = parseFloat(sizeMatch[1]);+ const sizeB = sizeMatch[2] === "m" ? size / 1000 : size;+ if (sizeB <= 9) reasoningDefault = false;}}}diff --git a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.tsindex eef635f9496..28a9711d312 100644--- a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts+++ b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts@@ -412,12 +412,28 @@ export function applyActiveModelStatusToStore(hydratingExistingModel &&storedReasoningEnabled === null) {+ // Anchored regex: first "Xb" / "X.Xb" after start-of-string or+ // [-_/.] so the version literal in "qwen3.5" / "qwen3.6" doesn't match+ // first, and for "Qwen3.5-35B-A3B" the result is 35 (total params),+ // not 3 (MoE active params). Mirrors the regex in+ // use-chat-model-runtime.ts and the inline one in llama_cpp.py.let reasoningDefault = true;const mid = checkpointId.toLowerCase();if (mid.includes("qwen3.5") || mid.includes("qwen3.6")) {- const sizeMatch = mid.match(/(\d+\.?\d*)\s*b/);- if (sizeMatch && Number.parseFloat(sizeMatch[1]) < 9) {- reasoningDefault = false;+ // Scan path segments right to left so the size nearest the leaf wins over+ // a size-like parent dir; trailing boundary prevents matching "8bit".+ const sizeRe = /(?:^|[-_.])(\d+\.?\d*)\s*([bm])(?:$|[-_.])/;+ const sizeMatch = mid+ .replace(/\\/g, "/")+ .split("/")+ .reduceRight<RegExpMatchArray | null>(+ (found, seg) => found ?? seg.match(sizeRe),+ null,+ );+ if (sizeMatch) {+ const size = Number.parseFloat(sizeMatch[1]);+ const sizeB = sizeMatch[2] === "m" ? size / 1000 : size;+ if (sizeB <= 9) reasoningDefault = false;}}useChatRuntimeStore.setState({ reasoningEnabled: reasoningDefault });diff --git a/studio/frontend/tests/qwen-thinking-size-gate.test.ts b/studio/frontend/tests/qwen-thinking-size-gate.test.tsnew file mode 100644index 00000000000..f12077783dd--- /dev/null+++ b/studio/frontend/tests/qwen-thinking-size-gate.test.ts@@ -0,0 +1,98 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { test } from "node:test";++// Mirrors the gate in use-chat-model-runtime.ts, apply-inference-status-to-store.ts and+// llama_cpp.py. Path segments are scanned right to left so the size nearest the leaf wins+// over a size-like parent dir, and a directory identifier (auto-switch snapshot sha, quant+// subdir) still resolves.+const SIZE_RE = /(?:^|[-_.])(\d+\.?\d*)\s*([bm])(?:$|[-_.])/;++function thinkingDefaultOff(modelId: string): boolean {+ const mid = modelId.toLowerCase();+ if (!mid.includes("qwen3.5") && !mid.includes("qwen3.6")) return false;+ const sizeMatch = mid+ .replace(/\\/g, "/")+ .split("/")+ .reduceRight<RegExpMatchArray | null>(+ (found, seg) => found ?? seg.match(SIZE_RE),+ null,+ );+ if (!sizeMatch) return false;+ const size = Number.parseFloat(sizeMatch[1]);+ return (sizeMatch[2] === "m" ? size / 1000 : size) <= 9;+}++test("35B-A3B keeps thinking on: total params win over MoE active params", () => {+ assert.equal(thinkingDefaultOff("unsloth/Qwen3.5-35B-A3B-GGUF"), false);+ assert.equal(thinkingDefaultOff("unsloth/Qwen3.6-35B-A3B-MTP-GGUF"), false);+});++test("sub-9B turns thinking off, including directory identifiers", () => {+ assert.equal(thinkingDefaultOff("unsloth/Qwen3.5-4B-GGUF"), true);+ assert.equal(thinkingDefaultOff("unsloth/Qwen3.5-0.8B-GGUF"), true);+ assert.equal(thinkingDefaultOff("unsloth/Qwen3.5-9B-GGUF"), true);+ assert.equal(thinkingDefaultOff("/m/Qwen3.5-4B-GGUF/UD-Q4_K_XL"), true);+ assert.equal(+ thinkingDefaultOff("/c/models--unsloth--Qwen3.5-4B-GGUF/snapshots/bfc15c3"),+ true,+ );+ assert.equal(thinkingDefaultOff("C:\\models\\Qwen3.5-4B.gguf"), true);+});++test("a trailing separator does not lose the size", () => {+ assert.equal(thinkingDefaultOff("unsloth/Qwen3.5-4B/"), true);+ assert.equal(thinkingDefaultOff("/models/Qwen3.5-4B//"), true);+ assert.equal(thinkingDefaultOff("C:\\models\\Qwen3.5-4B\\"), true);+});++test("a size-like directory does not shadow the real size", () => {+ assert.equal(thinkingDefaultOff("/models/8bit/qwen3.6-27b.gguf"), false);+ assert.equal(thinkingDefaultOff("/models/8b/qwen3.6-27b.gguf"), false);+ // Directory identifier, so there is no file name to prefer.+ assert.equal(thinkingDefaultOff("/models/8b/Qwen3.5-35B-A3B/UD-Q4_K_XL"), false);+ assert.equal(+ thinkingDefaultOff("/models/4b/Qwen3.6-27B-GGUF/snapshots/bfc15c3"),+ false,+ );+});++test("spacing and M-suffixed sizes keep parity with extract_model_size_b", () => {+ assert.equal(thinkingDefaultOff("Qwen3.5-4 B-GGUF"), true);+ assert.equal(thinkingDefaultOff("unsloth/Qwen3.5-800M-GGUF"), true);+ assert.equal(thinkingDefaultOff("unsloth/Qwen3.5-4 B"), true);+});++test("a quant subdir is never read as a size", () => {+ for (const q of ["Q4_K_M", "Q3_K_M", "IQ3_M", "UD-Q4_K_XL", "Q8_0", "BF16"]) {+ assert.equal(thinkingDefaultOff(`unsloth/Qwen3.5-35B-A3B-GGUF/${q}`), false);+ assert.equal(thinkingDefaultOff(`unsloth/Qwen3.5-4B-GGUF/${q}`), true);+ }+});++test("non-qwen3.5/3.6 models are never gated", () => {+ assert.equal(thinkingDefaultOff("unsloth/Qwen3-4B-GGUF"), false);+ assert.equal(thinkingDefaultOff("unsloth/Qwen3.5-9.5B-GGUF"), false);+ assert.equal(thinkingDefaultOff(""), false);+});++test("all four copies of the gate pattern stay in sync", () => {+ const here = path.dirname(fileURLToPath(import.meta.url));+ const read = (rel: string) => readFileSync(path.join(here, rel), "utf8");+ const patterns = [+ read("../src/features/chat/hooks/use-chat-model-runtime.ts").match(+ /const sizeRe = \/(.+?)\/;/,+ ),+ read("../src/features/chat/lib/apply-inference-status-to-store.ts").match(+ /const sizeRe = \/(.+?)\/;/,+ ),+ read("../../backend/core/inference/llama_cpp.py").match(+ /size_re = r"(.+?)"\n/,+ ),+ ];+ for (const found of patterns) assert.ok(found, "size gate pattern not found");+ const expected = SIZE_RE.source;+ for (const found of patterns) assert.equal(found![1], expected);+});