Skip to content

Studio: fit the context again when MTP is forced on a reload - #12231

Merged
danielhanchen merged 10 commits into
unslothai:mainfrom
NilayYadav:mtp-reload-context-refit
Sep 29, 2026
Merged

danielhanchen merged 10 commits into
unslothai:mainfrom
NilayYadav:mtp-reload-context-refit

Conversation

@NilayYadav

@NilayYadav NilayYadav commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

When Auto can't fit the MTP drafter, it turns it off and keeps the largest context. Studio then says to pick MTP in Settings to force it at a smaller context. With a saved or custom preset active, doing that reloaded at the same context that was fitted without the drafter, so the model spilled onto a second GPU instead of shrinking the context.

The reload now marks a context that is just the one the last load picked. When a drafter is forced, that context is fitted again the same way a fresh MTP load is, and it can only go down. A Context Length you type is still used as typed, and Auto is unchanged.

Tested on 2x L40S with Qwen3.6-27B-MTP UD-Q8_K_XL (real Studio, saved preset, MTP picked, Reload model):

  • main: 120,064 context split across both GPUs
  • this PR: 91,392 on one GPU, the same as a fresh MTP load, and chat works
  • a typed 110,000 still loads at 110,000 on both
  • with the reporter's GPUs (46 GB + 8 GB): 122,624 on both GPUs -> 100,864 on the big one

This replaces #9572. That PR does not fix the bug: on real GPUs it still loads 120,064 across both cards, exactly like main.

Fixes #9550

Before / after in Studio

Forcing MTP on a same-model reload of the context Auto fitted without the drafter (unsloth/Qwen3.5-4B-MTP-GGUF Q4_K_M, B200 held to about 12 GiB free, 4 parallel slots). Both sides use the same device headroom and the exact /api/inference/load payload the chat UI sends for that reload (max_seq_length = loaded context, max_seq_length_auto_derived = true, speculative_type = mtp). Both sides pass --load-mode auto as advanced arguments because this host's llama-server --help probe was slow.

  • Before (merge base 852795db9): the drafter is loaded at the replayed 79.9k context; Studio's own estimate is 13.80 GiB against about 12 GiB free, which is flagged in the run settings.
  • After (33711e388): the replayed context is re-fitted with the drafter, like a fresh MTP load, and lands at 56.1k with no memory warning.

Before and after: context meter 79.9k vs 56.1k with MTP forced

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

