feat(models): add LFM3 d1 decision models (d1_lfm3_vl, d1_lfm3_omni)

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

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

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

評価

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

調査の方向性

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 の本文から書いたものです。

説明

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

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

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 (default causal; only set is 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 env D1_VISION_MAX_PIXELS), d1_box_edges (default median), d1_prompt (1 or 2, default 1). LiquidAI/d1-2B sets d1_attention set, d1_set_size 16, d1_codes 2, d1_numbers true, d1_vision_max_pixels 1638400.
  • Calibration: calibration.json beside the weights holds default (1.3374 on d1-2B) and per-bucket temperatures (noul, score:<k>, choice:small for up to 3 options, choice:mid up to 8, choice:large up to 26, choice:inventory above); option scores are divided by the bucket temperature (else default) before the softmax. A missing file means temperature 1. tables serve only the typed answers, which are out of scope here.
  • Prompt (ChatML, no system turn): prefix {bos}<|im_start|>user\n{media markup}{body}, where body is empty for a null state, else plain(state_block(state, "json_only")) + "\n" + "QUESTION:\n". plain escapes 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_line with the default desc style); 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; else A..Z for up to 26; else scheme d1_codes (1: 00, 01, ...; 2: A..Z then AA, 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 grouped d1_set_size at a time behind their state, one unpadded row per group. The prefix and the first suffix are tokenized as one string; each further question appends question_header + suffix ("QUESTION:\n", empty for a null state). Every token carries a group id (-1 on the state, 1..N on question k). 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-VL encode_images or the LFM3-Audio tower and projector) and scattered into its placeholders in every row; pictures are capped at d1_vision_max_pixels.
  • Readout (_read): only the option rows of the tied head are computed: logits = hidden[slot] @ embed_tokens(option_token_ids).T in f32; each option scores its best form (bool: yes/Yes/YES vs no/No/NO; score level i: the single token of str(i); choice: its alias id plus the single token of " {code}" when distinct); calibration temperature; softmax.
  • Shared-API mapping (decision_question, decision_answer, predict): bool becomes noul and a list of choice labels becomes a map with null descriptions; bool answers round(p_yes, 4); choice value is the argmax label with metadata.confidence; score uses the mean readout (value = round(sum(i * p_i), 4)) with metadata.confidence and metadata.legend. usage.input_tokens sums the packed row lengths.
  • Models: d1_lfm3_vl.Model = D1 + Lfm3VlModel with decision_media = ("images",); d1_lfm3_omni.Model = D1 + Lfm3OmniModel with decision_media = ("images", "audio"). Both refuse generate.

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.rs dispatch, mlxcel decide and POST /v1/decisions.
  • After #3208 and #3216, lfm3_vl / lfm3_omni checkpoints with D1Model are 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) to Lfm3Model (#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]. predict returns InvalidInput("d1 multiple-choice questions are not supported yet") for a choice with multiple: 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 as instructions) are out of scope.
  • Defaults: set_size from d1_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) are DecisionError::Internal with 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: Lfm3Model layers, Lfm3VlModel image encoding, Lfm3AudioModel audio 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 from docs/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 (plain escaping); 27 or more choice options under d1_codes 2; single-letter labels used as their own codes; one question vs set_size groups (a question's answer must not depend on how many others share its group beyond upstream's own behavior, so compare against upstream, not against set_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 are InvalidInput.

Acceptance criteria

  • Loader tests: the published config.json of each checkpoint yields its DecisionKind; the same config without D1Model is refused; d1_attention: causal is 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; default used when the bucket is absent.
  • Parity against mlx-vlm in f32: committed fixtures for the README ticket example (refund bool, team choice, urgency score) at set_size 16 and 1 on LiquidAI/d1-2B, the COCO two-cats picture with a bool and a choice question, and on LiquidAI/d1-Omni-2B one audio-clip request; probabilities within 1e-4 and identical input_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?"}}' returns refund.value: true; an --image request with no state succeeds; the same requests work on POST /v1/decisions under mlxcel-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 hi still 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

環境構築

はじめの一歩

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

lablup/mlxcel のほかの issue

lablup/mlxcel の issue をすべて見る

似ている issue

Rust の issue をもっと見る

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

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