feat(vlm): add SenseNova-Loop-9B (sensenova_loop) support
メンテナーはふだん 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 の本文から書いたものです。
説明
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
- Port: Blaizzy/mlx-vlm#2752 (commit b221fd21, "Add native SenseNova-Loop-9B support"). It also adds an
execution_layersproperty to the shared Qwen3.5 model so the base forward iterates visits instead of physical layers. - Code: https://github.com/Blaizzy/mlx-vlm/tree/main/mlx_vlm/models/sensenova_loop (
config.pywithexecution_plan,language.pywithMHCRouter,sinkhorn,DecoderLayer,TextModel,sensenova_loop.pywithsanitize), base https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/models/qwen3_5/language.py. Test casesensenova_loopin https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/tests/model_cases.json (execution plan[0, 1, 2, 1, 2, 3]for a 4-layer config with a loop over[1, 3)x2, cache types, fp32 parameters, discarded weights, six invalid configs). - Qwen3.5 YaRN: Blaizzy/mlx-vlm#2649 (
_yarn_inv_freqin the Qwen3.5 language module). - Vendor reference:
modeling_sensenova_loop.pyin the checkpoint (Apache-2.0), revision329a65f701ba8c48b73c30d0cbaa6f0449733673.
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]:
flat = residual.reshape(B, L, n*dim).astype(f32);normalized = rms_norm(flat, weight=None, eps=1e-6);logits = normalized @ weight.T + bias.pre = sigmoid(logits[..., :n]),post = 2 * sigmoid(logits[..., n:2n]).mix = sinkhorn(logits[..., 2n:].reshape(B, L, n, n), iterations)wheresinkhornruns in float32 and, per iteration, subtractslogsumexpover the last axis then over the second-to-last axis, and finally exponentiates (log-space Sinkhorn; withfixed_identity,mixis the identity).branch = (pre.astype(residual.dtype)[..., None, :] @ residual).squeeze(-2) * pre_scale, shape[B, L, dim].- 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:893routesqwen3_5throughdetect_text_or_vlm_by_weights;sensenova_loophas no arm and fails withUnsupported 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),Qwen35Configparse andvalidate_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.rsassumes one visit per physical layer everywhere:Qwen35Model(line 1427) holdslayersand aModelOwnedSequenceState<Qwen3NextCache>built withconfig.num_hidden_layerscaches (line 2467); layer type comes fromQwen35Config::is_linear_layer(line 493, interval only,layer_typesignored); the full-attention cache index isfull_attention_interval - 1at 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.rsis empty), whilesrc/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
- Detection and registry.
"sensenova_loop" => Ok(ModelType::SenseNovaLoopVLM)beside theqwen3_5arms;ModelTypevariant,src/models/registry.rsnames,src/model_metadata.rsentry (kind: Vlm, directory: Vlm, adapters refused). A checkpoint withoutvision_configis refused with a named error (no text-only release exists). - Execution plan in
Qwen35Model. Addexecution_plan: Vec<usize>(identity for every existing Qwen3.5 checkpoint) and derivefa_visit/linear_visitfrom it. Size the internal and per-sequence caches byexecution_plan.len(), type them by the visited layer, iterate visits in every forward that SenseNova uses (prefill, chunked prefill, decode, batched decode throughforward_batched_decode_with_caches, MRoPE paths), and replace the fivefull_attention_interval - 1sites withfa_visit. Parselayer_typesintoQwen35Configand makeis_linear_layeruse 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 holdQwen35Modelconcretely, 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 atsrc/models/qwen3_5.rs:3725) must refuse a non-identity plan or mHC with a named error rather than run the physical-layer loop. - mHC. New
src/models/qwen3_5_mhc.rswithMhcRouter { 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)andmerge(residual, branch, post, mix), implemented as above in float32.Qwen35DecoderLayergets an optionalMhcPair { attn, ffn, start, end }and a routed forward used when present. - Config.
SenseNovaLoopConfigparsing and validatingloop_settingsandmhcexactly as listed (error text names the field and value), producing the plan. - YaRN. Qwen3.5 YaRN from
rope_parametersis 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). - Loader.
load_sensenova_loop_vlminsrc/loading/vlm_qwen.rsreusingload_qwen3_5_vlm_with_variant's steps; droploop_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. WireLoadedModelthrough the existingQwen35VLMcapability path (VlmRuntimeRef::Qwen,src/loaded_model_capabilities.rs:233) with the new variant, so CLI and server need no family branches. - Docs.
docs/supported-models.mdrow: 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.rsis 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.rsmust 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_prefillandpadded_batchregressions). - 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
NOTICEentries (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 archlistssensenova_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; alayer_typesentry other than the two allowed strings is refused. - mHC unit tests:
sinkhornoutput 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;routeandmergeon a seeded residual equal an upstream fixture;fixed_identityyields the identity mix. - Precision test: a synthetic bf16 checkpoint loads with every
.mhc_attn.*/.mhc_ffn.*tensor float32 and equal tof32(bf16)bit-exactly, other non-quantized weights f16 on Apple Silicon, andloop_gate.logitsabsent. - YaRN (from #3215) is active for this checkpoint: a test loads the SenseNova
rope_parametersthrough the SenseNova loader and asserts the YaRN frequency table and attention factor1.0693147180559945are 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_loopcase 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 0and an--imageprompt withenable_thinkingoff matchmlx_vlm.generategreedy 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/completionswith animage_urlpart and withtoolsreturns the CLI's text and a parsed tool call respectively. -
--draft-model/--draft-kind mtpon this family is refused with a named message on both CLI and server. - Integrated in
mlxcel generate --image,mlxcel-serverchat completions with images, andmlxcel arch;docs/supported-models.md,NOTICEand 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
環境構築
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートあり
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
lablup/mlxcel のほかの issue
-
area:core priority:high status:ready type:security
難易度 2/5 1〜3時間 初心者へのやさしさ 82/100
メンテナーはふだん 1 日以内に返信
-
priority:medium status:ready type:security
難易度 4/5 3〜5日 初心者へのやさしさ 45/100
メンテナーはふだん 1 日以内に返信
-
area:models modeltype:text priority:medium status:in-progress type:bug
難易度 4/5 3〜5日 初心者へのやさしさ 57/100
メンテナーはふだん 1 日以内に返信
-
area:models priority:low status:ready type:test
難易度 4/5 3〜5日 初心者へのやさしさ 48/100
メンテナーはふだん 1 日以内に返信
-
area:models modeltype:omni priority:medium status:ready type:bug
難易度 4/5 3〜5日 初心者へのやさしさ 48/100
メンテナーはふだん 1 日以内に返信
似ている issue
-
TypeScript BM25 drops supplementary characters at the token length limit対応中かも @ErenAta16 が今日担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
chroma-core/chroma#8038 ·
メンテナーはふだん 1 日以内に返信
-
p3 ready
難易度 2/5 1〜3時間 初心者へのやさしさ 71/100
メンテナーはふだん 1 日以内に返信
-
area:ui effort:medium enhancement P7 source:agent
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
メンテナーはふだん 1 日以内に返信
-
marketing
難易度 2/5 1〜3時間 初心者へのやさしさ 85/100
メンテナーはふだん 1 日以内に返信
-
machine rename accepts a label already used by another machine, making --machine <label> ambiguousオープンmaintainer-needed p2 remote triaged
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
メンテナーはふだん 1 日以内に返信