Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
985 lines
70 KiB
Markdown
985 lines
70 KiB
Markdown
# LFM3-1.7B on vLLM 0.32.0 / Intel XPU — working notes
|
||
|
||
## Environment (verified 2026-10-28)
|
||
- Image `vllm/vllm-openai-xpu:latest`: vLLM 0.32.0+xpu, torch 2.14.0+xpu, transformers 5.19.0,
|
||
triton-xpu 3.8.0, vllm-xpu-kernels 0.1.15.4, Python 3.12.
|
||
- 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/` (workspace only, not in this repo).
|
||
|
||
## Step 1 — architecture: LFM3 vs. vLLM's LFM2 (source of truth: modeling_lfm3.py)
|
||
|
||
Checkpoint: 286 tensors, single `model.safetensors`, BF16, **no `lm_head.weight`** (tied to
|
||
`model.embed_tokens.weight`). Key patterns:
|
||
```
|
||
model.embed_tokens.weight (128000, 2048)
|
||
model.embedding_norm.weight (2048,)
|
||
model.layers.N.operator_norm / ffn_norm / post_operator_norm / post_ffn_norm .weight (2048,)
|
||
model.layers.N.feed_forward.{w1,w3}.weight (7680, 2048) w2 (2048, 7680)
|
||
conv layers: model.layers.N.conv.conv.weight (2048, 1, 7)
|
||
model.layers.N.conv.in_proj.weight (6144, 2048) out_proj (2048, 2048) (no bias)
|
||
attn layers: model.layers.N.self_attn.{q,o}_proj (2048,2048) {k,v}_proj (512,2048)
|
||
q_norm/k_norm (128,) gate_proj (16, 2048)
|
||
```
|
||
|
||
| Aspect | vLLM LFM2 (lfm2.py) | LFM3 (modeling_lfm3.py) | Impact |
|
||
|---|---|---|---|
|
||
| Layer types | `conv`, `full_attention` | `conv`(13), `full_attention`(6), `sliding_attention`(5) | new layer kind; per-layer `per_layer_sliding_window=256` on `Attention` |
|
||
| Conv width | `conv_L_cache=3` | **7** | state shape `(dim, 6)`; vLLM Triton kernels can't do it (see below) |
|
||
| Conv block | in_proj → B,C,x → conv(B·x) → C·y → out_proj | identical (chunk order B, C, x; no bias) | reuse ShortConv logic |
|
||
| Conv dim config | `conv_dim`, `block_dim` | not present → `hidden_size` | adapt |
|
||
| MLP | `block_auto_adjust_ff_dim` etc. | plain SwiGLU, `intermediate_size=7680` used as-is | no ff-dim auto adjust |
|
||
| Norm layout | pre-norm (operator_norm, ffn_norm), fused residual add | **sandwich**: `post_operator_norm` on operator output and `post_ffn_norm` on FFN output *before* residual add | cannot use vLLM's fused add+norm residual trick the LFM2 way; explicit residual |
|
||
| Final norm | `embedding_norm` after last layer | **also after the last layer** (line 760) — the brief's "right after the token embedding" is wrong; the name is a historical LFM2 misnomer | final norm only |
|
||
| Attention out proj name | `out_proj` | `o_proj` | weight mapping |
|
||
| QK norm | q_layernorm/k_layernorm | `q_norm`/`k_norm`, per-head RMSNorm, before RoPE | same math, new names |
|
||
| Output gate | none | `o = o * sigmoid(gate_proj(x_normed))` per head (16 scalars/token), before o_proj | new |
|
||
| head_dim | hidden/heads | explicit 128 (= 2048/16) | |
|
||
| RoPE | single, neox | per layer type. sliding: theta 1e4, full rotation. full: theta 1e6, **"zero-tail" partial 0.5** | custom RoPE (see below) |
|
||
| RoPE precision | model dtype | q/k rotated in **fp32**, cast back | do it in fp32 too |
|
||
| Norm eps | norm_eps | `norm_eps = 1e-5` everywhere (incl. q/k norm) | |
|
||
| RMSNorm | x·rsqrt(mean x²+eps) · w | same (weight multiply after cast back to input dtype) | vLLM RMSNorm ok |
|
||
| Embedding pad idx | — | `padding_idx=124893` (only matters for training) | ignore |
|
||
|
||
### Zero-tail partial RoPE (full_attention layers) — NOT vLLM's standard partial rotary
|
||
HF computes `inv_freq[i] = theta^(-2i/128)` for i < 32 and `inv_freq[i] = 0` for 32 ≤ i < 64, then applies
|
||
neox-style `rotate_half` over the **full** 128-dim head. Consequences:
|
||
- dims 0..31 pair with 64..95 and rotate with frequencies of the *full* head-dim progression;
|
||
- dims 32..63 and 96..127 are untouched (cos=1, sin=0).
|
||
|
||
vLLM's `partial_rotary_factor=0.5` instead rotates dims 0..63 (pairs i ↔ i+32) with `theta^(-2i/64)`.
|
||
That would be silently wrong. → implement a RoPE with rotary_dim=128 and the zero-tail inv_freq
|
||
(subclass of vLLM's `RotaryEmbedding` overriding `_compute_inv_freq`), so the cos/sin cache is exact.
|
||
|
||
### Conv / hybrid state machinery in vLLM 0.32
|
||
- `ShortConv` (layers/mamba/short_conv.py) is generic in `config.conv_L_cache`; state shape from
|
||
`MambaStateShapeCalculator.short_conv_state_shape(conv_kernel=7)` → `(6, dim)` per slot in the
|
||
default "SD" layout (viewed as `(dim, 6)` via transpose). State dtype = model dtype.
|
||
- On non-CPU platforms (XPU included) it calls Triton `causal_conv1d_fn` / `causal_conv1d_update`
|
||
(ops/causal_conv1d.py). **Those kernels are hand-unrolled: prefill supports KERNEL_WIDTH 2–5
|
||
(loads/updates written for ≤4/5), decode ≤6. Width 7 is unsupported** → must ship our own conv.
|
||
- The CPU path uses a per-sequence torch `F.conv1d` loop (`causal_conv1d_fn_cpu`) — usable as a
|
||
model for a correct PyTorch fallback.
|
||
- The model class needs the `IsHybrid`/`HasInnerState` interface:
|
||
`get_mamba_state_shape_from_config`, `get_mamba_state_dtype_from_config`,
|
||
`get_mamba_state_copy_func` (copy from LFM2 with `intermediate_size=hidden_size`, `conv_kernel=7`).
|
||
- Prefix caching on hybrids → `mamba_cache_mode="align"` (state indices become per-block). The
|
||
ShortConv path doesn't pass APC block indices; plan: start with prefix caching disabled, revisit.
|
||
|
||
### Plan decisions
|
||
- Out-of-tree plugin `vllm_lfm3` with `vllm.general_plugins` entry point; registers
|
||
`Lfm3ForCausalLM` and `AutoConfig.register("lfm3", Lfm3Config)` (vendored copy of Liquid's
|
||
configuration, so `--trust-remote-code` is not required).
|
||
- Own `Lfm3ShortConv` (subclass of vLLM `ShortConv`) with width-7 conv: PyTorch reference first,
|
||
then a Triton-XPU kernel if it's correct and faster.
|
||
- Reference comparison uses Liquid's remote code inside the same image (fp32 on CPU).
|
||
|
||
## Steps 2–4 — plugin, packaging, weight loading
|
||
|
||
Layout of `./`:
|
||
```
|
||
vllm_lfm3/__init__.py register(): ModelRegistry ("vllm_lfm3.model:Lfm3ForCausalLM", lazy) +
|
||
AutoConfig.register("lfm3", Lfm3Config)
|
||
vllm_lfm3/configuration_lfm3.py vendored verbatim from the model dir (no --trust-remote-code needed)
|
||
vllm_lfm3/model.py Lfm3ForCausalLM / Lfm3Model / layers
|
||
vllm_lfm3/conv_ops.py width-agnostic causal conv1d: Triton (default) + torch fallback
|
||
pyproject.toml entry point [vllm.general_plugins] lfm3 = vllm_lfm3:register
|
||
Dockerfile FROM vllm/vllm-openai-xpu:latest + pip install --no-deps . -> lfm3-vllm-xpu
|
||
run_server.sh docker run … vllm serve (see "Serving" below)
|
||
tests/ test_conv_kernel.py, ref_compare.py, test_api.py
|
||
```
|
||
- **Packaging decision:** derived image `lfm3-vllm-xpu` (`docker build -t lfm3-vllm-xpu .`, ~1 s on top
|
||
of the base image). A pip-installed entry point is picked up by every vLLM process (API server,
|
||
EngineCore, workers) with no per-start install step; a bind-mounted source + `pip install` at
|
||
container start would also work but adds a step per start and a writable site-packages.
|
||
Verified in the log: `Resolved architecture: Lfm3ForCausalLM` in the API process and the model is
|
||
built in the spawned EngineCore.
|
||
- **Model design:**
|
||
- `Lfm3ShortConv` subclasses vLLM's `ShortConv` (projections, state shape/dtype, metadata, the
|
||
`torch.ops.vllm.short_conv` custom op are inherited) and only replaces `forward_cuda` (the path
|
||
XPU takes) with calls into `conv_ops`. Spec decode raises `NotImplementedError`.
|
||
- Hybrid state: `get_mamba_state_shape_from_config` → `short_conv_state_shape(hidden_size, conv_kernel=7)`
|
||
→ conv state `(6, 2048)` per slot; dtype = model dtype; copy func = vLLM's conv copy spec.
|
||
- Attention: `QKVParallelLinear` + `q_norm/k_norm` (vLLM RMSNorm per head) + RoPE + `Attention(
|
||
per_layer_sliding_window=256 if sliding else None)` + `sigmoid(gate_proj(x))` per head + `o_proj`.
|
||
vLLM 0.32 never copies the model-level `sliding_window` into `cache_config`, so full-attention
|
||
layers get no window. Flash-attn window is `(255, 0)` = 256 keys incl. self = HF's mask.
|
||
- RoPE: `Lfm3RotaryEmbedding(RotaryEmbedding)` with rotary_dim=128 and zero-tail `inv_freq`; one
|
||
instance per layer type, shared by its layers; cache sized to `max_model_len`.
|
||
- Sandwich norm with vLLM's fused add+RMSNorm: each layer returns the post-normed FFN output and
|
||
the un-added residual; `operator_norm(h, res)` / `ffn_norm(h, res)` do the residual adds,
|
||
`embedding_norm(h, res)` is the final norm.
|
||
- **Weight loading:** HF→vLLM mapping `.conv.`→`.short_conv.`, `q/k/v_proj`→`qkv_proj`, `w1/w3`→`w13`.
|
||
Unknown checkpoint tensors make `AutoWeightsLoader` raise; after loading, every model parameter
|
||
must have been loaded or `load_weights` raises with the missing names. All 286 tensors load.
|
||
(Caveat inherited from vLLM: AutoWeightsLoader silently ignores unexpected `*.bias` tensors —
|
||
irrelevant here, the checkpoint has no biases.)
|
||
- vLLM picks the hybrid KV layout automatically: 6 KV-cache groups of 6 layers (full / sliding /
|
||
conv); log says "Add 2 / 4 padding layers, may waste at most 15–67% KV cache memory" — harmless
|
||
for a 1.7B model at 0.5 GPU utilization.
|
||
- Prefix caching stays ON by default; vLLM switches the conv state to `mamba_cache_mode='align'`
|
||
(state copied between blocks by the framework). Our kernels only touch the current slot, which is
|
||
exactly what align mode expects → works (see step 7 for repeated-prefix test).
|
||
|
||
## Step 6 — XPU conv kernel, tested in isolation (`tests/test_conv_kernel.py`, log: logs/conv_kernel_test.log)
|
||
Reference: independent per-sequence `F.conv1d` in fp32. Cases: 5 sequences (lengths 37, 3, 1, 300, 6;
|
||
some with initial state, i.e. continued chunked prefill, some shorter than the 6-token state), then
|
||
5 decode steps with an extra padded row (slot -1); both conv-state layouts (SD default, DS).
|
||
|
||
| implementation | result |
|
||
|---|---|
|
||
| vLLM stock `causal_conv1d_fn`, width 7 | **Triton CompilationError** (kernel is unrolled for widths ≤ 5) |
|
||
| vLLM stock `causal_conv1d_update`, width 7 | runs, **wrong**: max abs err 19.6 |
|
||
| `conv_ops` torch | PASS (out err ≤ 1.5e-2 = bf16 rounding, states bit-exact) |
|
||
| `conv_ops` triton | PASS (same) |
|
||
|
||
Speed on the B65 (bf16, dim 2048, per layer call):
|
||
|
||
| | torch | triton |
|
||
|---|---|---|
|
||
| prefill 1×2048 tokens | 3.51 ms | 0.43 ms |
|
||
| prefill 16×512 tokens | 13.35 ms | 0.57 ms |
|
||
| decode batch 1 | 0.378 ms | 0.066 ms |
|
||
| decode batch 16 | 0.378 ms | 0.068 ms |
|
||
|
||
→ Triton is the default; `LFM3_CONV_IMPL=torch` switches to the fallback.
|
||
|
||
## Step 5 — correctness vs. Liquid's Transformers code (`tests/ref_compare.py`)
|
||
Reference = `modeling_lfm3.py` via trust_remote_code in the same image (transformers 5.19), on **CPU**
|
||
(independent of the XPU stack; fp32 ground truth + bf16 noise floor). vLLM side: XPU, enforce_eager,
|
||
all 5 prompts in one batch, prefix caching on (align mode). Compared at **every** position
|
||
(prompt_logprobs + 64 greedy tokens, top-20), teacher-forced; plus HF's own greedy `generate`.
|
||
Prompts: raw_short (5 tok), raw_code (13), chat_short (22), chat_long_600 (590), raw_long_1500 (1423).
|
||
Logs: logs/ref_hf_vllm_{fp32,bf16}.log, reports: results/*_report.json.
|
||
|
||
**vLLM fp32 (XPU, Triton attention) vs HF fp32 (CPU)** — the strict implementation check:
|
||
|
||
| prompt | positions | top-1 agree | mean |Δlogp| top-1 | max |Δlogp| top-5 | greedy 64 tok identical |
|
||
|---|---|---|---|---|---|
|
||
| raw_short | 68 | 68/68 | 1.4e-4 | 0.004 | 64/64 |
|
||
| raw_code | 76 | 76/76 | 1.0e-4 | 0.008 | 64/64 |
|
||
| chat_short | 85 | 85/85 | 3.1e-4 | 0.010 | 64/64 |
|
||
| chat_long_600 | 653 | 653/653 | 4.6e-4 | 0.069 | 64/64 |
|
||
| raw_long_1500 | 1486 | 1486/1486 | 0.8e-4 | 0.012 | 64/64 |
|
||
|
||
→ The port is numerically exact to fp32 tolerance, including positions > 256 (sliding window,
|
||
zero-tail RoPE on full attention, conv state across chunked prefill/decode).
|
||
|
||
**vLLM bf16 (XPU, Flash attention) vs HF fp32**, with HF bf16 (CPU) vs HF fp32 as noise floor:
|
||
|
||
| prompt | vLLM-bf16 mean Δ top-1 | HF-bf16 mean Δ top-1 (noise) | vLLM-bf16 top-1 agree | HF-bf16 top-1 agree | greedy identical (vs HF fp32) |
|
||
|---|---|---|---|---|---|
|
||
| raw_short | 0.0068 | 0.0086 | 68/68 | 67/68 | 64/64 |
|
||
| raw_code | 0.0100 | 0.0073 | 75/76 | 75/76 | 50/64 (near-tie, margin 0.017) |
|
||
| chat_short | 0.0108 | 0.0141 | 85/85 | 85/85 | 64/64 |
|
||
| chat_long_600 | 0.0171 | 0.0204 | 645/653 | 644/653 | 64/64 |
|
||
| raw_long_1500 | 0.0040 | 0.0042 | 1475/1486 | 1478/1486 | 28/64 (near-tie, margin 0.014) |
|
||
|
||
→ vLLM bf16 is as close to fp32 as HF's own bf16. Every top-1 disagreement is a near-tie
|
||
(fp32 logprob margin ≤ 0.23, mostly < 0.1); the two greedy divergences happen at ties of 0.014/0.017.
|
||
|
||
Gotcha found on the way: `generation_config.json` sets `repetition_penalty: 1.1`, which HF `generate`
|
||
applies even with `do_sample=False` — the first run's HF greedy outputs diverged after 2 tokens because
|
||
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` (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
|
||
still unsupported upstream; our kernels are still needed.
|
||
- GitHub search (API, no `gh` installed): 0 PRs and 0 issues for "LFM3", "LFM3 liquid",
|
||
"Lfm3ForCausalLM". (Related open issue #52887: causal_conv1d kernels round bf16 products before fp32
|
||
accumulation — our kernels accumulate in fp32.)
|
||
- Docker Hub `vllm/vllm-openai-xpu`: newest tag `nightly` = `nightly-edad8b0…` (2026-10-28 05:32),
|
||
built from a main commit older than the clone above → no LFM3 either. `latest` = v0.32.0.
|
||
- **Conclusion: neither main nor an open PR supports LFM3 → the plugin route (step 2) stands.**
|
||
|
||
## Step 7 — serving + API tests (`run_server.sh`, `tests/test_api.py`, log: logs/api_test_eager.log)
|
||
Server: `./run_server.sh -d` (= `vllm serve /models/LFM3-1.7B --served-model-name lfm3-1.7b --dtype bfloat16
|
||
--max-model-len 32768 --gpu-memory-utilization 0.5 --enforce-eager --reasoning-parser qwen3
|
||
--enable-auto-tool-choice --tool-call-parser qwen3_coder`, port 8000). Ready in ~85 s.
|
||
KV cache: 541,313 tokens (16.5× concurrency at 32k). Flash Attention backend, prefix caching on (align).
|
||
Sampling for chat tests: temperature 0.1, top_k 50, repetition_penalty 1.1.
|
||
|
||
| test | result |
|
||
|---|---|
|
||
| chat "17*23?" | reasoning split into `reasoning` (62 tokens), content `'391'`, no think tags in content |
|
||
| `chat_template_kwargs: {enable_thinking: false}` | no reasoning, direct answer |
|
||
| streaming | reasoning deltas then content deltas (383 events) |
|
||
| tool call (get_weather) | `finish_reason=tool_calls`, `{"city": "Berlin"}`, content None; follow-up turn with tool result → "light rain, 14°C" |
|
||
| long prompt (701 tokens, fact in first sentence) | answers `1817` → full-attention layers see past the 256 window |
|
||
| prefix caching (align mode) | 2nd identical request: 1280 tokens from cache, greedy output identical to cold run |
|
||
|
||
13/13 checks pass. Notes:
|
||
- The qwen3 reasoning parser works even though the template puts `<think>` into the prompt (the
|
||
model only emits `</think>`). vLLM 0.32 returns the field as `reasoning` (not `reasoning_content`).
|
||
- First request after start takes ~10 s extra (Triton JIT of the conv kernels; cached afterwards).
|
||
|
||
## Step 8 — without --enforce-eager (torch.compile + XPU graphs)
|
||
`EAGER=0 ./run_server.sh -d`: works out of the box. torch.compile 38 s (cached in-container), graph
|
||
capture FULL_AND_PIECEWISE (51 piecewise + 35 FULL decode sizes) ~17 s, server ready in ~145 s
|
||
(eager: ~85 s). Our Triton conv kernels are captured inside the FULL decode graphs.
|
||
Correctness re-checked, not assumed:
|
||
- API tests 13/13 (logs/api_test_compiled.log).
|
||
- **fp32 + graphs vs HF fp32** (results/vllm_fp32_graphs_report.json): top-1 68/68, 76/76, 85/85,
|
||
652/653 (one 0.002-margin tie), 1486/1486; mean |Δlogp| 1e-4–5e-4; greedy 64/64 on all 5 prompts.
|
||
- bf16 server vs eager bf16 run (tests/compare_greedy_server.py): divergences only at the known
|
||
near-ties (pos 47/50/49/28), same with 5 concurrent requests.
|
||
- Gotcha: `vllm serve` applies generation_config.json (repetition_penalty 1.1, temperature 0.1,
|
||
top_k 50) as *default* sampling params. Any greedy comparison through the API must pass
|
||
`repetition_penalty: 1.0` explicitly. (Handy for production: those are Liquid's recommended defaults.)
|
||
|
||
## Step 9 — benchmarks (`tests/bench.py`, wraps `vllm bench serve`, random dataset, --ignore-eos)
|
||
Files: results/bench_eager.md, results/bench_compiled.md (+ raw JSON in results/bench_<label>/).
|
||
Each run uses a fresh random seed; prefix-cache hits are tracked per row (all 0.0%).
|
||
|
||
| scenario | metric | eager | compiled + graphs |
|
||
|---|---|---|---|
|
||
| decode 128/512, c=1 | median TPOT | 34.3 ms (28.8 tok/s) | **7.8 ms (126 tok/s)** |
|
||
| decode 128/512, c=16 | output tok/s | 444 | **1593** |
|
||
| prefill 4096/1, c=1 | median TTFT | 227 ms (≈18k tok/s) | 234 ms (17.5k tok/s) |
|
||
| prefill 4096/1, c=16 | prefill tok/s | 22.0k | 22.3k |
|
||
|
||
- Decode in eager mode is launch-overhead bound (TPOT flat from batch 1 to 16); graphs give 4.3×
|
||
at c=1 and 3.6× at c=16. Prefill is compute bound and unaffected. → **Run without --enforce-eager.**
|
||
- Pitfalls hit while benchmarking (fixed in tests/bench.py): (1) a fixed `--seed` re-sends identical
|
||
random prompts → served from prefix cache (one bogus run showed 228k prefill tok/s); (2) the first
|
||
run after server start includes ~10 s Triton JIT (eager prefill c=1 throughput showed 3.1k tok/s
|
||
while its TTFT said 18k) → script now warms up first. An earlier eager prefill c=16 figure of 31k
|
||
was cache-contaminated and is superseded.
|
||
- Initial mixed 1k/256 run (eager, `vllm bench serve` default): c=1 29.7 tok/s out, TPOT 33.2 ms;
|
||
c=16 424 tok/s out, TPOT 36.0 ms (logs/bench_eager_c{1,16}.log).
|
||
- BetterBench: see below.
|
||
|
||
## Deployment
|
||
|
||
Build once: `docker build -t lfm3-vllm-xpu .`
|
||
|
||
Ready-to-use `docker run` (recommended: graphs on, i.e. no --enforce-eager):
|
||
```bash
|
||
docker run -d --rm --name lfm3-serve \
|
||
--device /dev/dri -v /dev/dri/by-path:/dev/dri/by-path --ipc=host --shm-size=16g \
|
||
-p 127.0.0.1:8000:8000 \
|
||
-v /models/LFM3-1.7B:/models/LFM3-1.7B:ro \
|
||
lfm3-vllm-xpu \
|
||
/models/LFM3-1.7B --served-model-name lfm3-1.7b --dtype bfloat16 \
|
||
--max-model-len 32768 --gpu-memory-utilization 0.5 \
|
||
--reasoning-parser qwen3 --enable-auto-tool-choice --tool-call-parser qwen3_coder \
|
||
--host 0.0.0.0 --port 8000
|
||
```
|
||
(`./run_server.sh -d` = same with --enforce-eager; `EAGER=0 ./run_server.sh -d` = the above.)
|
||
Startup ~145 s with graphs (compile cache lives inside the container and is lost with --rm; mounting
|
||
a host dir at /root/.cache/vllm would make restarts faster). No --trust-remote-code needed.
|
||
|
||
llama-swap model entry — as live in /etc/llama-swap/config.yaml. Since 2026-10-29: W8A16 (online FP8
|
||
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, per-channel scales) ----------
|
||
vllm/lfm3-1.7b:
|
||
useModelName: lfm3-1.7b
|
||
aliases:
|
||
- lfm3-1.7b
|
||
cmdStop: docker stop -t 30 vllm-lfm3
|
||
cmd: >
|
||
docker run --rm --name vllm-lfm3
|
||
--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:/model:ro
|
||
-v /srv/llm/runtimes/vllm-xpu/lfm3-v032/.cache/vllm-lfm3:/root/.cache/vllm
|
||
-e HF_HUB_OFFLINE=1
|
||
-e TRANSFORMERS_OFFLINE=1
|
||
lfm3-vllm-xpu:v0.32.0-lfm3-fp8fix
|
||
/model
|
||
--host=0.0.0.0
|
||
--port=8000
|
||
--served-model-name=lfm3-1.7b
|
||
--gpu-memory-utilization=0.5
|
||
--dtype=bfloat16
|
||
--quantization=fp8_per_channel
|
||
--max-model-len=32768
|
||
--enable-auto-tool-choice
|
||
--tool-call-parser=qwen3_coder
|
||
--reasoning-parser=qwen3
|
||
```
|
||
(The global `healthCheckTimeout: 1800` covers the ~140 s cold start; warm start with the cache mount ~80 s.)
|
||
Defaults applied by the server from generation_config.json: temperature 0.1, top_k 50,
|
||
repetition_penalty 1.1 (Liquid's recommendation) — clients don't need to send them.
|
||
|
||
## Known limitations
|
||
- Speculative decoding not supported by the short-conv path (raises NotImplementedError).
|
||
- TP > 1 is structurally supported (parallel linears, sharded conv dim) but untested (single GPU).
|
||
- Requests that override `repetition_penalty` etc. work as usual; generation_config defaults apply otherwise.
|
||
|
||
### Sanity check of the benchmark numbers against measured hardware limits (`tests/hw_roofline.py`)
|
||
B65 measured: decode-like bf16 GEMV ≈ 428 GB/s (raw copy 956 GB/s read+write), bf16 GEMM ≈ 92–94 TFLOPS.
|
||
- Decode reads all weights per step: ~1.73 B params (incl. tied lm_head) = 3.45 GB → floor ≈ 8.1 ms at
|
||
428 GB/s. Measured 7.8 ms (≈ 440 GB/s effective) → **at the bandwidth roofline**; only weight
|
||
quantization would speed up single-stream decode further. c=16 TPOT only +10% → still weight-bound.
|
||
- Prefill: 2 × 1.47 B FLOP/token (+ attention) → 4096 tokens ≈ 12.4 TFLOP; 227 ms ≈ 55 TFLOPS (58% of
|
||
GEMM peak), c=16 at 22.3k tok/s ≈ 65 TFLOPS (70%). Remainder = norms/conv/rope/attention/gating. Reasonable.
|
||
- Eager decode 34 ms = ~26 ms launch/dispatch overhead above the floor (~1 ms per layer), consistent with
|
||
TPOT being flat across batch sizes.
|
||
|
||
### BetterBench 0.6.1 (github.com/GGZ14/BetterBench @ f72bb90), compiled mode, `--quick --decode --prefill`
|
||
Installed in ./.venv-bench, BETTERBENCH_HOME=./.betterbench, `--no-update-check`.
|
||
Report: results/betterbench/compiled.html (+ compiled.json), log: logs/betterbench_compiled.log.
|
||
- Single stream, 8 real-prompt categories × 5 passes: decode **128.4 tok/s** median (all categories
|
||
128.2–129.1, CV ≤ 0.6%), inter-token p50 7.8 ms / p99 8.6 ms, TTFT p50 ≈ 64 ms.
|
||
- Prefill sweep (cold cache): 1.5k tok → 15.2k tok/s, 5.9k → 18.4k, 11.8k → 18.0k, 23.5k → 16.7k tok/s
|
||
(TTFT 1.41 s at 23.5k tokens); 64k skipped (context 32k).
|
||
- Agrees with tests/bench.py (7.8 ms TPOT, ~17.5k prefill tok/s at 4k).
|
||
- Caveats: BetterBench labels the stream "speculative decoding" because 1 of 40 runs delivered a
|
||
multi-token chunk; tok/update is 1.00 everywhere, there is no spec decode. In --quick mode all runs
|
||
hit max_tokens while still thinking (reasoning on by default), so TTFA (time to first answer token)
|
||
is not measurable; decode/prefill speeds are unaffected.
|
||
|
||
## Round 2 — graphs/compile tuning
|
||
|
||
### Step 1 — baseline config (confirmed 2026-10-28)
|
||
Baseline = bench-standard run `/srv/llm/bench/results/20261028-231853-pascal-vllm-lfm3-1.7b-vllm-arc-pro-b65`
|
||
(decode 127.6 t/s, ITL 1% low 102.3, TTFT p50 60 ms, aggregate @8 764.4 t/s, prefill @32k 16,670 t/s).
|
||
It did **not** use `--enforce-eager`: torch.compile (`CompilationMode.VLLM_COMPILE`) + vLLM default
|
||
graphs `FULL_AND_PIECEWISE`, capture sizes 1,2,4,8,16,24,…,512 (51 PIECEWISE + 35 FULL decode graphs;
|
||
the 2-graph FULL pass before them is the memory-profiling run). Same config as "compiled" in step 8/9.
|
||
|
||
Exact serve command (llama-swap `/running`, also in the result's `server-cmd.txt`):
|
||
```
|
||
docker run --rm --name vllm-lfm3 --device /dev/dri --group-add 991 --ipc=host --shm-size=16g
|
||
-p 127.0.0.1:5800:8000 -v /dev/dri:/dev/dri -v /dev/dri/by-path:/dev/dri/by-path:ro
|
||
-v /models/LFM3-1.7B:/model:ro
|
||
-v /srv/llm/runtimes/vllm-xpu/lfm3-v032/.cache/vllm-lfm3:/root/.cache/vllm
|
||
-e HF_HUB_OFFLINE=1 -e TRANSFORMERS_OFFLINE=1
|
||
lfm3-vllm-xpu:v0.32.0-lfm3 /model --host=0.0.0.0 --port=8000 --served-model-name=lfm3-1.7b
|
||
--gpu-memory-utilization=0.5 --dtype=bfloat16 --max-model-len=32768
|
||
--enable-auto-tool-choice --tool-call-parser=qwen3_coder --reasoning-parser=qwen3
|
||
```
|
||
Baseline BetterBench invocation (from the result's `meta.json`): BetterBench 0.6.1,
|
||
`--config /srv/llm/bench/bench-standard/config.json --quick --max-model-len 32768`, endpoint
|
||
`http://localhost:8080/v1`, model `vllm/lfm3-1.7b` (decode + concurrency + prefill, all defaults).
|
||
|
||
### Step 2 — variants (same image `lfm3-vllm-xpu:v0.32.0-lfm3`, same serve flags as the baseline)
|
||
Scripts: `tests/variant.sh NAME [--fresh] [vllm args]` (container `lfm3-var-NAME` on :8001, own compile
|
||
cache `./.cache/NAME`, server log `logs/variant_NAME.log`, startup/VRAM in `results/variants_startup.tsv`);
|
||
`tests/greedy_variant.py` (64 greedy tokens for the 5 ref_compare prompts, rep. penalty 1.0, prints the
|
||
reference's top-2 logprob margin at the first difference). Outputs: results/variants/greedy_*.json.
|
||
|
||
| variant | flags | starts | cold startup | torch.compile | graph capture | KV cache | VRAM used | greedy 64 tok vs eager (sequential) |
|
||
|---|---|---|---|---|---|---|---|---|
|
||
| a) eager | `--enforce-eager` | yes | 75 s | — | — | 541k tok | 15.75 GB | reference |
|
||
| b) default = baseline | — (FULL_AND_PIECEWISE, sizes 1…512) | yes | 138 s | 38.9 s | 7 s, 0.11 GiB | 506k tok | 15.67 GB | 3/5 identical; diffs at pos 47 / 50, margins 0.25 / 0.125 |
|
||
| d) FULL_DECODE_ONLY | `--compilation-config={"cudagraph_mode":"FULL_DECODE_ONLY","cudagraph_capture_sizes":[1,2,4,8]}` | yes | 128 s | 38.2 s | 1 s, ~0 GiB | 533k tok | 16.07 GB | 2/5 identical; diffs at pos 47 / 50 / 49, margins 0.25 / 0.125 / 0.000 |
|
||
| c) compile, no graphs | — | not run (b works) | | | | | | |
|
||
|
||
- "Cold startup" = `docker run` → `/v1/models` answers, with an empty compile cache. VRAM is ~fixed by
|
||
`--gpu-memory-utilization=0.5` (≈16 GB of 32), the variants only shift it between KV cache and graphs.
|
||
- **Noise floor:** eager vs *eager itself* run with all 5 prompts concurrently is also only 3/5 identical
|
||
(diffs at pos 47 margin 0.25, pos 49 margin 0.000). Batch composition changes bf16 reductions, so
|
||
"64 tokens identical" fails at near-ties even without any compile/graph change.
|
||
- Every divergence in every variant (sequential and concurrent) is at a top-2 margin ≤ 0.25 and at the
|
||
same positions as round 1's known near-ties (raw_short 47, chat_short 49, raw_code 50, raw_long_1500
|
||
28). No variant diverges at a confident token → all three are numerically equivalent to eager.
|
||
|
||
### Step 3 — BetterBench per variant
|
||
Invocation identical to the baseline (BetterBench 0.6.1, `--config /srv/llm/bench/bench-standard/config.json
|
||
--quick --max-model-len 32768`), endpoint `http://127.0.0.1:8001/v1` directly (no llama-swap), model
|
||
`lfm3-1.7b`. Results: results/variants/bb/{eager,default,fdo1248}.{json,html}, logs: logs/bb_*.log.
|
||
Table: `tests/bb_table.sh`; ITL column via `tests/itl_low.py` (see note). Bandwidth = 3.47 GB × decode t/s,
|
||
% of the B65's 608 GB/s spec.
|
||
|
||
| variant | decode t/s | eff. bandwidth | ITL 1% low t/s | TTFT p50 ms | aggregate @8 t/s | prefill @32k t/s | warm / cold startup |
|
||
|---|--:|--:|--:|--:|--:|--:|--:|
|
||
| baseline (= b, via llama-swap) | 127.6 | 443 GB/s (73%) | 102.3 | 60 | 764.4 | 16,670 | — |
|
||
| a) eager | 29.5 | 102 GB/s (17%) | 22.9* | 125 | 190.9 | 16,502 | 60 s / 75 s |
|
||
| **b) default (FULL_AND_PIECEWISE)** | **128.4** | **446 GB/s (73%)** | **105.1** | 67 | **768.2** | 16,626 | 83 s / 138 s |
|
||
| d) FULL_DECODE_ONLY [1,2,4,8] | 128.7 | 447 GB/s (73%) | 107.7* | 85 | 744.3 | 16,691 | 69 s / 128 s |
|
||
|
||
\* BetterBench printed "update p99" instead of ITL for these runs: one or more stream updates carried
|
||
2 tokens (SSE coalescing; tok/update is 1.00, no spec decode), which flips it into its "speculative"
|
||
view. `tests/itl_low.py` recomputes the number with BetterBench's own `itl_to_rate_samples` +
|
||
`summarize(rate_like=True)` per category and the config weights; it reproduces the baseline's 102.3 and
|
||
b's 105.1 exactly.
|
||
|
||
Findings:
|
||
- b and d decode identically (128.4 vs 128.7 t/s, within noise). Both sit at the measured GEMV
|
||
bandwidth of this card (~428–440 GB/s, tests/hw_roofline.py); the 608 GB/s spec is not reachable for
|
||
decode-shaped reads. **Graph mode is no longer a lever for decode** — only fewer bytes (quantization) are.
|
||
- d is worse where piecewise graphs matter: TTFT p50 +18 ms (85 vs 67 ms; short prefills run without
|
||
graphs in FULL_DECODE_ONLY), concurrency TTFT p50 at @8 105 vs 77 ms, aggregate @8 −3% (744 vs 768).
|
||
Its only gains are ~14 s faster warm startup and ~0.1 GiB less graph memory — irrelevant at 0.5 util.
|
||
- Eager is 4.3× slower at decode (launch-bound, flat ~29 t/s per request at every concurrency level).
|
||
- Prefill is compute-bound and identical across all variants (16.5–16.7k t/s at 23.5k tokens).
|
||
- Baseline vs b (llama-swap vs direct): equal within noise → the proxy costs nothing measurable.
|
||
|
||
### Step 4 — recommendation
|
||
**Keep b) the vLLM default (no `--enforce-eager`, no `--compilation-config`)**: best or tied on every
|
||
metric except a ~14 s slower warm start. That is exactly what the live llama-swap entry already runs, so
|
||
the snippet below only changes to match the live entry (no flag changes).
|
||
|
||
## Round 3 — W8A16 (online FP8 weights, BF16 compute)
|
||
|
||
### Step 1 — quant_config plumbing
|
||
All big linears are vLLM linear classes with `quant_config` passed through: attention `qkv_proj`
|
||
(QKVParallelLinear) and `o_proj` (RowParallelLinear), MLP `w13` (MergedColumnParallelLinear) and `w2`
|
||
(RowParallelLinear), conv `in_proj` / `out_proj` (built by vLLM's `ShortConv`, which passes quant_config).
|
||
Deliberately unquantized: `gate_proj` (16×2048 output gate, 0.002% of weights), the conv kernel weight
|
||
(read directly by our Triton conv kernel), embedding / tied `lm_head` (vLLM's online FP8 never quantizes
|
||
VocabParallelEmbedding), norms.
|
||
**Bug found when serving FP8:** `Lfm3ForCausalLM.load_weights` raised on parameters missing from the
|
||
checkpoint — online FP8 adds `weight_scale` params that a BF16 checkpoint can't contain (96 of them).
|
||
Fix: run our strict check only when `quant_config is None`; for quantized models vLLM's DefaultModelLoader
|
||
does the check itself and knows which params a checkpoint cannot carry. BF16 path unchanged. Built as
|
||
`lfm3-vllm-xpu:v0.32.0-lfm3-fp8fix` (the live llama-swap image `:v0.32.0-lfm3` is untouched).
|
||
|
||
### Step 2 — serving with `--quantization=fp8` (log: logs/variant_fp8.log)
|
||
- vLLM 0.32 maps it to online per-tensor FP8 (`fp8` is a deprecated alias of `fp8_per_tensor`), and on XPU
|
||
selects **`XPUW8A16FP8LinearKernel` for `Fp8PerTensorOnlineLinearMethod`** → `torch.ops._xpu_C.fp8_gemm_w8a16`:
|
||
FP8 (e4m3) weights + per-tensor scale, BF16 activations, i.e. real W8A16 (the W8A8 kernel is only the
|
||
fallback).
|
||
- **Model weight memory 1.88 GiB vs 3.24 GiB BF16** (−42%). Matches all linears in FP8 (~1.47 B params →
|
||
1.47 GB) + BF16 embedding/lm_head (0.52 GB) + small rest. Bytes read per decode step: ~2.02 GB vs 3.47 GB
|
||
→ ideal bandwidth-bound speedup ≤ 1.72×.
|
||
- KV cache memory 11.69 GiB (BF16: 10.61 GiB) at the same 0.5 utilization; graph capture 0.54 GiB
|
||
(BF16 0.12); cold start 144 s (torch.compile 38 s).
|
||
|
||
### Step 3 — quality vs BF16 (greedy, `tests/quality_prompts.py`, results/w8a16/quality_{bf16,fp8}.json)
|
||
| prompt | first token divergence (BF16 top-2 margin there) | BF16 answer | FP8 answer | correct? |
|
||
|---|---|---|---|---|
|
||
| math (train minutes) | 13 of 1166 (0.000) | 201 | 201 (613 tokens of reasoning instead of 1166) | both |
|
||
| code (is_palindrome) | 26 of 315 (0.375) | `cleaned = ''.join(ch.lower() … isalnum())` | same, variable named `filtered` | both |
|
||
| German (blue sky) | 33 of 332 (0.125) | correct, 2 sentences (one grammar slip "das kurzwelliges") | correct, 2 sentences (one awkward clause) | both |
|
||
| tool call (weather Hamburg) | 33 of 90 (0.25), inside reasoning | `get_weather{"city":"Hamburg","unit":"celsius"}` | identical call | both |
|
||
| summary (council vote) | 110 of 386 (0.25) | one sentence, all facts | one sentence, all facts, reordered | both |
|
||
|
||
64-token raw-prompt check vs eager BF16 (`tests/greedy_variant.py`, results/w8a16/greedy_fp8.json): 2/5
|
||
identical; raw_short diverges at token 1 (margin 0.31), chat_short at 4 (0.25), raw_code at 50 (0.125).
|
||
→ FP8 changes greedy paths much earlier than BF16 batch noise does (always at near-ties ≤ 0.375, never at a
|
||
confident token), but every final answer stayed correct and the tool call is byte-identical.
|
||
BF16 regression check after the load_weights fix: `:v0.32.0-lfm3-fp8fix` without quantization gives
|
||
greedy output bit-identical to the pre-fix default image (5/5 prompts, 64/64 tokens,
|
||
results/w8a16/greedy_bf16fix.json).
|
||
|
||
### Step 4 — BetterBench (same invocation as step 3; results/variants/bb/fp8.{json,html}, logs/bb_fp8.log)
|
||
| variant | decode t/s | eff. bandwidth (3.47 GB × t/s) | real bytes/step × t/s | ITL 1% low t/s | TTFT p50 ms | aggregate @8 t/s | prefill @32k t/s |
|
||
|---|--:|--:|--:|--:|--:|--:|--:|
|
||
| b) BF16 default | 128.4 | 446 GB/s (73%) | 446 GB/s (3.47 GB) | 105.1 | 67 | 768.2 | 16,626 |
|
||
| **FP8 W8A16 (`--quantization=fp8`)** | **191.3** | 664 GB/s (109%) | **386 GB/s** (2.02 GB) | **122.5** | 59 | **1,036.5** | 16,744 |
|
||
| Δ | **+49%** | | | +17% | −8 ms | **+35%** | +0.7% |
|
||
|
||
- The 3.47 GB column is a "BF16-equivalent" number and exceeds the 608 GB/s spec, which only shows that
|
||
fewer bytes are read. Real traffic is ~2.02 GB/step → 386 GB/s, ~88–90% of the measured BF16 GEMV
|
||
bandwidth (428–440 GB/s), so the FP8 GEMV kernel is slightly less bandwidth-efficient than BF16, and
|
||
we get 1.49× of the ideal 1.72×.
|
||
- Concurrency per-request decode: 192 / 186 / 176 / 160 t/s at 1/2/4/8 (BF16: 128 / 126 / 121 / 116).
|
||
- Prefill unchanged (compute-bound; `fp8_gemm_w8a16` dequantizes to BF16 compute).
|
||
- Next lever if wanted: the BF16 tied embedding/lm_head is now 0.52 of the 2.02 GB read per step (26%).
|
||
vLLM's online FP8 does not quantize `ParallelLMHead`; an FP8/INT8 lm_head would need an offline
|
||
checkpoint or plugin work. Step 5 (offline INT8 route) not needed: online FP8 works and is +49%.
|
||
|
||
### Recommendation / deployed (2026-10-29)
|
||
FP8 W8A16 is the new default: llama-swap `vllm/lfm3-1.7b` switched to image `lfm3-vllm-xpu:v0.32.0-lfm3-fp8fix`
|
||
+ `--quantization=fp8` (backup of the previous config: /etc/llama-swap/config.yaml.bak-pre-lfm3-fp8).
|
||
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.
|
||
|
||
**Deployed 2026-10-29 14:27:** llama-swap now serves **LFM3-VL-2B instead of LFM3-1.7B**: entry `vllm/lfm3-vl-2b`
|
||
(aliases `lfm3-vl-2b`, `lfm3-1.7b` so existing clients keep working), image `:v0.32.0-lfm3-vl`,
|
||
`--quantization=fp8_per_channel`, `--gpu-memory-utilization=0.5` (it replaces the text model, so no 0.4 split),
|
||
`--limit-mm-per-prompt={"image":4}`, cache `/srv/llm/runtimes/vllm-xpu/lfm3-v032/.cache/vllm-lfm3-vl`.
|
||
Backup of the previous config: /etc/llama-swap/config.yaml.bak-pre-lfm3-vl. Verified via :8080: watch-reload clean,
|
||
cold start 2m46s, `XPUW8A16FP8LinearKernel` for `Fp8PtpcOnlineLinearMethod`, weights 2.24 GiB, newspaper photo →
|
||
"The New York Times", "MEN WALK ON MOON"; alias `lfm3-1.7b` → "17*23" = 391.
|