# 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 `` into the prompt (the model only emits ``). 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_