Skip to content

Studio: say a chat is too long on safetensors models - #15616

Merged
danielhanchen merged 2 commits into
unslothai:mainfrom
NilayYadav:safetensors-prompt-too-long
Oct 28, 2026
Merged

danielhanchen merged 2 commits into
unslothai:mainfrom
NilayYadav:safetensors-prompt-too-long

Conversation

@NilayYadav

Copy link
Copy Markdown
Collaborator

On a safetensors model, a prompt longer than the Context Length was sent to the model anyway. Generation crashed with a tensor size mismatch, and every client only saw "An internal error occurred": the Studio chat, the OpenAI-compatible API, and the Anthropic-compatible API. A coding agent that compacts its conversation on "Prompt is too long" got an api_error instead, so it retried the same request and never compacted.

Such a prompt is now refused before generation with the same context refusal MLX and GGUF models give. The Studio chat shows "Message too long: N tokens exceeds the M-token context window" with the usual advice, the OpenAI-compatible API returns a 400 context_length_exceeded, and /v1/messages streams report "Prompt is too long". Prompts that fit run exactly as before.

@NilayYadav NilayYadav self-assigned this Oct 27, 2026
@NilayYadav

Copy link
Copy Markdown
Collaborator Author

Review + reproduction evidence

Pinned review: cd5b5bb627474677d23f7483446265eda9c6bbbb. No blocking findings. Two pre-existing gaps are left for a follow-up: image and audio-input chats still miss this check, and /v1/messages returns the refusal in the wrong shape on its server-tool and non-streaming paths.

I reproduced an over-length chat on a safetensors model (SmolLM2-135M-Instruct, Context Length 256, a 2177-token prompt) on the merge base c4f9de9 (Linux, NVIDIA L4, Chromium 1280x860):

  • Before: the chat shows one stray token, "Response interrupted." and "An internal error occurred.". /v1/chat/completions returns 500 api_error "An internal error occurred." (streams send one token, then the same error), /v1/messages returns 500 api_error (stream: one token, then api_error). Server log: The size of tensor a (256) must match the size of tensor b (2178) at non-singleton dimension 3.
  • PR head: the chat shows "Message too long: 2205 tokens exceeds the 256-token context window. Try increasing the Context Length in Model settings, or shorten the conversation." with no token. /v1/chat/completions returns 400 context_length_exceeded (param: messages), streams send the same error before any content, and the /v1/messages stream sends invalid_request_error "Prompt is too long. Try increasing the Context Length in Model settings, or shorten the conversation.".

PR 15616 before/after

  • A 54-token prompt gives a normal reply on both sides on all six request shapes (/v1/chat/completions and /v1/messages, stream and non-stream, and the chat UI).
  • Prompts of exactly the window (256 of 256) and one under still generate on both sides, so the strict > boundary is right.
  • test_generate_stream_refuses_a_prompt_longer_than_the_window fails on the merge base and passes on the PR (20 other tests unchanged). The added check costs 0.2 us once per request.

Conclusion: real and fixed for text chats on safetensors models; fitting prompts are unchanged. Image and audio-input chats still need the same guard in a follow-up.

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

Review + reproduction evidence (updated for 5b92241)

Pinned review: 5b9224162. One finding, fixed in 5b92241. This replaces my earlier comment, which said there were no blocking findings.

Finding (fixed): the first version refused every prompt longer than the loaded Context Length, but only the fast Llama path (Llama, Mistral, Qwen2/Qwen3, Gemma/Gemma 2, Granite, Cohere, Falcon H1) actually breaks there, because its forward cuts the input at max_seq_length. Models that load through the generic path (Gemma 3, gpt-oss, Qwen3.5, vision checkpoints used for text) generate past it just fine today, and nothing trims safetensors chats first. With Context Length 256 and a 2154-token prompt, Gemma 3 270m answered on the merge base and got "Message too long" on cd5b5bb. 5b92241 raises the refusal only when the loaded model runs that fast forward (checked once per model).

Same prompt (about 2.2k tokens), Context Length 256, merge base c4f9de9 vs 5b92241 (Linux, NVIDIA L4, Chromium 1280x860):

  • SmolLM2-135M (fast Llama path), before: the chat shows a stray token, "Response interrupted." and "An internal error occurred."; /v1/chat/completions 500 api_error, streams send one token then the same error, /v1/messages 500 api_error. Server log: The size of tensor a (256) must match the size of tensor b (2178).
  • SmolLM2-135M, PR head: "Message too long: 2208 tokens exceeds the 256-token context window. Try increasing the Context Length in Model settings, or shorten the conversation." with no token; 400 context_length_exceeded (param: messages), streams error before any content, and the /v1/messages stream sends invalid_request_error "Prompt is too long. Try increasing the Context Length in Model settings, or shorten the conversation.".
  • Gemma 3 270m, before and PR head: a normal reply in the chat and 200 on all request shapes (2154 prompt tokens), same as the merge base.

PR 15616 before/after

  • A 54-token prompt replies normally on both sides on all six request shapes (/v1/chat/completions and /v1/messages, stream and non-stream, and the chat UI).
  • Prompts of exactly the window (256 of 256) and one under still generate on the fast Llama path, so the strict > boundary is right.
  • test_generate_stream_refuses_a_prompt_longer_than_the_window fails on the merge base and passes on 5b92241; the new test_generate_stream_lets_a_stock_forward_model_run_past_the_window fails on cd5b5bb and passes on 5b92241; the other 20 tests are unchanged.

Conclusion: real and fixed for text chats on safetensors models that crash past the window, with no change for models that already handled long prompts. Two pre-existing gaps are left for a follow-up: image and audio-input chats still miss this check, and /v1/messages returns the refusal in the wrong shape on its server-tool and non-streaming paths.

@danielhanchen danielhanchen self-assigned this Oct 28, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 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 ⚠️ Failed 2026-10-28T06:08:07.405789Z
We couldn’t complete this review. Comment @codex review to try again.
5b92241 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

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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 added a commit that referenced this pull request Oct 28, 2026
…helper (#15679)

## Summary

`Repo tests (CPU, gloo)` has failed twice with every rank dying before
the test starts:

```
torch.distributed.DistNetworkError: The server socket has failed to listen on any local network address. port: 45095, useIpv6: false, code: -98, name: EADDRINUSE
AssertionError: rank exit codes [1, 1]
```

- #15616:
`tests/test_tp_native_gloo.py::test_sharded_loading_matches_full_load[phi3-2-None]`
- #15632: `test_tp_x_fsdp2_refuses_trainable_head_norms`, port 42541,
also in `tests/test_tp_native_gloo.py`

#14334 fixed this race by adding `tests/_rendezvous_port.free_port()`:
- It draws MASTER_PORT from below the kernel's ephemeral range
(32768-60999 on Linux), in a slice per xdist worker.
- So neither another worker nor an outgoing gloo connection can take the
port between the test releasing it and rank 0 listening on it.

That PR moved 21 tests onto the helper, but 15 distributed tests still
pick their port with `bind(("127.0.0.1", 0))`,
`tests/test_tp_native_gloo.py` among them. Both failing ports above are
inside the ephemeral range.

## Change

- **14 test files:** their local `_free_port()` now delegates to
`tests._rendezvous_port.free_port()`, the same three lines the other 21
files use, and their now-unused `socket` imports are dropped:
- `test_tp_native_gloo.py`, `test_pp_native_gloo.py`,
`test_pp_fsdp2_gloo.py`, `test_parallel_general_gloo.py`
- `test_moe_dw_accumulate.py`, `test_ddp_find_unused_default.py`,
`test_ddp_comm_defaults.py`
- `test_fast_inference_torchrun_agreement.py`,
`test_cudnn_sdpa_grad_layout_dtensor.py`
- five under `tests/python/`: block compile DDP, GRPO DDP sync, plain
trainer DDP, sentence transformer DDP and FSDP2 save
- **`tests/test_token_budget_batches.py`:** the inline `bind(0)` before
`MASTER_PORT` now uses the helper.
- **`tests/test_rendezvous_port_everywhere.py`** (new): any test outside
`tests/studio` that sets up a torch rendezvous (`MASTER_PORT`,
`master_port`, `init_process_group` or `TCPStore`) must either define
`_free_port` through the helper or not bind port 0 at all.
- Studio tests are out of scope: their ports are for HTTP servers they
start themselves.
- It includes self-tests for both shapes of the mistake, and a check
that the helper stays below the ephemeral range for several worker ids.

## Testing

- **`tests/test_rendezvous_port_everywhere.py`:** 6 passed.
- **Sabotage:** with `tests/test_tp_native_gloo.py` and
`tests/test_token_budget_batches.py` restored from main, the guard fails
and names both files.
- The 14 converted files plus `tests/test_token_budget_batches.py` and
the new guard, under `-n 4`: 243 passed, 2 skipped. On main the same 14
files plus `test_token_budget_batches.py` (without the guard): 237
passed, 2 skipped.
@danielhanchen
danielhanchen merged commit 02a98b0 into unslothai:main Oct 28, 2026
36 of 43 checks passed
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