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: improve onboarding UX, tooltips, and training defaults (#4355)
Daniel Han0acd1c7eec2a
diff --git a/studio/backend/assets/configs/inference_defaults.json b/studio/backend/assets/configs/inference_defaults.jsonindex 13ecb992bfd..f520041addc 100644--- a/studio/backend/assets/configs/inference_defaults.json+++ b/studio/backend/assets/configs/inference_defaults.json@@ -6,7 +6,8 @@"top_p": 0.8,"top_k": 20,"min_p": 0.0,- "repetition_penalty": 1.0+ "repetition_penalty": 1.0,+ "presence_penalty": 1.5},"qwen3-coder": {"temperature": 0.7,diff --git a/studio/backend/core/export/worker.py b/studio/backend/core/export/worker.pyindex 1128a5014a0..4f74f662ee4 100644--- a/studio/backend/core/export/worker.py+++ b/studio/backend/core/export/worker.py@@ -65,7 +65,7 @@ def _activate_transformers_version(model_name: str) -> None:"--target",venv_t5,"--no-deps",- "transformers==5.2.0",+ "transformers==5.3.0",],stdout = sp.PIPE,stderr = sp.STDOUT,@@ -312,7 +312,7 @@ def run_export_process(resp_queue,{"type": "status",- "message": "Importing ML libraries...",+ "message": "Importing Unsloth...","ts": time.time(),},)diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.pyindex 6f04588fbc3..a95fa93daaf 100644--- a/studio/backend/core/inference/inference.py+++ b/studio/backend/core/inference/inference.py@@ -28,6 +28,180 @@ from loggers import get_loggerlogger = get_logger(__name__)+class HarmonyTextStreamer:+ """Streaming text decoder for gpt-oss harmony channel protocol.++ gpt-oss models emit multi-channel output using special tokens like+ ``<|channel|>analysis<|message|>...`` and ``<|channel|>final<|message|>...``.+ A plain ``TextIteratorStreamer(skip_special_tokens=True)`` strips the special+ tokens but leaves the channel names concatenated with content, producing+ garbled output such as ``analysisWe need to respond...assistantfinalHello!``.++ This streamer decodes with ``skip_special_tokens=False`` so the full+ harmony markup is visible, then uses **stateful incremental** parsing+ to emit properly-formatted text:++ - ``<think>`` emitted once when the ``analysis`` channel is first seen+ - Analysis content streamed incrementally+ - ``</think>`` emitted once when the ``final`` channel is first seen+ - Final content streamed incrementally++ This avoids the delta-on-transformed bug where wrapping tags shift+ position as content grows.++ Implements the same ``put`` / ``end`` / iterator interface as+ ``TextIteratorStreamer`` so ``generate_stream`` can use it as a drop-in+ replacement.+ """++ import re as _re++ _HARMONY_RE = _re.compile(+ r"<\|channel\|>(\w+)<\|message\|>(.*?)(?=<\|end\|>|<\|channel\|>|\Z)",+ _re.DOTALL,+ )++ def __init__(self, tokenizer, *, skip_prompt: bool = True, timeout: float = 0.2):+ import queue++ self.tokenizer = tokenizer+ self.skip_prompt = skip_prompt+ self.timeout = timeout++ self._queue: queue.Queue = queue.Queue()+ self._token_ids: list = []+ self._prompt_len: int = 0+ self._is_first_put: bool = True+ self._stop: bool = False++ # Stateful channel tracking — avoids delta-on-transformed bugs+ self._emitted_think_open: bool = False+ self._emitted_think_close: bool = False+ self._analysis_emitted: int = 0 # chars of analysis content emitted+ self._final_emitted: int = 0 # chars of final content emitted++ # ------------------------------------------------------------------+ # put / end — called from the generation thread+ # ------------------------------------------------------------------++ def put(self, value):+ """Receive new token IDs from model.generate()."""+ import torch++ if isinstance(value, torch.Tensor):+ # value shape: (batch, seq) — take first batch element+ ids = value[0].tolist() if value.dim() > 1 else value.tolist()+ elif isinstance(value, (list, tuple)):+ ids = list(value)+ else:+ ids = [value]++ if self._is_first_put and self.skip_prompt:+ # First call contains the full prompt; remember its length+ self._prompt_len = len(ids)+ self._token_ids = list(ids)+ self._is_first_put = False+ return++ self._token_ids.extend(ids)++ # Decode only the generated part (after the prompt)+ gen_ids = self._token_ids[self._prompt_len :]+ raw = self.tokenizer.decode(gen_ids, skip_special_tokens = False)+ self._process_incremental(raw)++ def end(self):+ """Signal generation is complete."""+ # Final decode to capture any remaining content+ gen_ids = self._token_ids[self._prompt_len :]+ if gen_ids:+ raw = self.tokenizer.decode(gen_ids, skip_special_tokens = False)+ self._process_incremental(raw)++ # Close any open think tags+ if self._emitted_think_open and not self._emitted_think_close:+ self._queue.put("</think>")+ self._emitted_think_close = True++ self._stop = True+ self._queue.put(None) # sentinel++ # ------------------------------------------------------------------+ # Iterator interface — consumed by the streaming loop+ # ------------------------------------------------------------------++ def __iter__(self):+ return self++ def __next__(self):+ from queue import Empty++ while True:+ try:+ val = self._queue.get(timeout = self.timeout)+ except Empty:+ if self._stop:+ raise StopIteration+ raise # propagate Empty so caller can check thread liveness+ if val is None:+ raise StopIteration+ return val++ # ------------------------------------------------------------------+ # Stateful incremental harmony protocol parsing+ # ------------------------------------------------------------------++ def _process_incremental(self, raw: str) -> None:+ """Parse harmony channels and emit deltas per-channel.++ Instead of transforming the entire raw text and computing a string+ delta (which breaks when wrapping ``<think>`` tags shift position),+ this tracks per-channel content lengths and emits:++ - ``<think>`` once when analysis channel first appears+ - analysis content deltas (computed on channel content directly)+ - ``</think>`` once when final channel first appears+ - final content deltas+ """+ # If raw contains <|channel|> but no complete channel+message pair yet,+ # buffer silently — don't emit partial channel names as text.+ has_channel_token = "<|channel|>" in raw+ matches = list(self._HARMONY_RE.finditer(raw))++ if has_channel_token and not matches:+ # Partial harmony markup still building — wait for more tokens+ return++ if not has_channel_token and not matches:+ # No harmony protocol at all — should not happen for gpt-oss+ # but handle gracefully by not emitting anything+ return++ for m in matches:+ channel = m.group(1).lower()+ content = m.group(2)++ if channel == "analysis":+ if not self._emitted_think_open:+ self._queue.put("<think>")+ self._emitted_think_open = True++ new_content = content[self._analysis_emitted :]+ if new_content:+ self._analysis_emitted = len(content)+ self._queue.put(new_content)++ elif channel in ("final", "assistant"):+ if self._emitted_think_open and not self._emitted_think_close:+ self._queue.put("</think>")+ self._emitted_think_close = True++ new_content = content[self._final_emitted :]+ if new_content:+ self._final_emitted = len(content)+ self._queue.put(new_content)++class InferenceBackend:"""Unified inference backend supporting text, vision, and LoRA models"""@@ -1069,6 +1243,23 @@ class InferenceBackend:logger.error(f"Whisper ASR error: {e}")yield f"Error: {str(e)}"+ def _is_gpt_oss_model(self, model_name: str = None) -> bool:+ """Check if the given (or active) model uses the gpt-oss harmony protocol."""+ name = (model_name or self.active_model_name or "").lower()+ try:+ from utils.datasets import MODEL_TO_TEMPLATE_MAPPER++ # Exact match+ if MODEL_TO_TEMPLATE_MAPPER.get(name) == "gpt-oss":+ return True+ # Partial match (e.g. name-bnb-4bit variants)+ for key, tmpl in MODEL_TO_TEMPLATE_MAPPER.items():+ if tmpl == "gpt-oss" and (key in name or name in key):+ return True+ except Exception:+ pass+ return "gpt-oss" in name+def generate_stream(self,prompt: str,@@ -1104,12 +1295,32 @@ class InferenceBackend:from transformers import TextIteratorStreamerimport threading- streamer = TextIteratorStreamer(- tokenizer,- skip_prompt = True,- skip_special_tokens = True,- timeout = 0.2,- )+ # Use HarmonyTextStreamer for gpt-oss models to properly parse+ # the multi-channel harmony protocol into <think> tags+ if self._is_gpt_oss_model():+ try:+ streamer = HarmonyTextStreamer(+ tokenizer,+ skip_prompt = True,+ timeout = 0.2,+ )+ except Exception as e:+ logger.warning(+ f"HarmonyTextStreamer init failed, falling back: {e}"+ )+ streamer = TextIteratorStreamer(+ tokenizer,+ skip_prompt = True,+ skip_special_tokens = True,+ timeout = 0.2,+ )+ else:+ streamer = TextIteratorStreamer(+ tokenizer,+ skip_prompt = True,+ skip_special_tokens = True,+ timeout = 0.2,+ )generation_kwargs = dict(**inputs,@@ -1709,6 +1920,15 @@ class InferenceBackend:def _clean_generated_text(self, text: str) -> str:"""Strip leaked special tokens using the tokenizer's own token list."""+ if self._is_gpt_oss_model():+ # HarmonyTextStreamer produces clean <think>...</think> output.+ # Strip harmony protocol tokens and other gpt-oss added tokens+ # (e.g. <|return|>) that may leak past the streamer.+ import re++ text = re.sub(r"<\|[a-z_]+\|>", "", text)+ return text.strip()+tokenizer = self.models.get(self.active_model_name, {}).get("tokenizer")if tokenizer:for token in getattr(tokenizer, "all_special_tokens", []):diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 7b552ca8b19..64a7324adf3 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -9,6 +9,7 @@ through its OpenAI-compatible /v1/chat/completions endpoint."""import atexit+import contextlibimport jsonimport structimport structlog@@ -902,8 +903,8 @@ class LlamaCppBackend:)# For reasoning models, set default thinking mode.- # Qwen3.5 small models (0.8B, 2B, 4B, 9B) disable thinking by default- # per Qwen's recommendation. Larger models default to thinking ON.+ # Qwen3.5 models below 9B (0.8B, 2B, 4B) disable thinking by default.+ # Only 9B and larger enable thinking.if self._supports_reasoning:import re@@ -914,7 +915,7 @@ class LlamaCppBackend:size_match = re.search(r"(\d+\.?\d*)\s*b", mid)if size_match:size_val = float(size_match.group(1))- if size_val <= 2:+ if size_val < 9:thinking_default = Falseself._reasoning_default = thinking_defaultcmd.extend(@@ -1292,16 +1293,44 @@ class LlamaCppBackend:# and re-check cancel_event.continue+ @staticmethod+ @contextlib.contextmanager+ def _stream_with_retry(+ client: "httpx.Client",+ url: str,+ payload: dict,+ cancel_event: Optional[threading.Event] = None,+ ):+ """Open an httpx streaming POST, retrying on ReadTimeout.++ The short read timeout (0.5 s) that enables cancel-checking during+ streaming can also fire while waiting for the server to produce+ its first response bytes (e.g. a reasoning model thinking).+ This wrapper retries the connection until headers arrive or+ cancel_event is set.+ """+ while True:+ if cancel_event is not None and cancel_event.is_set():+ raise GeneratorExit+ try:+ with client.stream("POST", url, json = payload) as response:+ yield response+ return+ except httpx.ReadTimeout:+ # Server still thinking -- retry+ continue+def generate_chat_completion(self,messages: list[dict],image_b64: Optional[str] = None,- temperature: float = 0.7,- top_p: float = 0.9,- top_k: int = 40,- min_p: float = 0.0,+ temperature: float = 0.6,+ top_p: float = 0.95,+ top_k: int = 20,+ min_p: float = 0.01,max_tokens: Optional[int] = None,repetition_penalty: float = 1.0,+ presence_penalty: float = 0.0,stop: Optional[list[str]] = None,cancel_event: Optional[threading.Event] = None,enable_thinking: Optional[bool] = None,@@ -1327,6 +1356,7 @@ class LlamaCppBackend:"top_k": top_k if top_k >= 0 else 0,"min_p": min_p,"repeat_penalty": repetition_penalty,+ "presence_penalty": presence_penalty,}# Pass enable_thinking per-request for reasoning modelsif self._supports_reasoning and enable_thinking is not None:@@ -1345,7 +1375,9 @@ class LlamaCppBackend:# frequently instead of blocking indefinitely on slow models.stream_timeout = httpx.Timeout(connect = 10, read = 0.5, write = 10, pool = 10)with httpx.Client(timeout = stream_timeout) as client:- with client.stream("POST", url, json = payload) as response:+ with self._stream_with_retry(+ client, url, payload, cancel_event+ ) as response:if response.status_code != 200:error_body = response.read().decode()raise RuntimeError(@@ -1426,12 +1458,13 @@ class LlamaCppBackend:self,messages: list[dict],tools: list[dict],- temperature: float = 0.7,- top_p: float = 0.9,- top_k: int = 40,- min_p: float = 0.0,+ temperature: float = 0.6,+ top_p: float = 0.95,+ top_k: int = 20,+ min_p: float = 0.01,max_tokens: Optional[int] = None,repetition_penalty: float = 1.0,+ presence_penalty: float = 0.0,stop: Optional[list[str]] = None,cancel_event: Optional[threading.Event] = None,enable_thinking: Optional[bool] = None,@@ -1466,6 +1499,7 @@ class LlamaCppBackend:"top_k": top_k if top_k >= 0 else 0,"min_p": min_p,"repeat_penalty": repetition_penalty,+ "presence_penalty": presence_penalty,"tools": tools,"tool_choice": "auto",}@@ -1540,11 +1574,32 @@ class LlamaCppBackend:arguments = raw_args# Yield status update- query_text = arguments.get("query", tool_name)- yield {"type": "status", "text": f"Searching: {query_text}"}+ if tool_name == "web_search":+ status_text = f"Searching: {arguments.get('query', '')}"+ elif tool_name == "python":+ preview = (+ (arguments.get("code") or "").strip().split("\n")[0][:60]+ )+ status_text = (+ f"Running Python: {preview}"+ if preview+ else "Running Python..."+ )+ elif tool_name == "terminal":+ cmd_preview = (arguments.get("command") or "")[:60]+ status_text = (+ f"Running: {cmd_preview}"+ if cmd_preview+ else "Running command..."+ )+ else:+ status_text = f"Calling: {tool_name}"+ yield {"type": "status", "text": status_text}# Execute the tool- result = execute_tool(tool_name, arguments)+ result = execute_tool(+ tool_name, arguments, cancel_event = cancel_event+ )# Append tool result to conversationtool_msg = {@@ -1585,6 +1640,7 @@ class LlamaCppBackend:"top_k": top_k if top_k >= 0 else 0,"min_p": min_p,"repeat_penalty": repetition_penalty,+ "presence_penalty": presence_penalty,}if self._supports_reasoning and enable_thinking is not None:stream_payload["chat_template_kwargs"] = {@@ -1603,7 +1659,9 @@ class LlamaCppBackend:try:stream_timeout = httpx.Timeout(connect = 10, read = 0.5, write = 10, pool = 10)with httpx.Client(timeout = stream_timeout) as client:- with client.stream("POST", url, json = stream_payload) as response:+ with self._stream_with_retry(+ client, url, stream_payload, cancel_event+ ) as response:if response.status_code != 200:error_body = response.read().decode()raise RuntimeError(diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex b633d377f22..ee89dd2c0b5 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -4,9 +4,25 @@"""Tool definitions and executors for LLM tool calling.-Currently supports web search via DuckDuckGo (ddgs package, no API key needed).+Supports web search (DuckDuckGo), Python code execution, and terminal commands."""+import os++os.environ["UNSLOTH_IS_PRESENT"] = "1"++import subprocess+import sys+import tempfile+import threading++from unsloth_zoo.rl_environments import check_signal_escape_patterns++_EXEC_TIMEOUT = 300 # 5 minutes+_MAX_OUTPUT_CHARS = 8000 # truncate long output+_BASH_BLOCKED_WORDS = {"rm", "sudo", "dd", "chmod", "mkfs", "shutdown", "reboot"}++WEB_SEARCH_TOOL = {"type": "function","function": {@@ -25,13 +41,53 @@ WEB_SEARCH_TOOL = {},}-ALL_TOOLS = [WEB_SEARCH_TOOL]+PYTHON_TOOL = {+ "type": "function",+ "function": {+ "name": "python",+ "description": "Execute Python code in a sandbox and return stdout/stderr.",+ "parameters": {+ "type": "object",+ "properties": {+ "code": {+ "type": "string",+ "description": "The Python code to run",+ }+ },+ "required": ["code"],+ },+ },+}++TERMINAL_TOOL = {+ "type": "function",+ "function": {+ "name": "terminal",+ "description": "Execute a terminal command and return stdout/stderr.",+ "parameters": {+ "type": "object",+ "properties": {+ "command": {+ "type": "string",+ "description": "The command to run",+ }+ },+ "required": ["command"],+ },+ },+}++ALL_TOOLS = [WEB_SEARCH_TOOL, PYTHON_TOOL, TERMINAL_TOOL]-def execute_tool(name: str, arguments: dict) -> str:+def execute_tool(name: str, arguments: dict, cancel_event = None) -> str:"""Execute a tool by name with the given arguments. Returns result as a string."""if name == "web_search":return _web_search(arguments.get("query", ""))+ if name == "python":+ return _python_exec(arguments.get("code", ""), cancel_event)+ if name == "terminal":+ return _bash_exec(arguments.get("command", ""), cancel_event)return f"Unknown tool: {name}"@@ -55,3 +111,139 @@ def _web_search(query: str, max_results: int = 5) -> str:return "\n\n---\n\n".join(parts)except Exception as e:return f"Search failed: {e}"+++def _check_code_safety(code: str) -> str | None:+ """Validate code safety using unsloth_zoo.++ Returns an error message string if the code is unsafe, or None if OK.+ """+ # Check for signal/timeout escape patterns+ safe, info = check_signal_escape_patterns(code)+ if not safe:+ reasons = [+ item.get("description", "") for item in info.get("signal_tampering", [])+ ]+ return (+ f"Error: unsafe code detected ({'; '.join(reasons)}). "+ f"Please remove signal manipulation from your code."+ )++ return None+++def _cancel_watcher(proc, cancel_event, poll_interval = 0.2):+ """Daemon thread that kills a process when cancel_event is set."""+ while proc.poll() is None:+ if cancel_event is not None and cancel_event.is_set():+ proc.kill()+ return+ cancel_event.wait(poll_interval) if cancel_event else None+++def _truncate(text: str, limit: int = _MAX_OUTPUT_CHARS) -> str:+ if len(text) > limit:+ return text[:limit] + f"\n\n... (truncated, {len(text)} chars total)"+ return text+++def _python_exec(code: str, cancel_event = None) -> str:+ """Execute Python code in a subprocess sandbox."""+ if not code or not code.strip():+ return "No code provided."++ # Validate imports and code safety+ error = _check_code_safety(code)+ if error:+ return error++ tmp_path = None+ try:+ fd, tmp_path = tempfile.mkstemp(suffix = ".py", prefix = "studio_exec_")+ with os.fdopen(fd, "w") as f:+ f.write(code)++ proc = subprocess.Popen(+ [sys.executable, tmp_path],+ stdout = subprocess.PIPE,+ stderr = subprocess.STDOUT,+ text = True,+ cwd = tempfile.gettempdir(),+ )++ # Spawn cancel watcher if we have a cancel event+ if cancel_event is not None:+ watcher = threading.Thread(+ target = _cancel_watcher, args = (proc, cancel_event), daemon = True+ )+ watcher.start()++ try:+ output, _ = proc.communicate(timeout = _EXEC_TIMEOUT)+ except subprocess.TimeoutExpired:+ proc.kill()+ proc.communicate()+ return _truncate("Execution timed out after 5 minutes.")++ if cancel_event is not None and cancel_event.is_set():+ return "Execution cancelled."++ result = output or ""+ if proc.returncode != 0:+ result = f"Exit code {proc.returncode}:\n{result}"+ return _truncate(result) if result.strip() else "(no output)"++ except Exception as e:+ return f"Execution error: {e}"+ finally:+ if tmp_path and os.path.exists(tmp_path):+ try:+ os.unlink(tmp_path)+ except OSError:+ pass+++def _bash_exec(command: str, cancel_event = None) -> str:+ """Execute a bash command in a subprocess sandbox."""+ if not command or not command.strip():+ return "No command provided."++ # Block dangerous commands+ tokens = set(command.lower().split())+ blocked = tokens & _BASH_BLOCKED_WORDS+ if blocked:+ return f"Blocked command(s) for safety: {', '.join(sorted(blocked))}"++ try:+ with tempfile.TemporaryDirectory() as tmpdir:+ proc = subprocess.Popen(+ ["bash", "-c", command],+ stdout = subprocess.PIPE,+ stderr = subprocess.STDOUT,+ text = True,+ cwd = tmpdir,+ )++ if cancel_event is not None:+ watcher = threading.Thread(+ target = _cancel_watcher, args = (proc, cancel_event), daemon = True+ )+ watcher.start()++ try:+ output, _ = proc.communicate(timeout = _EXEC_TIMEOUT)+ except subprocess.TimeoutExpired:+ proc.kill()+ proc.communicate()+ return _truncate("Execution timed out after 5 minutes.")++ if cancel_event is not None and cancel_event.is_set():+ return "Execution cancelled."++ result = output or ""+ if proc.returncode != 0:+ result = f"Exit code {proc.returncode}:\n{result}"+ return _truncate(result) if result.strip() else "(no output)"++ except Exception as e:+ return f"Execution error: {e}"diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.pyindex 013c14b4f0f..06939081781 100644--- a/studio/backend/core/inference/worker.py+++ b/studio/backend/core/inference/worker.py@@ -67,7 +67,7 @@ def _activate_transformers_version(model_name: str) -> None:"--target",venv_t5,"--no-deps",- "transformers==5.2.0",+ "transformers==5.3.0",],stdout = sp.PIPE,stderr = sp.STDOUT,@@ -555,7 +555,7 @@ def run_inference_process(resp_queue,{"type": "status",- "message": "Importing ML libraries...",+ "message": "Importing Unsloth...","ts": time.time(),},)diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex 685a4a674ec..57559ded54a 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -61,7 +61,7 @@ def _activate_transformers_version(model_name: str) -> None:"--target",venv_t5,"--no-deps",- "transformers==5.2.0",+ "transformers==5.3.0",],stdout = sp.PIPE,stderr = sp.STDOUT,@@ -138,7 +138,64 @@ def run_training_process()return- # ── 1b. Set fork start method so dataset.map() can multiprocess ──+ # ── 1a. Auto-enable trust_remote_code for unsloth/* transformers 5.x models ──+ # Some newer architectures (e.g. NemotronH) have config parsing bugs in+ # transformers that require trust_remote_code=True as a workaround.+ # Only auto-enable for unsloth/* prefixed models (trusted source).+ from utils.transformers_version import needs_transformers_5++ if (+ needs_transformers_5(model_name)+ and model_name.lower().startswith("unsloth/")+ and not config.get("trust_remote_code", False)+ ):+ config["trust_remote_code"] = True+ logger.info(+ "Auto-enabled trust_remote_code for unsloth/* transformers 5.x model: %s",+ model_name,+ )++ # ── 1b. Auto-install mamba-ssm for SSM/hybrid models (NemotronH, Falcon-H1) ──+ _SSM_MODEL_SUBSTRINGS = ("nemotron_h", "nemotron-3-nano", "falcon_h1", "falcon-h1")+ if any(sub in model_name.lower() for sub in _SSM_MODEL_SUBSTRINGS):+ try:+ import mamba_ssm # noqa: F401++ logger.info("mamba-ssm already installed")+ except ImportError:+ logger.info(+ "SSM model detected — installing mamba-ssm and causal-conv1d (this may take several minutes)..."+ )+ _send_status(+ event_queue, "Installing mamba-ssm (first time only, ~7 min)..."+ )+ import subprocess as _sp++ # --no-build-isolation: compile against current torch (no version conflicts)+ # --no-deps: don't pull in torch/transformers/triton (already installed)+ for _pkg in ["causal_conv1d", "mamba_ssm"]:+ _r = _sp.run(+ [+ sys.executable,+ "-m",+ "pip",+ "install",+ "--no-build-isolation",+ "--no-deps",+ "--no-cache-dir",+ _pkg,+ ],+ stdout = _sp.PIPE,+ stderr = _sp.STDOUT,+ text = True,+ )+ if _r.returncode != 0:+ logger.error("Failed to install %s:\n%s", _pkg, _r.stdout)+ else:+ logger.info("Installed %s successfully", _pkg)+ logger.info("mamba-ssm installation complete")++ # ── 1c. Set fork start method so dataset.map() can multiprocess ──# The parent launched us via spawn (clean process), but the compiled# SFTTrainer checks get_start_method() and disables num_proc if not "fork".# Linux only: fork is the default start method and is safe here (no CUDA@@ -168,7 +225,7 @@ def run_training_process(# ── 2. Now import ML libraries (fresh in this clean process) ──try:- _send_status(event_queue, "Importing ML libraries...")+ _send_status(event_queue, "Importing Unsloth...")backend_path = str(Path(__file__).resolve().parent.parent.parent)if backend_path not in sys.path:@@ -486,7 +543,14 @@ def run_training_process(ensure_dir(Path(tensorboard_dir))# Start training (directly — no inner thread, we ARE the subprocess)- _send_status(event_queue, "Starting training...")+ dataset_display = (+ config.get("hf_dataset", "") or config.get("uploaded_file", "") or ""+ )+ _send_status(+ event_queue,+ f'Training "{model_name}"'+ + (f"\nDataset = {dataset_display}" if dataset_display else ""),+ )max_steps = config.get("max_steps", 0)save_steps = config.get("save_steps", 0)diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex e7ae63adf1f..5d17d2d0be8 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -9,7 +9,7 @@ from __future__ import annotationsimport timeimport uuid-from typing import Annotated, Literal, Optional, List, Union+from typing import Annotated, Any, Dict, Literal, Optional, List, Unionfrom pydantic import BaseModel, Discriminator, Field, Tag@@ -90,15 +90,16 @@ class GenerateRequest(BaseModel):messages: List[dict] = Field(..., description = "Chat messages in OpenAI format")system_prompt: str = Field("", description = "System prompt")- temperature: float = Field(0.7, ge = 0.0, le = 2.0, description = "Sampling temperature")- top_p: float = Field(0.9, ge = 0.0, le = 1.0, description = "Top-p sampling")- top_k: int = Field(40, ge = -1, le = 100, description = "Top-k sampling")+ temperature: float = Field(0.6, ge = 0.0, le = 2.0, description = "Sampling temperature")+ top_p: float = Field(0.95, ge = 0.0, le = 1.0, description = "Top-p sampling")+ top_k: int = Field(20, ge = -1, le = 100, description = "Top-k sampling")max_new_tokens: int = Field(2048, ge = 1, le = 4096, description = "Maximum tokens to generate")repetition_penalty: float = Field(1.0, ge = 1.0, le = 2.0, description = "Repetition penalty")+ presence_penalty: float = Field(0.0, ge = 0.0, le = 2.0, description = "Presence penalty")image_base64: Optional[str] = Field(None, description = "Base64 encoded image for vision models")@@ -183,6 +184,18 @@ class InferenceStatusResponse(BaseModel):loaded: List[str] = Field(default_factory = list, description = "Models currently loaded")+ inference: Optional[Dict[str, Any]] = Field(+ None, description = "Recommended inference parameters for the active model"+ )+ supports_reasoning: bool = Field(+ False, description = "Whether the active model supports reasoning/thinking mode"+ )+ supports_tools: bool = Field(+ False, description = "Whether the active model supports tool calling"+ )+ context_length: Optional[int] = Field(+ None, description = "Context length of the active model"+ )# =====================================================================@@ -262,16 +275,17 @@ class ChatCompletionRequest(BaseModel):)messages: list[ChatMessage] = Field(..., description = "Conversation messages")stream: bool = Field(True, description = "Whether to stream the response via SSE")- temperature: float = Field(0.7, ge = 0.0, le = 2.0)- top_p: float = Field(0.9, ge = 0.0, le = 1.0)+ temperature: float = Field(0.6, ge = 0.0, le = 2.0)+ top_p: float = Field(0.95, ge = 0.0, le = 1.0)max_tokens: Optional[int] = Field(None, ge = 1, description = "Maximum tokens to generate (None = until EOS)")+ presence_penalty: float = Field(0.0, ge = 0.0, le = 2.0, description = "Presence penalty")# ── Unsloth extensions (ignored by standard OpenAI clients) ──- top_k: int = Field(40, ge = -1, le = 100, description = "[x-unsloth] Top-k sampling")+ top_k: int = Field(20, ge = -1, le = 100, description = "[x-unsloth] Top-k sampling")min_p: float = Field(- 0.0, ge = 0.0, le = 1.0, description = "[x-unsloth] Min-p sampling threshold"+ 0.01, ge = 0.0, le = 1.0, description = "[x-unsloth] Min-p sampling threshold")repetition_penalty: float = Field(1.1, ge = 1.0, le = 2.0, description = "[x-unsloth] Repetition penalty"@@ -298,7 +312,11 @@ class ChatCompletionRequest(BaseModel):)enable_tools: Optional[bool] = Field(None,- description = "[x-unsloth] Enable tool calling (web search) for supported models",+ description = "[x-unsloth] Enable tool calling for supported models",+ )+ enabled_tools: Optional[list[str]] = Field(+ None,+ description = "[x-unsloth] List of enabled tool names (e.g. ['web_search', 'python', 'terminal']). If None, all tools are enabled.",)diff --git a/studio/backend/models/models.py b/studio/backend/models/models.pyindex cd42f06a43d..f721bbbf7ac 100644--- a/studio/backend/models/models.py+++ b/studio/backend/models/models.py@@ -85,6 +85,12 @@ class ModelDetails(BaseModel):base_model: Optional[str] = Field(None, description = "Base model if this is a LoRA adapter")+ max_position_embeddings: Optional[int] = Field(+ None, description = "Maximum context length supported by the model"+ )+ model_size_bytes: Optional[int] = Field(+ None, description = "Total size of model weight files in bytes"+ )class LoRAInfo(BaseModel):diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 5a49a730cac..d50f53ba8dc 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -95,6 +95,79 @@ async def load_model(# Version switching is handled automatically by the subprocess-based# inference backend — no need for ensure_transformers_version() here.+ # ── Already-loaded check: skip reload if the exact model is active ──+ backend = get_inference_backend()+ llama_backend = get_llama_cpp_backend()++ if request.gguf_variant:+ if (+ llama_backend.is_loaded+ and llama_backend.hf_variant+ and llama_backend.hf_variant.lower() == request.gguf_variant.lower()+ and llama_backend.model_identifier+ and llama_backend.model_identifier.lower() == request.model_path.lower()+ ):+ logger.info(+ f"Model already loaded (GGUF): {request.model_path} variant={request.gguf_variant}, skipping reload"+ )+ inference_config = load_inference_config(llama_backend.model_identifier)+ from utils.models import is_audio_input_type++ _gguf_audio = (+ llama_backend._audio_type+ if hasattr(llama_backend, "_audio_type")+ else None+ )+ _gguf_is_audio = getattr(llama_backend, "_is_audio", False)+ return LoadResponse(+ status = "already_loaded",+ model = llama_backend.model_identifier,+ display_name = llama_backend.model_identifier,+ is_vision = llama_backend._is_vision,+ is_lora = False,+ is_gguf = True,+ is_audio = _gguf_is_audio,+ audio_type = _gguf_audio,+ has_audio_input = is_audio_input_type(_gguf_audio)+ if _gguf_audio+ else False,+ inference = inference_config,+ context_length = llama_backend.context_length,+ supports_reasoning = llama_backend.supports_reasoning,+ chat_template = llama_backend.chat_template,+ )+ else:+ if (+ backend.active_model_name+ and backend.active_model_name.lower() == request.model_path.lower()+ ):+ logger.info(+ f"Model already loaded (Unsloth): {request.model_path}, skipping reload"+ )+ inference_config = load_inference_config(backend.active_model_name)+ _model_info = backend.models.get(backend.active_model_name, {})+ _chat_template = None+ try:+ _tpl_info = _model_info.get("chat_template_info", {})+ _chat_template = _tpl_info.get("template")+ except Exception as e:+ logger.warning(+ f"Could not retrieve chat template for {backend.active_model_name}: {e}"+ )+ return LoadResponse(+ status = "already_loaded",+ model = backend.active_model_name,+ display_name = backend.active_model_name,+ is_vision = _model_info.get("is_vision", False),+ is_lora = _model_info.get("is_lora", False),+ is_gguf = False,+ is_audio = _model_info.get("is_audio", False),+ audio_type = _model_info.get("audio_type"),+ has_audio_input = _model_info.get("has_audio_input", False),+ inference = inference_config,+ chat_template = _chat_template,+ )+# Create config using clean factory method# is_lora is auto-detected from adapter_config.json on disk/HFconfig = ModelConfig.from_identifier(@@ -501,15 +574,21 @@ async def get_status(# If a GGUF model is loaded via llama-server, report thatif llama_backend.is_loaded:+ _model_id = llama_backend.model_identifier+ _inference_cfg = load_inference_config(_model_id) if _model_id else Nonereturn InferenceStatusResponse(- active_model = llama_backend.model_identifier,+ active_model = _model_id,is_vision = llama_backend.is_vision,is_gguf = True,gguf_variant = llama_backend.hf_variant,is_audio = getattr(llama_backend, "_is_audio", False),audio_type = getattr(llama_backend, "_audio_type", None),loading = [],- loaded = [llama_backend.model_identifier],+ loaded = [_model_id],+ inference = _inference_cfg,+ supports_reasoning = llama_backend.supports_reasoning,+ supports_tools = llama_backend.supports_tools,+ context_length = llama_backend.context_length,)# Otherwise, report Unsloth backend status@@ -526,6 +605,11 @@ async def get_status(audio_type = model_info.get("audio_type")has_audio_input = model_info.get("has_audio_input", False)+ # gpt-oss safetensors models support reasoning via harmony channels+ supports_reasoning = False+ if backend.active_model_name and hasattr(backend, "_is_gpt_oss_model"):+ supports_reasoning = backend._is_gpt_oss_model()+return InferenceStatusResponse(active_model = backend.active_model_name,is_vision = is_vision,@@ -535,6 +619,7 @@ async def get_status(has_audio_input = has_audio_input,loading = list(getattr(backend, "loading_models", set())),loaded = list(backend.models.keys()),+ supports_reasoning = supports_reasoning,)except Exception as e:@@ -943,16 +1028,26 @@ async def openai_chat_completions(if use_tools:from core.inference.tools import ALL_TOOLS+ if payload.enabled_tools:+ tools_to_use = [+ t+ for t in ALL_TOOLS+ if t["function"]["name"] in payload.enabled_tools+ ]+ else:+ tools_to_use = ALL_TOOLS+def gguf_generate_with_tools():return llama_backend.generate_chat_completion_with_tools(messages = gguf_messages,- tools = ALL_TOOLS,+ tools = tools_to_use,temperature = payload.temperature,top_p = payload.top_p,top_k = payload.top_k,min_p = payload.min_p,max_tokens = payload.max_tokens,repetition_penalty = payload.repetition_penalty,+ presence_penalty = payload.presence_penalty,cancel_event = cancel_event,enable_thinking = payload.enable_thinking,)@@ -1035,9 +1130,10 @@ async def openai_chat_completions(cancel_event.set()raiseexcept Exception as e:- logger.error(- f"Error during GGUF tool streaming: {e}", exc_info = True- )+ import traceback++ tb = traceback.format_exc()+ logger.error(f"Error during GGUF tool streaming: {e}\n{tb}")error_chunk = {"error": {"message": "An internal error occurred",@@ -1068,6 +1164,7 @@ async def openai_chat_completions(min_p = payload.min_p,max_tokens = payload.max_tokens,repetition_penalty = payload.repetition_penalty,+ presence_penalty = payload.presence_penalty,cancel_event = cancel_event,enable_thinking = payload.enable_thinking,)diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex fa0daea7fdf..60be0559dd7 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -8,7 +8,7 @@ Model Management API routesimport osimport sysfrom pathlib import Path-from fastapi import APIRouter, Depends, HTTPException, Query+from fastapi import APIRouter, Body, Depends, HTTPException, Queryfrom typing import List, Optionalimport structlogfrom loggers import get_logger@@ -348,6 +348,44 @@ async def list_models(raise HTTPException(status_code = 500, detail = f"Failed to list models: {str(e)}")+def _get_max_position_embeddings(config) -> Optional[int]:+ """Extract max_position_embeddings from a model config, checking text_config fallback."""+ if hasattr(config, "max_position_embeddings"):+ return config.max_position_embeddings+ if hasattr(config, "text_config") and hasattr(+ config.text_config, "max_position_embeddings"+ ):+ return config.text_config.max_position_embeddings+ return None+++def _get_model_size_bytes(+ model_name: str, hf_token: Optional[str] = None+) -> Optional[int]:+ """Get total size of model weight files from HF Hub."""+ try:+ from huggingface_hub import HfApi++ api = HfApi(token = hf_token)+ info = api.repo_info(model_name, repo_type = "model", token = hf_token)+ if not info.siblings:+ return None++ weight_exts = (".safetensors", ".bin", ".pt", ".pth", ".gguf")+ total = 0+ for sibling in info.siblings:+ if sibling.rfilename and any(+ sibling.rfilename.endswith(ext) for ext in weight_exts+ ):+ if sibling.size is not None:+ total += sibling.size++ return total if total > 0 else None+ except Exception as e:+ logger.warning(f"Could not get model size for {model_name}: {e}")+ return None++@router.get("/config/{model_name:path}")async def get_model_config(model_name: str,@@ -379,15 +417,30 @@ async def get_model_config(# Check if it's a LoRA adapteris_lora = Falsebase_model = None+ max_position_embeddings = Nonetry:model_config = ModelConfig.from_identifier(model_name)is_lora = model_config.is_lorabase_model = model_config.base_model if is_lora else None+ max_position_embeddings = _get_max_position_embeddings(model_config)except Exception:pass+ # Fallback: try AutoConfig directly if not found yet+ if max_position_embeddings is None:+ try:+ from transformers import AutoConfig as _AutoConfig++ _trust = model_name.lower().startswith("unsloth/")+ _ac = _AutoConfig.from_pretrained(+ model_name, trust_remote_code = _trust, token = hf_token+ )+ max_position_embeddings = _get_max_position_embeddings(_ac)+ except Exception:+ pass+logger.info(- f"Model config result for {model_name}: is_vision={is_vision}, is_embedding={is_embedding}, audio_type={audio_type}, is_lora={is_lora}"+ f"Model config result for {model_name}: is_vision={is_vision}, is_embedding={is_embedding}, audio_type={audio_type}, is_lora={is_lora}, max_position_embeddings={max_position_embeddings}")return ModelDetails(id = model_name,@@ -401,6 +454,8 @@ async def get_model_config(has_audio_input = is_audio_input_type(audio_type),model_type = derive_model_type(is_vision, audio_type, is_embedding),base_model = base_model,+ max_position_embeddings = max_position_embeddings,+ model_size_bytes = _get_model_size_bytes(model_name, hf_token),)except Exception as e:@@ -842,7 +897,13 @@ async def list_cached_gguf(async def list_cached_models(current_subject: str = Depends(get_current_subject),):- """List non-GGUF model repos that have been downloaded to the HF cache."""+ """List non-GGUF model repos that have been downloaded to the HF cache.++ Only includes repos that actually contain model weight files+ (.safetensors, .bin), not repos with only config/metadata.+ """+ _WEIGHT_EXTENSIONS = (".safetensors", ".bin")+try:from huggingface_hub import scan_cache_dir@@ -859,6 +920,14 @@ async def list_cached_models()if total_size == 0:continue+ # Skip repos that only have config/metadata files (no weights)+ has_weights = any(+ f.file_name.endswith(_WEIGHT_EXTENSIONS)+ for rev in repo_info.revisions+ for f in rev.files+ )+ if not has_weights:+ continuekey = repo_id.lower()existing = seen_lower.get(key)if existing is None or total_size > existing["size_bytes"]:@@ -873,6 +942,129 @@ async def list_cached_models(return {"cached": []}[email protected]("/delete-cached")+async def delete_cached_model(+ repo_id: str = Body(...),+ variant: Optional[str] = Body(None),+ current_subject: str = Depends(get_current_subject),+):+ """Delete a cached model repo (or a specific GGUF variant) from the HF cache.++ When *variant* is provided, only the GGUF files matching that quant label+ are removed (e.g. ``UD-Q4_K_XL``). Otherwise the entire repo is deleted.+ Refuses if the model is currently loaded for inference.+ """+ if not _is_valid_repo_id(repo_id):+ raise HTTPException(status_code = 400, detail = "Invalid repo_id format")++ # Check if model is currently loaded+ try:+ from routes.inference import get_llama_cpp_backend++ llama_backend = get_llama_cpp_backend()+ if llama_backend.is_loaded and llama_backend.model_identifier:+ loaded_id = llama_backend.model_identifier.lower()+ if loaded_id == repo_id.lower() or loaded_id.startswith(repo_id.lower()):+ raise HTTPException(+ status_code = 400,+ detail = "Unload the model before deleting",+ )+ except HTTPException:+ raise+ except Exception:+ pass++ try:+ inference_backend = get_inference_backend()+ if inference_backend.active_model_name:+ active = inference_backend.active_model_name.lower()+ if active == repo_id.lower() or active.startswith(repo_id.lower()):+ raise HTTPException(+ status_code = 400,+ detail = "Unload the model before deleting",+ )+ except HTTPException:+ raise+ except Exception:+ pass++ try:+ from huggingface_hub import scan_cache_dir++ hf_cache = scan_cache_dir()+ target_repo = None+ for repo_info in hf_cache.repos:+ if repo_info.repo_type != "model":+ continue+ if repo_info.repo_id.lower() == repo_id.lower():+ target_repo = repo_info+ break++ if target_repo is None:+ raise HTTPException(status_code = 404, detail = "Model not found in cache")++ # ── Per-variant GGUF deletion ────────────────────────────+ if variant:+ deleted_bytes = 0+ deleted_count = 0+ for rev in target_repo.revisions:+ for f in rev.files:+ if not f.file_name.endswith(".gguf"):+ continue+ quant = _extract_quant_label(f.file_name)+ if quant.lower() != variant.lower():+ continue+ # Delete the blob (actual data) and the snapshot symlink+ try:+ blob = Path(f.blob_path)+ snap = Path(f.file_path)+ size = blob.stat().st_size if blob.exists() else 0+ if snap.exists() or snap.is_symlink():+ snap.unlink()+ if blob.exists():+ blob.unlink()+ deleted_bytes += size+ deleted_count += 1+ except Exception as e:+ logger.warning(f"Failed to delete {f.file_name}: {e}")++ if deleted_count == 0:+ raise HTTPException(+ status_code = 404,+ detail = f"Variant {variant} not found in cache for {repo_id}",+ )++ freed_mb = deleted_bytes / (1024 * 1024)+ logger.info(+ f"Deleted {deleted_count} file(s) for {repo_id} variant {variant}: "+ f"{freed_mb:.1f} MB freed"+ )+ return {"status": "deleted", "repo_id": repo_id, "variant": variant}++ # ── Full repo deletion ───────────────────────────────────+ revision_hashes = [rev.commit_hash for rev in target_repo.revisions]+ if not revision_hashes:+ raise HTTPException(status_code = 404, detail = "No revisions found for model")++ delete_strategy = hf_cache.delete_revisions(*revision_hashes)+ logger.info(+ f"Deleting cached model {repo_id}: "+ f"{delete_strategy.expected_freed_size_str} will be freed"+ )+ delete_strategy.execute()++ return {"status": "deleted", "repo_id": repo_id}++ except HTTPException:+ raise+ except Exception as e:+ logger.error(f"Error deleting cached model {repo_id}: {e}", exc_info = True)+ raise HTTPException(+ status_code = 500,+ detail = f"Failed to delete cached model: {str(e)}",+ )++@router.get("/checkpoints", response_model = CheckpointListResponse)async def list_checkpoints(outputs_dir: str = Query(diff --git a/studio/backend/run.py b/studio/backend/run.pyindex 2f186758ae3..2f064ab92e7 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -75,6 +75,7 @@ def _is_port_free(host: str, port: int) -> bool:try:with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)s.bind((host, port))return Trueexcept OSError:diff --git a/studio/backend/utils/datasets/llm_assist.py b/studio/backend/utils/datasets/llm_assist.pyindex 478bfe49da9..51541774d93 100644--- a/studio/backend/utils/datasets/llm_assist.py+++ b/studio/backend/utils/datasets/llm_assist.py@@ -154,7 +154,7 @@ def _run_with_helper(prompt: str, max_tokens: int = 256) -> Optional[str]:top_k = 20,max_tokens = max_tokens,repetition_penalty = 1.0,- enable_thinking = False,+ enable_thinking = False, # Always disable thinking for AI Assist):cumulative = text # cumulative — last value is full text@@ -429,7 +429,7 @@ def _generate_with_backend(backend, messages: list[dict], max_tokens: int = 512)top_k = 20,max_tokens = max_tokens,repetition_penalty = 1.0,- enable_thinking = False,+ enable_thinking = False, # Always disable thinking for AI Assist):cumulative = textresult = cumulative.strip()diff --git a/studio/backend/utils/datasets/model_mappings.py b/studio/backend/utils/datasets/model_mappings.pyindex 96b0c508764..95b4791574f 100644--- a/studio/backend/utils/datasets/model_mappings.py+++ b/studio/backend/utils/datasets/model_mappings.py@@ -424,7 +424,7 @@ TEMPLATE_TO_RESPONSES_MAPPER = {},"qwen3.5": {"instruction": "<|im_start|>user\n",- "response": "<|im_start|>assistant\n<think>\n",+ "response": "<|im_start|>assistant\n",},"qwen3-instruct": {"instruction": "<|im_start|>user\n",diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex 7234dbd155e..7d1bc528c67 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -243,8 +243,9 @@ def get_gpu_summary() -> Dict[str, Any]:return {"gpu_name": mem.get("device_name"),"vram_total_gb": round(mem.get("total_gb", 0), 2),+ "vram_free_gb": round(mem.get("free_gb", 0), 2),}- return {"gpu_name": None, "vram_total_gb": None}+ return {"gpu_name": None, "vram_total_gb": None, "vram_free_gb": None}def get_package_versions() -> Dict[str, Optional[str]]:diff --git a/studio/backend/utils/inference/inference_config.py b/studio/backend/utils/inference/inference_config.pyindex add51bce9b7..a0377f98696 100644--- a/studio/backend/utils/inference/inference_config.py+++ b/studio/backend/utils/inference/inference_config.py@@ -169,6 +169,7 @@ def load_inference_config(model_identifier: str) -> Dict[str, Any]:"top_p": _get_param("top_p", 0.95),"top_k": _get_param("top_k", -1),"min_p": _get_param("min_p", 0.01),+ "presence_penalty": _get_param("presence_penalty", 0.0),"trust_remote_code": model_inference.get("trust_remote_code", default_inference.get("trust_remote_code", False)),diff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.pyindex 58fbc35e33f..5666b3be350 100644--- a/studio/backend/utils/transformers_version.py+++ b/studio/backend/utils/transformers_version.py@@ -5,7 +5,7 @@Automatic transformers version switching.Some newer model architectures (Ministral-3, GLM-4.7-Flash, Qwen3-30B-A3B MoE,-tiny_qwen3_moe) require transformers>=5.2.0, while everything else needs the+tiny_qwen3_moe) require transformers>=5.3.0, while everything else needs thedefault 4.57.x that ships with Unsloth.When loading a LoRA adapter with a custom name, we resolve the base model from@@ -48,8 +48,16 @@ TRANSFORMERS_5_MODEL_SUBSTRINGS: tuple[str, ...] = ("tiny_qwen3_moe", # imdatta0/tiny_qwen3_moe_2.8B_0.7B)+# Tokenizer classes that only exist in transformers>=5.x+_TRANSFORMERS_5_TOKENIZER_CLASSES: set[str] = {+ "TokenizersBackend",+}++# Cache for dynamic tokenizer_config.json lookups to avoid repeated fetches+_tokenizer_class_cache: dict[str, bool] = {}+# Versions-TRANSFORMERS_5_VERSION = "5.2.0"+TRANSFORMERS_5_VERSION = "5.3.0"TRANSFORMERS_DEFAULT_VERSION = "4.57.1"# Pre-installed directory for transformers 5.x — created by setup.sh / setup.ps1@@ -107,11 +115,53 @@ def _resolve_base_model(model_name: str) -> str:return model_name+def _check_tokenizer_config_needs_v5(model_name: str) -> bool:+ """Fetch tokenizer_config.json from HuggingFace and check if the+ tokenizer_class requires transformers 5.x.++ Results are cached in ``_tokenizer_class_cache`` to avoid repeated fetches.+ Returns False on any network/parse error (fail-open to default version).+ """+ if model_name in _tokenizer_class_cache:+ return _tokenizer_class_cache[model_name]++ import urllib.request++ url = f"https://huggingface.co/{model_name}/raw/main/tokenizer_config.json"+ try:+ req = urllib.request.Request(url, headers = {"User-Agent": "unsloth-studio"})+ with urllib.request.urlopen(req, timeout = 10) as resp:+ data = json.loads(resp.read().decode())+ tokenizer_class = data.get("tokenizer_class", "")+ result = tokenizer_class in _TRANSFORMERS_5_TOKENIZER_CLASSES+ if result:+ logger.info(+ "Dynamic check: %s uses tokenizer_class=%s (requires transformers 5.x)",+ model_name,+ tokenizer_class,+ )+ _tokenizer_class_cache[model_name] = result+ return result+ except Exception as exc:+ logger.debug(+ "Could not fetch tokenizer_config.json for '%s': %s", model_name, exc+ )+ _tokenizer_class_cache[model_name] = False+ return False++def needs_transformers_5(model_name: str) -> bool:"""Return True if *model_name* belongs to an architecture that requires- ``transformers>=5.2.0``."""+ ``transformers>=5.3.0``.++ First checks the hardcoded substring list for known models, then+ dynamically fetches ``tokenizer_config.json`` from HuggingFace to check+ if the tokenizer_class (e.g. ``TokenizersBackend``) requires v5.+ """lowered = model_name.lower()- return any(sub in lowered for sub in TRANSFORMERS_5_MODEL_SUBSTRINGS)+ if any(sub in lowered for sub in TRANSFORMERS_5_MODEL_SUBSTRINGS):+ return True+ return _check_tokenizer_config_needs_v5(model_name)# ---------------------------------------------------------------------------diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsxindex f61990ace21..e41ec10dfe2 100644--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx@@ -225,6 +225,19 @@ function StreamdownBlock(props: BlockProps) {);}+ if (props.isIncomplete && codeFence && isSvgFence(codeFence)) {+ return (+ <div className="relative isolate">+ <div className="my-4 rounded-xl border border-border bg-muted/30 p-4">+ <div className="mb-2 text-xs font-medium text-muted-foreground">svg</div>+ <pre className="overflow-x-auto text-xs text-muted-foreground whitespace-pre-wrap break-all">+ <code>{codeFence.source}</code>+ </pre>+ </div>+ </div>+ );+ }+if (mermaidSource) {return (<div className="relative isolate">diff --git a/studio/frontend/src/components/assistant-ui/model-selector/pickers.tsx b/studio/frontend/src/components/assistant-ui/model-selector/pickers.tsxindex 34f0f9b5330..78881384b2e 100644--- a/studio/frontend/src/components/assistant-ui/model-selector/pickers.tsx+++ b/studio/frontend/src/components/assistant-ui/model-selector/pickers.tsx@@ -1,6 +1,16 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";import { Input } from "@/components/ui/input";import { Spinner } from "@/components/ui/spinner";import {@@ -8,7 +18,7 @@ import {TooltipContent,TooltipTrigger,} from "@/components/ui/tooltip";-import { listCachedGguf, listCachedModels, listGgufVariants } from "@/features/chat/api/chat-api";+import { deleteCachedModel, listCachedGguf, listCachedModels, listGgufVariants } from "@/features/chat/api/chat-api";import type { CachedGgufRepo, CachedModelRepo } from "@/features/chat/api/chat-api";import type { GgufVariantDetail } from "@/features/chat/types/api";import { usePlatformStore } from "@/config/env";@@ -24,7 +34,9 @@ import type { VramFitStatus } from "@/lib/vram";import { checkVramFit, estimateLoadingVram } from "@/lib/vram";import { Search01Icon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";+import { Trash2Icon } from "lucide-react";import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";+import { toast } from "sonner";import type {LoraModelOption,ModelOption,@@ -147,11 +159,13 @@ function GgufVariantExpander({onSelect,gpuGb,systemRamGb,+ onDeleteVariant,}: {repoId: string;onSelect: (id: string, meta: ModelSelectorChangeMeta) => void;gpuGb?: number;systemRamGb?: number;+ onDeleteVariant?: (quant: string) => void;}) {const [variants, setVariants] = useState<GgufVariantDetail[] | null>(null);const [defaultVariant, setDefaultVariant] = useState<string | null>(null);@@ -296,38 +310,48 @@ function GgufVariantExpander({const oom = fit === "oom";const tight = fit === "tight";return (- <button- key={v.filename}- type="button"- onClick={() => handleVariantClick(v.quant, v.downloaded, v.size_bytes)}- className={cn(- "flex w-full items-center justify-between gap-2 rounded-md px-2.5 py-1 text-left text-sm transition-colors hover:bg-accent",- )}- >- <span className="min-w-0 flex-1 truncate font-mono text-xs">- {v.quant}- {v.downloaded ? (- <span className="ml-1.5 text-[9px] font-sans font-medium text-green-400">- downloaded- </span>- ) : v.quant === effectiveRecommended ? (- <span className="ml-1.5 text-[9px] font-sans font-medium text-primary/70">- recommended- </span>- ) : null}- </span>- <span className="flex items-center gap-1.5 shrink-0">- {oom && (- <span className="text-[9px] font-medium text-red-400">OOM</span>+ <div key={v.filename} className="flex items-center gap-0.5">+ <button+ type="button"+ onClick={() => handleVariantClick(v.quant, v.downloaded, v.size_bytes)}+ className={cn(+ "flex min-w-0 flex-1 items-center justify-between gap-2 rounded-md px-2.5 py-1 text-left text-sm transition-colors hover:bg-accent",)}- {tight && (- <span className="text-[9px] font-medium text-amber-400">TIGHT</span>- )}- <span className="text-[10px] text-muted-foreground">- {formatBytes(v.size_bytes)}+ >+ <span className="min-w-0 flex-1 truncate font-mono text-xs">+ {v.quant}+ {v.downloaded ? (+ <span className="ml-1.5 text-[9px] font-sans font-medium text-green-400">+ downloaded+ </span>+ ) : v.quant === effectiveRecommended ? (+ <span className="ml-1.5 text-[9px] font-sans font-medium text-primary/70">+ recommended+ </span>+ ) : null}+ </span>+ <span className="flex items-center gap-1.5 shrink-0">+ {oom && (+ <span className="text-[9px] font-medium text-red-400">OOM</span>+ )}+ {tight && (+ <span className="text-[9px] font-medium text-amber-400">TIGHT</span>+ )}+ <span className="text-[10px] text-muted-foreground">+ {formatBytes(v.size_bytes)}+ </span></span>- </span>- </button>+ </button>+ {v.downloaded && onDeleteVariant && (+ <button+ type="button"+ onClick={(e) => { e.stopPropagation(); onDeleteVariant(v.quant); }}+ className="shrink-0 rounded-md p-1 text-muted-foreground/60 transition-colors hover:bg-destructive/10 hover:text-destructive"+ >+ <Trash2Icon className="size-3" />+ </button>+ )}+ </div>);})}</div>@@ -373,12 +397,22 @@ export function HubModelPicker({// Track which GGUF repo is expanded for variant selectionconst [expandedGguf, setExpandedGguf] = useState<string | null>(null);+ // Delete confirmation dialog state+ const [deleteTarget, setDeleteTarget] = useState<string | null>(null);+ const [deleting, setDeleting] = useState(false);+// Cached (already downloaded) repos -- use module-level cache so// re-mounting the popover does not flash an empty "Downloaded" section.const [cachedGguf, setCachedGguf] = useState<CachedGgufRepo[]>(_cachedGgufCache);const [cachedModels, setCachedModels] = useState<CachedModelRepo[]>(_cachedModelsCache);const alreadyCached = _cachedGgufCache.length > 0 || _cachedModelsCache.length > 0;const [cachedReady, setCachedReady] = useState(alreadyCached);++ const refreshCachedLists = useCallback(() => {+ listCachedGguf().then((v) => { _cachedGgufCache = v; setCachedGguf(v); }).catch(() => {});+ listCachedModels().then((v) => { _cachedModelsCache = v; setCachedModels(v); }).catch(() => {});+ }, []);+useEffect(() => {if (alreadyCached) return;let done = 0;@@ -387,6 +421,25 @@ export function HubModelPicker({listCachedModels().then((v) => { _cachedModelsCache = v; setCachedModels(v); }).catch(() => {}).finally(check);}, [alreadyCached]);+ const handleDeleteConfirm = useCallback(async () => {+ if (!deleteTarget) return;+ setDeleting(true);+ try {+ // deleteTarget is "repo_id" or "repo_id::variant"+ const sepIdx = deleteTarget.indexOf("::");+ const repoId = sepIdx >= 0 ? deleteTarget.slice(0, sepIdx) : deleteTarget;+ const variant = sepIdx >= 0 ? deleteTarget.slice(sepIdx + 2) : undefined;+ await deleteCachedModel(repoId, variant);+ toast.success(`Deleted ${variant ? `${repoId} ${variant}` : repoId}`);+ refreshCachedLists();+ } catch (err) {+ toast.error(err instanceof Error ? err.message : "Failed to delete model");+ } finally {+ setDeleting(false);+ setDeleteTarget(null);+ }+ }, [deleteTarget, refreshCachedLists]);+// Deduplicate: don't show downloaded models in the recommended list.// Compare case-insensitively since HF cache lowercases repo IDs.const downloadedSet = useMemo(() => {@@ -533,19 +586,35 @@ export function HubModelPicker({vramStatus={null}/>{expandedGguf === c.repo_id && (- <GgufVariantExpander repoId={c.repo_id} onSelect={onSelect} gpuGb={gpu.available ? gpu.memoryTotalGb : undefined} systemRamGb={gpu.available ? gpu.systemRamAvailableGb : undefined} />+ <GgufVariantExpander+ repoId={c.repo_id}+ onSelect={onSelect}+ gpuGb={gpu.available ? gpu.memoryTotalGb : undefined}+ systemRamGb={gpu.available ? gpu.systemRamAvailableGb : undefined}+ onDeleteVariant={(quant) => setDeleteTarget(`${c.repo_id}::${quant}`)}+ />)}</div>))}{!chatOnly && cachedModels.map((c) => (- <ModelRow- key={c.repo_id}- label={c.repo_id}- meta={formatBytes(c.size_bytes)}- selected={value === c.repo_id}- onClick={() => onSelect(c.repo_id, { source: "hub", isLora: false, isDownloaded: true })}- vramStatus={null}- />+ <div key={c.repo_id} className="flex items-center gap-0.5">+ <div className="min-w-0 flex-1">+ <ModelRow+ label={c.repo_id}+ meta={formatBytes(c.size_bytes)}+ selected={value === c.repo_id}+ onClick={() => onSelect(c.repo_id, { source: "hub", isLora: false, isDownloaded: true })}+ vramStatus={null}+ />+ </div>+ <button+ type="button"+ onClick={(e) => { e.stopPropagation(); setDeleteTarget(c.repo_id); }}+ className="shrink-0 rounded-md p-1.5 text-muted-foreground/60 transition-colors hover:bg-destructive/10 hover:text-destructive"+ >+ <Trash2Icon className="size-3.5" />+ </button>+ </div>))}</>) : null}@@ -627,6 +696,27 @@ export function HubModelPicker({) : null}</div></div>++ <AlertDialog open={deleteTarget !== null} onOpenChange={(open) => { if (!open && !deleting) setDeleteTarget(null); }}>+ <AlertDialogContent size="sm">+ <AlertDialogHeader>+ <AlertDialogTitle>Delete cached model?</AlertDialogTitle>+ <AlertDialogDescription>+ This will remove <span className="font-medium text-foreground">{deleteTarget?.includes("::") ? `${deleteTarget.split("::")[0]} (${deleteTarget.split("::")[1]})` : deleteTarget}</span> from disk. You can re-download it later.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={deleting}>No</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ disabled={deleting}+ onClick={(e) => { e.preventDefault(); handleDeleteConfirm(); }}+ >+ {deleting ? "Deleting..." : "Yes"}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog></div>);}diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex b4162ea36ee..a16d1f3c2ee 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -49,6 +49,7 @@ import {PencilIcon,RefreshCwIcon,SquareIcon,+ TerminalIcon,XIcon,} from "lucide-react";import { type FC, useCallback, useRef, useState } from "react";@@ -84,10 +85,10 @@ export const Thread: FC<{ hideComposer?: boolean; hideWelcome?: boolean }> = ({<ThreadPrimitive.ViewportFooter className="aui-thread-viewport-footer sticky bottom-0 mt-auto flex w-full flex-col gap-4 overflow-visible bg-background pb-4 md:pb-4"><ThreadScrollToBottom />+ <GeneratingSpinner /><AuiIf condition={({ thread }) => !thread.isEmpty}>{!hideComposer && <ComposerAnimated />}</AuiIf>- <GeneratingSpinner /></ThreadPrimitive.ViewportFooter></ThreadPrimitive.Viewport></ThreadPrimitive.Root>@@ -155,8 +156,8 @@ const ThreadWelcome: FC<{ hideComposer?: boolean }> = ({ hideComposer }) => {components={{ Suggestion: SuggestionItem }}/></div>- {!hideComposer && <ComposerAnimated />}<GeneratingSpinner />+ {!hideComposer && <ComposerAnimated />}</div></div></div>@@ -354,13 +355,42 @@ const WebSearchToggle: FC = () => {);};+const CodeToolsToggle: FC = () => {+ const supportsTools = useChatRuntimeStore((s) => s.supportsTools);+ const codeToolsEnabled = useChatRuntimeStore((s) => s.codeToolsEnabled);+ const setCodeToolsEnabled = useChatRuntimeStore(+ (s) => s.setCodeToolsEnabled,+ );++ if (!supportsTools) return null;++ return (+ <button+ type="button"+ onClick={() => setCodeToolsEnabled(!codeToolsEnabled)}+ className={cn(+ "flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium transition-colors",+ codeToolsEnabled+ ? "bg-primary/10 text-primary hover:bg-primary/20"+ : "bg-muted text-muted-foreground hover:bg-muted-foreground/15",+ )}+ aria-label={codeToolsEnabled ? "Disable code execution" : "Enable code execution"}+ >+ <TerminalIcon className="size-3.5" />+ <span>Code</span>+ </button>+ );+};+const ToolStatusDisplay: FC = () => {const toolStatus = useChatRuntimeStore((s) => s.toolStatus);if (!toolStatus) return null;+ const isRunning = toolStatus.startsWith("Running");+ const StatusIcon = isRunning ? TerminalIcon : GlobeIcon;return (<div className="mb-2 flex w-full flex-row items-center gap-2 px-1.5 pt-0.5 pb-1"><div className="flex animate-pulse items-center gap-2 rounded-full border border-primary/20 bg-primary/5 px-3 py-1.5 text-xs text-primary">- <GlobeIcon className="size-3.5" />+ <StatusIcon className="size-3.5" /><span>{toolStatus}</span></div></div>@@ -375,6 +405,7 @@ const ComposerAction: FC = () => {<ComposerAudioUpload /><ReasoningToggle /><WebSearchToggle />+ <CodeToolsToggle /></div><div className="flex items-center gap-1"><ComposerPrimitive.If dictation={false}>diff --git a/studio/frontend/src/components/ui/sonner.tsx b/studio/frontend/src/components/ui/sonner.tsxindex 11dca18213a..dff9e09cb56 100644--- a/studio/frontend/src/components/ui/sonner.tsx+++ b/studio/frontend/src/components/ui/sonner.tsx@@ -68,7 +68,8 @@ const Toaster = ({ ...props }: ToasterProps) => {toastOptions={{classNames: {toast: "cn-toast",- closeButton: "!top-1.5 !translate-y-0",+ description: "!text-muted-foreground",+ closeButton: "!top-3 !right-3 !translate-y-0",},}}{...props}diff --git a/studio/frontend/src/components/ui/tooltip.tsx b/studio/frontend/src/components/ui/tooltip.tsxindex f58d9f53094..b644c6ef326 100644--- a/studio/frontend/src/components/ui/tooltip.tsx+++ b/studio/frontend/src/components/ui/tooltip.tsx@@ -2,10 +2,14 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { Tooltip as TooltipPrimitive } from "radix-ui";+import { createContext, useCallback, useContext, useState } from "react";import type * as React from "react";import { cn } from "@/lib/utils";+type ToggleFn = () => void;+const TooltipToggleCtx = createContext<ToggleFn | null>(null);+function TooltipProvider({delayDuration = 400,...props@@ -20,19 +24,61 @@ function TooltipProvider({}function Tooltip({+ open: controlledOpen,+ onOpenChange: controlledOnOpenChange,...props}: React.ComponentProps<typeof TooltipPrimitive.Root>) {+ const isControlled = controlledOpen !== undefined;+ const [clickOpen, setClickOpen] = useState(false);++ const onOpenChange = useCallback(+ (nextOpen: boolean) => {+ if (!nextOpen) setClickOpen(false);+ controlledOnOpenChange?.(nextOpen);+ },+ [controlledOnOpenChange],+ );++ const toggle = useCallback(() => {+ setClickOpen((prev) => !prev);+ }, []);+return (<TooltipProvider>- <TooltipPrimitive.Root data-slot="tooltip" {...props} />+ <TooltipToggleCtx.Provider value={toggle}>+ <TooltipPrimitive.Root+ data-slot="tooltip"+ open={isControlled ? controlledOpen : clickOpen || undefined}+ onOpenChange={onOpenChange}+ {...props}+ />+ </TooltipToggleCtx.Provider></TooltipProvider>);}function TooltipTrigger({+ onClick,...props}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {- return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;+ const toggle = useContext(TooltipToggleCtx);++ const handleClick = useCallback(+ (e: React.MouseEvent<HTMLButtonElement>) => {+ e.preventDefault();+ toggle?.();+ onClick?.(e);+ },+ [toggle, onClick],+ );++ return (+ <TooltipPrimitive.Trigger+ data-slot="tooltip-trigger"+ onClick={handleClick}+ {...props}+ />+ );}function TooltipContent({diff --git a/studio/frontend/src/config/training.ts b/studio/frontend/src/config/training.tsindex ef40cbf2a4a..677e91fdd7c 100644--- a/studio/frontend/src/config/training.ts+++ b/studio/frontend/src/config/training.ts@@ -64,7 +64,7 @@ export const MODEL_TYPES: ReadonlyArray<{},];-export const CONTEXT_LENGTHS = [512, 1024, 2048, 4096, 8192, 16384, 32768];+export const CONTEXT_LENGTHS = [512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144];export const TARGET_MODULES = ["q_proj",@@ -104,7 +104,7 @@ export const DEFAULT_HYPERPARAMS = {gradientAccumulation: 8,weightDecay: 0.01,warmupSteps: 5,- maxSteps: 0,+ maxSteps: 60,saveSteps: 0,evalSteps: 0.00,packing: false,diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 29b5f60b64c..70ee13e08ae 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -176,6 +176,11 @@ async function resolveUseAdapter(if (!thread?.pairId) {return undefined;}+ // model1/model2 threads don't use the adapter toggle — each side+ // loads its own model via /api/inference/load before generation.+ if (thread.modelType === "model1" || thread.modelType === "model2") {+ return undefined;+ }return thread.modelType === "lora";} catch {return undefined;@@ -256,6 +261,7 @@ async function autoLoadSmallestModel(): Promise<boolean> {reasoningEnabled: loadResp.supports_reasoning ?? false,supportsTools: loadResp.supports_tools ?? false,toolsEnabled: false,+ codeToolsEnabled: false,defaultChatTemplate: loadResp.chat_template ?? null,chatTemplateOverride: null,});@@ -379,6 +385,7 @@ export function createOpenAIStreamAdapter(): ChatModelAdapter {const {supportsTools,toolsEnabled,+ codeToolsEnabled,} = runtime;const outboundMessages = messages@@ -429,6 +436,7 @@ export function createOpenAIStreamAdapter(): ChatModelAdapter {top_k: params.topK,min_p: params.minP,repetition_penalty: params.repetitionPenalty,+ presence_penalty: params.presencePenalty,...(useAdapter === undefined ? {} : { use_adapter: useAdapter }),},abortSignal,@@ -508,11 +516,20 @@ export function createOpenAIStreamAdapter(): ChatModelAdapter {top_k: params.topK,min_p: params.minP,repetition_penalty: params.repetitionPenalty,+ presence_penalty: params.presencePenalty,image_base64: imageBase64,audio_base64: audioBase64,...(useAdapter === undefined ? {} : { use_adapter: useAdapter }),...(supportsReasoning ? { enable_thinking: reasoningEnabled } : {}),- ...(supportsTools && toolsEnabled ? { enable_tools: true } : {}),+ ...(supportsTools && (toolsEnabled || codeToolsEnabled)+ ? {+ enable_tools: true,+ enabled_tools: [+ ...(toolsEnabled ? ["web_search"] : []),+ ...(codeToolsEnabled ? ["python", "terminal"] : []),+ ],+ }+ : {}),},abortSignal,);diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex effba93ef8d..d219a380af1 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -142,6 +142,17 @@ export async function listCachedModels(): Promise<CachedModelRepo[]> {return data.cached;}+export async function deleteCachedModel(repoId: string, variant?: string): Promise<void> {+ const payload: Record<string, string> = { repo_id: repoId };+ if (variant) payload.variant = variant;+ const response = await authFetch("/api/models/delete-cached", {+ method: "DELETE",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ });+ await parseJsonOrThrow<unknown>(response);+}+export async function listGgufVariants(repoId: string,hfToken?: string,diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex 8c7f1de6bcf..83cbf07b1d2 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -128,8 +128,39 @@ const SingleContent = memo(function SingleContent({);});+type CompareModelSelection = {+ id: string;+ isLora: boolean;+ ggufVariant?: string;+};++/**+ * Detect if this is a LoRA base-vs-fine-tuned compare.+ * Returns true when the loaded checkpoint is a LoRA — in that case+ * we use the fast simultaneous base/lora adapter-toggle path.+ */+function useIsLoraCompare(): boolean {+ return useChatRuntimeStore((s) => {+ const cp = s.params.checkpoint;+ return cp ? s.loras.some((l) => l.id === cp) : false;+ });+}+const CompareContent = memo(function CompareContent({pairId,+ models,+ loraModels,+}: { pairId: string; models: ModelOption[]; loraModels: LoraModelOption[] }): ReactElement {+ const isLoraCompare = useIsLoraCompare();++ return isLoraCompare+ ? <LoraCompareContent pairId={pairId} />+ : <GeneralCompareContent pairId={pairId} models={models} loraModels={loraModels} />;+});++/** Fast path: same model, adapter on/off, simultaneous generation. */+const LoraCompareContent = memo(function LoraCompareContent({+ pairId,}: { pairId: string }): ReactElement {const handlesRef = useRef<Record<string, CompareHandle>>({});const [baseThreadId, setBaseThreadId] = useState<string>();@@ -142,15 +173,11 @@ const CompareContent = memo(function CompareContent({.equals(pairId).toArray().then((threads) => {- if (!isActive) {- return;- }+ if (!isActive) return;setBaseThreadId(threads.find((t) => t.modelType === "base")?.id);setLoraThreadId(threads.find((t) => t.modelType === "lora")?.id);});- return () => {- isActive = false;- };+ return () => { isActive = false; };}, [pairId]);return (@@ -167,11 +194,7 @@ const CompareContent = memo(function CompareContent({</span></div><div className="min-h-0 flex-1">- <ChatRuntimeProvider- modelType="base"- pairId={pairId}- initialThreadId={baseThreadId}- >+ <ChatRuntimeProvider modelType="base" pairId={pairId} initialThreadId={baseThreadId}><RegisterCompareHandle name="base" /><Thread hideComposer={true} hideWelcome={true} /></ChatRuntimeProvider>@@ -183,20 +206,121 @@ const CompareContent = memo(function CompareContent({Fine-tuned (LoRA)</span></div>+ <div className="min-h-0 flex-1">+ <ChatRuntimeProvider modelType="lora" pairId={pairId} initialThreadId={loraThreadId}>+ <RegisterCompareHandle name="lora" />+ <Thread hideComposer={true} hideWelcome={true} />+ </ChatRuntimeProvider>+ </div>+ </div>+ </div>+ <div className="mx-auto w-full max-w-4xl px-4 py-4">+ <SharedComposer handlesRef={handlesRef} />+ </div>+ </div>+ </CompareHandlesProvider>+ );+});++/** General path: any two models, sequential load → generate. */+const GeneralCompareContent = memo(function GeneralCompareContent({+ pairId,+ models,+ loraModels,+}: { pairId: string; models: ModelOption[]; loraModels: LoraModelOption[] }): ReactElement {+ const handlesRef = useRef<Record<string, CompareHandle>>({});+ const [model1ThreadId, setModel1ThreadId] = useState<string>();+ const [model2ThreadId, setModel2ThreadId] = useState<string>();++ const globalCheckpoint = useChatRuntimeStore((s) => s.params.checkpoint);+ const globalGgufVariant = useChatRuntimeStore((s) => s.activeGgufVariant);+ const [model1, setModel1] = useState<CompareModelSelection>({+ id: globalCheckpoint || "",+ isLora: false,+ ggufVariant: globalGgufVariant ?? undefined,+ });+ const [model2, setModel2] = useState<CompareModelSelection>({ id: "", isLora: false });++ useEffect(() => {+ let isActive = true;+ db.threads+ .where("pairId")+ .equals(pairId)+ .toArray()+ .then((threads) => {+ if (!isActive) return;+ setModel1ThreadId(+ threads.find((t) => t.modelType === "model1" || t.modelType === "base")?.id,+ );+ setModel2ThreadId(+ threads.find((t) => t.modelType === "model2" || t.modelType === "lora")?.id,+ );+ });+ return () => { isActive = false; };+ }, [pairId]);++ return (+ <CompareHandlesProvider handlesRef={handlesRef}>+ <div className="flex min-h-0 flex-1 flex-col">+ <div+ data-tour="chat-compare-view"+ className="grid min-h-0 flex-1 grid-cols-1 px-0 md:grid-cols-2"+ >+ <div className="flex min-h-0 flex-col">+ <div className="flex items-center gap-2 px-3 py-1.5">+ <span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">+ Model 1+ </span>+ <ModelSelector+ models={models}+ loraModels={loraModels}+ value={model1.id}+ onValueChange={(id, meta) => setModel1({ id, isLora: meta.isLora, ggufVariant: meta.ggufVariant })}+ variant="ghost"+ size="sm"+ className="max-w-[50%]"+ />+ </div>+ <div className="min-h-0 flex-1">+ <ChatRuntimeProvider+ modelType="model1"+ pairId={pairId}+ initialThreadId={model1ThreadId}+ >+ <RegisterCompareHandle name="model1" />+ <Thread hideComposer={true} hideWelcome={true} />+ </ChatRuntimeProvider>+ </div>+ </div>+ <div className="flex min-h-0 flex-col border-t border-border/60 md:border-t-0 md:border-l">+ <div className="flex items-center gap-2 px-3 py-1.5 md:justify-end">+ <span className="text-[10px] font-semibold uppercase tracking-wider text-primary">+ Model 2+ </span>+ <ModelSelector+ models={models}+ loraModels={loraModels}+ value={model2.id}+ onValueChange={(id, meta) => setModel2({ id, isLora: meta.isLora, ggufVariant: meta.ggufVariant })}+ variant="ghost"+ size="sm"+ className="max-w-[50%]"+ />+ </div><div className="min-h-0 flex-1"><ChatRuntimeProvider- modelType="lora"+ modelType="model2"pairId={pairId}- initialThreadId={loraThreadId}+ initialThreadId={model2ThreadId}>- <RegisterCompareHandle name="lora" />+ <RegisterCompareHandle name="model2" /><Thread hideComposer={true} hideWelcome={true} /></ChatRuntimeProvider></div></div></div><div className="mx-auto w-full max-w-4xl px-4 py-4">- <SharedComposer handlesRef={handlesRef} />+ <SharedComposer handlesRef={handlesRef} model1={model1} model2={model2} /></div></div></CompareHandlesProvider>@@ -323,10 +447,8 @@ export function ChatPage(): ReactElement {selectModelRef.current = selectModel;}, [refresh, selectModel]);const canCompare = useMemo(() => {- const selected = inferenceParams.checkpoint;- if (!selected) return false;- return lorasFromStore.some((lora) => lora.id === selected);- }, [inferenceParams.checkpoint, lorasFromStore]);+ return Boolean(inferenceParams.checkpoint);+ }, [inferenceParams.checkpoint]);const handleCheckpointChange = useCallback((value: string, meta?: { isLora: boolean; ggufVariant?: string; isDownloaded?: boolean; expectedBytes?: number }) => {@@ -640,7 +762,7 @@ export function ChatPage(): ReactElement {newThreadNonce={view.newThreadNonce}/>) : (- <CompareContent key={view.pairId} pairId={view.pairId} />+ <CompareContent key={view.pairId} pairId={view.pairId} models={models} loraModels={loraModels} />)}</div>diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsxindex a7969b6c7b0..fe30a3412f0 100644--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx@@ -337,6 +337,15 @@ export function ChatSettingsPanel({onChange={set("repetitionPenalty")}displayValue={params.repetitionPenalty === 1 ? "Off" : undefined}/>+ <ParamSlider+ label="Presence Penalty"+ value={params.presencePenalty}+ min={0}+ max={2}+ step={0.1}+ onChange={set("presencePenalty")}+ displayValue={params.presencePenalty === 0 ? "Off" : undefined}+ />{!isGguf && (<ParamSliderlabel="Max Seq Length"diff --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 545b7711ed2..6927b1871f3 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@@ -147,6 +147,8 @@ function mergeRecommendedInference(topP: toFiniteNumber(inference?.top_p) ?? current.topP,topK: toFiniteNumber(inference?.top_k) ?? current.topK,minP: toFiniteNumber(inference?.min_p) ?? current.minP,+ presencePenalty:+ toFiniteNumber(inference?.presence_penalty) ?? current.presencePenalty,trustRemoteCode:typeof inference?.trust_remote_code === "boolean"? inference.trust_remote_code@@ -226,6 +228,36 @@ export function useChatModelRuntime() {if (statusRes.active_model) {setCheckpoint(statusRes.active_model, statusRes.gguf_variant);++ // Apply inference defaults on reconnect (page refresh with model already loaded)+ if (statusRes.inference) {+ const currentParams = useChatRuntimeStore.getState().params;+ setParams(+ mergeRecommendedInference(currentParams, statusRes as any, statusRes.active_model),+ );+ }++ // Restore reasoning/tools support flags and context length+ const supportsReasoning = statusRes.supports_reasoning ?? false;+ const supportsTools = statusRes.supports_tools ?? false;+ useChatRuntimeStore.setState({+ supportsReasoning,+ supportsTools,+ ggufContextLength: statusRes.is_gguf ? (statusRes.context_length ?? null) : null,+ });++ // Set reasoning default for Qwen3.5 small models+ if (supportsReasoning) {+ let reasoningDefault = true;+ const mid = statusRes.active_model.toLowerCase();+ if (mid.includes("qwen3.5")) {+ const sizeMatch = mid.match(/(\d+\.?\d*)\s*b/);+ if (sizeMatch && parseFloat(sizeMatch[1]) < 9) {+ reasoningDefault = false;+ }+ }+ useChatRuntimeStore.getState().setReasoningEnabled(reasoningDefault);+ }}} catch (error) {const message =@@ -235,7 +267,7 @@ export function useChatModelRuntime() {description: message,});}- }, [setCheckpoint, setLoras, setModels, setModelsError]);+ }, [setCheckpoint, setLoras, setModels, setModelsError, setParams]);const cancelLoading = useCallback(() => {const model = loadingModelRef.current;@@ -367,7 +399,7 @@ export function useChatModelRuntime() {const mid = modelId.toLowerCase();if (mid.includes("qwen3.5")) {const sizeMatch = mid.match(/(\d+\.?\d*)\s*b/);- if (sizeMatch && parseFloat(sizeMatch[1]) <= 2) {+ if (sizeMatch && parseFloat(sizeMatch[1]) < 9) {reasoningDefault = false;}}diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex 7985f4970e3..b4b7b6dc7b7 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -284,7 +284,7 @@ async function generateTitleWithModel(payload: {temperature: 0.2,top_p: 0.9,max_tokens: 24,- top_k: 40,+ top_k: 20,repetition_penalty: 1.0,messages: [{diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex 3eb1f699d28..c2ca25a6586 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -6,7 +6,9 @@ import { Button } from "@/components/ui/button";import { AUDIO_ACCEPT, MAX_AUDIO_SIZE, fileToBase64 } from "@/lib/audio-utils";import { useAui } from "@assistant-ui/react";import { cn } from "@/lib/utils";-import { ArrowUpIcon, GlobeIcon, HeadphonesIcon, LightbulbIcon, LightbulbOffIcon, MicIcon, PlusIcon, SquareIcon, XIcon } from "lucide-react";+import { ArrowUpIcon, GlobeIcon, HeadphonesIcon, LightbulbIcon, LightbulbOffIcon, MicIcon, PlusIcon, SquareIcon, TerminalIcon, XIcon } from "lucide-react";+import { toast } from "sonner";+import { loadModel } from "./api/chat-api";import { useChatRuntimeStore } from "./stores/chat-runtime-store";import {type KeyboardEvent,@@ -28,8 +30,14 @@ export type CompareMessagePart =export interface CompareHandle {append: (content: CompareMessagePart[]) => void;+ /** Append a user message without triggering generation. */+ appendMessage: (content: CompareMessagePart[]) => void;+ /** Trigger generation on the current thread (after appendMessage). */+ startRun: () => void;cancel: () => void;isRunning: () => boolean;+ /** Returns a promise that resolves when the current or next run finishes. */+ waitForRunEnd: () => Promise<void>;}const IMAGE_ACCEPT = "image/jpeg,image/png,image/webp,image/gif";@@ -139,8 +147,27 @@ export function RegisterCompareHandle({// fixes occasional reorder on reload.append: (content) =>aui.thread().append({ role: "user", content, createdAt: new Date() } as never),+ appendMessage: (content) =>+ aui.thread().append({ role: "user", content, createdAt: new Date(), startRun: false } as never),+ startRun: () => {+ const msgs = aui.thread().getState().messages;+ const lastId = msgs.length > 0 ? msgs[msgs.length - 1].id : null;+ aui.thread().startRun({ parentId: lastId });+ },cancel: () => aui.thread().cancelRun(),isRunning: () => aui.thread().getState().isRunning,+ waitForRunEnd: () =>+ new Promise<void>((resolve) => {+ let wasRunning = false;+ const unsub = useChatRuntimeStore.subscribe((state) => {+ const anyRunning = Object.keys(state.runningByThreadId).length > 0;+ if (anyRunning) wasRunning = true;+ if (wasRunning && !anyRunning) {+ unsub();+ resolve();+ }+ });+ }),};return () => {delete currentHandles[name];@@ -181,13 +208,24 @@ function PendingImageThumb({);}+type CompareModelSelection = {+ id: string;+ isLora: boolean;+ ggufVariant?: string;+};+export function SharedComposer({handlesRef,+ model1,+ model2,}: {handlesRef: CompareHandles;+ model1?: CompareModelSelection;+ model2?: CompareModelSelection;}): ReactElement {const [text, setText] = useState("");const [running, setRunning] = useState(false);+ const [comparing, setComparing] = useState(false);const [pendingImages, setPendingImages] = useState<PendingImage[]>([]);const [pendingAudio, setPendingAudio] = useState<{ name: string; base64: string } | null>(null);const [dragging, setDragging] = useState(false);@@ -205,6 +243,8 @@ export function SharedComposer({const supportsTools = useChatRuntimeStore((s) => s.supportsTools);const toolsEnabled = useChatRuntimeStore((s) => s.toolsEnabled);const setToolsEnabled = useChatRuntimeStore((s) => s.setToolsEnabled);+ const codeToolsEnabled = useChatRuntimeStore((s) => s.codeToolsEnabled);+ const setCodeToolsEnabled = useChatRuntimeStore((s) => s.setCodeToolsEnabled);const setPendingAudioStore = useChatRuntimeStore((s) => s.setPendingAudio);const clearPendingAudioStore = useChatRuntimeStore((s) => s.clearPendingAudio);@@ -268,14 +308,98 @@ export function SharedComposer({}if (content.length === 0) return;- for (const handle of Object.values(handlesRef.current)) {- handle.append(content);- }setText("");setPendingImages([]);setPendingAudio(null);clearPendingAudioStore();textareaRef.current?.focus();++ // Generalized compare: load each model before dispatching to its side+ const hasCompareHandles = Boolean(handlesRef.current["model1"] || handlesRef.current["model2"]);+ const isGeneralizedCompare = hasCompareHandles && Boolean(model1?.id || model2?.id);+ if (isGeneralizedCompare) {+ const store = useChatRuntimeStore.getState();+ const maxSeqLength = store.params.maxSeqLength;+ const trustRemoteCode = store.params.trustRemoteCode ?? false;+ const chatTemplateOverride = store.chatTemplateOverride;++ function modelDisplayName(id: string): string {+ const parts = id.split("/");+ return parts[parts.length - 1] || id;+ }++ // Helper: load a model and update store checkpoint+ async function ensureModelLoaded(sel: CompareModelSelection): Promise<string> {+ const resp = await loadModel({+ model_path: sel.id,+ hf_token: null,+ max_seq_length: maxSeqLength,+ load_in_4bit: true,+ is_lora: sel.isLora,+ gguf_variant: sel.ggufVariant ?? null,+ trust_remote_code: trustRemoteCode,+ chat_template_override: chatTemplateOverride,+ });+ useChatRuntimeStore.getState().setCheckpoint(+ resp.model,+ resp.is_gguf ? (sel.ggufVariant ?? undefined) : null,+ );+ return resp.status;+ }++ const handle1 = handlesRef.current["model1"];+ const handle2 = handlesRef.current["model2"];++ // Show user messages immediately on both sides+ if (handle1) handle1.appendMessage(content);+ if (handle2) handle2.appendMessage(content);++ const name1 = model1?.id ? modelDisplayName(model1.id) : "";+ const name2 = model2?.id ? modelDisplayName(model2.id) : "";+ const toastId = toast("Comparing models…", { duration: Infinity });++ setComparing(true);+ try {+ // Side 1: load → generate → wait+ if (handle1 && model1?.id) {+ toast("Loading Model 1…", { id: toastId, description: name1, duration: Infinity });+ await ensureModelLoaded(model1);+ toast("Generating with Model 1…", { id: toastId, description: name1, duration: Infinity });+ const done = handle1.waitForRunEnd();+ handle1.startRun();+ await done;+ }++ // Side 2: load → generate → wait+ if (handle2 && model2?.id) {+ const needsLoad = model2.id.toLowerCase() !== (model1?.id || "").toLowerCase()+ || (model2.ggufVariant ?? "") !== (model1?.ggufVariant ?? "");+ if (needsLoad) {+ toast("Loading Model 2…", { id: toastId, description: name2, duration: Infinity });+ }+ await ensureModelLoaded(model2);+ toast("Generating with Model 2…", { id: toastId, description: name2, duration: Infinity });+ const done = handle2.waitForRunEnd();+ handle2.startRun();+ await done;+ }++ toast.success("Compare complete", { id: toastId, duration: 2000 });+ } catch (err) {+ toast.error("Compare failed", {+ id: toastId,+ description: err instanceof Error ? err.message : "Unknown error",+ duration: 4000,+ });+ } finally {+ setComparing(false);+ }+ } else {+ // Original behavior: fire all handles simultaneously+ for (const handle of Object.values(handlesRef.current)) {+ handle.append(content);+ }+ }}function stop() {@@ -285,16 +409,18 @@ export function SharedComposer({}}+ const busy = running || comparing;+function onKeyDown(e: KeyboardEvent) {if (e.key === "Enter" && !e.shiftKey) {e.preventDefault();- if (!running) {+ if (!busy) {send();}}}- const canSend = (text.trim().length > 0 || pendingImages.length > 0 || pendingAudio !== null) && !running;+ const canSend = (text.trim().length > 0 || pendingImages.length > 0 || pendingAudio !== null) && !busy;return (<div@@ -410,7 +536,7 @@ export function SharedComposer({}}}className={cn(- "flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium transition-colors",+ "flex items-center gap-0.5 rounded-full px-2 py-0.5 text-xs font-medium transition-colors",reasoningEnabled? "bg-primary/10 text-primary hover:bg-primary/20": "bg-muted text-muted-foreground hover:bg-muted-foreground/15",@@ -418,9 +544,9 @@ export function SharedComposer({aria-label={reasoningEnabled ? "Disable thinking" : "Enable thinking"}>{reasoningEnabled ? (- <LightbulbIcon className="size-3.5" />+ <LightbulbIcon className="size-3" />) : (- <LightbulbOffIcon className="size-3.5" />+ <LightbulbOffIcon className="size-3" />)}<span>Think</span></button>@@ -441,6 +567,22 @@ export function SharedComposer({<span>Search</span></button>)}+ {supportsTools && (+ <button+ type="button"+ onClick={() => setCodeToolsEnabled(!codeToolsEnabled)}+ className={cn(+ "flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium transition-colors",+ codeToolsEnabled+ ? "bg-primary/10 text-primary hover:bg-primary/20"+ : "bg-muted text-muted-foreground hover:bg-muted-foreground/15",+ )}+ aria-label={codeToolsEnabled ? "Disable code execution" : "Enable code execution"}+ >+ <TerminalIcon className="size-3.5" />+ <span>Code</span>+ </button>+ )}</div><div className="flex items-center gap-1">{dictationSupported && (@@ -472,7 +614,7 @@ export function SharedComposer({)}</>)}- {running ? (+ {busy ? (<Buttontype="button"variant="default"diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex 57157057255..43736d6257e 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -48,6 +48,7 @@ type ChatRuntimeStore = {reasoningEnabled: boolean;supportsTools: boolean;toolsEnabled: boolean;+ codeToolsEnabled: boolean;toolStatus: string | null;generatingStatus: string | null;kvCacheDtype: string | null;@@ -69,6 +70,7 @@ type ChatRuntimeStore = {clearCheckpoint: () => void;setReasoningEnabled: (enabled: boolean) => void;setToolsEnabled: (enabled: boolean) => void;+ setCodeToolsEnabled: (enabled: boolean) => void;setToolStatus: (status: string | null) => void;setGeneratingStatus: (status: string | null) => void;setKvCacheDtype: (dtype: string | null) => void;@@ -90,6 +92,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set) => ({reasoningEnabled: true,supportsTools: false,toolsEnabled: false,+ codeToolsEnabled: false,toolStatus: null,generatingStatus: null,kvCacheDtype: null,@@ -140,6 +143,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set) => ({reasoningEnabled: true,supportsTools: false,toolsEnabled: false,+ codeToolsEnabled: false,toolStatus: null,kvCacheDtype: null,defaultChatTemplate: null,@@ -147,6 +151,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set) => ({})),setReasoningEnabled: (reasoningEnabled) => set({ reasoningEnabled }),setToolsEnabled: (toolsEnabled) => set({ toolsEnabled }),+ setCodeToolsEnabled: (codeToolsEnabled) => set({ codeToolsEnabled }),setToolStatus: (toolStatus) => set({ toolStatus }),setGeneratingStatus: (generatingStatus) => set({ generatingStatus }),setKvCacheDtype: (kvCacheDtype) => set({ kvCacheDtype }),diff --git a/studio/frontend/src/features/chat/thread-sidebar.tsx b/studio/frontend/src/features/chat/thread-sidebar.tsxindex 0f99e03d185..751f04c1712 100644--- a/studio/frontend/src/features/chat/thread-sidebar.tsx+++ b/studio/frontend/src/features/chat/thread-sidebar.tsx@@ -47,7 +47,7 @@ function groupThreads(threads: ThreadRecord[]): SidebarItem[] {title: t.title,createdAt: t.createdAt,});- } else if (t.modelType === "base") {+ } else if (!t.pairId) {items.push({type: "single",id: t.id,diff --git a/studio/frontend/src/features/chat/tour/steps.tsx b/studio/frontend/src/features/chat/tour/steps.tsxindex 1152ba1faf5..3c43d9fed43 100644--- a/studio/frontend/src/features/chat/tour/steps.tsx+++ b/studio/frontend/src/features/chat/tour/steps.tsx@@ -71,8 +71,8 @@ export function buildChatTourSteps({title: "Compare mode",body: (<>- When a LoRA is selected, compare base vs fine-tuned side-by-side.- This is the fastest way to sanity-check your training.+ Compare any two models side-by-side.+ Pick a different model for each side and see how they respond to the same prompt.</>),onEnter: openSidebar,diff --git a/studio/frontend/src/features/chat/types.ts b/studio/frontend/src/features/chat/types.tsindex 65fba4fcd28..11e53d76d3a 100644--- a/studio/frontend/src/features/chat/types.ts+++ b/studio/frontend/src/features/chat/types.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-export type ModelType = "base" | "lora";+export type ModelType = "base" | "lora" | "model1" | "model2";export type ChatView =| { mode: "single"; threadId?: string; newThreadNonce?: string }diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex d40b5fa853d..a7be85766eb 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -82,6 +82,7 @@ export interface LoadModelResponse {top_p?: number;top_k?: number;min_p?: number;+ presence_penalty?: number;trust_remote_code?: boolean;};context_length?: number | null;@@ -105,6 +106,17 @@ export interface InferenceStatusResponse {has_audio_input?: boolean;loading: string[];loaded: string[];+ inference?: {+ temperature?: number;+ top_p?: number;+ top_k?: number;+ min_p?: number;+ presence_penalty?: number;+ trust_remote_code?: boolean;+ };+ supports_reasoning?: boolean;+ supports_tools?: boolean;+ context_length?: number | null;}export interface AudioGenerationResponse {@@ -138,6 +150,7 @@ export interface OpenAIChatCompletionsRequest {top_k: number;min_p: number;repetition_penalty: number;+ presence_penalty: number;image_base64?: string;audio_base64?: string;use_adapter?: boolean | string | null;diff --git a/studio/frontend/src/features/chat/types/runtime.ts b/studio/frontend/src/features/chat/types/runtime.tsindex a40ec7ceb8a..2967584653c 100644--- a/studio/frontend/src/features/chat/types/runtime.ts+++ b/studio/frontend/src/features/chat/types/runtime.ts@@ -7,6 +7,7 @@ export interface InferenceParams {topK: number;minP: number;repetitionPenalty: number;+ presencePenalty: number;maxSeqLength: number;maxTokens: number;systemPrompt: string;@@ -16,11 +17,12 @@ export interface InferenceParams {}export const DEFAULT_INFERENCE_PARAMS: InferenceParams = {- temperature: 0.7,- topP: 0.9,- topK: 50,+ temperature: 0.6,+ topP: 0.95,+ topK: 20,minP: 0.01,repetitionPenalty: 1.0,+ presencePenalty: 0.0,maxSeqLength: 4096,maxTokens: 8192,systemPrompt: "",diff --git a/studio/frontend/src/features/onboarding/components/splash-screen.tsx b/studio/frontend/src/features/onboarding/components/splash-screen.tsxindex a1e1cfa5dda..7f5e3619c99 100644--- a/studio/frontend/src/features/onboarding/components/splash-screen.tsx+++ b/studio/frontend/src/features/onboarding/components/splash-screen.tsx@@ -48,7 +48,7 @@ export function SplashScreen({<h1 className="text-2xl font-semibold tracking-tight">Unsloth Studio</h1>- <p className="text-sm text-muted-foreground">Fine-tune LLMs faster</p>+ <p className="text-sm text-muted-foreground">Train and run LLMs locally</p></motion.div>{/* Buttons */}diff --git a/studio/frontend/src/features/onboarding/components/steps/dataset-step.tsx b/studio/frontend/src/features/onboarding/components/steps/dataset-step.tsxindex d93de501f17..9b0456f67ae 100644--- a/studio/frontend/src/features/onboarding/components/steps/dataset-step.tsx+++ b/studio/frontend/src/features/onboarding/components/steps/dataset-step.tsx@@ -51,6 +51,7 @@ import {InformationCircleIcon,Key01Icon,Search01Icon,+ SparklesIcon,Upload04Icon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";@@ -391,6 +392,12 @@ export function DatasetStep() {<SelectContent>{FORMAT_OPTIONS.map((opt) => (<SelectItem key={opt.value} value={opt.value}>+ {opt.value === "auto" && (+ <HugeiconsIcon+ icon={SparklesIcon}+ className="mr-1.5 inline size-3.5 align-text-bottom"+ />+ )}{opt.label}</SelectItem>))}diff --git a/studio/frontend/src/features/onboarding/components/steps/hyperparameters-step.tsx b/studio/frontend/src/features/onboarding/components/steps/hyperparameters-step.tsxindex 0a04a1e71fe..337023ad336 100644--- a/studio/frontend/src/features/onboarding/components/steps/hyperparameters-step.tsx+++ b/studio/frontend/src/features/onboarding/components/steps/hyperparameters-step.tsx@@ -7,7 +7,6 @@ import {FieldLegend,FieldSet,} from "@/components/ui/field";-import { Input } from "@/components/ui/input";import {Select,SelectContent,@@ -26,8 +25,40 @@ import { CONTEXT_LENGTHS } from "@/config/training";import { useMaxStepsEpochsToggle, useTrainingConfigStore } from "@/features/training";import { InformationCircleIcon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";+import { useMemo } from "react";import { useShallow } from "zustand/react/shallow";+/** Format a number in scientific notation like 2e-4, 5e-3, etc. */+function formatLR(value: number): string {+ if (value <= 0) return "0";+ const exp = Math.floor(Math.log10(value));+ const mantissa = value / 10 ** exp;+ const rounded = Math.round(mantissa * 10) / 10;+ if (rounded === 10) return `1e${exp + 1}`;+ if (rounded === Math.round(rounded)) return `${Math.round(rounded)}e${exp}`;+ return `${rounded}e${exp}`;+}++/**+ * Step learning rate up in a scientific-notation-friendly sequence:+ * 1e-4 -> 2e-4 -> 3e-4 -> ... -> 9e-4 -> 1e-3 -> 2e-3 -> ...+ */+function stepLR(value: number, direction: 1 | -1): number {+ if (value <= 0) return 1e-5;+ const exp = Math.floor(Math.log10(value) + 1e-9);+ const mantissa = Math.round(value / 10 ** exp);+ let newMantissa = mantissa + direction;+ let newExp = exp;+ if (newMantissa > 9) {+ newMantissa = 1;+ newExp = exp + 1;+ } else if (newMantissa < 1) {+ newMantissa = 9;+ newExp = exp - 1;+ }+ return newMantissa * 10 ** newExp;+}+export function HyperparametersStep() {const {trainingMethod,@@ -47,6 +78,7 @@ export function HyperparametersStep() {setLoraAlpha,loraDropout,setLoraDropout,+ maxPositionEmbeddings,} = useTrainingConfigStore(useShallow((s) => ({trainingMethod: s.trainingMethod,@@ -66,6 +98,7 @@ export function HyperparametersStep() {setLoraAlpha: s.setLoraAlpha,loraDropout: s.loraDropout,setLoraDropout: s.setLoraDropout,+ maxPositionEmbeddings: s.maxPositionEmbeddings,})),);@@ -83,10 +116,18 @@ export function HyperparametersStep() {const maxStepsSliderMax = Math.max(500, maxSteps, 30);const epochsSliderMax = Math.max(10, epochs, 1);+ // Use model's max_position_embeddings to cap context length options.+ // Fall back to 65536 (64K) if not available.+ const maxCtx = maxPositionEmbeddings ?? 65536;+ const contextLengthOptions = useMemo(+ () => CONTEXT_LENGTHS.filter((len) => len <= maxCtx),+ [maxCtx],+ );+return (<FieldGroup><FieldSet>- <FieldLegend variant="label">Training</FieldLegend>+ <FieldLegend variant="label">Choose your training parameters</FieldLegend><div className="flex flex-col gap-4"><divkey={useEpochs ? "epochs" : "steps"}@@ -205,7 +246,7 @@ export function HyperparametersStep() {<SelectValue /></SelectTrigger><SelectContent>- {CONTEXT_LENGTHS.map((len) => (+ {contextLengthOptions.map((len) => (<SelectItem key={len} value={String(len)}>{len.toLocaleString()}</SelectItem>@@ -242,13 +283,25 @@ export function HyperparametersStep() {</TooltipContent></Tooltip></FieldLabel>- <Input- type="number"- step="0.00001"- value={learningRate}- onChange={(e) => setLearningRate(Number(e.target.value))}- className="w-32 font-mono"- />+ <div className="flex items-center gap-1">+ <button+ type="button"+ className="flex size-7 items-center justify-center rounded-md border border-border text-muted-foreground hover:bg-muted cursor-pointer"+ onClick={() => setLearningRate(stepLR(learningRate, -1))}+ >+ -+ </button>+ <span className="w-16 text-center font-mono text-sm">+ {formatLR(learningRate)}+ </span>+ <button+ type="button"+ className="flex size-7 items-center justify-center rounded-md border border-border text-muted-foreground hover:bg-muted cursor-pointer"+ onClick={() => setLearningRate(stepLR(learningRate, 1))}+ >+ ++ </button>+ </div></div></div>diff --git a/studio/frontend/src/features/onboarding/components/steps/model-type-step.tsx b/studio/frontend/src/features/onboarding/components/steps/model-type-step.tsxindex 539ad42c5f3..4ab9fedf107 100644--- a/studio/frontend/src/features/onboarding/components/steps/model-type-step.tsx+++ b/studio/frontend/src/features/onboarding/components/steps/model-type-step.tsx@@ -14,6 +14,7 @@ import { cn } from "@/lib/utils";import { useTrainingConfigStore } from "@/features/training";import type { ModelType } from "@/types/training";import {+ BubbleChatIcon,Database02Icon,ImageIcon,InformationCircleIcon,@@ -21,7 +22,7 @@ import {VoiceIcon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";-import type { ReactElement } from "react";+import { type ReactElement, useState } from "react";import { useShallow } from "zustand/react/shallow";const TYPE_ICONS: Record<ModelType, typeof ImageIcon> = {@@ -47,28 +48,30 @@ export function ModelTypeStep(): ReactElement {setModelType: s.setModelType,})),);+ const [chatOnlySelected, setChatOnlySelected] = useState(false);return (<div className="flex flex-col gap-6"><div><h2 className="text-lg font-semibold">Welcome to Unsloth Studio</h2><p className="text-sm text-muted-foreground">- Fine-tune LLMs 2x faster with 70% less VRAM. Pick a model type to get- started.{" "}+ Choose a path - fine-tune LLMs, vision, embedding, audio models or just chat.{" "}<a- href="https://unsloth.ai/docs"+ href="https://unsloth.ai/docs/new/studio/start"target="_blank"rel="noreferrer"className="text-primary underline">- Watch video guide+ Get started with our guide</a></p></div><RadioGroup- value={modelType ?? ""}+ value={chatOnlySelected ? "" : (modelType ?? "")}onValueChange={(v) => {if (!COMING_SOON.includes(v as ModelType)) {+ setChatOnlySelected(false);+ sessionStorage.removeItem("unsloth_chat_only");setModelType(v as ModelType);}}}@@ -76,7 +79,7 @@ export function ModelTypeStep(): ReactElement {>{MODEL_TYPES.map((type) => {const Icon = TYPE_ICONS[type.value];- const isSelected = modelType === type.value;+ const isSelected = !chatOnlySelected && modelType === type.value;const isDisabled = COMING_SOON.includes(type.value);const inputId = `model-type-${type.value}`;@@ -172,6 +175,71 @@ export function ModelTypeStep(): ReactElement {</label>);})}+ <div+ className="cursor-pointer"+ onClick={() => {+ setChatOnlySelected(true);+ setModelType("text" as ModelType);+ sessionStorage.setItem("unsloth_chat_only", "1");+ }}+ >+ <Card+ size="sm"+ className={cn(+ "relative shadow-primary/30 transition-all duration-150 ease-out",+ "hover:ring-primary/40 hover:-translate-y-0.5 hover:shadow-sm",+ chatOnlySelected && "ring-2 ring-primary -translate-y-0.5 shadow-sm",+ )}+ >+ <CardContent className="flex items-center gap-4 py-4">+ {/* Invisible spacer matching RadioGroupItem (size-4 flex) in other cards */}+ <div className="size-4 shrink-0" aria-hidden="true" />+ <div+ className={cn(+ "size-10 rounded-xl corner-squircle flex items-center justify-center shrink-0",+ "transition-all duration-100 ease-out",+ chatOnlySelected+ ? "bg-primary/10 text-primary scale-105"+ : "bg-muted text-muted-foreground",+ )}+ >+ <HugeiconsIcon+ icon={BubbleChatIcon}+ className={cn(+ "size-5 transition-transform duration-100 ease-out",+ chatOnlySelected && "scale-110",+ )}+ strokeWidth={chatOnlySelected ? 2.5 : 2}+ />+ </div>+ <div className="flex flex-col gap-0.5 flex-1">+ <div className="flex items-center gap-1.5">+ <span className="font-medium">Chat</span>+ <Tooltip>+ <TooltipTrigger asChild={true}>+ <button+ type="button"+ className="text-muted-foreground/50 hover:text-muted-foreground"+ onClick={(e) => e.stopPropagation()}+ >+ <HugeiconsIcon+ icon={InformationCircleIcon}+ className="size-3.5"+ />+ </button>+ </TooltipTrigger>+ <TooltipContent>+ Chat with any model. Has tool calling, web search and more.+ </TooltipContent>+ </Tooltip>+ </div>+ <span className="text-xs text-muted-foreground">+ Chat with LLMs & vision models + audio generation.+ </span>+ </div>+ </CardContent>+ </Card>+ </div></RadioGroup></div>);diff --git a/studio/frontend/src/features/onboarding/components/steps/summary-step.tsx b/studio/frontend/src/features/onboarding/components/steps/summary-step.tsxindex a728858dd0a..8840983574f 100644--- a/studio/frontend/src/features/onboarding/components/steps/summary-step.tsx+++ b/studio/frontend/src/features/onboarding/components/steps/summary-step.tsx@@ -150,7 +150,7 @@ export function SummaryStep() {<Separator className="my-2" /><div className="space-y-1 text-sm"><Row label="Type" value={modelType} capitalize />- <Row label="Method" value={trainingMethod} uppercase />+ <Row label="Method" value={trainingMethod === "qlora" ? "QLoRA" : trainingMethod === "lora" ? "LoRA" : "Full"} /></div></CardContent></Card>@@ -198,14 +198,16 @@ export function SummaryStep() {</div><div className="flex flex-1 flex-col"><span className="text-xs text-muted-foreground">Training</span>- <span className="text-sm font-medium">{trainingMethod.toUpperCase()}</span>+ <span className="text-sm font-medium">+ {trainingMethod === "qlora" ? "QLoRA" : trainingMethod === "lora" ? "LoRA" : "Full"}+ </span></div></div><Separator className="my-2" /><div className="grid grid-cols-2 gap-x-6 gap-y-1 text-sm"><Row label="Epochs" value={epochs} mono /><Row label="Context" value={contextLength.toLocaleString()} mono />- <Row label="LR" value={learningRate} mono />+ <Row label="LR" value={learningRate.toExponential()} mono />{showLoraParams && (<><Row label="Rank" value={loraRank} mono />diff --git a/studio/frontend/src/features/onboarding/components/wizard-footer.tsx b/studio/frontend/src/features/onboarding/components/wizard-footer.tsxindex 6a8168a77b7..81e2f2738f0 100644--- a/studio/frontend/src/features/onboarding/components/wizard-footer.tsx+++ b/studio/frontend/src/features/onboarding/components/wizard-footer.tsx@@ -10,7 +10,7 @@ import { HugeiconsIcon } from "@hugeicons/react";import { useNavigate } from "@tanstack/react-router";import { useShallow } from "zustand/react/shallow";-export function WizardFooter() {+export function WizardFooter({ onBackToSplash }: { onBackToSplash: () => void }) {const { currentStep, prevStep, nextStep, canProceed } = useTrainingConfigStore(useShallow((s) => ({currentStep: s.currentStep,@@ -29,34 +29,55 @@ export function WizardFooter() {<Buttonvariant="outline"className="px-4 !pl-4"- onClick={prevStep}- disabled={isFirst}+ onClick={isFirst ? onBackToSplash : prevStep}><HugeiconsIcon icon={ArrowLeft02Icon} data-icon="inline-start" />Back</Button>- {isLast ? (- <Button- onClick={() => {- markOnboardingDone();- navigate({ to: "/studio" });- }}- disabled={!canProceed}- className="px-4 !pr-4"- >- Go to Studio- <HugeiconsIcon icon={ArrowRight02Icon} data-icon="inline-end" />- </Button>- ) : (- <Button- onClick={nextStep}- className="px-4 !pl-4"- disabled={!canProceed}- >- Continue- <HugeiconsIcon icon={ArrowRight02Icon} data-icon="inline-end" />- </Button>- )}+ <div className="flex items-center gap-2">+ {!isLast && (+ <Button+ variant="outline"+ className="px-4"+ onClick={() => {+ markOnboardingDone();+ navigate({ to: "/studio" });+ }}+ >+ Skip+ </Button>+ )}+ {isLast ? (+ <Button+ onClick={() => {+ markOnboardingDone();+ navigate({ to: "/studio" });+ }}+ disabled={!canProceed}+ className="px-4 !pr-4"+ >+ Go to Studio+ <HugeiconsIcon icon={ArrowRight02Icon} data-icon="inline-end" />+ </Button>+ ) : (+ <Button+ onClick={() => {+ if (currentStep === 1 && sessionStorage.getItem("unsloth_chat_only") === "1") {+ sessionStorage.removeItem("unsloth_chat_only");+ markOnboardingDone();+ window.location.href = "/chat";+ } else {+ nextStep();+ }+ }}+ className="px-4 !pl-4"+ disabled={!canProceed}+ >+ Continue+ <HugeiconsIcon icon={ArrowRight02Icon} data-icon="inline-end" />+ </Button>+ )}+ </div></div></footer>);diff --git a/studio/frontend/src/features/onboarding/components/wizard-layout.tsx b/studio/frontend/src/features/onboarding/components/wizard-layout.tsxindex 17b59061656..940ac333be7 100644--- a/studio/frontend/src/features/onboarding/components/wizard-layout.tsx+++ b/studio/frontend/src/features/onboarding/components/wizard-layout.tsx@@ -27,9 +27,15 @@ export function WizardLayout() {const hasFiredRef = useRef(false);const isFinalStep = currentStep === STEPS.length;+ // Only redirect on initial mount — not on re-renders after markOnboardingDone()+ // which would override explicit /chat navigation from skip buttons.+ const checkedRef = useRef(false);useEffect(() => {- if (isOnboardingDone()) {- navigate({ to: "/studio" });+ if (!checkedRef.current) {+ checkedRef.current = true;+ if (isOnboardingDone()) {+ navigate({ to: "/studio" });+ }}}, [navigate]);@@ -63,7 +69,7 @@ export function WizardLayout() {onStartOnboarding={() => setShowSplash(false)}onGoToStudio={() => {markOnboardingDone();- navigate({ to: "/studio" });+ window.location.href = "/studio";}}/>)}@@ -88,7 +94,7 @@ export function WizardLayout() {<WizardSidebar /><div className="flex-1 flex flex-col"><WizardContent />- <WizardFooter />+ <WizardFooter onBackToSplash={() => setShowSplash(true)} /></div></Card></motion.div>diff --git a/studio/frontend/src/features/onboarding/components/wizard-sidebar.tsx b/studio/frontend/src/features/onboarding/components/wizard-sidebar.tsxindex ca8b63bc3a5..70621fc1b7a 100644--- a/studio/frontend/src/features/onboarding/components/wizard-sidebar.tsx+++ b/studio/frontend/src/features/onboarding/components/wizard-sidebar.tsx@@ -1,9 +1,13 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import { Button } from "@/components/ui/button";import { Progress } from "@/components/ui/progress";import { STEPS } from "@/config/training";+import { markOnboardingDone } from "@/features/auth";import { useTrainingConfigStore } from "@/features/training";+import { ArrowRight02Icon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";import { WizardStepItem } from "./wizard-step-item";export function WizardSidebar() {@@ -29,11 +33,33 @@ export function WizardSidebar() {<p className="mt-2 text-xs text-muted-foreground md:hidden">Step {currentStep} of {STEPS.length}</p>+ <Button+ size="sm"+ className="mt-2 w-full md:hidden"+ onClick={() => {+ markOnboardingDone();+ window.location.href = "/chat";+ }}+ >+ Skip to Chat+ <HugeiconsIcon icon={ArrowRight02Icon} data-icon="inline-end" />+ </Button><nav className="mt-3 hidden flex-col gap-1 md:flex">{STEPS.map((step) => (<WizardStepItem key={step.number} step={step} />))}</nav>+ <Button+ size="sm"+ className="mt-3 hidden w-full md:flex"+ onClick={() => {+ markOnboardingDone();+ window.location.href = "/chat";+ }}+ >+ Skip to Chat+ <HugeiconsIcon icon={ArrowRight02Icon} data-icon="inline-end" />+ </Button></aside>);}diff --git a/studio/frontend/src/features/studio/sections/progress-section.tsx b/studio/frontend/src/features/studio/sections/progress-section.tsxindex 164f0c2f75e..da89ce66ee8 100644--- a/studio/frontend/src/features/studio/sections/progress-section.tsx+++ b/studio/frontend/src/features/studio/sections/progress-section.tsx@@ -272,7 +272,7 @@ export function ProgressSection(): ReactElement {{config.selectedModel ?? "--"}</MetricStat><MetricStat label="Method">- {config.trainingMethod.toUpperCase()}+ {config.trainingMethod === "qlora" ? "QLoRA" : config.trainingMethod === "lora" ? "LoRA" : "Full"}</MetricStat></div>diff --git a/studio/frontend/src/features/studio/training-start-overlay.tsx b/studio/frontend/src/features/studio/training-start-overlay.tsxindex af670bb38e0..92bd2b7b08f 100644--- a/studio/frontend/src/features/studio/training-start-overlay.tsx+++ b/studio/frontend/src/features/studio/training-start-overlay.tsx@@ -101,11 +101,7 @@ export function TrainingStartOverlay({{"> unsloth training starts..."}</TypingAnimation><AnimatedSpan className="my-2">- <pre className="whitespace-pre text-left text-muted-foreground">{`==((====))==-\\\\ /|-O^O/ \\_/ \\-\\ /- "-____-"`}</pre>+ <pre className="whitespace-pre text-muted-foreground inline-block">{`==((====))==\n \\\\ /|\nO^O/ \\_/ \\\n\\ /\n "-____-"`}</pre></AnimatedSpan><TypingAnimation duration={44}>{"> Preparing model and dataset..."}diff --git a/studio/frontend/src/features/training/api/models-api.ts b/studio/frontend/src/features/training/api/models-api.tsindex 024296fd28e..84051e3e1db 100644--- a/studio/frontend/src/features/training/api/models-api.ts+++ b/studio/frontend/src/features/training/api/models-api.ts@@ -71,6 +71,8 @@ export interface ModelConfigResponse {is_lora: boolean;base_model?: string | null;model_type?: "text" | "vision" | "audio" | "embeddings" | null;+ max_position_embeddings?: number | null;+ model_size_bytes?: number | null;}export interface LocalModelInfo {diff --git a/studio/frontend/src/features/training/components/hf-dataset-subset-split-selectors.tsx b/studio/frontend/src/features/training/components/hf-dataset-subset-split-selectors.tsxindex 7d67fe7ad40..ab8d8cf7666 100644--- a/studio/frontend/src/features/training/components/hf-dataset-subset-split-selectors.tsx+++ b/studio/frontend/src/features/training/components/hf-dataset-subset-split-selectors.tsx@@ -115,7 +115,7 @@ export function HfDatasetSubsetSplitSelectors({</div><SelectorDropdownvariant={variant}- label="Eval Split"+ label="Evaluation Split"tooltip="Select which split to use for evaluation. None means no evaluation during training."value={null}onChange={setDatasetEvalSplit}@@ -199,7 +199,7 @@ export function HfDatasetSubsetSplitSelectors({)}<SelectorDropdownvariant={variant}- label="Eval Split"+ label="Evaluation Split"tooltip="Select which split to use for evaluation. None means no evaluation during training."value={datasetEvalSplit}onChange={setDatasetEvalSplit}diff --git a/studio/frontend/src/features/training/hooks/use-max-steps-epochs-toggle.ts b/studio/frontend/src/features/training/hooks/use-max-steps-epochs-toggle.tsindex 4f35dd54f54..42c517cf3dc 100644--- a/studio/frontend/src/features/training/hooks/use-max-steps-epochs-toggle.ts+++ b/studio/frontend/src/features/training/hooks/use-max-steps-epochs-toggle.ts@@ -5,7 +5,7 @@ import { useCallback, useEffect, useState } from "react";const PREV_MAX_STEPS_KEY = "unsloth_prev_max_steps";const PREV_SAVE_STEPS_KEY = "unsloth_prev_save_steps";-const DEFAULT_MAX_STEPS = 30;+const DEFAULT_MAX_STEPS = 60;const DEFAULT_EPOCHS = 3;function readStoredNumber(key: string, fallback: number): number {diff --git a/studio/frontend/src/features/training/stores/training-config-store.ts b/studio/frontend/src/features/training/stores/training-config-store.tsindex e1b8d4b1a2d..c658f15016f 100644--- a/studio/frontend/src/features/training/stores/training-config-store.ts+++ b/studio/frontend/src/features/training/stores/training-config-store.ts@@ -2,7 +2,8 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { DEFAULT_HYPERPARAMS, STEPS } from "@/config/training";-import type { ModelType, StepNumber } from "@/types/training";+import { authFetch } from "@/features/auth";+import type { ModelType, StepNumber, TrainingMethod } from "@/types/training";import { create } from "zustand";import { persist } from "zustand/middleware";import { checkDatasetFormat } from "../api/datasets-api";@@ -14,6 +15,39 @@ import type { TrainingConfigState, TrainingConfigStore } from "../types/config";const MIN_STEP: StepNumber = 1;const MAX_STEP: StepNumber = STEPS.length as StepNumber;+/**+ * Auto-select LoRA (16-bit) vs QLoRA (4-bit) based on model size and GPU memory.+ *+ * Rule: if model_size_gb * 1.5 * context_scale fits in free VRAM, use "lora" (16-bit).+ * Otherwise use "qlora" (4-bit).+ *+ * Context scale: <=8192 = 1.0, >8192 = 1.7, >=16384 = 2.0, >=32768 = 4.0+ */+async function autoSelectTrainingMethod(+ modelSizeBytes: number,+ contextLength: number,+): Promise<TrainingMethod | null> {+ try {+ const res = await authFetch("/api/system/hardware");+ if (!res.ok) return null;+ const data = await res.json();+ const freeGb: number | null = data?.gpu?.vram_free_gb ?? null;+ if (freeGb == null) return null;++ const modelSizeGb = modelSizeBytes / (1024 ** 3);++ let contextScale = 1.0;+ if (contextLength >= 32768) contextScale = 4.0;+ else if (contextLength >= 16384) contextScale = 2.0;+ else if (contextLength > 8192) contextScale = 1.7;++ const estimatedUsage = modelSizeGb * 1.5 * contextScale;+ return estimatedUsage <= freeGb ? "lora" : "qlora";+ } catch {+ return null;+ }+}+function emptyManualMapping(): TrainingConfigState["datasetManualMapping"] {return {};}@@ -50,6 +84,7 @@ const initialState: TrainingConfigState = {isCheckingDataset: false,isDatasetImage: null,isDatasetAudio: false,+ maxPositionEmbeddings: null,...DEFAULT_HYPERPARAMS,};@@ -75,6 +110,7 @@ const NON_PERSISTED_STATE_KEYS: ReadonlySet<keyof TrainingConfigState> = new Set"isDatasetImage","isDatasetAudio","trainOnCompletions",+ "maxPositionEmbeddings",]);function partializePersistedState(@@ -153,6 +189,18 @@ export const useTrainingConfigStore = create<TrainingConfigStore>()(const inferredModelType: ModelType = modelDetails.model_type?? (isEmbedding ? "embeddings" : modelDetails.is_vision ? "vision" : modelDetails.is_audio ? "audio" : "text");+ // Auto-select training method based on model size vs GPU memory.+ // If model_size * 1.5 * context_scale fits in free VRAM, use LoRA 16-bit.+ // Otherwise use QLoRA 4-bit.+ const modelSizeBytes = modelDetails.model_size_bytes;+ if (modelSizeBytes && modelSizeBytes > 0) {+ void autoSelectTrainingMethod(modelSizeBytes, patch.contextLength ?? get().contextLength)+ .then((method) => {+ if (get().selectedModel !== modelName) return;+ if (method) set({ trainingMethod: method });+ });+ }+set({...patch,modelType: inferredModelType,@@ -163,6 +211,7 @@ export const useTrainingConfigStore = create<TrainingConfigStore>()(isCheckingVision: false,modelDefaultsError: null,modelDefaultsAppliedFor: modelName,+ maxPositionEmbeddings: modelDetails.max_position_embeddings ?? null,});}).catch((error) => {@@ -318,7 +367,8 @@ export const useTrainingConfigStore = create<TrainingConfigStore>()(void loadAndApplyModelDefaults(state.selectedModel);},setTrainingMethod: (trainingMethod) => set({ trainingMethod }),- setHfToken: (hfToken) => set({ hfToken }),+ setHfToken: (hfToken) =>+ set({ hfToken: hfToken.trim().replace(/^["']+|["']+$/g, "") }),setDatasetSource: (datasetSource) => set({ datasetSource }),selectHfDataset: (dataset) => {_datasetCheckController?.abort();diff --git a/studio/frontend/src/features/training/types/config.ts b/studio/frontend/src/features/training/types/config.tsindex 635ef8671af..2d19dea8749 100644--- a/studio/frontend/src/features/training/types/config.ts+++ b/studio/frontend/src/features/training/types/config.ts@@ -80,6 +80,7 @@ export interface TrainingConfigState {finetuneAttentionModules: boolean;finetuneMLPModules: boolean;targetModules: string[];+ maxPositionEmbeddings: number | null;}export interface TrainingConfigActions {diff --git a/studio/frontend/src/hooks/use-hardware-info.ts b/studio/frontend/src/hooks/use-hardware-info.tsindex 3efd693df27..1e9210be5a5 100644--- a/studio/frontend/src/hooks/use-hardware-info.ts+++ b/studio/frontend/src/hooks/use-hardware-info.ts@@ -7,6 +7,7 @@ import { useEffect, useState } from "react";export interface HardwareInfo {gpuName: string | null;vramTotalGb: number | null;+ vramFreeGb: number | null;torch: string | null;cuda: string | null;transformers: string | null;@@ -16,6 +17,7 @@ export interface HardwareInfo {const DEFAULT: HardwareInfo = {gpuName: null,vramTotalGb: null,+ vramFreeGb: null,torch: null,cuda: null,transformers: null,@@ -38,6 +40,7 @@ async function fetchOnce(): Promise<HardwareInfo> {const info: HardwareInfo = {gpuName: data?.gpu?.gpu_name ?? null,vramTotalGb: data?.gpu?.vram_total_gb ?? null,+ vramFreeGb: data?.gpu?.vram_free_gb ?? null,torch: data?.versions?.torch ?? null,cuda: data?.versions?.cuda ?? null,transformers: data?.versions?.transformers ?? null,diff --git a/studio/frontend/src/hooks/use-hf-token-validation.ts b/studio/frontend/src/hooks/use-hf-token-validation.tsindex 8a4b66c6a91..f13be6b10a9 100644--- a/studio/frontend/src/hooks/use-hf-token-validation.ts+++ b/studio/frontend/src/hooks/use-hf-token-validation.ts@@ -23,7 +23,10 @@ const INITIAL: HfTokenValidationState = {* Returns validation state: isValid (null = not checked), error message, and isChecking.*/export function useHfTokenValidation(token: string): HfTokenValidationState {- const debouncedToken = useDebouncedValue(token.trim(), 500);+ const debouncedToken = useDebouncedValue(+ token.trim().replace(/^["']+|["']+$/g, ""),+ 500,+ );const [state, setState] = useState<HfTokenValidationState>(INITIAL);const versionRef = useRef(0);diff --git a/studio/setup.ps1 b/studio/setup.ps1index 15b5d217b05..2420448deb5 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -896,7 +896,7 @@ python "$PSScriptRoot\install_python_stack.py"$ErrorActionPreference = $prevEAP# ── Pre-install transformers 5.x into .venv_t5/ ──-# Models like GLM-4.7-Flash need transformers>=5.2.0. Instead of pip-installing+# Models like GLM-4.7-Flash need transformers>=5.3.0. Instead of pip-installing# at runtime (slow, ~10-15s), we pre-install into a separate directory.# The training subprocess just prepends .venv_t5/ to sys.path — instant switch.Write-Host ""@@ -906,9 +906,9 @@ if (Test-Path $VenvT5Dir) { Remove-Item -Recurse -Force $VenvT5Dir }New-Item -ItemType Directory -Path $VenvT5Dir -Force | Out-Null$prevEAP_t5 = $ErrorActionPreference$ErrorActionPreference = "Continue"-pip install --target $VenvT5Dir --no-deps "transformers==5.2.0" 2>&1 | Out-Null+pip install --target $VenvT5Dir --no-deps "transformers==5.3.0" 2>&1 | Out-Nullif ($LASTEXITCODE -ne 0) {- Write-Host "[FAIL] Could not install transformers 5.2.0 into .venv_t5/" -ForegroundColor Red+ Write-Host "[FAIL] Could not install transformers 5.3.0 into .venv_t5/" -ForegroundColor Red$ErrorActionPreference = $prevEAP_t5exit 1}diff --git a/studio/setup.sh b/studio/setup.shindex 1aabad45d88..4c8a6c7dde3 100755--- a/studio/setup.sh+++ b/studio/setup.sh@@ -246,13 +246,13 @@ elseinstall_python_stack# ── 6b. Pre-install transformers 5.x into .venv_t5/ ──- # Models like GLM-4.7-Flash need transformers>=5.2.0. Instead of pip-installing+ # Models like GLM-4.7-Flash need transformers>=5.3.0. Instead of pip-installing# at runtime (slow, ~10-15s), we pre-install into a separate directory.# The training subprocess just prepends .venv_t5/ to sys.path — instant switch.echo ""echo " Pre-installing transformers 5.x for newer model support..."mkdir -p "$VENV_T5_DIR"- run_quiet "pip install transformers 5.x" pip install --target "$VENV_T5_DIR" --no-deps "transformers==5.2.0"+ run_quiet "pip install transformers 5.x" pip install --target "$VENV_T5_DIR" --no-deps "transformers==5.3.0"run_quiet "pip install huggingface_hub for t5" pip install --target "$VENV_T5_DIR" --no-deps "huggingface_hub==1.3.0"echo "✅ Transformers 5.x pre-installed to $VENV_T5_DIR/"