Codex review coverage (run on the mirror NilayYadav#125, since Codex does not answer on upstream PRs):

Round Commit Item Verdict Action
1 5d35973a21 P2: treat replayed contexts as Auto on Metal Not taken On Metal, Auto keeps MTP engaged (the drafter-drop probe only runs in the discrete-GPU layer planner), so the #9550 state is not produced there. Forcing a larger separate drafter after Auto picked MTP behaves the same on main; left for a follow-up.
2 d9c460dae6 P2: keep a -c/--ctx-size passed through extra args Fixed in 6c9ee3f18b The refit is gated on ctx_override is None. Before: pass-through -c 123136 with MTP forced launched at 101,888. After: 123,136.

Also fixed from review in d9c460dae6: when the refit could not place the model at the requested slot count, the load was still treated as a typed context downstream, so the slot re-fit was skipped. On one 45 GB GPU with a drafter whose per-slot state does not fit at 4 slots, a fresh MTP load picks 151,040 at 3 slots, and the replay launched at 8,192 at 3 slots. It now matches the fresh load (151,040 at 3 slots).

Tests: test_llama_cpp_placement.py 205 passed on the current head; each of the two new tests fails without its fix. A Codex round on 6c9ee3f18b is next.

@shimmyshimmer

Copy link
Copy Markdown
Member

Review record for #12231, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#185.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror e5792fb5b (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] (on the mirror)

🛡️ Codex Security Review

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

Reviewed commit: e5792fb5b2

View security finding report

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

No triage reaction was recorded on the mirror

Round 2: reviewed mirror e5792fb5b (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/core/inference/llama_cpp.py (on the mirror)

@@ -25774,6 +25775,22 @@ def _subset_model_size(n_gpus: int) -> int:
                                 # on Auto.
                                 max_available_ctx = min(_AUTO_OFFLOAD_CTX, native_ctx_for_cap)
 
+                        if (
+                            explicit_ctx
+                            and ctx_override is None
+                            and intent.max_seq_length_auto_derived
+                            and _mtp_reserves_gpu
+                            # Forced = anything that bypasses the Auto drop probe, advanced arguments included.
+                            and (
+                                (_canonicalize_spec_mode(speculative_type) or "auto") != "auto"
+                                or _user_mtp_via_extras
+                                or _user_draft_via_extras
+                                or _extra_args_set_spec_type(extra_args)
+                                or _extra_args_mtp_draft_path(extra_args, env = _spec_env)
+                            )
+                        ):
+                            # Fitted without the drafter: size it like a fresh MTP load, slot re-fit included.
+                            explicit_ctx = False

P2 Badge Align duplicate-load matching with the refitted context

When this branch shrinks a replayed positive context, the successful launch still records the original n_ctx in _requested_n_ctx, while the frontend records the smaller returned context and sends that value on the next same-model load. Since _runtime_matches_intent compares the incoming value directly with _requested_n_ctx, reselecting or applying the otherwise unchanged forced-MTP configuration unnecessarily tears down and reloads the model once instead of taking the already-loaded path. Record or compare the effective refitted context for this auto-derived case.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in a4103e1: a re-fitted replay now records the launched context as requested, so re-applying the same settings takes the loaded path.

Round 3: reviewed mirror fbb0f4341 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/core/inference/llama_cpp.py (on the mirror)

@@ -25774,6 +25776,23 @@ def _subset_model_size(n_gpus: int) -> int:
                                 # on Auto.
                                 max_available_ctx = min(_AUTO_OFFLOAD_CTX, native_ctx_for_cap)
 
+                        if (
+                            explicit_ctx
+                            and ctx_override is None
+                            and intent.max_seq_length_auto_derived

P2 Badge Classify replayed contexts before tensor planning

When the same reload also enables Tensor Parallel, the tensor_parallel and tp_gpus branch above runs before this predicate, so _plan_tensor_parallel may shrink effective_ctx without setting _replayed_ctx_refit. The successful launch therefore still records the larger incoming n_ctx; the frontend then replays the smaller reported context and the duplicate-load check unnecessarily reloads once more. Fresh evidence beyond the prior thread is that the follow-up fix is unreachable on this tensor-parallel branch; move the replay classification before the branch or otherwise record its fitted context there.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in 9b99ba6 by the same move: the classification now runs before the tensor-parallel branch, which previously never reached it.

chatgpt-codex-connector[bot] on studio/backend/core/inference/llama_cpp.py (on the mirror)

@@ -25774,6 +25776,23 @@ def _subset_model_size(n_gpus: int) -> int:
                                 # on Auto.
                                 max_available_ctx = min(_AUTO_OFFLOAD_CTX, native_ctx_for_cap)
 
+                        if (
+                            explicit_ctx
+                            and ctx_override is None
+                            and intent.max_seq_length_auto_derived

P2 Badge Reclassify replayed contexts before projector placement

For a vision GGUF with a GPU-resident forced drafter, this replay is still treated as explicit by the earlier mmproj placement probe, which prices the projector at the old, larger context and can move it to CPU. Only afterward does this block turn the request into an Auto-style fit and shrink the context, even though at that smaller context a fresh forced-drafter load could have kept the projector on GPU. This leaves image encoding unnecessarily slower, so the replay classification needs to happen before the projector residency decision.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in 9b99ba6: the replay is classified right after explicit_ctx is set, before the projector probe, so it matches a fresh forced-drafter load (reproduced at 13500 MiB: 35840 with the projector on CPU before, 14336 with it on GPU after).

Round 4: reviewed mirror 1a58a9f82 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/core/inference/llama_cpp.py (on the mirror)

@@ -24961,6 +24963,26 @@ def _cc_split_extra(
                     _draft_cpu_no_embedded = _draft_on_cpu and (
                         _separate_draft_launches or not self._nextn_predict_layers
                     )
+                    # A replayed context was fitted without the drafter: once one is forced, size it
+                    # like a fresh MTP load. Before every explicit_ctx reader (projector probe,
+                    # tensor planner, fit), and on the reserve the Auto-only drop probe cannot clear.
+                    if (
+                        explicit_ctx
+                        and ctx_override is None
+                        and intent.max_seq_length_auto_derived
+                        and _mtp_will_engage
+                        and not _draft_cpu_no_embedded

P2 Badge Refit CPU-offloaded forced drafters too

When a separate drafter is pinned to CPU (for example with --spec-draft-ngl 0) and the previous same-model Auto-context load had speculative decoding off, _draft_cpu_no_embedded is true, so forcing MTP leaves the replayed context classified as explicit. The later _cpu_draft_target_state path still adds context-dependent target rollback and verification-row VRAM to the fit, meaning this load can spill/offload at the old context even though a fresh forced-MTP load would shrink it; CPU placement should remove only the drafter's GPU costs, not skip replay refitting entirely.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in f729413: a CPU-pinned drafter now re-fits too. Reproduced with a hybrid target at 10000 MiB: 17920 with the projector on CPU before, 9728 with it on GPU after, matching a fresh forced load. The target-side cost is flat per slot rather than context-dependent, but the fit still has to shrink the context to make room for it.

Round 5: reviewed mirror c7b244149 (this PR's f729413d7)

chatgpt-codex-connector[bot] on studio/backend/models/inference.py (on the mirror)

@@ -84,6 +84,10 @@ class LoadRequest(BaseModel):
             "(llama.cpp or MLX) choose the context itself."
         ),
     )
+    max_seq_length_auto_derived: bool = Field(
+        False,
+        description = "max_seq_length is the previous load's fitted context, not a user choice",
+    )

P2 Badge Size training admission with the refitted context

When training is active and the replayed window plus the newly forced drafter fails the coexistence budget but a smaller refitted window would fit, the request is rejected before this flag reaches the planner. Both /validate and /load invoke _guard_chat_load_against_training, which sizes request.max_seq_length unchanged at routes/inference.py:15368; moreover, ValidateModelRequest and the validation payload do not carry this marker at all. Thread the auto-derived state through validation and make the admission estimate use the same refit semantics, otherwise Apply still returns 409 in the constrained-VRAM case this change is intended to support.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Not changing this here: main sends the same replayed max_seq_length to the training guard for this load and returns the same 409, so this PR does not regress it. Extending the re-fit to the coexistence estimate means threading the flag through ValidateModelRequest as well, which is a separate change.

Round 6: reviewed mirror c7b2441495 (this PR's f729413d7)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: c7b2441495

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror c7b2441495 (this PR's f729413d7).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 29, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 29, 2026
@danielhanchen
danielhanchen merged commit f160cf5 into unslothai:main Sep 29, 2026
70 of 72 checks passed
Lyxot added a commit that referenced this pull request Nov 19, 2026
…reset (#18379)

## Problem

With Context on Auto, reloading the same GGUF model fitted the context
again only when the active preset was the untouched built-in Default.
Under a saved preset, or after any Run settings edit such as Temperature
(which marks Default as modified), changing the KV cache type, vision or
the GPU set and clicking Reload model kept the old context:

- A change that frees memory (f16 to q8_0 KV) did not grow the context.
- A change that needs more memory (q8_0 to f16 KV) kept the old context
and gave up something else instead. In the run below, the vision
projector moved to the CPU.

## Cause

`resolveLoadMaxSeqLength` (`preset-policy.ts`) returned 0 for an Auto
GGUF load only when `presetSource === "builtin-default"`. Under `custom`
and `modified`, a same-model reload resent `loadedContextLength`, the
context the resident model was fitted to, with
`max_seq_length_auto_derived: true`. The backend treats any positive
`max_seq_length` as explicit. It fits a resent value again only when MTP
is forced, an exception added by #12231 for the MTP case of this bug
(#9550). This PR removes the resend itself.

## Fix

- An Auto GGUF load always sends 0, so a reload is sized like a fresh
load whatever preset is active.
- `isReplayedLoadContext` and the frontend's
`max_seq_length_auto_derived` field are removed. This reload was their
only sender.
- The memory estimate on the model config page follows the same rule.
- The config page's two fixed-layer checks (estimate and Apply) now
treat an unset per-model GPU memory mode as the standing preference, as
`performLoad` does. Without this, with fixed layers and an inherited
Manual mode, the estimate would price a context of 0 while Reload keeps
the resident context.

## Unchanged

- A typed Context Length is still sent as typed.
- Manual GPU memory with fixed layers still keeps the resident context
on a same-model reload (`performLoad`), since `--fit off` would
otherwise launch at the native context.
- Rollback after a failed model switch can still resend the previous
model's fitted context.
- Non-GGUF, MLX and the backend. The backend still accepts
`max_seq_length_auto_derived` from API clients.
- Picking the resident model again after an Auto load still uses it
without a reload.

## Verification

Live A/B through the real UI with Playwright. The same backend served
the `main` and PR frontend builds. The model was
`unsloth/Qwen3.5-9B-GGUF` Q4_K_M on an RTX 6000 Ada with about 10 GB of
VRAM free, so Auto fits below the native context. The `/load` body was
captured in the browser, and the context was read from
`/api/inference/status`.

| Step | `main`, Default untouched | `main`, Temperature edited | PR,
Temperature edited |
|---|---|---|---|
| Load on Auto, f16 KV | 64,512 | 64,512 | 64,512 |
| KV f16 to q8_0, Reload | sends `0`, gets 96,768 | sends `64512`, stays
64,512 | sends `0`, gets 96,768 |
| KV q8_0 to f16, Reload | | sends `96768`, stays 96,768 with
`--no-mmproj-offload` | sends `0`, gets 64,512, projector on GPU |

In the `main` q8_0 to f16 step, the model was already at 96,768 (reached
through the Default path) before the Temperature edit.

Tests:

- `replayed-load-context.test.ts`, which asserted the resend, is
replaced by `auto-context-reload.test.ts`. The new file also covers the
inherited Manual estimate case. The same-model reload cases in
`context-pin-survives-load.test.ts` and the two fixed-layer contract
tests in `test_model_picker_contracts.py` are updated.
- `npm test` has 8 failures, the same 8 as on unmodified `main`, and
none involve this change. `npm run typecheck` passes, and ESLint output
for the changed files is unchanged.
- The Python tests that read the changed frontend files (29 modules,
1,507 tests) pass.

---------

Co-authored-by: Lyxot <[email protected]>
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.

[Bug] AMD: Unsloth Studio drops MTP to fit context, and turning MTP back on doesn't re-fit (W7900 + W7500)

3 participants