Skip to content

Studio: build the MCP catalog once per loaded-tool lookup and price the listing off the event loop - #18486

Merged
danielhanchen merged 2 commits into
mainfrom
perf/r36-mcp-catalog-once
Nov 20, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
perf/r36-mcp-catalog-once

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

In MCP search mode, a tool loop looks up the full spec of every MCP tool it has loaded. This covers UNSLOTH_STUDIO_MCP_SEARCH_ONLY=1 and any catalog too big to list in full (over 10% of the context window). The lookup is ToolLoopController.active_tools(include_deferred=True), called on every GGUF tool round (llama_cpp.py), on every external transport turn and on every executed call (studio_tool_loop.py). Each name went through _mcp_tool_spec -> tools.mcp_tool_spec, and each of those rebuilt the whole catalog through _cached_mcp_catalog(). That opens studio.db, lists every server, re-resolves the managed rows (the Blender launch path, the Unreal token file), and builds every server's specs again (public_tool, _mcp_tool_names, note_mcp_tool). It then keeps one spec and throws the rest away. With 10 loaded tools, every round rebuilt the catalog 10 times. mcp_tool_search results went through the same per-name path.

There is also a separate problem in get_enabled_mcp_tools, which a send awaits. Its tail builds the specs and runs _mcp_listing, and that tail ran on the event loop. When the catalog does not fit, _mcp_listing prices the listing, the search declaration and each preloaded tool with count_chat_tokens. That is a synchronous HTTP call to llama-server on every cache miss.

Change

  • core/inference/tools.py: a new mcp_tool_specs(names) returns {name: spec} from a single _cached_mcp_catalog() build. If two specs share a name, the first one wins, which matches the old linear scan. Names without the mcp__ prefix never trigger a build. mcp_tool_spec(name) now calls it. Nothing is cached between calls, so an edit is still seen by the next lookup.
  • core/inference/tool_loop_controller.py: _mcp_tool_specs(names) makes one batch lookup and then neutralizes each spec on its own, as before. active_tools(include_deferred=True) and _mcp_tool_search_specs both use it, and they keep their order and duplicates. prepare_call still looks up its single name.
  • get_enabled_mcp_tools: the listing tail now runs in asyncio.to_thread, as cached_mcp_tools already does for the count route. Discovery, the on-loop re-read and the cache writes stay where they were.

Results

Real studio.db with N cached tools spread over HTTP servers (10, 12 and 30 tools per server). Median of 7 repeats, max minus min in brackets. main was run twice as an A/A.

active_tools(include_deferred=True) with k loaded tools:

N tools k main main (A/A) this PR speedup
30 5 3.95 ms (0.27) 4.32 ms (0.44) 0.81 ms (0.09) 4.9x
30 10 7.02 ms (3.22) 4.99 ms (0.33) 1.02 ms (0.16) 4.9x to 6.9x
30 20 10.02 ms (2.46) 9.85 ms (0.46) 1.48 ms (0.19) 6.8x
96 5 4.16 ms (0.23) 4.13 ms (0.14) 1.26 ms (0.45) 3.3x
96 10 8.45 ms (1.25) 8.50 ms (0.82) 1.51 ms (0.56) 5.6x
96 20 16.74 ms (0.29) 16.99 ms (0.72) 1.91 ms (0.17) 8.8x
300 5 9.67 ms (4.34) 8.51 ms (0.38) 2.37 ms (0.18) 3.6x to 4.1x
300 10 17.19 ms (0.97) 17.55 ms (11.43) 2.77 ms (0.25) 6.2x
300 20 36.50 ms (2.89) 35.89 ms (3.25) 2.99 ms (0.14) 12x

One catalog build (_cached_mcp_catalog()) costs 0.8 ms at 30 or 96 tools and 2.5 ms at 300. A round now pays roughly one build instead of k.

Event-loop blocking in get_enabled_mcp_tools: a 1 ms heartbeat task runs during the call, and the table shows its largest gap. The token counter is stubbed with a fixed delay per uncached text to stand in for the llama-server round trip. Search mode was on with a query set, giving 8 counter calls on a cold cache. Median of 7.

N tools ctx counter delay main this PR
30 8192 3 ms 29.5 ms 3.9 ms
96 16384 3 ms 27.7 ms 2.0 ms
96 32768 3 ms 27.5 ms 4.6 ms
300 32768 3 ms 30.5 ms 4.1 ms
96 16384 1 ms 12.1 ms 2.0 ms

On a warm count cache, main blocks for 2 to 6 ms. Most of what remains after this change is the worker thread holding the GIL while it builds the JSON.

