Skip to content

Apply the context length and quant settings when attaching to a running server - #10093

Merged
danielhanchen merged 17 commits into
unslothai:mainfrom
NilayYadav:start-attach-load-knobs
Sep 1, 2026
Merged

danielhanchen merged 17 commits into
unslothai:mainfrom
NilayYadav:start-attach-load-knobs

Conversation

@NilayYadav

Copy link
Copy Markdown
Collaborator

If Unsloth is already running and you want a bigger context window, this does nothing at all:

unsloth start --context-length 32768 --gguf-variant UD-Q8_K_XL

No reload, no warning, no error. The model keeps running with its old settings and the command
prints its ready message as if the flags had worked.

Add --model and the same flags are applied properly. The settings were only being read when
a model was named on the command line.

This reads the model that is already loaded and uses the same reload path, so the flags now
work either way. The server still answers "already loaded" when nothing actually changed, so a
second session attaching with the same settings does not restart anything.

Running unsloth start with no flags still attaches without touching the model.

How to check: with a model already loaded, run the command above and confirm the context
length changes.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed that in unsloth_cli/commands/start.py the load knobs are only consulted when a model is named, so attaching with --context-length or --gguf-variant currently has no effect. Will get this reviewed.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

Attaching with --context-length or --gguf-variant and no --model now applies
to the running server, but via the identifier the loader actually holds rather
than the sanitized id /v1/models advertises: _same_loaded_identifier compares a
resident local path exactly, so posting the basename could never dedupe and the
server would try to resolve it as a new model. A native path lease redacts that
identifier, so there we fail before loading instead of guessing.

Keeps the Codex pre-eviction GGUF gate on the inferred target. It is the only
check that runs before the load; _require_gguf_for_codex runs after _connect
returns, so dropping it turned a rejected launch into one that evicted the
shared model first. Warns before a reload that restarts the server for every
attached session, and treats an unprovable comparison as a difference so an
older server does not get a silent restart.

Records which load flags were actually typed, so --context-length 0,
--load-in-4bit and --no-tensor-parallel work as resets. This has to come from
the command's own ctx: Typer invokes callbacks with no active click context,
and it vendors click, so the context returns a typer._click ParameterSource
that is not identical to click.core's. Both mistakes fail silently and look
exactly like a bare attach, so there are tests through the real CLI.

Server side, the non-GGUF already-loaded check now compares the settings it was
sent instead of the identifier alone, and honors force_reload. Only fields the
caller set are compared and an unrecorded value counts as a match, because
every UI call site ships max_seq_length and load_in_4bit on every load whether
or not the user touched them. max_seq_length 0 means model default and never
forces a reload. The values are recorded at the route: the backend entry is
built in the load subprocess and only a fixed model_info mirror crosses back.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-01T05:40:12.769706Z 69b3c1e Manual request
🔒 Security Review ✅ Completed 2026-09-01T04:55:03.778698Z f298ff7 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member

Pushed some changes to this branch. The bug you found is real: I confirmed the load knobs are only consulted when a model is named, so attaching with --context-length did nothing at all. Thanks for catching it.

I reworked the fix a bit, mostly because the premise that the server dedups on settings does not hold for non-GGUF models.

Why the five-line version was not enough

routes/inference.py:13260 takes its non-GGUF already_loaded path on _same_loaded_identifier plus _mlx_runtime_settings_match, and that second one only compares MLX KV bits and the chat template. max_seq_length, load_in_4bit, tensor_parallel and gpu_memory_mode are compared nowhere, so the reload the CLI triggered came back already_loaded and changed nothing. Same silent no-op as before, but now with a success message. The GGUF side was always fine, _runtime_matches_intent compares n_ctx and the rest properly.

The other four points Codex raised also reproduce:

  • /v1/models advertises public_model_id, which strips /srv/models/Foo-Q4_K_M.gguf down to Foo-Q4_K_M. _same_loaded_identifier compares resident local paths exactly, so that basename can never dedupe and the server tries to resolve it as a new model. The load now carries the identifier /api/inference/status reports. A native path lease redacts that field, so there we fail before loading rather than guess a path.
  • preload_check is the only gate that runs before the load. _require_gguf_for_codex runs after _connect returns, so nulling it turned a rejected unsloth start codex into one that evicted the shared model first. It now runs on an inferred target too.
  • The inferred id equals active_id, so neither warning branch fired even though a changed n_ctx really does restart llama-server for everyone. It warns now, and an unprovable comparison counts as a difference so an older server does not get a silent restart.
  • Explicit flags equal to their default are now recorded from the command's own ctx, so --context-length 0 and --no-tensor-parallel work as resets.

