lfm3: add INT4, FP8 per-channel and VL notes, tests, eval and results

Sync the repo with the working directory: full NOTES.md (rounds 4-5, LFM3-VL),
VL tests and test images, quality eval, AutoRound W4A16 quantization scripts
and calibration recipe, the variant.sh MODEL/DOCKER_ENV options, and the
remaining benchmark results. Large regenerable artifacts (INT4 checkpoint,
ref_vl.pt, raw logprob dumps) stay out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-29 13:59:43 +01:00
1 parent 0412bb1f72
commit 1834792bb8
67 files changed
+119589 -9

No files matched your search

+491 -4
View File
@@ -6,7 +6,7 @@
- transformers 5.19 ≥ 5.12.1 (config.json) → Liquid's remote code imports and builds fine inside the
image; **no separate reference venv needed**. transformers 5.19 does *not* ship `lfm3` natively
(only lfm2, lfm2_moe, lfm2_vl).
- vLLM sources relevant to this work are copied (read-only reference) into `./ref/`.
- vLLM sources relevant to this work are copied (read-only reference) into `./ref/` (workspace only, not in this repo).
## Step 1 — architecture: LFM3 vs. vLLM's LFM2 (source of truth: modeling_lfm3.py)
@@ -184,7 +184,7 @@ applies even with `do_sample=False` — the first run's HF greedy outputs diverg
of that, not because of the port. The script now forces `repetition_penalty=1.0`.
## Upstream check (2026-10-28, requested mid-way; done after step 5 because work had already progressed)
- vLLM `main` shallow clone in `./vllm-main` (HEAD c105af4, 2026-10-28 11:31 -0700): no match for
- vLLM `main` shallow clone in `./vllm-main` (workspace only, not in this repo) (HEAD c105af4, 2026-10-28 11:31 -0700): no match for
`lfm3` / `Lfm3ForCausalLM` anywhere; registry only has Lfm2 / Lfm2Moe / Lfm2Vl / Lfm2Bidirectional /
ColBERTLfm2.
- Main's Triton `causal_conv1d` is still unrolled for widths ≤ 5 (prefill) / ≤ 6 (decode) → width 7
@@ -277,7 +277,7 @@ llama-swap model entry — as live in /etc/llama-swap/config.yaml. Since 2026-10
weights, round 3, +49% decode) on the `:v0.32.0-lfm3-fp8fix` image, with the vLLM default compile +
FULL_AND_PIECEWISE graphs confirmed in round 2. Previous BF16 entry: same without `--quantization=fp8`, image `:v0.32.0-lfm3`.
```yaml
# ---------- vLLM 0.32 + lfm3 plugin – LFM3-1.7B (W8A16: online FP8 weights) ----------
# ---------- vLLM 0.32 + lfm3 plugin – LFM3-1.7B (W8A16: online FP8 weights, per-channel scales) ----------
vllm/lfm3-1.7b:
useModelName: lfm3-1.7b
aliases:
@@ -301,7 +301,7 @@ FULL_AND_PIECEWISE graphs confirmed in round 2. Previous BF16 entry: same withou
--served-model-name=lfm3-1.7b
--gpu-memory-utilization=0.5
--dtype=bfloat16
--quantization=fp8
--quantization=fp8_per_channel
--max-model-len=32768
--enable-auto-tool-choice
--tool-call-parser=qwen3_coder
@@ -487,3 +487,490 @@ FP8 W8A16 is the new default: llama-swap `vllm/lfm3-1.7b` switched to image `lfm
Verified through llama-swap: reload clean, cold start 2m26s, kernel `XPUW8A16FP8LinearKernel`, weights 1.88 GiB,
"17*23" → 391. For a manual `docker run` (Deployment section above), add `--quantization=fp8` and use the
`:v0.32.0-lfm3-fp8fix` image (rebuild from this repo: `docker build -t lfm3-vllm-xpu:v0.32.0-lfm3-fp8fix .`).
### Standardized run (bench-standard 0.2.0, quick, via llama-swap) — 2026-10-29
`/srv/llm/bench/results/20261029-074532-pascal-vllm-lfm3-1.7b-vllm-arc-pro-b65` (`server-cmd.txt` confirms `--quantization=fp8` + `:fp8fix` image).
| run | decode t/s | ITL 1% low t/s | TTFT p50 ms | aggregate @8 t/s | prefill @32k t/s |
|---|--:|--:|--:|--:|--:|
| BF16 baseline (bench-standard 0.1.0) | 127.6 | 102.3 | 60 | 764.4 | 16,670 |
| **FP8 W8A16 (bench-standard 0.2.0)** | **190.8** (+50%) | 116.2 | 59 | **1,076.2** (+41%) | 16,641 |
Matches the direct-port FP8 run (191.3 / 122.5 / 59 / 1,036.5 / 16,744) within run-to-run noise.
## Round 4 — W4A16 (INT4 weight-only) experiment
### Step 1 — preconditions
**Plugin.** All big linears take `quant_config` (see round 3 step 1). Fused modules:
`packed_modules_mapping = {"qkv_proj": [q,k,v], "w13": [w1,w3], "in_proj": ["in_proj"]}` and the
`hf_to_vllm_mapper` stacks `.q_proj/.k_proj/.v_proj → .qkv_proj` and `.w1/.w3 → .w13` (shard 0/1) and maps
`.conv. → .short_conv.`. These are applied by vLLM to every checkpoint tensor (qweight/scales/qzeros
included) and, via `SupportsQuant`, to the quant config's layer names (INC's `apply_vllm_mapper` remaps
`block_name_to_quantize` and `extra_config`), so HF-named quantized checkpoints line up.
Exception that matters for INT4: **`self_attn.gate_proj`** (16×2048 output gate) is an `nn.Linear` in
Liquid's code, so a quantizer would pick it up, but our plugin builds it without quant_config (expects
BF16). → exclude it at quantization time (32k params, nothing to gain). Conv kernel is `nn.Conv1d` → not a
quantizer target anyway.
**XPU INT4 support in the image (vLLM 0.32.0+xpu, vllm-xpu-kernels 0.1.15.4).** XPU's
`supported_quantization` includes gptq, auto_gptq, awq, inc, compressed-tensors. All W4A16 routes end in a
real INT4 kernel (no dequant-to-BF16 path):
| checkpoint format | vLLM config | XPU kernel | constraints |
|---|---|---|---|
| GPTQ (`quant_method: gptq`, sym) | AutoGPTQConfig → `choose_mp_linear_kernel` | `XPUwNa16LinearKernel` → `_xpu_C.int4_gemm_w4a16` (oneDNN) | uint4/uint4b8, group % 32, K % 32 |
| compressed-tensors W4A16 (pack-quantized) | CompressedTensorsWNA16 → `choose_mp_linear_kernel` | same `XPUwNa16LinearKernel` | same |
| **AutoRound native** (`quant_method: auto-round`, packing `auto_round:auto_gptq`) | INC (`inc`) → `INCWNA16Scheme` | **ARK** (`auto_round_kernel`, auto-round-lib 0.16.0 ships in the image and imports) by default; oneDNN `int4_gemm_w4a16` via `VLLM_XPU_INC_WNA16_BACKEND=w4a16` | sym only, bits 2/4 |
All LFM3 input dims (2048, 7680) are multiples of 32; group 128 is fine.
**Choice: AutoRound native format** (bits 4, group 128, sym) — the preferred tool's own format, served by
vLLM's INC path with two real XPU INT4 kernels (ARK and oneDNN) that can be A/B'd from one checkpoint.
GPTQ/compressed-tensors would only reach the oneDNN kernel. AutoRound itself (`auto-round`, the
quantizer) is not in the image → to be pip-installed into ./ for step 2.
### Step 2 — quantization setup
Tooling (all inside ./quant): AutoRound 0.16.1 pip-installed with `--target quant/pylib` and run inside
the vLLM image (`lfm3-vllm-xpu:v0.32.0-lfm3-fp8fix`: torch 2.14+xpu, transformers 5.19, accelerate, datasets
already there) with `PYTHONPATH=/quant/pylib`. HF dataset cache: quant/calib/hf_cache (neither pylib nor the cache is in this repo; re-run `pip install --target quant/pylib auto-round==0.16.1` and `quant/build_calib.py`).
**Calibration dataset recipe** (`quant/build_calib.py`, recipe JSON: quant/calib/calib_256x2048.json):
- 256 samples × 2048 tokens = 524k tokens. Every conversation is rendered with the model's own chat
template (`<|im_start|>` turns, `<think></think>` on assistant turns, tools via `tools=` →
`<tools>` system block, calls via `tool_calls` → `<tool_call><function=…><parameter=…>` XML,
tool results → `<tool_response>`), shuffled (seed 0) and packed back-to-back into exact 2048-token
samples (AutoRound drops samples shorter than seqlen).
- Mix by token share: English chat 45% (HuggingFaceH4/ultrachat_200k test_sft, 199 conversations, 237k
tok), German 20% (OpenAssistant/oasst1 lang=de prompter→assistant pairs, 567 pairs, 105k tok), tool calls
15% (glaiveai/glaive-function-calling-v2 rows with `<functioncall>`, converted to the template's tool
format, 239 conversations, 79k tok), code 20% (iamtarun/python_code_instructions_18k_alpaca, 629, 106k tok).
- Spot-checked: tool conversations render exactly like vLLM's own prompts (system `<tools>`, XML call).
Quantizer: `quant/quantize_autoround.py` — bits 4, group 128, sym, iters 200, seqlen 2048, nsamples 256,
`layer_config` keeps all `self_attn.gate_proj` at 16 bit, export `format="auto_round"` to
./quant/LFM3-1.7B-W4A16-autoround/.
### Step 2 — quantization run (log: logs/autoround_w4a16.log, run info: quant/quant_run.json)
- First attempt crashed at block 2 (first attention block): `cos, sin = position_embeddings` → None
(logs/autoround_w4a16_fail1.log). Cause: AutoRound records the kwargs reaching block 0 (a conv layer) and
replays them to every block, but LFM3 gives each layer the RoPE table and mask of its own type
(conv / sliding_attention / full_attention). Even without the crash, sliding layers would have been
calibrated with the wrong mask.
- Fix (in quant/quantize_autoround.py only, model code untouched): wrap `Lfm3DecoderLayer.forward` so each
layer rebuilds its own `position_embeddings` and mask via Liquid's `rotary_emb` / `create_masks_by_layer_type`
(cached per shape); `enable_torch_compile=False`. Verified on XPU with `quant/check_patch.py`: patched vs
unpatched model on a 1000-token sample → max |Δlogit| = 0.0, top-1 agreement 100%.
- Calibrated **on XPU** (AutoRound 0.16.1, device_map=xpu): **16.5 min** (988 s), peak VRAM 16.2 GB, peak RAM
8.4 GB. Quantized 142/154 Linear (11 attn × q/k/v/o, 13 conv × in/out, 24 MLP × w1/w2/w3); kept 16-bit:
11 × `self_attn.gate_proj` + tied `lm_head`. Per-block loss is tiny in absolute terms (~5e-10 →
~2.5e-10, LFM3's sandwich norms scale the branch outputs) and drops ~50% per block.
- Checkpoint now at `/models/LFM3-1.7B-W4A16-autoround/` (originally written to ./quant/; AutoRound wrote it into a `model-w4g128/` subdir; moved up):
`quant_method: auto-round`, `packing_format: auto_round:auto_gptq`, bits 4, group 128, sym, `extra_config`
= the 11 gate_proj at 16 bit. **model.safetensors 1.29 GB vs 3.3 GB BF16 (39%)**.
### Step 3 — serving (logs: logs/variant_w4_eager*.log, logs/variant_w4_graphs.log)
- Default INC backend on XPU = **ARK** (`auto_round_kernel`): **engine core dies silently** right after
"Loading weights took 0.51 s" (no Python traceback → native crash in ARK's weight repacking;
logs/variant_w4_eager_ark_crash.log). Not debugged further.
- **`VLLM_XPU_INC_WNA16_BACKEND=w4a16`** → INC `INCXPULinearMethod` → oneDNN `_xpu_C.int4_gemm_w4a16`: works.
**Model weight memory 1.24 GiB** (BF16 3.24, FP8 1.88) → weights stay packed INT4 on the GPU, not
dequantized at load. (Harmless warnings: fp16 group scales cast to bf16 params.)
- Eager (`--enforce-eager`): ready in 62 s. Graphs (vLLM default compile + FULL_AND_PIECEWISE, the round-2
winner): ready in 140 s cold (torch.compile 40 s, capture 11 s / 0.54 GiB). Greedy graphs vs eager: 4/5
identical, the 5th differs at an exact tie (margin 0.000).
- Greedy vs BF16 eager (tests/greedy_variant.py): 1/5 identical; divergences at BF16 margins 0.31 / 0.125 /
**0.75 / 1.375** — unlike FP8 (all ≤ 0.375), INT4 flips tokens BF16 was fairly sure about.
### Step 4 — quality vs BF16 / FP8 (details + side-by-side outputs: eval/w4a16_compare.md)
`eval/eval_quality.py` (inputs: `eval/build_eval_data.py` → eval/eval_data.json), all variants with graphs.
| variant | PPL wikitext-2 (20×2048 tok, 40,940 scored) | vs BF16 | 8-prompt answers correct | completion tokens (8 prompts) |
|---|--:|--:|---|--:|
| BF16 | 18.518 | — | 8/8 | 3,790 |
| FP8 W8A16 | 19.208 | +3.7% | 8/8 | 3,436 |
| INT4 W4A16 | 19.886 | **+7.4%** | 8/8 | 4,123 |
- Both tool calls (weather, flights incl. integer arg) are byte-identical across all three and parse with
qwen3_coder (`finish_reason: tool_calls`); JSON valid and identical; German fine; needle at 700+ tokens found.
- All three summaries say "published October 1942" — the article itself has "first published in September
1942" and "published in the October New English Weekly" → shared ambiguity, not a quantization error.
- INT4 degradation shows as: 2× FP8's perplexity loss; greedy flips at confident tokens (margins up to
1.375); **longer thinking** on 5/8 prompts (math 986 vs 632 BF16 tokens).
### Step 5 — BetterBench (same invocation as rounds 2/3, direct on :8001; results/variants/bb/w4_{eager,graphs}.*)
Effective bandwidth = weight bytes × decode t/s (BF16 checkpoint 3.458 GB; FP8 online, 2.02 GB loaded;
INT4 checkpoint 1.287 GB).
| variant | decode t/s | weight bytes | eff. bandwidth | ITL 1% low t/s | TTFT p50 ms | aggregate @8 t/s | prefill @32k t/s |
|---|--:|--:|--:|--:|--:|--:|--:|
| BF16 graphs | 128.4 | 3.458 GB | 444 GB/s | 105.1 | 67 | 768.2 | 16,626 |
| FP8 W8A16 graphs | 191.3 | 2.02 GB | 386 GB/s | 122.5 | 59 | 1,036.5 | 16,744 |
| W4A16 eager | 33.2 | 1.287 GB | 43 GB/s | 25.1 | 116 | 213.1 | 13,940 |
| **W4A16 graphs** | **219.8** | 1.287 GB | 283 GB/s | 129.1 | 59 | **1,198.2** | 14,210 |
- INT4 graphs vs FP8: decode +15%, aggregate @8 +16%, ITL 1% low +5%, **prefill −15%** (INT4 GEMM unpacks
weights; prefill is compute-bound). vs BF16: decode +71%, @8 +56%.
- Bandwidth efficiency drops with every format step: the oneDNN INT4 GEMV reaches only ~283 GB/s (64% of the
BF16 GEMV's ~444 GB/s), and the BF16 tied lm_head (0.52 GB) is now **41% of the bytes read per step**.
36% fewer bytes than FP8 → only 15% faster.
- Eager stays launch-bound (33 t/s, flat 32–34 per request at every concurrency level) — not an option.
- Per-request decode under concurrency (graphs): 224 / 214 / 193 / 179 t/s at 1/2/4/8 (FP8: 192 / 186 / 176 / 160).
- **End-to-end on the 8 eval prompts** (completion tokens ÷ decode rate): BF16 29.5 s, FP8 18.0 s,
**INT4 18.8 s** — INT4's longer thinking cancels its decode advantage on this (small) sample.
### Step 6 — recommendation
**Keep FP8 W8A16 as the default.** INT4 is ~15% faster per token than FP8, but it costs twice FP8's
perplexity loss, 15% prefill, longer reasoning (which ate the speed gain end-to-end on our prompts), a
custom calibration workaround, and it only runs with a non-default kernel (`VLLM_XPU_INC_WNA16_BACKEND=w4a16`;
the default ARK backend crashes). Worth it only for throughput-bound batch work with short or
non-thinking outputs, where per-token speed dominates. Bigger lever for both FP8 and INT4: the BF16 lm_head
(41% of INT4's per-step bytes).
llama-swap snippet for the INT4 variant (NOT applied to the real config; needs the checkpoint copied to a
path the llama-swap user can read, e.g. /models — the brief keeps it in ./quant):
```yaml
# ---------- vLLM 0.32 + lfm3 plugin – LFM3-1.7B W4A16 (AutoRound INT4, oneDNN kernel) ----------
vllm/lfm3-1.7b-int4:
useModelName: lfm3-1.7b-int4
aliases:
- lfm3-1.7b-int4
cmdStop: docker stop -t 30 vllm-lfm3-int4
cmd: >
docker run --rm --name vllm-lfm3-int4
--device /dev/dri --group-add 991
--ipc=host --shm-size=16g
-p 127.0.0.1:${PORT}:8000
-v /dev/dri:/dev/dri
-v /dev/dri/by-path:/dev/dri/by-path:ro
-v /models/LFM3-1.7B-W4A16-autoround:/model:ro
-v /srv/llm/runtimes/vllm-xpu/lfm3-v032/.cache/vllm-lfm3-int4:/root/.cache/vllm
-e HF_HUB_OFFLINE=1
-e TRANSFORMERS_OFFLINE=1
-e VLLM_XPU_INC_WNA16_BACKEND=w4a16
lfm3-vllm-xpu:v0.32.0-lfm3-fp8fix
/model
--host=0.0.0.0
--port=8000
--served-model-name=lfm3-1.7b-int4
--gpu-memory-utilization=0.5
--dtype=bfloat16
--max-model-len=32768
--enable-auto-tool-choice
--tool-call-parser=qwen3_coder
--reasoning-parser=qwen3
```
(`quantization` is read from the checkpoint's config.json → INC; no `--quantization` flag needed.)
## Round 5 — FP8 per-channel vs per-tensor (2026-10-29)
Why: INT8 weight-only (W8A16) has no dense-layer path on XPU in this image (XPU kernels: `fp8_gemm_w8a16`,
`fp8_gemm`, `int4_gemm_w4a16`, `int4_gemm_w4a8` only; online `int8_per_channel_weight_only` is MoE-only;
GPTQ/compressed-tensors XPU kernels take uint4 only; INC XPU bits 2/4 only). In W8A16 the math is BF16 anyway,
so the lever is weight-scale granularity, not FP8 vs INT8.
`--quantization=fp8_per_channel` (image `:v0.32.0-lfm3-fp8fix`): vLLM selects **`XPUW8A16FP8LinearKernel` for
`Fp8PtpcOnlineLinearMethod`** → still W8A16 (BF16 activations), one FP8 scale per output channel instead of
one per matrix. Weights 1.88 GiB (same), cold start 146 s. Logs: logs/variant_fp8pc.log, logs/bb_fp8pc.log.
| variant | PPL (wikitext-2, same 40,940 tok) | vs BF16 | decode t/s | ITL 1% low | TTFT p50 | aggregate @8 | prefill @32k |
|---|--:|--:|--:|--:|--:|--:|--:|
| BF16 | 18.518 | — | 128.4 | 105.1 | 67 | 768.2 | 16,626 |
| FP8 per-tensor (live until now) | 19.207 | +3.7% | 191.3 | 122.5 | 59 | 1,036.5 | 16,744 |
| **FP8 per-channel** | **18.523** | **+0.03%** | **191.2** | 124.5 | 58 | 1,095.3 | 16,924 |
| INT4 W4A16 graphs (round 4) | 19.886 | +7.4% | 219.8 | 129.1 | 59 | 1,198.2 | 14,210 |
- Per-channel removes essentially all of FP8's quality loss (perplexity equal to BF16 within 0.03%) at
identical decode speed (the @8 +6% is within run-to-run spread).
- 8 eval prompts: all correct (math 30.90, Canberra, German e-mail, both tool calls identical to BF16/FP8, valid
JSON, needle found); 3,803 completion tokens (BF16 3,790, per-tensor 3,436, INT4 4,123). Greedy 64-token
check vs BF16 eager: 1/5 identical, all divergences at near-ties (margins ≤ 0.25).
- **Recommendation: switch the llama-swap entry from `--quantization=fp8` to `--quantization=fp8_per_channel`**
(same image, nothing else changes).
**Deployed 2026-10-29 09:50:** llama-swap `vllm/lfm3-1.7b` now uses `--quantization=fp8_per_channel` (backup:
/etc/llama-swap/config.yaml.bak-pre-fp8pc). Verified via :8080: reload clean, cold start 2m04s,
`XPUW8A16FP8LinearKernel` for `Fp8PtpcOnlineLinearMethod`, weights 1.88 GiB, "17*23" → 391. The Deployment
snippet above is updated accordingly.
## LFM3-VL (LFM3-VL-2B, image input) — 2026-10-29
### Step 0 — upstream check
- vLLM main @ fa3b9d1 (2026-10-29): no `lfm3` anywhere, only `Lfm2VlForConditionalGeneration`.
- GitHub search on vllm-project/vllm for "LFM3-VL", "Lfm3Vl", "lfm3_vl", "LFM3": 0 PRs, 0 issues.
Nothing to build on or compare against, so this is our own port.
### Step 1 — analysis (source: model folder `modeling_lfm3_vl.py`, `processing_lfm3_vl.py`,
`image_processing_lfm3_vl.py`, `config.json`, `processor_config.json`)
**Checkpoint.** `model.safetensors`, 424 tensors, BF16. `architectures: [Lfm3VlForConditionalGeneration]`,
`model_type: lfm3_vl` (vision sub-config `lfm3_vl_vision`, text sub-config `lfm3`).
Special tokens: `image_token_id` 125030 `<|image|>`, `video_token_id` 125029 `<|video|>`,
`vision_start_token_id` 125009 `<|vision_start|>`, `vision_end_token_id` 125010 `<|vision_end|>`;
bos 124894, eos 124900 `<|im_end|>`, pad 124893. `lfm3_conv.py`, `modeling_lfm3.py` and `chat_template.jinja`
are identical to the LFM3-1.7B folder; `text_config` is identical to LFM3-1.7B's config except
`max_position_embeddings` 128000 (vs 262144).
**Language backbone = our Lfm3Model unchanged**, but with its own weights: all 286 LM tensors differ from
LFM3-1.7B (the backbone was trained further with vision), so it must load from the VL checkpoint.
Params: vision tower 164.2 M, projector 25.2 M.
**Vision encoder** (`Lfm3VlVisionModel`, 14 layers, hidden 1024, FFN 2560):
- Patchifier: `nn.Linear(3·2·16·16 = 1536 → 1024, bias=False)` on flattened patches (patch 16, temporal
patch 2: an image is duplicated along time, as in Qwen2-VL), then RMSNorm (`embedding_norm`).
- Layers alternate like the LM: types `conv` ×7 (layers 0,1,3,5,7,9,11,13) and `full_attention` ×6
(2,4,6,8,10,12). Pre-norm blocks: `x += op(operator_norm(x)); x += SwiGLU(ffn_norm(x))`
(w1/w3/w2, no bias). No sandwich norm, no output gate, no final norm after the last layer.
- Attention: bidirectional, **GQA 16 q / 8 kv heads, head_dim 64**, q_proj/k_proj/v_proj/out_proj without
bias, per-head RMSNorm on q and k (`q_layernorm`/`k_layernorm`, eps 1e-5), attends within each image
(frame) only (cu_seqlens per frame). No windowing.
- Positional encoding: **2D axial RoPE** (theta 1e6) over the whole head_dim: `inv_freq` from
spatial_dim = 32 (16 freqs); angle = [h·f, w·f] concatenated (32), then duplicated → 64 for
NeoX-style `rotate_half`. Position ids are (h, w) patch coordinates in **merge-block order**
(Transformers `get_vision_position_ids`, same as Qwen2-VL). No absolute position embedding → any
resolution, no interpolation.
- Conv layers (`Lfm3VlVisionConv2d`): `in_proj` 1024 → 3·1024 split B, C, x; `gated = B·x` → depthwise
**3×3 Conv2d** (groups 1024, padding 1, no bias) over the 2D patch grid of each frame (tokens are
reordered from merge-block order to raster, convolved, reordered back) → `out_proj(C · conv)`.
Zero padding at the frame border, frames don't see each other.
- vLLM building blocks: `MMEncoderAttention` (supports GQA and cu_seqlens; on XPU it uses FLASH_ATTN /
TRITON_ATTN / TORCH_SDPA), `QKVParallelLinear`/`ReplicatedLinear`, `RMSNorm`. The rotary is custom
(just cos/sin + rotate_half in fp32, as in the reference). Depthwise conv via `F.conv2d`.
**Projector** (`Lfm3VlMultiModalProjector`): `LayerNorm(1024)` per vision token (**before** merging,
unlike LFM2-VL where it is on the 4096-dim merged vector) → reshape 4 consecutive tokens (one 2×2 merge block,
already adjacent thanks to merge-block order) → 4096 → `linear_1` 4096→4096 (bias) → GELU → `linear_2`
4096→2048 (bias). 2×2 patches → 1 LM token, so one token covers 32×32 px.
**Image preprocessing** (`Lfm3VlImageProcessor`, Qwen2-VL-style "smart_resize"): convert RGB, resize
(bicubic) to the nearest multiple of 32 on both sides keeping the aspect ratio, with
`min_pixels` 65 536 (`size.shortest_edge`) and `max_pixels` 16 777 216 (`size.longest_edge`);
rescale 1/255, normalize mean = std = 0.5; patchify in merge-block order.
**No tiling, no thumbnail.** Tokens per image = (H/32)·(W/32), between **64 and 16 384**. Examples:
≤256² px → 64; 640×480 → 300; 1024×768 → 768; 1024² → 1024; 1920×1080 → 1088×1920 = 2040;
2400×400 → 900; 4000×3000 → 11 750; ≥4096² → 16 384. Aspect ratio max 200.
**Prompt placement.** The chat template renders an image content part as
`<|vision_start|><|image|><|vision_end|>`; the processor expands the single `<|image|>` to N `<|image|>`
tokens (start/end stay single). vLLM: prompt update = replace `<|image|>` with N × `<|image|>`;
the embeddings go into the `<|image|>` positions only. Video (phase 2) instead becomes per frame
`<t.t seconds><|vision_start|>` + `<|video|>`·n + `<|vision_end|>`.
**Weight names** (HF → our module):
- `model.language_model.*` → our `Lfm3Model` (same names as `model.*` in LFM3-1.7B, so our mapper:
`.conv.` → `.short_conv.`, stacked q/k/v and w1/w3) — 286 tensors.
- `model.vision_tower.{patchifier,embedding_norm,layers.N.{conv.{in_proj,spatial_conv,out_proj},
self_attn.{q,k,v,out}_proj,q_layernorm,k_layernorm,feed_forward.w1/w2/w3,operator_norm,ffn_norm}}` — 130.
Careful: the vision `.conv.` must not be hit by the LM's `.conv.` → `.short_conv.` rename.
- `model.multi_modal_projector.{layer_norm,linear_1,linear_2}.{weight,bias}` — 6.
- `lm_head` tied to `model.language_model.embed_tokens` (not in the file).
**Differences from LFM2-VL that matter**
| | LFM2-VL (vLLM) | LFM3-VL |
|---|---|---|
| vision encoder | SigLIP2 NaFlex (ViT, learned pos-emb interpolated) | own conv+attention hybrid, axial 2D RoPE, GQA, qk-norm |
| preprocessing | 512² tiles + thumbnail, row/col tokens | Qwen2-VL smart_resize, one native-resolution image, no tiling |
| placeholders | `<|image_start|>`, `<|img_row_i_col_j|>`, `<|img_thumbnail|>` | `<|vision_start|>` + N·`<|image|>` + `<|vision_end|>` |
| merging | pixel-unshuffle in the projector, LayerNorm on 4096 | patches arrive merge-block ordered, LayerNorm on 1024 before merge |
| LM | LFM2 | LFM3 (our plugin) |
So from `lfm2_vl.py` we take the overall model plumbing (SupportsMultiModal + IsHybrid, mapper, embed_multimodal);
the processing info / prompt update / field config follow `qwen2_vl.py` (pixel_values flat + `image_grid_thw`).
**Things to decide in step 2**
- Max image size: the default max is 16 384 tokens per image; with `--max-model-len 32768` and 4 images
the profiling dummy would not fit. Plan: default limit of 16 384 is kept as the model's, but the
dummy/profiling uses what fits; recommend `--mm-processor-kwargs '{"max_pixels": ...}'` in the
served config (e.g. 4 MP ≈ 4096 tokens) so one huge photo doesn't eat the context.
- No trust_remote_code needed: register `lfm3_vl` config + Liquid's processor classes in the plugin.
### Step 2 — implementation
Files (plugin package, same `vllm.general_plugins` entry point `lfm3 = vllm_lfm3:register`):
- `vllm_lfm3/model_vl.py` — `Lfm3VlForConditionalGeneration` (SupportsMultiModal, SupportsPP, IsHybrid),
vision encoder, projector, multimodal processor. The LM is **our `Lfm3ForCausalLM`**, built through
`init_vllm_registered_model(hf_config=text_config, architectures=["Lfm3ForCausalLM"])` — no duplicate
backbone code; it keeps its own `.conv.`→`.short_conv.` mapper and missing-weight check.
Mamba-state (short conv) shape/dtype come from `text_config`, like LFM2-VL.
- Vendored verbatim from the model folder (Apache-2.0) so nothing needs `--trust-remote-code`:
`configuration_lfm3_vl.py`, `processing_lfm3_vl.py`, `image_processing_lfm3_vl.py`,
`video_processing_lfm3_vl.py` (the processor constructor needs the video processor even for images).
`register()` adds `Lfm3VlForConditionalGeneration` to the ModelRegistry and registers config
(`lfm3_vl`, `lfm3_vl_vision`), AutoProcessor, AutoImageProcessor (torchvision backend) and
AutoVideoProcessor. `tests/vl/check_processor.py`: the vendored processor gives the same input ids and
bit-identical pixel_values as Liquid's remote processor (5 image sizes, run in separate processes).
- Vision encoder: `QKVParallelLinear` (disable_tp) for q/k/v, `ReplicatedLinear` for the other linears,
vLLM `RMSNorm`, our `Lfm3MLP` (merged w1/w3 + SiluAndMul) for the SwiGLU, `MMEncoderAttention` with
`num_kv_heads=8` and per-image `cu_seqlens` → on XPU vLLM picks **FLASH_ATTN** varlen (logged
"Using AttentionBackendEnum.FLASH_ATTN for MMEncoderAttention"). Axial RoPE applied in fp32 like the
reference. Depthwise conv = `F.conv2d(groups=1024)`; equal-size frames run as one batch, mixed sizes
frame by frame (same as Liquid). The encoder runs eager (vLLM's `compile_mm_encoder` is off by default).
- Processor (vLLM side): `pixel_values` flat per image (`flat_from_sizes(grid.prod)`), `image_grid_thw`
batched/CPU; prompt replacement `<|image|>` → N·`<|image|>`; dummy image for profiling = the largest
allowed token count factorized into an aspect ratio ≤ 200 (as qwen2_vl). `min_pixels`/`max_pixels`
(flat or `size` dict) via `--mm-processor-kwargs` are honoured for the token count.
Tokenization with `add_special_tokens=False` (the template already starts with `<|startoftext|>`).
- Video: `get_supported_mm_limits` lists only `image`, so vLLM rejects video parts; `embed_multimodal` also
raises on `pixel_values_videos`/`image_embeds`.
- Weight loading: VL mapper `model.language_model.`→`language_model.model.`, `model.vision_tower.`→
`vision_tower.`, `model.multi_modal_projector.`→`multi_modal_projector.`. Unknown names raise
(AutoWeightsLoader / the vision `load_weights`), and after loading every parameter of the whole model
must have been loaded (unquantized), else `ValueError` with the missing names. Weights: 3.58 GiB.
- Vision tower and projector are built without `quant_config` (stay BF16 under `--quantization fp8`).
- Profiling: encoder cache budget 16 384 tokens, profiled with one 16 384-token dummy image
(65 536 patches) — fits, ~15 s of the startup.
### Step 3 — correctness vs Transformers (Liquid's remote code, CPU, fp32, sdpa)
Scripts: `tests/vl/ref_vl.py` (reference, no plugin) → `results/vl/ref_vl.pt` (177 MB, not committed; regenerate with the script); `tests/vl/check_vl.py`
(vLLM offline, XPU BF16, encoder outputs via `LLM.apply_model` on the reference's own pixel_values) →
`results/vl/check_{eager,compiled}.json`. Images in `tests/vl/images/`: photo 640×488 (newspaper),
screenshot 1600×1889 (BetterBench report with tables), small 96×72, wide strip 1600×280 (text).
Greedy 64 tokens, no repetition penalty, reasoning on (generation starts inside `<think>`).
| case | image tokens vLLM / ref | vision max\|Δ\| (ref absmax) | projector max\|Δ\| / cos_min | 1st-token top-20 logprob max\|Δ\| | 64 greedy tokens |
|---|---|---|---|---|---|
| photo 640×488 | 300 / 300 | 1.97 (31.6) | 0.030 / 0.964 | 0.072 | identical |
| screenshot 1600×1889 | 2950 / 2950 | 2.49 (33.6) | 0.019 / 0.990 | 0.112 | identical |
| small 96×72 | 70 / 70 | 0.68 (30.1) | 0.014 / 0.997 | 0.121 | identical |
| wide 1600×280 | 450 / 450 | 3.62 | 0.014 / 0.997 | 0.163 | identical |
| text only | 0 / 0 | – | – | 0.111 | identical |
(eager; prompt token ids identical in all cases)
- Is the encoder diff just BF16? Liquid's own vision tower in BF16 vs its fp32 (`tests/vl/ref_bf16_encoder.py`):
projector cos_min photo 0.944, screenshot 0.985, small 0.999, wide 0.997; vision max|Δ| photo 10.1. Our
BF16 port is as close or closer to fp32 than the reference's own BF16 → precision, not a port error.
- Mixed-size batch through the encoder (all 4 images in one call) vs one image at a time: photo /
screenshot / wide bit-identical (cos 1.0), small cos_mean 0.99976 (different GEMM shape) → no leakage
across images in attention or conv.
- With compile + CUDA graphs (`enforce_eager=False`, FULL_AND_PIECEWISE): 4/5 identical; `small` diverges at
token 52 where vLLM's top-2 logprob margin is exactly 0.0 (a BF16 tie).
- Text-only through the VL model: identical to the reference for 64 tokens. (The VL backbone weights differ
from LFM3-1.7B, so its outputs are not comparable to the 1.7B text model; the text *path* is the same code.)
### Step 4 — serve + OpenAI API tests
Image `lfm3-vllm-xpu:v0.32.0-lfm3-vl` (same Dockerfile, plugin now with VL). Server via
`tests/vl/serve_vl.sh NAME [args]` on :8002 with the brief's flags + `--gpu-memory-utilization 0.4` (the daily
lfm3 in llama-swap keeps its 0.5 alongside, nothing was unloaded). Model mounted read-only straight from
`/mnt/model-library/LiquidAI/LFM3-VL-2B` (no copy to /models needed). Startup: eager 95 s, compile + graphs
158 s (first start, cold compile cache).
`tests/vl/api_test.py PORT LABEL` → `results/vl/api_{eager,graphs}.json`. Images are served to the container over
http from the host (`python3 -m http.server --bind 172.17.0.1` in `tests/vl/images`). No sampling params in the
requests → the server uses the checkpoint's `generation_config.json` (temperature 0.1, top_k 50,
repetition_penalty 1.1, = Liquid's recommendation), seed 0.
| test | eager | compile + graphs | result |
|---|---|---|---|
| 1 image by http URL (newspaper photo) | 323 prompt tok, 2476 out, 85.9 s | 1834 out, 22.6 s | "The New York Times", headline "MEN WALK ON MOON" ✔ (reads the year as 1961/62, it's 1969 — model) |
| 2 images in one request (photo + text strip) | 779 prompt tok, 10.9 s | 2.8 s | describes both correctly (NYT July 21 1969 / "Full numbers" table) ✔ |
| base64 data URL (screenshot 1600×1889, 2950 image tok) | 2979 prompt tok, 25.9 s | 7.5 s | document type + all 10 column headers of the first table exactly, and the headers of the other 3 tables ✔ |
| text only | 22 prompt tok, 3.6 s | 0.9 s | "The capital of Australia is Canberra." ✔ |
| image + tool call (`search_web`) | 3.2 s | 0.9 s | `finish_reason: tool_calls`, `search_web({"query": "The New York Times"})` (qwen3_coder parser) ✔ |
| video_url part | 400 "At most 0 video(s) may be provided in one prompt." | same | rejected ✔ |
| 5 images | 400 "At most 4 image(s) may be provided in one prompt." | same | rejected ✔ |
- **Compile + CUDA graphs work** for the VL model (vLLM default FULL_AND_PIECEWISE on the LM; the vision
encoder itself runs eager, vLLM's `compile_mm_encoder` / `cudagraph_mm_encoder` are off by default).
~3× faster than eager end to end, as for the text model → recommendation: default mode, no `--enforce-eager`.
- Greedy decoding (temperature 0) can get the thinking stuck in a doubt loop ("is it really 'The New York
Times'?", 2048 tokens without an answer); Liquid's fp32 reference starts the same pattern in its first 64 tokens,
so it's model behaviour. With the default sampling it finishes; with
`chat_template_kwargs: {"enable_thinking": false}` the same question is answered in 23 tokens. Reasoning on
images is long (~2 k tokens for a simple question) — for Open WebUI consider thinking off for quick questions.
### Step 5 — benchmarks
BetterBench 0.6.1, same invocation as all earlier rounds (`--config /srv/llm/bench/bench-standard/config.json
--quick --max-model-len 32768`), text-only corpus, against the VL server on :8002 (compile + graphs, 0.4 GPU share,
the daily lfm3 idle alongside). Results `results/vl/bb_vl_{graphs,fp8pc}.{json,html}`, logs `logs/bb_vl_*.log`.
| model / variant | decode t/s | ITL 1% low t/s | TTFT p50 ms | aggregate @8 t/s | prefill @32k t/s |
|---|--:|--:|--:|--:|--:|
| LFM3-1.7B BF16 (round 2, reference) | 128.4 | 105.1 | 67 | 768.2 | 16,626 |
| **LFM3-VL-2B BF16** | **127.4** | 101.7 | 65 | 757.7 | 16,563 |
| LFM3-1.7B FP8 per-channel (round 5, live) | 191.2 | 124.5 | 58 | 1,095.3 | 16,924 |
| **LFM3-VL-2B FP8 per-channel** (LM only, vision BF16) | **188.6** | 120.1 | 59 | 1,075.6 | 16,592 |
→ for text the VL model is as fast as the text model (same backbone, the vision tower costs nothing when no
image is sent).
**Image cost** (`tests/vl/image_ttft.py`, streaming, max_tokens 1, base64 PNG data URL like Open WebUI, fresh
image per request so no mm/prefix cache hit, median of 10, vs a text prompt of the same length):
| image | image tokens | TTFT with image | TTFT same-length text | image cost |
|---|--:|--:|--:|--:|
| 1024×768 (BF16) | 768 (784 prompt) | 218 ms | 73 ms | **145 ms** |
| 1024×1024 (BF16) | 1024 (1040 prompt) | 270 ms | 80 ms | **190 ms** |
| 1024×768 (FP8) | 768 | 223 ms | 72 ms | 151 ms |
| 1024×1024 (FP8) | 1024 | 273 ms | 74 ms | 199 ms |
Split of the image cost (`tests/vl/encoder_timing.py`, offline: CPU preprocessing = Liquid's image processor;
XPU = our vision tower + projector, synchronized, median):
| size | image tokens | preprocess (CPU) | vision encoder + projector (XPU) |
|---|--:|--:|--:|
| 512×512 | 256 | 1.9 ms | 18.8 ms |
| 1024×768 | 768 | 8.0 ms | 26.0 ms |
| 1024×1024 | 1024 | 8.3 ms | 36.8 ms |
| 1920×1080 | 2040 | 16.5 ms | 85.4 ms |
| 2048×2048 | 4096 | 39.3 ms | 220.9 ms |
So for a 1024-px image only ~35–45 ms of the ~150–190 ms is preprocessing + encoder; the rest is API-server
work: base64 + PNG decode of a 1.4–1.7 MB data URL, hashing, and moving fp32 pixel_values (3072×1536×4 B =
18.9 MB for 1024×768) to the engine. Possible later win: smaller/JPEG uploads, or a shm mm-processor cache.
**Text model regression (brief requirement)** — LFM3-1.7B on the new image `:v0.32.0-lfm3-vl`
(`model.py` itself unchanged), `tests/greedy_variant.py`, results in `results/vl/text_regress/`:
- live config `--quantization=fp8_per_channel`: **5/5 prompts bit-identical** (64/64 tokens) to round 5.
- BF16 default: 4/5 identical; raw_short differs at token 47 where the reference's top-2 margin is 0.000 —
the known near-tie from round 2 (noise floor), not a change.
- BetterBench of the live FP8 config on the new image: decode 188.6 t/s vs 191.2 (−1.4 %), @8 1,064.5 vs 1,095.3,
prefill @32k 16,594 vs 16,924 — run at 0.45 GPU share with the daily lfm3 resident on the same GPU
(round 5 had the GPU alone); within run-to-run/sharing noise, no code change in the text path.
### Recommendation + deliverables
Serve LFM3-VL-2B with compile + graphs (no `--enforce-eager`) and `--quantization=fp8_per_channel`
(+48 % decode, vision tower stays BF16, all API tests and the screenshot reading unchanged). BF16 is the
reference-exact option (drop the `--quantization` flag).
Working docker run (tested, port 8002):
```
docker run -d --rm --name lfm3-vl \
--device /dev/dri --group-add 991 --ipc=host --shm-size=16g \
-p 127.0.0.1:8002:8000 \
-v /dev/dri:/dev/dri -v /dev/dri/by-path:/dev/dri/by-path:ro \
-v /mnt/model-library/LiquidAI/LFM3-VL-2B:/model:ro \
-v $PWD/.cache/vl-fp8pc:/root/.cache/vllm \
-e HF_HUB_OFFLINE=1 -e TRANSFORMERS_OFFLINE=1 \
lfm3-vllm-xpu:v0.32.0-lfm3-vl /model --host=0.0.0.0 --port=8000 --served-model-name=lfm3-vl-2b \
--gpu-memory-utilization=0.4 --dtype=bfloat16 --quantization=fp8_per_channel --max-model-len=32768 \
--limit-mm-per-prompt='{"image": 4}' \
--reasoning-parser=qwen3 --enable-auto-tool-choice --tool-call-parser=qwen3_coder
```
llama-swap entry snippet (NOT applied — the real config is untouched; cache dir to be created by you):
```yaml
vllm/lfm3-vl-2b:
useModelName: lfm3-vl-2b
aliases:
- lfm3-vl-2b
cmdStop: docker stop -t 30 vllm-lfm3-vl
cmd: >
docker run --rm --name vllm-lfm3-vl
--device /dev/dri --group-add 991
--ipc=host --shm-size=16g
-p 127.0.0.1:${PORT}:8000
-v /dev/dri:/dev/dri
-v /dev/dri/by-path:/dev/dri/by-path:ro
-v /mnt/model-library/LiquidAI/LFM3-VL-2B:/model:ro
-v /srv/llm/runtimes/vllm-xpu/lfm3-v032/.cache/vllm-lfm3-vl:/root/.cache/vllm
-e HF_HUB_OFFLINE=1
-e TRANSFORMERS_OFFLINE=1
lfm3-vllm-xpu:v0.32.0-lfm3-vl
/model
--host=0.0.0.0
--port=8000
--served-model-name=lfm3-vl-2b
--gpu-memory-utilization=0.4
--dtype=bfloat16
--quantization=fp8_per_channel
--max-model-len=32768
--limit-mm-per-prompt={"image":4}
--enable-auto-tool-choice
--tool-call-parser=qwen3_coder
--reasoning-parser=qwen3
```
Notes for the entry: 0.4 lets it run next to the 0.5 text model (both resident ≈ 29.8 GB of 32); alone it can
take more. `:v0.32.0-lfm3-vl` also serves the text model unchanged, so the text entry could move to it later
(not done). Optional: `--mm-processor-kwargs='{"max_pixels": 4194304}'` caps an image at 4096 tokens
(default max 16 384 tokens per image = a 4096² photo eats half the 32k context).
**Open WebUI:** enable the **"Vision"** capability on the `lfm3-vl-2b` model (Admin → Models → edit →
Capabilities), otherwise the image upload is not offered / not sent. It sends images as base64 data URLs,
which is exactly what `base64_data_url` tested. Reasoning is on by default and long for images (~2 k tokens for
a simple question); thinking off per request = `chat_template_kwargs: {"enable_thinking": false}`. The
server's generation_config defaults (temperature 0.1, rep. penalty 1.1) apply when Open WebUI sends none —
avoid forcing temperature 0 (can loop inside the thinking).
Phase 2 (video) not started — waiting for your OK.