Repository navigation
fix(server): recalibrate loop detection and gate the Gemma 4 default-on - #969
Merged
Merged
Conversation
The Gemma 4 family loop-detection default-on from #432 truncates correct answers. With `min_count=4` over pattern sizes 1..=20, a markdown table alignment row trips the detector: `| :--- | :--- | :--- | :--- |` tokenizes as `'|'` (236909) followed by the 3-token block `[' :' 1017, '---' 7243, ' |' 1109]` repeated once per column, so the 4th column fires `detect_repetition_loop` at pattern size 3. Generation ends there, the scheduler finishes the sequence with `FinishReason::RepetitionLoop`, and the client sees a normal stop. Any table with 4 or more columns hits this, as do `!!!!`, divider runs, and other short legitimate repeats. Two changes, both needed to close the hole. `LOOP_DETECTION_RECOMMENDED` goes from `(1, 20, 4)` to `(1, 20, 12)`. The failure modes are asymmetric: a false positive silently truncates a correct answer and is hard to diagnose because the finish looks normal, while a genuine collapse repeats until the token budget is exhausted, so a later stop costs at most `(12 - 4) * 20 = 160` extra tokens. A count of 12 leaves alignment rows up to 11 columns alone. The family default-on is now gated on the request carrying an amplifier: a non-empty `tools` array, or a `json_schema` `response_format` that compiled into a grammar constraint. #432's own reproduction found that plain chat is always clean, so running the detector there bought no protection. `resolve_loop_detection` takes a fourth `request_uses_constrained_decoding` argument and `RequestOptionOverrides` a matching field; `chat::build_generate_options` takes it as an explicit `bool` parameter, since `SamplingParams` carries neither tools nor `response_format` and each of its 10 call sites has to decide for itself. Precedence is otherwise unchanged: explicit per-request override, then `MLXCEL_LOOP_DETECTION` (both its `off` and its `on` / triple forms, neither subject to the gate), then the gated family default, then disabled. Per call site: both chat routes and both Responses routes pass declared tools plus `structured.is_some()`; both Anthropic routes pass tools only, because the translator always sets `response_format: None`; both `/v1/completions` routes pass the grammar signal only, because `CompletionRequest` has no `tools`; the disaggregated chat front passes tools only, because the router never compiles a constraint; the disaggregated completions front and the native `/completion` endpoint pass `false`, because neither can carry either amplifier. `serving_protocol::sampling_from_serializable` was audited and needs no change: it reconstructs a `SamplingConfig`, not `RequestOptionOverrides`, and already leaves `loop_detection` disabled because the field is not on the handoff wire. Tests cover the reproduction stream directly: `[107, 236909]` then `[1017, 7243, 1109]` repeated 4 times must not fire at the new threshold and still does at the old one, alignment rows of 2 through 11 columns stay clean, the same block repeated 12 times still fires, and the single-token collapse boundary moves to 12. The server tests exercise the gate matrix through both `resolve_loop_detection` and `build_server_generate_options`. Validated with `cargo fmt --check` and `cargo clippy --lib --bins --tests -- -D warnings`, both clean, plus `cargo test --release` and `cargo test --release -p mlxcel-core` (the root run does not cover the core crate, where the detector tests live). Three test failures predate this branch and come from the build configuration rather than the change: a GPU-only BitNet kernel test aborting on a CPU-only build, an XLA preprocessor test that needs the `xla-iree` feature, and a CLI help test that expects clap to render `[aliases:` where this clap renders `[alias:`. None of them touch a file in this diff. Refs #967
The gate added in the previous commit counted a non-empty `tools` array regardless of `tool_choice`. That was wrong. The amplifier issue #432 identified is tool declarations in the rendered prompt steering the model toward collapse, and `chat_request::effective_tools` drops the declarations when `tool_choice` is `"none"`, so such a request is prompt-identical to plain chat. Enabling detection for it bought no protection while re-exposing the markdown-table false positive this issue exists to remove, which is the same trade #967 rejects everywhere else. `effective_tools` becomes `pub(crate)` and is now the single source of truth for the tools half of the signal at every chat-shaped call site: both chat routes, both Anthropic routes, both Responses routes, and the disaggregated chat front. Deriving the gate and the template from one helper is what keeps them from drifting: if the rendering rule changes, the gate follows, because the gate's premise is what the model actually sees. Its doc comment now records that it is load-bearing for loop-detection activation. The `/v1/completions` routes, the disaggregated completions front, and the native `/completion` endpoint are unchanged; none of them has a `tools` field. The grammar half is untouched and stays independent of `tool_choice`: a `json_schema` response_format constrains decoding whether or not tools are rendered. New tests cover the four cases through `effective_tools` and serde-deserialized chat requests: `tool_choice: "none"` with declared tools resolves to disabled, absent `tool_choice` and `"auto"` both resolve to the recommended threshold, and `"none"` plus a grammar constraint still resolves to recommended. Also inlines a literal into its format string in `examples/qmm_gemv_microbench.rs`, an unrelated pre-existing `clippy::print_literal` failure under clippy 1.93. It is included only so `cargo clippy --all-targets -- -D warnings`, named verbatim in issue #967's acceptance criteria, passes. Validated with `cargo fmt --check` (exit 0), `cargo clippy --all-targets -- -D warnings` (exit 0, now clean), `cargo test --release --lib` (4763 passed, 0 failed) and `cargo test --release -p mlxcel-core loop_detection` (20 passed, 0 failed). Refs #967
Review follow-ups on the issue #967 gate. No resolution logic changes: precedence, the threshold, and the `tool_choice` semantics all resolve exactly as before. `uses_constrained_decoding` becomes `carries_loop_amplifier`, the `RequestOptionOverrides` field and the `resolve_loop_detection` parameter become `request_carries_loop_amplifier`, and the `build_generate_options` parameter is renamed to match instead of shadowing the imported helper. The old name described only the grammar half, so it invited a future route author to pass `structured.is_some()` alone and silently drop the tools amplifier. Chat-shaped routes now call a new `chat_carries_loop_amplifier(&ChatCompletionRequest, bool)` rather than extracting the tools slice themselves. Taking the whole request removes the failure mode by construction: there is no slice parameter a call site could fill with the raw `request.tools`, which would quietly restore `tool_choice: "none"` to the amplified set. The `/v1/completions` routes keep the low-level predicate with an explicit `None`, since that request type has no tools field. Five route-shaped tests build the options the way each route builds them, from the same request type through the same translator where there is one, and assert the resolved `loop_detection`. The Responses and Anthropic cases cover the translators' `tool_choice` mapping end to end, which nothing previously exercised. The async handlers themselves are still not invoked: `AppState` requires a real `ModelProvider`, so a loaded model, which `routes/cache_tests.rs` already documents as out of scope for unit tests. Documentation corrections. `docs/supported-models.md` contradicted itself, saying the collapse "is not limited to those cases" directly above the new text explaining that unamplified requests get no detector; it now states one position: the defect is upstream in the weights so an unamplified collapse is possible, mlxcel deliberately does not run the detector there because the false-positive cost exceeded the protection, and `MLXCEL_LOOP_DETECTION=on` or the per-request fields are the recourse. Both docs and the `LOOP_DETECTION_RECOMMENDED` comment now state the full cost of the higher `min_count`: a genuine collapse of pattern size `p` runs `8p` tokens longer, and separately a pattern is undetectable when the remaining budget is under `p * 12`, so `thinking_budget_tokens = 128` loses coverage of `p >= 11` where `p * 4 = 44` tokens previously sufficed. The docs also note that the residual risk now sits where the gate is open, and that `json_schema` output is itself prone to legitimate repetition (uniform arrays, repeated separators), so `min_count=12` shrinks that false-positive class without eliminating it. Comment fixes: `router_front.rs` no longer claims the disaggregated front "resolves exactly as the single-node chat route" without qualification, since `serving_protocol::sampling_from_serializable` hardcodes the disabled baseline and the value is inert there today; `native_completion.rs` cited a missing `response_format` field when the endpoint has one and rejects anything but `{"type": "text"}` with a 400; and `loop_detection_tests::server_recommended` names the server-side test that pins the same triple, since the core crate cannot reference the constant. Validated with `cargo fmt --check` (exit 0), `cargo clippy --all-targets -- -D warnings` (exit 0), `cargo test --release --lib` (4768 passed, 0 failed) and `cargo test --release -p mlxcel-core loop_detection` (20 passed, 0 failed). Refs #967
The #967 narrowing lost coverage the #432 unconditional default-on had, on the most common agentic traffic shape. `chat_request::has_tool_fields` routes any request whose messages carry `tool_calls` or `tool_call_id` to the raw-JSON render path, and `build_raw_json_messages_with_thinking` writes those fields into the rendered prompt independently of `effective_tools`. So an agent loop replaying prior tool calls and tool results on a follow-up turn that omits the top-level `tools` array, or sends `tool_choice: "none"` on that turn, feeds Gemma 4 a thoroughly tool-shaped prompt with the detector off. The narrowing was meant to exclude plain chat, and those turns are not plain chat. `has_tool_fields` becomes `pub(crate)` and joins `chat_carries_loop_amplifier` as a third disjunct. The gate now reads: rendered tool declarations, OR tool-shaped message content, OR a compiled grammar constraint. The `tool_choice: "none"` case still resolves disabled when the messages carry no tool fields, which is genuinely plain chat, and that test is unchanged. `effective_tools` reports what is handed to the template, not what the template renders. `render_simple_fallback` drops tools entirely when the Jinja render fails, and a checkpoint whose template ignores its `tools` argument renders none either, so the gate can report amplified for a prompt that is not. Its doc comment now says so and records that the over-approximation is deliberate: erring toward keeping detection on is the safe direction, and the alternative is resolving the gate after rendering. Documentation. Both docs described the gate as keying on tool declarations, which was already incomplete and is more so now; they now state all three disjuncts and say plainly that the test is "the prompt is tool-shaped or decoding is grammar-constrained", not "the request has a `tools` array". The residual false-positive surface is now documented concretely rather than hedged, because it reproduces on hardware. A `json_schema` request for an integer array of 30 zeros returns `{"values": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,` and stops: cut after exactly 12 values, `completion_tokens: 43`, `finish_reason: "stop"`. The document is truncated mid-array, so it is neither valid JSON nor conformant with the schema the client declared. The higher threshold improves this (the same request was cut after 4 values at `min_count=4`) but cannot remove it, since any fixed count is exceeded by a longer legitimate run. The recourse is the per-request `max_pattern_size: 0` escape hatch, which is not subject to the gate. Changing the policy for grammar-constrained decoding would contradict issue #967's Part 2 as filed and needs its own issue. Validated with `cargo fmt --check` (exit 0), `cargo clippy --all-targets -- -D warnings` (exit 0), `cargo test --release --lib` (4771 passed, 0 failed) and `cargo test --release -p mlxcel-core loop_detection` (20 passed, 0 failed). Refs #967
This was referenced Jul 30, 2026
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
…on (lablup#969) ## Summary The Gemma 4 loop-detection default-on added in lablup#432 truncates correct answers. With `min_count=4` over pattern sizes 1..=20, a markdown table alignment row trips the detector: `| :--- | :--- | :--- | :--- |` tokenizes as `'|'` (236909) followed by the 3-token block `[' :' 1017, '---' 7243, ' |' 1109]` repeated once per column, so the 4th column fires `detect_repetition_loop` at pattern size 3. Generation stops there, the scheduler finishes the sequence with `FinishReason::RepetitionLoop`, and the client sees a normal stop with no error. This PR raises the threshold and restricts the family default-on to the requests where the collapse actually happens. ## Part 1: threshold recalibration `LOOP_DETECTION_RECOMMENDED` moves from `LoopDetectionConfig::new(1, 20, 4)` to `LoopDetectionConfig::new(1, 20, 12)`. This constant is also the `MLXCEL_LOOP_DETECTION=on` force-enable value. **Cost of the higher threshold.** The two failure modes are not symmetric. A false positive silently truncates a correct answer mid-sentence and is hard to diagnose, because the wire `finish_reason` is an ordinary `stop`. A genuine Gemma 4 collapse (upstream weights-level defect, google-deepmind/gemma#622) repeats until the token budget is exhausted, so detecting it later mostly just emits more garbage tokens. A count of 12 also leaves alignment rows up to 11 columns alone, which covers every table shape seen in practice. The higher count costs two distinct things, and the second is easy to miss: 1. **Delay.** A pattern of size `p` is now cut after `12p` tokens instead of `4p`, so a genuine collapse runs `8p` tokens longer. That is 8 extra tokens for the single-token (`p = 1`) collapse in this issue's reproduction, and 160 at the `p = 20` ceiling. 2. **Lost coverage under a short budget.** Firing at size `p` now requires `p * 12` tail tokens rather than `p * 4`, so a pattern is undetectable whenever the remaining budget is shorter than `p * 12`. With `thinking_budget_tokens = 128`, patterns of `p >= 11` can no longer be caught, where `p * 4 = 44` tokens previously sufficed. This is not a regression against the known reproduction, which is `p = 1`, but short-budget requests do lose coverage of long patterns. ## Part 2: gate the family default-on The family default-on now requires the request to carry an amplifier. The test is whether the prompt is tool-shaped or decoding is grammar-constrained, not whether the request has a `tools` array, and any one of three things satisfies it: tool declarations that reach the rendered prompt, tool-shaped message content (`tool_calls` or `tool_call_id` on any message), or a `json_schema` `response_format` that compiled into a grammar constraint. lablup#432's own reproduction recorded "no tools in the request: always clean", so running the detector on plain chat bought no protection while costing this entire class of false positives. `RequestOptionOverrides` gains `pub uses_constrained_decoding: bool` (`Default` is `false`, the safe baseline). `resolve_loop_detection` gains a fourth `request_uses_constrained_decoding` parameter, and the family branch becomes `family_default_on && request_uses_constrained_decoding`. The predicate lives in one place, `request_options::uses_constrained_decoding(tools: Option<&[Tool]>, has_grammar_constraint: bool)`, so "non-empty tools" is not re-derived per route. The declarations half is read from `chat_request::effective_tools`, promoted to `pub(crate)`. That is the same helper the chat template uses to decide which tools to render, so `tool_choice: "none"` alone does not count: it renders no declarations, leaving a prompt indistinguishable from plain chat. Reading one helper for both the gate and the template is deliberate; if the rendering rule changes, the gate follows it rather than drifting from what the model sees. The message-content half is `chat_request::has_tool_fields`, also promoted to `pub(crate)`. Without it the narrowing lost coverage that lablup#432's unconditional default-on had, on the most common agentic shape: `has_tool_fields` routes any request whose messages carry `tool_calls` or `tool_call_id` to the raw-JSON render path, and `build_raw_json_messages_with_thinking` writes those fields into the prompt independently of `effective_tools`. An agent loop replaying prior tool calls on a follow-up turn that omits the top-level `tools` array, or sends `tool_choice: "none"` on that turn, therefore gets a thoroughly tool-shaped prompt. Those turns are not plain chat and stay armed. A `tool_choice: "none"` request whose messages carry no tool fields is still plain chat and still resolves disabled. Both halves report what is *handed to* the template, not what the template renders. `render_simple_fallback` drops tools entirely when the Jinja render fails, and a checkpoint whose template ignores its `tools` argument renders none either, so the gate can report amplified for a prompt that is not. `effective_tools` now documents this, and the over-approximation is deliberate: erring toward keeping lablup#432's protection on is the safe direction, and the alternative is resolving the gate after rendering. The grammar half is independent of `tool_choice`. `chat::build_generate_options` takes the flag as an explicit `bool` parameter rather than deriving it: it receives only `SamplingParams`, which carries neither tools nor `response_format`. Making it a required argument forces every call site to make a decision at compile time. ### New precedence order (exact) 1. **Explicit per-request override.** Any of `max_pattern_size` / `min_pattern_size` / `min_count` on the request. Wins over everything, including the gate, in both directions (force-enable and force-disable via `max_pattern_size=0`). 2. **`MLXCEL_LOOP_DETECTION` global override.** Applies to every request unconditionally in both its `off` form and its `on` / `MIN,MAX,COUNT` forms. **Not** subject to the gate. 3. **Gemma 4 family default-on, gated.** Applied only when `model_is_gemma4_family && request_uses_constrained_decoding`. 4. **Disabled.** The precedence order itself is unchanged; only step 3 gained a condition. Step 2 does change value though: `MLXCEL_LOOP_DETECTION=on` resolves through `LOOP_DETECTION_RECOMMENDED`, so an operator who had set `on` now gets `1,20,12` instead of `1,20,4`, a roughly 3x less sensitive detector. Setting `MLXCEL_LOOP_DETECTION=1,20,4` restores the previous value exactly. Steps 1 and 4 are behaviorally identical. ### Call sites touched, and the flag each received | # | Site | Value | Reason | |---|------|-------|--------| | 1 | `routes/chat.rs:407` (non-stream chat) | `uses_constrained_decoding(effective_tools(&request), structured.is_some())` | All three disjuncts available: `chat_carries_loop_amplifier` reads declarations and message content off the request, and `structured` (built at lines 324-340, before this point) supplies the grammar half. | | 2 | `routes/chat.rs:647` (stream chat) | same as above | Same derivation, so both chat surfaces resolve identically. | | 3 | `routes/anthropic.rs:185` (non-stream messages) | `uses_constrained_decoding(effective_tools(&translated.chat_request), false)` | `anthropic_translator` always sets `response_format: None` and this route compiles no constraint, so only the two tool disjuncts can apply. The translator maps `tool_choice` too, so an Anthropic `{"type": "none"}` lands as `Mode("none")` and drops the declarations, but translated `tool_calls` / `tool_call_id` on messages still amplify. | | 4 | `routes/anthropic.rs:313` (stream messages) | same as above | Same reason. | | 5 | `routes/responses.rs:228` (non-stream) | `uses_constrained_decoding(effective_tools(&translated.chat_request), structured.is_some())` | The translator maps `tools`, `tool_choice`, `text.format`, and prior function-call items onto the matching `chat_request` fields; `structured` is the compiled constraint. | | 6 | `routes/responses.rs:351` (stream) | same as above | Same reason. | | 7 | `routes/completions.rs:248` (non-stream) | `uses_constrained_decoding(None, structured.is_some())` | `CompletionRequest` has no `tools`, so only the grammar signal applies. | | 8 | `routes/completions.rs:325` (stream) | same as above | Same reason. | | 9 | `router_front.rs:676` (disaggregated chat front) | `uses_constrained_decoding(effective_tools(&request), false)` | Reads the same `effective_tools` that the `prepare_chat_request_with_cache` call just above used to render the prompt, so this front resolves exactly as the single-node route. The router never compiles a grammar constraint (the `PrefillRequestFrame` cannot carry one), so the grammar half is always false. | | 10 | `router_front.rs:956` (disaggregated completions front) | `false` (literal) | No `tools` field and no chat messages, and the `response_format` guard above already rejects structured output with a 400, so no disjunct can be present. | | 11 | `routes/native_completion.rs:286` (builds `RequestOptionOverrides` directly) | `uses_constrained_decoding: false` | The native `/completion` endpoint accepts neither tools nor `response_format`. The comment there now records that the family default-on no longer reaches this endpoint and that `MLXCEL_LOOP_DETECTION` is the way to enable detection on it. | `batch/xla_worker_tests.rs:144` uses `..RequestOptionOverrides::default()` and needed no change; it picks up `false`. ### Audited, no change needed `distributed/disaggregated/serving_protocol.rs:276` sets `loop_detection: Default::default()` on a `SamplingConfig` reconstructed from the wire mirror, not on a `RequestOptionOverrides`. Loop detection is not part of `SerializableSamplingState`, so the decode node already keeps the disabled baseline regardless of this change. Left as is. A consequence worth stating: the amplifier flag computed at `router_front.rs:676` is **inert today**. `sampling_to_serializable` does not put `loop_detection` on the wire and the reconstruction above hardcodes the disabled config, so no sampler on the disaggregated path ever sees it. The value is still computed there, and the comment now says why: so the front is correct on the day the field is serialized, rather than silently wrong. The earlier claim that this front "resolves exactly as the single-node chat route" was true of the computed value but misleading about the effect, and has been corrected. ## Reversal of the issue's `tool_choice` rule The implementation brief for this PR specified that a non-empty `tools` array should count regardless of `tool_choice`, justified by the declarations reaching the rendered prompt either way. Issue lablup#967 itself does not mention `tool_choice`, so this was never part of the filed issue. That justification is also false in this codebase: `chat_request::effective_tools` (`src/server/chat_request.rs:335`) returns `None` when `tool_choice` is `"none"`, so the template never sees them. The rule is reversed here rather than merely re-justified. `tool_choice: "none"` now drops the *declarations* signal, because a request whose declarations are never rendered is prompt-identical to plain chat: there is no amplifier to protect against, and turning detection on for it would reintroduce exactly the false positive this issue removes. It does not disarm a turn that replays tool calls in its messages, since those reach the prompt on the raw-JSON path regardless. ## Naming The predicate is `carries_loop_amplifier`, not the `uses_constrained_decoding` the implementation brief suggested. The old name described only the grammar half; the tools half is prompt content, not a decoding constraint. More concretely, the old name invited a future route author to read it as "is structured output on?" and pass `structured.is_some()` alone, silently dropping the tools amplifier. The `RequestOptionOverrides` field and the `resolve_loop_detection` parameter are `request_carries_loop_amplifier` to match, and the `build_generate_options` parameter was renamed off the helper's name so it no longer shadows the import. Chat-shaped routes call `chat_carries_loop_amplifier(&ChatCompletionRequest, bool)`, which reads `effective_tools` itself. Taking the whole request rather than a tools slice removes the mistake by construction: there is no slice parameter a call site could fill with raw `request.tools`. `/v1/completions` keeps the low-level predicate with an explicit `None`, since `CompletionRequest` has no tools field. ## Route wiring coverage Five tests build the options the way each route builds them, from the same request type, through the same translator where there is one, into the same `chat::build_generate_options`, and assert the resolved `loop_detection` on a Gemma 4 config. Each covers both the `tool_choice: "none"` (disabled) and no-`tool_choice` (recommended triple) cases. | Route | Test | What it covers | |-------|------|----------------| | `/v1/chat/completions` | `chat_route_gates_on_rendered_tools` | Request shape through the gate into the built options. | | `/v1/responses` | `responses_route_gates_on_rendered_tools` | Real `responses_request_to_chat` translation, so the `tools` / `tool_choice` flattening is covered end to end. | | `/v1/messages` | `anthropic_route_gates_on_rendered_tools` | Real `anthropic_request_to_chat` translation, including the `{"type": "none"}` to `Mode("none")` mapping, plus an assertion that the surface carries no `response_format`. | | `/v1/completions` | `completions_route_gates_on_the_grammar_constraint_only` | Grammar-only signal; `CompletionRequest` has neither a `tools` field nor chat messages, so both tool disjuncts are structurally absent. | | disaggregated chat front | `disaggregated_chat_front_gates_on_rendered_tools` | The shared composition that `route_chat` performs. | **What is not covered, and why.** The async handlers themselves are never invoked. `AppState` (`src/server/state.rs:337`) holds an `Arc<ModelProvider>`, which requires loading a model from disk; `src/server/routes/cache_tests.rs:18` already documents that as out of scope for unit tests, and the repo has no `AppState` fixture. So the one thing these tests cannot pin is the literal call expression inside each handler: an edit that changed `chat.rs:407` to call `carries_loop_amplifier(request.tools.as_deref(), ..)` would still pass. That gap is why the helper was reshaped to take `&ChatCompletionRequest`: the low-level predicate is not even imported in `chat.rs`, `anthropic.rs`, or `responses.rs` any more, so reintroducing the bug takes a deliberate new import rather than a plausible slip. Closing the gap fully would need an `AppState` test fixture with a stub `ModelProvider`, which is a larger piece of infrastructure than this PR should introduce. ## Tests `src/lib/mlxcel-core/src/loop_detection_tests.rs` - `markdown_alignment_row_does_not_fire_at_the_server_threshold`: the exact reproduction stream, `[107, 236909]` then `[1017, 7243, 1109]` repeated 4 times, must not fire at `(1, 20, 12)`. Alignment rows of 2 through 11 columns are checked too. The same stream is asserted to still fire at the old `(1, 20, 4)`, as the explicit before/after witness. - `repeated_cell_block_still_fires_at_the_server_threshold`: the same 3-token block repeated 12 and 30 times still fires, so the detector is recalibrated rather than defeated. - `single_token_collapse_fires_at_the_server_threshold`: 11 repeats do not fire, 12 do, including with a clean prefix. - The pre-existing fixture helper `recommended()` was renamed to `min_count_4()` because its doc comment claimed to be the server's threshold, which it no longer is. A new `server_recommended()` mirrors `LOOP_DETECTION_RECOMMENDED`. `src/server/request_options_tests.rs` - `uses_constrained_decoding_predicate`: absent, empty and non-empty `tools`, plus the grammar flag. - `tool_choice_none_drops_the_tools_signal`, `absent_tool_choice_keeps_the_tools_signal`, `tool_choice_auto_keeps_the_tools_signal`, and `grammar_constraint_is_independent_of_tool_choice_none` run a serde-deserialized `ChatCompletionRequest` through `effective_tools` into the gate, so the wire shape is what is under test. - `replayed_tool_calls_amplify_without_a_tools_array`, `replayed_tool_results_amplify_without_a_tools_array`, and `tool_choice_none_does_not_disarm_replayed_tool_calls` cover the message-content disjunct: an agent-loop follow-up turn with no top-level `tools` resolves to the recommended triple, via either `tool_calls` or `tool_call_id`, and `tool_choice: "none"` does not disarm it. - `gemma4_family_default_on_requires_an_amplifier`: gemma4 + tools and gemma4 + `json_schema` resolve to the recommended threshold; gemma4 plain chat and non-gemma4 + tools resolve to disabled. - `global_override_on_enables_plain_chat_despite_the_gate` and `global_override_off_disables_an_amplified_gemma4_request`: the env override is not subject to the gate in either direction. - `explicit_request_enable_wins_over_the_amplifier_gate`: a plain chat that explicitly asks for `1,20,4` still gets it. - `gemma4_plain_chat_stays_disabled_through_build_server_generate_options`, `gemma4_amplified_request_auto_enables_through_build_server_generate_options` and `non_gemma4_amplified_request_stays_disabled_through_build_server_generate_options` exercise the flag through the plumbing, not just the predicate. - `recommended_threshold_survives_a_four_column_markdown_table` pins the constant itself. `src/server/startup_tests.rs` needed no change: line 1253 asserts `on` maps to `LOOP_DETECTION_RECOMMENDED` symbolically, and the `"1,20,4,extra"` malformed fixture at line 1287 is unaffected. ## Docs - `docs/environment-variables.md`: activation-surface paragraph, the `MLXCEL_LOOP_DETECTION` table row (`1,20,12`, plus a note that `1,20,4` restores the old threshold), and precedence items 3 and 4. - `docs/supported-models.md`: the Gemma 4 loop-detection section now states the gated policy, the new triple, and the false-positive tradeoff. - `docs/python-client.md` was checked and left alone: it lists only the three field names and states no triple or activation policy, so nothing there became wrong. Stale in-code comments asserting the old unconditional policy were rewritten in `request_options.rs`, `startup.rs`, `chat.rs`, `native_completion.rs`, and `config.rs` (the last one was not in the brief but made the same claim on `ServerConfig::model_is_gemma4_family`). ## Known limitation: the grammar-constrained surface still has false positives This is measured on `gemma-4-12b-it-4bit`, not hypothetical, and it is documented in `docs/supported-models.md` rather than left implicit. A `json_schema` request whose schema permits a long run of identical values is still truncated. Asking for an integer array containing `0` repeated 30 times, under a schema requiring that array, returns `{"values": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,` and stops: cut after exactly 12 values, `completion_tokens: 43`, `finish_reason: "stop"`, with `loop detection: ending generation early (repetition loop) generated=43` in the server log. The returned document is truncated mid-array, so it is neither valid JSON nor conformant with the schema the client declared, and the client sees an ordinary stop. This PR improves the case without closing it: at the previous `min_count=4` the same request was cut after 4 values. No value of the threshold removes the class, because any fixed `min_count` is exceeded by a longer legitimate run. A client that hits it should send `max_pattern_size: 0` on that call, which disables detection for that request only and is not subject to the gate. Not fixed here on purpose. Removing the grammar half of the gate would contradict issue lablup#967's Part 2 as filed, and choosing a different policy for grammar-constrained decoding is a design decision that needs its own issue. ## Test plan Run on a CPU-only, default-feature build (this host builds CUDA only with `MLX_CUDA_ARCHITECTURES=121 --features cuda`). - [x] `cargo fmt --check` clean, exit 0. - [x] `cargo clippy --all-targets -- -D warnings` clean, exit 0. This is the command issue lablup#967 names; see the note below about the one unrelated file that had to change for it. - [x] `cargo test --release --lib`: `test result: ok. 4771 passed; 0 failed; 113 ignored; 0 measured; 2 filtered out`. The 2 filtered out are the pre-existing environmental failures below. All 32 tests in `server::request_options::tests` pass. - [x] `cargo test --release -p mlxcel-core loop_detection`: `test result: ok. 20 passed; 0 failed; 0 ignored; 0 measured; 1093 filtered out`. A bare `cargo test --release` at the repo root only builds the `mlxcel` package, so the detector tests in `mlxcel-core` need the explicit `-p`. ### Unrelated lint fix included on purpose `examples/qmm_gemv_microbench.rs:250` passed the literal `"2-12"` as a `println!` argument, tripping `clippy::print_literal` under clippy 1.93. It is inlined into the format string. The file is otherwise unrelated to this PR (it last changed in lablup#684) and is included only so the `cargo clippy --all-targets -- -D warnings` acceptance criterion passes. One line, no behavior change. ### Pre-existing failures on this build, none in a file this PR touches Named so the runs above are reproducible. Each is a missing build feature, not a logic regression. 1. `models::bitnet::tests::bitlinear_matmul_known_ternary_case` aborts the `mlxcel` lib test binary: `terminate called after throwing an instance of 'std::runtime_error' / what(): [cuda_kernel] No CUDA back-end.` (SIGABRT). It calls `mlxcel_core::bitlinear_matmul`, a GPU-only kernel with no CPU fallback and no `#[cfg(feature = "cuda")]` gate, and dates to lablup#287. 2. `multimodal::host_preprocessor::tests::xla_loader_keeps_text_and_unqualified_vlm_image_capability_false` panics with `called Result::unwrap() on an Err value: InvalidConfig("Qwen2-VL XLA image execution requires the xla-iree feature")`. 3. `cli_help_consistency::drafter_flag_aliases_are_documented_on_both_binaries` asserts the help contains `[aliases: --model-draft]`, but clap in this toolchain renders a single alias as `[alias: --model-draft]`. 4. The full `mlxcel-core` suite aborts the same way on GPU-only FFI tests, starting at `ffi_tests::test_fused_paged_decode_matches_gather_over_200_steps`. This PR's only change in that crate is `loop_detection_tests.rs`, which passes in full. The heavy `*_parity.rs` and `*_real_models.rs` integration binaries run real model forwards and are slow on a CPU-only build; they do not touch request-option plumbing. ## Hardware acceptance Measured on `models/gemma-4-12b-it-4bit` with a CUDA build of `mlxcel-server`, no env override (`MLXCEL_LOOP_DETECTION` unset). - **A, plain chat, request for a 5-column markdown table.** Completed, `finish_reason: stop`, 235 completion tokens, 0 loop-detection cuts. This is issue lablup#967's first acceptance criterion. - **B, plain chat, forced-repetition prompt.** Ran to `finish_reason: length`, 500 tokens, 0 cuts. Confirms the gate disables detection for plain chat. - **C, same prompt with a `tools` array.** Cut at 13 completion tokens (1 leading token plus exactly 12 repeats), `finish_reason: stop`, 1 cut, with the `loop detection: ending generation early (repetition loop)` log line. This is issue lablup#967's second acceptance criterion and shows `min_count=12` firing precisely. - **D, same prompt with `tools` plus `tool_choice: "none"`.** Ran to `finish_reason: length`, 500 tokens, 0 cuts. Confirms the `effective_tools` semantics end to end. - **F, same prompt with replayed `tool_calls` and `tool_call_id` messages but no top-level `tools` array.** Cut at 13 tokens, 1 cut. Confirms the `has_tool_fields` disjunct arms agent-replay turns. Cases A through D were byte-identical across three separate runs (before the rename refactor in d17a385, after it, and after the `has_tool_fields` change in 1ea192e), so those two commits are confirmed behavior-preserving on hardware. Closes lablup#967
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.
Summary
The Gemma 4 loop-detection default-on added in #432 truncates correct answers. With
min_count=4over pattern sizes 1..=20, a markdown table alignment row trips the detector:| :--- | :--- | :--- | :--- |tokenizes as'|'(236909) followed by the 3-token block[' :' 1017, '---' 7243, ' |' 1109]repeated once per column, so the 4th column firesdetect_repetition_loopat pattern size 3. Generation stops there, the scheduler finishes the sequence withFinishReason::RepetitionLoop, and the client sees a normal stop with no error. This PR raises the threshold and restricts the family default-on to the requests where the collapse actually happens.Part 1: threshold recalibration
LOOP_DETECTION_RECOMMENDEDmoves fromLoopDetectionConfig::new(1, 20, 4)toLoopDetectionConfig::new(1, 20, 12). This constant is also theMLXCEL_LOOP_DETECTION=onforce-enable value.Cost of the higher threshold. The two failure modes are not symmetric. A false positive silently truncates a correct answer mid-sentence and is hard to diagnose, because the wire
finish_reasonis an ordinarystop. A genuine Gemma 4 collapse (upstream weights-level defect, google-deepmind/gemma#622) repeats until the token budget is exhausted, so detecting it later mostly just emits more garbage tokens. A count of 12 also leaves alignment rows up to 11 columns alone, which covers every table shape seen in practice.The higher count costs two distinct things, and the second is easy to miss:
pis now cut after12ptokens instead of4p, so a genuine collapse runs8ptokens longer. That is 8 extra tokens for the single-token (p = 1) collapse in this issue's reproduction, and 160 at thep = 20ceiling.pnow requiresp * 12tail tokens rather thanp * 4, so a pattern is undetectable whenever the remaining budget is shorter thanp * 12. Withthinking_budget_tokens = 128, patterns ofp >= 11can no longer be caught, wherep * 4 = 44tokens previously sufficed. This is not a regression against the known reproduction, which isp = 1, but short-budget requests do lose coverage of long patterns.Part 2: gate the family default-on
The family default-on now requires the request to carry an amplifier. The test is whether the prompt is tool-shaped or decoding is grammar-constrained, not whether the request has a
toolsarray, and any one of three things satisfies it: tool declarations that reach the rendered prompt, tool-shaped message content (tool_callsortool_call_idon any message), or ajson_schemaresponse_formatthat compiled into a grammar constraint. #432's own reproduction recorded "no tools in the request: always clean", so running the detector on plain chat bought no protection while costing this entire class of false positives.RequestOptionOverridesgainspub uses_constrained_decoding: bool(Defaultisfalse, the safe baseline).resolve_loop_detectiongains a fourthrequest_uses_constrained_decodingparameter, and the family branch becomesfamily_default_on && request_uses_constrained_decoding. The predicate lives in one place,request_options::uses_constrained_decoding(tools: Option<&[Tool]>, has_grammar_constraint: bool), so "non-empty tools" is not re-derived per route.The declarations half is read from
chat_request::effective_tools, promoted topub(crate). That is the same helper the chat template uses to decide which tools to render, sotool_choice: "none"alone does not count: it renders no declarations, leaving a prompt indistinguishable from plain chat. Reading one helper for both the gate and the template is deliberate; if the rendering rule changes, the gate follows it rather than drifting from what the model sees.The message-content half is
chat_request::has_tool_fields, also promoted topub(crate). Without it the narrowing lost coverage that #432's unconditional default-on had, on the most common agentic shape:has_tool_fieldsroutes any request whose messages carrytool_callsortool_call_idto the raw-JSON render path, andbuild_raw_json_messages_with_thinkingwrites those fields into the prompt independently ofeffective_tools. An agent loop replaying prior tool calls on a follow-up turn that omits the top-leveltoolsarray, or sendstool_choice: "none"on that turn, therefore gets a thoroughly tool-shaped prompt. Those turns are not plain chat and stay armed. Atool_choice: "none"request whose messages carry no tool fields is still plain chat and still resolves disabled.Both halves report what is handed to the template, not what the template renders.
render_simple_fallbackdrops tools entirely when the Jinja render fails, and a checkpoint whose template ignores itstoolsargument renders none either, so the gate can report amplified for a prompt that is not.effective_toolsnow documents this, and the over-approximation is deliberate: erring toward keeping #432's protection on is the safe direction, and the alternative is resolving the gate after rendering. The grammar half is independent oftool_choice.chat::build_generate_optionstakes the flag as an explicitboolparameter rather than deriving it: it receives onlySamplingParams, which carries neither tools norresponse_format. Making it a required argument forces every call site to make a decision at compile time.New precedence order (exact)
max_pattern_size/min_pattern_size/min_counton the request. Wins over everything, including the gate, in both directions (force-enable and force-disable viamax_pattern_size=0).MLXCEL_LOOP_DETECTIONglobal override. Applies to every request unconditionally in both itsoffform and itson/MIN,MAX,COUNTforms. Not subject to the gate.model_is_gemma4_family && request_uses_constrained_decoding.The precedence order itself is unchanged; only step 3 gained a condition. Step 2 does change value though:
MLXCEL_LOOP_DETECTION=onresolves throughLOOP_DETECTION_RECOMMENDED, so an operator who had setonnow gets1,20,12instead of1,20,4, a roughly 3x less sensitive detector. SettingMLXCEL_LOOP_DETECTION=1,20,4restores the previous value exactly. Steps 1 and 4 are behaviorally identical.Call sites touched, and the flag each received
routes/chat.rs:407(non-stream chat)uses_constrained_decoding(effective_tools(&request), structured.is_some())chat_carries_loop_amplifierreads declarations and message content off the request, andstructured(built at lines 324-340, before this point) supplies the grammar half.routes/chat.rs:647(stream chat)routes/anthropic.rs:185(non-stream messages)uses_constrained_decoding(effective_tools(&translated.chat_request), false)anthropic_translatoralways setsresponse_format: Noneand this route compiles no constraint, so only the two tool disjuncts can apply. The translator mapstool_choicetoo, so an Anthropic{"type": "none"}lands asMode("none")and drops the declarations, but translatedtool_calls/tool_call_idon messages still amplify.routes/anthropic.rs:313(stream messages)routes/responses.rs:228(non-stream)uses_constrained_decoding(effective_tools(&translated.chat_request), structured.is_some())tools,tool_choice,text.format, and prior function-call items onto the matchingchat_requestfields;structuredis the compiled constraint.routes/responses.rs:351(stream)routes/completions.rs:248(non-stream)uses_constrained_decoding(None, structured.is_some())CompletionRequesthas notools, so only the grammar signal applies.routes/completions.rs:325(stream)router_front.rs:676(disaggregated chat front)uses_constrained_decoding(effective_tools(&request), false)effective_toolsthat theprepare_chat_request_with_cachecall just above used to render the prompt, so this front resolves exactly as the single-node route. The router never compiles a grammar constraint (thePrefillRequestFramecannot carry one), so the grammar half is always false.router_front.rs:956(disaggregated completions front)false(literal)toolsfield and no chat messages, and theresponse_formatguard above already rejects structured output with a 400, so no disjunct can be present.routes/native_completion.rs:286(buildsRequestOptionOverridesdirectly)uses_constrained_decoding: false/completionendpoint accepts neither tools norresponse_format. The comment there now records that the family default-on no longer reaches this endpoint and thatMLXCEL_LOOP_DETECTIONis the way to enable detection on it.batch/xla_worker_tests.rs:144uses..RequestOptionOverrides::default()and needed no change; it picks upfalse.Audited, no change needed
distributed/disaggregated/serving_protocol.rs:276setsloop_detection: Default::default()on aSamplingConfigreconstructed from the wire mirror, not on aRequestOptionOverrides. Loop detection is not part ofSerializableSamplingState, so the decode node already keeps the disabled baseline regardless of this change. Left as is.A consequence worth stating: the amplifier flag computed at
router_front.rs:676is inert today.sampling_to_serializabledoes not putloop_detectionon the wire and the reconstruction above hardcodes the disabled config, so no sampler on the disaggregated path ever sees it. The value is still computed there, and the comment now says why: so the front is correct on the day the field is serialized, rather than silently wrong. The earlier claim that this front "resolves exactly as the single-node chat route" was true of the computed value but misleading about the effect, and has been corrected.Reversal of the issue's
tool_choiceruleThe implementation brief for this PR specified that a non-empty
toolsarray should count regardless oftool_choice, justified by the declarations reaching the rendered prompt either way. Issue #967 itself does not mentiontool_choice, so this was never part of the filed issue. That justification is also false in this codebase:chat_request::effective_tools(src/server/chat_request.rs:335) returnsNonewhentool_choiceis"none", so the template never sees them.The rule is reversed here rather than merely re-justified.
tool_choice: "none"now drops the declarations signal, because a request whose declarations are never rendered is prompt-identical to plain chat: there is no amplifier to protect against, and turning detection on for it would reintroduce exactly the false positive this issue removes. It does not disarm a turn that replays tool calls in its messages, since those reach the prompt on the raw-JSON path regardless.Naming
The predicate is
carries_loop_amplifier, not theuses_constrained_decodingthe implementation brief suggested. The old name described only the grammar half; the tools half is prompt content, not a decoding constraint. More concretely, the old name invited a future route author to read it as "is structured output on?" and passstructured.is_some()alone, silently dropping the tools amplifier. TheRequestOptionOverridesfield and theresolve_loop_detectionparameter arerequest_carries_loop_amplifierto match, and thebuild_generate_optionsparameter was renamed off the helper's name so it no longer shadows the import.Chat-shaped routes call
chat_carries_loop_amplifier(&ChatCompletionRequest, bool), which readseffective_toolsitself. Taking the whole request rather than a tools slice removes the mistake by construction: there is no slice parameter a call site could fill with rawrequest.tools./v1/completionskeeps the low-level predicate with an explicitNone, sinceCompletionRequesthas no tools field.Route wiring coverage
Five tests build the options the way each route builds them, from the same request type, through the same translator where there is one, into the same
chat::build_generate_options, and assert the resolvedloop_detectionon a Gemma 4 config. Each covers both thetool_choice: "none"(disabled) and no-tool_choice(recommended triple) cases./v1/chat/completionschat_route_gates_on_rendered_tools/v1/responsesresponses_route_gates_on_rendered_toolsresponses_request_to_chattranslation, so thetools/tool_choiceflattening is covered end to end./v1/messagesanthropic_route_gates_on_rendered_toolsanthropic_request_to_chattranslation, including the{"type": "none"}toMode("none")mapping, plus an assertion that the surface carries noresponse_format./v1/completionscompletions_route_gates_on_the_grammar_constraint_onlyCompletionRequesthas neither atoolsfield nor chat messages, so both tool disjuncts are structurally absent.disaggregated_chat_front_gates_on_rendered_toolsroute_chatperforms.What is not covered, and why. The async handlers themselves are never invoked.
AppState(src/server/state.rs:337) holds anArc<ModelProvider>, which requires loading a model from disk;src/server/routes/cache_tests.rs:18already documents that as out of scope for unit tests, and the repo has noAppStatefixture. So the one thing these tests cannot pin is the literal call expression inside each handler: an edit that changedchat.rs:407to callcarries_loop_amplifier(request.tools.as_deref(), ..)would still pass. That gap is why the helper was reshaped to take&ChatCompletionRequest: the low-level predicate is not even imported inchat.rs,anthropic.rs, orresponses.rsany more, so reintroducing the bug takes a deliberate new import rather than a plausible slip. Closing the gap fully would need anAppStatetest fixture with a stubModelProvider, which is a larger piece of infrastructure than this PR should introduce.Tests
src/lib/mlxcel-core/src/loop_detection_tests.rsmarkdown_alignment_row_does_not_fire_at_the_server_threshold: the exact reproduction stream,[107, 236909]then[1017, 7243, 1109]repeated 4 times, must not fire at(1, 20, 12). Alignment rows of 2 through 11 columns are checked too. The same stream is asserted to still fire at the old(1, 20, 4), as the explicit before/after witness.repeated_cell_block_still_fires_at_the_server_threshold: the same 3-token block repeated 12 and 30 times still fires, so the detector is recalibrated rather than defeated.single_token_collapse_fires_at_the_server_threshold: 11 repeats do not fire, 12 do, including with a clean prefix.recommended()was renamed tomin_count_4()because its doc comment claimed to be the server's threshold, which it no longer is. A newserver_recommended()mirrorsLOOP_DETECTION_RECOMMENDED.src/server/request_options_tests.rsuses_constrained_decoding_predicate: absent, empty and non-emptytools, plus the grammar flag.tool_choice_none_drops_the_tools_signal,absent_tool_choice_keeps_the_tools_signal,tool_choice_auto_keeps_the_tools_signal, andgrammar_constraint_is_independent_of_tool_choice_nonerun a serde-deserializedChatCompletionRequestthrougheffective_toolsinto the gate, so the wire shape is what is under test.replayed_tool_calls_amplify_without_a_tools_array,replayed_tool_results_amplify_without_a_tools_array, andtool_choice_none_does_not_disarm_replayed_tool_callscover the message-content disjunct: an agent-loop follow-up turn with no top-leveltoolsresolves to the recommended triple, via eithertool_callsortool_call_id, andtool_choice: "none"does not disarm it.gemma4_family_default_on_requires_an_amplifier: gemma4 + tools and gemma4 +json_schemaresolve to the recommended threshold; gemma4 plain chat and non-gemma4 + tools resolve to disabled.global_override_on_enables_plain_chat_despite_the_gateandglobal_override_off_disables_an_amplified_gemma4_request: the env override is not subject to the gate in either direction.explicit_request_enable_wins_over_the_amplifier_gate: a plain chat that explicitly asks for1,20,4still gets it.gemma4_plain_chat_stays_disabled_through_build_server_generate_options,gemma4_amplified_request_auto_enables_through_build_server_generate_optionsandnon_gemma4_amplified_request_stays_disabled_through_build_server_generate_optionsexercise the flag through the plumbing, not just the predicate.recommended_threshold_survives_a_four_column_markdown_tablepins the constant itself.src/server/startup_tests.rsneeded no change: line 1253 assertsonmaps toLOOP_DETECTION_RECOMMENDEDsymbolically, and the"1,20,4,extra"malformed fixture at line 1287 is unaffected.Docs
docs/environment-variables.md: activation-surface paragraph, theMLXCEL_LOOP_DETECTIONtable row (1,20,12, plus a note that1,20,4restores the old threshold), and precedence items 3 and 4.docs/supported-models.md: the Gemma 4 loop-detection section now states the gated policy, the new triple, and the false-positive tradeoff.docs/python-client.mdwas checked and left alone: it lists only the three field names and states no triple or activation policy, so nothing there became wrong.Stale in-code comments asserting the old unconditional policy were rewritten in
request_options.rs,startup.rs,chat.rs,native_completion.rs, andconfig.rs(the last one was not in the brief but made the same claim onServerConfig::model_is_gemma4_family).Known limitation: the grammar-constrained surface still has false positives
This is measured on
gemma-4-12b-it-4bit, not hypothetical, and it is documented indocs/supported-models.mdrather than left implicit.A
json_schemarequest whose schema permits a long run of identical values is still truncated. Asking for an integer array containing0repeated 30 times, under a schema requiring that array, returns{"values": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,and stops: cut after exactly 12 values,completion_tokens: 43,finish_reason: "stop", withloop detection: ending generation early (repetition loop) generated=43in the server log. The returned document is truncated mid-array, so it is neither valid JSON nor conformant with the schema the client declared, and the client sees an ordinary stop.This PR improves the case without closing it: at the previous
min_count=4the same request was cut after 4 values. No value of the threshold removes the class, because any fixedmin_countis exceeded by a longer legitimate run. A client that hits it should sendmax_pattern_size: 0on that call, which disables detection for that request only and is not subject to the gate.Not fixed here on purpose. Removing the grammar half of the gate would contradict issue #967's Part 2 as filed, and choosing a different policy for grammar-constrained decoding is a design decision that needs its own issue.
Test plan
Run on a CPU-only, default-feature build (this host builds CUDA only with
MLX_CUDA_ARCHITECTURES=121 --features cuda).cargo fmt --checkclean, exit 0.cargo clippy --all-targets -- -D warningsclean, exit 0. This is the command issue fix(server): Gemma 4 default-on loop detection falsely truncates markdown tables; raise min_count and gate activation to tool/grammar-constrained requests #967 names; see the note below about the one unrelated file that had to change for it.cargo test --release --lib:test result: ok. 4771 passed; 0 failed; 113 ignored; 0 measured; 2 filtered out. The 2 filtered out are the pre-existing environmental failures below. All 32 tests inserver::request_options::testspass.cargo test --release -p mlxcel-core loop_detection:test result: ok. 20 passed; 0 failed; 0 ignored; 0 measured; 1093 filtered out. A barecargo test --releaseat the repo root only builds themlxcelpackage, so the detector tests inmlxcel-coreneed the explicit-p.Unrelated lint fix included on purpose
examples/qmm_gemv_microbench.rs:250passed the literal"2-12"as aprintln!argument, trippingclippy::print_literalunder clippy 1.93. It is inlined into the format string. The file is otherwise unrelated to this PR (it last changed in #684) and is included only so thecargo clippy --all-targets -- -D warningsacceptance criterion passes. One line, no behavior change.Pre-existing failures on this build, none in a file this PR touches
Named so the runs above are reproducible. Each is a missing build feature, not a logic regression.
models::bitnet::tests::bitlinear_matmul_known_ternary_caseaborts themlxcellib test binary:terminate called after throwing an instance of 'std::runtime_error' / what(): [cuda_kernel] No CUDA back-end.(SIGABRT). It callsmlxcel_core::bitlinear_matmul, a GPU-only kernel with no CPU fallback and no#[cfg(feature = "cuda")]gate, and dates to feat(models): add BitNet b1.58 (1.58-bit ternary) support (#252) #287.multimodal::host_preprocessor::tests::xla_loader_keeps_text_and_unqualified_vlm_image_capability_falsepanics withcalled Result::unwrap() on an Err value: InvalidConfig("Qwen2-VL XLA image execution requires the xla-iree feature").cli_help_consistency::drafter_flag_aliases_are_documented_on_both_binariesasserts the help contains[aliases: --model-draft], but clap in this toolchain renders a single alias as[alias: --model-draft].mlxcel-coresuite aborts the same way on GPU-only FFI tests, starting atffi_tests::test_fused_paged_decode_matches_gather_over_200_steps. This PR's only change in that crate isloop_detection_tests.rs, which passes in full.The heavy
*_parity.rsand*_real_models.rsintegration binaries run real model forwards and are slow on a CPU-only build; they do not touch request-option plumbing.Hardware acceptance
Measured on
models/gemma-4-12b-it-4bitwith a CUDA build ofmlxcel-server, no env override (MLXCEL_LOOP_DETECTIONunset).finish_reason: stop, 235 completion tokens, 0 loop-detection cuts. This is issue fix(server): Gemma 4 default-on loop detection falsely truncates markdown tables; raise min_count and gate activation to tool/grammar-constrained requests #967's first acceptance criterion.finish_reason: length, 500 tokens, 0 cuts. Confirms the gate disables detection for plain chat.toolsarray. Cut at 13 completion tokens (1 leading token plus exactly 12 repeats),finish_reason: stop, 1 cut, with theloop detection: ending generation early (repetition loop)log line. This is issue fix(server): Gemma 4 default-on loop detection falsely truncates markdown tables; raise min_count and gate activation to tool/grammar-constrained requests #967's second acceptance criterion and showsmin_count=12firing precisely.toolsplustool_choice: "none". Ran tofinish_reason: length, 500 tokens, 0 cuts. Confirms theeffective_toolssemantics end to end.tool_callsandtool_call_idmessages but no top-leveltoolsarray. Cut at 13 tokens, 1 cut. Confirms thehas_tool_fieldsdisjunct arms agent-replay turns.Cases A through D were byte-identical across three separate runs (before the rename refactor in d17a385, after it, and after the
has_tool_fieldschange in 1ea192e), so those two commits are confirmed behavior-preserving on hardware.Closes #967