Two more things I hit that were not in the review: taking the first loaded row from /v1/models is not necessarily the active chat model, so it uses status.active_model; and _connect passes requested=None after auto-starting a server, so with knobs set the old code reloaded the model it had just loaded.

Worth knowing if you touch this again

Recording the requested settings inside InferenceBackend.load_model does not work. That object lives in the load subprocess and only a fixed model_info mirror crosses back, so the keys never reach the reader. They are stamped at the route instead.

And the explicit-flag tracking cannot use click.get_current_context(): Typer invokes callbacks with no active click context. Typer also vendors its own click, so the context hands back a typer._click ParameterSource that is not identical to click.core's, which means an is comparison matches nothing. Both failures are silent and look exactly like a bare attach, so I added tests that go through the real CLI.

I also did not add the 400 for tensor_parallel/gpu_memory_mode on non-GGUF that I first tried. The chat UI sends gpu_memory_mode outside every isGguf gate and it defaults to "auto", so that rejects every non-GGUF model load in the product. They stay ignored, as before.

Testing

unsloth_cli/tests and the inference backend tests pass with no new failures. Beyond that I ran the attach path against a real HTTP server standing in for each server generation (current, pre-status, and one missing the newer fields), for hub, path-loaded, HF-cache and lease-backed residents, across Windows, macOS, WSL and Linux path shapes including UNC, drive letters, spaces and unicode, and replayed every real /api/inference/load caller body to confirm none of them start reloading. Also checked --context-length 0 and friends on click 8.0 through 8.5, since the pin is click>=8.0.

Known limitations, all noted in comments: max_seq_length 0 means model default so it does not force a non-GGUF reload; the status-to-load race wants a server-side reload_active with an expected-resident token, which is a bigger change than this needs; and the UI still short-circuits via resident-config-match.ts for non-GGUF, so this is a CLI-side improvement until that grows a non-GGUF comparable variant.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 1, 2026

@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: bd8f17d62c

ℹ️ 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 +1815 to +1817
if requested is None and load_has_overrides and infer_resident:
status_snapshot = _inference_status(base, key)
requested, attach_public_id = _resident_load_target(models, status_snapshot, allow_casefold)

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 Guard inferred reloads against resident changes

When another client replaces the resident model after this status snapshot but before _load_model_with_progress, an attach without --model still posts the stale identifier inferred here. _load_model_impl only deduplicates against the model that is current when the POST arrives; if it is now different, it proceeds to reload the stale model, unexpectedly evicting the newer resident and disrupting its attached sessions. Include the expected resident identity/version in the load request and reject the inferred reload when it no longer matches.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not taking this one. The race is real, but it is not introduced here and the proposed fix location cannot close it. Attaching with --model has the same window: _resolve_model reads /v1/models, then posts to /api/inference/load, and another client can swap the resident in between. Closing it properly needs the server to accept an expected-resident identity and answer 409, which is an API change well beyond this PR. A CLI-side re-check before the POST would only narrow the window while adding a failure mode of its own, so it would buy the appearance of safety rather than safety. Tracking it separately as a server-side conditional load.

An inferred attach names the resident by whatever /api/inference/status
reports, which for a GGUF loaded by repo id is the repo id itself. That
carries no quant, and the load endpoint only takes its direct-GGUF path when
the identifier ends in .gguf, so ModelConfig.from_identifier auto-selected
from _GGUF_QUANT_PREFERENCE instead. Changing only the context length could
therefore evict a chosen Q8_0 and download UD-Q4_K_XL. The intent builder
takes hf_variant from the resolved config and never inherits the resident, so
nothing downstream corrected it.

Re-send the quant status reports unless the identifier is a .gguf path, which
loads as itself and is never redirected by a variant. Sending it also puts the
request on the GGUF branch, where a matching context dedupes to a real no-op.
An inferred attach is a full load, not a patch: _gguf_request_intent copies
every defaulted LoadRequest field into the new intent, so a knob left out of
the payload is reset rather than kept. Changing only the context length could
therefore drop the KV cache dtype, slot count, batch sizes, extra args and GPU
placement the model was running with. Carry the resident's own values for the
knobs the user did not name, taking the requested_ variants because those are
what the load was invoked with. A null means never set, so it is omitted
rather than sent, since omitting is what lets the server inherit.

