Skip to content

unsloth run/start: apply per-model recommended sampling + sampling override flags - #7335

Merged
danielhanchen merged 9 commits into
mainfrom
unsloth-recommended-sampling
Jul 24, 2026
Merged

danielhanchen merged 9 commits into
mainfrom
unsloth-recommended-sampling

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Unsloth Studio ships per-model recommended sampling params (temperature, top_p, top_k, min_p, repetition_penalty, presence_penalty), tuned per model family (e.g. Gemma temp 1.0 / top_k 64, Qwen3 think-off 0.7/0.8). Today those are applied only client-side by the web Chat UI, so a coding agent driven through unsloth start or a client on unsloth run gets the generic request-schema defaults (temp 0.6 / top_k 20 / min_p 0.01) instead of the model's tuned values, and there is no way to pin sampling from the CLI.

This applies the recommendation server-side for the fields a request omits, and adds CLI flags to override any field.

Behavior

Effective value per field, highest precedence first:

  1. Operator CLI pin (--temperature etc., forwarded as UNSLOTH_SAMPLING_*) - a hard override that wins even over an explicit client value.
  2. The client's explicit per-request value.
  3. The per-model recommendation.
  4. The static request-schema default (unchanged when nothing is recommended or pinned).

The recommendation is sourced from the model-specific YAML or the family defaults only. The generic default.yaml tier is intentionally excluded, so a model with no specific/family recommendation keeps the existing schema defaults rather than shifting globally.

Only fields the client did not send are filled (tracked via model_fields_set), so an explicit request stays byte-identical unless the operator pinned that field.

Changes

  • studio/backend/utils/inference/inference_config.py: surface repetition_penalty from load_inference_config; add resolve_effective_sampling + the UNSLOTH_SAMPLING_* operator-override parsing (range-validated, cached recommendation lookup).
  • studio/backend/routes/inference.py: fill omitted sampling fields at the /v1/chat/completions entry (covers the tools / response_format passthrough and the non-passthrough GGUF + transformers paths), the streaming /v1/responses builder, and the Anthropic /v1/messages default-fill.
  • unsloth_cli/commands/studio.py and unsloth_cli/commands/start.py: add --temperature/--top-p/--top-k/--min-p/--repetition-penalty/--presence-penalty (default unset), grouped under a Sampling help panel; values travel to the auto-started server via the env, mirroring the tool-call flags.

Note: --top-p/--top-k/--min-p/--presence-penalty used to pass through to llama-server as raw args on unsloth run; they are now first-class flags routed through the resolver so they take effect on the passthrough path too (where a llama-server startup default has no effect).

Tests

  • studio/backend/tests/test_sampling_resolution.py: precedence (operator pin > client > recommendation > default), operator-override parsing/range validation, repetition_penalty surfaced, unknown model keeps schema defaults, and the payload-fill helper.
  • CLI: unsloth run writes UNSLOTH_SAMPLING_* only for flags that are set; unsloth start forwards them via child_env; agent commands parse the flags; out-of-range values are rejected by typer.

Stacked on #7328 (base set to that branch); retarget to main once it merges.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f0f72863af

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +207 to +209
if val < lo or val > hi:
return None
return val

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject non-finite operator sampling values

When an operator sets a float override such as UNSLOTH_SAMPLING_TEMPERATURE=NaN, float(raw) succeeds and both range comparisons are false, so this returns nan. That value then overrides every request and bypasses Pydantic when it is assigned onto the payload, eventually producing an invalid JSON/backend sampling value rather than falling back as the docstring promises. Explicitly reject non-finite floats before the range check.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. A NaN slipped the range check (nan comparisons are always False, so nan < lo and nan > hi are both False). Fixed in 21f1cd2: the operator override now rejects non-finite and out-of-range values via a shared _clean_sampling_value helper.

Comment on lines +241 to +245
for field in _SAMPLING_FIELDS:
for source in (model_inference, family):
val = source.get(field)
if isinstance(val, (int, float)) and not isinstance(val, bool):
recommended[field] = val

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate model recommendations before applying them

This accepts any numeric YAML recommendation, including the existing unsloth/Llasa-3B mapping whose YAML sets top_p: 1.2 (assets/configs/model_defaults/llasa/unsloth_Llasa-3B.yaml:43). For an omitted top_p, the new resolver assigns that value after ChatCompletionRequest validation, even though that request model limits top_p to 1.0, and forwards it to the local backend. Filter recommendations through the same per-field bounds (or validate assignment) so a bad model config cannot bypass the API contract.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Model and family recommendations now pass through the same finite + in-range validation as the operator overrides, so a malformed recommendation is dropped and the field falls back to the schema default rather than reaching llama-server. Fixed in 21f1cd2.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 21f1cd2739

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci autofix

Base automatically changed from unsloth-tool-call-flags to main July 23, 2026 08:45
danielhanchen and others added 4 commits July 23, 2026 08:51
…erride flags