Tests

New tests/test_mcp_catalog_built_once.py:

  • active_tools(include_deferred=True) with 8 loaded tools, plus an unknown mcp__ name and a non-MCP name, builds the catalog once and returns the same specs as the single-name lookup (fails on main, which builds it 8 times).
  • No deferred tools: no build.
  • mcp_tool_search result specs: one build, with order and duplicates kept (fails on main).
  • Disabling a server is seen by the next lookup.
  • The listing's token counter runs off the event-loop thread (fails on main).

Equivalence, main vs this PR, compared as a byte-identical JSON dump. The matrix has two servers with the same display name and the same raw tool names, a duplicate raw name, an empty name, a name long enough to need an alias, markup in a description, an app-only tool, a disabled server, an uncached server, a stdio server, managed Blender and Unreal rows (the Unreal row reads its token file), and the Unsloth Studio tools row. The dump covers every catalog name plus unknown and non-MCP names through mcp_tool_spec and _mcp_tool_spec, and active_tools with and without deferred tools and with and without mcp_tool_search over 4 loaded sets. It also covers _mcp_tool_search_specs with duplicates and bad lines, prepare_call loading a deferred tool, the get_enabled_mcp_tools listings at 4 context sizes (full, search-only and preloaded) with and without stdio and with a server subset, and the alias table.

30 MCP and tool-loop test files (test_mcp_*, test_tool_loop_controller.py, test_studio_tool_loop.py, test_llama_cpp_tool_loop.py, test_external_tool_result_fits_window.py, test_account_tool_isolation.py, test_blender_managed.py, test_editor_mcp_managed.py and others): on main, 6169 passed and 171 skipped. Three of these tests stubbed the per-name _mcp_tool_spec / mcp_tool_spec and now stub the batch functions instead, with the same any-name behaviour. With that change, this PR passes the same set plus the new file.

…he listing off the event loop

active_tools(include_deferred=True) and mcp_tool_search results looked each
loaded tool up with its own full catalog rebuild (studio.db read, managed row
resolve, every server's specs). Look them all up from one build. The MCP
listing tail of get_enabled_mcp_tools, which can make several synchronous
token-count calls to llama-server, now runs in a worker thread.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

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

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-20T12:20:53.914230Z
We couldn’t complete this review. Comment @codex review to try again.
f2f5a62 Draft marked ready
ℹ️ 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: Didn't find any major issues. Breezy!

Reviewed commit: f2f5a628c8

ℹ️ 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 Nov 19, 2026
)

## Summary

`Repo tests (CPU, studio)` fails on `main` (seen on #18486, which only
touches the Studio tool loop):

```
FAILED tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe
E   AssertionError: these skip guards read a probe tests/_zoo_aggressive_cuda_spoof.py patches to True process-wide, ...
E       test_inductor_triton_wrapper_eager_vals.py:82: torch.cuda.is_available()
```

Reproduced locally on `main` at `3bf013b163`.

## Root cause

#18472 added `tests/test_inductor_triton_wrapper_eager_vals.py`, whose
GPU test is gated on `torch.cuda.is_available()`.
`tests/_zoo_aggressive_cuda_spoof.py` patches that probe to `True`
process-wide, so on a CPU runner the test un-skips and tries to compile
a Triton kernel whenever it shares a pytest session with the spoofing
suites. The existing guard caught it; the fix in #18472 itself is
unaffected.

## Changes

- The skip now gates on `has_real_cuda()` first (`not has_real_cuda() or
not torch.cuda.is_available()`), the form the guard recognises and the
other CUDA-only tests use.

## Testing