The server cannot tell an explicit --context-length 0 reset from the 0 every
UI load sends, so it reads 0 as no preference and answers already_loaded.
Set force_reload when status PROVED the settings differ, which also makes the
warning we already printed truthful. Not when status is unavailable: there the
comparison cannot conclude anything and forcing would evict on every attach.

Three narrower fixes alongside: GGUF reports load_in_4bit as null because it
has no such setting, which read as a difference and warned about an unload
that would not happen; a status that answers with active_model null is stating
there is no chat resident, so falling back to catalog order there could post a
loaded speech sidecar to the load endpoint, and now it fails with a clear
message instead; and the failed-load survivor probe took its model from
catalog order, so it could report an unrelated first entry as still serving
after the chat model was in fact evicted.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

The round-trip map covered every runtime knob except the one whose LoadRequest
default is not a no-op: load_in_4bit defaults to True, so a non-GGUF resident
loaded at full precision came back quantized when the user changed only the
context length. Status reports the requested value, and it is null on GGUF,
which has no such setting, so the existing drop-nulls rule keeps GGUF loads
unchanged. An explicit --load-in-4bit or --no-load-in-4bit still wins, since
the round-trip only fills knobs the payload does not already carry.
Seven fixes, all in the two mechanisms the previous commits added.

Round-trip: max_seq_length has the same trap load_in_4bit did, defaulting to
0, which _gguf_request_intent copies into n_ctx, so changing another knob
reset a custom context to automatic. Carry requested_context_length too.

Refuse rather than reload when status reports requires_trust_remote_code: the
payload can carry neither the flag nor its approval fingerprint, and the
standard backend tears the worker down before the replacement is accepted, so
a rejected custom-code load would leave nothing resident. Naming the model
with --model still goes through the normal consent path.

Four cases where the difference check saw a change that is not one, each of
which now forces a real restart that applies nothing. tensor_parallel and
gpu_memory_mode are llama.cpp settings the standard load never forwards, so
they no longer count for a non-GGUF resident. A tensor request the
architecture gate normalized to layer mode reports false because it was
applied, not because it was ignored. A paravirtual host pins every placement
request to one runtime, so the raw mode cannot tell two apart; the frontend
resident comparator already skips placement on that flag.

And two where it missed a change that is real. Quant comparison now casefolds
the raw strings instead of stripping separators, so Q4KM against Q4_K_M warns
and forces, matching the preload gate and what the server actually does. Manual
memory mode carries an implicit gpu_layers -1, which reset a pinned layer
count with no warning: switching into manual still asks for automatic layers,
but an attach to a resident already in manual keeps the count it was pinned to.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 2 commits September 1, 2026 04:12
The difference verdict is now computed once and shared. The preload gate, the
warning, the consent refusal and force_reload all key on it, and asking twice
against a snapshot read at different moments is how they drift apart.

The remote-code refusal was unconditional, so a no-op attach to a custom-code
resident was rejected even though nothing would reload. It now applies only
when the settings actually differ.

A proven no-op skips the Codex preload gate: nothing is evicted, so the gate
protects nothing, and running it rejects an attach the disk-free already-loaded
path could still serve, such as a direct .gguf the server has mapped but that
has since moved. A real change still runs it.

Three more comparisons corrected. A CPU fallback is preserved across reloads by
_preserve_cpu_fallback_intent, so like a paravirtual host its raw mode cannot
tell two requests apart, which is why resident-config-match.ts skips placement
on both. An explicit --no-tensor-parallel against an architecture-gated
fallback now counts as a change, because the backend keeps the tensor intent
behind it and does not read a bare false as an explicit drop, so nothing else
could ever clear it. And the round-trip takes mlx_kv_bits_requested rather than
the applied value, which is null when the runtime refused the request and would
have erased what the user asked for.

Finally, a --gguf-variant against a resident loaded from a single .gguf file is
refused: from_identifier consults a variant only for a directory, so posting it
would reload the same file and then label it with a quant that does not
describe its weights.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 1, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits September 1, 2026 04:39
Two of my own guards overlapped: the difference check flagged manual memory
mode with a pinned layer count as a change, while the payload builder had since
been taught to preserve that same count. The request was therefore identical to
the resident and still forced a restart. Manual to manual is a real no-op now;
switching into manual from auto is still a change, since the mode comparison
above already catches it.

Placement was also not surviving a non-GGUF reload. The route stamped only the
requested context and precision, and the parent-side orchestrator entry does not
keep the requested GPU ids, so status reported none and the round-trip omitted
them: a reload for some other knob fell back to automatic selection and could
move the model onto a different GPU. The route now records them and the non-GGUF
status branch publishes them, with a test that fails if any of the three stamped
fields stops being recorded or published.

