feat(vlm): add SenseNova-Loop-9B (sensenova_loop) support

オープン
#3,217 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
5/5
見積もり時間
1週間以上
初心者へのやさしさ
12/100
issue の種類
機能追加
明瞭さ
おおむね明確
活発さ
活発
技術スタック
rust

調査の方向性

Start with the detection arm at src/models/detection.rs:893 and the Qwen3.5 loader in src/loading/vlm_qwen.rs:979-1080, then read Qwen35Model in src/models/qwen3_5.rs, where the per-physical-layer cache sizing and the full_attention_interval - 1 cache index sites are. Done means the execution plan iterates 56 visits, the mHC router and config validation match the issue, and the checkpoint loads and generates. This is a multi-part design task, so it is not a good first issue.

索引モデルが issue の本文から書いたものです。

説明

arch:hybrid area:models modelsize:small modeltype:vlm priority:medium status:blocked type:enhancement

Summary

Add SenseNova-Loop-9B (model_type: sensenova_loop, SenseNovaLoopForConditionalGeneration), a Qwen3.5-9B-shaped VLM whose text decoder is a looped transformer: 32 physical Qwen3.5 layers, with layers 4..27 executed twice per token (56 layer visits), each visit owning its own KV or GatedDeltaNet cache slot, and two-stream manifold-constrained hyper-connections (mHC) routing the residual inside the looped range. The vision tower, processor and M-RoPE are Qwen3.5's, which mlxcel runs already. The new work is an execution plan over physical layers, per-visit caches, the mHC router, and float32 handling of the router weights. The checkpoint also declares YaRN for its Qwen3.5 M-RoPE, which #3215 adds; this issue depends on it. This is not a config alias: today's Qwen35Model assumes one visit per layer throughout.

Upstream reference

Checkpoints

HF id Revision Format Size
sensenova/SenseNova-Loop-9B 3cc220e9c14bd7a74813c1299765e22147b1a3d5 original bf16, 11 shards plus mtp.safetensors; gated (gated: auto, accept the terms on HF) 19.32 GB
netprojects/SenseNova-Loop-9B-MLX-8bit 0c3da96cb43fa84e85ec62eb721e0686e47734e1 third-party MLX affine 8-bit, custom split layout (model.safetensors*, vision.safetensors, model.fp32norms.safetensors, mtp.safetensors) loaded by mlx-lm through trust_remote_code 10.93 GB
netprojects/SenseNova-Loop-9B-MLX-4bit 772a13c097b934c7d697424d6b249a2536bf4e3e same custom layout, 4-bit 6.45 GB

The original checkpoint is the validation target (convert locally with mlx_vlm.convert for a quantized arm). The netprojects builds keep vision and the float32 norms in separate files with their own key layout; supporting that layout is out of scope unless its keys turn out to match the original, which the implementer should check and record. Their config.json is readable without HF access and is the source of the values below.

Architecture (from the upstream code and the checkpoint config)

Config. Top level: loop_settings {start: 4, end: 28, eval_count: 2, counts: [2]}, mhc {start: 4, end: 28, streams: 2, iterations: 20, fixed_identity: false, pre_scale: 1.0}, image_token_id 248056, video_token_id 248057, vision_start_token_id 248053, vision_end_token_id 248054, eos_token_id [248044, 248046], tie_word_embeddings false. text_config (qwen3_5_text): hidden 4096, 32 layers, explicit layer_types with full attention at layers 3, 7, 11, 15, 19, 23, 27, 31 (full_attention_interval 4), 16 heads, 4 KV heads, head_dim 256, attn_output_gate true, linear_num_key_heads 16, linear_num_value_heads 32, key/value head dim 128, conv kernel 4, intermediate 12288, vocab 248320, max_position_embeddings 524288, rope_parameters {type: yarn, factor: 2.0, original_max_position_embeddings: 262144, rope_theta: 1e7, partial_rotary_factor: 0.25, mrope_section: [11, 11, 10], mrope_interleaved: true}. vision_config is qwen3_5_vision (depth 27, hidden 1152, out_hidden_size 4096, patch 16, spatial_merge_size 2, temporal_patch_size 2, no DeepStack).

