Repository navigation
fix(studio): normalize Muse Glimmer's recipient-addressed protocol - #8422
Conversation
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 54a8e00722
ℹ️ 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".
Muse Glimmer addresses each assistant block to a recipient: "self" carries the reasoning, "user" the reply, any other name a tool call. Nothing recognized that protocol, so the chat surfaced the model's whole scratchpad plus its control markup verbatim -- ` to=self<|message|>...<|eom|><|start|>assistant to=user<|message|>4` reached the user instead of a reasoning block and "4". Detect the protocol from the active chat template, as the Gemma thought channel already is, and normalize it with a parser that tracks the recipient of each block rather than one opener/closer pair. Blocks repeat, so reasoning may resume after a reply header and a reply may arrive with no reasoning before it; both now normalize. A block addressed to a tool ends normalization with its markup intact, because the tool-call parser downstream needs to see it. Detection now returns recipient names rather than literal markers, so every construction site goes through a factory that picks the parser for the protocol. The marker-pair parser is unchanged, and so is every protocol that uses it.
54a8e00 to
e43fe96
Compare
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
…d anything Loading an architecture newer than the installed transformers pops the "New model architecture" dialog, which offers to install the latest release. `check_upgrade_for_model` fires whenever a config's `model_type` is absent from every installed overlay and the tier tables, on the premise its docstring states: that is "exactly when today's load would fail with an unrecognized-architecture error". That premise does not hold on MLX. The inference backend is chosen by hardware, and the MLX branch returns before the transformers backend is ever constructed, so mlx-lm and mlx-vlm decide what loads there and transformers only supplies the tokenizer. Muse Glimmer is the case in hand: `muse_glimmer` is absent from transformers 5.5.0's `CONFIG_MAPPING_NAMES`, yet text and vision inference and training all run on it. The offer is not merely redundant on that hardware, it is unactionable -- no transformers version can make an architecture loadable when transformers is not what builds it -- and accepting it costs a minutes-long install for no change. Skip the check on MLX hosts, the same reason GGUF is already skipped one branch above. Every other device is untouched, and a failure to detect hardware falls back to offering the upgrade so a detection problem cannot silence a real one. Deciding this per model instead -- suppressing the offer when mlx-lm or mlx-vlm ships that particular `model_type` -- was tried and dropped: a wrapper whose top-level type MLX ships can still carry a brand-new nested backbone that neither backend can build, so module presence does not establish that the config loads. The tests for this check now pin a device rather than reading the host's, since on Apple Silicon they would otherwise exercise the short-circuit instead of the behaviour they assert.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ea314d8b51
ℹ️ 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".
Three defects in the recipient-addressed normalizer, all the same mistake about which bytes are framing and which are the answer. Whitespace separating two blocks was emitted as content. Downstream that becomes a text run between two reasoning runs, and the UI merges only reasoning that is adjacent, so a single reasoning pass rendered as two thinking sections. A tool-addressed block was forwarded untouched, on the premise that the tool-call parser downstream would read it. Nothing does: TOOL_XML_SIGNALS carries no signal for this protocol, so measured end to end the call was never executed and its markup was streamed to the user as prose. Such a block is now held until it closes and rewritten as a canonical <tool_call>, following the response_template grammar the checkpoint ships rather than the syntax its prompt happens to teach. The turn marker was emitted literally. ReasoningTextIteratorStreamer keeps special tokens and Transformers streams the EOS token before its stopping check fires, so a completed reply could end in visible control markup. Text the model wrote beside its calls is kept in every case, including when the token budget or a cancellation cuts the block short. A call is promoted only when it closed on a completed stream, so cancelling a turn can never be the thing that starts a tool running.
|
Codex Review: Didn't find any major issues. Delightful! 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". |
unslothai#8410 gave the reasoning normalizer a prompt-derived initial channel state while this branch was routing every construction site through a factory that picks the parser for the detected protocol. Both survive: the factory now takes in_reasoning and threads it to the marker-pair parser. The recipient-addressed parser does not take it. prompt_opens_reasoning_channel looks for its opener at the prompt tail, and for this protocol the opener is the recipient name "self", which an ordinary prompt can end on by chance. The template ends every generation prompt at "<|start|>assistant", so the model always writes its own header and this parser always starts between blocks.
Both sides appended to the end of test_transformers_latest.py, so the only conflict was a collision of position rather than of design; the two blocks are kept whole and side by side. The module-scoped autouse fixture that pins a transformers-loading device now also covers main's new transfer-budget tests. None of them reach check_upgrade_for_model or utils.hardware, so the pinned device is inert for them.
|
Confirmed the recipient-addressed blocks are unhandled in chat_template_helpers.py, where detection still only covers the Gemma opener pair, so the scratchpad and tool markup land in displayed content. The direction is right, but this branch also changes check_upgrade_for_model in utils/transformers_latest.py; could you split that out and get the Lint CI job green so the normalizer change can be reviewed on its own? |
The audio path's conflict was two independent edits on adjacent lines: main added the stop-sequence state this path was missing, and this branch had already routed the normalizer through make_reasoning_normalizer. Both are kept. The factory only diverges from ReasoningChannelNormalizer when the first marker is the recipient sentinel, and both default in_reasoning to False, so main's audio behavior is unchanged for every model that reaches it today.
Main grew its own _architecture_cannot_come_from_transformers, keeping the MLX rule this branch added and carving out the one case it got wrong: a bitsandbytes checkpoint that the MLX loader dequantizes through transformers, where the upgrade offer still helps. Main's version supersedes this branch's, so it is taken whole and this branch's duplicate is dropped. Textually the two survived side by side, and the no-argument call ran first, so main's carve-out was unreachable and its two bitsandbytes tests never exercised the branch they name. Both files now match main exactly.
…#8422 - A tool-addressed block with no <atem:invoke> latched passthrough for the rest of the turn, so later reasoning and replies shipped raw control markup. Keep the body as content and carry on parsing. - Derive the header holdback from an explicit recipient bound. A namespaced tool name longer than the old 64-char assumption leaked <|start|>assistant into the chat under token-sized chunking. - Scan a held tool block from where the last scan stopped. A 250KB argument cost 8.2s on the generation thread; it is now 0.7s. - Keep a parameter value as text when it will not re-serialize as JSON. NaN, the infinities and an overflowing 1e400 were emitted as bare tokens, which is not RFC 8259, and deep nesting raised RecursionError instead of falling back. - Drop a held partial header or terminator at end of stream instead of showing it. - Consume CRLF after a reasoning header, not just LF. - Sweep the recipient message key in neutralize_control_markup_in_messages: a recipient-addressed template concatenates it into the header, so a client could forge a system turn with real control tokens (unslothai#7066). - Guard the streamer import in the tests, which backend CI cannot satisfy.
Codex Review SummaryThis 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. |
|
Thanks for this. I went through it in detail, simulated it across the platform and accelerator matrix, and pushed two commits to your branch: a merge of current Before and afterThe issue is real and reproduces on After the PR the same input normalizes to Nothing else breaks
Fixes pushed
Two of your tests asserted the old behaviour and are updated rather than deleted: the call-free block now keeps its body instead of the whole framed block, and a stream cut inside a header no longer shows the fragment. SimulationLabels are honest about what actually ran: spoofing
Coverage included long, unicode and namespaced recipients, truncation at every character of every ATEM tag and of the header, terminators and quotes inside parameter values, CRLF, cancellation at every prefix of a tool turn, and a Gemma differential against the pre-PR normalizer. Two things to know
The remaining red check before my merge commit was entirely the stale base: 19 failures on your head, 0 after merging One thing I left alone deliberately: a literal |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0d899a87c1
ℹ️ 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".
| _ATEM_RECIPIENT_MAX_LEN = 256 | ||
| _ATEM_HEADER_RE = re.compile( | ||
| r"(?:<\|start\|>assistant )?to=(?P<recipient>[^<\s]{1,%d})<\|message\|>" | ||
| % _ATEM_RECIPIENT_MAX_LEN |
There was a problem hiding this comment.
Remove the recipient-length parsing cutoff
When an accepted tool definition has a name longer than 256 characters, Muse emits that full name as the recipient, but this bound prevents _ATEM_HEADER_RE from recognizing the header. Studio accepts tools as an unvalidated list[dict], and neutralize_tool_descriptions does not impose a length limit, so such a catalog can reach this parser; the result is that the native header and ATEM invocation are exposed as assistant text and the requested tool is never executed. Either reject/cap names before advertising them or parse an unbounded recipient incrementally.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Keeping the bound. OpenAI's function-name contract is ^[a-zA-Z0-9_-]{1,64}$, and over-length names are rejected with 'string too long. Expected a string with maximum length 64' (https://community.openai.com/t/openai-badrequesterror-error-code-400-does-not-match-a-za-z0-9-1-64/709823), which is the surface Studio's OpenAI-compatible API mirrors; Studio applies the same 64-char check to composed MCP names in tools.py. 256 is deliberately four times that, so a name that trips this is already one no OpenAI-compatible caller would accept. The alternative you suggest, an unbounded incremental recipient, trades a bounded holdback window for unbounded buffering on a stream that never produces <|message|>, which is a worse failure than the one it removes. Worth noting the bound made this strictly better rather than worse: before it, the window and the regex disagreed and the header leaked at 66 characters.
| if recipient == self._reasoning_recipient: | ||
| output.append(self._buffer[: match.start()]) | ||
| self._buffer = self._buffer[match.end() :] | ||
| output.append(_THINK_OPEN) | ||
| self._in_reasoning = True | ||
| self._skip_opening_newline = True | ||
| elif recipient == self._reply_recipient: | ||
| output.append(self._buffer[: match.start()]) |
There was a problem hiding this comment.
Reserve channel-recipient names in tool catalogs
When the request advertises a valid function named user or self, Muse addresses its invocation to that same name, but these branches always classify the block as reply or reasoning before inspecting its ATEM invocation. Consequently a user call is emitted as raw ATEM prose and a self call is wrapped in <think>, so neither reaches the downstream tool parser. Studio currently accepts and advertises both names, so reject these protocol-reserved names for Muse or disambiguate channel blocks from tool invocations using the body.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The collision is in the checkpoint's own protocol rather than in this parser: its template renders a tool call as 'to=' + tc.function.name, and its system prompt declares '# Valid recipients: "self", .*, "user"', so a function actually named user or self is ambiguous to the model as much as to us. Disambiguating from the body, as suggested, would mean scanning every reply block for ATEM markup, which breaks the reply channel the moment a legitimate answer quotes '<atem:invoke' and turns displayed text into an executable call. That is a worse failure than the one being fixed, and it opens an injection path. Reserving the names is a tool-advertisement policy decision rather than a normalizer change, so it belongs outside this PR if we want it.
…unslothai#8422 - An invocation whose parameter tag never closed was still promoted, so a write_file call ran with its path silently missing and a multi-argument call ran with only the parameters that happened to close. Keep such a call as text instead; a well-formed sibling in the same block still runs. - finish() released a first header that had already reached its <|message|>, such as 'to=user<|mess', because only fragments opening with < were treated as framing. Once <| is present it is no longer ambiguous with prose like 'auto=true', which still survives.
|
@codex review |
1 similar comment
|
@codex review |
…for PR unslothai#8422 Path.read_text() with no encoding uses the platform default, so the guard breaks on Windows the moment one of those modules gains a non-ASCII byte. This is what tests/test_source_read_encoding.py checks for, and it was failing the repo-root CPU test job.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cf6befa5c0
ℹ️ 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".
| if recipient == self._reasoning_recipient: | ||
| output.append(self._buffer[: match.start()]) | ||
| self._buffer = self._buffer[match.end() :] | ||
| output.append(_THINK_OPEN) |
There was a problem hiding this comment.
Suppress an empty reasoning block when only a header arrives
When generation naturally ends immediately after to=self<|message|>—for example because the token budget is exhausted before the first reasoning token—this eagerly emits <think>, and finish() then appends </think>, producing an empty reasoning block and a blank thinking panel. The existing marker-pair normalizer avoids emitting a block when no reasoning text was generated; defer this opener until content arrives or discard it at finish.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The premise does not hold, so leaving this. The claim is that the marker-pair normalizer avoids emitting a block when no reasoning text was generated, but it behaves identically here: feeding ReasoningChannelNormalizer its opener and finishing gives '', and so does opener plus closer with nothing between. Both protocols already agree, so there is no asymmetry to correct. An empty thinking panel is also cosmetic rather than a correctness problem, and deferring the opener would mean holding text back on the far more common path where reasoning does follow.
| _ATEM_HEADER_RE = re.compile( | ||
| r"(?:<\|start\|>assistant )?to=(?P<recipient>[^<\s]{1,%d})<\|message\|>" | ||
| % _ATEM_RECIPIENT_MAX_LEN |
There was a problem hiding this comment.
Recognize the implicit-user final header
Muse's response grammar allows a final block to omit the optional to=user recipient and begin directly with <|message|> after the generation prompt. Because this regex recognizes only explicit to=...<|message|> headers, a valid reply such as <|message|>Hello<|eot|> is normalized to the visible text <|message|>Hello instead of Hello. Treat the recipient-less message header as a reply header when the parser is between blocks.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The grammar says the opposite, so leaving this. In the checkpoint's tokenizer_config.json the content field's open_pattern is literally 'to=user<|message|>', so a bare <|message|> is not a content block to the checkpoint's own parser. The template agrees: the assistant branch does "set recipient = message.get('recipient') or 'user'", so recipient is never falsy and the "if recipient" guard around " to=" cannot take its empty path. There is no implicit-user header to recognise, and accepting a bare <|message|> as a reply header would make any occurrence of that token in ordinary text open a block.
…thai#8422 - A nested invoke opener made the inner closing tag end the outer call, so '<atem:invoke name="danger"><atem:invoke name="safe">...' promoted danger carrying safe's arguments. Malformed output could therefore run a different advertised tool; such a call is kept as text now. - A block terminator arriving with no block open is framing, not content. continue_final_message resumes inside a reply block, so its closing <|eom|> lands between blocks and used to reach the chat. The between-block branch now consumes either terminator, and the boundary holdback keeps a partial of both so the result stays the same however the stream is chunked.
|
Codex Review: Didn't find any major issues. Swish! 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". |
Collapse the multi-line rationales that restate the code they sit above. No code change: verified with comment_tools.py check --strip-docstrings.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 55d07c1147
ℹ️ 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".
| return pieces # the rest of the block is a call still being written | ||
| body = block[opening.end() : end] | ||
| parameters = list(_ATEM_PARAMETER_RE.finditer(body)) | ||
| if len(parameters) != body.count("<atem:parameter") or "<atem:invoke" in body: |
There was a problem hiding this comment.
Reject malformed invocation bodies before promotion
When Muse closes an <atem:invoke> but misspells or emits an unsupported child tag (for example, <atem:param name="path">/tmp/x</atem:param>), both parameters and body.count("<atem:parameter") are zero, so this validation accepts the malformed body and emits an executable canonical call with empty arguments. ToolLoopController.prepare_call treats an allowed canonical call as executable, meaning a tool with optional or default arguments can run even though the model never produced a valid invocation; require all non-whitespace body content to be covered by complete parameter spans before promoting the call.
Useful? React with 👍 / 👎.
Muse Glimmer (
mlx-community/Muse-Glimmer-30B-4bit, supported by mlx-vlm since 0.6.12) addresses each assistant block to a recipient:selfcarries the reasoning,userthe reply, any other name a tool call. Nothing in Studio recognized that protocol, so the chat surfaced the model's whole scratchpad plus its control markup verbatim. Asking "What is 2+2?" put this in the message body:instead of a collapsible reasoning block followed by
4.What changed
The protocol is detected from the active chat template, the same way the Gemma thought channel already is, and normalized by a parser that tracks the recipient of each block rather than a single opener/closer pair.
The pair model does not fit this protocol. Blocks repeat, so reasoning can resume after a reply header and a reply can arrive with no reasoning before it; both normalize correctly now. Headers are held back across chunk boundaries, since generation resumes mid-header after the prompt's trailing
<|start|>assistant.Everything the protocol uses to delimit a block is framing and is consumed: the header, the block terminators, whitespace separating one block from the next, and the terminal turn marker. Markup this parser does not own is still passed through untouched, which remains the neutralizer's job downstream.
Detection returns recipient names rather than literal markers, so every construction site goes through a factory that selects the parser for the detected protocol — including the safetensors streamer and the audio-input path, which would otherwise have treated the literal strings
selfanduseras markup. The existing marker-pair parser is unchanged, and so is every protocol that uses it. A test walks the AST of the inference modules and fails if any site constructs a normalizer directly, which is how the audio-input site was caught when this branch was rebased.Tool calls are translated, not forwarded
A tool-addressed block was initially forwarded with its markup intact, on the premise that the tool-call parser downstream would read it. It does not:
TOOL_XML_SIGNALSincore/inference/tool_call_parser.pycarries no signal for this protocol and no production file mentions it. Measured end to end through/api/inference/chat/completionsagainst the real checkpoint with a tool attached: 0 tool calls streamed, and the entire raw block arrived in displayed content as prose.Such a block is now held until it closes and rewritten into the canonical
<tool_call>{"name": …, "arguments": {…}}</tool_call>form the existing parser accepts. The call syntax comes from theresponse_templategrammar in the checkpoint'stokenizer_config.jsonrather than from the syntax its system prompt happens to teach, because that grammar is what the checkpoint declares as its own parser contract — includingallow_non_jsonvalue parsing, so a prose argument reaches the tool exactly as written, and no enclosing element around repeated invocations, so a bare repeated call parses too.Text the model wrote around its calls keeps its place among them, on the completed path and the cancelled one alike, including when the token budget cuts a block short mid-tag. A call is promoted only when it closed on a stream that was not cancelled, so cancelling a turn can never be the thing that starts a tool running.
Re-measured after the fix on a restarted backend: one call streamed with the correct name and arguments, and empty
content.Validation
Text and image inference, plain chat and a tool-enabled turn, were all run end to end in Studio against the real checkpoint, offline. Reasoning renders as one collapsible block, the answer follows it with no control markup, and a tool turn streams an executable call.
Every added test was mutation-checked: reverting or weakening the production change it covers fails exactly that test, including reverting each individual normalizer construction site. The normalizer is fed token deltas on the transformers path and cumulative-snapshot deltas on the MLX path, so it was also swept whole-string against 1-, 3- and 7-character chunking with no divergence.
Notes for reviewers
<|start|>assistantand the model emitsto=self…. That space is framing and is now consumed. It mattered more than it looks: emitted between two blocks it becomes a content run between two reasoning runs, and the UI merges only reasoning parts that are adjacent, so a single reasoning pass rendered as two separate "Thought for N seconds" sections.<|eot|>was initially passed through, on the premise that generation stops on it so it could only reach the normalizer when a caller replays a whole turn. That is false on the safetensors path:ReasoningTextIteratorStreamerforcesskip_special_tokens=Falseand Transformers streams the EOS token before its stopping check fires, so a completed reply could end in visible control markup. It is now consumed wherever it lands, matching the checkpoint's grammar, which closes a reply on either terminator.utils/transformers_latest.pyor its tests.