With no status at all, catalog order is not evidence of which model serves chat.
/v1/models lists loaded speech sidecars, so the first entry can be one, and
posting it to the load endpoint would hand the agent a speech model. An older
server with exactly one loaded model is still answerable; anything ambiguous now
asks for --model instead of guessing.
@chatgpt-codex-connector

Copy link
Copy Markdown

Security review completed. No security issues were found in this pull request.

Reviewed commit: 7acb43c72a

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

The refusal I added for a variant against a single .gguf file did not check
whether the variant actually differed, so restating the quant already running
blocked every other override with it. Naming the running quant asks for no
change, so the inapplicable field is dropped and the rest of the attach
proceeds; only a different quant is still refused, since from_identifier
consults a variant for a directory and could not select it anyway.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: f298ff737e

ℹ️ 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[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
An image model answers status with an active_model like any other, so an agent
attach accepted it as its target: the reload would tear down the diffusion
runtime and then point the coding agent at a model that can never answer it.
It is now treated like no chat resident at all and asks for --model.

_runtime_matches_intent also rejects an identical intent while a spec probe, a
DFlash drafter or a changed speculative binary is waiting to be retried, so the
server reloads whatever the CLI asked for. Equality of the overrides was
therefore no proof of a no-op, and claiming one skipped the preload gate and
printed no warning before a POST that interrupts every attached generation.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for security reviews. Please try again later.

@danielhanchen
danielhanchen merged commit 9aeefd5 into unslothai:main Sep 1, 2026
51 of 52 checks passed

@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: 69b3c1ed04

ℹ️ 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 +2124 to +2126
attach_public_id is not None
and inferred_differs
and status_snapshot.get("requires_trust_remote_code")

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 Protect explicitly named remote-code residents

When --model explicitly names the currently resident non-GGUF model, attach_public_id remains None, so this consent guard is skipped. A context or 4-bit mismatch now reaches the new non-GGUF reload path, but the CLI sends neither trust_remote_code nor an approval fingerprint; the orchestrator terminates the existing worker before the replacement reports the consent failure, leaving every attached session without a model. Query and refuse the same-resident explicit path as well, or provide a way to re-authorize it before teardown.

Useful? React with 👍 / 👎.

Comment on lines +12832 to +12835
if "max_seq_length" in fields_set and int(request.max_seq_length or 0) > 0:
resident = entry.get("max_seq_length_requested")
if resident is not None and int(resident) != int(request.max_seq_length):
return False

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 Preserve unspecified settings before reloading non-GGUF models

When a caller explicitly names the resident non-GGUF model and supplies only max_seq_length, this mismatch now triggers a reload, but the subsequent load uses every other LoadRequest default. For example, unsloth start claude --model <resident> --context-length 8192 against a full-precision resident omits load_in_4bit in the CLI payload, Pydantic supplies True, and the replacement silently becomes 4-bit; the inverse operation can similarly reset a custom context when only precision is supplied. Before returning a mismatch, inherit resident values for fields absent from model_fields_set, as the new inferred-attach path already does.

Useful? React with 👍 / 👎.

Comment on lines +289 to +290
// A safetensors or MLX status reports this too, so the general non-GGUF rule below
// is what keeps this check off those models.

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 Compare non-GGUF context before adopting the resident

When a saved configuration changes maxSeqLength for the already-resident safetensors or MLX model, this rule still excludes the context check solely because status.is_gguf === false. The adoptable shortcut therefore returns true and skips /load, so the new backend comparison never gets a chance to apply the requested context; resolveContextLength already resolves the live maxSeqLength, and the newly populated requested_context_length now provides the resident value needed for this comparison. Allow this specific check for non-GGUF models rather than excluding every non-MLX check.

Useful? React with 👍 / 👎.

Comment on lines +1847 to +1853
if any(
status.get(field)
for field in (
"spec_probe_retry_pending",
"spec_dflash_retry_pending",
"spec_fallback_binary_changed",
)

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 Treat a pending audio probe as an inferred reload

When a GGUF status reports audio_probe_pending: true, _reuse_loaded_gguf deliberately refuses its already-loaded fast path even if every requested setting matches, so posting an inferred attach reloads the server to complete the probe. _load_settings_differ does not include that status flag, causing a matching CLI override to skip the preload gate and the shared-session unload warning before it nevertheless tears down the resident model; the frontend explicitly handles this same condition. Include audio_probe_pending among the states that make the inferred request potentially reloading.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants