Skip to content

Studio: make Stop work while an MLX model is still reading the prompt - #15615

Merged
danielhanchen merged 4 commits into
unslothai:mainfrom
NilayYadav:nothing-during-mlx-prefill-mac
Oct 28, 2026
Merged

danielhanchen merged 4 commits into
unslothai:mainfrom
NilayYadav:nothing-during-mlx-prefill-mac

Conversation

@NilayYadav

Copy link
Copy Markdown
Collaborator

On a Mac with an MLX model, replies that cannot join the shared batch (for example with Tools turned on, a JSON response format or logprobs) ignored Stop until the whole prompt had been read and the first token came out. With a long document in the chat that took many seconds after Stop, and a message sent in the meantime failed with "This thread already has an active generation".

The MLX single-reply path now checks for Stop after every chunk of the prompt, the same way the batched path already does, so a stopped reply ends at once and the next message goes through. The part of the prompt already read stays in the prompt cache, so sending again does not start from zero. Replies that are not stopped run as before.

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

Copy link
Copy Markdown
Collaborator Author

Review + reproduction evidence

Pinned review: 9b4e9506a2f9a833c709aa739b97186529a21fa4. No blocking findings.

I reproduced the flow on an Apple M5 Pro Mac (mlx 0.32.4, mlx-lm 0.32.2, Chromium 1400x900) with mlx-community/Llama-3.2-1B-Instruct-4bit, Tools on, an ~85.6k token prompt: send, press Stop while the prompt is still being read, then send a short follow-up in the same chat. The backend log confirms the reply took the single-reply path on both sides.

  • Before (merge base 739bdfab2): Stop was accepted by the cancel route at 23:29:07.298, but the reply only ended at 23:30:05.177, 57.9 s later, once the whole prompt had been read. The follow-up sent right after Stop got a 409 and the chat showed "This thread already has an active generation" with a Retry button. An earlier run on the same build ended 37.9 s after Stop.
  • PR head (9b4e9506a): cancel at 23:32:33.577, reply ended at 23:32:33.920, 0.34 s later. The follow-up got a 202 and was answered ("ready").

PR 15615 before/after

  • Prompt cache after Stop: sending the same long prompt again in a new chat started with cached=1514 before and cached=16384 after, so the part already read is reused. Both sides then gave the same answer ("COPPER"), so the shorter cached prefix does not change the context the model sees.
  • Tests: test_mlx_stop_during_prefill_ends_the_reply_before_the_prompt_is_read fails on the merge base and passes on head (Linux: 1 FIXED, 354 unchanged; Mac with real MLX: 482 passed on head, and 1 failed / 481 passed with only the fix reverted).
  • Cost when nothing is stopped: on a 30k token prompt, 5 interleaved runs each, prefill was 5704 vs 5621 tok/s and decode 139.5 vs 135.1 tok/s (spread 666 and 29 tok/s), so within noise. The check runs 17 times per 30k token prompt, once per prefill chunk, never per token.

Conclusion: the bug is real on main and this PR fixes it for MLX text models. Vision and audio models (the mlx-vlm path) still finish reading the prompt before honoring Stop; that path is not touched here and is a separate follow-up.

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

Reached Codex review convergence at NilayYadav#901 on 9b4e950.