- `pytest tests/test_inductor_triton_wrapper_eager_vals.py
tests/python/test_accelerator_skip_guards.py`: 25 passed, 1 skipped (the
GPU test, on this CPU host); the guard fails on `main` with the error
above.
danielhanchen added a commit that referenced this pull request Nov 19, 2026
…get scope, classifier DDP default (#18499)

## Summary

PEFT 0.22.0 was released today, and CI installs the latest PEFT, so
every PR now fails several shards (seen on #18486, #18487 and others):

- `Repo tests (CPU, gloo)`, `gloo-tp`, `gloo-tp-env`: tensor parallel
parity tests, e.g. `test_qwen4exp_parallel_matches_one_process[tp2]`,
`test_deepseek_v41_parallel_matches_one_process[tp4]`,
`test_tp2_matches_one_process[llama]`. The saved adapter is missing
keys, or is empty.
- `Repo tests (CPU, rest)`:
`test_peft_moe_linear_targets.py::test_regex_keeps_its_scope`.
- `Repo tests (CPU, rest-2)`:
`test_ddp_find_unused_default.py::test_sequence_classification_head_defaults_to_false`
and `..._trainable_embeddings_default_to_false`.

All of them pass with PEFT 0.21.2 and fail with 0.22.0 on `main`,
locally. These are not test problems: each one is a real behaviour
change for users on PEFT 0.22.

## Root causes and fixes

### 1. Tensor parallel `save_pretrained` drops every sharded LoRA factor
(`tp_native.py`, `pp_native.py`)

`_peft_state_dict` asks PEFT which entries to save by passing the
model's state dict and matching PEFT's selection back by tensor
identity, then gathers the selected DTensors itself (`_full`, which also
puts fused tensor parallel layouts back in their 1-GPU order).

PEFT 0.22 now gathers selected DTensors inside
`get_peft_model_state_dict` (`_gather_state_dict_for_save`), returning
new plain tensors. None of them match by identity, so every sharded
factor was silently left out. Only replicated tensors survived, and the
adapter written by `save_tp_adapter` was partial or empty.

Fix: PEFT now selects over each DTensor's local shard (`to_local()`),
which it does not gather, and each selection maps back to its key. The
gather and fused-layout handling stay in Unsloth as before. The pipeline
parallel adapter gather (`adapter_state_dict` in `pp_native.py`) had the
same exposure for FSDP2 / tensor parallel stages: PEFT's own gather
would skip the fused-layout lookup. It gets the same change. On PEFT
0.21 both paths behave exactly as before.

### 2. A regex `target_modules` loses its scope on MoE models
(`import_fixes.py`)

PEFT 0.22 rewrote the v5 MoE target conversion so that dense Linears
that share an expert name keep LoRA (what #12281 patched in for older
PEFT). It converts a regex `target_modules` to the bare leaf names it
resolves to, so a regex scoped to one layer's projections, e.g.
`model\Wlayers\W1\Wmlp\Wshared_experts\W(gate_proj|up_proj|down_proj)`,
now puts LoRA on every layer's `gate_proj` / `up_proj` / `down_proj`.
PEFT's own code carries a TODO noting it "may match too broadly if only
specific layers are targeted".

Fix: after conversion, a bare leaf target that names only Linears, some
of which the regex did not match, goes back to exactly the module names
the regex matched. Parameter targets and `all-linear` are untouched.

### 3. DDP `find_unused_parameters` default for sequence classification
(`_ddp_defaults.py`)

PEFT 0.22 adds DistilBERT's `pre_classifier` to the default SEQ_CLS
`modules_to_save` (`classifier`, `score`, `pre_classifier`). Unsloth's
list of classifier heads that run every forward was `("score",
"classifier")`, so a plain classifier LoRA no longer counted as safe and
DDP fell back to `find_unused_parameters=True`, which crashes reentrant
checkpointing ("ready only once"). `pre_classifier` runs every forward
too, so it joins the list.

## Testing

| | PEFT 0.21.2 | PEFT 0.22.0 |
|---|---|---|
| `main` | passes | 5 tensor parallel parity cells, the regex scope test
and 2 DDP default tests fail (the CI failures) |
| this branch | 336 passed, 9 skipped | 336 passed, 9 skipped |

The 336 cover the tensor and pipeline parallel gloo set
(`test_qwen4exp_parallel_gloo.py`, `test_parallel_deepseek_v41_gloo.py`,
`test_tp_native_oracle.py`, `test_tp_kv_replicated_gloo.py`,
`test_pp_fsdp2_gloo.py`, `test_pp_native_gloo.py`,
`test_pp_env_gloo.py`, `test_pp_schedules_gloo.py`,
`test_frozen_table_tp_gloo.py`, `test_frozen_table_pp_gloo.py`),
`test_ddp_find_unused_default.py`, `test_peft_moe_linear_targets.py` and
`tests/version_compat/test_peft_conversion_symbol_backfill.py`. The
existing parity tests are the guard: each compares the saved adapter and
the LoRA targets with a single-process reference, and they fail on
`main` under PEFT 0.22.0.
@danielhanchen danielhanchen self-assigned this Nov 20, 2026
@danielhanchen
danielhanchen marked this pull request as ready for review November 20, 2026 12:20
@danielhanchen
danielhanchen merged commit 290707f into main Nov 20, 2026
@danielhanchen
danielhanchen deleted the perf/r36-mcp-catalog-once branch November 20, 2026 12:20
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.

1 participant