feat(models): add LFM3 d1 decision models (d1_lfm3_vl, d1_lfm3_omni)
メンテナーはふだん 1 日以内に返信
まだ誰も着手していません。
評価
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 初心者へのやさしさ
- 12/100
- issue の種類
- 機能追加
- 明瞭さ
- おおむね明確
- 活発さ
- 活発
- 技術スタック
- rust
- 領域
- ai, machine-learning
調査の方向性
Do not start yet: src/decision/ and the DecisionModel trait come from #2343, and #3208, #3216 and the LFM3 backbones must land first. Once they do, the new module goes in src/decision/d1_lfm3/ with two arms in src/decision/loader.rs, and Lfm3Model in #3206 needs a forward_hidden_with_layer_masks variant. Done means both checkpoints answer choice, score and bool questions through /v1/decisions with the contract's answer shapes.
索引モデルが issue の本文から書いたものです。
説明
Summary
Support LiquidAI's LFM3-based d1 decision models, LiquidAI/d1-2B (LFM3-VL backbone) and LiquidAI/d1-Omni-2B (LFM3-Omni backbone), through mlxcel's typed decision API. d1 answers named questions about a state (text, JSON, pictures, audio) in one forward pass per group of questions and reads probabilities at answer slots: nothing is decoded. The checkpoints keep model_type: lfm3_vl / lfm3_omni and declare architectures: ["D1Model"], so after #3208 and #3216 they are refused for generation and have no other path. This is low priority: it needs the decision API (#2343) and both LFM3 backbones first.
Surface decision. Do not add a new CLI subcommand or endpoint. #2343 already defines the decision surface (mlxcel decide, mlxcel-server --decision-model, POST /v1/decisions), upstream mlx-vlm serves these checkpoints through the equivalent shared /v1/decisions route, and #2367 (d1-3B on LFM2-VL) and #2368 (d1-omni-600M) plug into the same trait. This issue adds two DecisionModel implementations and their loader arms.
Upstream reference
- Blaizzy/mlx-vlm#2611 (merge
29e033ae), https://github.com/Blaizzy/mlx-vlm/tree/main/mlx_vlm/models/d1_lfm3_vl and https://github.com/Blaizzy/mlx-vlm/tree/main/mlx_vlm/models/d1_lfm3_omni - Engine and forward: https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/models/d1_lfm3_vl/d1.py (
pack_set,state_length,set_masks,SystemOne._request,SystemOne._read,D1.d1_features,D1.d1_hidden,decision_question,decision_answer,D1.predict,LEAD = "<think></think>") - Prompt: https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/models/d1_lfm3_vl/prompt.py (
option_codes,_FALLBACK_POOL,aliases,readout_ids,probabilities,readout_table,state_block,plain,question_block,prefix_text,question_header,suffix_layout,check_question,as_question) - Config and calibration: https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/models/d1_lfm3_vl/config.py (
D1Config), https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/models/d1_lfm3_vl/calibration.py (bucket,Calibration) - Media: https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/models/d1_lfm3_vl/media.py (
Reader) - README (answer shapes, parity tables): https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/models/d1_lfm3_vl/README.md
- The prompt, question and calibration code derives from the code shipped with the checkpoints under the LFM Open License v1.0 (https://github.com/Blaizzy/mlx-vlm/blob/main/mlx_vlm/models/d1_lfm3_vl/LICENSE); carry the attribution per CLAUDE.md "Third-party attribution".
Decision contract (from #2343, repeated so this issue stands alone)
#2343 adds src/decision/ with QuestionKind { Choice, Score, Bool, MultiLabel } (noul deserializes to Bool), MediaKind { Image, Video, Audio }, DecisionMedia { images: Vec<image::DynamicImage>, videos: Vec<PathBuf>, audio: Option<Vec<f32>> } (16 kHz mono), and the trait:
pub trait DecisionModel: Send {
fn decision_types(&self) -> &[QuestionKind];
fn decision_media(&self) -> &[MediaKind];
fn predict(&mut self, state: Option<&serde_json::Value>, questions: &[(String, Question)], media: DecisionMedia) -> Result<DecisionResult, DecisionError>;
}
The shared layer validates before predict: state may be null only with media; media not in decision_media is rejected; type defaults to choice and must be in decision_types; choice criteria are at least 2 unique non-empty labels, as a list or a label -> description map; score criteria are an ordered list of at least 2 level descriptions; bool criteria are absent or a map with optional false / true descriptions. Model-specific limits return DecisionError::InvalidInput (HTTP 400). Answer shapes, keyed by question name in request order: choice {"type": "choice", "value": "<argmax label>", "probabilities": {...}, "metadata": {...}}; score {"type": "score", "value": <expected level, float>, "probabilities": {"0": p, ...}, "metadata": {"legend": {...}, ...}}; bool {"type": "bool", "value": p >= 0.5, "probability": p}; usage {"input_tokens": n, "output_tokens": 0}.
How d1 on LFM3 works (upstream)
- Config keys (
D1Config, defaults when absent or null):d1_attention(defaultcausal; onlysetis accepted, anything else is a load error),d1_set_size(default 4, valid 2..128),d1_codes(default 1),d1_numbers(default false),d1_vision_max_pixels(default 1048576, overridable by envD1_VISION_MAX_PIXELS),d1_box_edges(defaultmedian),d1_prompt(1 or 2, default 1).LiquidAI/d1-2Bsetsd1_attention set,d1_set_size 16,d1_codes 2,d1_numbers true,d1_vision_max_pixels 1638400. - Calibration:
calibration.jsonbeside the weights holdsdefault(1.3374 on d1-2B) and per-buckettemperatures(noul,score:<k>,choice:smallfor up to 3 options,choice:midup to 8,choice:largeup to 26,choice:inventoryabove); option scores are divided by the bucket temperature (elsedefault) before the softmax. A missing file means temperature 1.tablesserve only the typed answers, which are out of scope here. - Prompt (ChatML, no system turn): prefix
{bos}<|im_start|>user\n{media markup}{body}, wherebodyis empty for a null state, elseplain(state_block(state, "json_only"))+"\n"+"QUESTION:\n".plainescapes special-token text in caller strings. Suffix per question:question_block+"<|im_end|>\n<|im_start|>assistant\n"+"<think></think>".question_block: choice"{instructions}\n\nOptions:\n"+ one"{code} {description, else the label with _ replaced by a space}"line per option +"\n\nReply with the option code only."(_option_linewith the defaultdescstyle); bool"{instructions}"+ (with criteria)"\nYes: {true}\nNo: {false}"+"\n\nReply with yes or no only."; score"{instructions}\n\n"+"{i} {level}"lines +"\n\nReply with a single digit 0-{n-1} only.". - Option codes (
option_codes,aliases): the labels themselves when every label is one letter; elseA..Zfor up to 26; else schemed1_codes(1:00,01, ...; 2:A..ZthenAA,AB, ...). Each code must encode to one token not used by an earlier option, else the first unused single-token entry of_FALLBACK_POOL(A-Z,00-99,a-z,#0-#199,AA-ZZ). - Packing (
pack_set): questions are groupedd1_set_sizeat a time behind their state, one unpadded row per group. The prefix and the first suffix are tokenized as one string; each further question appendsquestion_header + suffix("QUESTION:\n", empty for a null state). Every token carries a group id (-1on the state,1..Non questionk). Each question's answer slot is its suffix's last token. - Set attention (
set_masks): full-attention layers use the mask(q < s) | (k < s) | (g[q] == g[k])(the state and its own question, both ways); sliding layers stay causal in their 256-token window; conv layers stay causal over the row. Positions run over the whole row; there is no cache between groups. - Media: each state picture (and, on omni, audio clip) is encoded once per request (
d1_features: LFM3-VLencode_imagesor the LFM3-Audio tower and projector) and scattered into its placeholders in every row; pictures are capped atd1_vision_max_pixels. - Readout (
_read): only the option rows of the tied head are computed:logits = hidden[slot] @ embed_tokens(option_token_ids).Tin f32; each option scores its best form (bool:yes/Yes/YESvsno/No/NO; score leveli: the single token ofstr(i); choice: its alias id plus the single token of" {code}"when distinct); calibration temperature; softmax. - Shared-API mapping (
decision_question,decision_answer,predict):boolbecomesnouland a list of choice labels becomes a map with null descriptions; bool answersround(p_yes, 4); choicevalueis the argmax label withmetadata.confidence; score uses themeanreadout (value = round(sum(i * p_i), 4)) withmetadata.confidenceandmetadata.legend.usage.input_tokenssums the packed row lengths. - Models:
d1_lfm3_vl.Model = D1 + Lfm3VlModelwithdecision_media = ("images",);d1_lfm3_omni.Model = D1 + Lfm3OmniModelwithdecision_media = ("images", "audio"). Both refusegenerate.
Checkpoints and host
| Checkpoint | Size | Media |
|---|---|---|
LiquidAI/d1-2B |
3.85 GB bf16 | images |
LiquidAI/d1-Omni-2B (capital O on the Hub; upstream's README writes d1-omni-2B) |
4.35 GB bf16 | images, audio |
GGUF and ONNX variants exist and are out of scope. Validate on bf16 or an 8-bit conversion made with mlxcel or mlx-vlm (calibration.json and the d1_* keys must be copied); upstream measures 4-bit flipping answers, so do not claim 4-bit. Under 5 GB: home = both.
Current behavior
src/decision/does not exist yet; #2343 (open,status:ready) creates it with the trait,src/decision/loader.rsdispatch,mlxcel decideandPOST /v1/decisions.- After #3208 and #3216,
lfm3_vl/lfm3_omnicheckpoints withD1Modelare refused for generation with the d1 message; nothing answers them.
Proposed solution
New module src/decision/d1_lfm3/ (mod.rs, config.rs, prompt.rs, pack.rs, readout.rs, calibration.rs, each with _tests.rs), and two DecisionKind arms in src/decision/loader.rs: D1Lfm3Vl when model_type is lfm3_vl and D1Lfm3Omni when it is lfm3_omni, in both cases only when architectures contains D1Model or auto_map.AutoModel ends with D1Model. A plain LFM3-VL or LFM3-Omni checkpoint passed to --decision-model fails with "<path> is not a decision checkpoint".
- Forward: add
pub(crate) fn forward_hidden_with_layer_masks(&self, embeds, masks: &Lfm3LayerMasks)toLfm3Model(#3206) taking one mask per layer type (full: the set mask as an additive mask; sliding: windowed causal; conv: causal), returning final-norm hidden states without any cache. Do not touch the generation forward. Media features come from the #3208 tower and projector and the #3214 audio encoder and projector, through their existing functions. - Question types:
decision_types=[Choice, Score, Bool].predictreturnsInvalidInput("d1 multiple-choice questions are not supported yet")for a choice withmultiple: true. The typed questions (text,number,date, estimates,box,boxes) are not part of the #2343 contract, so the shared gate already rejects them. - Media: d1-2B
decision_media=[Image]; d1-Omni-2B[Image, Audio]. Video and spoken questions (a media dict asinstructions) are out of scope. - Defaults:
set_sizefromd1_set_size; no request override in this issue. Batched multi-row prefill is not required; run groups sequentially. - Tokenizer gaps (no single-token
yes/no, digits, or alias) areDecisionError::Internalwith upstream's message.
Scope
In scope: the module above, both loader arms, docs/decisions.md (created by #2343) and docs/supported-models.md entries naming both checkpoints, their question types and media, NOTICE attribution for the LFM Open License-derived prompt code.
Out of scope: multiple choice, typed reads, estimates, boxes, video, spoken questions, abstain_below, score_readout other than mean, request-level set_size, 4-bit support claims, the LFM2-based d1-3B (#2367) and d1-omni-600M (#2368).
Implementation notes
- Reuse:
Lfm3Modellayers,Lfm3VlModelimage encoding,Lfm3AudioModelaudio encoding, the #2343 media decoding; do not add a second LFM3 stack. - Constraints: no change to LFM3 generation output. If
Lfm3Model's shared forward must change rather than gain the new function, run the teacher-forced logit trace fromdocs/benchmarks.md(examples/logit_trace.rs,scripts/compare_logit_traces.py) on an LFM3 text checkpoint, including the reverted arm. - Edge cases: null state with pictures; a JSON state with special-token text (
plainescaping); 27 or more choice options underd1_codes 2; single-letter labels used as their own codes; one question vsset_sizegroups (a question's answer must not depend on how many others share its group beyond upstream's own behavior, so compare against upstream, not againstset_size 1); a picture above the pixel cap. - Error handling: config validation failures name the key and value; tokenizer gaps are
Internal; model-specific limits areInvalidInput.
Acceptance criteria
- Loader tests: the published
config.jsonof each checkpoint yields itsDecisionKind; the same config withoutD1Modelis refused;d1_attention: causalis refused at load. - Prompt and alias tests pin the text and token ids for a choice, a bool with criteria, and a score question on a JSON state, and the alias fallback for a label set whose codes collide.
- Packing tests: group ids, state length and slot positions for three questions in one group; the set mask for a 2-question row equals a hand-built matrix.
- Calibration test: bucket selection for 2, 5, 12 and 30 options and for score and bool;
defaultused when the bucket is absent. - Parity against mlx-vlm in f32: committed fixtures for the README ticket example (
refundbool,teamchoice,urgencyscore) atset_size16 and 1 onLiquidAI/d1-2B, the COCO two-cats picture with a bool and a choice question, and onLiquidAI/d1-Omni-2Bone audio-clip request; probabilities within 1e-4 and identicalinput_tokens. They fail on current code. -
mlxcel decide -m LiquidAI/d1-2B --state "I was charged twice. Please refund one charge." --questions '{"refund": {"type": "bool", "instructions": "Is it a refund request?"}}'returnsrefund.value: true; an--imagerequest with no state succeeds; the same requests work onPOST /v1/decisionsundermlxcel-server --decision-model; audio on d1-2B is rejected by the shared gate; audio on d1-Omni-2B succeeds. -
mlxcel generate -m LiquidAI/d1-2B -p histill fails with the d1 message.
Verification
cargo test --profile test-fast d1_lfm3
cargo test --profile test-fast lfm3_tests::
cargo test --profile test-fast lfm3_vl
cargo test --profile test-fast lfm3_omni
make verify-test
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --check
./target/release/mlxcel decide -m models/d1-2B --state "I was charged twice. Please refund one charge." --questions '{"refund": {"type": "bool", "instructions": "Is it a refund request?"}}'
Related
- Blocked by #2343 (decision API), #3208 (LFM3-VL backbone, d1-2B) and #3216 (LFM3-Omni backbone, d1-Omni-2B).
- Siblings on the LFM2 generation: #2367 (d1-3B) and #2368 (d1-omni-600M), under epic #2375.
- 主要言語
- 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 日以内に返信