Execution plan (upstream execution_plan): tuple(range(start)) + tuple(range(start, end)) * eval_count + tuple(range(end, n)), here 0..3, 4..27, 4..27, 28..31 (56 visits). Validation, each a named load error: loop_settings missing or not an object; start, end, eval_count, n not integers or not 0 <= start < end <= n and eval_count >= 1; counts != [eval_count] (variable-count loops are unsupported); layer_types of the wrong length or with values other than full_attention / linear_attention; no full-attention layer. For mhc when present: an object with integer start, end, streams, iterations, 0 <= start < end <= n, streams in {2, 4}, iterations >= 1, boolean fixed_identity, finite positive pre_scale (default 1.0), no unknown keys, and the mHC range must lie inside one of the phases [0, start), [start, end), [end, n).

Caches. One cache per visit, typed by the visited layer (KVCache for full attention, conv plus recurrent state for linear attention); weights stay registered once per physical layer. The full-attention cache used for the mask offset is the first visit whose layer is full attention (upstream fa_idx = next(i for i, layer in enumerate(execution_layers) if not layer.is_linear)), and likewise the first linear visit for the SSM mask.

mHC router (MHCRouter, float32 throughout). Parameters per routed layer: mhc_attn and mhc_ffn, each weight [2n + n*n, n*dim] and bias [2n + n*n] in float32 (n = streams, dim = hidden; 2n only when fixed_identity). Forward on a residual [B, L, n, dim]:

  1. flat = residual.reshape(B, L, n*dim).astype(f32); normalized = rms_norm(flat, weight=None, eps=1e-6); logits = normalized @ weight.T + bias.
  2. pre = sigmoid(logits[..., :n]), post = 2 * sigmoid(logits[..., n:2n]).
  3. mix = sinkhorn(logits[..., 2n:].reshape(B, L, n, n), iterations) where sinkhorn runs in float32 and, per iteration, subtracts logsumexp over the last axis then over the second-to-last axis, and finally exponentiates (log-space Sinkhorn; with fixed_identity, mix is the identity).
  4. branch = (pre.astype(residual.dtype)[..., None, :] @ residual).squeeze(-2) * pre_scale, shape [B, L, dim].
  5. Merge after the sublayer: residual = mix.astype(residual.dtype) @ residual + post.astype(branch.dtype)[..., None] * branch[..., None, :].

This is not DeepSeek-V4's Sinkhorn (src/models/deepseek_v4_hyper.rs runs a row softmax plus epsilon and alternating normalizations), and not Qwen4-Exp's low-rank gated residual (src/models/qwen4_exp_hyper.rs), so neither can be reused as is; reuse their weight-loading and float32-handling patterns.

Routed decoder layer (DecoderLayer.__call__ for a layer inside the mHC range): at physical_index == mhc.start, residual = broadcast(x[..., None, :], [B, L, n, dim]), otherwise residual = x.reshape(B, L, n, dim) (the hidden state carried between routed layers is [B, L, n*dim]); branch, post, mix = mhc_attn(residual); branch = input_layernorm(branch); linear or full attention with the visit's cache; merge; branch, post, mix = mhc_ffn(residual); branch = mlp(post_attention_layernorm(branch)); merge; at physical_index == mhc.end - 1 return residual.mean(axis=-2) ([B, L, dim]), otherwise residual.reshape(B, L, n*dim). On the second loop pass, layer 4 broadcasts again from layer 27's averaged output. Layers outside the mHC range are plain Qwen3.5 layers.

YaRN for the Qwen3.5 M-RoPE (Blaizzy/mlx-vlm#2649, HF _compute_yarn_parameters with truncate=True): rotary dim = head_dim * partial_rotary_factor = 64, base = rope_theta; low = floor(dim * ln(orig / (beta_fast * 2 pi)) / (2 ln base)), high = ceil(dim * ln(orig / (beta_slow * 2 pi)) / (2 ln base)) clamped to [0, dim-1] (beta_fast 32, beta_slow 1 defaults, high += 0.001 if equal); ramp = clip((arange(dim/2) - low) / (high - low), 0, 1); inv_freq = (1/(factor*pos)) * ramp + (1/pos) * (1 - ramp) with pos = base^(arange(0, dim, 2)/dim); attention_factor = 0.1 * ln(factor) + 1 (about 1.0693 for factor 2) unless attention_factor or mscale/mscale_all_dim say otherwise; cos and sin are multiplied by attention_factor, which scales only the rotary slice of q and k. Upstream disables the fused M-RoPE kernel on this path because the fused kernel ignores the scaling.

Sanitize (sensenova_loop.py): drop the training-only model.language_model.loop_gate.logits (and language_model.model.loop_gate.logits), then run the Qwen3.5 sanitize, then cast every key containing .mhc_attn. or .mhc_ffn. to float32. The quant predicate excludes mhc_attn / mhc_ffn from quantization and the cast predicate excludes them from dtype casting.

Processor and prompt. Upstream registers the Qwen3-VL processor for this model type and the LIST_WITH_IMAGE_FIRST message format; the chat template renders <|vision_start|><|image_pad|><|vision_end|> per image and ends the generation prompt with <think>\n (or <think>\n\n</think>\n\n when enable_thinking is false). Tool calls use the Qwen3-Coder XML form (<tool_call><function=...><parameter=...>), which mlxcel already parses (try_qwen3_coder, src/server/tool_calls/formats.rs:1351).

Speculative decoding. Upstream refuses the Qwen3.5 fused speculative verifier because it bypasses mHC routing. The bundled mtp.safetensors is not loaded by the target.

Current mlxcel state

  • src/models/detection.rs:893 routes qwen3_5 through detect_text_or_vlm_by_weights; sensenova_loop has no arm and fails with Unsupported model type.
  • src/loading/vlm_qwen.rs:979-1080 (load_qwen3_5_vlm_with_variant) is the loader to reuse: split_qwen3_5_vlm_weights (line 945), Qwen35Config parse and validate_supported, qwen3_5::sanitize_weights, Qwen35Model::from_weights, set_mrope, the Qwen3-VL vision encoder and processor, qwen35_vl_token_ids.
  • src/models/qwen3_5.rs assumes one visit per physical layer everywhere: Qwen35Model (line 1427) holds layers and a ModelOwnedSequenceState<Qwen3NextCache> built with config.num_hidden_layers caches (line 2467); layer type comes from Qwen35Config::is_linear_layer (line 493, interval only, layer_types ignored); the full-attention cache index is full_attention_interval - 1 at lines 1482, 2671, 2792, 3231 and 3323; validate_cache_row (line 1526) checks cache types against physical layers. There is no YaRN on the Qwen3.5 RoPE path (grep -n yarn src/models/qwen3_5.rs is empty), while src/models/rope_utils.rs:541 (yarn_rope_setup) implements YaRN for other families.
  • finish_vlm_weights_common (src/loading/vlm.rs:383-408) converts every bf16 tensor to f16 on Apple Silicon for non-quantized checkpoints; models::convert_bf16_weights_with_keep (src/models/sanitize.rs:2734) is the keep-predicate variant gemma3n uses.

Proposed solution

  1. Detection and registry. "sensenova_loop" => Ok(ModelType::SenseNovaLoopVLM) beside the qwen3_5 arms; ModelType variant, src/models/registry.rs names, src/model_metadata.rs entry (kind: Vlm, directory: Vlm, adapters refused). A checkpoint without vision_config is refused with a named error (no text-only release exists).
  2. Execution plan in Qwen35Model. Add execution_plan: Vec<usize> (identity for every existing Qwen3.5 checkpoint) and derive fa_visit / linear_visit from it. Size the internal and per-sequence caches by execution_plan.len(), type them by the visited layer, iterate visits in every forward that SenseNova uses (prefill, chunked prefill, decode, batched decode through forward_batched_decode_with_caches, MRoPE paths), and replace the five full_attention_interval - 1 sites with fa_visit. Parse layer_types into Qwen35Config and make is_linear_layer use it when present; refuse unknown values; when both are present and disagree, refuse with both values named. Choosing this over a separate model type: the Qwen3.5 VLM wrapper, server batching and MRoPE state all hold Qwen35Model concretely, and an identity plan keeps every existing path bit-identical. Paths that are not ported to a non-identity plan (speculative verify and MTP, DFlash capture, tensor and pipeline parallel stage models at src/models/qwen3_5.rs:3725) must refuse a non-identity plan or mHC with a named error rather than run the physical-layer loop.
  3. mHC. New src/models/qwen3_5_mhc.rs with MhcRouter { weight, bias, streams, iterations, fixed_identity, pre_scale }, from_weights(weights, prefix, settings, hidden) validating shapes [2n + n*n, n*hidden] / [2n + n*n] and float32 dtype, route(&residual) -> (branch, post, mix) and merge(residual, branch, post, mix), implemented as above in float32. Qwen35DecoderLayer gets an optional MhcPair { attn, ffn, start, end } and a routed forward used when present.
  4. Config. SenseNovaLoopConfig parsing and validating loop_settings and mhc exactly as listed (error text names the field and value), producing the plan.
  5. YaRN. Qwen3.5 YaRN from rope_parameters is implemented by #3215 (item (b) there), which this issue is blocked by; do not write a second implementation here. The execution-plan work in items 2-4 can proceed in parallel, but the real-checkpoint acceptance below needs #3215 merged. Confirm that #3215's YaRN path covers every forward this family uses once visits replace layers (chunked prefill, batched decode).
  6. Loader. load_sensenova_loop_vlm in src/loading/vlm_qwen.rs reusing load_qwen3_5_vlm_with_variant's steps; drop loop_gate.logits; keep .mhc_attn. / .mhc_ffn. out of the bf16 -> f16 conversion and cast them bf16 -> f32 directly (never through f16); refuse a quantized mHC tensor with a named error. Wire LoadedModel through the existing Qwen35VLM capability path (VlmRuntimeRef::Qwen, src/loaded_model_capabilities.rs:233) with the new variant, so CLI and server need no family branches.
  7. Docs. docs/supported-models.md row: loop structure, 56 visits, mHC, YaRN, cache memory note (56 cache slots, 14 of them full-attention KV), refused paths.

Scope

In scope: sensenova/SenseNova-Loop-9B bf16 and a local mlx-vlm quantized conversion; text, image and multi-image prompts; thinking on and off; tool calls through the existing Qwen3-Coder parser; CLI and server; batched decode.

Out of scope: the bundled MTP drafter (mtp.safetensors) and any speculative path for this family (refused); variable-count loops (counts with more than one value) and the training loop_gate; the netprojects custom layout unless its keys match; validating the full 512K context; tensor and pipeline parallel.

Implementation notes

  • Precision rule. load_vlm_weights() / load_vlm_weights_common() keep doing bf16 -> f16 for non-quantized weights on Apple Silicon; the mHC tensors are the documented exception because upstream and the reference keep them float32 (cast_predicate), and bf16 -> f16 -> f32 would flush small router weights. Quantized checkpoints keep bf16 scales and biases as is.
  • Shared hotspot. src/models/qwen3_5.rs is shared by Qwen3.5 dense, MoE, MiniCPM-V 4.6, Qwen3.5 text exports and others; update the // Used by: comments on any function whose contract changes, and keep the identity plan bit-identical (see Acceptance).
  • Memory. Cache memory scales with visits: 56 slots instead of 32. The memory estimate in src/execution/memory_estimate.rs must count visits, not physical layers, for this family.
  • Edge cases. Batched rows with left padding: the routed layers must apply the same padding masks as the plain path; chunked prefill must keep each visit's cache independent (upstream checks this with chunked_prefill and padded_batch regressions).
  • Attribution. The routing and execution plan derive from SenseNova's Apache-2.0 reference and from mlx-vlm (MIT). Add per-file derivation lines and NOTICE entries (carry any upstream NOTICE text forward under Apache-2.0 Section 4(d)), per the "Third-party attribution" rule in the repository development guidelines.

Acceptance criteria

  • mlxcel arch lists sensenova_loop; detection test on the checkpoint config.
  • Config tests: the upstream fixture (4 layers, loop [1, 3) x2) yields plan [0, 1, 2, 1, 2, 3] and cache types [Linear, Attention, Linear, Attention, Linear, Attention]; each of the six upstream invalid configs (missing-loop, zero-passes, variable-passes, crossing-phase, invalid-streams, zero-iterations) is a load error naming the field; a layer_types entry other than the two allowed strings is refused.
  • mHC unit tests: sinkhorn output for a fixed 2x2 and 4x4 logit tensor equals upstream to 1e-6 (fixture committed with the upstream commit noted), rows and columns sum to 1 within 1e-5; route and merge on a seeded residual equal an upstream fixture; fixed_identity yields the identity mix.
  • Precision test: a synthetic bf16 checkpoint loads with every .mhc_attn.* / .mhc_ffn.* tensor float32 and equal to f32(bf16) bit-exactly, other non-quantized weights f16 on Apple Silicon, and loop_gate.logits absent.
  • YaRN (from #3215) is active for this checkpoint: a test loads the SenseNova rope_parameters through the SenseNova loader and asserts the YaRN frequency table and attention factor 1.0693147180559945 are the ones attached to the model.
  • Regression: every existing Qwen3.5 test passes unchanged, and a tiny Qwen3.5 model with an identity plan produces bit-identical logits before and after the change.
  • Tiny random-weight SenseNova model (the upstream sensenova_loop case shape): chunked prefill equals single prefill, a left-padded two-row batch equals the two rows run separately, and the speculative verify entry point returns the named refusal.
  • Real checkpoint: mlxcel generate -m models/SenseNova-Loop-9B -p "Explain why the sky is blue." -n 128 --temp 0 and an --image prompt with enable_thinking off match mlx_vlm.generate greedy output on the same prompt, or the PR shows a teacher-forced logit trace (docs/benchmarks.md) whose disagreements at decided positions are explained; the arm with the loop disabled (plan = identity) and the arm without YaRN must both fail the trace. Record outputs, the mlx-vlm commit and the image in the PR.
  • Server: /v1/chat/completions with an image_url part and with tools returns the CLI's text and a parsed tool call respectively.
  • --draft-model / --draft-kind mtp on this family is refused with a named message on both CLI and server.
  • Integrated in mlxcel generate --image, mlxcel-server chat completions with images, and mlxcel arch; docs/supported-models.md, NOTICE and derivation lines updated.

Verification

cargo build --release --features metal,accelerate
cargo test --profile test-fast --features metal,accelerate qwen3_5
cargo test --profile test-fast --features metal,accelerate sensenova
make verify-test
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --check
./target/release/mlxcel download sensenova/SenseNova-Loop-9B
./target/release/mlxcel generate -m models/SenseNova-Loop-9B --image photo.jpg -p "Describe this image." -n 128 --temp 0

Related

  • Qwen3.5 YaRN (dependency): #3215.
  • Qwen3.5 MTP drafter loading (not used here): #2400.
  • Hyper-connection precedents: DeepSeek-V4 (src/models/deepseek_v4_hyper.rs), Qwen3.8-Flash-Next (src/models/qwen4_exp_hyper.rs). Looped-layer precedent: IQuest-Coder Loop (src/models/iquestloopcoder_model.rs).
  • Other looped models in this sync: Inkling 2 Mini (inkling2_loop).
主要言語
Rust
スター
505
フォーク
81
平均マージ
14時間 2分
マージ済み PR(30日)
448

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

lablup/mlxcel のほかの issue

lablup/mlxcel の issue をすべて見る

似ている issue

Rust の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。