From 1807498d8ec869f61061f028e9418db31bda307f Mon Sep 17 00:00:00 2001 From: Jaeyeong Choi <144660874+Jaeyeong-CHOI@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:07:34 +0900 Subject: [PATCH] feat(models): add Ripple-65B (ricursive) support Adds Ricursive Ripple-65B-Preview (model_type ricursive, RicursiveForCausalLM) to mlxcel generate, mlxcel-server and mlxcel arch, following mlx-vlm's ricursive port (Blaizzy/mlx-vlm#2697) including its rounding: RoPE sliding-window layers and NoPE full layers, four RMS norms per block plus per-head q/k norms, value residuals that lerp every layer's value input toward the scaled input embedding in FP32, an FP32 sigmoid output gate, a clipped SwiGLU with an FP32 SiLU and embed_scale applied in FP32 after the lookup. Per-sequence caches are scheduler-owned with native batched decode. MLX's fused rms_norm already rounds before applying the weight, which is the reference order, so the block uses the shared RMSNorm. The family keeps its checkpoint dtype at load, as mlx-vlm runs it: the bf16 -> f16 cast (Apple Silicon, pre-Ampere CUDA, MLXCEL_CUDA_F16_NORMALIZE) would turn value_res_lambda into f16, which the loader refuses. limited_swiglu's clamp moves into a shared helper next to the new limited_swiglu_f32_silu; DeepSeek-V4 and V4.1 compute what they did. The ModelOpt NVFP4 export and per-module mixed quantizations are refused by name. Closes #3224 --- CHANGELOG.md | 6 + docs/supported-models.md | 1 + src/distributed/tensor_parallel/inference.rs | 1 + src/execution/memory_estimate.rs | 1 + src/lib/mlxcel-core/src/cache.rs | 2 +- src/lib/mlxcel-core/src/cache/attend.rs | 3 +- src/lib/mlxcel-core/src/utils.rs | 6 +- src/loaded_model.rs | 2 + src/model_metadata.rs | 1 + src/models/batched_decode_coverage_tests.rs | 1 + src/models/deepseek_v4_moe.rs | 52 +- src/models/detection.rs | 1 + src/models/detection_tests.rs | 11 + src/models/mod.rs | 9 + src/models/model_owned.rs | 11 +- src/models/registry.rs | 2 + src/models/ricursive.rs | 1183 ++++++++++++++++++ src/models/ricursive_tests.rs | 1122 +++++++++++++++++ src/models/sanitize.rs | 65 +- 19 files changed, 2464 insertions(+), 16 deletions(-) create mode 100644 src/models/ricursive.rs create mode 100644 src/models/ricursive_tests.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 5bad1fa82f..b8b3414288 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +## [Unreleased] + +### Added + +- **Ricursive Ripple** (`ricursive`, #3224): `frogggias/Ripple-65B-Preview-MLX-4bit` and `-8bit` run in `mlxcel generate`, `mlxcel-server` and `mlxcel arch` with native batched decode, in the checkpoint's own dtype (no load-time bf16 -> f16 cast). On GB10 the 4-bit checkpoint's greedy output matches mlx-vlm token for token. The ModelOpt NVFP4 export and mixed per-module quantizations are refused by name. + ## [v0.9.0] - 2026-11-30 ### Added diff --git a/docs/supported-models.md b/docs/supported-models.md index 80cfc9ab08..b97f115774 100644 --- a/docs/supported-models.md +++ b/docs/supported-models.md @@ -69,6 +69,7 @@ Implemented model families include: - RecursiveSI Flint (`flint`), a 49-layer text decoder with learned attention sinks on both full and sliding layers. The 513-token sliding cache keeps no prefix. RoPE follows `no_rope_layer_indices` when supplied and otherwise applies to sliding layers. After two dense layers, each MoE layer selects six of 256 sigmoid-scored experts with an optional selection bias and adds an ungated shared expert. Selected scores are normalized with a `1e-20` epsilon and accumulated in FP32. The output head takes FP32 activations and holds its operands in FP32, because CUDA would otherwise compute the projection in bf16. For a quantized head that is only the scales and biases: the published heads (`[150144, 2048]`, group size 64) grow from 19.2 MB to 38.4 MB. The dense BF16 `RecursiveSI/flint` head grows from 615 MB to 1.23 GB, a tied dense head keeps the BF16 embedding and adds a 1.23 GB FP32 copy, and load briefly holds the BF16 planes and the FP32 copy together. The loader accepts mlx-vlm's `language_model.` prefix and vendor INT4 byte-packed weights with a separate embedding bit width. Both `mlx-community/flint-oQ4e` and `RecursiveSI/flint-int4` generated 391 for 17 × 23 on CUDA. Native batched decode uses per-sequence caches. Tensor parallel, speculative targets and prompt-cache snapshots are unsupported. - Laguna XS 2.1 / XS.2 / S 2.1 (`laguna`, Poolside code models: a pre-norm decoder with QK-RMSNorm, a hybrid of `full_attention` layers (YaRN over the first `partial_rotary_factor` share of each head, explicit `attention_factor`, dense `KVCache`) and `sliding_attention` layers (plain RoPE at base 10000, `RotatingKVCache` windowed to `sliding_window` 512), per-layer query-head counts from `num_attention_heads_per_layer`, a per-head softplus attention output gate (`g_proj`, `gating: "per-head"`), an optional per-head attention sink on sliding layers, a dense SwiGLU MLP on layer 0, and elsewhere a sigmoid-routed (or `sqrtsoftplus`) top-k MoE whose expert selection adds `e_score_correction_bias` while the weights stay bias-free, renormalized and scaled by `moe_routed_scaling_factor`, plus an always-on shared expert. The published NVFP4 checkpoints keep the experts and the shared expert in the `compressed-tensors` `nvfp4-pack-quantized` layout (`weight_packed` / `weight_scale` / `weight_global_scale`); the loader reinterprets the packed E2M1 bytes as MLX native NVFP4 words, keeps every E4M3 block scale byte for byte, and applies `1 / weight_global_scale` per expert after the routed matmul (the `SwitchLinear` `global_scale` sidecar) rather than folding it into the 3-mantissa-bit block scales. Pre-stacked MLX conversions (`switch_mlp.*`, a fused `gate_up_proj` is split) and per-expert bf16 exports load through the same path. The chat template emits the tokenizer's own BOS spelling (`〈|EOS|〉`, id 2, which is also an EOS) first, so the tokenize sites suppress `add_special_tokens` for a prompt that starts with the tokenizer's BOS string (`MlxcelTokenizer::prompt_carries_bos`); generation stops on ids 2 and 24 (``, a plain added token), and `` / `` are the reasoning markers. The YaRN block's `attention_factor` is used when the config carries one and derived from `factor` otherwise, which is what `transformers`' `_compute_yarn_parameters` does and therefore what the checkpoint's own `modeling_laguna.py` inherits; mlx-lm's port drops the key and always derives, so `Laguna-XS.2-4bit`, which declares `attention_factor: 1.0` where the derived value would be 1.3466, rotates differently under the two runtimes. XS 2.1 declares the derived value and agrees either way. Not wired for tensor parallel. Validated against `poolside/Laguna-XS-2.1-NVFP4` (native compressed-tensors NVFP4, 234 planes transcoded at load), `mlx-community/Laguna-XS.2-4bit` (pre-stacked affine, per-layer 8-bit router planes reconciled from the tensor shapes) and `poolside/Laguna-S-2.1-NVFP4` (48 layers, 256 experts at top-10). S 2.1 mixes expert formats in one checkpoint: layers 1 to 39 carry NVFP4 routed experts (117 planes), layers 40 to 47 keep their routed experts in bf16, and the shared experts are bf16 throughout, so a load exercises both the NVFP4 and the per-expert bf16 paths. It generates fluent Python with finite logits. Its load-time resident figure (49.4 GiB) counts only the transcoded planes, since the bf16 weights realize on the first forward, so plan for about 93 GiB and a 128 GB host. The external reference is the checkpoint's own `modeling_laguna.py`, run out of band in float32 by `scripts/laguna_oracle_trace.py`, which decodes the NVFP4 planes exactly and writes the `examples/logit_trace` format. Against it on XS 2.1, mlxcel (bf16) has no top-1 disagreement at a position the reference had decided (top-two gap of 2 or more): 0 of 75 at width 1 and 0 of 296 at width 8, both behind 512 tokens of context, and 0 of 107 at width 256 in a window that starts with the BOS token. Those traces left chunk 0 without the `〈|EOS|〉` BOS, which degrades the reference as well (perplexity about 950 against 17.8 anchored), and the only decided disagreement at width 256, 1 of 93, was in that window. Since #1785 both tools anchor every window, chunk 0 included. Re-measured that way on a GB10 (reference in float32 on CUDA, `docs/architecture.md` as the corpus): 0 of 250 decided positions disagree at width 256 and 0 of 317 at width 8 behind 512 tokens, and chunk 0 at width 256 reads perplexity 19.9 in both the reference and mlxcel, against 364 and 378 without the anchor. The reference implements neither `sqrtsoftplus` routing nor the sliding-layer sinks (it allocates `sink` but never reads it), and no published checkpoint enables either, so those two paths are covered by synthetic-config tests only.) - Paradigma Limite (`limite`, `LimiteForCausalLM`, `paradigma-inc/limite-1b-violetto`, bf16, 2.1 GB: a 48-layer dense decoder in which every norm is a weightless RMSNorm whose epsilon is the activation dtype's `finfo.eps` (0.0078125 in bf16), so the checkpoint runs in its own bf16 instead of the usual load-time f16 cast. Sliding layers attend `sliding_window + 1` = 1025 keys (`k >= q - 1024` inclusive) through a `RotatingKVCache` of that size, with a partial interleaved RoPE on 32 of 64 pairs (odd-lane sine negated, cos/sin rounded to bf16); every fourth layer is a NoPE full-causal global layer on a growing `KVCache`. Attention uses a fixed softmax scale of 0.1, value embeddings added to V on `ve_layers`, XSA value-direction removal, and a per-head sigmoid gate before `o_proj`; projections fold their learned scalars after rounding them to bf16, and each layer mixes its residual with four learned lambdas. Layers 24 and 47 take their attention input and residual base from the MUDD mixer, a learned per-position mix of earlier layer outputs accumulated left to right. The tied head returns `23 * sigmoid((h @ E.T + 5) / 7.5)` in f32, and those bounded values are what the sampler sees, as in the reference (greedy decoding is unaffected, temperature sampling is not). The config's convention strings (`rope_style`, `sliding_window_convention`, `mudd_hist_convention`, `rms_norm_eps_mode` and the rest) are checked at load, and `rope_per_layer: true`, `mlp_type: relu2`, a non-sigmoid softcap and quantized exports are refused. The caches are model-owned per sequence: batched decode runs natively, `--kv-cache-mode` applies to the global layers (the 1025-key sliding layers store FP16), and the scheduler's KV bound and release apply as for the other model-owned families. Not wired for tensor or pipeline parallel. The reference is mlx-vlm's `mlx_vlm/models/limite`, traced by `scripts/limite_oracle_trace.py`. Teacher-forced over `docs/architecture.md` in 64-token chunks behind up to 1536 tokens of context, mlxcel disagrees with it on 0 of 814 positions the reference decided (top-two gap of 2 or more), and with `--drop-mudd` (layers 24 and 47 read plain `rms_norm(x)`) the reference disagrees with itself on all 814.) +- Ricursive Ripple (`ricursive`, `RicursiveForCausalLM`, `ricursiveAI/Ripple-65B-Preview` and its MLX conversions `frogggias/Ripple-65B-Preview-MLX-4bit` and `-8bit`): an 80-layer dense decoder whose `layer_types` put a NoPE full-attention layer after every four RoPE sliding-window layers (window 1024, a `RotatingKVCache`; a null `sliding_window` gives every layer a growing cache). Each block has four RMS norms (input, post-attention, pre- and post-feedforward) plus per-head `q_norm` / `k_norm`; every norm normalizes in f32, rounds to the activation dtype and then multiplies by its weight. The values of every layer read `lerp(h0, x, sigmoid(value_res_lambda))`, where `h0` is the input embedding times `embed_scale` (in f32, before the first norm) and `x` the layer's normalized input; the attention output passes an elementwise f32 sigmoid gate (`g_proj`) before `o_proj`, and the MLP is a SwiGLU whose gate and up projections are clipped at `ffn_clamp_threshold` with the SiLU computed in f32. RoPE keeps the reference's rounding (cos and sin rounded to the activation dtype, the rotation in f32). The reference is mlx-vlm's `mlx_vlm/models/ricursive` (Blaizzy/mlx-vlm#2697). Every Ripple checkpoint loads in its own dtype, as mlx-vlm runs it: the load-time bf16 -> f16 cast (Apple Silicon, pre-Ampere CUDA, `MLXCEL_CUDA_F16_NORMALIZE`) is skipped for the family, because the `value_res_lambda` scalars must stay f32 or bf16. Per-sequence caches are scheduler-owned and batched decode runs natively; every layer stores FP16 KV (`--kv-cache-mode` is not applied). Not wired: tensor and pipeline parallel and the DFlash2 drafter; the ModelOpt NVFP4 export (`ricursiveAI/Ripple-65B-Preview-NVFP4`) and conversions with per-module quantization overrides (`araysuter/Ripple-65B-Preview-MLX-mixed-2bit`) are refused at load by name. - Inkling (`inkling_mm_model` and `inkling`): the text backbone combines hybrid sliding/global NoPE attention, learned banded relative-position bias and log-position temperature, four f32 short-convolution states per layer, dense-first SwiGLU, logsigmoid-softmax routed and shared experts, muP-scaled logits, and padded-vocabulary trimming. Image input is supported through both the CLI `--image` path and OpenAI-compatible server `image_url` content blocks when the checkpoint carries `vision_config` and `model.visual.*` weights. The HMLP tower maps row-major 40x40 RGB tiles duplicated across two temporal slots directly to text-width soft tokens; exact-width images intentionally receive a trailing all-padding tile column, and each rendered image placeholder expands to the number of tiles preprocessing actually produced before ordered feature scatter. Audio input is supported for checkpoints that also carry `audio_config` and `model.audio.*` weights through CLI `--audio` and server `input_audio`, alone or with still images. The bounded host path decodes, downmixes, and resamples WAV input to 16 kHz, produces reference-compatible dMel IDs, scatters image rows first and audio rows second, and keeps every multimodal request on classic prepared-embedding prefill. Video input is supported through CLI `--video` and server `video_url`: sampled frames default to 2 fps, odd sequences repeat their final frame, and at most 16 evenly spaced adjacent pairs are allocated request-wide without crossing clip boundaries. Each clip restarts its timestamp origin, and timestamps use actual probed source-frame time after sampling. Before decoding, the request is capped at eight clips, 32 unique selected frames, and 512 MiB of decoded pixel storage; only selected frames are decoded and retained. The second frame replaces temporal slot 1 only in the suffix of HMLP rows belonging to video tiles. Companion still images remain ahead of complete timestamped Inkling content parts inside the current user turn and retain duplicated temporal planes. Native chained MTP is available for B = 1 with the original `model.mtp.layers.*` tensors for standalone text targets and text-only requests on HMLP-wrapped checkpoints. Speculative decode uses the wrapper's `text` backbone, while image-, audio-, and video-bearing requests stay on the classic prepared-embedding prefill path before continuing through the shared text target. MTP shares the target embedding, final norm, and LM head, and after verification keeps the accepted prefix of the verify block's exact KV plus four-convolution state. Prompt-lookup speculation (`--prompt-lookup`, the server's `--draft-kind prompt-lookup`) runs on text-only requests while `MLXCEL_INKLING_ROW_INVARIANT` is on (the default, issue #3422): a token-only verify block of 2 to 16 rows is byte-identical to single-token decode, and its rejected tail is dropped by trimming the KV tail and taking each convolution state from the block's recorded input window. At temperature 0 the text equals classic decode on both checkpoints; on an M3 Ultra a copy-heavy reply runs 1.14x classic on `Inkling-Small-mlx-4bit` and 2.12x on `Inkling-0.6B-A0.6B` (`benchmark_results/inkling-prompt-lookup-m3ultra-2026-11-25.md`). The loader accepts original bf16/f32, native ModelOpt NVFP4, and pre-converted affine MLX text weights, plus dense or affine-quantized HMLP projections and dense or affine-quantized audio embeddings. Fused kernels, padded batching, and image-feature caching remain separate work. Validation covers f64-referenced dMel extraction and quantization, summed-channel audio embeddings, deterministic HMLP planning/folding, tiling/normalization, placeholder cardinality, image-then-audio scatter, current-user audio insertion with history, clip-local adjacent-frame selection, temporal suffix splicing, pre-decode resource caps, timestamp drift, raw-weight detection and normalization, the synthetic text graph, caches, sanitizer, chat markers, deterministic tiny-model greedy MTP parity, exact snapshot/replay, wrapper dispatch, and prepared-prefill preservation. Every Inkling checkpoint loads in its own dtype: the bf16 -> f16 load-time cast is skipped for the family, because the native NVFP4 export declares its quantization only in `hf_quant_config.json`, read as unquantized, and decoded every greedy token to id 0 once its bf16 dense weights were cast to f16 (issue #1549). Real-checkpoint validation on an M3 Ultra (512 GB, issue #1549): `inference-optimization/Inkling-0.6B-A0.6B` under `MLXCEL_FUSED_MOE=0` matches HF `transformers` 5.24.0 (`InklingForConditionalGeneration`, float32, CPU) token for token on nine RAW greedy prompts of up to 64 tokens, each up to the reference's first `<|endoftext|>`. `mlx-community/Inkling-Small-mlx-4bit` produces the same 128 greedy tokens as mlx-vlm on a chat-template prompt; it names two tabby cats, a pink blanket and the TV remotes in COCO image 39769 through both `--image` and server `image_url`; it transcribes a clean five-second 16 kHz WAV word for word (WER 0, 100 audio placeholders, `ceil(80000 / 800)`) through both `--audio` and `input_audio`; and for a synthetic 4 s clip of a red square moving left to right it answers "to the right" (8 sampled frames at 2 fps, 4 adjacent pairs anchored at 0.0, 1.1, 2.2 and 3.3 s, 216 video tokens). CLI and server outputs are byte-identical for all four, and the process peaks at about 154 to 158 GB. `thinkingmachines/Inkling-Small-NVFP4` gives the same image, audio and video answers and agrees with mlx-vlm's NVFP4 load (which applies the same per-expert `scale2` sidecars) for its first 354 characters before a near-tie reorders two words; it peaks at about 274 GB.) - Inkling 2 Small and Mini (`inkling2`, `inkling2_loop`, issue #3228): a new text and vision architecture, not a revision of Inkling. The text decoder adds block attention residuals (a softmax over completed six-layer blocks feeds every attention, MLP and final input), query-dependent attention sinks, separate q/k/v input norms, value RMS norm and l2-clipped q/k/r, dynamic short convolutions on the global layers, sigmoid routing with a correction bias and route scale, softcapped SwiGLU experts, and tanh-softcapped logits trimmed to the 200058-token vocabulary; it reuses Inkling's banded relative-position mask, log-position temperature and f32 short-convolution states. Mini runs its middle 12 layers three times (48 layer visits over 24 physical layers), with per-visit caches and cross-pass message controllers on the attention, k, v and MLP inputs; `MLXCEL_INKLING2_LOOP_PASSES` overrides the pass count for diagnostics. Each visit keeps a chronological KV cache: a sliding visit retains at most `L + W - 1 + 64` keys and attends over the newest `L + W - 1` plus the zero sink row, which equals mlx-vlm's `AttentionSinkKVCache` (upstream f2956e68), and the convolution histories keep 16 extra rows, so a tail trim of up to 16 tokens (and within the sliding margin) rewinds KV and convolution state exactly; a deeper trim is refused without changing any state. The vision tower is a 2-D RoPE ViT over 40x40 tiles with no resize (`ceil(h/40) x ceil(w/40)` tiles, -1 padding, alpha composited on a checkerboard), and each image placeholder expands to `rows * cols` features. The loader reads the native release (`model.llm.*` / `model.visual.*`, BF16 and FP32 cast groups plus NVFP4 experts in layers 0-19 and MXFP8 experts in layers 20-23 as declared by `hf_quant_config.json`, with `2688 * amax / denominator` as the NVFP4 global scale), the Transformers layout of `mlx-community/Inkling-2-Mini-4bit` (affine 4-bit group-64 dense projections and tables, experts kept in their native formats), and mlx-vlm conversions; every Inkling 2 checkpoint keeps its own dtype at load. The template's reasoning effort is set with `--reasoning-effort LEVEL` on `mlxcel generate` and `mlxcel run` (a named level or a number in [0.0, 0.99]; the template default is 0.9), and the KV banner counts the 48 per-visit caches of Mini, not the 24 physical layers (issue #3378). Text, single and multiple images (CLI `--image`, server `image_url`) and tool calls are supported; tool calls use the Inkling message framing `<|message_model|>NAME<|content_invoke_tool_json|>{"name": ..., "args": {...}}<|end_message|>` (shared with Inkling 1's template) streaming and non-streaming, and a malformed invoke message yields no call and is dropped from the content, as every other family's unparsed tool markup is. Batched decode is native (issue #3377): one forward over every row, with only the attention core run per row against its own cache, and a cohort of cold prompts prefills in one right-padded forward whose padding is trimmed exactly; on an M3 Ultra the server's aggregate throughput at 8 concurrent requests goes from 25.9 to 62.7 tok/s (native) and from 30.3 to 62.7 tok/s (4-bit), B = 1 output is unchanged, and B = 4 and 8 traces agree with B = 1 on every decided position (`docs/benchmark_results/inkling2-batched-decode-m3ultra-2026-11-24.md`). Audio and `is_varloop` are not supported. The DSpark drafter bundled in `mtp.safetensors` runs through `--draft-model` set to the target directory (issue #3374; see the DSpark row of the speculative decoding table). The checkpoints carry no audio weights (only `model.llm.*` and `model.visual.*`, no `audio_config`; Small's index lists 1348 `model.llm.*` and 422 `model.visual.*` of its 1770 tensors and no audio or Whisper tensor, and its chat template is Mini's) and the official chat template raises on audio parts, so audio is refused up front with `audio input is not supported - hint: Inkling 2 has no audio encoder; its checkpoints carry only text and vision weights`: HTTP 501 `not_supported_error` on `/v1/chat/completions` (`input_audio` and `audio_url`), `/v1/responses`, `/v1/messages` and its `count_tokens`, `/apply-template` and `/v1/audio/transcriptions`, before any clip is fetched, and a non-zero exit from `mlxcel generate`/`run --audio` before the weights load (issue #3376). On Metal, Mini runs mlx-vlm's three kernels (issue #3359): a fused short convolution (bf16, up to 4 rows of up to 8 tokens), fused attention head preparation (one sequence, up to 8 tokens) and, inside a speculative verify forward of 2 to 8 tokens, a grouped NVFP4/MXFP8 expert matvec that decodes each expert once for all its routes; each matches the ops path bitwise, and `MLXCEL_INKLING2_KERNELS=0` turns all three off. Decode on an M3 Ultra goes from 32.1 to 35.3 tok/s (native) and from 36.8 to 44.8 tok/s (4-bit), and a verify forward of 8 tokens from 60.4 to 51.8 ms (`docs/benchmark_results/inkling2-mini-kernels-m3ultra-2026-11-24.md`). Prompt-lookup speculation (`--prompt-lookup`) is supported: a rejected verify block is rewound from the model's own state, and a verify block keeps as many extra convolution rows as it appends, so a block of any allowed length can be dropped whole. Small (`thinkingmachines/Inkling-2-Small`, 363 GiB of target weights) runs on a 512 GB host (issue #3373): the loader evaluates the sanitized weights one decoder layer at a time with the MLX buffer cache off, as mlx-vlm's README does for Small, so the contiguous gate and up copies split from each expert `w13` are not all built by the first token (which took the process to 459 GiB on the unbounded path); the MLX peak is 367 GiB and `mlxcel inspect` estimates 365 GiB for weights, KV and activations. On an M3 Ultra its 128 greedy tokens match mlx-vlm 466069f5, teacher-forced traces have 0 of 409 (text) and 0 of 88 (image, 600 identical prompt ids) decided-position disagreements, decode runs at 19.5 tok/s (mlx-vlm 20.5) with the short convolution kernel as the only kernel taken (Small has no `loop_config`), four concurrent server requests reach 36.8 tok/s in aggregate, and the bundled 5-layer DSpark drafter, under `MLXCEL_MTP_ALLOW_INEXACT=1` since the exactness probe declines as on Mini, goes from 19.3 to 33.0 tok/s on a code prompt and breaks even on prose (`docs/benchmark_results/inkling2-small-m3ultra-2026-11-24.md`). Validation on an M3 Ultra (512 GB): on `models/inkling-2-mini` (native) `mlxcel generate -p "Explain why the sky is blue." -n 128 --temp 0` produces the same 128 greedy tokens as mlx-vlm 466069f5 at the template's default effort, and a teacher-forced trace over 1024 positions has 0 of 490 decided-position disagreements (27 undecided, all within a 0.33 logit gap, perplexity -0.21%); forcing one loop pass (`MLXCEL_INKLING2_LOOP_PASSES=1`) turns the answer into repetitive text, so the loop is load-bearing. The image prompt `What is in this image?` on a 1280 x 720 photograph (18 x 32 tiles) renders the same 600 prompt ids as mlx-vlm, and its teacher-forced 128-token continuation has 0 of 76 decided disagreements (greedy output agrees for the first 440 characters, then a near-tie picks another word); the server's `image_url` answer is byte-identical to the CLI's. On `models/inkling-2-mini-4bit` (loaded into mlx-vlm through a rename-only remap, since 466069f5 reads only the native layout; the remap is `scripts/inkling2_mlx_community_remap.py`, used by the `--inkling2-mlx-community` flag of the two logit-trace scripts, issue #3378) the trace has 0 of 494 decided disagreements (perplexity -0.17%) and greedy output agrees for 45 tokens before an undecided position. The server answers the `get_weather` example with a structured `tool_calls` entry, streaming and non-streaming, with no recipient or JSON in `delta.content`. Before the kernels, decode ran at about 32 tok/s on both checkpoints (mlx-vlm: 32.8 native, 38.5 4-bit), and the processes peak at 17.6 GB (native) and 15.5 GB (4-bit). - TeleChat3 (`telechat3`, TeleAI: structurally a stock Llama decoder (RMSNorm, GQA, SwiGLU, untied `lm_head`), so what matters is the one thing that is not stock. `Telechat3-36B-Thinking` ships `rope_scaling.rope_type = "telechat3-yarn"` with `factor: 4.0`, `original_max_position_embeddings: 8192`, `beta_fast: 32` and `beta_slow: 1`. Upstream routes that into the same `YarnRoPE` it uses for `"yarn"` and `"deepseek_yarn"`: the vendor prefix names the checkpoint that produced the config, not a different algorithm, so the shared YaRN reader accepts all three spellings. This is why the family does not reuse the `llama3` decoder. `llama3::ModelArgs` reads its `rope_scaling` field since #1355, but only for the `default`, `linear` and `llama3` schemes, and it carries no `beta_fast` / `beta_slow`, so routing TeleChat3 through that path would warn once and then rotate at the unscaled base while every tensor kept the right shape; YaRN and default RoPE agree closely at small offsets and only diverge past `original_max_position_embeddings`, so no short-prompt output could expose it. TeleChat3 also keeps `rope_theta` at the top level of `config.json` while the shared reader looks for it inside the scaling block (defaulting to 500000, not this family's 1000000), so the base is injected into the block before the table is built; a table built at the wrong base is finite, correctly shaped and wrong. `attention_bias` puts bias terms on q/k/v/o and is plumbed because the family declares it, but the published 36B checkpoint sets it **false**, so it is not what distinguishes this family in practice. Like every other text family here it satisfies the maskless-prefill contract by routing a multi-token prefill with no caller mask through `causal_attention`. Not wired for tensor parallel, for the same reason it does not reuse the llama3 decoder: the TP runtime parses `config.json` straight into `llama3::ModelArgs`, which has no YaRN branch, so a sharded TeleChat3 would drop the scaling. Validation checkpoint: `mlx-community/Telechat3-36B-Thinking-4bit`.) diff --git a/src/distributed/tensor_parallel/inference.rs b/src/distributed/tensor_parallel/inference.rs index 87865340dd..cd225a124c 100644 --- a/src/distributed/tensor_parallel/inference.rs +++ b/src/distributed/tensor_parallel/inference.rs @@ -409,6 +409,7 @@ fn fallback_architecture(model_type: ModelType) -> &'static str { ModelType::Flint => "flint", ModelType::Laguna => "laguna", ModelType::Limite => "limite", + ModelType::Ricursive => "ricursive", ModelType::MiniCPM | ModelType::MiniCPMOVLM => "minicpm", ModelType::MiniCPM3 => "minicpm3", ModelType::StableLM => "stablelm", diff --git a/src/execution/memory_estimate.rs b/src/execution/memory_estimate.rs index 40cfa3f7f2..9b3e2e8a8a 100644 --- a/src/execution/memory_estimate.rs +++ b/src/execution/memory_estimate.rs @@ -1372,6 +1372,7 @@ fn inspect_registry_id(model_type: ModelType) -> &'static str { ModelType::Flint => "flint", ModelType::Laguna => "laguna", ModelType::Limite => "limite", + ModelType::Ricursive => "ricursive", ModelType::Helium => "helium", ModelType::Lille130m => "lille_130m", ModelType::K2Horizon => "k2_horizon", diff --git a/src/lib/mlxcel-core/src/cache.rs b/src/lib/mlxcel-core/src/cache.rs index 8e76574a18..0db6ea19fe 100644 --- a/src/lib/mlxcel-core/src/cache.rs +++ b/src/lib/mlxcel-core/src/cache.rs @@ -4539,7 +4539,7 @@ pub fn cache_window(family: &str, window: usize, has_sliding_layer: bool) -> Res /// Used by: AFMoE, DeepSeek V4, Exaone4, Exaone MoE, Gemma3 (and its backbone /// and embedding variants), Gemma4 (MTP target and verify rows included), /// GPT-OSS, IQuestLoopCoder, Kolibri-1, Laguna, Llama4, Mellum, Ministral3, MiMo V2 -/// Flash, Muse Glimmer, OpenAI privacy filter, RecurrentGemma, Step3.5 +/// Flash, Muse Glimmer, OpenAI privacy filter, RecurrentGemma, Ricursive, Step3.5 pub struct RotatingKVCache { pub keys: Option>, pub values: Option>, diff --git a/src/lib/mlxcel-core/src/cache/attend.rs b/src/lib/mlxcel-core/src/cache/attend.rs index ec2dddc5be..e49751f735 100644 --- a/src/lib/mlxcel-core/src/cache/attend.rs +++ b/src/lib/mlxcel-core/src/cache/attend.rs @@ -495,7 +495,8 @@ pub fn attend_batched( /// not repeatedly copy growing intermediates as the batch gets wider. /// /// Used by: [`attend_batched`], `models::gemma3::Attention::forward_batched_decode`, -/// `models::llama4::CxxAttention::forward_batched_decode_rows`. +/// `models::llama4::CxxAttention::forward_batched_decode_rows`, +/// `models::ricursive::RicursiveAttention::forward_batched_decode`. pub fn attend_batched_rows( q_batched: &MlxArray, k_batched: &MlxArray, diff --git a/src/lib/mlxcel-core/src/utils.rs b/src/lib/mlxcel-core/src/utils.rs index 959c0f73a5..746b492ece 100644 --- a/src/lib/mlxcel-core/src/utils.rs +++ b/src/lib/mlxcel-core/src/utils.rs @@ -355,7 +355,8 @@ impl PrefillAttention { /// Ministral3, Exaone4, ExaoneMoe, Mellum, Step3P5, AFMoE and Gemma3n /// (#3072); GptOss, FalconOcr and the sink full layers of MiMoV2 (#3098); /// the NoPE global layers of Limite (#2360); the full layers of OlmoHybrid, -/// Plamo3 (#2374) and Spark-X2.5 (#2372); and Gear's full-attention layers (#2376). +/// Plamo3 (#2374) and Spark-X2.5 (#2372); Gear's full-attention layers (#2376); +/// and the NoPE full layers of Ricursive (#3224). pub fn prefill_causal_mask( seq_len: i32, offset: i32, @@ -438,7 +439,8 @@ pub enum SlidingPrefillKeys { /// ExaoneMoe, Mellum, Step3P5, AFMoE, Gemma3n; GptOss, MiMoV2 and an all-local /// DeepSeekV4 stack (#3098); Limite, whose window is `sliding_window + 1` /// (#2360); Spark-X2.5, whose window is `sliding_window` -/// (#2372); and Gear's sliding-attention layers (#2376). +/// (#2372); Gear's sliding-attention layers (#2376); and Ricursive's sliding +/// layers (#3224). pub fn prefill_sliding_window_mask( seq_len: i32, prior: i32, diff --git a/src/loaded_model.rs b/src/loaded_model.rs index a87f38b898..a44e2c10e8 100644 --- a/src/loaded_model.rs +++ b/src/loaded_model.rs @@ -244,6 +244,7 @@ pub enum LoadedModel { Laguna(models::LagunaWrapper), // Sliding/global caches owned per sequence by the wrapper. Limite(models::LimiteWrapper), + Ricursive(models::RicursiveWrapper), MiniCPM(models::MiniCPMModel), MiniCPM3(models::MiniCPM3Model), StableLM(models::StableLMModel), @@ -460,6 +461,7 @@ macro_rules! delegate_language_model { LoadedModel::Flint(inner) => LanguageModel::$method(inner, $($arg),*), LoadedModel::Laguna(inner) => LanguageModel::$method(inner, $($arg),*), LoadedModel::Limite(inner) => LanguageModel::$method(inner, $($arg),*), + LoadedModel::Ricursive(inner) => LanguageModel::$method(inner, $($arg),*), LoadedModel::MiniCPM(inner) => LanguageModel::$method(inner, $($arg),*), LoadedModel::MiniCPM3(inner) => LanguageModel::$method(inner, $($arg),*), LoadedModel::StableLM(inner) => LanguageModel::$method(inner, $($arg),*), diff --git a/src/model_metadata.rs b/src/model_metadata.rs index 6806da86f1..9a2e4ec569 100644 --- a/src/model_metadata.rs +++ b/src/model_metadata.rs @@ -269,6 +269,7 @@ macro_rules! for_each_model_registration { Flint => { kind: Text, directory: ConfigBacked, weight: Some(WeightLoadRoute::ConfigBacked), adapter: None, config_backed: { dir_loader: models::flint::load, args: models::flint::ModelArgs, weight_builder: models::flint::from_weights, wrap: |m| LoadedModel::Flint(models::LagunaWrapper::new(m)) } }; Laguna => { kind: Text, directory: ConfigBacked, weight: Some(WeightLoadRoute::ConfigBacked), adapter: None, config_backed: { dir_loader: models::LagunaModel::load, args: models::laguna::ModelArgs, weight_builder: models::LagunaModel::from_weights, wrap: |m| LoadedModel::Laguna(models::LagunaWrapper::new(m)) } }; Limite => { kind: Text, directory: ConfigBacked, weight: Some(WeightLoadRoute::ConfigBacked), adapter: None, config_backed: { dir_loader: models::LimiteModel::load, args: models::limite::ModelArgs, weight_builder: models::LimiteModel::from_weights, wrap: |m| LoadedModel::Limite(models::LimiteWrapper::new(m)) } }; + Ricursive => { kind: Text, directory: ConfigBacked, weight: Some(WeightLoadRoute::ConfigBacked), adapter: None, config_backed: { dir_loader: models::RicursiveModel::load, args: models::ricursive::ModelArgs, weight_builder: models::RicursiveModel::from_weights, wrap: |m| LoadedModel::Ricursive(models::RicursiveWrapper::new(m)) } }; MiniCPM => { kind: Text, directory: ConfigBacked, weight: Some(WeightLoadRoute::ConfigBacked), adapter: None, config_backed: { dir_loader: models::MiniCPMModel::load, args: models::minicpm::ModelArgs, weight_builder: models::MiniCPMModel::from_weights, wrap: LoadedModel::MiniCPM } }; MiniCPM3 => { kind: Text, directory: ConfigBacked, weight: Some(WeightLoadRoute::ConfigBacked), adapter: None, config_backed: { dir_loader: models::MiniCPM3Model::load, args: models::minicpm3::ModelArgs, weight_builder: models::MiniCPM3Model::from_weights, wrap: LoadedModel::MiniCPM3 } }; StableLM => { kind: Text, directory: ConfigBacked, weight: Some(WeightLoadRoute::ConfigBacked), adapter: None, config_backed: { dir_loader: models::StableLMModel::load, args: models::stablelm::ModelArgs, weight_builder: models::StableLMModel::from_weights, wrap: LoadedModel::StableLM } }; diff --git a/src/models/batched_decode_coverage_tests.rs b/src/models/batched_decode_coverage_tests.rs index 03ca256084..7431e1c80d 100644 --- a/src/models/batched_decode_coverage_tests.rs +++ b/src/models/batched_decode_coverage_tests.rs @@ -136,6 +136,7 @@ const EXPECTED_NATIVE: &[&str] = &[ "Qwen3VLMoeModel@src/models/qwen3_vl_moe.rs", "Qwen3VLMoeModel@src/vision/qwen3_vl_moe.rs", "Raon1MiniModel@src/models/raon1_mini_lm.rs", + "RicursiveWrapper@src/models/ricursive.rs", "Rwkv7@src/models/rwkv7.rs", "SeedOssModel@src/models/seed_oss.rs", "SmolLM3Model@src/models/smollm3.rs", diff --git a/src/models/deepseek_v4_moe.rs b/src/models/deepseek_v4_moe.rs index 32dff01738..5f44d7de80 100644 --- a/src/models/deepseek_v4_moe.rs +++ b/src/models/deepseek_v4_moe.rs @@ -62,13 +62,12 @@ use super::{ModelArgs, ScoringFunc, get_weight_copy}; /// `silu(min(gate, limit)) * clip(up, -limit, limit)` (`_limited_swiglu`). /// A non-positive limit disables clamping, as in the reference. +/// +/// Used by: DeepSeekV4 (`LimitedSwitchGlu` and `LimitedMlp` here) and +/// DeepSeekV4.1 (`deepseek_v41_moe.rs`). Ricursive takes the same clamp +/// through [`limited_swiglu_f32_silu`]. pub(crate) fn limited_swiglu(gate: &MlxArray, up: &MlxArray, limit: f32) -> UniquePtr { - if limit > 0.0 { - let dtype = mlxcel_core::array_dtype(gate); - let limit_arr = mlxcel_core::full_f32(&[1], limit, dtype); - let neg_limit = mlxcel_core::full_f32(&[1], -limit, dtype); - let gate = mlxcel_core::minimum(gate, &limit_arr); - let up = mlxcel_core::clip(up, &neg_limit, &limit_arr); + if let Some((gate, up)) = clamp_swiglu_inputs(gate, up, limit) { let gate = mlxcel_core::utils::silu(&gate); mlxcel_core::multiply(&gate, &up) } else { @@ -77,6 +76,47 @@ pub(crate) fn limited_swiglu(gate: &MlxArray, up: &MlxArray, limit: f32) -> Uniq } } +/// [`limited_swiglu`] with the SiLU computed in FP32 and rounded once to the +/// gate's dtype before the multiplication by `up` (Ricursive's +/// `_clipped_swiglu`). The clamp and its non-positive-limit opt-out are the +/// same. +/// +/// Used by: Ricursive. +pub(crate) fn limited_swiglu_f32_silu( + gate: &MlxArray, + up: &MlxArray, + limit: f32, +) -> UniquePtr { + let silu_rounded = |gate: &MlxArray| { + let silu = + mlxcel_core::utils::silu(&mlxcel_core::astype(gate, mlxcel_core::dtype::FLOAT32)); + mlxcel_core::astype(&silu, mlxcel_core::array_dtype(gate)) + }; + if let Some((gate, up)) = clamp_swiglu_inputs(gate, up, limit) { + mlxcel_core::multiply(&silu_rounded(&gate), &up) + } else { + mlxcel_core::multiply(&silu_rounded(gate), up) + } +} + +/// `(min(gate, limit), clip(up, -limit, limit))` in the gate's dtype, or +/// `None` for a non-positive limit (no clamp). +fn clamp_swiglu_inputs( + gate: &MlxArray, + up: &MlxArray, + limit: f32, +) -> Option<(UniquePtr, UniquePtr)> { + (limit > 0.0).then(|| { + let dtype = mlxcel_core::array_dtype(gate); + let limit_arr = mlxcel_core::full_f32(&[1], limit, dtype); + let neg_limit = mlxcel_core::full_f32(&[1], -limit, dtype); + ( + mlxcel_core::minimum(gate, &limit_arr), + mlxcel_core::clip(up, &neg_limit, &limit_arr), + ) + }) +} + /// Apply the configured scoring function to f32 logits. fn score_logits(logits_f32: &MlxArray, func: ScoringFunc) -> UniquePtr { match func { diff --git a/src/models/detection.rs b/src/models/detection.rs index 08c15bd123..52b2edc3ef 100644 --- a/src/models/detection.rs +++ b/src/models/detection.rs @@ -1185,6 +1185,7 @@ pub(crate) fn detect_model_type_with_probes( "flint" => Ok(ModelType::Flint), "laguna" => Ok(ModelType::Laguna), "limite" => Ok(ModelType::Limite), + "ricursive" => Ok(ModelType::Ricursive), "minicpm" => Ok(ModelType::MiniCPM), "minicpm3" => Ok(ModelType::MiniCPM3), "stablelm" => Ok(ModelType::StableLM), diff --git a/src/models/detection_tests.rs b/src/models/detection_tests.rs index 1e0dbd96e4..492f32de31 100644 --- a/src/models/detection_tests.rs +++ b/src/models/detection_tests.rs @@ -1081,6 +1081,17 @@ fn mellum_model_type_is_detected() { fs::remove_dir_all(model_dir).unwrap(); } +#[test] +fn ricursive_model_type_is_detected() { + assert_eq!( + detect_config( + "ricursive", + json!({ "model_type": "ricursive", "architectures": ["RicursiveForCausalLM"] }) + ), + ModelType::Ricursive + ); +} + #[test] fn limite_model_type_is_detected() { let model_dir = temp_path("limite_text"); diff --git a/src/models/mod.rs b/src/models/mod.rs index aa095d76f0..92331b4e46 100644 --- a/src/models/mod.rs +++ b/src/models/mod.rs @@ -361,6 +361,7 @@ pub(crate) mod raon_mhc; pub(crate) mod raon_rda; pub mod reasoning_effort_steering; pub mod recurrent_gemma; +pub mod ricursive; pub mod rwkv7; pub mod seed_oss; pub mod siglip_text; @@ -549,6 +550,7 @@ pub use qwen3_vl_moe::Qwen3VLMoeModel; pub use qwen4_exp::Qwen4ExpModel; pub use raon1_mini::Raon1MiniModel; pub use recurrent_gemma::GriffinModel; +pub use ricursive::{RicursiveModel, RicursiveWrapper}; pub use rwkv7::Rwkv7; pub(crate) use sanitize::{ Gemma4WeightBacking, config_has_quantization_metadata, is_modelopt_nvfp4_text_checkpoint, @@ -845,6 +847,7 @@ pub enum ModelType { Laguna, // Poolside Laguna XS / S (hybrid sliding/full MoE with NVFP4 experts) Limite, // Paradigma Limite (MUDD dense connections, sliding/NoPE-global, sigmoid-softcapped head) + Ricursive, // Ricursive Ripple (sandwich norms, sliding RoPE / NoPE-global, value residuals) // Other Transformer models Lille130m, // Lille 130M (fused-QKV GQA, in-sublayer RMSNorm, traditional RoPE) @@ -1150,6 +1153,7 @@ pub const ALL_MODEL_TYPES: &[ModelType] = &[ ModelType::Mellum, ModelType::Laguna, ModelType::Limite, + ModelType::Ricursive, // Other Transformer models ModelType::Helium, ModelType::Lille130m, @@ -1628,6 +1632,10 @@ impl ModelType { ModelType::Flint => ("Flint (RecursiveSI hybrid MoE)", "MoE (other)"), ModelType::Laguna => ("Laguna XS / S (Poolside code, hybrid MoE)", "Specialized"), ModelType::Limite => ("Paradigma Limite (MUDD, sliding/global)", "Specialized"), + ModelType::Ricursive => ( + "Ricursive Ripple (sliding/NoPE-global, value residuals)", + "Specialized", + ), ModelType::StableLM => ("StableLM", "Specialized"), ModelType::Baichuan => ("Baichuan", "Specialized"), ModelType::MiniCPM => ("MiniCPM 1", "Specialized"), @@ -1946,6 +1954,7 @@ mod metadata_tests { Flint, Laguna, Limite, + Ricursive, Helium, Lille130m, K2Horizon, diff --git a/src/models/model_owned.rs b/src/models/model_owned.rs index bea7361f6f..f97b5fbee4 100644 --- a/src/models/model_owned.rs +++ b/src/models/model_owned.rs @@ -174,7 +174,8 @@ impl KvCacheLayerModes { /// called with a scheduler sequence id (ADR 0010). /// /// Used by: `kolibri1`, `muse_glimmer`, `mimo_v2_flash`, `gpt_oss`, -/// `ministral3`, `exaone4`, `mellum`, `laguna`, `step3p5`, `limite`. +/// `ministral3`, `exaone4`, `mellum`, `laguna`, `step3p5`, `limite`, +/// `ricursive`. pub(crate) fn refuse_scheduler_owned_sequence_id(family: &str, seq_id: SequenceId) -> ! { panic!( "{family} state is scheduler-owned: sequence {seq_id} must be forwarded through \ @@ -188,7 +189,7 @@ pub(crate) fn refuse_scheduler_owned_sequence_id(family: &str, seq_id: SequenceI /// batches panic (ADR 0010, #3325). /// /// Used by: `kolibri1`, `gpt_oss`, `ministral3`, `exaone4`, `mellum`, -/// `laguna`, `step3p5`, `limite`. +/// `laguna`, `step3p5`, `limite`, `ricursive`. pub(crate) fn forward_scheduler_owned_anonymous_batch< M: mlxcel_core::generate::LanguageModel + ?Sized, >( @@ -213,7 +214,8 @@ pub(crate) fn forward_scheduler_owned_anonymous_batch< /// their pool `LayerState` directly (issue #1755, ADR 0010). /// /// Used by: `kolibri1`, `muse_glimmer`, `mimo_v2_flash`, `gpt_oss`, -/// `ministral3`, `exaone4`, `mellum`, `laguna`, `step3p5`, `limite`. +/// `ministral3`, `exaone4`, `mellum`, `laguna`, `step3p5`, `limite`, +/// `ricursive`. pub(crate) fn trim_fallback_layer_state( family: &str, fallback: &RefCell>, @@ -241,7 +243,8 @@ pub(crate) fn trim_fallback_layer_state( /// and return the input shape. /// /// Used by: `kolibri1`, `muse_glimmer`, `mimo_v2_flash`, `gpt_oss`, -/// `ministral3`, `exaone4`, `mellum`, `laguna`, `step3p5`, `limite`. +/// `ministral3`, `exaone4`, `mellum`, `laguna`, `step3p5`, `limite`, +/// `ricursive`. pub(crate) fn validate_layer_state_forward( family: &str, n_layers: usize, diff --git a/src/models/registry.rs b/src/models/registry.rs index c2fa139a92..11db3e244f 100644 --- a/src/models/registry.rs +++ b/src/models/registry.rs @@ -860,6 +860,7 @@ impl ModelType { ModelType::Flint => "flint", ModelType::Laguna => "laguna", ModelType::Limite => "limite", + ModelType::Ricursive => "ricursive", ModelType::Helium => "helium", ModelType::Lille130m => "lille_130m", ModelType::K2Horizon => "k2_horizon", @@ -1307,6 +1308,7 @@ pub(crate) fn model_type_keys(model_type: ModelType) -> &'static [&'static str] ModelType::Flint => &["flint"], ModelType::Laguna => &["laguna"], ModelType::Limite => &["limite"], + ModelType::Ricursive => &["ricursive"], ModelType::MiniCPM => &["minicpm"], ModelType::MiniCPM3 => &["minicpm3"], ModelType::StableLM => &["stablelm"], diff --git a/src/models/ricursive.rs b/src/models/ricursive.rs new file mode 100644 index 0000000000..0557f26062 --- /dev/null +++ b/src/models/ricursive.rs @@ -0,0 +1,1183 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Ricursive Ripple (`model_type: ricursive`, `RicursiveForCausalLM`). +//! +//! A dense decoder following mlx-vlm's `ricursive` port (Blaizzy/mlx-vlm#2697), +//! which in turn follows the checkpoint's `modeling_ricursive.py`: +//! - `layer_types` mixes RoPE sliding-window layers (a `RotatingKVCache`) with +//! NoPE full-attention layers (a growing cache); a null `sliding_window` +//! gives every layer a growing cache and a plain causal mask. +//! - Four RMS norms per block (`input`, `post_attention`, `pre_feedforward`, +//! `post_feedforward`) plus per-head `q_norm` / `k_norm`. The reference +//! normalizes in FP32, rounds to the activation dtype and then applies the +//! weight, which is the order MLX's fused `rms_norm` kernel already follows +//! (`w * T(x * inv)` on CUDA and Metal), so every norm is the shared +//! [`RMSNorm`]. The single-rounding form is `rms_norm_round_once`. +//! - Value residuals: every layer's `v_proj` input is +//! `lerp(h0, x_normed, sigmoid(value_res_lambda))`, where `h0` is the scaled +//! input embedding ([`value_residual_lerp`]). +//! - An elementwise sigmoid output gate (`g_proj`), clipped SwiGLU +//! (`ffn_clamp_threshold`) with an FP32 SiLU, and `embed_scale` applied in +//! FP32 after the embedding lookup. +//! +//! The rotary embedding keeps the upstream rounding: cos and sin are computed +//! in FP32, rounded to the activation dtype, and the rotation runs in FP32 +//! before one final rounding ([`RicursiveRope`]). +//! +//! Per-sequence sliding/full cache state is scheduler-owned (ADR 0010): the +//! pool holds one [`LayerState`] per layer and hands it to +//! [`LanguageModel::forward_layer_state`]. Every layer stores FP16 KV. + +use crate::models::model_owned::{ + forward_scheduler_owned_anonymous_batch, refuse_scheduler_owned_sequence_id, + table_less_storage_modes, trim_fallback_layer_state, validate_layer_state_forward, +}; +use mlxcel_core::cache::{ + KVCacheMode, LayerState, LayerStateEncoding, LayerStateForward, LayerStateKind, + LayerStateSnapshotSpec, SequenceId, attend_batched_rows, +}; +use mlxcel_core::generate::{BatchedDecodeKind, LanguageModel}; +use mlxcel_core::layers::{KVCache, RMSNorm, UnifiedEmbedding, UnifiedLinear}; +use mlxcel_core::utils::{ + PrefillAttention, SlidingPrefillKeys, prefill_causal_mask, prefill_sliding_window_mask, +}; +use mlxcel_core::weights::WeightMap; +use mlxcel_core::{MlxArray, UniquePtr}; +use serde::Deserialize; +use std::cell::RefCell; +use std::path::Path; + +const FULL_ATTENTION: &str = "full_attention"; +const SLIDING_ATTENTION: &str = "sliding_attention"; +const FAMILY: &str = "Ricursive"; + +// Configuration. + +/// The MLX `quantization` block. Every module loads with the one default +/// `group_size`/`bits` pair, so per-module entries are kept only to refuse +/// the ones that differ from it (see [`Quantization::validate_uniform`]). +#[derive(Debug, Clone, Deserialize)] +pub struct Quantization { + pub group_size: i32, + pub bits: i32, + /// `mode` and the per-module-path entries of a mixed conversion. + #[serde(flatten)] + pub rest: serde_json::Map, +} + +impl Quantization { + /// Refuse per-module overrides. Mixed conversions such as + /// `araysuter/Ripple-65B-Preview-MLX-mixed-2bit` quantize some modules at + /// another `bits`/`group_size`; this loader reads every module with the + /// default pair and would mis-read those planes. An entry that repeats the + /// default is accepted. + fn validate_uniform(&self) -> Result<(), String> { + let mode = |v: &serde_json::Value| { + v.get("mode") + .and_then(serde_json::Value::as_str) + .unwrap_or("affine") + .to_string() + }; + let default_mode = self + .rest + .get("mode") + .and_then(serde_json::Value::as_str) + .unwrap_or("affine"); + for (path, entry) in &self.rest { + let same = match entry { + serde_json::Value::Object(_) => { + entry.get("group_size").and_then(serde_json::Value::as_i64) + == Some(i64::from(self.group_size)) + && entry.get("bits").and_then(serde_json::Value::as_i64) + == Some(i64::from(self.bits)) + && mode(entry) == default_mode + } + serde_json::Value::Bool(_) => false, + _ => true, + }; + if !same { + return Err(format!( + "{FAMILY}: per-module quantization overrides are not supported ({path}: \ + {entry} against the default bits {}, group_size {}); use a uniformly \ + quantized MLX conversion such as frogggias/Ripple-65B-Preview-MLX-4bit", + self.bits, self.group_size + )); + } + } + Ok(()) + } +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(untagged)] +pub enum EosTokenId { + Single(i32), + Multiple(Vec), +} + +/// `config.json` of a Ripple checkpoint. Defaults follow mlx-vlm's +/// `ModelConfig` (the published Ripple-65B-Preview values). +#[derive(Debug, Clone, Deserialize)] +pub struct ModelArgs { + #[serde(default = "default_model_type")] + pub model_type: String, + #[serde(default = "default_vocab_size")] + pub vocab_size: usize, + #[serde(default = "default_hidden_size")] + pub hidden_size: usize, + #[serde(default = "default_intermediate_size")] + pub intermediate_size: usize, + #[serde(default = "default_num_hidden_layers")] + pub num_hidden_layers: usize, + #[serde(default = "default_num_attention_heads")] + pub num_attention_heads: usize, + #[serde(default = "default_num_key_value_heads")] + pub num_key_value_heads: usize, + #[serde(default = "default_head_dim")] + pub head_dim: usize, + #[serde(default = "default_hidden_act")] + pub hidden_act: String, + #[serde(default = "default_rms_norm_eps")] + pub rms_norm_eps: f32, + /// Kept in `f64` so the inverse frequencies match the reference's Python + /// `base ** (i / dims)` before the FP32 cast. + #[serde(default = "default_rope_theta")] + pub rope_theta: f64, + /// `None` (an explicit null) gives every layer a growing cache and a plain + /// causal mask; sliding layers still rotate. + #[serde(default = "default_sliding_window")] + pub sliding_window: Option, + /// `full_attention` / `sliding_attention` per layer; when absent, layer + /// `i` is full on `i % 5 == 4` (the reference default). + #[serde(default)] + pub layer_types: Option>, + #[serde(default = "default_true")] + pub use_gated_attention: bool, + #[serde(default = "default_true")] + pub gate_full_precision: bool, + #[serde(default)] + pub use_valres: bool, + /// Clip for the SwiGLU inputs; null or 0 disables it, as in the reference. + #[serde(default)] + pub ffn_clamp_threshold: Option, + /// FP32 multiplier on the embedding lookup; null when the checkpoint + /// folds it into the table. + #[serde(default)] + pub embed_scale: Option, + #[serde(default)] + pub tie_word_embeddings: bool, + #[serde(default)] + pub eos_token_id: Option, + #[serde(default)] + pub quantization: Option, +} + +fn default_model_type() -> String { + "ricursive".to_string() +} +fn default_vocab_size() -> usize { + 100_352 +} +fn default_hidden_size() -> usize { + 5120 +} +fn default_intermediate_size() -> usize { + 40_960 +} +fn default_num_hidden_layers() -> usize { + 80 +} +fn default_num_attention_heads() -> usize { + 80 +} +fn default_num_key_value_heads() -> usize { + 8 +} +fn default_head_dim() -> usize { + 128 +} +fn default_hidden_act() -> String { + "silu".to_string() +} +fn default_rms_norm_eps() -> f32 { + 1e-6 +} +fn default_rope_theta() -> f64 { + 10_000.0 +} +fn default_sliding_window() -> Option { + Some(1024) +} +fn default_true() -> bool { + true +} + +impl ModelArgs { + pub fn group_size(&self) -> i32 { + self.quantization + .as_ref() + .map(|q| q.group_size) + .unwrap_or(64) + } + + pub fn bits(&self) -> i32 { + self.quantization.as_ref().map(|q| q.bits).unwrap_or(4) + } + + /// Whether layer `idx` is a sliding-attention (RoPE) layer. + pub fn is_sliding(&self, idx: usize) -> bool { + match &self.layer_types { + Some(types) => types.get(idx).is_some_and(|t| t == SLIDING_ATTENTION), + None => idx % 5 != 4, + } + } + + /// The clamp the MLP applies, `None` when it is null or zero. + pub fn clamp_threshold(&self) -> Option { + self.ffn_clamp_threshold.filter(|t| *t != 0.0) + } + + fn eos_token_ids(&self) -> Vec { + match &self.eos_token_id { + Some(EosTokenId::Single(id)) => vec![*id], + Some(EosTokenId::Multiple(ids)) => ids.clone(), + None => Vec::new(), + } + } + + /// The load-time checks of the reference config plus the geometry this + /// port relies on. + pub fn validate(&self) -> Result<(), String> { + if let Some(types) = &self.layer_types { + if types.len() != self.num_hidden_layers { + return Err(format!( + "{FAMILY}: layer_types has {} entries, num_hidden_layers is {}", + types.len(), + self.num_hidden_layers + )); + } + if let Some((idx, other)) = types + .iter() + .enumerate() + .find(|(_, t)| *t != FULL_ATTENTION && *t != SLIDING_ATTENTION) + { + return Err(format!( + "{FAMILY}: unsupported layer type {other:?} at layer {idx} \ + (expected {FULL_ATTENTION:?} or {SLIDING_ATTENTION:?})" + )); + } + } + if self.hidden_act != "silu" { + return Err(format!( + "{FAMILY}: unsupported hidden_act {:?} (only \"silu\")", + self.hidden_act + )); + } + if self.num_hidden_layers == 0 { + return Err(format!("{FAMILY}: num_hidden_layers must be positive")); + } + if self.num_key_value_heads == 0 + || self.num_attention_heads == 0 + || !self + .num_attention_heads + .is_multiple_of(self.num_key_value_heads) + { + return Err(format!( + "{FAMILY}: num_attention_heads ({}) must be a positive multiple of \ + num_key_value_heads ({})", + self.num_attention_heads, self.num_key_value_heads + )); + } + if self.head_dim == 0 || !self.head_dim.is_multiple_of(2) { + return Err(format!( + "{FAMILY}: head_dim ({}) must be positive and even", + self.head_dim + )); + } + if let Some(window) = self.sliding_window { + mlxcel_core::cache::validate_sliding_window(FAMILY, window)?; + } + if let Some(threshold) = self.ffn_clamp_threshold + && !(threshold.is_finite() && threshold >= 0.0) + { + return Err(format!( + "{FAMILY}: ffn_clamp_threshold ({threshold}) must be finite and non-negative" + )); + } + if let Some(scale) = self.embed_scale + && !scale.is_finite() + { + return Err(format!("{FAMILY}: embed_scale ({scale}) must be finite")); + } + if !(self.rope_theta.is_finite() && self.rope_theta > 0.0) { + return Err(format!( + "{FAMILY}: rope_theta ({}) must be finite and positive", + self.rope_theta + )); + } + if let Some(q) = &self.quantization { + mlxcel_core::layers::validate_quantization_params(q.group_size, q.bits)?; + q.validate_uniform()?; + } + Ok(()) + } +} + +// Numerics shared by every block. + +/// `lerp(residual, x, sigmoid(lambda))`, the reference `_interpolate_values`: +/// the blend is the FP32 sigmoid of `lambda` rounded to `x`'s dtype, and the +/// interpolation follows `torch.lerp` in FP32 (`seed + b * (end - seed)` for +/// `b < 0.5`, `end + (b - 1) * (end - seed)` otherwise) with one rounding to +/// `x`'s dtype. `residual` is the scaled input embedding `h0`, `x` the +/// layer's normalized attention input. +pub(crate) fn value_residual_lerp( + residual: &MlxArray, + x: &MlxArray, + lambda: &MlxArray, +) -> UniquePtr { + let f32 = mlxcel_core::dtype::FLOAT32; + let dtype = mlxcel_core::array_dtype(x); + let blend = mlxcel_core::sigmoid(&mlxcel_core::astype(lambda, f32)); + let blend = mlxcel_core::astype(&mlxcel_core::astype(&blend, dtype), f32); + let seed = mlxcel_core::astype(&mlxcel_core::astype(residual, dtype), f32); + let end = mlxcel_core::astype(x, f32); + let delta = mlxcel_core::subtract(&end, &seed); + let low = mlxcel_core::add(&seed, &mlxcel_core::multiply(&blend, &delta)); + let one = mlxcel_core::full_f32(&[1], 1.0, f32); + let high = mlxcel_core::add( + &end, + &mlxcel_core::multiply(&mlxcel_core::subtract(&blend, &one), &delta), + ); + let half = mlxcel_core::full_f32(&[1], 0.5, f32); + let blended = mlxcel_core::where_cond(&mlxcel_core::less(&blend, &half), &low, &high); + mlxcel_core::astype(&blended, dtype) +} + +/// Non-traditional (rotate-half) RoPE over the full head dimension with the +/// reference's rounding (`RotaryEmbedding` / `_apply_rotary`). +pub(crate) struct RicursiveRope { + /// `1 / base^(i / head_dim)` for even `i`, `[head_dim / 2]` FP32. + inv_freq: UniquePtr, + half: i32, +} + +/// cos and sin of one forward's positions, rounded to the activation dtype +/// and held in FP32, `[B | 1, 1, L, head_dim / 2]`. Every sliding layer of a +/// forward shares them: all layers sit at the same offset. +pub(crate) struct RopeAngles { + cos: UniquePtr, + sin: UniquePtr, +} + +impl RicursiveRope { + pub(crate) fn new(head_dim: usize, base: f64) -> Self { + // The reference builds `[base ** (i / dims) ...]` in Python floats, + // casts to FP32 and takes the reciprocal in FP32. + let inv: Vec = (0..head_dim) + .step_by(2) + .map(|i| 1.0f32 / (base.powf(i as f64 / head_dim as f64) as f32)) + .collect(); + let half = inv.len() as i32; + Self { + inv_freq: mlxcel_core::from_slice_f32(&inv, &[half]), + half, + } + } + + /// Angles for `len` new positions after each row's `offsets` entry + /// (one entry broadcasts over the batch). + pub(crate) fn angles(&self, offsets: &[i32], len: i32, dtype: i32) -> RopeAngles { + let rows = offsets.len() as i32; + let positions: Vec = offsets + .iter() + .flat_map(|&offset| (0..len).map(move |i| offset as f32 + i as f32)) + .collect(); + let positions = mlxcel_core::from_slice_f32(&positions, &[rows, 1, len, 1]); + let angles = mlxcel_core::multiply(&positions, &self.inv_freq); + let round = |a: UniquePtr| { + mlxcel_core::astype(&mlxcel_core::astype(&a, dtype), mlxcel_core::dtype::FLOAT32) + }; + RopeAngles { + cos: round(mlxcel_core::cos(&angles)), + sin: round(mlxcel_core::sin(&angles)), + } + } + + /// Rotate `x` (`[B, H, L, head_dim]`) in FP32 and round once. + pub(crate) fn apply(&self, x: &MlxArray, angles: &RopeAngles) -> UniquePtr { + let dtype = mlxcel_core::array_dtype(x); + let x = mlxcel_core::astype(x, mlxcel_core::dtype::FLOAT32); + let first = mlxcel_core::slice_last_dim(&x, 0, self.half); + let second = mlxcel_core::slice_last_dim(&x, self.half, 2 * self.half); + let mul = mlxcel_core::multiply; + let rotated_first = + mlxcel_core::subtract(&mul(&first, &angles.cos), &mul(&second, &angles.sin)); + let rotated_second = + mlxcel_core::add(&mul(&second, &angles.cos), &mul(&first, &angles.sin)); + let rotated = mlxcel_core::concatenate(&rotated_first, &rotated_second, -1); + mlxcel_core::astype(&rotated, dtype) + } +} + +// Attention. + +pub(crate) struct RicursiveAttention { + q_proj: UnifiedLinear, + k_proj: UnifiedLinear, + v_proj: UnifiedLinear, + o_proj: UnifiedLinear, + g_proj: Option, + q_norm: RMSNorm, + k_norm: RMSNorm, + /// `[1]` learned value-residual logit; `None` when `use_valres` is false. + value_res_lambda: Option>, + num_heads: i32, + num_kv_heads: i32, + head_dim: i32, + scale: f32, + gate_full_precision: bool, + /// Sliding layers rotate; full layers are NoPE. + pub(crate) is_sliding: bool, + /// Attention window of a sliding layer, 0 for full layers or a null + /// `sliding_window`. + window: i32, +} + +impl RicursiveAttention { + fn project_qkv( + &self, + x: &MlxArray, + value_residual: Option<&MlxArray>, + rope: Option<(&RicursiveRope, &RopeAngles)>, + ) -> ( + UniquePtr, + UniquePtr, + UniquePtr, + ) { + let shape = mlxcel_core::array_shape(x); + let (b, l) = (shape[0], shape[1]); + let values = match (value_residual, &self.value_res_lambda) { + (Some(residual), Some(lambda)) => self + .v_proj + .forward(&value_residual_lerp(residual, x, lambda)), + _ => self.v_proj.forward(x), + }; + let q = mlxcel_core::reshape( + &self.q_proj.forward(x), + &[b, l, self.num_heads, self.head_dim], + ); + let k = mlxcel_core::reshape( + &self.k_proj.forward(x), + &[b, l, self.num_kv_heads, self.head_dim], + ); + let v = mlxcel_core::reshape(&values, &[b, l, self.num_kv_heads, self.head_dim]); + let q = self.q_norm.forward(&q); + let k = self.k_norm.forward(&k); + let q = mlxcel_core::transpose_axes(&q, &[0, 2, 1, 3]); + let k = mlxcel_core::transpose_axes(&k, &[0, 2, 1, 3]); + let v = mlxcel_core::transpose_axes(&v, &[0, 2, 1, 3]); + match rope.filter(|_| self.is_sliding) { + Some((rope, angles)) => (rope.apply(&q, angles), rope.apply(&k, angles), v), + None => (q, k, v), + } + } + + fn project_output(&self, x: &MlxArray, attn: &MlxArray) -> UniquePtr { + let shape = mlxcel_core::array_shape(x); + let out = mlxcel_core::transpose_axes(attn, &[0, 2, 1, 3]); + let out = mlxcel_core::reshape(&out, &[shape[0], shape[1], self.num_heads * self.head_dim]); + let out = match &self.g_proj { + Some(g_proj) => { + let gate = g_proj.forward(x); + let gate = if self.gate_full_precision { + mlxcel_core::astype(&gate, mlxcel_core::dtype::FLOAT32) + } else { + gate + }; + let gate = mlxcel_core::astype( + &mlxcel_core::sigmoid(&gate), + mlxcel_core::array_dtype(&out), + ); + mlxcel_core::multiply(&out, &gate) + } + None => out, + }; + self.o_proj.forward(&out) + } + + fn forward( + &self, + x: &MlxArray, + value_residual: Option<&MlxArray>, + rope: Option<(&RicursiveRope, &RopeAngles)>, + cache: &mut LayerState, + mask: Option<&MlxArray>, + ) -> UniquePtr { + let l = mlxcel_core::array_shape(x)[1]; + let (q, k, v) = self.project_qkv(x, value_residual, rope); + let (keys, values) = match cache { + LayerState::Kv(c) => c.update_and_fetch(k, v), + LayerState::Rotating(c) => c.update_and_fetch(k, v), + other => panic!( + "{FAMILY} forward over a {} layer: the layer state does not match \ + layer_state_kinds()", + other.storage_name() + ), + }; + // A mask-less multi-token forward is a single-row prefill left to + // MLX's causal mode or native window route (#3072). + let attn = if l > 1 && mask.is_none() { + mlxcel_core::maskless_prefill_attention(&q, &keys, &values, self.scale, self.window) + } else if l > 1 { + mlxcel_core::layers::attention(&q, &keys, &values, self.scale, mask, 0.0, self.window) + } else { + mlxcel_core::causal_attention(&q, &keys, &values, self.scale, 0.0, self.window) + }; + self.project_output(x, &attn) + } + + fn forward_batched_decode( + &self, + x: &MlxArray, + value_residual: Option<&MlxArray>, + rope: Option<(&RicursiveRope, &RopeAngles)>, + caches: &mut [&mut LayerState], + ) -> UniquePtr { + let (q, k, v) = self.project_qkv(x, value_residual, rope); + let attn = attend_batched_rows(&q, &k, &v, caches, self.scale, None); + self.project_output(x, &attn) + } + + fn from_weights( + weights: &Weights<'_>, + args: &ModelArgs, + prefix: &str, + is_sliding: bool, + ) -> Result { + let value_res_lambda = if args.use_valres { + Some(weights.value_res_lambda(prefix)?) + } else { + None + }; + let g_proj = if args.use_gated_attention { + Some(weights.linear(&format!("{prefix}.g_proj"))?) + } else { + None + }; + let head_dim = args.head_dim as i32; + Ok(Self { + q_proj: weights.linear(&format!("{prefix}.q_proj"))?, + k_proj: weights.linear(&format!("{prefix}.k_proj"))?, + v_proj: weights.linear(&format!("{prefix}.v_proj"))?, + o_proj: weights.linear(&format!("{prefix}.o_proj"))?, + g_proj, + q_norm: weights.norm(&format!("{prefix}.q_norm"))?, + k_norm: weights.norm(&format!("{prefix}.k_norm"))?, + value_res_lambda, + num_heads: args.num_attention_heads as i32, + num_kv_heads: args.num_key_value_heads as i32, + head_dim, + scale: (head_dim as f32).powf(-0.5), + gate_full_precision: args.gate_full_precision, + is_sliding, + window: match args.sliding_window { + Some(window) if is_sliding => window as i32, + _ => 0, + }, + }) + } +} + +// MLP. + +pub(crate) struct RicursiveMlp { + gate_proj: UnifiedLinear, + up_proj: UnifiedLinear, + down_proj: UnifiedLinear, + /// Non-positive disables the clamp (a null or zero threshold). + clamp: f32, +} + +impl RicursiveMlp { + fn forward(&self, x: &MlxArray) -> UniquePtr { + let gate = self.gate_proj.forward(x); + let up = self.up_proj.forward(x); + let hidden = super::deepseek_v4::moe::limited_swiglu_f32_silu(&gate, &up, self.clamp); + self.down_proj.forward(&hidden) + } +} + +// Decoder layer. + +pub(crate) struct RicursiveDecoderLayer { + pub(crate) self_attn: RicursiveAttention, + mlp: RicursiveMlp, + input_layernorm: RMSNorm, + post_attention_layernorm: RMSNorm, + pre_feedforward_layernorm: RMSNorm, + post_feedforward_layernorm: RMSNorm, +} + +impl RicursiveDecoderLayer { + fn finish(&self, x: &MlxArray, attn: &MlxArray) -> UniquePtr { + let h = mlxcel_core::add(x, &self.post_attention_layernorm.forward(attn)); + let mlp = self + .mlp + .forward(&self.pre_feedforward_layernorm.forward(&h)); + mlxcel_core::add(&h, &self.post_feedforward_layernorm.forward(&mlp)) + } + + fn forward( + &self, + x: &MlxArray, + value_residual: Option<&MlxArray>, + rope: Option<(&RicursiveRope, &RopeAngles)>, + cache: &mut LayerState, + mask: Option<&MlxArray>, + ) -> UniquePtr { + let normed = self.input_layernorm.forward(x); + let attn = self + .self_attn + .forward(&normed, value_residual, rope, cache, mask); + self.finish(x, &attn) + } + + fn forward_batched_decode( + &self, + x: &MlxArray, + value_residual: Option<&MlxArray>, + rope: Option<(&RicursiveRope, &RopeAngles)>, + caches: &mut [&mut LayerState], + ) -> UniquePtr { + let normed = self.input_layernorm.forward(x); + let attn = self + .self_attn + .forward_batched_decode(&normed, value_residual, rope, caches); + self.finish(x, &attn) + } +} + +// Weights. + +/// Read access to a checkpoint's weights under its key prefix: the HF names, +/// or the same names under `language_model.` (mlx-vlm conversions). +struct Weights<'a> { + map: &'a WeightMap, + prefix: &'static str, + group_size: i32, + bits: i32, + eps: f32, +} + +impl<'a> Weights<'a> { + fn new(map: &'a WeightMap, args: &ModelArgs) -> Self { + let prefix = if !map.contains_key("model.embed_tokens.weight") + && map.contains_key("language_model.model.embed_tokens.weight") + { + "language_model." + } else { + "" + }; + Self { + map, + prefix, + group_size: args.group_size(), + bits: args.bits(), + eps: args.rms_norm_eps, + } + } + + fn key(&self, name: &str) -> String { + format!("{}{name}", self.prefix) + } + + fn linear(&self, name: &str) -> Result { + UnifiedLinear::from_weights(self.map, &self.key(name), self.group_size, self.bits) + } + + fn norm(&self, name: &str) -> Result { + let key = self.key(&format!("{name}.weight")); + let weight = self + .map + .get(&key) + .ok_or_else(|| format!("Weight not found: {key}"))?; + Ok(RMSNorm::new(mlxcel_core::copy(weight), self.eps)) + } + + /// The `[1]` value-residual logit of the attention block at `prefix`. + /// It must be a plain FP32 or BF16 tensor: the conversions keep it out of + /// quantization, and a quantized copy has no meaningful dequantization. + fn value_res_lambda(&self, prefix: &str) -> Result, String> { + let key = self.key(&format!("{prefix}.value_res_lambda")); + if self.map.contains_key(&format!("{key}.scales")) { + return Err(format!( + "{FAMILY}: {key} is quantized; it must stay a float32 or bfloat16 [1] tensor" + )); + } + let weight = self.map.get(&key).ok_or_else(|| { + format!("{FAMILY}: use_valres is true but the checkpoint has no {key}") + })?; + let dtype = mlxcel_core::array_dtype(weight); + if dtype != mlxcel_core::dtype::FLOAT32 && dtype != mlxcel_core::dtype::BFLOAT16 { + return Err(format!( + "{FAMILY}: {key} must be float32 or bfloat16 (dtype {dtype})" + )); + } + let shape = mlxcel_core::array_shape(weight); + if shape.iter().product::() != 1 { + return Err(format!( + "{FAMILY}: {key} must hold one value, got shape {shape:?}" + )); + } + Ok(mlxcel_core::reshape(weight, &[1])) + } +} + +// Model. + +pub(crate) const RICURSIVE_LAYER_STATE_SNAPSHOT: LayerStateSnapshotSpec = LayerStateSnapshotSpec { + family: "ricursive", + label: "Ricursive", + encoding: LayerStateEncoding::Windowed { + standard: "standard", + rotating: "rotating", + }, +}; + +pub struct RicursiveModel { + embed_tokens: UnifiedEmbedding, + pub(crate) layers: Vec, + norm: RMSNorm, + /// `None` when the head is tied to the embedding. + lm_head: Option, + rope: RicursiveRope, + embed_scale: Option, + use_valres: bool, + /// The window of the sliding layers' `RotatingKVCache`s, `None` when the + /// config's `sliding_window` is null (every layer then grows). + sliding_window: Option, + eos_token_ids: Vec, +} + +impl RicursiveModel { + pub fn load>(model_dir: P) -> Result<(Self, ModelArgs), String> { + let model_dir = model_dir.as_ref(); + let config_str = std::fs::read_to_string(model_dir.join("config.json")) + .map_err(|e| format!("Failed to read config.json: {e}"))?; + let config: serde_json::Value = serde_json::from_str(&config_str) + .map_err(|e| format!("Failed to parse config.json: {e}"))?; + // The ModelOpt NVFP4 export (`ricursiveAI/Ripple-65B-Preview-NVFP4`) + // has not been validated against this decoder; refuse it by name + // rather than load its repacked triplets as affine weights. + if crate::models::is_modelopt_nvfp4_text_checkpoint(Some(&config), model_dir) { + return Err(format!( + "{FAMILY}: ModelOpt NVFP4 checkpoints are not supported yet; use an MLX affine \ + conversion such as frogggias/Ripple-65B-Preview-MLX-4bit" + )); + } + let args: ModelArgs = serde_json::from_value(config) + .map_err(|e| format!("Failed to parse config.json: {e}"))?; + args.validate()?; + let weights = crate::models::load_text_weights(model_dir, None)?; + let model = Self::from_weights(&weights, &args)?; + Ok((model, args)) + } + + pub fn from_weights(weights: &WeightMap, args: &ModelArgs) -> Result { + args.validate()?; + let w = Weights::new(weights, args); + let embed_tokens = UnifiedEmbedding::from_weights( + weights, + &w.key("model.embed_tokens"), + w.group_size, + w.bits, + )?; + let mut layers = Vec::with_capacity(args.num_hidden_layers); + for idx in 0..args.num_hidden_layers { + let prefix = format!("model.layers.{idx}"); + let clamp = args.clamp_threshold().unwrap_or(0.0); + layers.push(RicursiveDecoderLayer { + self_attn: RicursiveAttention::from_weights( + &w, + args, + &format!("{prefix}.self_attn"), + args.is_sliding(idx), + )?, + mlp: RicursiveMlp { + gate_proj: w.linear(&format!("{prefix}.mlp.gate_proj"))?, + up_proj: w.linear(&format!("{prefix}.mlp.up_proj"))?, + down_proj: w.linear(&format!("{prefix}.mlp.down_proj"))?, + clamp, + }, + input_layernorm: w.norm(&format!("{prefix}.input_layernorm"))?, + post_attention_layernorm: w.norm(&format!("{prefix}.post_attention_layernorm"))?, + pre_feedforward_layernorm: w + .norm(&format!("{prefix}.pre_feedforward_layernorm"))?, + post_feedforward_layernorm: w + .norm(&format!("{prefix}.post_feedforward_layernorm"))?, + }); + } + // A tied checkpoint may still carry an `lm_head.weight`; the reference + // drops it and projects through the embedding. + let lm_head = if args.tie_word_embeddings { + None + } else { + Some(w.linear("lm_head")?) + }; + Ok(Self { + embed_tokens, + layers, + norm: w.norm("model.norm")?, + lm_head, + rope: RicursiveRope::new(args.head_dim, args.rope_theta), + embed_scale: args.embed_scale.map(|s| s as f32), + use_valres: args.use_valres, + sliding_window: args.sliding_window.map(|w| w as i32), + eos_token_ids: args.eos_token_ids(), + }) + } + + /// The scaled input embedding `h0`: the lookup times `embed_scale` in + /// FP32, rounded back to the lookup's dtype. + fn embed(&self, input_ids: &MlxArray) -> UniquePtr { + let h = self.embed_tokens.forward(input_ids); + match self.embed_scale { + Some(scale) => { + let dtype = mlxcel_core::array_dtype(&h); + let scaled = mlxcel_core::multiply_scalar( + &mlxcel_core::astype(&h, mlxcel_core::dtype::FLOAT32), + scale, + ); + mlxcel_core::astype(&scaled, dtype) + } + None => h, + } + } + + fn project(&self, h: &MlxArray) -> UniquePtr { + let h = self.norm.forward(h); + match &self.lm_head { + Some(head) => head.forward(&h), + None => self.embed_tokens.as_linear(&h), + } + } + + fn uses_rotating_cache(&self, layer: &RicursiveDecoderLayer) -> bool { + layer.self_attn.is_sliding && self.sliding_window.is_some() + } + + pub(crate) fn layer_kinds(&self) -> Vec { + self.layers + .iter() + .map(|layer| match self.sliding_window { + Some(window) if layer.self_attn.is_sliding => LayerStateKind::sliding(window), + _ => LayerStateKind::Full, + }) + .collect() + } + + pub(crate) fn make_layer_state(&self) -> Vec { + self.layer_kinds() + .into_iter() + .map(|kind| LayerState::new(&kind, KVCacheMode::Fp16)) + .collect() + } + + fn has_sliding_layer(&self) -> bool { + self.layers.iter().any(|layer| layer.self_attn.is_sliding) + } + + /// Forward over one sequence's state, projecting every position + /// (`row == None`) or only position `row` (`[B, 1, vocab]`, #3070). + pub(crate) fn forward_rows( + &self, + input_ids: &MlxArray, + caches: &mut [LayerState], + row: Option, + ) -> UniquePtr { + let shape = mlxcel_core::array_shape(input_ids); + let (batch, seq_len) = (shape[0], shape[1]); + let h0 = self.embed(input_ids); + let dtype = mlxcel_core::array_dtype(&h0); + + let attn = &self.layers[0].self_attn; + let attention = PrefillAttention::new( + attn.num_heads as usize, + attn.num_kv_heads as usize, + attn.head_dim as usize, + ); + // Each layer kind's mask is `None` for a decode row and wherever a + // single row can take MLX's causal mode or native window route + // (#3072); the layer then runs `maskless_prefill_attention`. + let full_idx = self + .layers + .iter() + .position(|l| !self.uses_rotating_cache(l)); + let rotating_idx = self.layers.iter().position(|l| self.uses_rotating_cache(l)); + let mask_full = full_idx.and_then(|idx| { + prefill_causal_mask(seq_len, caches[idx].offset(), batch, attention, dtype) + }); + let mask_sliding = rotating_idx.and_then(|idx| { + prefill_sliding_window_mask( + seq_len, + caches[idx].offset(), + self.sliding_window.unwrap_or(0), + batch, + attention, + dtype, + SlidingPrefillKeys::Rotating, + ) + }); + let angles = self + .has_sliding_layer() + .then(|| self.rope.angles(&[caches[0].offset()], seq_len, dtype)); + let rope = angles.as_ref().map(|angles| (&self.rope, angles)); + let residual = self.use_valres.then_some(&*h0); + + let mut h: Option> = None; + for (idx, layer) in self.layers.iter().enumerate() { + let mask = if self.uses_rotating_cache(layer) { + mask_sliding.as_deref() + } else { + mask_full.as_deref() + }; + let x = h.as_deref().unwrap_or(&h0); + h = Some(layer.forward(x, residual, rope, &mut caches[idx], mask)); + } + let h = mlxcel_core::generate::select_row(h.expect("at least one layer"), row); + self.project(&h) + } + + /// One decode token per row, each row over its own layer state. + fn forward_batched_decode( + &self, + input_ids: &MlxArray, + rows: &mut [&mut [LayerState]], + ) -> UniquePtr { + let h0 = self.embed(input_ids); + let dtype = mlxcel_core::array_dtype(&h0); + let offsets: Vec = rows.iter().map(|row| row[0].offset()).collect(); + let angles = self + .has_sliding_layer() + .then(|| self.rope.angles(&offsets, 1, dtype)); + let rope = angles.as_ref().map(|angles| (&self.rope, angles)); + let residual = self.use_valres.then_some(&*h0); + let mut h: Option> = None; + for (idx, layer) in self.layers.iter().enumerate() { + let mut layer_rows: Vec<&mut LayerState> = + rows.iter_mut().map(|row| &mut row[idx]).collect(); + let x = h.as_deref().unwrap_or(&h0); + h = Some(layer.forward_batched_decode(x, residual, rope, &mut layer_rows)); + } + self.project(&h.expect("at least one layer")) + } +} + +// LanguageModel wrapper. + +/// [`RicursiveModel`] behind the `LanguageModel` trait. The id-less entry +/// points run on one fallback state; scheduler sequences arrive through +/// [`LanguageModel::forward_layer_state`] with their pool state (ADR 0010). +pub struct RicursiveWrapper { + model: RicursiveModel, + fallback: RefCell>, +} + +impl RicursiveWrapper { + pub fn new(model: RicursiveModel) -> Self { + let fallback = RefCell::new(model.make_layer_state()); + Self { model, fallback } + } + + pub fn model(&self) -> &RicursiveModel { + &self.model + } + + fn reset_fallback(&self) { + *self.fallback.borrow_mut() = self.model.make_layer_state(); + } + + fn forward_fallback(&self, input_ids: &MlxArray, row: Option) -> UniquePtr { + let mut state = self.fallback.borrow_mut(); + self.model.forward_rows(input_ids, &mut state, row) + } +} + +impl LanguageModel for RicursiveWrapper { + fn forward( + &self, + input_ids: &MlxArray, + _caches: &mut [KVCache], + _mask: Option<&MlxArray>, + ) -> UniquePtr { + self.forward_fallback(input_ids, None) + } + + fn forward_with_sequence_id( + &self, + input_ids: &MlxArray, + seq_id: Option, + _caches: &mut [KVCache], + _mask: Option<&MlxArray>, + ) -> UniquePtr { + if let Some(seq_id) = seq_id { + refuse_scheduler_owned_sequence_id(FAMILY, seq_id); + } + self.forward_fallback(input_ids, None) + } + + fn last_row_logits( + &self, + input_ids: &MlxArray, + input_embeddings: Option<&MlxArray>, + seq_id: Option, + _caches: &mut [KVCache], + _mask: Option<&MlxArray>, + last_pos: usize, + ) -> Option> { + if let Some(seq_id) = seq_id { + refuse_scheduler_owned_sequence_id(FAMILY, seq_id); + } + // No embeddings path: decline so the default keeps its behavior. + if input_embeddings.is_some() { + return None; + } + Some(self.forward_fallback(input_ids, Some(last_pos))) + } + + fn make_caches(&self) -> Vec { + self.reset_fallback(); + Vec::new() + } + + fn num_layers(&self) -> usize { + self.model.layers.len() + } + + fn layer_state_kinds(&self) -> Option> { + Some(self.model.layer_kinds()) + } + + fn make_layer_state(&self) -> Option> { + Some(self.model.make_layer_state()) + } + + fn layer_state_snapshot_spec(&self) -> Option { + Some(RICURSIVE_LAYER_STATE_SNAPSHOT) + } + + fn forward_layer_state( + &self, + request: &LayerStateForward<'_>, + rows: &mut [&mut [LayerState]], + ) -> Result, String> { + let shape = validate_layer_state_forward(FAMILY, self.model.layers.len(), request, rows)?; + if request.input_embeddings.is_some() { + return Err(format!( + "{FAMILY} forward: input embeddings are not supported" + )); + } + if let [state] = rows { + return Ok(self + .model + .forward_rows(request.input_ids, state, request.last_pos)); + } + if shape[1] != 1 || request.mask.is_some() { + if request.last_pos.is_some() { + return Err(format!( + "{FAMILY} forward: a multi-row batch takes token ids and returns every \ + position" + )); + } + let mut result: Option> = None; + for (row_idx, state) in rows.iter_mut().enumerate() { + let input = mlxcel_core::slice( + request.input_ids, + &[row_idx as i32, 0], + &[row_idx as i32 + 1, shape[1]], + ); + let logits = self.model.forward_rows(&input, state, None); + result = Some(match result { + Some(acc) => mlxcel_core::concatenate(&acc, &logits, 0), + None => logits, + }); + } + return result.ok_or_else(|| format!("{FAMILY} forward: empty batch")); + } + Ok(self.model.forward_batched_decode(request.input_ids, rows)) + } + + /// No mode table: every layer keeps an FP16 `KVCache` or + /// `RotatingKVCache`, reported so the server does not fall back to the + /// configured table (issue #2790). + fn kv_cache_storage_modes(&self) -> Option>> { + table_less_storage_modes(self.model.layers.len(), |_| LayerStateKind::Full) + } + + fn supports_batching(&self) -> bool { + true + } + + fn supports_padded_prefill(&self) -> bool { + true + } + + fn trim_state(&self, seq: Option, excess: i32) -> Result<(), String> { + trim_fallback_layer_state(FAMILY, &self.fallback, seq, excess) + } + + fn supports_snapshot_reuse(&self) -> bool { + true + } + + fn reset_runtime_state(&self) { + self.reset_fallback(); + } + + fn batched_decode_kind(&self) -> BatchedDecodeKind { + BatchedDecodeKind::Native + } + + fn forward_batched( + &self, + input_ids: &MlxArray, + batch_caches: &mut [&mut [KVCache]], + mask: Option<&MlxArray>, + ) -> UniquePtr { + forward_scheduler_owned_anonymous_batch(self, FAMILY, input_ids, batch_caches, mask) + } + + fn forward_batched_with_ids( + &self, + input_ids: &MlxArray, + seq_ids: Option<&[SequenceId]>, + batch_caches: &mut [&mut [KVCache]], + mask: Option<&MlxArray>, + ) -> UniquePtr { + if let Some(&seq_id) = seq_ids.and_then(|ids| ids.first()) { + refuse_scheduler_owned_sequence_id(FAMILY, seq_id); + } + self.forward_batched(input_ids, batch_caches, mask) + } + + fn eos_token_ids(&self) -> Vec { + self.model.eos_token_ids.clone() + } +} + +#[cfg(test)] +#[path = "ricursive_tests.rs"] +mod tests; diff --git a/src/models/ricursive_tests.rs b/src/models/ricursive_tests.rs new file mode 100644 index 0000000000..82a891bce5 --- /dev/null +++ b/src/models/ricursive_tests.rs @@ -0,0 +1,1122 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Ricursive (Ripple) tests: the block numerics against hand computations, the +//! whole tiny model against a host-side f32 replay of the reference forward, +//! cached prefill and decode across the sliding window, config validation and +//! the shared last-row and native-batch contracts. + +use super::{ModelArgs, RicursiveModel, RicursiveRope, RicursiveWrapper, value_residual_lerp}; +use crate::models::deepseek_v4::moe::limited_swiglu_f32_silu; +use crate::models::embedding_test_support::mlx_test_guard; +use crate::models::last_row_logits_harness::last_row_case; +use crate::models::pooled_model::Pooled; +use mlxcel_core::generate::LanguageModel; +use mlxcel_core::weights::WeightMap; +use mlxcel_core::{MlxArray, UniquePtr, dtype}; +use safetensors::Dtype as SafeDtype; +use safetensors::tensor::TensorView; +use std::collections::BTreeMap; + +const HIDDEN: usize = 8; +const HEADS: usize = 2; +const KV_HEADS: usize = 1; +const HEAD_DIM: usize = 4; +const INTER: usize = 16; +const VOCAB: usize = 16; +const WINDOW: usize = 4; +const LAYER_TYPES: [&str; 3] = ["sliding_attention", "full_attention", "sliding_attention"]; + +fn values(x: &MlxArray) -> Vec { + let x = mlxcel_core::astype(x, dtype::FLOAT32); + mlxcel_core::eval(&x); + mlxcel_core::utils::array_to_vec_f32(&x) +} + +fn ids(tokens: &[i32]) -> UniquePtr { + mlxcel_core::from_slice_i32(tokens, &[1, tokens.len() as i32]) +} + +fn config() -> serde_json::Value { + serde_json::json!({ + "model_type": "ricursive", + "hidden_size": HIDDEN, + "num_hidden_layers": LAYER_TYPES.len(), + "num_attention_heads": HEADS, + "num_key_value_heads": KV_HEADS, + "head_dim": HEAD_DIM, + "intermediate_size": INTER, + "vocab_size": VOCAB, + "rms_norm_eps": 1e-6, + "rope_theta": 10000.0, + "sliding_window": WINDOW, + "layer_types": LAYER_TYPES, + "use_gated_attention": true, + "gate_full_precision": true, + "use_valres": true, + "ffn_clamp_threshold": 0.2, + "embed_scale": 2.0, + "tie_word_embeddings": false, + "eos_token_id": [14, 15], + "hidden_act": "silu" + }) +} + +fn args_from(value: serde_json::Value) -> ModelArgs { + serde_json::from_value(value).unwrap() +} + +fn args() -> ModelArgs { + args_from(config()) +} + +/// Host copies of the tiny checkpoint, `name -> (values, shape)`. +type HostWeights = BTreeMap, Vec)>; + +fn patterned(len: usize, seed: usize, scale: f32) -> Vec { + (0..len) + .map(|i| (((i * 37 + seed * 17) % 101) as f32 - 50.0) * scale) + .collect() +} + +/// Nonzero weights everywhere and norm weights away from 1, so taking `h0` +/// after a norm or skipping a norm's weight changes the logits. The two +/// sliding layers' `value_res_lambda` blend below and above 0.5. +fn host_weights(layers: usize) -> HostWeights { + let mut w = HostWeights::new(); + let mut seed = 0; + let mut put = |w: &mut HostWeights, name: String, shape: Vec, kind: &str| { + seed += 1; + let len = shape.iter().product(); + let data = match kind { + "norm" => patterned(len, seed, 0.006) + .into_iter() + .map(|v| 1.0 + v) + .collect(), + _ => patterned(len, seed, 0.004), + }; + w.insert(name, (data, shape)); + }; + put( + &mut w, + "model.embed_tokens.weight".into(), + vec![VOCAB, HIDDEN], + "w", + ); + put(&mut w, "lm_head.weight".into(), vec![VOCAB, HIDDEN], "w"); + put(&mut w, "model.norm.weight".into(), vec![HIDDEN], "norm"); + for layer in 0..layers { + let p = format!("model.layers.{layer}"); + for (name, shape) in [ + ("self_attn.q_proj", vec![HEADS * HEAD_DIM, HIDDEN]), + ("self_attn.k_proj", vec![KV_HEADS * HEAD_DIM, HIDDEN]), + ("self_attn.v_proj", vec![KV_HEADS * HEAD_DIM, HIDDEN]), + ("self_attn.o_proj", vec![HIDDEN, HEADS * HEAD_DIM]), + ("self_attn.g_proj", vec![HEADS * HEAD_DIM, HIDDEN]), + ("mlp.gate_proj", vec![INTER, HIDDEN]), + ("mlp.up_proj", vec![INTER, HIDDEN]), + ("mlp.down_proj", vec![HIDDEN, INTER]), + ] { + put(&mut w, format!("{p}.{name}.weight"), shape, "w"); + } + for name in [ + "input_layernorm", + "post_attention_layernorm", + "pre_feedforward_layernorm", + "post_feedforward_layernorm", + ] { + put(&mut w, format!("{p}.{name}.weight"), vec![HIDDEN], "norm"); + } + for name in ["q_norm", "k_norm"] { + put( + &mut w, + format!("{p}.self_attn.{name}.weight"), + vec![HEAD_DIM], + "norm", + ); + } + let lambda = [-1.1, 0.9, 0.3][layer % 3]; + w.insert( + format!("{p}.self_attn.value_res_lambda"), + (vec![lambda], vec![1]), + ); + } + // Spread the embedding rows so the residual stream differs per token. + let embed = &mut w.get_mut("model.embed_tokens.weight").unwrap().0; + for (i, v) in embed.iter_mut().enumerate() { + *v *= 1.0 + (i / HIDDEN) as f32; + } + w +} + +fn weight_map(host: &HostWeights) -> WeightMap { + let mut map = WeightMap::new(); + for (name, (data, shape)) in host { + let shape: Vec = shape.iter().map(|&d| d as i32).collect(); + map.insert(name.clone(), mlxcel_core::from_slice_f32(data, &shape)); + } + map +} + +fn tiny_model() -> RicursiveModel { + RicursiveModel::from_weights(&weight_map(&host_weights(LAYER_TYPES.len())), &args()).unwrap() +} + +pub(crate) fn tiny_wrapper() -> RicursiveWrapper { + RicursiveWrapper::new(tiny_model()) +} + +// Host replay of the reference forward (mlx-vlm `ricursive/language.py`) in +// f32, where every rounding to the activation dtype is the identity. + +fn linear(w: &(Vec, Vec), x: &[f32]) -> Vec { + let (data, shape) = w; + let (out, inp) = (shape[0], shape[1]); + assert_eq!(x.len(), inp); + (0..out) + .map(|o| (0..inp).map(|i| data[o * inp + i] * x[i]).sum()) + .collect() +} + +fn rms(x: &[f32], w: &[f32], eps: f32) -> Vec { + let mean = x.iter().map(|v| v * v).sum::() / x.len() as f32; + let r = 1.0 / (mean + eps).sqrt(); + x.iter().zip(w).map(|(v, w)| v * r * w).collect() +} + +fn sigmoid(x: f32) -> f32 { + 1.0 / (1.0 + (-x).exp()) +} + +fn rope(x: &[f32], pos: usize) -> Vec { + let half = x.len() / 2; + let mut out = x.to_vec(); + for i in 0..half { + let inv = 1.0 / 10000f64.powf((2 * i) as f64 / x.len() as f64); + let theta = pos as f64 * inv; + let (s, c) = (theta.sin() as f32, theta.cos() as f32); + out[i] = x[i] * c - x[i + half] * s; + out[i + half] = x[i + half] * c + x[i] * s; + } + out +} + +/// `[position][vocab]` logits of one full forward over `tokens`. +fn reference_logits(w: &HostWeights, args: &ModelArgs, tokens: &[i32]) -> Vec> { + let get = |name: &str| w.get(name).unwrap_or_else(|| panic!("{name}")); + let eps = args.rms_norm_eps; + let embed = get("model.embed_tokens.weight"); + let scale = args.embed_scale.unwrap_or(1.0) as f32; + let h0: Vec> = tokens + .iter() + .map(|&t| { + let row = t as usize * HIDDEN; + embed.0[row..row + HIDDEN] + .iter() + .map(|v| v * scale) + .collect() + }) + .collect(); + let mut xs = h0.clone(); + let n = tokens.len(); + let group = HEADS / KV_HEADS; + for layer in 0..args.num_hidden_layers { + let p = format!("model.layers.{layer}"); + let norm = |name: &str, x: &[f32]| rms(x, &get(&format!("{p}.{name}.weight")).0, eps); + let sliding = args.is_sliding(layer); + let xn: Vec> = xs.iter().map(|x| norm("input_layernorm", x)).collect(); + let blend = sigmoid(get(&format!("{p}.self_attn.value_res_lambda")).0[0]); + let per_head = |proj: &str, norm_name: &str, x: &[f32], heads: usize, pos: usize| { + let flat = linear(get(&format!("{p}.self_attn.{proj}.weight")), x); + (0..heads) + .map(|h| { + let head = &flat[h * HEAD_DIM..(h + 1) * HEAD_DIM]; + let head = if norm_name.is_empty() { + head.to_vec() + } else { + rms( + head, + &get(&format!("{p}.self_attn.{norm_name}.weight")).0, + eps, + ) + }; + if sliding && !norm_name.is_empty() { + rope(&head, pos) + } else { + head + } + }) + .collect::>() + }; + let q: Vec<_> = (0..n) + .map(|t| per_head("q_proj", "q_norm", &xn[t], HEADS, t)) + .collect(); + let k: Vec<_> = (0..n) + .map(|t| per_head("k_proj", "k_norm", &xn[t], KV_HEADS, t)) + .collect(); + let v: Vec<_> = (0..n) + .map(|t| { + let mixed: Vec = h0[t] + .iter() + .zip(&xn[t]) + .map(|(seed, end)| seed + blend * (end - seed)) + .collect(); + per_head("v_proj", "", &mixed, KV_HEADS, t) + }) + .collect(); + for t in 0..n { + let mut out: Vec = Vec::with_capacity(HEADS * HEAD_DIM); + for (h, q_head) in q[t].iter().enumerate() { + let kh = h / group; + let keys: Vec = (0..=t) + .filter(|&s| !sliding || args.sliding_window.is_none_or(|win| t - s < win)) + .collect(); + let scores: Vec = keys + .iter() + .map(|&s| { + let dot: f32 = q_head.iter().zip(&k[s][kh]).map(|(a, b)| a * b).sum(); + dot / (HEAD_DIM as f32).sqrt() + }) + .collect(); + let max = scores.iter().cloned().fold(f32::MIN, f32::max); + let exp: Vec = scores.iter().map(|s| (s - max).exp()).collect(); + let total: f32 = exp.iter().sum(); + let mut head_out = [0.0f32; HEAD_DIM]; + for (&s, e) in keys.iter().zip(&exp) { + for (acc, value) in head_out.iter_mut().zip(&v[s][kh]) { + *acc += e / total * value; + } + } + out.extend(head_out); + } + let gate = linear(get(&format!("{p}.self_attn.g_proj.weight")), &xn[t]); + let gated: Vec = out + .iter() + .zip(&gate) + .map(|(o, g)| o * sigmoid(*g)) + .collect(); + let attn = linear(get(&format!("{p}.self_attn.o_proj.weight")), &gated); + let attn = norm("post_attention_layernorm", &attn); + let x: Vec = xs[t].iter().zip(&attn).map(|(a, b)| a + b).collect(); + let m = norm("pre_feedforward_layernorm", &x); + let limit = args.clamp_threshold(); + let g = linear(get(&format!("{p}.mlp.gate_proj.weight")), &m); + let u = linear(get(&format!("{p}.mlp.up_proj.weight")), &m); + let act: Vec = g + .iter() + .zip(&u) + .map(|(&g, &u)| { + let (g, u) = match limit { + Some(l) => (g.min(l), u.clamp(-l, l)), + None => (g, u), + }; + g * sigmoid(g) * u + }) + .collect(); + let down = linear(get(&format!("{p}.mlp.down_proj.weight")), &act); + let down = norm("post_feedforward_layernorm", &down); + xs[t] = x.iter().zip(&down).map(|(a, b)| a + b).collect(); + } + } + xs.iter() + .map(|x| { + linear( + get("lm_head.weight"), + &rms(x, &get("model.norm.weight").0, eps), + ) + }) + .collect() +} + +fn assert_rows_close(actual: &[f32], expected: &[Vec], tol: f32, what: &str) { + let flat: Vec = expected.iter().flatten().copied().collect(); + assert_eq!(actual.len(), flat.len(), "{what}: logit count"); + let worst = actual + .iter() + .zip(&flat) + .map(|(a, b)| (a - b).abs()) + .fold(0.0f32, f32::max); + assert!(worst <= tol, "{what}: max logit error {worst}"); +} + +const PROMPT: [i32; 11] = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 7]; + +/// The whole tiny model, one prefill longer than the window, against the +/// host replay. This pins `h0` as the scaled embedding before the first norm, +/// RoPE on sliding layers only, the window, the gate, the clamp and the four +/// norms. +#[test] +fn full_forward_matches_the_reference_replay() { + let _guard = mlx_test_guard(); + let host = host_weights(LAYER_TYPES.len()); + let expected = reference_logits(&host, &args(), &PROMPT); + let model = tiny_wrapper(); + let mut caches = model.make_caches(); + let logits = model.forward(&ids(&PROMPT), &mut caches, None); + assert_eq!( + mlxcel_core::array_shape(&logits), + vec![1, PROMPT.len() as i32, VOCAB as i32] + ); + assert_rows_close(&values(&logits), &expected, 1e-4, "single prefill"); +} + +/// The replay itself must be sensitive to what the test claims it pins: +/// taking `h0` after the first `input_layernorm`, or rotating the full +/// layer, moves the logits well beyond the comparison tolerance. +#[test] +fn reference_replay_separates_the_value_residual_source_and_the_rope_layers() { + let host = host_weights(LAYER_TYPES.len()); + let base = reference_logits(&host, &args(), &PROMPT); + let max_diff = |a: &[Vec], b: &[Vec]| { + a.iter() + .flatten() + .zip(b.iter().flatten()) + .map(|(x, y)| (x - y).abs()) + .fold(0.0f32, f32::max) + }; + // Every layer rotating: the full layer is no longer NoPE. + let mut all_sliding = config(); + all_sliding["layer_types"] = serde_json::json!([ + "sliding_attention", + "sliding_attention", + "sliding_attention" + ]); + all_sliding["sliding_window"] = serde_json::json!(64); + let mut wide = config(); + wide["sliding_window"] = serde_json::json!(64); + let rotated = reference_logits(&host, &args_from(all_sliding), &PROMPT); + let unrotated = reference_logits(&host, &args_from(wide), &PROMPT); + assert!(max_diff(&rotated, &unrotated) > 1e-3); + // No value residual at all (blend 1 everywhere) stands in for `h0` + // taken after the norm on layer 0, where `lerp(norm(h0), norm(h0), b)` + // is `norm(h0)`. + let mut no_residual = host.clone(); + for layer in 0..LAYER_TYPES.len() { + no_residual + .get_mut(&format!("model.layers.{layer}.self_attn.value_res_lambda")) + .unwrap() + .0[0] = 40.0; + } + let plain = reference_logits(&no_residual, &args(), &PROMPT); + assert!(max_diff(&base, &plain) > 1e-3); +} + +/// One prefill equals a chunked prefill (pieces of 3, 5 and 3) and equals a +/// 3-token prefill followed by single-token decode, across the 4-token +/// window, row by row. +#[test] +fn full_prefill_matches_chunked_prefill_and_decode_across_the_window() { + let _guard = mlx_test_guard(); + let full_model = tiny_wrapper(); + let mut caches = full_model.make_caches(); + let full = values(&full_model.forward(&ids(&PROMPT), &mut caches, None)); + + let chunked_model = tiny_wrapper(); + let mut caches = chunked_model.make_caches(); + let mut chunked = Vec::new(); + for piece in [&PROMPT[..3], &PROMPT[3..8], &PROMPT[8..]] { + chunked.extend(values(&chunked_model.forward( + &ids(piece), + &mut caches, + None, + ))); + } + + let decode_model = tiny_wrapper(); + let mut caches = decode_model.make_caches(); + let mut decoded = values(&decode_model.forward(&ids(&PROMPT[..3]), &mut caches, None)); + for &token in &PROMPT[3..] { + decoded.extend(values(&decode_model.forward( + &ids(&[token]), + &mut caches, + None, + ))); + } + let rows: Vec> = full.chunks(VOCAB).map(<[f32]>::to_vec).collect(); + assert_rows_close(&chunked, &rows, 1e-5, "chunked prefill"); + assert_rows_close(&decoded, &rows, 1e-5, "prefill then decode"); + + // The sliding layers keep a ring of the window; the full layer grows. + let model = decode_model.model(); + let kinds = model.layer_kinds(); + assert_eq!( + kinds, + vec![ + mlxcel_core::cache::LayerStateKind::sliding(WINDOW as i32), + mlxcel_core::cache::LayerStateKind::Full, + mlxcel_core::cache::LayerStateKind::sliding(WINDOW as i32), + ] + ); +} + +#[test] +fn value_residual_lerp_matches_torch_lerp_below_and_above_half() { + let _guard = mlx_test_guard(); + let residual = [1.0f32, -2.0, 0.5, 3.0]; + let x = [3.0f32, 1.0, -0.5, -1.0]; + // sigmoid(-ln 3) = 0.25 takes `seed + b * delta`; sigmoid(ln 3) = 0.75 + // takes `end + (b - 1) * delta`; sigmoid(0) = 0.5 is the upper branch. + for lambda in [-(3.0f32.ln()), 3.0f32.ln(), 0.0] { + let blend = sigmoid(lambda); + let out = values(&value_residual_lerp( + &mlxcel_core::from_slice_f32(&residual, &[4]), + &mlxcel_core::from_slice_f32(&x, &[4]), + &mlxcel_core::from_slice_f32(&[lambda], &[1]), + )); + for i in 0..4 { + let delta = x[i] - residual[i]; + let expected = if blend < 0.5 { + residual[i] + blend * delta + } else { + x[i] + (blend - 1.0) * delta + }; + assert!( + (out[i] - expected).abs() < 1e-6, + "lambda {lambda}: element {i} is {}, expected {expected}", + out[i] + ); + } + } + // The extremes select the endpoints: `h0` for a large negative lambda, + // the normalized input for a large positive one. + let at = |lambda: f32| { + values(&value_residual_lerp( + &mlxcel_core::from_slice_f32(&residual, &[4]), + &mlxcel_core::from_slice_f32(&x, &[4]), + &mlxcel_core::from_slice_f32(&[lambda], &[1]), + )) + }; + assert_eq!(at(-60.0), residual); + assert_eq!(at(60.0), x); +} + +/// bf16 activations: the blend is rounded to bf16 before the FP32 lerp, and +/// the result is rounded once. +#[test] +fn value_residual_lerp_rounds_the_blend_and_the_result_to_the_activation_dtype() { + let _guard = mlx_test_guard(); + let bf16 = |data: &[f32]| { + mlxcel_core::astype( + &mlxcel_core::from_slice_f32(data, &[data.len() as i32]), + dtype::BFLOAT16, + ) + }; + let residual = bf16(&[0.1, -1.7, 2.25, 0.003]); + let x = bf16(&[1.3, 0.6, -0.9, 5.5]); + let lambda = mlxcel_core::astype(&mlxcel_core::from_slice_f32(&[0.37], &[1]), dtype::BFLOAT16); + let out = value_residual_lerp(&residual, &x, &lambda); + assert_eq!(mlxcel_core::array_dtype(&out), dtype::BFLOAT16); + // The same steps spelled out with MLX ops. + let f32 = dtype::FLOAT32; + let blend = mlxcel_core::sigmoid(&mlxcel_core::astype(&lambda, f32)); + let blend = mlxcel_core::astype(&mlxcel_core::astype(&blend, dtype::BFLOAT16), f32); + let seed = mlxcel_core::astype(&residual, f32); + let end = mlxcel_core::astype(&x, f32); + let delta = mlxcel_core::subtract(&end, &seed); + let b = values(&blend)[0]; + assert!(b > 0.5, "lambda 0.37 must take the upper branch"); + let one = mlxcel_core::full_f32(&[1], 1.0, f32); + let upper = mlxcel_core::add( + &end, + &mlxcel_core::multiply(&mlxcel_core::subtract(&blend, &one), &delta), + ); + let expected = mlxcel_core::astype(&upper, dtype::BFLOAT16); + assert_eq!(values(&out), values(&expected)); +} + +/// Normalize in FP32, round to bf16, then scale (the reference `_rms_norm`): +/// on a constructed bf16 row the block norm gives exactly those bits, and the +/// single-rounding form (`rms_norm_round_once`, scale before rounding) gives +/// different ones. +#[test] +fn rms_norm_rounds_before_applying_the_weight() { + let _guard = mlx_test_guard(); + // Squares and their sum are exact in FP32 and the length is a power of + // two, so the mean, and with it the normalizer, does not depend on the + // reduction order. + let row: Vec = (0..64) + .map(|i| [1.0, -1.5, 2.0, 0.75, -3.0, 1.25, -0.5, 2.5][i % 8] * (1.0 + (i / 8) as f32)) + .collect(); + let weight: Vec = (0..64).map(|i| 1.0 + 0.0390625 * (i % 7) as f32).collect(); + let x = mlxcel_core::astype( + &mlxcel_core::from_slice_f32(&row, &[1, 64]), + dtype::BFLOAT16, + ); + let w = mlxcel_core::astype( + &mlxcel_core::from_slice_f32(&weight, &[64]), + dtype::BFLOAT16, + ); + let eps = 1e-6; + let host = host_weights(1); + let mut map = weight_map(&host); + map.insert( + "model.layers.0.input_layernorm.weight".into(), + mlxcel_core::copy(&w), + ); + let mut value = config(); + value["num_hidden_layers"] = serde_json::json!(1); + value["layer_types"] = serde_json::json!(["sliding_attention"]); + let model = RicursiveModel::from_weights(&map, &args_from(value)).unwrap(); + let ours = model.layers[0].input_layernorm.forward(&x); + assert_eq!(mlxcel_core::array_dtype(&ours), dtype::BFLOAT16); + + let f32 = dtype::FLOAT32; + let hidden = mlxcel_core::astype(&x, f32); + let variance = mlxcel_core::mean_axis(&mlxcel_core::square(&hidden), -1, true); + let eps_arr = mlxcel_core::full_f32(&[1], eps, f32); + let normalized = mlxcel_core::multiply( + &hidden, + &mlxcel_core::rsqrt(&mlxcel_core::add(&variance, &eps_arr)), + ); + let round_then_scale = + mlxcel_core::multiply(&mlxcel_core::astype(&normalized, dtype::BFLOAT16), &w); + let scale_then_round = mlxcel_core::layers::rms_norm_round_once(&x, &w, eps); + + let ours = values(&ours); + let reference = values(&round_then_scale); + let single = values(&scale_then_round); + assert_eq!(ours, reference, "the block norm must round before scaling"); + let differing = single + .iter() + .zip(&reference) + .filter(|(a, b)| a != b) + .count(); + assert!( + differing > 0, + "the constructed row must separate the two orders" + ); +} + +/// In FP32 (no rounding) the reference rotary matches MLX's non-traditional +/// `fast_rope` at a nonzero offset, so the half split, the frequencies and the +/// offset are the standard ones. +#[test] +fn rope_matches_rotate_half_rope_at_an_offset() { + let _guard = mlx_test_guard(); + let head_dim = 8; + let data = patterned(2 * 3 * head_dim, 5, 0.03); + let x = mlxcel_core::from_slice_f32(&data, &[1, 2, 3, head_dim as i32]); + let rope = RicursiveRope::new(head_dim, 10_000.0); + let angles = rope.angles(&[7], 3, dtype::FLOAT32); + let ours = values(&rope.apply(&x, &angles)); + let fast = values(&mlxcel_core::fast_rope( + &x, + head_dim as i32, + false, + 10_000.0, + 1.0, + 7, + )); + let worst = ours + .iter() + .zip(&fast) + .map(|(a, b)| (a - b).abs()) + .fold(0.0f32, f32::max); + assert!(worst < 1e-5, "max rope difference {worst}"); + // Per-row offsets: row 1 at offset 7 equals the single-row result. + let batched = mlxcel_core::concatenate(&x, &x, 0); + let angles = rope.angles(&[0, 7], 3, dtype::FLOAT32); + let rows = values(&rope.apply(&batched, &angles)); + assert_eq!(rows[ours.len()..], ours[..]); +} + +#[test] +fn rope_and_cache_kind_follow_layer_types() { + let _guard = mlx_test_guard(); + let model = tiny_model(); + let sliding: Vec = model + .layers + .iter() + .map(|l| l.self_attn.is_sliding) + .collect(); + assert_eq!(sliding, [true, false, true]); + // Without `layer_types` every fifth layer (i % 5 == 4) is full. + let mut value = config(); + value.as_object_mut().unwrap().remove("layer_types"); + value["num_hidden_layers"] = serde_json::json!(10); + let args = args_from(value); + let full: Vec = (0..10).filter(|&i| !args.is_sliding(i)).collect(); + assert_eq!(full, [4, 9]); + // A null window keeps the rotation but gives every layer a growing cache. + let mut value = config(); + value["sliding_window"] = serde_json::Value::Null; + let args = args_from(value); + assert_eq!(args.sliding_window, None); + let model = + RicursiveModel::from_weights(&weight_map(&host_weights(LAYER_TYPES.len())), &args).unwrap(); + assert!( + model + .layer_kinds() + .iter() + .all(|kind| *kind == mlxcel_core::cache::LayerStateKind::Full) + ); + assert!(model.layers[0].self_attn.is_sliding); +} + +/// A null window: the rotating layers see the whole prompt, and the logits +/// match the replay without a window, which differs from the windowed one +/// at this length. +#[test] +fn null_window_matches_the_reference_replay_without_a_window() { + let _guard = mlx_test_guard(); + let mut value = config(); + value["sliding_window"] = serde_json::Value::Null; + let args = args_from(value); + let host = host_weights(LAYER_TYPES.len()); + let model = + RicursiveWrapper::new(RicursiveModel::from_weights(&weight_map(&host), &args).unwrap()); + let mut caches = model.make_caches(); + let logits = values(&model.forward(&ids(&PROMPT), &mut caches, None)); + let unwindowed = reference_logits(&host, &args, &PROMPT); + assert_rows_close(&logits, &unwindowed, 1e-4, "null window"); + let windowed = reference_logits(&host, &self::args(), &PROMPT); + let diff = windowed + .iter() + .flatten() + .zip(unwindowed.iter().flatten()) + .map(|(a, b)| (a - b).abs()) + .fold(0.0f32, f32::max); + assert!( + diff > 1e-4, + "the window must matter at this length ({diff})" + ); +} + +#[test] +fn embed_scale_null_matches_a_folded_table() { + let _guard = mlx_test_guard(); + let host = host_weights(LAYER_TYPES.len()); + let scaled = tiny_wrapper(); + let mut caches = scaled.make_caches(); + let reference = values(&scaled.forward(&ids(&PROMPT), &mut caches, None)); + + // Fold the power-of-two scale into the table and set embed_scale null. + let mut folded = host.clone(); + for v in &mut folded.get_mut("model.embed_tokens.weight").unwrap().0 { + *v *= 2.0; + } + let mut value = config(); + value["embed_scale"] = serde_json::Value::Null; + let unscaled_args = args_from(value); + let model = RicursiveWrapper::new( + RicursiveModel::from_weights(&weight_map(&folded), &unscaled_args).unwrap(), + ); + let mut caches = model.make_caches(); + assert_eq!( + values(&model.forward(&ids(&PROMPT), &mut caches, None)), + reference + ); + + // A null scale over the unfolded table is a different model. + let model = RicursiveWrapper::new( + RicursiveModel::from_weights(&weight_map(&host), &unscaled_args).unwrap(), + ); + let mut caches = model.make_caches(); + assert_ne!( + values(&model.forward(&ids(&PROMPT), &mut caches, None)), + reference + ); +} + +#[test] +fn clipped_swiglu_clamps_at_the_threshold_and_not_without_one() { + let _guard = mlx_test_guard(); + let gate = [-30.0f32, 19.5, 20.0, 25.0, 3.0, -0.5]; + let up = [-25.0f32, 5.0, 20.0, 30.0, -21.0, 0.25]; + let silu = |g: f32| g * sigmoid(g); + let run = |limit: f32| { + values(&limited_swiglu_f32_silu( + &mlxcel_core::from_slice_f32(&gate, &[6]), + &mlxcel_core::from_slice_f32(&up, &[6]), + limit, + )) + }; + let clamped = run(20.0); + let unclamped = run(0.0); + for i in 0..6 { + let expected = silu(gate[i].min(20.0)) * up[i].clamp(-20.0, 20.0); + assert!( + (clamped[i] - expected).abs() <= 1e-4 * expected.abs().max(1.0), + "clamped element {i}: {} vs {expected}", + clamped[i] + ); + let expected = silu(gate[i]) * up[i]; + assert!( + (unclamped[i] - expected).abs() <= 1e-4 * expected.abs().max(1.0), + "unclamped element {i}: {} vs {expected}", + unclamped[i] + ); + } + // Gate 25 is held at 20 and up 30 at 20: silu(20) * 20. + assert!((clamped[3] - silu(20.0) * 20.0).abs() < 1e-3); + assert!((unclamped[3] - silu(25.0) * 30.0).abs() < 1e-3); + // The config maps a null or zero threshold to no clamp. + let mut value = config(); + value["ffn_clamp_threshold"] = serde_json::Value::Null; + assert_eq!(args_from(value).clamp_threshold(), None); + let mut value = config(); + value["ffn_clamp_threshold"] = serde_json::json!(0.0); + assert_eq!(args_from(value).clamp_threshold(), None); + assert_eq!(args().clamp_threshold(), Some(0.2)); +} + +/// bf16: the SiLU runs in FP32 and is rounded once before the bf16 +/// multiplication by `up`. +#[test] +fn clipped_swiglu_rounds_the_fp32_silu_once() { + let _guard = mlx_test_guard(); + let gate_data = patterned(256, 3, 0.07); + let up_data = patterned(256, 4, 0.05); + let bf16 = |d: &[f32]| { + mlxcel_core::astype( + &mlxcel_core::from_slice_f32(d, &[d.len() as i32]), + dtype::BFLOAT16, + ) + }; + let (gate, up) = (bf16(&gate_data), bf16(&up_data)); + let out = limited_swiglu_f32_silu(&gate, &up, 20.0); + assert_eq!(mlxcel_core::array_dtype(&out), dtype::BFLOAT16); + let silu = mlxcel_core::utils::silu(&mlxcel_core::astype(&gate, dtype::FLOAT32)); + let expected = mlxcel_core::multiply(&mlxcel_core::astype(&silu, dtype::BFLOAT16), &up); + assert_eq!(values(&out), values(&expected)); +} + +fn load_error(value: serde_json::Value, weights: &WeightMap) -> String { + match RicursiveModel::from_weights(weights, &args_from(value)) { + Ok(_) => panic!("expected a load error"), + Err(err) => err, + } +} + +#[test] +fn config_and_weight_validation_reject_by_name() { + let _guard = mlx_test_guard(); + let weights = weight_map(&host_weights(LAYER_TYPES.len())); + let cases: Vec<(serde_json::Value, &str)> = vec![ + ( + serde_json::json!({"layer_types": ["sliding_attention", "full_attention"]}), + "layer_types has 2 entries, num_hidden_layers is 3", + ), + ( + serde_json::json!({"layer_types": ["sliding_attention", "chunked_attention", "full_attention"]}), + "unsupported layer type \"chunked_attention\" at layer 1", + ), + ( + serde_json::json!({"hidden_act": "gelu"}), + "unsupported hidden_act \"gelu\"", + ), + ( + serde_json::json!({"num_attention_heads": 3, "num_key_value_heads": 2}), + "num_attention_heads (3) must be a positive multiple of num_key_value_heads (2)", + ), + ( + serde_json::json!({"num_key_value_heads": 0}), + "must be a positive multiple of num_key_value_heads (0)", + ), + ( + serde_json::json!({"sliding_window": 0}), + "sliding_window must be between 1 and", + ), + ( + serde_json::json!({"ffn_clamp_threshold": -1.0}), + "ffn_clamp_threshold (-1) must be finite and non-negative", + ), + ( + serde_json::json!({"head_dim": 3}), + "head_dim (3) must be positive and even", + ), + ( + serde_json::json!({"num_hidden_layers": 0, "layer_types": []}), + "num_hidden_layers must be positive", + ), + ]; + for (patch, message) in cases { + let mut value = config(); + for (key, v) in patch.as_object().unwrap() { + value[key] = v.clone(); + } + let err = load_error(value, &weights); + assert!(err.starts_with("Ricursive"), "{err}"); + assert!(err.contains(message), "{err} does not mention {message}"); + } + + // value_res_lambda: missing, quantized, wrong dtype, wrong size. + let key = "model.layers.1.self_attn.value_res_lambda"; + let mut missing = weight_map(&host_weights(LAYER_TYPES.len())); + missing.remove(key); + let err = load_error(config(), &missing); + assert!( + err.contains("use_valres is true") && err.contains(key), + "{err}" + ); + let mut no_valres = config(); + no_valres["use_valres"] = serde_json::json!(false); + assert!(RicursiveModel::from_weights(&missing, &args_from(no_valres)).is_ok()); + + let mut quantized = weight_map(&host_weights(LAYER_TYPES.len())); + quantized.insert( + format!("{key}.scales"), + mlxcel_core::ones(&[1], dtype::FLOAT32), + ); + let err = load_error(config(), &quantized); + assert!(err.contains("is quantized") && err.contains(key), "{err}"); + + let mut half = weight_map(&host_weights(LAYER_TYPES.len())); + half.insert(key.into(), mlxcel_core::ones(&[1], dtype::FLOAT16)); + let err = load_error(config(), &half); + assert!(err.contains("must be float32 or bfloat16"), "{err}"); + + let mut wide = weight_map(&host_weights(LAYER_TYPES.len())); + wide.insert(key.into(), mlxcel_core::ones(&[2], dtype::FLOAT32)); + let err = load_error(config(), &wide); + assert!(err.contains("must hold one value"), "{err}"); +} + +/// mlx-vlm conversions prefix every key with `language_model.`; a tied +/// checkpoint drops `lm_head` and projects through the embedding. +#[test] +fn language_model_prefix_and_tied_head_load() { + let _guard = mlx_test_guard(); + let host = host_weights(LAYER_TYPES.len()); + let plain = tiny_wrapper(); + let mut caches = plain.make_caches(); + let reference = values(&plain.forward(&ids(&PROMPT), &mut caches, None)); + + let mut prefixed = WeightMap::new(); + for (name, value) in weight_map(&host) { + prefixed.insert(format!("language_model.{name}"), value); + } + let model = RicursiveWrapper::new(RicursiveModel::from_weights(&prefixed, &args()).unwrap()); + let mut caches = model.make_caches(); + assert_eq!( + values(&model.forward(&ids(&PROMPT), &mut caches, None)), + reference + ); + + let mut tied_host = host.clone(); + let embed = tied_host["model.embed_tokens.weight"].clone(); + tied_host.insert("lm_head.weight".into(), embed); + let mut tied = config(); + tied["tie_word_embeddings"] = serde_json::json!(true); + let mut tied_weights = weight_map(&host); + tied_weights.remove("lm_head.weight"); + let model = RicursiveWrapper::new( + RicursiveModel::from_weights(&tied_weights, &args_from(tied)).unwrap(), + ); + let mut caches = model.make_caches(); + let expected = reference_logits(&tied_host, &args(), &PROMPT); + assert_rows_close( + &values(&model.forward(&ids(&PROMPT), &mut caches, None)), + &expected, + 1e-4, + "tied head", + ); +} + +/// The ModelOpt NVFP4 export is refused by name before any weight is read. +#[test] +fn modelopt_nvfp4_export_is_refused_by_name() { + let dir = std::env::temp_dir().join(format!("mlxcel-ricursive-nvfp4-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut value = config(); + value["quantization_config"] = serde_json::json!({ + "quant_method": "modelopt", + "quant_algo": "NVFP4", + "config_groups": {"group_0": {"weights": {"num_bits": 4, "type": "float", "group_size": 16}}} + }); + std::fs::write(dir.join("config.json"), value.to_string()).unwrap(); + let err = match RicursiveModel::load(&dir) { + Ok(_) => panic!("a ModelOpt NVFP4 export must not load"), + Err(err) => err, + }; + std::fs::remove_dir_all(&dir).unwrap(); + assert!( + err.contains("Ricursive: ModelOpt NVFP4 checkpoints are not supported yet"), + "{err}" + ); +} + +/// Round-to-nearest-even bf16 bytes of `values`, little endian. +fn bf16_bytes(values: &[f32]) -> Vec { + values + .iter() + .flat_map(|v| { + let bits = v.to_bits(); + let rounded = bits.wrapping_add(0x7fff + ((bits >> 16) & 1)) >> 16; + (rounded as u16).to_le_bytes() + }) + .collect() +} + +/// A bf16 checkpoint keeps its dtype through the shared loader on the arms +/// that cast bf16 to f16: the Apple Silicon default for unquantized +/// checkpoints and, on CUDA, the `MLXCEL_CUDA_F16_NORMALIZE` opt-in set here. +/// A cast turned every `value_res_lambda` into f16, which the loader refuses. +/// The loaded model matches the same weights built in memory as bf16. +#[test] +fn bf16_checkpoint_loads_in_bf16_under_the_f16_opt_in() { + let _guard = mlx_test_guard(); + let host = host_weights(LAYER_TYPES.len()); + let dir = tempfile::tempdir().expect("tempdir"); + let tensors: Vec<(String, Vec, Vec)> = host + .iter() + .map(|(name, (data, shape))| (name.clone(), shape.clone(), bf16_bytes(data))) + .collect(); + let views: Vec<(String, TensorView<'_>)> = tensors + .iter() + .map(|(name, shape, bytes)| { + let view = TensorView::new(SafeDtype::BF16, shape.clone(), bytes).expect("view"); + (name.clone(), view) + }) + .collect(); + safetensors::serialize_to_file(views, None, &dir.path().join("model.safetensors")) + .expect("serialize"); + std::fs::write(dir.path().join("config.json"), config().to_string()).unwrap(); + + let loaded = { + let _env = crate::test_support::env_lock::env_lock(); + let saved: Vec<(&str, Option)> = + ["MLXCEL_CUDA_F16_NORMALIZE", "MLXCEL_KEEP_BF16"] + .into_iter() + .map(|name| (name, std::env::var_os(name))) + .collect(); + // SAFETY: tests are serialized through `env_lock`. + unsafe { + std::env::set_var("MLXCEL_CUDA_F16_NORMALIZE", "1"); + std::env::remove_var("MLXCEL_KEEP_BF16"); + } + let loaded = RicursiveModel::load(dir.path()); + // SAFETY: tests are serialized through `env_lock`. + unsafe { + for (name, value) in saved { + match value { + Some(value) => std::env::set_var(name, value), + None => std::env::remove_var(name), + } + } + } + loaded + }; + let (model, _) = loaded.unwrap_or_else(|err| panic!("the bf16 checkpoint must load: {err}")); + for layer in &model.layers { + let lambda = layer.self_attn.value_res_lambda.as_ref().unwrap(); + assert_eq!(mlxcel_core::array_dtype(lambda), dtype::BFLOAT16); + } + + let mut in_memory = WeightMap::new(); + for (name, value) in weight_map(&host) { + in_memory.insert(name, mlxcel_core::astype(&value, dtype::BFLOAT16)); + } + let reference = + RicursiveWrapper::new(RicursiveModel::from_weights(&in_memory, &args()).unwrap()); + let mut caches = reference.make_caches(); + let expected = values(&reference.forward(&ids(&PROMPT), &mut caches, None)); + let model = RicursiveWrapper::new(model); + let mut caches = model.make_caches(); + assert_eq!( + values(&model.forward(&ids(&PROMPT), &mut caches, None)), + expected + ); +} + +/// The window each layer hands the maskless prefill and decode kernels: the +/// sliding window on sliding layers, 0 (none) on full layers and on every +/// layer when the window is null. The tiny model's prefill takes the masked +/// path and its decode cache already holds only the window, so no forward +/// test reads this value; it is pinned here. +#[test] +fn attention_window_is_the_sliding_window_on_sliding_layers_only() { + let _guard = mlx_test_guard(); + let host = host_weights(LAYER_TYPES.len()); + let windows = |args: &ModelArgs| -> Vec { + RicursiveModel::from_weights(&weight_map(&host), args) + .unwrap() + .layers + .iter() + .map(|layer| layer.self_attn.window) + .collect() + }; + let w = WINDOW as i32; + assert_eq!(windows(&args()), [w, 0, w]); + let mut one = config(); + one["sliding_window"] = serde_json::json!(1); + assert_eq!(windows(&args_from(one)), [1, 0, 1]); + let mut null = config(); + null["sliding_window"] = serde_json::Value::Null; + assert_eq!(windows(&args_from(null)), [0, 0, 0]); +} + +/// Mixed conversions (`araysuter/Ripple-65B-Preview-MLX-mixed-2bit`) carry +/// per-module `bits`/`group_size` entries this loader would read with the +/// default pair; they are refused by name. Entries repeating the default +/// load. +#[test] +fn per_module_quantization_overrides_are_refused_by_name() { + let with_quantization = |q: serde_json::Value| { + let mut value = config(); + value["quantization"] = q; + args_from(value).validate() + }; + assert!(with_quantization(serde_json::json!({"group_size": 64, "bits": 4})).is_ok()); + assert!( + with_quantization(serde_json::json!({ + "group_size": 64, "bits": 4, "mode": "affine", + "model.layers.0.mlp.down_proj": {"group_size": 64, "bits": 4, "mode": "affine"}, + "lm_head": {"group_size": 64, "bits": 4} + })) + .is_ok() + ); + for (path, entry) in [ + ( + "model.layers.0.mlp.down_proj", + serde_json::json!({"group_size": 32, "bits": 2, "mode": "affine"}), + ), + ( + "model.embed_tokens", + serde_json::json!({"group_size": 64, "bits": 8, "mode": "affine"}), + ), + ( + "lm_head", + serde_json::json!({"group_size": 32, "bits": 4, "mode": "mxfp4"}), + ), + ("model.layers.3.self_attn.g_proj", serde_json::json!(false)), + ] { + let mut q = serde_json::json!({"group_size": 64, "bits": 4, "mode": "affine"}); + q[path] = entry; + let err = with_quantization(q).unwrap_err(); + assert!( + err.starts_with("Ricursive: per-module quantization overrides are not supported") + && err.contains(path) + && err.contains("frogggias/Ripple-65B-Preview-MLX-4bit"), + "{err}" + ); + } +} + +#[test] +fn eos_ids_come_from_the_config() { + let _guard = mlx_test_guard(); + assert_eq!(tiny_wrapper().eos_token_ids(), vec![14, 15]); +} + +#[test] +fn ricursive_native_isolation() { + let _guard = mlx_test_guard(); + crate::models::mixed_cache_batched_decode_tests::contracts( + || Pooled::new(tiny_wrapper()), + |m, id| m.sequence_offsets(id), + ); +} + +last_row_case!(ricursive_last_row_logits, || Pooled::new(tiny_wrapper())); diff --git a/src/models/sanitize.rs b/src/models/sanitize.rs index 6ee5fbb0b3..b02befa1aa 100644 --- a/src/models/sanitize.rs +++ b/src/models/sanitize.rs @@ -1591,8 +1591,9 @@ fn modelopt_quantization_config( /// compressed-tensors NVFP4 one, whose triplets its loader must repack (issue /// #2351). /// -/// Used by: [`load_text_weights`], and the Qwen3.5 VLM loader's -/// `split_qwen3_5_vlm_weights` +/// Used by: [`load_text_weights`], the Qwen3.5 VLM loader's +/// `split_qwen3_5_vlm_weights`, and Ricursive's loader, which refuses the +/// export by name pub(crate) fn is_modelopt_nvfp4_text_checkpoint( config: Option<&Value>, model_dir: &std::path::Path, @@ -2705,6 +2706,14 @@ fn is_talkie_config(config: &Value) -> bool { config.get("model_type").and_then(Value::as_str) == Some("talkie") } +/// Whether `config` describes a Ricursive (Ripple) checkpoint +/// (`model_type: ricursive`). +/// +/// Used by: [`bf16_to_f16_at_load`]. +fn is_ricursive_config(config: &Value) -> bool { + config.get("model_type").and_then(Value::as_str) == Some("ricursive") +} + /// Whether `config` describes an Inkling checkpoint: the HMLP-wrapped /// `inkling_mm_model`, the standalone `inkling` text model, or a config whose /// `text_config` is `inkling_text`. `inkling2` is a different family. @@ -2794,6 +2803,13 @@ pub fn bf16_to_f16_at_load(is_quantized: bool, config: Option<&Value>) -> bool { if config.is_some_and(is_talkie_config) { return false; } + // Ricursive (Ripple, issue #3224) stays in its checkpoint dtype. mlx-vlm + // runs it in bf16, and its `value_res_lambda` scalars must stay f32 or + // bf16: an f16 cast made the loader refuse every layer. The residual + // stream also carries the 71.55 `embed_scale` through 80 layers. + if config.is_some_and(is_ricursive_config) { + return false; + } if pre_ampere_cuda() { // Quantized checkpoints included, unlike every other arm: the packed // planes are u32 and do not move, so only the bf16 side-data converts, @@ -3236,6 +3252,51 @@ mod tests { assert!(!bf16_to_f16_at_load(true, Some(&talkie))); } + /// Ricursive keeps its checkpoint dtype (issue #3224) on every arm that + /// would otherwise cast: Apple Silicon for unquantized checkpoints, and + /// on CUDA the `MLXCEL_CUDA_F16_NORMALIZE` opt-in (pre-Ampere parts also + /// cast quantized ones). The opt-in is set here so the CUDA arm is + /// exercised on Ampere and later too. + #[test] + fn ricursive_configs_keep_checkpoint_dtype() { + let _guard = crate::test_support::env_lock::env_lock(); + let saved: Vec<(&str, Option)> = + ["MLXCEL_CUDA_F16_NORMALIZE", "MLXCEL_KEEP_BF16"] + .into_iter() + .map(|name| (name, std::env::var_os(name))) + .collect(); + // SAFETY: tests are serialized through `env_lock`. + unsafe { + std::env::set_var("MLXCEL_CUDA_F16_NORMALIZE", "1"); + std::env::remove_var("MLXCEL_KEEP_BF16"); + } + let ripple = serde_json::json!({ + "model_type": "ricursive", + "architectures": ["RicursiveForCausalLM"] + }); + let quantized = serde_json::json!({ + "model_type": "ricursive", + "quantization": {"group_size": 64, "bits": 4} + }); + let unquantized = !bf16_to_f16_at_load(false, Some(&ripple)); + let packed = !bf16_to_f16_at_load(true, Some(&quantized)); + // SAFETY: tests are serialized through `env_lock`. + unsafe { + for (name, value) in saved { + match value { + Some(value) => std::env::set_var(name, value), + None => std::env::remove_var(name), + } + } + } + assert!(is_ricursive_config(&ripple)); + assert!(!is_ricursive_config( + &serde_json::json!({"model_type": "exaone4"}) + )); + assert!(unquantized, "an unquantized Ripple checkpoint was cast"); + assert!(packed, "a quantized Ripple checkpoint was cast"); + } + #[test] fn gemma4_group_size_reads_modelopt_config_groups() { let config = serde_json::json!({