Skip to content

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.

Unsloth run/start: per-model recommended sampling and override flags (#7335)

Daniel Han629cc50f1a76
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index b6bbbdfb5f8..389a0d245a9 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -6061,6 +6061,7 @@ async def generate_audio(
# Advertised repo id after an auto-switch load, else a clean public id,
# never the absolute .gguf path.
model_name = _llama_public_model_id(llama_backend)
+ _audio_model_id = getattr(llama_backend, "model_identifier", None) or model_name
gen = lambda: llama_backend.generate_audio_response(
text = text,
audio_type = llama_backend._audio_type,
@@ -6079,6 +6080,7 @@ async def generate_audio(
if not model_info.get("is_audio"):
raise HTTPException(status_code = 400, detail = "Active model is not an audio model.")
model_name = public_model_id(backend.active_model_name)
+ _audio_model_id = getattr(backend, "active_model_name", None) or model_name
gen = lambda: backend.generate_audio_response(
text = text,
temperature = payload.temperature,
@@ -6090,6 +6092,13 @@ async def generate_audio(
use_adapter = payload.use_adapter,
)
+ # Apply per-model recommended sampling + any operator UNSLOTH_SAMPLING_* pin before
+ # generating, so `unsloth run --temperature` (and the other pins) and per-model
+ # recommendations reach audio (TTS) generation too, not just chat. The gen lambdas read
+ # payload.* lazily at call time, so filling here takes effect; this covers both the direct
+ # /audio/generate route and the chat-completions audio branches that delegate here.
+ _fill_recommended_sampling_openai(payload, _audio_model_id)
+
try:
wav_bytes, sample_rate = await asyncio.to_thread(gen)
except Exception as e:
@@ -7381,6 +7390,51 @@ async def delete_openai_container(
await client.close()
+def _fill_recommended_sampling_openai(payload, model_id) -> None:
+ """Apply per-model recommended sampling (and any operator UNSLOTH_SAMPLING_* pin) to a
+ ChatCompletionRequest in place.
+
+ Only the sampling fields the client did NOT explicitly send (tracked via
+ ``model_fields_set``) are overwritten, so a client that sets a field stays byte-identical
+ unless an operator pins it. Fields with neither a recommendation nor a pin keep their
+ existing (schema-default) value.
+ """
+ from utils.inference.inference_config import resolve_effective_sampling, SAMPLING_FIELD_NAMES
+
+ explicit = {
+ f: (getattr(payload, f) if f in payload.model_fields_set else None)
+ for f in SAMPLING_FIELD_NAMES
+ }
+ effective = resolve_effective_sampling(model_id, explicit)
+ for field, value in effective.items():
+ setattr(payload, field, value)
+
+
+# /v1/completions is proxied to llama-server verbatim; its repetition knob is "repeat_penalty",
+# and every other sampling field keeps its name (mirrors _build_passthrough_payload).
+_COMPLETIONS_SAMPLING_BODY_KEY = {"repetition_penalty": "repeat_penalty"}
+
+
+def _fill_recommended_sampling_completions(body: dict, model_id) -> None:
+ """Apply per-model recommended sampling (and any operator UNSLOTH_SAMPLING_* pin) to a raw
+ ``/v1/completions`` body in place, so the legacy (non-chat) endpoint honors the same pins as
+ ``/v1/chat/completions``.
+
+ Unlike :func:`_fill_recommended_sampling_openai`, which fills a ChatCompletionRequest whose
+ schema already carries per-field defaults, this body is proxied to llama-server as-is. A field
+ with no operator pin, client value, or per-model recommendation is therefore left untouched
+ (``fill_defaults = False``) so llama-server keeps its own default rather than being forced onto
+ this schema's value. llama-server names the repetition knob ``repeat_penalty``, so read and
+ write that alias for the client-sent value and any pin.
+ """
+ from utils.inference.inference_config import resolve_effective_sampling, SAMPLING_FIELD_NAMES
+
+ explicit = {f: body.get(_COMPLETIONS_SAMPLING_BODY_KEY.get(f, f)) for f in SAMPLING_FIELD_NAMES}
+ effective = resolve_effective_sampling(model_id, explicit, fill_defaults = False)
+ for field, value in effective.items():
+ body[_COMPLETIONS_SAMPLING_BODY_KEY.get(field, field)] = value
+
+
@router.post("/chat/completions")
async def openai_chat_completions(
payload: ChatCompletionRequest,
@@ -7710,6 +7764,13 @@ async def openai_chat_completions(
completion_id = f"chatcmpl-{uuid.uuid4().hex[:12]}"
created = int(time.time())
+ # Apply recommended sampling + operator pins to the omitted fields before generating,
+ # so audio-input (non-whisper) generation honors `unsloth run --temperature` and
+ # per-model recommendations like chat does. Whisper (ASR) ignores these fields.
+ _fill_recommended_sampling_openai(
+ payload, getattr(backend, "active_model_name", None) or model_name
+ )
+
def audio_input_generate():
if model_info.get("audio_type") == "whisper":
return backend.generate_whisper_response(
@@ -7853,6 +7914,18 @@ async def openai_chat_completions(
),
)
+ # Apply per-model recommended sampling (and any operator UNSLOTH_SAMPLING_* pin) to the
+ # fields the client omitted, so agents and API clients get the model's tuned defaults
+ # unless they set the field explicitly. Placed after external-provider routing (which
+ # returned above) so only local llama-server / transformers requests are touched, and it
+ # covers both the passthrough and non-passthrough branches below since both read payload.*.
+ _reco_model_id = (
+ getattr(llama_backend, "model_identifier", None)
+ if using_gguf
+ else getattr(backend, "active_model_name", None)
+ ) or model_name
+ _fill_recommended_sampling_openai(payload, _reco_model_id)
+
# ── Standard OpenAI function-calling pass-through (GGUF only) ────
# When a client (opencode / Claude Code via OpenAI compat / Cursor /
# Continue / ...) sends standard OpenAI `tools` without Unsloth's
@@ -10630,6 +10703,10 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge
if _resolved_max_tokens is not None
else (llama_backend.context_length or _DEFAULT_MAX_TOKENS_FLOOR)
)
+ # Apply per-model recommended sampling and any operator UNSLOTH_SAMPLING_* pin to the raw
+ # body so /v1/completions honors the same pins as /v1/chat/completions; it is otherwise a
+ # verbatim proxy that would keep llama-server's defaults for every omitted sampling field.
+ _fill_recommended_sampling_completions(body, getattr(llama_backend, "model_identifier", None))
target_url = f"{llama_backend.base_url}/v1/completions"
is_stream = body.get("stream", False)
prompt_text = _flatten_monitor_prompt(body.get("prompt", ""))
@@ -11588,6 +11665,9 @@ async def _responses_stream(
detail = "Image provided but current GGUF model does not support vision.",
)
+ # Streaming /v1/responses builds the passthrough body directly (bypassing
+ # openai_chat_completions), so apply recommended sampling here too.
+ _fill_recommended_sampling_openai(chat_req, getattr(llama_backend, "model_identifier", None))
body = _build_openai_passthrough_body(
chat_req, backend_ctx = llama_backend.context_length, llama_backend = llama_backend
)
@@ -13019,14 +13099,28 @@ async def anthropic_messages(
# endpoint matches /v1/chat/completions.
_has_image = _normalize_anthropic_openai_images(openai_messages, llama_backend.is_vision)
- temperature = payload.temperature if payload.temperature is not None else 0.6
- top_p = payload.top_p if payload.top_p is not None else 0.95
- top_k = payload.top_k if payload.top_k is not None else 20
- min_p = payload.min_p if payload.min_p is not None else 0.01
- repetition_penalty = (
- payload.repetition_penalty if payload.repetition_penalty is not None else 1.0
+ # Fill omitted sampling fields with the per-model recommendation (or an operator
+ # UNSLOTH_SAMPLING_* pin); an explicit client value wins unless the operator pinned it.
+ # Anthropic sampling fields are Optional, so None already marks "client omitted".
+ from utils.inference.inference_config import resolve_effective_sampling
+
+ _anthropic_sampling = resolve_effective_sampling(
+ getattr(llama_backend, "model_identifier", None) or model_name,
+ {
+ "temperature": payload.temperature,
+ "top_p": payload.top_p,
+ "top_k": payload.top_k,
+ "min_p": payload.min_p,
+ "repetition_penalty": payload.repetition_penalty,
+ "presence_penalty": payload.presence_penalty,
+ },
)
- presence_penalty = payload.presence_penalty if payload.presence_penalty is not None else 0.0
+ temperature = _anthropic_sampling["temperature"]
+ top_p = _anthropic_sampling["top_p"]
+ top_k = _anthropic_sampling["top_k"]
+ min_p = _anthropic_sampling["min_p"]
+ repetition_penalty = _anthropic_sampling["repetition_penalty"]
+ presence_penalty = _anthropic_sampling["presence_penalty"]
stop = payload.stop_sequences or None
# Translate Anthropic tool_choice to OpenAI format for llama-server. Falls
diff --git a/studio/backend/tests/test_audio_sampling_fill.py b/studio/backend/tests/test_audio_sampling_fill.py
new file mode 100644
index 00000000000..efea18b83e2
--- /dev/null
+++ b/studio/backend/tests/test_audio_sampling_fill.py
@@ -0,0 +1,90 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Audio (TTS) generation applies recommended sampling + operator pins, like chat.
+
+Regression guard for the fix that moved the sampling fill ahead of the audio generators: a
+prior version resolved sampling only after the audio branches returned, so `unsloth run
+--temperature` (UNSLOTH_SAMPLING_*) and per-model recommendations never reached audio
+generation. These exercise the transformers TTS path of ``generate_audio`` (the direct
+``/audio/generate`` route, which the chat-completions audio branches also delegate to).
+"""
+
+import asyncio
+
+import pytest
+
+import routes.inference as inference_route
+from models.inference import ChatCompletionRequest
+from utils.inference import inference_config as ic
+
+
+class _FakeLlama:
+ # is_loaded False forces the transformers (non-GGUF) TTS branch in generate_audio.
+ is_loaded = False
+ _is_audio = False
+
+
+class _FakeTransformersBackend:
+ def __init__(self):
+ self.active_model_name = "some/custom-tts"
+ self.models = {"some/custom-tts": {"is_audio": True}}
+ self.captured = {}
+
+ def generate_audio_response(self, **kwargs):
+ self.captured.update(kwargs)
+ return (b"RIFFfake", 24000)
+
+
[email protected](autouse = True)
+def _isolate(monkeypatch):
+ ic._recommended_sampling.cache_clear()
+ for field in ic.SAMPLING_FIELD_NAMES:
+ monkeypatch.delenv(ic._SAMPLING_FIELDS[field][0], raising = False)
+ yield
+ ic._recommended_sampling.cache_clear()
+
+
+def _run_generate_audio(
+ monkeypatch,
+ *,
+ recommended = None,
+ temperature = None,
+):
+ backend = _FakeTransformersBackend()
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _FakeLlama())
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: backend)
+
+ async def _noop_switch(*a, **k):
+ return None
+
+ monkeypatch.setattr(inference_route, "_maybe_auto_switch_model", _noop_switch)
+
+ # Recommendation source == the Chat UI's .inference block.
+ monkeypatch.setattr(ic, "load_inference_config", lambda mid: dict(recommended or {}))
+ ic._recommended_sampling.cache_clear()
+
+ kwargs = {"model": "some/custom-tts", "messages": [{"role": "user", "content": "hi"}]}
+ if temperature is not None:
+ kwargs["temperature"] = temperature
+ payload = ChatCompletionRequest(**kwargs)
+
+ asyncio.run(inference_route.generate_audio(payload, request = None, current_subject = "t"))
+ return backend.captured
+
+
+def test_audio_uses_recommended_sampling_when_omitted(monkeypatch):
+ captured = _run_generate_audio(monkeypatch, recommended = {"temperature": 1.0, "top_k": 64})
+ assert captured["temperature"] == 1.0
+ assert captured["top_k"] == 64
+
+
+def test_audio_operator_pin_overrides_client(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_SAMPLING_TEMPERATURE", "0.9")
+ captured = _run_generate_audio(monkeypatch, recommended = {"temperature": 1.0}, temperature = 0.2)
+ assert captured["temperature"] == 0.9 # operator pin wins even over an explicit client value
+
+
+def test_audio_client_explicit_preserved(monkeypatch):
+ captured = _run_generate_audio(monkeypatch, recommended = {"temperature": 1.0}, temperature = 0.2)
+ assert captured["temperature"] == 0.2 # explicit client value preserved over recommendation
diff --git a/studio/backend/tests/test_sampling_resolution.py b/studio/backend/tests/test_sampling_resolution.py
new file mode 100644
index 00000000000..1ebbae2502f
--- /dev/null
+++ b/studio/backend/tests/test_sampling_resolution.py
@@ -0,0 +1,270 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Effective sampling resolution: per-model recommendation + operator pins.
+
+Precedence per field: operator UNSLOTH_SAMPLING_* pin -> client explicit value ->
+per-model recommendation (load_inference_config) -> static schema default.
+"""
+
+import pytest
+
+from utils.inference.inference_config import resolve_effective_sampling, SAMPLING_FIELD_NAMES
+from utils.inference import inference_config as ic
+
+_SCHEMA_DEFAULTS = {
+ "temperature": 0.6,
+ "top_p": 0.95,
+ "top_k": 20,
+ "min_p": 0.01,
+ "repetition_penalty": 1.0,
+ "presence_penalty": 0.0,
+}
+
+
[email protected](autouse = True)
+def _isolate(monkeypatch):
+ # The recommended lookup is lru-cached; clear it so a patched config takes effect.
+ ic._recommended_sampling.cache_clear()
+ for field in SAMPLING_FIELD_NAMES:
+ monkeypatch.delenv(ic._SAMPLING_FIELDS[field][0], raising = False)
+ yield
+ ic._recommended_sampling.cache_clear()
+
+
+def _all_omitted():
+ return {f: None for f in SAMPLING_FIELD_NAMES}
+
+
+def _set_recommended(monkeypatch, mapping):
+ # _recommended_sampling sources from load_inference_config -- the exact block the Chat UI
+ # seeds from -- so patch that directly. Fields absent from `mapping` fall to schema defaults.
+ monkeypatch.setattr(ic, "load_inference_config", lambda mid: dict(mapping))
+ ic._recommended_sampling.cache_clear()
+
+
+def test_recommended_applies_when_client_omits(monkeypatch):
+ _set_recommended(monkeypatch, {"temperature": 1.0, "top_k": 64, "min_p": 0.0})
+ eff = resolve_effective_sampling("some/model", _all_omitted())
+ assert eff["temperature"] == 1.0
+ assert eff["top_k"] == 64
+ assert eff["min_p"] == 0.0
+ # A field with no recommendation keeps the static schema default.
+ assert eff["top_p"] == 0.95
+
+
+def test_client_explicit_beats_recommended(monkeypatch):
+ _set_recommended(monkeypatch, {"temperature": 1.0})
+ eff = resolve_effective_sampling("some/model", {**_all_omitted(), "temperature": 0.2})
+ assert eff["temperature"] == 0.2
+
+
+def test_operator_pin_beats_client_and_recommended(monkeypatch):
+ _set_recommended(monkeypatch, {"temperature": 1.0})
+ monkeypatch.setenv("UNSLOTH_SAMPLING_TEMPERATURE", "0.9")
+ eff = resolve_effective_sampling("some/model", {**_all_omitted(), "temperature": 0.2})
+ assert eff["temperature"] == 0.9
+
+
+def test_unknown_model_matches_ui_inference_block(monkeypatch):
+ # An unknown model gets the same values the Chat UI would seed (load_inference_config's
+ # default.yaml fallback: temp 0.7 / top_k -1), NOT the request schema defaults.
+ ui_block = {
+ "temperature": 0.7,
+ "top_p": 0.95,
+ "top_k": -1,
+ "min_p": 0.01,
+ "presence_penalty": 0.0,
+ "repetition_penalty": 1.0,
+ }
+ monkeypatch.setattr(ic, "load_inference_config", lambda mid: dict(ui_block))
+ ic._recommended_sampling.cache_clear()
+ eff = resolve_effective_sampling("some/unknown-model", _all_omitted())
+ assert eff["temperature"] == 0.7
+ assert eff["top_k"] == -1
+ assert eff["min_p"] == 0.01
+
+
+def test_empty_recommendation_falls_back_to_schema_defaults(monkeypatch):
+ # If load_inference_config yields nothing usable, the resolver falls back to the request
+ # schema defaults.
+ monkeypatch.setattr(ic, "load_inference_config", lambda mid: {})
+ ic._recommended_sampling.cache_clear()
+ eff = resolve_effective_sampling("some/model", _all_omitted())
+ assert eff == _SCHEMA_DEFAULTS
+
+
+ "model",
+ ["unsloth/gemma-4-E4B", "unsloth/Qwen3-4B", "unsloth/Qwen3.5-9B", "someorg/unknown-xyz"],
+)
+def test_recommendation_matches_ui_source(model):
+ # Parity guard: what the server recommends for omitted fields equals the Chat UI's source
+ # (load_inference_config) for every field the UI adopts (mergeBackendRecommendedInference).
+ ic._recommended_sampling.cache_clear()
+ ui = ic.load_inference_config(model)
+ rec = ic._recommended_sampling(model)
+ for f in ic._UI_RECOMMENDED_FIELDS:
+ cleaned = ic._clean_sampling_value(f, ui.get(f))
+ if cleaned is not None:
+ assert rec.get(f) == cleaned, f"{model}:{f} rec={rec.get(f)} ui={ui.get(f)}"
+
+
+def test_repetition_penalty_not_auto_recommended(monkeypatch):
+ # The Chat UI's mergeBackendRecommendedInference never adopts a backend repetition_penalty
+ # (e.g. lfm2's family value 1.05), so the server must not auto-apply one either. It stays at
+ # the schema default unless the client sends it or an operator pins it.
+ monkeypatch.setattr(
+ ic, "load_inference_config", lambda mid: {"temperature": 0.7, "repetition_penalty": 1.05}
+ )
+ ic._recommended_sampling.cache_clear()
+ eff = resolve_effective_sampling("some/lfm2-model", _all_omitted())
+ assert eff["temperature"] == 0.7 # a UI-adopted field is recommended
+ assert eff["repetition_penalty"] == 1.0 # rep is NOT auto-recommended (matches the UI)
+ # An operator can still pin it explicitly.
+ monkeypatch.setenv("UNSLOTH_SAMPLING_REPETITION_PENALTY", "1.05")
+ eff2 = resolve_effective_sampling("some/lfm2-model", _all_omitted())
+ assert eff2["repetition_penalty"] == 1.05
+
+
+ "raw, expected",
+ [
+ ("0.5", 0.5),
+ ("abc", None), # unparseable
+ ("9.0", None), # above temperature max (2.0)
+ ("-1", None), # below temperature min (0.0)
+ (" ", None), # blank
+ ("nan", None), # NaN would pass a naive range check
+ ("inf", None), # non-finite
+ ("-inf", None), # non-finite
+ ],
+)
+def test_operator_override_parsing(monkeypatch, raw, expected):
+ monkeypatch.setenv("UNSLOTH_SAMPLING_TEMPERATURE", raw)
+ assert ic._operator_sampling_override("temperature") == expected
+
+
+def test_out_of_range_recommendation_is_dropped(monkeypatch):
+ # A malformed model recommendation (out of range) is ignored, so the request keeps the
+ # schema default rather than forwarding a bad value to llama-server.
+ _set_recommended(monkeypatch, {"temperature": 5.0, "top_k": 64})
+ eff = resolve_effective_sampling("some/model", _all_omitted())
+ assert eff["temperature"] == 0.6 # 5.0 is outside [0, 2] -> schema default
+ assert eff["top_k"] == 64 # a valid recommendation is still applied
+
+
+def test_operator_override_top_k_int_and_range(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_SAMPLING_TOP_K", "40")
+ assert ic._operator_sampling_override("top_k") == 40
+ monkeypatch.setenv("UNSLOTH_SAMPLING_TOP_K", "200") # above max 100
+ assert ic._operator_sampling_override("top_k") is None
+ monkeypatch.setenv("UNSLOTH_SAMPLING_TOP_K", "-1") # min allowed
+ assert ic._operator_sampling_override("top_k") == -1
+
+
+ "field, val",
+ [
+ ("top_k", 10**400), # oversized int on an int field: int() ok, but math.isfinite raises
+ ("top_k", float("nan")), # NaN reaching an int field: int(nan) raises ValueError
+ ("top_k", float("inf")), # inf reaching an int field: int(inf) raises OverflowError
+ (
+ "temperature",
+ 10**400,
+ ), # oversized int on a float field: float(huge_int) raises OverflowError
+ ],
+)
+def test_clean_sampling_value_rejects_unrepresentable(field, val):
+ # None of these may raise; each is unusable and must be dropped to None (regression: an
+ # oversized value used to raise OverflowError before the range check could drop it).
+ assert ic._clean_sampling_value(field, val) is None
+
+
+def test_oversized_operator_override_ignored(monkeypatch):
+ # A huge integer string parses via int() but overflows float(); math.isfinite would raise
+ # OverflowError and 500 the request. It must be ignored like any other bad override and the
+ # field must fall back to the schema default -- no exception.
+ monkeypatch.setenv("UNSLOTH_SAMPLING_TOP_K", "9" * 400)
+ assert ic._operator_sampling_override("top_k") is None
+ _set_recommended(monkeypatch, {}) # no per-model recommendation -> schema default applies
+ eff = resolve_effective_sampling("some/model", _all_omitted())
+ assert eff["top_k"] == 20 # schema default, resolved without raising
+
+
+def test_oversized_recommendation_ignored(monkeypatch):
+ # A malformed per-model recommendation carrying an oversized int must not raise while
+ # resolving either; the field simply falls back to the schema default.
+ _set_recommended(monkeypatch, {"temperature": 10**400, "top_k": 64})
+ eff = resolve_effective_sampling("some/model", _all_omitted())
+ assert eff["temperature"] == 0.6 # oversized -> dropped -> schema default
+ assert eff["top_k"] == 64 # a valid recommendation is still applied
+
+
+def test_fill_recommended_sampling_openai_payload(monkeypatch):
+ from models.inference import ChatCompletionRequest
+ from routes.inference import _fill_recommended_sampling_openai
+
+ _set_recommended(monkeypatch, {"temperature": 1.0, "top_k": 64, "min_p": 0.0})
+
+ # Client sent only temperature; top_k / min_p were omitted.
+ payload = ChatCompletionRequest(
+ model = "m", messages = [{"role": "user", "content": "hi"}], temperature = 0.2
+ )
+ _fill_recommended_sampling_openai(payload, "some/model")
+ assert payload.temperature == 0.2 # explicit client value preserved
+ assert payload.top_k == 64 # recommended fills the omitted field
+ assert payload.min_p == 0.0
+ assert payload.top_p == 0.95 # no recommendation -> schema default unchanged
+
+
+def test_fill_recommended_sampling_openai_operator_pin_overrides_client(monkeypatch):
+ from models.inference import ChatCompletionRequest
+ from routes.inference import _fill_recommended_sampling_openai
+
+ monkeypatch.setattr(ic, "load_model_defaults", lambda mid: {})
+ monkeypatch.setattr(ic, "get_family_inference_params", lambda mid: {})
+ ic._recommended_sampling.cache_clear()
+ monkeypatch.setenv("UNSLOTH_SAMPLING_TEMPERATURE", "0.9")
+
+ payload = ChatCompletionRequest(
+ model = "m", messages = [{"role": "user", "content": "hi"}], temperature = 0.2
+ )
+ _fill_recommended_sampling_openai(payload, "some/model")
+ assert payload.temperature == 0.9 # operator pin wins even over an explicit client value
+
+
+def test_fill_recommended_sampling_completions_body(monkeypatch):
+ # /v1/completions is a raw proxy: recommendations fill omitted fields, but a field with no
+ # recommendation and no pin is left absent so llama-server keeps its own default (unlike the
+ # chat schema, which carries per-field defaults).
+ from routes.inference import _fill_recommended_sampling_completions
+
+ _set_recommended(monkeypatch, {"temperature": 1.0, "top_k": 64, "min_p": 0.0})
+
+ body = {"prompt": "hi", "temperature": 0.2}
+ _fill_recommended_sampling_completions(body, "some/model")
+ assert body["temperature"] == 0.2 # explicit client value preserved
+ assert body["top_k"] == 64 # recommendation fills the omitted field
+ assert body["min_p"] == 0.0
+ # No recommendation and no pin -> NOT injected (llama-server keeps its default).
+ assert "top_p" not in body
+ assert "presence_penalty" not in body
+ assert "repeat_penalty" not in body
+
+
+def test_fill_recommended_sampling_completions_operator_pin(monkeypatch):
+ # An operator pin overrides the client's raw-body value, and the repetition pin is written
+ # under llama-server's "repeat_penalty" key (the schema field is repetition_penalty).
+ from routes.inference import _fill_recommended_sampling_completions
+
+ monkeypatch.setattr(ic, "load_inference_config", lambda mid: {})
+ ic._recommended_sampling.cache_clear()
+ monkeypatch.setenv("UNSLOTH_SAMPLING_TEMPERATURE", "0.9")
+ monkeypatch.setenv("UNSLOTH_SAMPLING_REPETITION_PENALTY", "1.2")
+
+ body = {"prompt": "hi", "temperature": 0.2, "repeat_penalty": 1.05}
+ _fill_recommended_sampling_completions(body, "some/model")
+ assert body["temperature"] == 0.9 # operator pin wins over the client's explicit value
+ assert body["repeat_penalty"] == 1.2 # repetition pin lands on llama-server's key
+ assert "repetition_penalty" not in body # never leak the schema field name into the body
diff --git a/studio/backend/utils/inference/inference_config.py b/studio/backend/utils/inference/inference_config.py
index 05eb08067cb..a264e06c85b 100644
--- a/studio/backend/utils/inference/inference_config.py
+++ b/studio/backend/utils/inference/inference_config.py
@@ -5,7 +5,10 @@
from pathlib import Path
from typing import Dict, Any, Optional
+from functools import lru_cache
import json
+import math
+import os
import yaml
import structlog
from loggers import get_logger
@@ -160,3 +163,137 @@ def load_inference_config(model_identifier: str) -> Dict[str, Any]:
}
return inference_config
+
+
+# ── Effective sampling resolution for `unsloth run` / `unsloth start` ──────────
+#
+# Per-model recommended sampling is applied to a request only for the fields the
+# client omitted; an operator can pin a field from the CLI via UNSLOTH_SAMPLING_*
+# (a hard override that wins even over an explicit client value). Precedence per
+# field: operator pin -> client explicit -> per-model recommendation -> the static
+# schema default (mirroring ChatCompletionRequest, so behavior is unchanged when
+# nothing is recommended or pinned).
+
+# field -> (env var, static default, min, max, is_int)
+_SAMPLING_FIELDS = {
+ "temperature": ("UNSLOTH_SAMPLING_TEMPERATURE", 0.6, 0.0, 2.0, False),
+ "top_p": ("UNSLOTH_SAMPLING_TOP_P", 0.95, 0.0, 1.0, False),
+ "top_k": ("UNSLOTH_SAMPLING_TOP_K", 20, -1, 100, True),
+ "min_p": ("UNSLOTH_SAMPLING_MIN_P", 0.01, 0.0, 1.0, False),
+ "repetition_penalty": ("UNSLOTH_SAMPLING_REPETITION_PENALTY", 1.0, 1.0, 2.0, False),
+ "presence_penalty": ("UNSLOTH_SAMPLING_PRESENCE_PENALTY", 0.0, 0.0, 2.0, False),
+}
+
+# Public, ordered tuple of the sampling fields callers resolve.
+SAMPLING_FIELD_NAMES = tuple(_SAMPLING_FIELDS)
+
+# Fields the Studio Chat UI adopts as *per-model recommendations* from the backend
+# `.inference` block. Its frontend `mergeBackendRecommendedInference`
+# (presets/preset-policy.ts) seeds exactly these five and never reads repetition_penalty,
+# so the server auto-recommends the same five for request parity. repetition_penalty stays a
+# manual-only knob (client-sent or an UNSLOTH_SAMPLING_REPETITION_PENALTY operator pin),
+# matching the UI where it is never auto-filled per model.
+_UI_RECOMMENDED_FIELDS = ("temperature", "top_p", "top_k", "min_p", "presence_penalty")
+
+
+def _clean_sampling_value(field: str, val: Any):
+ """Coerce ``val`` to the field's numeric type when it is a finite, in-range number, else None.
+
+ Rejects bool, non-numeric, NaN/inf, and out-of-range values so neither a bad operator env
+ var nor a malformed model recommendation can reach llama-server. NaN matters because
+ ``nan < lo`` and ``nan > hi`` are both False, so a plain range check would let it through.
+ Coerce before the finiteness check: ``math.isfinite`` and ``float()`` raise ``OverflowError``
+ on an int too big for a C double (an oversized UNSLOTH_SAMPLING_TOP_K would otherwise 500 the
+ request), while an in-range int is range-checked exactly and ``int()`` rejects a NaN/inf that
+ reached an int field.
+ """
+ if isinstance(val, bool) or not isinstance(val, (int, float)):
+ return None
+ _env, _default, lo, hi, is_int = _SAMPLING_FIELDS[field]
+ try:
+ val = int(val) if is_int else float(val)
+ except (ValueError, OverflowError):
+ # int(nan)/int(inf) and float(oversized_int) raise; treat them as unusable.
+ return None
+ # After coercion an int is always finite; only a float can still be NaN/inf.
+ if isinstance(val, float) and not math.isfinite(val):
+ return None
+ if val < lo or val > hi:
+ return None
+ return val
+
+
+def _operator_sampling_override(field: str):
+ """Operator-pinned value for a sampling field from UNSLOTH_SAMPLING_*, or None.
+
+ An unparseable, non-finite, or out-of-range value is ignored so a bad env var can never
+ reach llama-server; the field then falls back to the client / recommended value.
+ """
+ _env, _default, _lo, _hi, is_int = _SAMPLING_FIELDS[field]
+ raw = os.environ.get(_env)
+ if raw is None or raw.strip() == "":
+ return None
+ try:
+ val = int(raw) if is_int else float(raw)
+ except (TypeError, ValueError):
+ return None
+ return _clean_sampling_value(field, val)
+
+
+@lru_cache(maxsize = 128)
+def _recommended_sampling(model_id: str) -> Dict[str, Any]:
+ """Per-model recommended sampling, resolved through the SAME path the Studio Chat UI uses.
+
+ The Chat UI seeds its sampling from the ``.inference`` block of the load/status responses,
+ which is exactly :func:`load_inference_config` (model-specific YAML -> family defaults
+ (inference_defaults.json) -> default.yaml). Sourcing recommendations here keeps the values
+ the server applies to a request identical to what the UI shows for the same model. Only the
+ fields the UI actually adopts (:data:`_UI_RECOMMENDED_FIELDS`) are recommended; each value
+ is validated (finite + in range) before use. Cached by model id.
+ """
+ if not model_id:
+ return {}
+ try:
+ cfg = load_inference_config(model_id) or {}
+ except Exception as e:
+ logger.debug(f"Could not load recommended sampling for '{model_id}': {e}")
+ return {}
+ recommended: Dict[str, Any] = {}
+ for field in _UI_RECOMMENDED_FIELDS:
+ cleaned = _clean_sampling_value(field, cfg.get(field))
+ if cleaned is not None:
+ recommended[field] = cleaned
+ return recommended
+
+
+def resolve_effective_sampling(
+ model_id: Optional[str],
+ explicit: Dict[str, Any],
+ *,
+ fill_defaults: bool = True,
+) -> Dict[str, Any]:
+ """Resolve the effective sampling params for a request.
+
+ ``explicit`` maps each field in :data:`SAMPLING_FIELD_NAMES` to the client-sent
+ value, or ``None`` when the client omitted it. Precedence (highest first): an
+ operator ``UNSLOTH_SAMPLING_*`` pin, then the client's explicit value, then the
+ per-model recommendation, then the static schema default.
+
+ When ``fill_defaults`` is False a field with no operator pin, client value, or
+ per-model recommendation is omitted from the result instead of set to the static
+ schema default, so a raw proxy body (``/v1/completions``) keeps llama-server's own
+ default for that field rather than being forced onto this schema's value.
+ """
+ recommended = _recommended_sampling(model_id or "")
+ effective: Dict[str, Any] = {}
+ for field, (_env, default, _lo, _hi, _int) in _SAMPLING_FIELDS.items():
+ override = _operator_sampling_override(field)
+ if override is not None:
+ effective[field] = override
+ elif explicit.get(field) is not None:
+ effective[field] = explicit[field]
+ elif field in recommended:
+ effective[field] = recommended[field]
+ elif fill_defaults:
+ effective[field] = default
+ return effective
diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.py
index 434c4a0ad51..408ea4bd345 100644
--- a/unsloth_cli/commands/start.py
+++ b/unsloth_cli/commands/start.py
@@ -145,6 +145,7 @@ _CODEX_ENV_UNSET = ("OPENAI_API_KEY", "CODEX_API_KEY", "CODEX_ACCESS_TOKEN")
# instead of one long unaligned list.
_PANEL_MODEL = "Model"
_PANEL_SERVER = "Server"
+_PANEL_SAMPLING = "Sampling"
_PANEL_SESSION = "Agent session"
_MODEL_OPTION = typer.Option(
@@ -212,6 +213,56 @@ _TOOL_CALL_NUDGING_OPTION = typer.Option(
help = "Retry once with a nudge when a non-streaming passthrough tool call can't be healed. "
"On by default; when the flag is omitted an inherited UNSLOTH_TOOL_CALL_NUDGE is kept.",
)
+# Sampling overrides pin a value on the auto-started server (winning over the client and the
+# per-model recommendation). Default unset -> the model's recommended sampling is used.
+_TEMPERATURE_OPTION = typer.Option(
+ None,
+ "--temperature",
+ min = 0.0,
+ max = 2.0,
+ rich_help_panel = _PANEL_SAMPLING,
+ help = "Pin the sampling temperature. Default: unset (per-model recommendation).",
+)
+_TOP_P_OPTION = typer.Option(
+ None,
+ "--top-p",
+ min = 0.0,
+ max = 1.0,
+ rich_help_panel = _PANEL_SAMPLING,
+ help = "Pin top-p (nucleus) sampling. Default: unset (per-model recommendation).",
+)
+_TOP_K_OPTION = typer.Option(
+ None,
+ "--top-k",
+ min = -1,
+ max = 100,
+ rich_help_panel = _PANEL_SAMPLING,
+ help = "Pin top-k sampling. Default: unset (per-model recommendation).",
+)
+_MIN_P_OPTION = typer.Option(
+ None,
+ "--min-p",
+ min = 0.0,
+ max = 1.0,
+ rich_help_panel = _PANEL_SAMPLING,
+ help = "Pin min-p sampling threshold. Default: unset (per-model recommendation).",
+)
+_REPETITION_PENALTY_OPTION = typer.Option(
+ None,
+ "--repetition-penalty",
+ min = 1.0,
+ max = 2.0,
+ rich_help_panel = _PANEL_SAMPLING,
+ help = "Pin the repetition penalty. Default: unset (per-model recommendation).",
+)
+_PRESENCE_PENALTY_OPTION = typer.Option(
+ None,
+ "--presence-penalty",
+ min = 0.0,
+ max = 2.0,
+ rich_help_panel = _PANEL_SAMPLING,
+ help = "Pin the presence penalty. Default: unset (per-model recommendation).",
+)
# Agent-session knobs.
_KEY_OPTION = typer.Option(
@@ -415,6 +466,12 @@ class ServerOptions(NamedTuple):
enable_tools: bool = False
tool_call_healing: Optional[bool] = None
tool_call_nudging: Optional[bool] = None
+ temperature: Optional[float] = None
+ top_p: Optional[float] = None
+ top_k: Optional[int] = None
+ min_p: Optional[float] = None
+ repetition_penalty: Optional[float] = None
+ presence_penalty: Optional[float] = None
def _split_repo_variant(model: str) -> tuple:
@@ -958,6 +1015,18 @@ def _start_studio_server(
child_env["UNSLOTH_TOOL_CALL_NUDGE"] = "1" if server.tool_call_nudging else "0"
elif "UNSLOTH_TOOL_CALL_NUDGE" not in child_env:
child_env["UNSLOTH_TOOL_CALL_NUDGE"] = "1"
+ # Forward any sampling pin via the env; `unsloth run` reads UNSLOTH_SAMPLING_* and the
+ # backend resolver applies it as a hard override. Only set fields the operator specified.
+ for _sampling_env, _sampling_value in (
+ ("UNSLOTH_SAMPLING_TEMPERATURE", server.temperature),
+ ("UNSLOTH_SAMPLING_TOP_P", server.top_p),
+ ("UNSLOTH_SAMPLING_TOP_K", server.top_k),
+ ("UNSLOTH_SAMPLING_MIN_P", server.min_p),
+ ("UNSLOTH_SAMPLING_REPETITION_PENALTY", server.repetition_penalty),
+ ("UNSLOTH_SAMPLING_PRESENCE_PENALTY", server.presence_penalty),
+ ):
+ if _sampling_value is not None:
+ child_env[_sampling_env] = str(_sampling_value)
kwargs: dict = {
"stdout": log,
"stderr": subprocess.STDOUT,
@@ -1045,6 +1114,30 @@ def _require_studio(
"""Return (base, server). server is a Popen only when WE auto-started it."""
base = find_studio_server()
if base is not None:
+ # Attaching to a server someone else started: UNSLOTH_SAMPLING_* pins only reach the
+ # server process when WE launch it (via _start_studio_server), so a sampling flag on the
+ # attach path can't take effect. Warn instead of silently dropping it, so the operator is
+ # not misled into thinking generation now uses the pinned value.
+ _pinned = [
+ _flag
+ for _flag, _value in (
+ ("--temperature", server_options.temperature),
+ ("--top-p", server_options.top_p),
+ ("--top-k", server_options.top_k),
+ ("--min-p", server_options.min_p),
+ ("--repetition-penalty", server_options.repetition_penalty),
+ ("--presence-penalty", server_options.presence_penalty),
+ )
+ if _value is not None
+ ]
+ if _pinned:
+ typer.echo(
+ f"Warning: an Unsloth server is already running at {base}; sampling pins "
+ f"({', '.join(_pinned)}) apply only when this command starts the server, so the "
+ "running server keeps its current sampling. Stop it with `unsloth studio stop` "
+ "and re-run to apply them.",
+ err = True,
+ )
return base, None
expected = os.environ.get("UNSLOTH_STUDIO_URL", "http://127.0.0.1:8888").rstrip("/")
# Auto-start a local server only for an interactive launch with a model to serve, and
@@ -2807,6 +2900,12 @@ def claude(
enable_tools: bool = _ENABLE_TOOLS_OPTION,
tool_call_healing: Optional[bool] = _TOOL_CALL_HEALING_OPTION,
tool_call_nudging: Optional[bool] = _TOOL_CALL_NUDGING_OPTION,
+ temperature: Optional[float] = _TEMPERATURE_OPTION,
+ top_p: Optional[float] = _TOP_P_OPTION,
+ top_k: Optional[int] = _TOP_K_OPTION,
+ min_p: Optional[float] = _MIN_P_OPTION,
+ repetition_penalty: Optional[float] = _REPETITION_PENALTY_OPTION,
+ presence_penalty: Optional[float] = _PRESENCE_PENALTY_OPTION,
serve: bool = _SERVE_OPTION,
yolo: bool = _YOLO_OPTION,
persist: bool = _PERSIST_OPTION,
@@ -2821,7 +2920,17 @@ def claude(
LoadOptions(gguf_variant, max_seq_length, load_in_4bit, tensor_parallel),
serve = serve,
launch = launch,
- server_options = ServerOptions(enable_tools, tool_call_healing, tool_call_nudging),
+ server_options = ServerOptions(
+ enable_tools = enable_tools,
+ tool_call_healing = tool_call_healing,
+ tool_call_nudging = tool_call_nudging,
+ temperature = temperature,
+ top_p = top_p,
+ top_k = top_k,
+ min_p = min_p,
+ repetition_penalty = repetition_penalty,
+ presence_penalty = presence_penalty,
+ ),
)
model_id = entry["id"]
install_hint = (
@@ -2908,6 +3017,12 @@ def codex(
enable_tools: bool = _ENABLE_TOOLS_OPTION,
tool_call_healing: Optional[bool] = _TOOL_CALL_HEALING_OPTION,
tool_call_nudging: Optional[bool] = _TOOL_CALL_NUDGING_OPTION,
+ temperature: Optional[float] = _TEMPERATURE_OPTION,
+ top_p: Optional[float] = _TOP_P_OPTION,
+ top_k: Optional[int] = _TOP_K_OPTION,
+ min_p: Optional[float] = _MIN_P_OPTION,
+ repetition_penalty: Optional[float] = _REPETITION_PENALTY_OPTION,
+ presence_penalty: Optional[float] = _PRESENCE_PENALTY_OPTION,
serve: bool = _SERVE_OPTION,
yolo: bool = _YOLO_OPTION,
persist: bool = _PERSIST_OPTION,
@@ -2922,7 +3037,17 @@ def codex(
LoadOptions(gguf_variant, max_seq_length, load_in_4bit, tensor_parallel),
serve = serve,
launch = launch,
- server_options = ServerOptions(enable_tools, tool_call_healing, tool_call_nudging),
+ server_options = ServerOptions(
+ enable_tools = enable_tools,
+ tool_call_healing = tool_call_healing,
+ tool_call_nudging = tool_call_nudging,
+ temperature = temperature,
+ top_p = top_p,
+ top_k = top_k,
+ min_p = min_p,
+ repetition_penalty = repetition_penalty,
+ presence_penalty = presence_penalty,
+ ),
)
# This preflight runs after _connect may have auto-started a server but before _run
# takes over its lifecycle, so tear the server down here if it rejects the model
@@ -2990,6 +3115,12 @@ def openclaw(
enable_tools: bool = _ENABLE_TOOLS_OPTION,
tool_call_healing: Optional[bool] = _TOOL_CALL_HEALING_OPTION,
tool_call_nudging: Optional[bool] = _TOOL_CALL_NUDGING_OPTION,
+ temperature: Optional[float] = _TEMPERATURE_OPTION,
+ top_p: Optional[float] = _TOP_P_OPTION,
+ top_k: Optional[int] = _TOP_K_OPTION,
+ min_p: Optional[float] = _MIN_P_OPTION,
+ repetition_penalty: Optional[float] = _REPETITION_PENALTY_OPTION,
+ presence_penalty: Optional[float] = _PRESENCE_PENALTY_OPTION,
serve: bool = _SERVE_OPTION,
yolo: bool = _YOLO_OPTION,
persist: bool = _PERSIST_OPTION,
@@ -3004,7 +3135,17 @@ def openclaw(
LoadOptions(gguf_variant, max_seq_length, load_in_4bit, tensor_parallel),
serve = serve,
launch = launch,
- server_options = ServerOptions(enable_tools, tool_call_healing, tool_call_nudging),
+ server_options = ServerOptions(
+ enable_tools = enable_tools,
+ tool_call_healing = tool_call_healing,
+ tool_call_nudging = tool_call_nudging,
+ temperature = temperature,
+ top_p = top_p,
+ top_k = top_k,
+ min_p = min_p,
+ repetition_penalty = repetition_penalty,
+ presence_penalty = presence_penalty,
+ ),
)
openclaw_args = list(ctx.args)
# Default a bare `unsloth start openclaw` to the local TUI. Anything the caller
@@ -3054,6 +3195,12 @@ def opencode(
enable_tools: bool = _ENABLE_TOOLS_OPTION,
tool_call_healing: Optional[bool] = _TOOL_CALL_HEALING_OPTION,
tool_call_nudging: Optional[bool] = _TOOL_CALL_NUDGING_OPTION,
+ temperature: Optional[float] = _TEMPERATURE_OPTION,
+ top_p: Optional[float] = _TOP_P_OPTION,
+ top_k: Optional[int] = _TOP_K_OPTION,
+ min_p: Optional[float] = _MIN_P_OPTION,
+ repetition_penalty: Optional[float] = _REPETITION_PENALTY_OPTION,
+ presence_penalty: Optional[float] = _PRESENCE_PENALTY_OPTION,
serve: bool = _SERVE_OPTION,
yolo: bool = _YOLO_OPTION,
persist: bool = _PERSIST_OPTION,
@@ -3068,7 +3215,17 @@ def opencode(
LoadOptions(gguf_variant, max_seq_length, load_in_4bit, tensor_parallel),
serve = serve,
launch = launch,
- server_options = ServerOptions(enable_tools, tool_call_healing, tool_call_nudging),
+ server_options = ServerOptions(
+ enable_tools = enable_tools,
+ tool_call_healing = tool_call_healing,
+ tool_call_nudging = tool_call_nudging,
+ temperature = temperature,
+ top_p = top_p,
+ top_k = top_k,
+ min_p = min_p,
+ repetition_penalty = repetition_penalty,
+ presence_penalty = presence_penalty,
+ ),
)
if as_subagent:
subagent_id = _subagent_model_id(base, key, entry, model, gguf_variant)
@@ -3198,6 +3355,12 @@ def hermes(
enable_tools: bool = _ENABLE_TOOLS_OPTION,
tool_call_healing: Optional[bool] = _TOOL_CALL_HEALING_OPTION,
tool_call_nudging: Optional[bool] = _TOOL_CALL_NUDGING_OPTION,
+ temperature: Optional[float] = _TEMPERATURE_OPTION,
+ top_p: Optional[float] = _TOP_P_OPTION,
+ top_k: Optional[int] = _TOP_K_OPTION,
+ min_p: Optional[float] = _MIN_P_OPTION,
+ repetition_penalty: Optional[float] = _REPETITION_PENALTY_OPTION,
+ presence_penalty: Optional[float] = _PRESENCE_PENALTY_OPTION,
serve: bool = _SERVE_OPTION,
yolo: bool = _YOLO_OPTION,
persist: bool = _PERSIST_OPTION,
@@ -3214,7 +3377,17 @@ def hermes(
LoadOptions(gguf_variant, max_seq_length, load_in_4bit, tensor_parallel),
serve = serve,
launch = launch,
- server_options = ServerOptions(enable_tools, tool_call_healing, tool_call_nudging),
+ server_options = ServerOptions(
+ enable_tools = enable_tools,
+ tool_call_healing = tool_call_healing,
+ tool_call_nudging = tool_call_nudging,
+ temperature = temperature,
+ top_p = top_p,
+ top_k = top_k,
+ min_p = min_p,
+ repetition_penalty = repetition_penalty,
+ presence_penalty = presence_penalty,
+ ),
)
install_hint = _hermes_install_hint()
with _session_config("hermes", launch, persist = persist) as home:
@@ -3238,6 +3411,12 @@ def pi(
enable_tools: bool = _ENABLE_TOOLS_OPTION,
tool_call_healing: Optional[bool] = _TOOL_CALL_HEALING_OPTION,
tool_call_nudging: Optional[bool] = _TOOL_CALL_NUDGING_OPTION,
+ temperature: Optional[float] = _TEMPERATURE_OPTION,
+ top_p: Optional[float] = _TOP_P_OPTION,
+ top_k: Optional[int] = _TOP_K_OPTION,
+ min_p: Optional[float] = _MIN_P_OPTION,
+ repetition_penalty: Optional[float] = _REPETITION_PENALTY_OPTION,
+ presence_penalty: Optional[float] = _PRESENCE_PENALTY_OPTION,
serve: bool = _SERVE_OPTION,
yolo: bool = _YOLO_OPTION,
persist: bool = _PERSIST_OPTION,
@@ -3252,7 +3431,17 @@ def pi(
LoadOptions(gguf_variant, max_seq_length, load_in_4bit, tensor_parallel),
serve = serve,
launch = launch,
- server_options = ServerOptions(enable_tools, tool_call_healing, tool_call_nudging),
+ server_options = ServerOptions(
+ enable_tools = enable_tools,
+ tool_call_healing = tool_call_healing,
+ tool_call_nudging = tool_call_nudging,
+ temperature = temperature,
+ top_p = top_p,
+ top_k = top_k,
+ min_p = min_p,
+ repetition_penalty = repetition_penalty,
+ presence_penalty = presence_penalty,
+ ),
)
install_hint = "npm install -g --ignore-scripts @earendil-works/pi-coding-agent"
if as_subagent:
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 9a472d29969..84c22aa4ac7 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -1661,6 +1661,7 @@ def _consume_legacy_short_aliases(
_RUN_PANEL_MODEL = "Model"
_RUN_PANEL_SERVER = "Server & network"
_RUN_PANEL_TOOLS = "Tool calls"
+_RUN_PANEL_SAMPLING = "Sampling"
_RUN_PANEL_ADVANCED = "Advanced"
@@ -1758,6 +1759,57 @@ def run(
"Default: on. No effect on streaming requests or the server-side agentic loop."
),
),
+ temperature: Optional[float] = typer.Option(
+ None,
+ "--temperature",
+ min = 0.0,
+ max = 2.0,
+ rich_help_panel = _RUN_PANEL_SAMPLING,
+ help = (
+ "Pin the sampling temperature for every request that omits it, overriding the "
+ "model's recommended value. Default: unset (use the per-model recommendation)."
+ ),
+ ),
+ top_p: Optional[float] = typer.Option(
+ None,
+ "--top-p",
+ min = 0.0,
+ max = 1.0,
+ rich_help_panel = _RUN_PANEL_SAMPLING,
+ help = "Pin top-p (nucleus) sampling. Default: unset (per-model recommendation).",
+ ),
+ top_k: Optional[int] = typer.Option(
+ None,
+ "--top-k",
+ min = -1,
+ max = 100,
+ rich_help_panel = _RUN_PANEL_SAMPLING,
+ help = "Pin top-k sampling. Default: unset (per-model recommendation).",
+ ),
+ min_p: Optional[float] = typer.Option(
+ None,
+ "--min-p",
+ min = 0.0,
+ max = 1.0,
+ rich_help_panel = _RUN_PANEL_SAMPLING,
+ help = "Pin min-p sampling threshold. Default: unset (per-model recommendation).",
+ ),
+ repetition_penalty: Optional[float] = typer.Option(
+ None,
+ "--repetition-penalty",
+ min = 1.0,
+ max = 2.0,
+ rich_help_panel = _RUN_PANEL_SAMPLING,
+ help = "Pin the repetition penalty. Default: unset (per-model recommendation).",
+ ),
+ presence_penalty: Optional[float] = typer.Option(
+ None,
+ "--presence-penalty",
+ min = 0.0,
+ max = 2.0,
+ rich_help_panel = _RUN_PANEL_SAMPLING,
+ help = "Pin the presence penalty. Default: unset (per-model recommendation).",
+ ),
yes: bool = typer.Option(
False,
"--yes",
@@ -1841,7 +1893,7 @@ def run(
Example:
unsloth studio run --model unsloth/Qwen3-1.7B-GGUF --gguf-variant UD-Q4_K_XL
- unsloth studio run --model unsloth/Qwen3-1.7B-GGUF --top-k 20 --seed 42 --parallel 8
+ unsloth studio run --model unsloth/Qwen3-1.7B-GGUF --temperature 0.7 --seed 42 --parallel 8
unsloth studio run --model some-model --chat-template-file /path/to/tpl.jinja
unsloth studio run --model unsloth/Qwen3-27B-GGUF --gguf-variant Q8_0 --tensor-parallel
"""
@@ -1870,6 +1922,21 @@ def run(
elif "UNSLOTH_TOOL_CALL_NUDGE" not in os.environ:
os.environ["UNSLOTH_TOOL_CALL_NUDGE"] = "1"
+ # Sampling overrides: the backend resolver reads UNSLOTH_SAMPLING_* to hard-pin a field
+ # (winning over both the client and the per-model recommendation). Only write a flag that
+ # was set explicitly so an omitted flag inherits any value the parent forwarded (e.g.
+ # `unsloth start`) and, when nothing is set, leaves the per-model recommendation in charge.
+ for _sampling_env, _sampling_value in (
+ ("UNSLOTH_SAMPLING_TEMPERATURE", temperature),
+ ("UNSLOTH_SAMPLING_TOP_P", top_p),
+ ("UNSLOTH_SAMPLING_TOP_K", top_k),
+ ("UNSLOTH_SAMPLING_MIN_P", min_p),
+ ("UNSLOTH_SAMPLING_REPETITION_PENALTY", repetition_penalty),
+ ("UNSLOTH_SAMPLING_PRESENCE_PENALTY", presence_penalty),
+ ):
+ if _sampling_value is not None:
+ os.environ[_sampling_env] = str(_sampling_value)
+
# Set before any re-exec so the in-venv server inherits it via the env.
# `run --verbose` used to pass through to llama-server (its own -v); keep
# that by forwarding --log-verbose so we add Unsloth logs without dropping it.
diff --git a/unsloth_cli/tests/test_start.py b/unsloth_cli/tests/test_start.py
index 42745ef9c55..ade82cc06b9 100644
--- a/unsloth_cli/tests/test_start.py
+++ b/unsloth_cli/tests/test_start.py
@@ -1984,6 +1984,118 @@ def test_start_studio_server_respects_inherited_tool_call_env(monkeypatch):
assert env["UNSLOTH_TOOL_CALL_NUDGE"] == "1"
+def test_start_studio_server_forwards_sampling_via_env(monkeypatch):
+ # Sampling pins ride to the child server through UNSLOTH_SAMPLING_*; unset ones stay absent
+ # so the backend keeps the per-model recommendation.
+ captured = {}
+
+ class FakePopen:
+ def __init__(self, command, **kwargs):
+ captured["kwargs"] = kwargs
+ self.pid = 1
+
+ def poll(self):
+ return None
+
+ monkeypatch.setattr(start.subprocess, "Popen", FakePopen)
+ monkeypatch.setattr(start, "_studio_healthy", lambda base, timeout = 3.0: True)
+ monkeypatch.setattr(start, "_log_tail", lambda path, lines = 20: "API Key: sk-unsloth-x")
+ monkeypatch.setattr(start.time, "sleep", lambda _s: None)
+ for _v in ("TEMPERATURE", "TOP_P", "TOP_K", "MIN_P", "REPETITION_PENALTY", "PRESENCE_PENALTY"):
+ monkeypatch.delenv(f"UNSLOTH_SAMPLING_{_v}", raising = False)
+
+ # No sampling flags -> nothing forwarded.
+ start._start_studio_server("http://127.0.0.1:8888", "unsloth/M-GGUF", start.LoadOptions())
+ env = captured["kwargs"]["env"]
+ assert not any(k.startswith("UNSLOTH_SAMPLING_") for k in env)
+
+ # Pins are forwarded; unset ones stay absent.
+ start._start_studio_server(
+ "http://127.0.0.1:8888",
+ "unsloth/M-GGUF",
+ start.LoadOptions(),
+ start.ServerOptions(temperature = 0.3, top_k = 40, min_p = 0.05),
+ )
+ env = captured["kwargs"]["env"]
+ assert env["UNSLOTH_SAMPLING_TEMPERATURE"] == "0.3"
+ assert env["UNSLOTH_SAMPLING_TOP_K"] == "40"
+ assert env["UNSLOTH_SAMPLING_MIN_P"] == "0.05"
+ assert "UNSLOTH_SAMPLING_TOP_P" not in env
+
+
+def test_require_studio_warns_on_sampling_pin_when_reusing_server(monkeypatch, capsys):
+ # Attaching to an already-running server can't apply UNSLOTH_SAMPLING_* pins (only
+ # _start_studio_server forwards them), so a sampling flag on the attach path must warn
+ # instead of being silently dropped while the command "succeeds".
+ monkeypatch.setattr(start, "find_studio_server", lambda: BASE)
+ base, server = start._require_studio(
+ "unsloth/M-GGUF",
+ start.LoadOptions(),
+ serve = True,
+ launch = True,
+ server_options = start.ServerOptions(temperature = 0.3, top_k = 40),
+ )
+ assert base == BASE
+ assert server is None # attach path: we did not start the server
+ err = capsys.readouterr().err
+ assert "already running" in err
+ assert "--temperature" in err and "--top-k" in err
+ # Only the pinned fields are named; an unset one is not.
+ assert "--top-p" not in err
+
+
+def test_require_studio_no_sampling_warning_without_pins(monkeypatch, capsys):
+ # Reusing a server with no sampling pins stays silent (tool flags are out of scope here).
+ monkeypatch.setattr(start, "find_studio_server", lambda: BASE)
+ base, server = start._require_studio(
+ "unsloth/M-GGUF",
+ start.LoadOptions(),
+ serve = True,
+ server_options = start.ServerOptions(enable_tools = True),
+ )
+ assert base == BASE and server is None
+ assert "sampling" not in capsys.readouterr().err.lower()
+
+
+def test_start_claude_parses_sampling_flags(fake_studio, monkeypatch):
+ # `unsloth start claude ... --temperature 0.3 --top-k 40` routes the pins into ServerOptions.
+ monkeypatch.setenv("UNSLOTH_STUDIO_URL", "http://127.0.0.1:8888")
+ monkeypatch.setattr(start, "find_studio_server", lambda: None)
+ captured = {}
+ fake = SimpleNamespace(pid = 1, poll = lambda: None)
+
+ def fake_start(
+ base,
+ model,
+ load,
+ server_options = None,
+ ):
+ captured["server_options"] = server_options
+ start._auto_served_server = fake
+ return fake
+
+ monkeypatch.setattr(start, "_start_studio_server", fake_start)
+ monkeypatch.setattr(start, "_shutdown_server", lambda server: None)
+ monkeypatch.setattr(start.shutil, "which", lambda _: "/usr/local/bin/claude")
+ monkeypatch.setattr(start.subprocess, "run", lambda command, env: SimpleNamespace(returncode = 0))
+
+ result = CliRunner().invoke(
+ start.start_app,
+ [
+ "claude",
+ "--model",
+ "unsloth/gemma-4-E2B-it-GGUF",
+ "--temperature",
+ "0.3",
+ "--top-k",
+ "40",
+ ],
+ )
+ assert result.exit_code == 0, result.output
+ so = captured["server_options"]
+ assert so.temperature == 0.3 and so.top_k == 40 and so.top_p is None
+
+
def test_connect_model_bare_id_matches_loaded_without_reload(fake_studio):
# A bare `--model <loaded repo>` (no load knobs) attaches to the already-loaded model
# without touching /api/inference/load, so it can never evict another session.
diff --git a/unsloth_cli/tests/test_studio_run_parallel_flag.py b/unsloth_cli/tests/test_studio_run_parallel_flag.py
index b2fc421359f..972abb5d4d4 100644
--- a/unsloth_cli/tests/test_studio_run_parallel_flag.py
+++ b/unsloth_cli/tests/test_studio_run_parallel_flag.py
@@ -305,6 +305,43 @@ def test_run_omitted_flag_respects_inherited_env(monkeypatch, inherited):
assert studio_mod.os.environ["UNSLOTH_TOOL_CALL_NUDGE"] == inherited
+_SAMPLING_ENV_SUFFIXES = (
+ "TEMPERATURE",
+ "TOP_P",
+ "TOP_K",
+ "MIN_P",
+ "REPETITION_PENALTY",
+ "PRESENCE_PENALTY",
+)
+
+
+def test_run_sampling_flags_set_env(monkeypatch):
+ """`--temperature`/`--top-k` write UNSLOTH_SAMPLING_* (a hard override the backend applies);
+ an omitted sampling flag leaves its env unset so the per-model recommendation stays."""
+ studio_mod = _load_run_command()
+ for _v in _SAMPLING_ENV_SUFFIXES:
+ monkeypatch.delenv(f"UNSLOTH_SAMPLING_{_v}", raising = False)
+ _invoke_run(monkeypatch, _BASE + ["--temperature", "0.3", "--top-k", "40"])
+ assert studio_mod.os.environ["UNSLOTH_SAMPLING_TEMPERATURE"] == "0.3"
+ assert studio_mod.os.environ["UNSLOTH_SAMPLING_TOP_K"] == "40"
+ assert "UNSLOTH_SAMPLING_TOP_P" not in studio_mod.os.environ
+
+
+def test_run_no_sampling_flags_leaves_env_unset(monkeypatch):
+ """Plain `unsloth run` writes no UNSLOTH_SAMPLING_*; the server keeps the recommendation."""
+ studio_mod = _load_run_command()
+ for _v in _SAMPLING_ENV_SUFFIXES:
+ monkeypatch.delenv(f"UNSLOTH_SAMPLING_{_v}", raising = False)
+ _invoke_run(monkeypatch, _BASE)
+ assert not any(k.startswith("UNSLOTH_SAMPLING_") for k in studio_mod.os.environ)
+
+
+def test_run_rejects_out_of_range_sampling_flag(monkeypatch):
+ """typer enforces the documented ranges before a value can reach the server."""
+ result, _captured = _invoke_run(monkeypatch, _BASE + ["--temperature", "9"])
+ assert result.exit_code != 0
+
+
@pytest.mark.parametrize("platform", ["linux", "darwin", "win32"])
def test_reexec_argv_is_consistent_across_platforms(monkeypatch, platform):
"""Linux/Darwin (execvp) and Windows (Popen) must build the same argv."""
@@ -344,12 +381,14 @@ def test_reexec_mixed_parallel_with_passthrough(monkeypatch):
"""--parallel + llama-server pass-through flags must all reach the child."""
result, captured = _invoke_run(
monkeypatch,
- _BASE + ["--parallel", "8", "--top-k", "20", "--temp", "0.7"],
+ # --top-k is now a first-class sampling flag (routed via UNSLOTH_SAMPLING_*), so use
+ # --seed / --temp here, which remain genuine llama-server pass-through flags.
+ _BASE + ["--parallel", "8", "--seed", "42", "--temp", "0.7"],
)
assert len(captured) == 1
argv = captured[0]["argv"]
assert _value_after(argv, "--parallel") == "8", argv
- assert _value_after(argv, "--top-k") == "20", argv
+ assert _value_after(argv, "--seed") == "42", argv
assert _value_after(argv, "--temp") == "0.7", argv