Studio ships per-model recommended sampling (temperature / top_p / top_k / min_p /
repetition_penalty / presence_penalty) but only the web Chat UI applied it; a coding
agent driven through `unsloth start` or a client on `unsloth run` got the generic
schema defaults instead of the model's tuned values. Apply the recommendation
server-side for the fields a request omits, and add CLI flags to pin any field.

- Resolve effective sampling per request: an operator UNSLOTH_SAMPLING_* pin wins,
  then the client's explicit value, then the per-model recommendation, then the
  static schema default. The recommendation is sourced from the model-specific YAML
  or the family defaults only; the generic default.yaml tier is excluded so an
  unknown model keeps the request schema defaults instead of shifting globally.
- Fill the omitted fields at the chat-completions entry (covers the tools /
  response_format passthrough and the non-passthrough paths), the streaming
  /v1/responses builder, and the Anthropic /v1/messages default-fill. Only fields
  the client did not send are touched, so an explicit request stays byte-identical
  unless the operator pinned that field.
- Add --temperature/--top-p/--top-k/--min-p/--repetition-penalty/--presence-penalty
  to `unsloth run` and `unsloth start` (default unset). The values travel to the
  auto-started server via the env, mirroring the tool-call flags.
- Surface repetition_penalty from load_inference_config so its recommended value is
  no longer dropped.
… submodule

- Reject non-finite (NaN/inf) and out-of-range sampling values in one helper shared by the
  operator UNSLOTH_SAMPLING_* override and the per-model recommendation, so a bad env var or
  a malformed model config cannot reach llama-server. NaN mattered because a plain range
  check passes it (nan comparisons are always False).
- Import resolve_effective_sampling / SAMPLING_FIELD_NAMES directly from the submodule instead
  of re-exporting them through utils/inference/__init__.py, which the import-hoist lint flagged
  as added-but-unused re-exports.
…_penalty)

Source recommendations from load_inference_config (the same .inference block the
Chat UI seeds from) and restrict them to the five fields the UI actually adopts
via mergeBackendRecommendedInference: temperature, top_p, top_k, min_p,
presence_penalty. repetition_penalty is never auto-recommended (matching the UI,
which keeps it at the client default even for families like lfm2 whose JSON
carries 1.05); it stays settable via an explicit client value or the
UNSLOTH_SAMPLING_REPETITION_PENALTY operator pin. This makes the server-applied
recommendation identical to what the UI shows for every model. Add a parity guard
test over real configs plus a repetition_penalty-not-auto-recommended test.
@danielhanchen
danielhanchen force-pushed the unsloth-recommended-sampling branch from 64bf1b6 to 5ad466b Compare July 23, 2026 08:55
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5ad466b481

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if not model_id:
return {}
try:
cfg = load_inference_config(model_id) or {}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Exclude fallback defaults from recommendations

For any active model that has neither a model-specific YAML nor a family match, load_inference_config falls back to model_defaults/default.yaml, so this call treats its generic temperature=0.7 and top_k=-1 values as recommendations. Consequently every omitted-field request for an unknown/custom model changes from the request-schema defaults (0.6 / 20) despite there being no per-model recommendation. Resolve recommendations from only model-specific/family sources (or discard the default.yaml fallback) before returning them here.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Chat UI is the source of truth here, and for a model with no model-specific or family recommendation it does apply the default.yaml values. Both /api/inference/load and /api/inference/status call load_inference_config() unconditionally, so an unknown-but-loaded model's .inference block is fully populated with the default.yaml values (temperature 0.7, top_k -1). The frontend mergeBackendRecommendedInference reads those directly; its defaultInferenceParams 0.6/20 fallback only applies when a backend field is missing, which never happens for a loaded model. So the UI already shows 0.7 / -1 for an unknown model, and sourcing recommendations from load_inference_config keeps unsloth run identical to it. Excluding the default.yaml fallback would make the server diverge from the Chat UI for exactly these models, which is the opposite of the intent, so leaving as-is.

Comment on lines +7881 to +7886
_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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Resolve sampling before audio-path early returns

When /v1/chat/completions serves a GGUF audio model, a transformers TTS model, or a transformers audio-input model, those branches return before this call and pass the request's untouched schema defaults into the audio generators. As a result, unsloth run --temperature (and the other UNSLOTH_SAMPLING_* pins) and model recommendations have no effect for those audio requests, unlike normal chat generation. Apply the resolver before dispatching to the audio branches (and in the direct /audio/generate route).

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. The audio branches (GGUF audio, transformers TTS, transformers audio-input) and the direct /audio/generate route returned before the chat sampling fill, so operator pins and per-model recommendations never reached audio generation. Fixed in 375cb52: the fill now runs inside generate_audio before the lazily-evaluated gen lambda, covering the direct route and both chat audio branches that delegate to it, plus the chat-completions audio-input branch. Whisper (ASR) passes no sampling and is unaffected. Added regression tests over the transformers TTS path.

