Skip to content

Studio: refuse MLX prompts longer than the served context - #16821

Merged
NilayYadav merged 3 commits into
unslothai:mainfrom
Lyxot:fix/mlx-refuse-prompt-past-window
Nov 6, 2026
Merged

NilayYadav merged 3 commits into
unslothai:mainfrom
Lyxot:fix/mlx-refuse-prompt-past-window

Conversation

@Lyxot

@Lyxot Lyxot commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator

Problem

An MLX load in Unsloth Studio did not refuse a prompt longer than its context window. On a load pinned to ~41k tokens, a 152k-token prompt came back as an empty 200 when not streamed. Streamed, the same request spent about 20 minutes in prefill while the cache dropped the earliest part of the conversation. llama.cpp loads refuse the same request up front with a context-size error (HTTP 400).

Root cause

MLXInferenceBackend._check_context_budget runs only when _kv_context_budget is set, and _resolve_kv_policy sets that only for loads with a quantized KV cache. Every other load admitted any prompt:

  • where the cache can be bounded, max_kv_size gives a rotating cache, which silently evicts the start of the prompt during prefill;
  • where it cannot (hybrid models with layers that never rotate), the cache grows past the context the load was asked to serve.

With no free room, generation_budget_for_window fell back to the default budget, so generation still went ahead.

Change

A new _prompt_within_window counts the prompt and raises ContextBudgetExceeded when it leaves no room in the served context (prompt + 1 > window), using the same threshold and error as the existing budget check. It runs whether or not max_tokens is set, on:

  • single requests, through _generation_limit (text, raw completion, vision, audio), and
  • resident batch rows, through _plan_text_row.

The refusal reuses the existing ContextBudgetExceeded plumbing (worker payload → orchestrator → route), so clients get the same typed context error a quantized-KV MLX load or a llama.cpp load already returns.

_kv_context_budget is intentionally not reused for this: setting it also disables batching and makes every vision request prepare its media to count tokens.

Tradeoffs

  • On loads without a KV budget, a prompt with media is still counted at placeholder level, as before. That can under-count images but never refuses a prompt that fits. Counting images exactly would mean preparing media on every request.
  • An explicit max_tokens that runs past the window during decode is unchanged; this PR only covers the prompt.

Validation

New tests in studio/backend/tests/test_mlx_inference_backend.py, each parametrized over an unset and an explicit max_tokens: one covers the text and vision single-request paths, including a cached-prefix prompt that must be counted in full; the other covers batch-row planning. Each production edit was mutated on its own and the matching test failed (6/6).

python -m pytest studio/backend/tests/test_mlx_inference_backend.py studio/backend/tests/test_mlx_load_warm_and_narrow.py -q
# 584 passed

Real models, loaded with a 512-token context and sent a ~2000-token prompt:

Model Cache bound Before After
mlx-community/Qwen3-4B-4bit rotating, enforced admitted (single, explicit max_tokens, batch) refused in under 0.05 s on all three
mlx-community/Qwen3.5-0.8B-4bit (mlx-vlm) not enforceable admitted on all three refused on all three

A short prompt still generates normally on both.

An MLX load only refused an over-length prompt when KV quantization set a per-request budget. Plain loads admitted any prompt: a rotating cache silently dropped its start during prefill, and an unbounded cache ran past the loaded context. Count the prompt against the served context on every single-request and batch-row path and raise ContextBudgetExceeded, matching llama.cpp loads.
@Lyxot
Lyxot requested a review from danielhanchen as a code owner November 5, 2026 16:25
@Lyxot

Lyxot commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 5, 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-11-05T19:25:20.100700Z 14e44e1 Manual request
ℹ️ 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.

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

ℹ️ 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

Copy link
Copy Markdown

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

Reviewed commit: 9205842865

ℹ️ 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".

@NilayYadav NilayYadav self-assigned this Nov 5, 2026
@Lyxot

Lyxot commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

Review and CI status for 9205842

Codex: converged — Didn't find any major issues on 9205842.

CI: upstream jobs were still queued, so the same head and base ran in a staging PR (Lyxot#234, now closed). All green: 16 passed, 2 skipped (Kaggle T4 GPU, which is skipped here too).

Workflow Result
Backend CI ✅ run
Core ✅ run
Lint CI ✅ run
MLX CI on Mac M1 ✅ run
Mac Unsloth UI + API + Update + Inference CI ✅ run
Startup profile ✅ run
Studio VAE seam guard ✅ run
Unsloth API CI ✅ run
Unsloth GGUF CI ✅ run
Unsloth UI CI ✅ run
Wheel CI ✅ run
Windows Unsloth API CI ✅ run
Windows Unsloth GGUF CI ✅ run
Windows Unsloth UI CI ✅ run
Workflow trigger lint ✅ run
studiobench CI ✅ run
Kaggle T4 Unsloth GPU CI (×2) skipped

What changed during review: nothing; the head is unchanged. The one Codex finding (a possible one-token overcount on image-capable checkpoints served through mlx-lm) was answered and resolved without a code change: it only affects a prompt left with room for a single output token, and fixing it would change prompt counting shared with existing budget sizing, which is outside this PR.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 14e44e183d

ℹ️ 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".

@unslothai unslothai deleted a comment from Lyxot Nov 5, 2026
NilayYadav

This comment was marked as outdated.

@NilayYadav

Copy link
Copy Markdown
Collaborator

Review + reproduction evidence

Pinned review: 703c5f7d8. 1 finding, fixed in 14e44e183; no blocking findings remain.

I reproduced an MLX load pinned to a 512-token context receiving a longer prompt on the merge base bfdd8fa (Apple Silicon, macOS, Chromium 1440x900):

  • Before: Qwen3-0.6B-4bit with a 3169-token prompt returns HTTP 200 and 2048 tokens of 精精精..., streamed, non-streamed and with max_tokens: 32. The chat UI shows 4.6k / 512 and a garbage reply. Qwen3.5-0.8B-4bit (cache bound not enforced) admits 3173 tokens and generates 2048 more.
  • PR head: the same requests return 400 context_length_exceeded ("Message too long: 3170 tokens exceeds the 512-token context window...") in 0.02 s; streamed requests get the same error chunk; the chat UI shows the error with Retry. Same on Qwen3.5-0.8B-4bit.

PR 16821 before/after

  • Short prompts and a 17-message history with truncate_oldest (fitted to 371 tokens, context_truncated) behave identically on both sides; image requests on the mlx-vlm batch are unchanged.
  • New tests fail on the merge base and pass on the head (4/4), no other test changes outcome.
  • The only added cost is one extra prompt encode per batched request with an explicit max_tokens, about 43 ms at 32k tokens.

Conclusion: real bug, fixed, pending CI on the final head.

@NilayYadav
NilayYadav merged commit 692fcd6 into unslothai:main Nov 6, 2026
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.

3 participants