Repository navigation
Studio: build the MCP catalog once per loaded-tool lookup and price the listing off the event loop - #18486
Merged
Conversation
…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.
Member
Author
|
@codex review |
Codex Review Summary: ❌ FailedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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
marked this pull request as ready for review
November 20, 2026 12:20
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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=1and any catalog too big to list in full (over 10% of the context window). The lookup isToolLoopController.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 opensstudio.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_searchresults 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_listingprices the listing, the search declaration and each preloaded tool withcount_chat_tokens. That is a synchronous HTTP call to llama-server on every cache miss.Change
core/inference/tools.py: a newmcp_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 themcp__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_specsboth use it, and they keep their order and duplicates.prepare_callstill looks up its single name.get_enabled_mcp_tools: the listing tail now runs inasyncio.to_thread, ascached_mcp_toolsalready does for the count route. Discovery, the on-loop re-read and the cache writes stay where they were.Results
Real
studio.dbwith N cached tools spread over HTTP servers (10, 12 and 30 tools per server). Median of 7 repeats, max minus min in brackets.mainwas run twice as an A/A.active_tools(include_deferred=True)with k loaded tools: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.On a warm count cache,
mainblocks 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 unknownmcp__name and a non-MCP name, builds the catalog once and returns the same specs as the single-name lookup (fails onmain, which builds it 8 times).mcp_tool_searchresult specs: one build, with order and duplicates kept (fails onmain).main).Equivalence,
mainvs 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 throughmcp_tool_specand_mcp_tool_spec, andactive_toolswith and without deferred tools and with and withoutmcp_tool_searchover 4 loaded sets. It also covers_mcp_tool_search_specswith duplicates and bad lines,prepare_callloading a deferred tool, theget_enabled_mcp_toolslistings 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.pyand others): onmain, 6169 passed and 171 skipped. Three of these tests stubbed the per-name_mcp_tool_spec/mcp_tool_specand 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.