pre-commit-ci Bot and others added 2 commits July 23, 2026 09:01
The audio branches of /v1/chat/completions (GGUF audio, transformers TTS,
transformers audio-input) and the direct /audio/generate route returned before
the chat sampling fill, so unsloth run --temperature (and the other
UNSLOTH_SAMPLING_* pins) plus per-model recommendations had no effect on audio
generation, unlike normal chat. Fill the request inside generate_audio (before
the lazily-evaluated gen lambda, covering the direct route and both chat audio
branches that delegate to it) and in the chat-completions audio-input branch, so
every model path resolves sampling consistently. Whisper (ASR) passes no sampling
and is unaffected. Add regression tests over the transformers TTS path.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

repetition_penalty = payload.repetition_penalty,

P2 Badge Honor presence-penalty pins for TTS requests

For TTS requests, the resolver updates payload.presence_penalty, but this generation call never forwards it (and the TTS backend signatures likewise have no presence-penalty parameter). Consequently, unsloth run --presence-penalty and per-model presence-penalty recommendations have no effect on /audio/generate or audio chat completions, despite being advertised as hard sampling overrides.


return backend.generate_audio_input_response(
messages = chat_messages,
system_prompt = system_prompt,
audio_array = audio_array,
temperature = payload.temperature,
top_p = payload.top_p,
top_k = payload.top_k,
min_p = payload.min_p,
max_new_tokens = _effective_max_tokens(payload) or 2048,
repetition_penalty = payload.repetition_penalty,
cancel_event = cancel_event,

P2 Badge Apply resolved sampling to non-Whisper audio input

For a non-Whisper model with audio_base64, this path now resolves and forwards temperature/top-p/top-k/min-p/repetition settings, but InferenceBackend.generate_audio_input_response ignores all of them and always calls model.generate(..., do_sample=False). Thus the newly advertised recommendations and UNSLOTH_SAMPLING_* pins do not affect audio-input generation, despite the adjacent comment specifically excluding only Whisper from that expectation.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2295e2a304

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

"""
if isinstance(val, bool) or not isinstance(val, (int, float)):
return None
if not math.isfinite(val):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Ignore oversized integer sampling overrides

When UNSLOTH_SAMPLING_TOP_K contains a very large integer string, int(raw) succeeds but math.isfinite(val) raises OverflowError before the out-of-range check can drop it. In that environment every request that resolves sampling will 500 instead of ignoring the bad operator override as documented here; catch OverflowError or range-check integer fields before calling math.isfinite.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 7e2e794: coerce before the finiteness check and catch OverflowError and ValueError, so an oversized top_k (or a huge-int recommendation on a float field) is ignored instead of raising and 500ing the request. Regression: test_clean_sampling_value_rejects_unrepresentable.

enable_tools = enable_tools,
tool_call_healing = tool_call_healing,
tool_call_nudging = tool_call_nudging,
temperature = temperature,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject sampling pins when reusing a server

When unsloth start ... --temperature/--top-k/... attaches to an already running Unsloth, these new values are accepted and packed into ServerOptions, but _require_studio returns immediately for an existing find_studio_server() result and never calls _start_studio_server, so no UNSLOTH_SAMPLING_* env reaches the server process. In that common attach path the command succeeds while generation keeps the server's previous sampling; reject or warn on sampling pins unless this invocation auto-starts the server.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 7e2e794: on the attach path _require_studio now warns and names the pinned flags, since sampling pins only reach the server when this command starts it. The operator is told to stop and re-run to apply them, instead of the pins being silently dropped. Regression: test_require_studio_warns_on_sampling_pin_when_reusing_server.

Comment on lines +1937 to +1938
if _sampling_value is not None:
os.environ[_sampling_env] = str(_sampling_value)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply sampling pins to completions too

Because these flags now only set UNSLOTH_SAMPLING_* instead of reaching llama-server as startup defaults, /v1/completions requests bypass them entirely: openai_completions only patches max_tokens before proxying the caller's body to llama-server and never calls the sampling resolver. A client using the legacy OpenAI completions endpoint with omitted sampling under unsloth run --temperature ... will keep llama-server's defaults rather than the operator pin; apply the resolver to that body before proxying, or keep forwarding a startup default for this endpoint.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 7e2e794: openai_completions now applies operator pins and per-model recommendations via _fill_recommended_sampling_completions, using fill_defaults=False so omitted fields keep llama-server's own defaults rather than this schema's, and mapping repetition_penalty to llama-server's repeat_penalty key. Regression: test_fill_recommended_sampling_completions_body and _operator_pin.

Copy link
Copy Markdown
Member

Useful model-quality improvement, but a few gaps remain: pins are ignored with an existing server, /v1/completions bypasses them and huge integer overrides can error. The default.yaml behaviour also needs clarifying, and CI is still pending.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 24, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 24, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: d8965a2b93

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 629cc50 into main Jul 24, 2026
48 of 53 checks passed
@danielhanchen
danielhanchen deleted the unsloth-recommended-sampling branch July 24, 2026 03:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants