Skip to content

feat(models): add BitNet b1.58 (1.58-bit ternary) support (#252) - #287

Merged
inureyes merged 2 commits into
mainfrom
feat/issue-252-bitnet
Jun 14, 2026
Merged

inureyes merged 2 commits into
mainfrom
feat/issue-252-bitnet

Conversation

@inureyes

Copy link
Copy Markdown
Member

Summary

Ports BitNet b1.58 (Microsoft), the 1.58-bit ternary-weight Llama-style transformer. Closes #252.

Every projection is a BitLinear: ternary weights ({-1, 0, +1}) packed 4-per-uint8 + a single per-tensor weight_scale.

What changed

  • bitlinear_matmul Metal kernel (port of mlx-lm bitlinear_layers.py make_bitlinear_kernel): multiplies directly on the 2-bit-packed bytes ((bits & 3) - 1 per ternary value), so the unpacked weights never materialize. One simdgroup per (batch, out-row/4) with a simd_sum reduction. FFI + lib.rs + header.
  • src/models/bitnet.rs: the model + a BitLinear layer. Two sub-norms beyond Llama (attn_sub_norm before o_proj, ffn_sub_norm inside the MLP), a squared-ReLU MLP (relu2(gate) * up), tied embeddings, GQA, RoPE. Scales are inverted unless linear_class == "autobitlinear".
  • Registration: detection.rs, the ModelType enum + arch list + metadata (mod.rs), load metadata (model_metadata.rs), LoadedModel (loaded_model.rs), TP fallback architecture.
  • bf16 fix: BitNet runs in its native bf16 — its squared-ReLU overflows the f16 max (65504), so load_text_weights skips the bf16→f16 Apple-Silicon conversion for model_type == "bitnet". (The conversion produced NaNs from layer 0; this matches the reference.)

Validation

  • mlx-community/bitnet-b1.58-2B-4T: coherent greedy output ("The capital of France is Paris...", "Gravity is the force that attracts two bodies with mass..."), ~150 tok/s decode (M1 Ultra).
  • BitLinear numerics unit test on a hand-computed known ternary case (bitlinear_matmul_known_ternary_case).
  • Kernel cross-checked against an independent dequantize+matmul path during bring-up (identical results).
  • cargo fmt + cargo clippy clean. mlxcel arch lists BitNet.
  • docs/supported-models.md updated.

Notes

Validated with the base ternary checkpoint per the incremental-porting principle; the -4bit/-6bit/-8bit affine-quantized variants (which further quantize embedding/lm_head) are a follow-up.

Closes #252.

Port BitNet b1.58, the ternary-weight Llama-style transformer. Every projection
is a BitLinear: 1.58-bit ternary weights ({-1, 0, +1}) packed 4-per-uint8 and
scaled by a single per-tensor weight_scale.

- bitlinear_matmul: a Metal kernel (port of mlx-lm bitlinear_layers.py
  make_bitlinear_kernel) that multiplies directly on the 2-bit-packed bytes
  ((bits & 3) - 1 per ternary value) so the unpacked weights never materialize;
  one simdgroup per (batch, out-row/4) with a simd_sum reduction. FFI in
  mlx_cxx_kernels.cpp + lib.rs + the header.
- src/models/bitnet.rs: the model and a BitLinear layer. Two sub-norms beyond
  Llama (attn_sub_norm before o_proj, ffn_sub_norm inside the MLP) and a
  squared-ReLU MLP (relu2(gate) * up). Embedding and (untied) lm_head stay full
  precision; weight scales are inverted unless linear_class == autobitlinear.
- Registered in detection.rs ("bitnet"), the ModelType enum + arch list +
  metadata (mod.rs), the load metadata (model_metadata.rs), LoadedModel
  (loaded_model.rs), and the tensor-parallel fallback architecture.
- BitNet runs in its native bf16: its squared-ReLU activation overflows the f16
  max (65504), so load_text_weights now skips the bf16->f16 Apple-Silicon
  conversion for model_type "bitnet" (matching the reference; the conversion
  produced NaNs).

Validated against mlx-community/bitnet-b1.58-2B-4T: coherent greedy output,
~150 tok/s decode (M1 Ultra), plus a BitLinear numerics unit test on a known
ternary case. docs/supported-models.md updated.
@inureyes inureyes added type:enhancement New features, capabilities, or significant additions area:models Model architectures, weights, loading, metadata area:core mlxcel-core: MLX FFI, primitives, KV cache, layers platform:macos macOS (Apple Silicon) specific priority:medium Medium priority labels Jun 14, 2026
Strengthen the `mlxcel arch` registration check. The previous
all_model_types_covers_every_variant test only asserted count > 80, so a
ModelType variant added to the enum but forgotten in ALL_MODEL_TYPES would
silently be absent from `mlxcel arch`. The new every_variant_is_registered_for_arch
test lists every variant once through an `all_variants!` macro whose inner
exhaustive `match` makes the compiler reject the list if a variant is missing,
then iterates the same list to assert membership in ALL_MODEL_TYPES. Adding a
ModelType is now a build error until it is both listed and registered. The audit
behind this found the current list already complete (107/107, including BitNet
and the other recent additions).

Also validated the BitNet -4bit variant (mlx-community/bitnet-b1.58-2B-4T-4bit):
its embedding/lm_head are 4-bit affine with bf16 scales while the BitLinear
weights stay ternary; keeping the whole model bf16 (the relu2 overflow fix) also
keeps that 4-bit dequant dtype-consistent, so it works unchanged ("2 + 2 equals
4.", ~159 tok/s). docs updated.
@inureyes
inureyes merged commit 9262b43 into main Jun 14, 2026
4 checks passed
@inureyes
inureyes deleted the feat/issue-252-bitnet branch June 14, 2026 14:29
@inureyes inureyes added this to the 0.3 milestone Jun 21, 2026
inureyes added a commit that referenced this pull request Jul 30, 2026
…on (#969)

## Summary

The Gemma 4 loop-detection default-on added in #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. #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 #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 #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 #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 #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 #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 #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 #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 #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 #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 #967
@inureyes inureyes self-assigned this Aug 31, 2026
@inureyes inureyes added the status:done Completed label Sep 6, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
lablup#287)

* feat(models): add BitNet b1.58 (1.58-bit ternary) support (lablup#252)

Port BitNet b1.58, the ternary-weight Llama-style transformer. Every projection
is a BitLinear: 1.58-bit ternary weights ({-1, 0, +1}) packed 4-per-uint8 and
scaled by a single per-tensor weight_scale.

- bitlinear_matmul: a Metal kernel (port of mlx-lm bitlinear_layers.py
  make_bitlinear_kernel) that multiplies directly on the 2-bit-packed bytes
  ((bits & 3) - 1 per ternary value) so the unpacked weights never materialize;
  one simdgroup per (batch, out-row/4) with a simd_sum reduction. FFI in
  mlx_cxx_kernels.cpp + lib.rs + the header.
- src/models/bitnet.rs: the model and a BitLinear layer. Two sub-norms beyond
  Llama (attn_sub_norm before o_proj, ffn_sub_norm inside the MLP) and a
  squared-ReLU MLP (relu2(gate) * up). Embedding and (untied) lm_head stay full
  precision; weight scales are inverted unless linear_class == autobitlinear.
- Registered in detection.rs ("bitnet"), the ModelType enum + arch list +
  metadata (mod.rs), the load metadata (model_metadata.rs), LoadedModel
  (loaded_model.rs), and the tensor-parallel fallback architecture.
- BitNet runs in its native bf16: its squared-ReLU activation overflows the f16
  max (65504), so load_text_weights now skips the bf16->f16 Apple-Silicon
  conversion for model_type "bitnet" (matching the reference; the conversion
  produced NaNs).

Validated against mlx-community/bitnet-b1.58-2B-4T: coherent greedy output,
~150 tok/s decode (M1 Ultra), plus a BitLinear numerics unit test on a known
ternary case. docs/supported-models.md updated.

* test(models): enforce ALL_MODEL_TYPES completeness; validate bitnet-4bit

Strengthen the `mlxcel arch` registration check. The previous
all_model_types_covers_every_variant test only asserted count > 80, so a
ModelType variant added to the enum but forgotten in ALL_MODEL_TYPES would
silently be absent from `mlxcel arch`. The new every_variant_is_registered_for_arch
test lists every variant once through an `all_variants!` macro whose inner
exhaustive `match` makes the compiler reject the list if a variant is missing,
then iterates the same list to assert membership in ALL_MODEL_TYPES. Adding a
ModelType is now a build error until it is both listed and registered. The audit
behind this found the current list already complete (107/107, including BitNet
and the other recent additions).

Also validated the BitNet -4bit variant (mlx-community/bitnet-b1.58-2B-4T-4bit):
its embedding/lm_head are 4-bit affine with bf16 scales while the BitLinear
weights stay ternary; keeping the whole model bf16 (the relu2 overflow fix) also
keeps that 4-bit dequant dtype-consistent, so it works unchanged ("2 + 2 equals
4.", ~159 tok/s). docs updated.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:models Model architectures, weights, loading, metadata platform:macos macOS (Apple Silicon) specific priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(models): add BitNet (1.58-bit ternary) support

1 participant