danielhanchen added a commit that referenced this pull request Oct 28, 2026
…g (pytest 9.2) (#15638)

## Summary


`studio/backend/tests/test_mcp_session_cache_reset_between_tests.py::test_the_next_test_starts_with_an_empty_cache_and_the_session_closed`
has failed on the `(Python 3.13, g-r)` shard of #15587, #15593, #15601
and #15615 (`assert 0 == 1` on `_Session.closed`).

### Root cause

CI now resolves pytest 9.2.0, and pytest-xdist 3.8.0 (the latest
release) does not work with it:
- `--dist loadgroup` keeps an `xdist_group` on one worker by rewriting
`item._nodeid` to `<id>@<group>`.
- pytest 9.2 builds `Item.nodeid` from a structured `_id` instead, so
that write is lost.
- Every grouped test is therefore scheduled like an ungrouped one.

The MCP pair (and the other `*_reset_between_tests` pairs) only hold
when both tests run on the same worker. With `-v`, the first test ran on
`gw0` and the second on `gw3`.

Minimal reproduction:

```python
pytestmark = pytest.mark.xdist_group("g1")
def test_one(): pass
def test_two(): pass
```

`pytest -n 2 --dist loadgroup -v`:
- pytest 9.1.1 reports `test_one@g1` and `test_two@g1`, both on `gw0`.
- pytest 9.2.0 reports `test_one` on `gw0` and `test_two` on `gw1`.

The same pytest release is behind the `torch._dynamo.config.* does not
exist` failures (#15624 pins Backend CI below 9.2 for that; #15626 makes
the suite tolerate it).

## Change

This builds on #15624 (merged), which pins `'pytest<9.2'` in
`studio-backend-ci.yml`, the only workflow that runs `--dist loadgroup`.

- **`version-compat-ci.yml`**: `'pytest>=8'` becomes `'pytest>=8,<9.2'`.
These lanes run the CPU-spoof fixtures that monkeypatch
`torch._dynamo.config`, which pytest 9.2 deletes on undo.
- **`tests/_shared/xdist_group_check.py`**, installed as a `trylast`
`pytest_collection_modifyitems` hook in `tests/conftest.py` and
`studio/backend/tests/conftest.py`:
- On an xdist worker running `--dist loadgroup`, any test that carries
an `xdist_group` mark but whose node id has no `@group` tag now fails
with the reason.
- Before, it would sometimes pass and sometimes fail depending on
scheduling. If the pin is lifted before pytest-xdist catches up, the
grouped tests fail by name with an explanation instead of flaking.
- Raising a usage error at collection time would be swallowed into an
xdist `INTERNALERROR`, so each affected test fails individually instead.
- **`tests/test_xdist_group_check.py`**: unit tests for the check, the
conftest wiring, and both pins (Backend CI from #15624 and
version-compat from this PR).

## Testing

Run on `studio/backend/tests/test_mcp_*.py` with `-n 4 --dist
loadgroup`:
- **pytest 9.1.1:** 2089 passed, twice.
- **pytest 9.2.0:** the MCP pair failed in both runs.
- **Serially on 9.2.0:** 2089 passed, so the failure needs xdist.

With the check in place, the two grouped pair files under `-n 2 --dist
loadgroup`:
- **pytest 9.1.1:** 4 passed.
- **pytest 9.2.0:** all 4 grouped tests fail with "--dist loadgroup did
not tag this xdist_group test ...".

`tests/test_xdist_group_check.py` with
`tests/test_torch_config_guard.py` (from #15626) after merging main: 18
passed.
@danielhanchen danielhanchen self-assigned this Oct 28, 2026
@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 🔄 Running since 2026-10-28T07:46:51.068713Z 7e2c63d 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.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@shimmyshimmer

Copy link
Copy Markdown
Member

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

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 08f7e7a88c (this PR's 7e2c63def)

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

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

Reviewed commit: 08f7e7a88c

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 08f7e7a88c (this PR's 7e2c63def).

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

@danielhanchen
danielhanchen merged commit 500f6db into unslothai:main Oct 28, 2026
16 of 38 checks passed
danielhanchen added a commit that referenced this pull request Oct 28, 2026
#15745)

## Summary

`Repo tests (CPU, rest)` fails on main with three guard failures. It
shows on every staging CI run of recent PRs (#15613, #15615, #15673 and
others), whatever the PR changes:

```
tests/test_rendezvous_port_everywhere.py::test_distributed_tests_take_their_port_from_the_shared_helper
    tests/test_gc_skip_auto_dist_cells.py: _free_port does not use tests._rendezvous_port
    tests/test_gc_skip_auto_dist_gloo.py: _free_port does not use tests._rendezvous_port
tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding[5]
    tests/test_mamba_fused_lora_adapters.py:464: read_text()
tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding[13]
    tests/test_refresh_moved_layer_devices.py:81: read_text()
```

These tests landed around the same time as the guards that now catch
them:
- 570b9b8 added the two `gc_skip_auto_dist` gloo tests with their own
`bind(("127.0.0.1", 0))` port picker. That is the ephemeral-range race
that #15679 moved every distributed test off, which produces
`EADDRINUSE`.
- 986558e and 7f3c5a1 read checked-in source with the platform
default encoding, which breaks on Windows once the file gains a
non-ASCII byte.

The guards are right in all three cases, so the tests change, not the
guards.

## Change

- `tests/test_gc_skip_auto_dist_cells.py`,
`tests/test_gc_skip_auto_dist_gloo.py`: `_free_port()` delegates to
`tests._rendezvous_port.free_port()`, the same three lines every other
distributed test uses. The now-unused `import socket` is dropped.
- `tests/test_mamba_fused_lora_adapters.py:464`,
`tests/test_refresh_moved_layer_devices.py:81`: `read_text(encoding =
"utf-8")`.

## Testing

- `tests/test_source_read_encoding.py` +
`tests/test_rendezvous_port_everywhere.py`: 3 failed on main, 22 passed
with this change.
- The four touched test files under `-n 4`: 43 passed, 4 skipped.
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.

3 participants