Add LFM3-1.7B vLLM XPU plugin
Out-of-tree vLLM 0.32 plugin for LiquidAI LFM3 on Intel XPU: model, width-7 short-conv Triton kernels, Dockerfile, reference/API/bench tests, working notes and benchmark results. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
4e7a7ce903
26 files changed
+21423
No files matched your search
@@ -0,0 +1,5 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv*/
|
||||
logs/
|
||||
.betterbench/
|
||||
@@ -0,0 +1,7 @@
|
||||
# xpu-llm-ports
|
||||
|
||||
Model ports and serving setups for vLLM on Intel XPU (Arc / Battlemage). One self-contained folder per project.
|
||||
|
||||
| folder | what |
|
||||
|---|---|
|
||||
| [`lfm3/`](lfm3/) | LiquidAI LFM3-1.7B as an out-of-tree vLLM 0.32 plugin (width-7 short-conv Triton kernels, zero-tail partial RoPE). Verified against Liquid's HF code; see [`lfm3/NOTES.md`](lfm3/NOTES.md). |
|
||||
@@ -0,0 +1,4 @@
|
||||
*
|
||||
!pyproject.toml
|
||||
!vllm_lfm3
|
||||
vllm_lfm3/__pycache__
|
||||
@@ -0,0 +1,6 @@
|
||||
# vLLM 0.32.0 XPU + LFM3 plugin
|
||||
FROM vllm/vllm-openai-xpu:latest
|
||||
COPY pyproject.toml /opt/vllm-lfm3/pyproject.toml
|
||||
COPY vllm_lfm3 /opt/vllm-lfm3/vllm_lfm3
|
||||
RUN pip install --no-cache-dir --no-deps --no-build-isolation /opt/vllm-lfm3 \
|
||||
&& python -c "from importlib.metadata import entry_points as e; assert any(x.name == 'lfm3' for x in e(group='vllm.general_plugins'))"
|
||||
+325
@@ -0,0 +1,325 @@
|
||||
# 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/`.
|
||||
|
||||
## 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` (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 (snippet only — the real config was not touched):
|
||||
```yaml
|
||||
models:
|
||||
"lfm3-1.7b":
|
||||
cmd: >
|
||||
docker run --rm --name lfm3-swap
|
||||
--device /dev/dri -v /dev/dri/by-path:/dev/dri/by-path --ipc=host --shm-size=16g
|
||||
-p 127.0.0.1:${PORT}: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
|
||||
cmdStop: docker stop lfm3-swap
|
||||
proxy: http://127.0.0.1:${PORT}
|
||||
checkEndpoint: /v1/models
|
||||
# graph capture + torch.compile: allow a slow first start
|
||||
healthCheckTimeout: 300
|
||||
```
|
||||
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.
|
||||
@@ -0,0 +1,16 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=64"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "vllm-lfm3"
|
||||
version = "0.1.0"
|
||||
description = "Out-of-tree vLLM plugin: LiquidAI LFM3 (Lfm3ForCausalLM) with width-7 short-conv kernels"
|
||||
requires-python = ">=3.10"
|
||||
license = { text = "Apache-2.0" }
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
lfm3 = "vllm_lfm3:register"
|
||||
|
||||
[tool.setuptools]
|
||||
packages = ["vllm_lfm3"]
|
||||
@@ -0,0 +1,14 @@
|
||||
# LFM3-1.7B bench — compiled (2026-10-28 20:01)
|
||||
|
||||
Server: lfm3-vllm-xpu, Arc Pro B65, bf16, `vllm bench serve` random dataset, `--ignore-eos`.
|
||||
|
||||
| scenario | conc | in/out | requests | median TTFT ms | P99 TTFT ms | median TPOT ms | P99 ITL ms | prefill tok/s | decode tok/s | total tok/s | prefix-cache hits |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| prefill | 1 | 4096/1 | 8 | 234.3 | 239.8 | 0.00 | 0.00 | 17481 | 4.3 | 17486 | 0.0% |
|
||||
| prefill | 16 | 4096/1 | 64 | 2914.3 | 2970.8 | 0.00 | 0.00 | 22334 | 5.5 | 22340 | 0.0% |
|
||||
| decode | 1 | 128/512 | 4 | 60.5 | 63.3 | 7.81 | 8.60 | 32 | 126.3 | 158 | 0.0% |
|
||||
| decode | 16 | 128/512 | 32 | 735.7 | 1330.3 | 8.60 | 11.83 | 398 | 1593.0 | 1991 | 0.0% |
|
||||
|
||||
- prefill tok/s = input tokens / duration (meaningful for the prefill rows: 1 output token).
|
||||
- decode tok/s = output tokens / duration (meaningful for the decode rows).
|
||||
- raw JSON: results/bench_compiled/
|
||||
@@ -0,0 +1,14 @@
|
||||
# LFM3-1.7B bench — eager (2026-10-28 20:06)
|
||||
|
||||
Server: lfm3-vllm-xpu, Arc Pro B65, bf16, `vllm bench serve` random dataset, `--ignore-eos`.
|
||||
|
||||
| scenario | conc | in/out | requests | median TTFT ms | P99 TTFT ms | median TPOT ms | P99 ITL ms | prefill tok/s | decode tok/s | total tok/s | prefix-cache hits |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| prefill | 1 | 4096/1 | 8 | 226.6 | 8286.0 | 0.00 | 0.00 | 3125 | 0.8 | 3126 | 0.0% |
|
||||
| prefill | 16 | 4096/1 | 64 | 2959.9 | 3019.6 | 0.00 | 0.00 | 21986 | 5.4 | 21991 | 0.0% |
|
||||
| decode | 1 | 128/512 | 4 | 140.2 | 615.8 | 34.29 | 39.43 | 7 | 28.8 | 36 | 0.0% |
|
||||
| decode | 16 | 128/512 | 32 | 762.8 | 1372.6 | 34.58 | 39.28 | 111 | 444.3 | 555 | 0.0% |
|
||||
|
||||
- prefill tok/s = input tokens / duration (meaningful for the prefill rows: 1 output token).
|
||||
- decode tok/s = output tokens / duration (meaningful for the decode rows).
|
||||
- raw JSON: results/bench_eager/
|
||||
@@ -0,0 +1 @@
|
||||
{"date": "20261028-183719", "endpoint_type": "openai", "backend": "openai", "label": null, "model_id": "lfm3-1.7b", "tokenizer_id": "/models/LFM3-1.7B", "num_prompts": 16, "request_rate": "inf", "burstiness": 1.0, "max_concurrency": 1, "duration": 137.7218146850064, "completed": 16, "failed": 0, "total_input_tokens": 16384, "total_output_tokens": 4096, "request_throughput": 0.11617622114982123, "request_goodput": null, "output_throughput": 29.741112614354236, "total_token_throughput": 148.70556307177117, "latencies": [8.547571271992638, 8.889110722011537, 8.513282951011206, 8.516900429007364, 8.512097928993171, 8.458169747987995, 8.545284949999768, 8.677622813003836, 8.673199532990111, 8.5786840429937, 8.398340497995378, 8.560537099998328, 8.771953076997306, 8.82979527200223, 8.54980193200754, 8.692260933006764], "queue_times": [0.00019121299555990845, 8.548296945999027, 17.437811625990435, 25.951511513994774, 34.468911342002684, 42.98138918800396, 51.44007847500325, 59.98573068200494, 68.66370639100205, 77.33717527899717, 85.91631292000238, 94.31508973700693, 102.87608187599108, 111.64841317999526, 120.47858315899794, 129.0288025179907], "max_output_tokens_per_s": 32.0, "max_concurrent_requests": 2, "rtfx": 0.0, "mean_ttft_ms": 132.67103337602748, "median_ttft_ms": 130.65361749613658, "std_ttft_ms": 10.283852664352313, "p99_ttft_ms": 163.36125710149642, "mean_tpot_ms": 33.23330310489765, "median_tpot_ms": 33.056460207844076, "std_tpot_ms": 0.49405169584662145, "p99_tpot_ms": 34.19131536847072, "mean_itl_ms": 33.29859446659687, "median_itl_ms": 32.96410600160016, "std_itl_ms": 2.0494982688944394, "p99_itl_ms": 37.60655520265573}
|
||||
@@ -0,0 +1 @@
|
||||
{"date": "20261028-183856", "endpoint_type": "openai", "backend": "openai", "label": null, "model_id": "lfm3-1.7b", "tokenizer_id": "/models/LFM3-1.7B", "num_prompts": 128, "request_rate": "inf", "burstiness": 1.0, "max_concurrency": 16, "duration": 77.2350853659882, "completed": 128, "failed": 0, "total_input_tokens": 131072, "total_output_tokens": 32768, "request_throughput": 1.6572778989426353, "request_goodput": null, "output_throughput": 424.26314212931464, "total_token_throughput": 2121.3157106465733, "latencies": [10.037679993998609, 10.047345661994768, 10.042648675997043, 10.046023457995034, 10.04251428299176, 10.044332826000755, 10.044498019997263, 10.044862045993796, 10.04329628701089, 10.040232840998215, 10.0433536979981, 10.042256018990884, 10.042341560008936, 10.041676587992697, 10.037509930989472, 10.041362602001755, 9.819725743000163, 9.851629393000621, 9.850456070998916, 9.898166882005171, 10.22680056799436, 9.896311127988156, 9.942601371993078, 9.992322669990244, 9.992435912005021, 10.080986556000425, 10.080267333003576, 10.31128699699184, 10.133725549996598, 10.133678589001647, 10.223262081999565, 10.310411421989556, 9.695172035004362, 9.69489330999204, 9.69403112398868, 9.692679659012356, 9.739328219991876, 9.69348164400435, 9.702799065998988, 9.751829700995586, 9.663167815000634, 9.745581956012757, 9.748429528000997, 9.69287210200855, 9.657831926000654, 9.744790930999443, 9.748869016999379, 9.658696481987135, 9.09198084200034, 9.09024959000817, 9.090810890003922, 9.089309831993887, 9.088061798000126, 9.088049258003593, 9.07955851200677, 9.086438208003528, 9.086374677994172, 9.171062621011515, 9.090526054991642, 9.177627921992098, 9.11450112699822, 9.091543343005469, 9.146814382998855, 9.056383404007647, 9.35729738799273, 9.359884927005623, 9.359544130013091, 9.362176348004141, 9.363507323985687, 9.364591314006248, 9.360881835993496, 9.360209684004076, 9.361369545003981, 9.359132753001177, 9.336881793002249, 9.33724495000206, 9.416287938001915, 9.359542031001183, 9.448080015004962, 9.360055430995999, 9.49209607699595, 9.49046842601092, 9.49058098900423, 9.490552379007568, 9.495295565997367, 9.493375650010421, 9.497682350003743, 9.494779895991087, 9.493577893998008, 9.491322892004973, 9.491380613995716, 9.490446476003854, 9.492138738001813, 9.491470705004758, 9.49212417700619, 9.492996083004982, 9.739734079004847, 9.740669616003288, 9.740388341000653, 9.740971631006687, 9.740540972998133, 9.739231278988882, 9.739642025990179, 9.740138615990872, 9.739007923999452, 9.741430779991788, 9.741265535994899, 9.740432149992557, 9.741230084997369, 9.741979389000335, 9.740470631004428, 9.74036435999733, 9.657889616995817, 9.658524547994602, 9.657091761997435, 9.647557876000064, 9.634829611008172, 9.63504810500308, 9.623564595007338, 9.607944175993907, 9.606947948006564, 9.560442518995842, 9.5422856350051, 9.542292154990719, 9.492329492000863, 9.472289781988366, 9.472220191004453, 9.38522882500547], "queue_times": [0.0009688880090834573, 0.0011502209963509813, 0.0020920090028084815, 0.0022011200053384528, 0.0023099920072127134, 0.003311031003249809, 0.0034339930134592578, 0.003519025005516596, 0.004542094000498764, 0.0046261449897428975, 0.004720236989669502, 0.0057252350088674575, 0.005898998002521694, 0.006002680005622096, 0.006992299007833935, 0.007101850991602987, 10.039637580994167, 10.045481727007427, 10.045763873000396, 10.047022136001033, 10.047288230998674, 10.048560044000624, 10.048813689005328, 10.049014882999472, 10.049193975995877, 10.049373319008737, 10.04954734200146, 10.049733116000425, 10.049923079001019, 10.05008797199116, 10.050260935997358, 10.0504033180041, 19.860071746996255, 19.896564000009676, 19.89756470899738, 19.94549003399152, 19.94585339000332, 19.992023081998923, 20.04187517199898, 20.04224611900281, 20.130546608997975, 20.130868024993106, 20.183958135006833, 20.184238970992737, 20.274160209999536, 20.274516287012375, 20.361046122998232, 20.36132754900609, 29.555657859003986, 29.592217543991865, 29.592547940992517, 29.63848804900772, 29.68578110198723, 29.686101546991267, 29.745063094989746, 29.79412022100587, 29.79440183599945, 29.876595662994077, 29.87735573700047, 29.932481035008095, 29.932800930997473, 30.01945067998895, 30.0200505219982, 30.110172685002908, 38.64798006800993, 38.68279120999796, 38.684216026988, 38.72803326600115, 38.77433807001216, 38.77469594600552, 38.82533595000859, 38.88104820800072, 38.88133673398988, 38.96861122499104, 39.04761857300764, 39.04794474899245, 39.110427082996466, 39.110925572007545, 39.16682666398992, 39.16715414999635, 48.006107622000854, 48.043158025000594, 48.04436293699837, 48.090689032003866, 48.13860153699352, 48.13950915398891, 48.186640953994356, 48.24208326700318, 48.242758859996684, 48.32824472799257, 48.38525161000143, 48.385692748997826, 48.470628005001345, 48.52728742099134, 48.527598696993664, 48.61502528098936, 57.498982581993914, 57.534124051002436, 57.53530122300435, 57.58181622199481, 57.633991424998385, 57.63432Line truncated
|
||||
@@ -0,0 +1,477 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>BetterBench — lfm3-1.7b</title>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--page:#f9f9f7; --surface:#fcfcfb;
|
||||
--ink:#0b0b0b; --ink-2:#52514e; --muted:#898781;
|
||||
--grid:#e1e0d9; --axis:#c3c2b7; --border:rgba(11,11,11,0.10);
|
||||
--s1:#2a78d6; --s2:#eb6834;
|
||||
--s1-mid:#86b6ef; --s1-soft:rgba(42,120,214,0.13);
|
||||
--tip-bg:#ffffff;
|
||||
--sans:system-ui,-apple-system,"Segoe UI",sans-serif;
|
||||
--mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,monospace;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-theme="light"]) {
|
||||
color-scheme: dark;
|
||||
--page:#0d0d0d; --surface:#1a1a19;
|
||||
--ink:#ffffff; --ink-2:#c3c2b7; --muted:#898781;
|
||||
--grid:#2c2c2a; --axis:#383835; --border:rgba(255,255,255,0.10);
|
||||
--s1:#3987e5; --s2:#d95926;
|
||||
--s1-mid:#256abf; --s1-soft:rgba(57,135,229,0.16);
|
||||
--tip-bg:#232322;
|
||||
}
|
||||
}
|
||||
:root[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
--page:#0d0d0d; --surface:#1a1a19;
|
||||
--ink:#ffffff; --ink-2:#c3c2b7; --muted:#898781;
|
||||
--grid:#2c2c2a; --axis:#383835; --border:rgba(255,255,255,0.10);
|
||||
--s1:#3987e5; --s2:#d95926;
|
||||
--s1-mid:#256abf; --s1-soft:rgba(57,135,229,0.16);
|
||||
--tip-bg:#232322;
|
||||
}
|
||||
|
||||
* { box-sizing:border-box; }
|
||||
body { background:var(--page); color:var(--ink); font-family:var(--sans);
|
||||
line-height:1.55; margin:0; padding:32px 20px 72px; }
|
||||
.wrap { max-width:1080px; margin:0 auto; display:flex; flex-direction:column; gap:26px; }
|
||||
|
||||
header { display:flex; flex-direction:column; gap:13px; }
|
||||
.eyebrow { font-family:var(--mono); font-size:11px; letter-spacing:.13em;
|
||||
text-transform:uppercase; color:var(--muted); }
|
||||
h1 { font-size:clamp(26px,4vw,36px); line-height:1.12; margin:0;
|
||||
letter-spacing:-.02em; text-wrap:balance; }
|
||||
.runbar { display:flex; flex-wrap:wrap; gap:8px; }
|
||||
.chip { font-family:var(--mono); font-size:12px; color:var(--ink-2);
|
||||
border:1px solid var(--border); border-radius:6px; padding:4px 9px;
|
||||
background:var(--surface); display:inline-flex; align-items:center; gap:7px; }
|
||||
.chip code { font-family:var(--mono); font-size:12px; }
|
||||
.swatch { width:9px; height:9px; border-radius:2px; flex:none; }
|
||||
|
||||
.thin { color:var(--muted); cursor:help; font-weight:400; padding-left:1px; }
|
||||
.tiles { display:grid; grid-template-columns:repeat(auto-fit,minmax(200px,1fr)); gap:13px; }
|
||||
.tile { background:var(--surface); border:1px solid var(--border); border-radius:10px;
|
||||
padding:15px 16px; display:flex; flex-direction:column; gap:4px; }
|
||||
.tile .label { font-family:var(--mono); font-size:10.5px; letter-spacing:.1em;
|
||||
text-transform:uppercase; color:var(--muted); }
|
||||
.tile .val { font-size:26px; font-weight:600; letter-spacing:-.02em; line-height:1.15; }
|
||||
.tile .val small { font-size:14px; font-weight:400; color:var(--ink-2); letter-spacing:0; }
|
||||
.tile .sub { font-family:var(--mono); font-size:11.5px; color:var(--muted); }
|
||||
|
||||
figure { margin:0; background:var(--surface); border:1px solid var(--border);
|
||||
border-radius:10px; padding:18px 18px 14px;
|
||||
display:flex; flex-direction:column; gap:2px; }
|
||||
figcaption { display:flex; flex-direction:column; gap:3px; margin-bottom:8px; }
|
||||
figcaption .t { font-size:15.5px; font-weight:600; letter-spacing:-.01em; }
|
||||
figcaption .d { font-size:13px; color:var(--ink-2); max-width:76ch; }
|
||||
.legend { display:flex; gap:16px; flex-wrap:wrap; margin:2px 0 10px; }
|
||||
.legend span { font-family:var(--mono); font-size:12px; color:var(--ink-2);
|
||||
display:inline-flex; align-items:center; gap:6px; }
|
||||
.chartbox { position:relative; width:100%; }
|
||||
.chartbox svg { display:block; width:100%; height:auto; overflow:visible; }
|
||||
.note { font-size:12.5px; color:var(--muted); margin:9px 0 0; }
|
||||
|
||||
text { font-family:var(--mono); }
|
||||
.tick { font-size:10.5px; fill:var(--muted); }
|
||||
.axtitle { font-size:10.5px; fill:var(--muted); letter-spacing:.08em; }
|
||||
.dlabel { font-size:11px; font-weight:600; }
|
||||
.gridline { stroke:var(--grid); stroke-width:1; }
|
||||
.baseline { stroke:var(--axis); stroke-width:1; }
|
||||
.refline { stroke:var(--muted); stroke-width:1; stroke-dasharray:4 4; }
|
||||
.cross { stroke:var(--axis); stroke-width:1; stroke-dasharray:3 3; }
|
||||
|
||||
.tip { position:absolute; pointer-events:none; opacity:0; transition:opacity .1s ease;
|
||||
z-index:5; background:var(--tip-bg); border:1px solid var(--border);
|
||||
border-radius:7px; padding:8px 10px; box-shadow:0 3px 14px rgba(0,0,0,.13);
|
||||
font-family:var(--mono); font-size:11.5px; color:var(--ink);
|
||||
white-space:nowrap; min-width:132px; }
|
||||
.tip .th { color:var(--muted); font-size:10px; letter-spacing:.08em;
|
||||
text-transform:uppercase; margin-bottom:5px; }
|
||||
.tip .row { display:flex; align-items:center; gap:10px; justify-content:space-between; }
|
||||
.tip .nm { display:inline-flex; align-items:center; gap:6px; color:var(--ink-2); }
|
||||
.tip b { font-weight:600; }
|
||||
|
||||
details { background:var(--surface); border:1px solid var(--border);
|
||||
border-radius:10px; padding:0 18px; }
|
||||
summary { cursor:pointer; padding:15px 0; font-size:14.5px; font-weight:600;
|
||||
list-style:none; display:flex; align-items:center; gap:9px; }
|
||||
summary::-webkit-details-marker { display:none; }
|
||||
summary::before { content:"\25B8"; color:var(--muted); font-family:var(--mono); }
|
||||
details[open] summary::before { content:"\25BE"; }
|
||||
summary:focus-visible { outline:2px solid var(--s1); outline-offset:3px; border-radius:4px; }
|
||||
.tscroll { overflow-x:auto; padding-bottom:14px; }
|
||||
table { border-collapse:collapse; width:100%; font-size:12.5px; font-family:var(--mono);
|
||||
font-variant-numeric:tabular-nums; margin-bottom:10px; }
|
||||
caption { text-align:left; font-family:var(--sans); font-size:13px; color:var(--ink-2);
|
||||
padding:10px 0 8px; }
|
||||
th, td { padding:6px 11px 6px 0; text-align:right; white-space:nowrap; }
|
||||
th:first-child, td:first-child { text-align:left; }
|
||||
thead th { color:var(--muted); font-weight:500; font-size:10.5px; letter-spacing:.07em;
|
||||
text-transform:uppercase; border-bottom:1px solid var(--axis); }
|
||||
tbody tr + tr td { border-top:1px solid var(--grid); }
|
||||
tbody td:first-child { color:var(--ink-2); }
|
||||
|
||||
footer { font-size:12.5px; color:var(--muted); border-top:1px solid var(--border);
|
||||
padding-top:16px; }
|
||||
footer code { font-family:var(--mono); font-size:12px; color:var(--ink-2); }
|
||||
noscript p { font-size:13px; color:var(--ink-2); }
|
||||
@media (prefers-reduced-motion: reduce) { * { transition:none !important; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<header>
|
||||
<div class="eyebrow">BetterBench 0.6.1 · 28 Oct 2026 · 20:25 · llm</div>
|
||||
<h1>lfm3-1.7b</h1>
|
||||
<div class="runbar"><span class="chip"><span class="swatch" style="background:var(--s1)"></span>lfm3-1.7b</span><span class="chip"><code>http://127.0.0.1:8000/v1</code></span><span class="chip">corpus v1.0</span><span class="chip">5 passes/cat</span><span class="chip">temp 0.7</span><span class="chip">cold prefix cache (nonce)</span><span class="chip">phases: decode, prefill</span><span class="chip">32,768 tok context</span><span class="chip"><span class="swatch" style="background:var(--s2)"></span>mode: compiled</span><span class="chip"><span class="swatch" style="background:var(--s2)"></span>image: lfm3-vllm-xpu</span><span class="chip"><span class="swatch" style="background:var(--s2)"></span>gpu: ArcProB65</span></div>
|
||||
</header>
|
||||
<section class="tiles">
|
||||
<div class="tile">
|
||||
<span class="label">Combined decode</span>
|
||||
<span class="val">128.4 <small>t/s</small></span>
|
||||
<span class="sub">weighted across categories</span>
|
||||
</div>
|
||||
<div class="tile">
|
||||
<span class="label">Combined update p99</span>
|
||||
<span class="val">8.6 <small>ms</small></span>
|
||||
<span class="sub">the stutter between stream updates</span>
|
||||
</div>
|
||||
<div class="tile">
|
||||
<span class="label">Combined TTFT p50</span>
|
||||
<span class="val">64 <small>ms</small></span>
|
||||
<span class="sub">single-stream, batch = 1</span>
|
||||
</div>
|
||||
<div class="tile">
|
||||
<span class="label">Prefill @ 32,000 tok</span>
|
||||
<span class="val">16,669 <small>t/s</small></span>
|
||||
<span class="sub">median prompt processing</span>
|
||||
</div>
|
||||
</section>
|
||||
<noscript><p>Charts need JavaScript — the full numbers are in the tables below.</p></noscript>
|
||||
<figure>
|
||||
<figcaption>
|
||||
<span class="t">Decode throughput by category</span>
|
||||
<span class="d">Median per-pass decode t/s at batch = 1, 5 passes per category. The dashed line is the weighted combined score.</span>
|
||||
</figcaption>
|
||||
|
||||
<div class="chartbox" id="cb-decode"></div>
|
||||
<p class="note">Hover a bar for its IQR and coefficient of variation — a high CV means the category's passes disagree, so read small differences there with care.</p>
|
||||
</figure>
|
||||
<figure>
|
||||
<figcaption>
|
||||
<span class="t">Stream-update gap by category</span>
|
||||
<span class="d">This server packs several tokens into one stream update, so there is no per-token latency to plot. These are the measured wall-clock gaps between updates: p50 is the typical rhythm, p99 the stutter. Lower is better.</span>
|
||||
</figcaption>
|
||||
<div class="legend"><span><span class="swatch" style="background:var(--s1)"></span>update p50</span><span><span class="swatch" style="background:var(--s2)"></span>update p99</span></div>
|
||||
<div class="chartbox" id="cb-itl"></div>
|
||||
<p class="note">Hover a bar for the tokens landing per update. p99 is an upper bound on any pause a reader feels; it is not comparable across servers that pack different numbers of tokens into an update.</p>
|
||||
</figure>
|
||||
<figure>
|
||||
<figcaption>
|
||||
<span class="t">Prompt processing throughput by depth</span>
|
||||
<span class="d">Median prefill t/s (prompt tokens ÷ TTFT) at increasing input depth, cold prefix cache. The band spans the 1% low to the 99% high.</span>
|
||||
</figcaption>
|
||||
|
||||
<div class="chartbox" id="cb-prefill"></div>
|
||||
<p class="note">Skipped depth 64,000 — deeper than the model's context window.</p>
|
||||
</figure>
|
||||
<details open>
|
||||
<summary>Full numbers</summary>
|
||||
<div class="tscroll">
|
||||
<table>
|
||||
<caption>Single-stream, batch = 1 · several tokens per stream update</caption>
|
||||
<thead><tr><th>category</th><th>passes</th><th>TTFT p50</th><th>TTFT p99</th><th>update p50 (ms)</th><th>update p99 (ms)</th><th>tok/update</th><th>decode med</th><th>±IQR</th><th>CV</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>chat</td><td>5</td><td>65.6</td><td>85.7<span class="thin" title="under-sampled percentile — see the note below the tables">†</span></td><td>7.8</td><td>9.2</td><td>1.00</td><td>129.1</td><td>1.0</td><td>0.5%</td></tr>
|
||||
<tr><td>code</td><td>5</td><td>63.3</td><td>66.0<span class="thin" title="under-sampled percentile — see the note below the tables">†</span></td><td>7.8</td><td>8.7</td><td>1.00</td><td>128.2</td><td>0.3</td><td>0.3%</td></tr>
|
||||
<tr><td>file edit</td><td>5</td><td>64.4</td><td>66.8<span class="thin" title="under-sampled percentile — see the note below the tables">†</span></td><td>7.8</td><td>8.5</td><td>1.00</td><td>128.3</td><td>0.5</td><td>0.3%</td></tr>
|
||||
<tr><td>json</td><td>5</td><td>66.0</td><td>66.7<span class="thin" title="under-sampled percentile — see the note below the tables">†</span></td><td>7.8</td><td>8.6</td><td>1.00</td><td>128.8</td><td>0.2</td><td>0.2%</td></tr>
|
||||
<tr><td>math</td><td>5</td><td>64.2</td><td>68.7<span class="thin" title="under-sampled percentile — see the note below the tables">†</span></td><td>7.8</td><td>8.6</td><td>1.00</td><td>128.4</td><td>0.1</td><td>0.5%</td></tr>
|
||||
<tr><td>prose</td><td>5</td><td>64.4</td><td>67.1<span class="thin" title="under-sampled percentile — see the note below the tables">†</span></td><td>7.8</td><td>8.5</td><td>1.00</td><td>128.4</td><td>0.7</td><td>0.5%</td></tr>
|
||||
<tr><td>reasoning</td><td>5</td><td>63.1</td><td>65.9<span class="thin" title="under-sampled percentile — see the note below the tables">†</span></td><td>7.8</td><td>8.6</td><td>1.00</td><td>128.3</td><td>0.2</td><td>0.5%</td></tr>
|
||||
<tr><td>summarization</td><td>5</td><td>65.1</td><td>70.2<span class="thin" title="under-sampled percentile — see the note below the tables">†</span></td><td>7.8</td><td>8.9</td><td>1.00</td><td>128.8</td><td>0.7</td><td>0.6%</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<table>
|
||||
<caption>Reasoning / answer split · TTFA is time to the first answer token</caption>
|
||||
<thead><tr><th>category</th><th>runs w/ split</th><th>reasoning share (est)</th><th>TTFA p50 (ms)</th><th>never reached answer</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>chat</td><td>5/5</td><td>100%</td><td>—</td><td>5/5</td></tr>
|
||||
<tr><td>code</td><td>5/5</td><td>100%</td><td>—</td><td>5/5</td></tr>
|
||||
<tr><td>file edit</td><td>5/5</td><td>100%</td><td>—</td><td>5/5</td></tr>
|
||||
<tr><td>json</td><td>5/5</td><td>100%</td><td>—</td><td>5/5</td></tr>
|
||||
<tr><td>math</td><td>5/5</td><td>100%</td><td>—</td><td>5/5</td></tr>
|
||||
<tr><td>prose</td><td>5/5</td><td>100%</td><td>—</td><td>5/5</td></tr>
|
||||
<tr><td>reasoning</td><td>5/5</td><td>100%</td><td>—</td><td>5/5</td></tr>
|
||||
<tr><td>summarization</td><td>5/5</td><td>94%</td><td>—</td><td>4/5</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<table>
|
||||
<caption>Prefill sweep · cold prefix cache</caption>
|
||||
<thead><tr><th>target depth</th><th>prompt tok med</th><th>TTFT p50</th><th>PP 1% low</th><th>PP median</th><th>PP 99% high</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><td>2,000</td><td>1,514</td><td>99.6</td><td>14,967.3<span class="thin" title="under-sampled percentile — see the note below the tables">†</span></td><td>15,216.7</td><td>15,620.9<span class="thin" title="under-sampled percentile — see the note below the tables">†</span></td></tr>
|
||||
<tr><td>8,000</td><td>5,942</td><td>323.3</td><td>17,542.5<span class="thin" title="under-sampled percentile — see the note below the tables">†</span></td><td>18,374.0</td><td>18,928.7<span class="thin" title="under-sampled percentile — see the note below the tables">†</span></td></tr>
|
||||
<tr><td>16,000</td><td>11,826</td><td>654.5</td><td>17,890.5<span class="thin" title="under-sampled percentile — see the note below the tables">†</span></td><td>18,039.5</td><td>18,178.4<span class="thin" title="under-sampled percentile — see the note below the tables">†</span></td></tr>
|
||||
<tr><td>32,000</td><td>23,483</td><td>1,410.7</td><td>16,530.0<span class="thin" title="under-sampled percentile — see the note below the tables">†</span></td><td>16,668.7</td><td>16,916.9<span class="thin" title="under-sampled percentile — see the note below the tables">†</span></td></tr>
|
||||
<tr><td>64,000</td><td>—</td><td>—</td><td>—</td><td><em>skipped</em></td><td>—</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
<footer>Generated by BetterBench 0.6.1 from a corpus v1.0 run. Corpus hash <code>e332dceff176d033</code>. Combined-score weights — code 0.3, reasoning 0.2, prose 0.15, json 0.15, file_edit 0.1, summarization 0.1. Results are only comparable within a corpus version. Stopped at <code>max_tokens</code>: 40/40 runs (100%) — on a thinking model a truncated run measures the thinking phase, not a complete answer. 12 percentiles are marked † — they rest on fewer samples than <code>n · tail ≥ 5</code> requires (a p99 needs 500 observations), so read them as roughly the worst observed rather than as percentiles. The full list is under <code>sample_gate</code> in the results JSON. See METHODOLOGY.md §sample-size.</footer>
|
||||
</div>
|
||||
<script>
|
||||
"use strict";
|
||||
const D = {"cats": ["chat", "code", "file edit", "json", "math", "prose", "reasoning", "summarization"], "runs": [5, 5, 5, 5, 5, 5, 5, 5], "decode": [129.1022094889762, 128.20586903450126, 128.27160738301583, 128.7563251894094, 128.43350162812965, 128.3603652298855, 128.260559074168, 128.78242044790713], "decodeIqr": [0.9622115679498222, 0.27767102012848, 0.5303135223506672, 0.18086854072424785, 0.1302792179498624, 0.6889946257768429, 0.17555216564028342, 0.7370915278986558], "cv": [0.5486138592553561, 0.28243353919962855, 0.2705437309818874, 0.1809890685367367, 0.5015605785857459, 0.4923685049374124, 0.5113383522634769, 0.5999805074557256], "itlLow": [89.68902689812728, 97.29522795106024, 107.1639559004361, 110.80638232744374, 110.58896372024117, 114.41943924383007, null, 98.34935783233226], "itlMed": [128.75623793966716, 128.19273624690445, 128.33948984907119, 128.57479712418947, 128.19142161756133, 127.99811580570561, null, 128.5581854111411], "itlHigh": [153.06707225690204, 139.54087752642363, 143.73629532176653, 142.1806915943158, 141.3116808750854, 139.84270315385325, null, 142.84997747971164], "batched": true, "updP50": [7.7666139986831695, 7.800753999617882, 7.791833995725028, 7.777574006468058, 7.80083399877185, 7.81261500378605, 7.800839499395806, 7.778578998113517], "updP99": [9.198224745632569, 8.658754332573153, 8.499166404362768, 8.62729036656674, 8.635548493039094, 8.548644593975041, 8.582369999785442, 8.86844227163237], "tokPerUpd": [1.0, 1.0027662517289073, 1.0, 1.0, 1.0004133939644482, 1.0, 1.0010921004732436, 1.001001001001001], "ttft50": [65.56155199359637, 63.3239210001193, 64.42116099060513, 65.95237800502218, 64.22961800126359, 64.3917099951068, 63.123996995273046, 65.14582499221433], "combined": 128.38677887117052, "conc": {"levels": [], "agg": [], "t50": [], "t99": [], "per": [], "ok": [], "req": []}, "pre": {"depths": [2000, 8000, 16000, 32000], "tok": [1514.5, 5942.5, 11826.5, 23483.0], "low": [14967.264327369743, 17542.504602850448, 17890.486533017476, 16529.964484651147], "med": [15216.696838477137, 18373.994732786254, 18039.463362339164, 16668.651884913594], "high": [15620.857721748442, 18928.675799767832, 18178.394562377693, 16916.875352379036], "t50": [99.58000150072621, 323.31633850117214, 654.478692500561, 1410.7479969970882]}};
|
||||
const NS = "http://www.w3.org/2000/svg";
|
||||
const el = (n, a) => { const e = document.createElementNS(NS, n);
|
||||
for (const k in a) e.setAttribute(k, a[k]); return e; };
|
||||
const fmt = (v, d) => (v === null || v === undefined) ? "—"
|
||||
: v.toLocaleString("en-US", { minimumFractionDigits: d, maximumFractionDigits: d });
|
||||
const has = v => v !== null && v !== undefined;
|
||||
const maxOf = arrs => Math.max(...arrs.flat().filter(has));
|
||||
const niceTop = v => { if (!(v > 0)) return 1;
|
||||
const p = Math.pow(10, Math.floor(Math.log10(v)) - 1);
|
||||
return Math.ceil(v / (2 * p)) * 2 * p; };
|
||||
const box = id => document.getElementById(id);
|
||||
|
||||
function mkTip(b) { const t = document.createElement("div"); t.className = "tip";
|
||||
b.appendChild(t); return t; }
|
||||
function showTip(tip, b, x, y, html) {
|
||||
tip.innerHTML = html; tip.style.opacity = "1";
|
||||
let left = x + 14;
|
||||
if (left + tip.offsetWidth > b.clientWidth) left = x - tip.offsetWidth - 14;
|
||||
tip.style.left = Math.max(0, left) + "px";
|
||||
tip.style.top = Math.max(0, y - tip.offsetHeight - 10) + "px";
|
||||
}
|
||||
const row = (color, name, val) =>
|
||||
`<div class="row"><span class="nm">${color
|
||||
? `<span class="swatch" style="background:${color}"></span>` : ""}${name}</span><b>${val}</b></div>`;
|
||||
|
||||
function frame(svg, M, iw, ih, yMin, yMax, yTitle, ticks) {
|
||||
for (let k = 0; k <= (ticks || 4); k++) {
|
||||
const v = yMin + ((yMax - yMin) * k) / (ticks || 4);
|
||||
const y = M.t + ih - (ih * (v - yMin)) / (yMax - yMin);
|
||||
svg.appendChild(el("line", { x1: M.l, x2: M.l + iw, y1: y, y2: y, class: "gridline" }));
|
||||
const tx = el("text", { x: M.l - 10, y: y + 3.5, class: "tick", "text-anchor": "end" });
|
||||
tx.textContent = fmt(v, v < 10 ? 1 : 0); svg.appendChild(tx);
|
||||
}
|
||||
svg.appendChild(el("line", { x1: M.l, x2: M.l + iw, y1: M.t + ih, y2: M.t + ih, class: "baseline" }));
|
||||
const ay = el("text", { x: M.l, y: M.t - 7, class: "axtitle" });
|
||||
ay.textContent = yTitle; svg.appendChild(ay);
|
||||
}
|
||||
function xLabels(svg, labels, X, y) {
|
||||
labels.forEach((lab, i) => {
|
||||
const t = el("text", { x: X(i), y: y, class: "tick", "text-anchor": "middle" });
|
||||
t.textContent = lab; svg.appendChild(t);
|
||||
});
|
||||
}
|
||||
|
||||
/* --- grouped / single bars, zero-based --- */
|
||||
function bars(id, o) {
|
||||
const b = box(id); if (!b) return;
|
||||
const W = 900, H = o.height || 340, M = { t: 20, r: 16, b: 50, l: 64 };
|
||||
const iw = W - M.l - M.r, ih = H - M.t - M.b;
|
||||
const svg = el("svg", { viewBox: `0 0 ${W} ${H}`, role: "img", "aria-label": o.aria });
|
||||
const n = o.x.length, yMax = o.yMax;
|
||||
const Y = v => M.t + ih - (ih * v) / yMax;
|
||||
frame(svg, M, iw, ih, 0, yMax, o.yTitle);
|
||||
const band = iw / n, ns = o.series.length, GAP = 2;
|
||||
const bw = Math.min(40, (band - 24 - GAP * (ns - 1)) / ns);
|
||||
xLabels(svg, o.x, i => M.l + band * i + band / 2, M.t + ih + 20);
|
||||
if (has(o.ref)) {
|
||||
const y = Y(o.ref);
|
||||
svg.appendChild(el("line", { x1: M.l, x2: M.l + iw, y1: y, y2: y, class: "refline" }));
|
||||
const t = el("text", { x: M.l + iw, y: y - 6, class: "tick", "text-anchor": "end" });
|
||||
t.textContent = o.refLabel; svg.appendChild(t);
|
||||
}
|
||||
const tip = mkTip(b);
|
||||
o.x.forEach((lab, i) => {
|
||||
const cx = M.l + band * i + band / 2;
|
||||
const start = cx - (ns * bw + (ns - 1) * GAP) / 2;
|
||||
o.series.forEach((s, si) => {
|
||||
const v = s.v[i]; if (!has(v)) return;
|
||||
const x = start + si * (bw + GAP);
|
||||
const r = el("rect", { x: x, y: Y(v), width: bw, height: Math.max(2, ih - (Y(v) - M.t)),
|
||||
rx: 4, ry: 4, fill: s.color });
|
||||
r.style.cursor = "crosshair";
|
||||
const html = `<div class="th">${lab}</div>` +
|
||||
o.series.map(q => row(ns > 1 ? q.color : null, q.name, o.tipVal(q.v[i]))).join("") +
|
||||
(o.extra ? o.extra(i) : "");
|
||||
r.addEventListener("pointerenter", () => {
|
||||
const rc = svg.getBoundingClientRect();
|
||||
showTip(tip, b, ((x + bw / 2) / W) * rc.width, (Y(v) / H) * rc.height, html);
|
||||
});
|
||||
r.addEventListener("pointerleave", () => { tip.style.opacity = "0"; });
|
||||
svg.appendChild(r);
|
||||
});
|
||||
});
|
||||
b.appendChild(svg);
|
||||
}
|
||||
|
||||
/* --- floating range bars with a median tick --- */
|
||||
function rangeBars(id, o) {
|
||||
const b = box(id); if (!b) return;
|
||||
const W = 900, H = 340, M = { t: 20, r: 16, b: 50, l: 64 };
|
||||
const iw = W - M.l - M.r, ih = H - M.t - M.b;
|
||||
const svg = el("svg", { viewBox: `0 0 ${W} ${H}`, role: "img", "aria-label": o.aria });
|
||||
const n = o.x.length, yMax = o.yMax;
|
||||
const Y = v => M.t + ih - (ih * v) / yMax;
|
||||
frame(svg, M, iw, ih, 0, yMax, o.yTitle);
|
||||
const band = iw / n, bw = Math.min(34, band - 26);
|
||||
xLabels(svg, o.x, i => M.l + band * i + band / 2, M.t + ih + 20);
|
||||
const tip = mkTip(b);
|
||||
o.x.forEach((lab, i) => {
|
||||
const lo = o.low[i], hi = o.high[i], md = o.med[i];
|
||||
if (!has(lo) || !has(hi)) return;
|
||||
const cx = M.l + band * i + band / 2, x = cx - bw / 2;
|
||||
const r = el("rect", { x: x, y: Y(hi), width: bw, height: Math.max(3, Y(lo) - Y(hi)),
|
||||
rx: 4, ry: 4, fill: "var(--s1-mid)" });
|
||||
r.style.cursor = "crosshair";
|
||||
svg.appendChild(r);
|
||||
if (has(md)) svg.appendChild(el("line", { x1: x, x2: x + bw, y1: Y(md), y2: Y(md),
|
||||
stroke: "var(--ink)", "stroke-width": 2 }));
|
||||
const html = `<div class="th">${lab}</div>` +
|
||||
row(null, "99% high", o.tipVal(hi)) + row(null, "median", o.tipVal(md)) +
|
||||
row(null, "1% low", o.tipVal(lo)) + (o.extra ? o.extra(i) : "");
|
||||
r.addEventListener("pointerenter", () => {
|
||||
const rc = svg.getBoundingClientRect();
|
||||
showTip(tip, b, (cx / W) * rc.width, (Y(hi) / H) * rc.height, html);
|
||||
});
|
||||
r.addEventListener("pointerleave", () => { tip.style.opacity = "0"; });
|
||||
});
|
||||
b.appendChild(svg);
|
||||
}
|
||||
|
||||
/* --- line chart with optional band --- */
|
||||
function line(id, o) {
|
||||
const b = box(id); if (!b) return;
|
||||
const W = 900, H = 320, M = { t: 20, r: 24, b: 52, l: 64 };
|
||||
const iw = W - M.l - M.r, ih = H - M.t - M.b;
|
||||
const svg = el("svg", { viewBox: `0 0 ${W} ${H}`, role: "img", "aria-label": o.aria });
|
||||
const n = o.x.length, yMin = o.yMin, yMax = o.yMax;
|
||||
const X = i => M.l + (n === 1 ? iw / 2 : (iw * i) / (n - 1));
|
||||
const Y = v => M.t + ih - (ih * (v - yMin)) / (yMax - yMin);
|
||||
frame(svg, M, iw, ih, yMin, yMax, o.yTitle);
|
||||
xLabels(svg, o.x, X, M.t + ih + 20);
|
||||
if (o.xTitle) {
|
||||
const t = el("text", { x: M.l, y: H - 8, class: "axtitle" });
|
||||
t.textContent = o.xTitle; svg.appendChild(t);
|
||||
}
|
||||
if (o.band && o.band.low.every(has) && o.band.high.every(has)) {
|
||||
const up = o.band.high.map((v, i) => (i ? "L" : "M") + X(i) + " " + Y(v)).join(" ");
|
||||
const dn = o.band.low.map((v, i) => "L" + X(n - 1 - i) + " " + Y(o.band.low[n - 1 - i])).join(" ");
|
||||
svg.appendChild(el("path", { d: up + " " + dn + " Z", fill: "var(--s1-soft)", stroke: "none" }));
|
||||
}
|
||||
svg.appendChild(el("path", {
|
||||
d: o.v.map((v, i) => (i ? "L" : "M") + X(i) + " " + Y(v)).join(" "),
|
||||
fill: "none", stroke: "var(--s1)", "stroke-width": 2,
|
||||
"stroke-linejoin": "round", "stroke-linecap": "round" }));
|
||||
o.v.forEach((v, i) => svg.appendChild(el("circle", {
|
||||
cx: X(i), cy: Y(v), r: 5, fill: "var(--s1)", stroke: "var(--surface)", "stroke-width": 2 })));
|
||||
const cross = el("line", { class: "cross", y1: M.t, y2: M.t + ih, opacity: 0 });
|
||||
svg.appendChild(cross);
|
||||
const hit = el("rect", { x: M.l, y: M.t, width: iw, height: ih, fill: "transparent" });
|
||||
svg.appendChild(hit);
|
||||
b.appendChild(svg);
|
||||
const tip = mkTip(b);
|
||||
hit.addEventListener("pointermove", ev => {
|
||||
const rc = svg.getBoundingClientRect();
|
||||
const px = ((ev.clientX - rc.left) / rc.width) * W;
|
||||
let i = 0, best = Infinity;
|
||||
for (let k = 0; k < n; k++) { const d = Math.abs(X(k) - px); if (d < best) { best = d; i = k; } }
|
||||
cross.setAttribute("x1", X(i)); cross.setAttribute("x2", X(i)); cross.setAttribute("opacity", 1);
|
||||
showTip(tip, b, (X(i) / W) * rc.width, (Y(o.v[i]) / H) * rc.height,
|
||||
`<div class="th">${o.tipHead(i)}</div>` + o.tipBody(i));
|
||||
});
|
||||
hit.addEventListener("pointerleave", () => { tip.style.opacity = "0"; cross.setAttribute("opacity", 0); });
|
||||
}
|
||||
|
||||
/* ------------------------------ build ------------------------------ */
|
||||
if (D.cats.length) {
|
||||
bars("cb-decode", {
|
||||
aria: "Median decode throughput per category.",
|
||||
x: D.cats, yTitle: "DECODE T/S (MEDIAN)",
|
||||
yMax: niceTop(maxOf([D.decode])), height: 350,
|
||||
ref: D.combined, refLabel: "combined " + fmt(D.combined, 1),
|
||||
series: [{ name: "decode t/s", color: "var(--s1)", v: D.decode }],
|
||||
tipVal: v => fmt(v, 1) + " t/s",
|
||||
extra: i => row(null, "±IQR", fmt(D.decodeIqr[i], 1)) +
|
||||
row(null, "CV", fmt(D.cv[i], 1) + "%") +
|
||||
row(null, "passes", D.runs[i])
|
||||
});
|
||||
if (D.batched) {
|
||||
/* Grouped bars, not a floating range bar: p50 and p99 can differ by two
|
||||
orders of magnitude (a 17 ms rhythm against a 1.3 s stall), and a bar
|
||||
floating between them collapses the p50 end onto the axis. */
|
||||
bars("cb-itl", {
|
||||
aria: "Stream-update gap p50 and p99 by category.",
|
||||
x: D.cats, yTitle: "UPDATE GAP (MS)",
|
||||
yMax: niceTop(maxOf([D.updP99, D.updP50])), height: 320,
|
||||
series: [{ name: "p50", color: "var(--s1)", v: D.updP50 },
|
||||
{ name: "p99", color: "var(--s2)", v: D.updP99 }],
|
||||
tipVal: v => fmt(v, 1) + " ms",
|
||||
extra: i => row(null, "tok/update", fmt(D.tokPerUpd[i], 2)) +
|
||||
row(null, "passes", D.runs[i])
|
||||
});
|
||||
} else {
|
||||
rangeBars("cb-itl", {
|
||||
aria: "Inter-token latency range per category, 1% low to 99% high.",
|
||||
x: D.cats, yTitle: "INSTANTANEOUS T/S",
|
||||
yMax: niceTop(maxOf([D.itlHigh])),
|
||||
low: D.itlLow, med: D.itlMed, high: D.itlHigh,
|
||||
tipVal: v => fmt(v, 1) + " t/s",
|
||||
extra: i => row(null, "spread", has(D.itlHigh[i]) && has(D.itlLow[i])
|
||||
? fmt(D.itlHigh[i] - D.itlLow[i], 1) + " t/s" : "—")
|
||||
});
|
||||
}
|
||||
}
|
||||
if (D.conc.levels.length > 1) {
|
||||
line("cb-conc", {
|
||||
aria: "Aggregate throughput as concurrency rises.",
|
||||
x: D.conc.levels.map(String), xTitle: "CONCURRENCY LEVEL",
|
||||
yTitle: "AGGREGATE T/S", yMin: 0, yMax: niceTop(maxOf([D.conc.agg])),
|
||||
v: D.conc.agg,
|
||||
tipHead: i => "concurrency " + D.conc.levels[i] + " · " + D.conc.ok[i] + "/" + D.conc.req[i] + " ok",
|
||||
tipBody: i => row(null, "aggregate", fmt(D.conc.agg[i], 1) + " t/s") +
|
||||
row(null, "per-req", fmt(D.conc.per[i], 1) + " t/s") +
|
||||
row(null, "TTFT p50", fmt(D.conc.t50[i], 1) + " ms")
|
||||
});
|
||||
bars("cb-ttft", {
|
||||
aria: "TTFT p50 and p99 by concurrency level.",
|
||||
x: D.conc.levels.map(String), yTitle: "TTFT (MS)",
|
||||
yMax: niceTop(maxOf([D.conc.t99, D.conc.t50])), height: 300,
|
||||
series: [{ name: "p50", color: "var(--s1)", v: D.conc.t50 },
|
||||
{ name: "p99", color: "var(--s2)", v: D.conc.t99 }],
|
||||
tipVal: v => fmt(v, 1) + " ms",
|
||||
extra: i => row(null, "requests", D.conc.ok[i] + "/" + D.conc.req[i])
|
||||
});
|
||||
}
|
||||
if (D.pre.depths.length > 1) {
|
||||
const lo = Math.min(...D.pre.low.filter(has).concat(D.pre.med.filter(has)));
|
||||
const hi = Math.max(...D.pre.high.filter(has).concat(D.pre.med.filter(has)));
|
||||
const pad = (hi - lo) * 0.25 || hi * 0.1;
|
||||
line("cb-prefill", {
|
||||
aria: "Prefill throughput by input depth.",
|
||||
x: D.pre.depths.map(d => d >= 1000 ? (d / 1000) + "k" : String(d)),
|
||||
xTitle: "TARGET INPUT DEPTH (TOKENS)", yTitle: "PP T/S (MEDIAN)",
|
||||
yMin: Math.max(0, lo - pad), yMax: hi + pad,
|
||||
v: D.pre.med, band: { low: D.pre.low, high: D.pre.high },
|
||||
tipHead: i => D.pre.depths[i].toLocaleString() + " target · "
|
||||
+ fmt(D.pre.tok[i], 0) + " actual tok",
|
||||
tipBody: i => row(null, "99% high", fmt(D.pre.high[i], 1)) +
|
||||
row(null, "median", fmt(D.pre.med[i], 1)) +
|
||||
row(null, "1% low", fmt(D.pre.low[i], 1)) +
|
||||
row(null, "TTFT p50", fmt(D.pre.t50[i], 0) + " ms")
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,242 @@
|
||||
{
|
||||
"vllm_dtype": "bfloat16",
|
||||
"hf": {
|
||||
"float32": {
|
||||
"raw_short": {
|
||||
"positions": 68,
|
||||
"max_abs_logprob_diff_top5": 0.1926,
|
||||
"mean_abs_logprob_diff_top1": 0.00684,
|
||||
"top1_disagreement_margins": [],
|
||||
"max_diff_pos<=256": 0.1926,
|
||||
"max_diff_pos>256": 0.0,
|
||||
"top1_agreement": "68/68",
|
||||
"top5_overlap": 0.9765,
|
||||
"final_prompt_pos_diff": 0.118,
|
||||
"teacher_forced_greedy_mismatches": [],
|
||||
"hf_greedy_identical_prefix": "64/64"
|
||||
},
|
||||
"raw_code": {
|
||||
"positions": 76,
|
||||
"max_abs_logprob_diff_top5": 0.7259,
|
||||
"mean_abs_logprob_diff_top1": 0.01002,
|
||||
"top1_disagreement_margins": [
|
||||
0.017
|
||||
],
|
||||
"max_diff_pos<=256": 0.7259,
|
||||
"max_diff_pos>256": 0.0,
|
||||
"top1_agreement": "75/76",
|
||||
"top5_overlap": 0.9684,
|
||||
"final_prompt_pos_diff": 0.2729,
|
||||
"teacher_forced_greedy_mismatches": [
|
||||
[
|
||||
50,
|
||||
65296,
|
||||
71,
|
||||
0.0173
|
||||
]
|
||||
],
|
||||
"hf_greedy_identical_prefix": "50/64"
|
||||
},
|
||||
"chat_short": {
|
||||
"positions": 85,
|
||||
"max_abs_logprob_diff_top5": 0.3189,
|
||||
"mean_abs_logprob_diff_top1": 0.01081,
|
||||
"top1_disagreement_margins": [],
|
||||
"max_diff_pos<=256": 0.3189,
|
||||
"max_diff_pos>256": 0.0,
|
||||
"top1_agreement": "85/85",
|
||||
"top5_overlap": 0.9882,
|
||||
"final_prompt_pos_diff": 0.0791,
|
||||
"teacher_forced_greedy_mismatches": [],
|
||||
"hf_greedy_identical_prefix": "64/64"
|
||||
},
|
||||
"chat_long_600": {
|
||||
"positions": 653,
|
||||
"max_abs_logprob_diff_top5": 1.125,
|
||||
"mean_abs_logprob_diff_top1": 0.01713,
|
||||
"top1_disagreement_margins": [
|
||||
0.028,
|
||||
0.089,
|
||||
0.03,
|
||||
0.024,
|
||||
0.063,
|
||||
0.027,
|
||||
0.001,
|
||||
0.234
|
||||
],
|
||||
"max_diff_pos<=256": 0.4101,
|
||||
"max_diff_pos>256": 1.125,
|
||||
"top1_agreement": "645/653",
|
||||
"top5_overlap": 0.9783,
|
||||
"final_prompt_pos_diff": 0.1523,
|
||||
"teacher_forced_greedy_mismatches": [],
|
||||
"hf_greedy_identical_prefix": "64/64"
|
||||
},
|
||||
"raw_long_1500": {
|
||||
"positions": 1486,
|
||||
"max_abs_logprob_diff_top5": 0.3912,
|
||||
"mean_abs_logprob_diff_top1": 0.00403,
|
||||
"top1_disagreement_margins": [
|
||||
0.004,
|
||||
0.094,
|
||||
0.048,
|
||||
0.093,
|
||||
0.051,
|
||||
0.018,
|
||||
0.004,
|
||||
0.061,
|
||||
0.034,
|
||||
0.114,
|
||||
0.014
|
||||
],
|
||||
"max_diff_pos<=256": 0.314,
|
||||
"max_diff_pos>256": 0.3912,
|
||||
"top1_agreement": "1475/1486",
|
||||
"top5_overlap": 0.9786,
|
||||
"final_prompt_pos_diff": 0.0508,
|
||||
"teacher_forced_greedy_mismatches": [
|
||||
[
|
||||
28,
|
||||
5344,
|
||||
35197,
|
||||
0.0141
|
||||
]
|
||||
],
|
||||
"hf_greedy_identical_prefix": "28/64"
|
||||
}
|
||||
},
|
||||
"bfloat16": {
|
||||
"raw_short": {
|
||||
"noise_vs_hf_fp32_max_top5": 0.2851,
|
||||
"noise_vs_hf_fp32_mean_top1": 0.00859,
|
||||
"noise_vs_hf_fp32_top1_agree": "67/68",
|
||||
"positions": 68,
|
||||
"max_abs_logprob_diff_top5": 0.3124,
|
||||
"mean_abs_logprob_diff_top1": 0.00759,
|
||||
"top1_disagreement_margins": [],
|
||||
"max_diff_pos<=256": 0.3124,
|
||||
"max_diff_pos>256": 0.0,
|
||||
"top1_agreement": "68/68",
|
||||
"top5_overlap": 0.9647,
|
||||
"final_prompt_pos_diff": 0.1149,
|
||||
"teacher_forced_greedy_mismatches": [
|
||||
[
|
||||
39,
|
||||
10749,
|
||||
278,
|
||||
0.0
|
||||
]
|
||||
],
|
||||
"hf_greedy_identical_prefix": "47/64"
|
||||
},
|
||||
"raw_code": {
|
||||
"noise_vs_hf_fp32_max_top5": 0.4804,
|
||||
"noise_vs_hf_fp32_mean_top1": 0.00731,
|
||||
"noise_vs_hf_fp32_top1_agree": "75/76",
|
||||
"positions": 76,
|
||||
"max_abs_logprob_diff_top5": 0.6877,
|
||||
"mean_abs_logprob_diff_top1": 0.00953,
|
||||
"top1_disagreement_margins": [
|
||||
0.0,
|
||||
0.125
|
||||
],
|
||||
"max_diff_pos<=256": 0.6877,
|
||||
"max_diff_pos>256": 0.0,
|
||||
"top1_agreement": "74/76",
|
||||
"top5_overlap": 0.9737,
|
||||
"final_prompt_pos_diff": 0.1249,
|
||||
"teacher_forced_greedy_mismatches": [
|
||||
[
|
||||
50,
|
||||
65296,
|
||||
71,
|
||||
0.125
|
||||
]
|
||||
],
|
||||
"hf_greedy_identical_prefix": "50/64"
|
||||
},
|
||||
"chat_short": {
|
||||
"noise_vs_hf_fp32_max_top5": 0.3472,
|
||||
"noise_vs_hf_fp32_mean_top1": 0.01408,
|
||||
"noise_vs_hf_fp32_top1_agree": "85/85",
|
||||
"positions": 85,
|
||||
"max_abs_logprob_diff_top5": 0.408,
|
||||
"mean_abs_logprob_diff_top1": 0.01487,
|
||||
"top1_disagreement_margins": [
|
||||
0.0
|
||||
],
|
||||
"max_diff_pos<=256": 0.408,
|
||||
"max_diff_pos>256": 0.0,
|
||||
"top1_agreement": "84/85",
|
||||
"top5_overlap": 0.9812,
|
||||
"final_prompt_pos_diff": 0.125,
|
||||
"teacher_forced_greedy_mismatches": [],
|
||||
"hf_greedy_identical_prefix": "49/64"
|
||||
},
|
||||
"chat_long_600": {
|
||||
"noise_vs_hf_fp32_max_top5": 2.6357,
|
||||
"noise_vs_hf_fp32_mean_top1": 0.02041,
|
||||
"noise_vs_hf_fp32_top1_agree": "644/653",
|
||||
"positions": 653,
|
||||
"max_abs_logprob_diff_top5": 2.8686,
|
||||
"mean_abs_logprob_diff_top1": 0.02527,
|
||||
"top1_disagreement_margins": [
|
||||
0.0,
|
||||
0.125,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.125,
|
||||
0.0,
|
||||
0.0,
|
||||
0.125,
|
||||
0.0,
|
||||
0.125,
|
||||
0.0
|
||||
],
|
||||
"max_diff_pos<=256": 0.484,
|
||||
"max_diff_pos>256": 2.8686,
|
||||
"top1_agreement": "640/653",
|
||||
"top5_overlap": 0.9709,
|
||||
"final_prompt_pos_diff": 0.1975,
|
||||
"teacher_forced_greedy_mismatches": [],
|
||||
"hf_greedy_identical_prefix": "64/64"
|
||||
},
|
||||
"raw_long_1500": {
|
||||
"noise_vs_hf_fp32_max_top5": 0.4448,
|
||||
"noise_vs_hf_fp32_mean_top1": 0.00415,
|
||||
"noise_vs_hf_fp32_top1_agree": "1478/1486",
|
||||
"positions": 1486,
|
||||
"max_abs_logprob_diff_top5": 0.5,
|
||||
"mean_abs_logprob_diff_top1": 0.00469,
|
||||
"top1_disagreement_margins": [
|
||||
0.0,
|
||||
0.0,
|
||||
0.125,
|
||||
0.125,
|
||||
0.125,
|
||||
0.0,
|
||||
0.125,
|
||||
0.125,
|
||||
0.0,
|
||||
0.125
|
||||
],
|
||||
"max_diff_pos<=256": 0.4116,
|
||||
"max_diff_pos>256": 0.5,
|
||||
"top1_agreement": "1476/1486",
|
||||
"top5_overlap": 0.9717,
|
||||
"final_prompt_pos_diff": 0.1242,
|
||||
"teacher_forced_greedy_mismatches": [
|
||||
[
|
||||
28,
|
||||
5344,
|
||||
35197,
|
||||
0.125
|
||||
]
|
||||
],
|
||||
"hf_greedy_identical_prefix": "64/64"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"vllm_dtype": "float32",
|
||||
"hf": {
|
||||
"float32": {
|
||||
"raw_short": {
|
||||
"positions": 68,
|
||||
"max_abs_logprob_diff_top5": 0.0046,
|
||||
"mean_abs_logprob_diff_top1": 0.00013,
|
||||
"top1_disagreement_margins": [],
|
||||
"max_diff_pos<=256": 0.0046,
|
||||
"max_diff_pos>256": 0.0,
|
||||
"top1_agreement": "68/68",
|
||||
"top5_overlap": 1.0,
|
||||
"final_prompt_pos_diff": 0.0032,
|
||||
"teacher_forced_greedy_mismatches": [],
|
||||
"hf_greedy_identical_prefix": "64/64"
|
||||
},
|
||||
"raw_code": {
|
||||
"positions": 76,
|
||||
"max_abs_logprob_diff_top5": 0.0085,
|
||||
"mean_abs_logprob_diff_top1": 0.00014,
|
||||
"top1_disagreement_margins": [],
|
||||
"max_diff_pos<=256": 0.0085,
|
||||
"max_diff_pos>256": 0.0,
|
||||
"top1_agreement": "76/76",
|
||||
"top5_overlap": 0.9974,
|
||||
"final_prompt_pos_diff": 0.0011,
|
||||
"teacher_forced_greedy_mismatches": [],
|
||||
"hf_greedy_identical_prefix": "64/64"
|
||||
},
|
||||
"chat_short": {
|
||||
"positions": 85,
|
||||
"max_abs_logprob_diff_top5": 0.0128,
|
||||
"mean_abs_logprob_diff_top1": 0.00032,
|
||||
"top1_disagreement_margins": [],
|
||||
"max_diff_pos<=256": 0.0128,
|
||||
"max_diff_pos>256": 0.0,
|
||||
"top1_agreement": "85/85",
|
||||
"top5_overlap": 1.0,
|
||||
"final_prompt_pos_diff": 0.0024,
|
||||
"teacher_forced_greedy_mismatches": [],
|
||||
"hf_greedy_identical_prefix": "64/64"
|
||||
},
|
||||
"chat_long_600": {
|
||||
"positions": 653,
|
||||
"max_abs_logprob_diff_top5": 0.0572,
|
||||
"mean_abs_logprob_diff_top1": 0.00045,
|
||||
"top1_disagreement_margins": [
|
||||
0.002
|
||||
],
|
||||
"max_diff_pos<=256": 0.0211,
|
||||
"max_diff_pos>256": 0.0572,
|
||||
"top1_agreement": "652/653",
|
||||
"top5_overlap": 0.9994,
|
||||
"final_prompt_pos_diff": 0.002,
|
||||
"teacher_forced_greedy_mismatches": [],
|
||||
"hf_greedy_identical_prefix": "64/64"
|
||||
},
|
||||
"raw_long_1500": {
|
||||
"positions": 1486,
|
||||
"max_abs_logprob_diff_top5": 0.0137,
|
||||
"mean_abs_logprob_diff_top1": 9e-05,
|
||||
"top1_disagreement_margins": [],
|
||||
"max_diff_pos<=256": 0.0122,
|
||||
"max_diff_pos>256": 0.0137,
|
||||
"top1_agreement": "1486/1486",
|
||||
"top5_overlap": 0.9996,
|
||||
"final_prompt_pos_diff": 0.0025,
|
||||
"teacher_forced_greedy_mismatches": [],
|
||||
"hf_greedy_identical_prefix": "64/64"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
{
|
||||
"vllm_dtype": "float32",
|
||||
"hf": {
|
||||
"float32": {
|
||||
"raw_short": {
|
||||
"positions": 68,
|
||||
"max_abs_logprob_diff_top5": 0.0038,
|
||||
"mean_abs_logprob_diff_top1": 0.00014,
|
||||
"top1_disagreement_margins": [],
|
||||
"max_diff_pos<=256": 0.0038,
|
||||
"max_diff_pos>256": 0.0,
|
||||
"top1_agreement": "68/68",
|
||||
"top5_overlap": 1.0,
|
||||
"final_prompt_pos_diff": 0.0038,
|
||||
"teacher_forced_greedy_mismatches": [],
|
||||
"hf_greedy_identical_prefix": "64/64"
|
||||
},
|
||||
"raw_code": {
|
||||
"positions": 76,
|
||||
"max_abs_logprob_diff_top5": 0.0079,
|
||||
"mean_abs_logprob_diff_top1": 0.0001,
|
||||
"top1_disagreement_margins": [],
|
||||
"max_diff_pos<=256": 0.0079,
|
||||
"max_diff_pos>256": 0.0,
|
||||
"top1_agreement": "76/76",
|
||||
"top5_overlap": 1.0,
|
||||
"final_prompt_pos_diff": 0.001,
|
||||
"teacher_forced_greedy_mismatches": [],
|
||||
"hf_greedy_identical_prefix": "64/64"
|
||||
},
|
||||
"chat_short": {
|
||||
"positions": 85,
|
||||
"max_abs_logprob_diff_top5": 0.0104,
|
||||
"mean_abs_logprob_diff_top1": 0.00031,
|
||||
"top1_disagreement_margins": [],
|
||||
"max_diff_pos<=256": 0.0104,
|
||||
"max_diff_pos>256": 0.0,
|
||||
"top1_agreement": "85/85",
|
||||
"top5_overlap": 1.0,
|
||||
"final_prompt_pos_diff": 0.0037,
|
||||
"teacher_forced_greedy_mismatches": [],
|
||||
"hf_greedy_identical_prefix": "64/64"
|
||||
},
|
||||
"chat_long_600": {
|
||||
"positions": 653,
|
||||
"max_abs_logprob_diff_top5": 0.0693,
|
||||
"mean_abs_logprob_diff_top1": 0.00046,
|
||||
"top1_disagreement_margins": [],
|
||||
"max_diff_pos<=256": 0.0154,
|
||||
"max_diff_pos>256": 0.0693,
|
||||
"top1_agreement": "653/653",
|
||||
"top5_overlap": 0.9994,
|
||||
"final_prompt_pos_diff": 0.0025,
|
||||
"teacher_forced_greedy_mismatches": [],
|
||||
"hf_greedy_identical_prefix": "64/64"
|
||||
},
|
||||
"raw_long_1500": {
|
||||
"positions": 1486,
|
||||
"max_abs_logprob_diff_top5": 0.0124,
|
||||
"mean_abs_logprob_diff_top1": 8e-05,
|
||||
"top1_disagreement_margins": [],
|
||||
"max_diff_pos<=256": 0.0123,
|
||||
"max_diff_pos>256": 0.0124,
|
||||
"top1_agreement": "1486/1486",
|
||||
"top5_overlap": 0.9997,
|
||||
"final_prompt_pos_diff": 0.0022,
|
||||
"teacher_forced_greedy_mismatches": [],
|
||||
"hf_greedy_identical_prefix": "64/64"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+28
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env bash
|
||||
# Start LFM3-1.7B on vLLM (XPU) with the vllm_lfm3 plugin baked into lfm3-vllm-xpu.
|
||||
# ./run_server.sh # eager mode (default, validated)
|
||||
# EAGER=0 ./run_server.sh # torch.compile / XPU graphs
|
||||
# PORT=8000 NAME=lfm3-serve ./run_server.sh -d # extra args go to `docker run`
|
||||
set -euo pipefail
|
||||
PORT=${PORT:-8000}
|
||||
NAME=${NAME:-lfm3-serve}
|
||||
EAGER=${EAGER:-1}
|
||||
EXTRA_VLLM_ARGS=${EXTRA_VLLM_ARGS:-}
|
||||
[[ "$EAGER" == "1" ]] && EAGER_FLAG=--enforce-eager || EAGER_FLAG=
|
||||
|
||||
exec docker run --rm --name "$NAME" "$@" \
|
||||
--device /dev/dri -v /dev/dri/by-path:/dev/dri/by-path \
|
||||
--ipc=host --shm-size=16g \
|
||||
-p 127.0.0.1:${PORT}: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 \
|
||||
$EAGER_FLAG \
|
||||
--reasoning-parser qwen3 \
|
||||
--enable-auto-tool-choice --tool-call-parser qwen3_coder \
|
||||
--host 0.0.0.0 --port 8000 \
|
||||
$EXTRA_VLLM_ARGS
|
||||
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Quick prefill / decode benchmark against a running LFM3 server, via `vllm bench serve`.
|
||||
|
||||
Scenarios (each at concurrency 1 and 16):
|
||||
prefill : 4096 input tokens, 1 output token -> TTFT, prefill tok/s
|
||||
decode : 128 input tokens, 512 output tokens -> TPOT, decode tok/s
|
||||
mixed : 1024 in / 256 out (the classic serving shape; optional, --mixed)
|
||||
|
||||
python3 tests/bench.py --label eager # server on 127.0.0.1:8000
|
||||
-> results/bench_<label>.md (+ raw JSON per run in results/bench_<label>/)
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
IMAGE = "lfm3-vllm-xpu"
|
||||
|
||||
SCENARIOS = {
|
||||
# name: (input_len, output_len, {concurrency: num_prompts})
|
||||
"prefill": (4096, 1, {1: 8, 16: 64}),
|
||||
"decode": (128, 512, {1: 4, 16: 32}),
|
||||
"mixed": (1024, 256, {1: 8, 16: 64}),
|
||||
}
|
||||
|
||||
|
||||
def prefix_cache_hits(base_url):
|
||||
text = urllib.request.urlopen(base_url + "/metrics").read().decode()
|
||||
return sum(float(l.split()[-1]) for l in text.splitlines() if l.startswith("vllm:prefix_cache_hits_total"))
|
||||
|
||||
|
||||
def run(label, scenario, conc, base_url):
|
||||
inp, out, nprompts = SCENARIOS[scenario]
|
||||
rdir = os.path.join(ROOT, "results", f"bench_{label}")
|
||||
os.makedirs(rdir, exist_ok=True)
|
||||
fname = f"{scenario}_c{conc}.json"
|
||||
cmd = [
|
||||
"docker", "run", "--rm", "--name", "lfm3-bench", "--network", "host",
|
||||
"-v", "/models/LFM3-1.7B:/models/LFM3-1.7B:ro", "-v", f"{rdir}:/results",
|
||||
"--entrypoint", "vllm", IMAGE, "bench", "serve",
|
||||
"--backend", "openai", "--base-url", base_url, "--model", "lfm3-1.7b",
|
||||
"--tokenizer", "/models/LFM3-1.7B", "--dataset-name", "random",
|
||||
"--random-input-len", str(inp), "--random-output-len", str(out), "--ignore-eos",
|
||||
"--num-prompts", str(nprompts[conc]), "--max-concurrency", str(conc),
|
||||
# fresh seed per run: identical random prompts would be served from the prefix cache
|
||||
"--seed", str(time.time_ns() % 2**31), "--save-result", "--result-dir", "/results", "--result-filename", fname,
|
||||
]
|
||||
t0, hits0 = time.time(), prefix_cache_hits(base_url)
|
||||
p = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if p.returncode != 0:
|
||||
sys.exit(f"bench failed ({scenario} c={conc}):\n{p.stdout[-2000:]}\n{p.stderr[-2000:]}")
|
||||
r = json.load(open(os.path.join(rdir, fname)))
|
||||
r["_wall"] = time.time() - t0
|
||||
r["_cache_hit_frac"] = (prefix_cache_hits(base_url) - hits0) / max(1, r["total_input_tokens"])
|
||||
return r
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--label", required=True, help="e.g. eager, compiled")
|
||||
ap.add_argument("--base-url", default="http://127.0.0.1:8000")
|
||||
ap.add_argument("--mixed", action="store_true", help="also run 1024/256 mixed")
|
||||
ap.add_argument("--only", choices=list(SCENARIOS), help="run a single scenario")
|
||||
a = ap.parse_args()
|
||||
|
||||
# warm up (first requests after server start JIT-compile the Triton conv kernels)
|
||||
for n_tok in (1024, 4096):
|
||||
req = urllib.request.Request(
|
||||
a.base_url + "/v1/completions",
|
||||
json.dumps({"model": "lfm3-1.7b", "prompt": "hello " * n_tok, "max_tokens": 8}).encode(),
|
||||
{"Content-Type": "application/json"},
|
||||
)
|
||||
urllib.request.urlopen(req, timeout=300).read()
|
||||
|
||||
scen = [a.only] if a.only else ["prefill", "decode"] + (["mixed"] if a.mixed else [])
|
||||
rows = []
|
||||
for s in scen:
|
||||
for c in (1, 16):
|
||||
r = run(a.label, s, c, a.base_url)
|
||||
inp, out, _ = SCENARIOS[s]
|
||||
rows.append((s, c, inp, out, r))
|
||||
print(f"{s:<8} c={c:<3} TTFT {r['median_ttft_ms']:8.1f} ms TPOT {r['median_tpot_ms']:6.2f} ms "
|
||||
f"in {r['total_input_tokens'] / r['duration']:8.0f} tok/s out {r['output_throughput']:7.1f} tok/s "
|
||||
f"cache-hits {100 * r['_cache_hit_frac']:.1f}%")
|
||||
|
||||
md = [
|
||||
f"# LFM3-1.7B bench — {a.label} ({time.strftime('%Y-%m-%d %H:%M')})",
|
||||
"",
|
||||
"Server: lfm3-vllm-xpu, Arc Pro B65, bf16, `vllm bench serve` random dataset, `--ignore-eos`.",
|
||||
"",
|
||||
"| scenario | conc | in/out | requests | median TTFT ms | P99 TTFT ms | median TPOT ms | P99 ITL ms | prefill tok/s | decode tok/s | total tok/s | prefix-cache hits |",
|
||||
"|---|---|---|---|---|---|---|---|---|---|---|---|",
|
||||
]
|
||||
for s, c, inp, out, r in rows:
|
||||
md.append(
|
||||
f"| {s} | {c} | {inp}/{out} | {r['completed']} | {r['median_ttft_ms']:.1f} | {r['p99_ttft_ms']:.1f} | "
|
||||
f"{r['median_tpot_ms']:.2f} | {r['p99_itl_ms']:.2f} | {r['total_input_tokens'] / r['duration']:.0f} | "
|
||||
f"{r['output_throughput']:.1f} | {r['total_token_throughput']:.0f} | {100 * r['_cache_hit_frac']:.1f}% |"
|
||||
)
|
||||
md += [
|
||||
"",
|
||||
"- prefill tok/s = input tokens / duration (meaningful for the prefill rows: 1 output token).",
|
||||
"- decode tok/s = output tokens / duration (meaningful for the decode rows).",
|
||||
f"- raw JSON: results/bench_{a.label}/",
|
||||
]
|
||||
path = os.path.join(ROOT, "results", f"bench_{a.label}.md")
|
||||
open(path, "w").write("\n".join(md) + "\n")
|
||||
print(f"\n-> {path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Greedy-decode the ref_compare prompts on a running server and compare with a saved
|
||||
ref_compare vLLM run (default: results/vllm_bf16.json, eager mode). repetition_penalty is
|
||||
forced to 1.0: vLLM serve otherwise applies generation_config.json (1.1) as default.
|
||||
|
||||
python3 tests/compare_greedy_server.py [results/vllm_bf16.json] [--concurrent]
|
||||
"""
|
||||
import json, sys, urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
path = next((a for a in sys.argv[1:] if a.endswith(".json")), "results/vllm_bf16.json")
|
||||
ref = json.load(open(path))["results"]
|
||||
|
||||
def gen(item):
|
||||
name, r = item
|
||||
body = {"model": "lfm3-1.7b", "prompt": r["prompt_ids"], "max_tokens": len(r["gen_ids"]),
|
||||
"temperature": 0.0, "repetition_penalty": 1.0, "ignore_eos": True, "logprobs": 1, "return_tokens_as_token_ids": True}
|
||||
req = urllib.request.Request("http://127.0.0.1:8000/v1/completions", json.dumps(body).encode(),
|
||||
{"Content-Type": "application/json"})
|
||||
out = json.loads(urllib.request.urlopen(req, timeout=300).read())
|
||||
toks = [int(t.split(":")[1]) for t in out["choices"][0]["logprobs"]["tokens"]]
|
||||
return name, toks
|
||||
|
||||
items = list(ref.items())
|
||||
workers = len(items) if "--concurrent" in sys.argv else 1
|
||||
with ThreadPoolExecutor(workers) as ex:
|
||||
for name, toks in ex.map(gen, items):
|
||||
want = ref[name]["gen_ids"]
|
||||
same = next((i for i, (a, b) in enumerate(zip(toks, want)) if a != b), len(want))
|
||||
print(f"{name:<15} identical prefix {same}/{len(want)}")
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Measure achievable XPU memory bandwidth and bf16 GEMM throughput (roofline anchors)."""
|
||||
import time, torch
|
||||
d = "xpu"
|
||||
def t(fn, n=20):
|
||||
fn(); torch.xpu.synchronize(); t0 = time.perf_counter()
|
||||
for _ in range(n): fn()
|
||||
torch.xpu.synchronize(); return (time.perf_counter() - t0) / n
|
||||
x = torch.empty(512 * 2**20, dtype=torch.uint8, device=d); y = torch.empty_like(x)
|
||||
s = t(lambda: y.copy_(x)); print(f"copy bandwidth (read+write): {2 * x.numel() / s / 1e9:.0f} GB/s")
|
||||
w = torch.randn(7680, 2048, device=d, dtype=torch.bfloat16); v = torch.randn(1, 2048, device=d, dtype=torch.bfloat16)
|
||||
s = t(lambda: v @ w.T, 200); print(f"GEMV 7680x2048 bf16 (decode-like): {w.numel() * 2 / s / 1e9:.0f} GB/s")
|
||||
for m in (4096, 8192):
|
||||
a = torch.randn(m, 2048, device=d, dtype=torch.bfloat16); b = torch.randn(7680, 2048, device=d, dtype=torch.bfloat16)
|
||||
s = t(lambda: a @ b.T); print(f"GEMM {m}x2048x7680 bf16: {2 * m * 2048 * 7680 / s / 1e12:.1f} TFLOPS")
|
||||
print(torch.xpu.get_device_name(), f"{torch.xpu.get_device_properties().total_memory / 2**30:.0f} GiB")
|
||||
@@ -0,0 +1,224 @@
|
||||
"""Correctness check: vLLM + vllm_lfm3 vs. Liquid's Transformers reference code.
|
||||
|
||||
Stage 1 (XPU, lfm3-vllm-xpu image): python ref_compare.py vllm OUT.json [--dtype bfloat16]
|
||||
greedy-decodes 64 tokens per prompt, dumps top-K logprobs for every prompt position
|
||||
(prompt_logprobs) and every generated position.
|
||||
Stage 2 (CPU, same image, no GPU): python ref_compare.py hf OUT.json [--hf-dtypes float32,bfloat16]
|
||||
runs modeling_lfm3.py (trust_remote_code) teacher-forced over prompt + vLLM continuation
|
||||
and compares logprobs / top-k agreement; then HF's own greedy generate vs vLLM's tokens.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
|
||||
MODEL = "/models/LFM3-1.7B"
|
||||
TOPK = 20
|
||||
MAX_NEW = 64
|
||||
|
||||
LONG_TEXT = (
|
||||
"The history of the bicycle spans more than two centuries. Early designs such as the "
|
||||
"draisine, introduced in 1817, had no pedals; riders pushed themselves along with their "
|
||||
"feet. In the 1860s French inventors attached pedals directly to the front wheel, creating "
|
||||
"the velocipede, nicknamed the boneshaker because of its iron tires and rigid frame. The "
|
||||
"high-wheeler or penny-farthing followed in the 1870s, whose huge front wheel increased the "
|
||||
"distance covered per pedal revolution but made the machine dangerous to mount and ride. "
|
||||
"The safety bicycle of the 1880s, with two wheels of equal size and a chain driving the rear "
|
||||
"wheel, solved most of these problems, and the pneumatic tire, patented by John Boyd Dunlop "
|
||||
"in 1888, made riding far more comfortable. These innovations triggered a cycling boom in "
|
||||
"the 1890s that changed social life, gave women new independence, and pushed governments to "
|
||||
"improve roads. In the twentieth century bicycles became everyday transport in many "
|
||||
"countries, especially in the Netherlands, Denmark and China, while racing bicycles evolved "
|
||||
"with lighter frames, derailleur gears and aerodynamic components. Today electric bicycles "
|
||||
"extend the range and appeal of cycling to commuters and older riders, and cities around "
|
||||
"the world are building protected bike lanes to encourage this efficient, healthy and "
|
||||
"low-emission mode of transport. "
|
||||
)
|
||||
|
||||
|
||||
def register_plugin():
|
||||
# registers the "lfm3" config with transformers so the tokenizer loads without
|
||||
# trust_remote_code (vLLM itself loads the plugin on its own)
|
||||
import vllm_lfm3
|
||||
|
||||
vllm_lfm3.register()
|
||||
|
||||
|
||||
def build_prompts(tokenizer):
|
||||
chat = lambda msg: tokenizer.apply_chat_template( # noqa: E731
|
||||
[{"role": "user", "content": msg}], add_generation_prompt=True, tokenize=False
|
||||
)
|
||||
prompts = {
|
||||
"raw_short": "The capital of France is",
|
||||
"raw_code": "def fibonacci(n):\n \"\"\"Return the n-th Fibonacci number.\"\"\"\n",
|
||||
"chat_short": chat("What is C. elegans? Answer in two sentences."),
|
||||
"chat_long_600": chat(LONG_TEXT * 2 + "\n\nSummarize the text above in three bullet points."),
|
||||
"raw_long_1500": LONG_TEXT * 5 + "In summary,",
|
||||
}
|
||||
return {k: tokenizer(v, add_special_tokens=False)["input_ids"] for k, v in prompts.items()}
|
||||
|
||||
|
||||
def run_vllm(out_path, dtype, eager=True):
|
||||
from transformers import AutoTokenizer
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.inputs import TokensPrompt
|
||||
|
||||
register_plugin()
|
||||
tok = AutoTokenizer.from_pretrained(MODEL)
|
||||
prompts = build_prompts(tok)
|
||||
llm = LLM(
|
||||
model=MODEL,
|
||||
dtype=dtype,
|
||||
max_model_len=4096,
|
||||
gpu_memory_utilization=0.4,
|
||||
enforce_eager=eager,
|
||||
max_logprobs=TOPK,
|
||||
seed=0,
|
||||
)
|
||||
sp = SamplingParams(
|
||||
temperature=0.0, max_tokens=MAX_NEW, logprobs=TOPK, prompt_logprobs=TOPK,
|
||||
ignore_eos=True,
|
||||
)
|
||||
names = list(prompts)
|
||||
# batch them all together: exercises mixed lengths / continuous batching
|
||||
outs = llm.generate([TokensPrompt(prompt_token_ids=prompts[n]) for n in names], sp)
|
||||
result = {}
|
||||
for name, o in zip(names, outs):
|
||||
c = o.outputs[0]
|
||||
|
||||
def conv(lp):
|
||||
return None if lp is None else {str(t): v.logprob for t, v in lp.items()}
|
||||
|
||||
result[name] = {
|
||||
"prompt_ids": prompts[name],
|
||||
"gen_ids": list(c.token_ids),
|
||||
"gen_text": c.text,
|
||||
# prompt_logprobs[i] is the distribution for token i given tokens < i
|
||||
"prompt_logprobs": [conv(lp) for lp in o.prompt_logprobs],
|
||||
"gen_logprobs": [conv(lp) for lp in c.logprobs],
|
||||
}
|
||||
print(f"[{name}] {len(prompts[name])} prompt tokens -> {c.text[:120]!r}")
|
||||
json.dump({"dtype": dtype, "results": result}, open(out_path, "w"))
|
||||
|
||||
|
||||
def run_hf(in_path, hf_dtypes):
|
||||
import torch
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||
|
||||
torch.set_num_threads(8)
|
||||
data = json.load(open(in_path))
|
||||
tok = AutoTokenizer.from_pretrained(MODEL)
|
||||
report = {"vllm_dtype": data["dtype"], "hf": {}}
|
||||
fp32_top = {} # name -> (values, indices) of the HF fp32 top-5, for the bf16 noise floor
|
||||
|
||||
for hf_dtype in hf_dtypes:
|
||||
model = AutoModelForCausalLM.from_pretrained(
|
||||
MODEL, trust_remote_code=True, dtype=getattr(torch, hf_dtype)
|
||||
).eval()
|
||||
rep = report["hf"][hf_dtype] = {}
|
||||
print(f"\n===== HF reference dtype={hf_dtype} vs vLLM dtype={data['dtype']} =====")
|
||||
for name, r in data["results"].items():
|
||||
ids = r["prompt_ids"] + r["gen_ids"]
|
||||
with torch.no_grad():
|
||||
logits = model(torch.tensor([ids])).logits[0].float()
|
||||
logp = torch.log_softmax(logits, -1)
|
||||
n_prompt = len(r["prompt_ids"])
|
||||
# vLLM distributions, aligned so that entry j predicts token ids[j+1]
|
||||
vdists = r["prompt_logprobs"][1:] + r["gen_logprobs"]
|
||||
assert len(vdists) == len(ids) - 1, (len(vdists), len(ids))
|
||||
|
||||
max_diff, sum_diff, top1_agree, topk_overlap, n = 0.0, 0.0, 0, 0.0, 0
|
||||
top1_margins = [] # HF logp gap between HF's and vLLM's top-1 where they differ
|
||||
diffs_window = {"<=256": 0.0, ">256": 0.0}
|
||||
for j, vd in enumerate(vdists):
|
||||
if vd is None:
|
||||
continue
|
||||
vd = {int(t): v for t, v in vd.items()}
|
||||
# vLLM returns top-K plus the sampled/actual token; take the top-K by value
|
||||
vtop = sorted(vd, key=vd.get, reverse=True)[:TOPK]
|
||||
htop = torch.topk(logp[j], TOPK).indices.tolist()
|
||||
d = max(abs(vd[t] - logp[j, t].item()) for t in vtop[:5])
|
||||
max_diff = max(max_diff, d)
|
||||
sum_diff += abs(vd[vtop[0]] - logp[j, vtop[0]].item())
|
||||
if vtop[0] != htop[0]:
|
||||
top1_margins.append(round((logp[j, htop[0]] - logp[j, vtop[0]]).item(), 3))
|
||||
key = "<=256" if j < 256 else ">256"
|
||||
diffs_window[key] = max(diffs_window[key], d)
|
||||
top1_agree += vtop[0] == htop[0]
|
||||
topk_overlap += len(set(vtop[:5]) & set(htop[:5])) / 5
|
||||
n += 1
|
||||
|
||||
# teacher-forced check of the vLLM greedy continuation
|
||||
gen_mismatch = []
|
||||
for i, t in enumerate(r["gen_ids"]):
|
||||
j = n_prompt - 1 + i
|
||||
hf_arg = int(logp[j].argmax())
|
||||
if hf_arg != t:
|
||||
margin = (logp[j, hf_arg] - logp[j, t]).item()
|
||||
gen_mismatch.append((i, t, hf_arg, round(margin, 4)))
|
||||
|
||||
# HF's own greedy generate from the prompt
|
||||
with torch.no_grad():
|
||||
g = model.generate(
|
||||
torch.tensor([r["prompt_ids"]]), max_new_tokens=MAX_NEW, do_sample=False,
|
||||
min_new_tokens=MAX_NEW, pad_token_id=tok.pad_token_id,
|
||||
# generation_config.json sets repetition_penalty=1.1: pure greedy needs 1.0
|
||||
repetition_penalty=1.0, temperature=None, top_k=None, top_p=None,
|
||||
)[0, n_prompt:].tolist()
|
||||
common = next((i for i, (a, b) in enumerate(zip(g, r["gen_ids"])) if a != b), len(g))
|
||||
|
||||
noise = {}
|
||||
n_pos = logp.shape[0] - 1
|
||||
if hf_dtype == "float32":
|
||||
fp32_top[name] = torch.topk(logp[:n_pos], 5)
|
||||
elif name in fp32_top:
|
||||
vals, idx = fp32_top[name]
|
||||
d = (logp[:n_pos].gather(1, idx) - vals).abs()
|
||||
noise = {
|
||||
"noise_vs_hf_fp32_max_top5": round(d.max().item(), 4),
|
||||
"noise_vs_hf_fp32_mean_top1": round(d[:, 0].mean().item(), 5),
|
||||
"noise_vs_hf_fp32_top1_agree": f"{int((logp[:n_pos].argmax(-1) == idx[:, 0]).sum())}/{n_pos}",
|
||||
}
|
||||
rep[name] = {**noise,
|
||||
"positions": n,
|
||||
"max_abs_logprob_diff_top5": round(max_diff, 4),
|
||||
"mean_abs_logprob_diff_top1": round(sum_diff / n, 5),
|
||||
"top1_disagreement_margins": top1_margins,
|
||||
"max_diff_pos<=256": round(diffs_window["<=256"], 4),
|
||||
"max_diff_pos>256": round(diffs_window[">256"], 4),
|
||||
"top1_agreement": f"{top1_agree}/{n}",
|
||||
"top5_overlap": round(topk_overlap / n, 4),
|
||||
"final_prompt_pos_diff": round(
|
||||
max(
|
||||
abs(v - logp[n_prompt - 1, int(t)].item())
|
||||
for t, v in sorted(
|
||||
r["gen_logprobs"][0].items(), key=lambda kv: -kv[1]
|
||||
)[:5]
|
||||
),
|
||||
4,
|
||||
),
|
||||
"teacher_forced_greedy_mismatches": gen_mismatch,
|
||||
"hf_greedy_identical_prefix": f"{common}/{MAX_NEW}",
|
||||
}
|
||||
print(f"[{name}] {json.dumps(rep[name])}")
|
||||
if common < MAX_NEW:
|
||||
print(f" vLLM: {tok.decode(r['gen_ids'])!r}\n HF : {tok.decode(g)!r}")
|
||||
del model
|
||||
out = in_path.replace(".json", "_report.json")
|
||||
json.dump(report, open(out, "w"), indent=1)
|
||||
print(f"\nreport -> {out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("stage", choices=["vllm", "hf"])
|
||||
ap.add_argument("path")
|
||||
ap.add_argument("--dtype", default="bfloat16")
|
||||
ap.add_argument("--no-eager", action="store_true", help="torch.compile + XPU graphs")
|
||||
ap.add_argument("--hf-dtypes", default="float32,bfloat16")
|
||||
a = ap.parse_args()
|
||||
if a.stage == "vllm":
|
||||
run_vllm(a.path, a.dtype, eager=not a.no_eager)
|
||||
else:
|
||||
run_hf(a.path, a.hf_dtypes.split(","))
|
||||
sys.exit(0)
|
||||
@@ -0,0 +1,191 @@
|
||||
#!/usr/bin/env python3
|
||||
"""OpenAI-API smoke tests for the LFM3 vLLM server (stdlib only, runs on the host).
|
||||
|
||||
python3 tests/test_api.py [--base http://127.0.0.1:8000/v1]
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
MODEL = "lfm3-1.7b"
|
||||
SAMPLING = {"temperature": 0.1, "top_k": 50, "repetition_penalty": 1.1}
|
||||
|
||||
LONG_TEXT = (
|
||||
"The draisine, a two-wheeled running machine without pedals, was introduced by Karl Drais "
|
||||
"in the year 1817 in Mannheim. "
|
||||
+ (
|
||||
"Over the following decades many inventors experimented with ways to propel such "
|
||||
"machines more efficiently, using cranks, levers, treadles and eventually chains, and "
|
||||
"cycling clubs spread across Europe and North America as roads improved and tires "
|
||||
"became more comfortable for everyday riders. "
|
||||
)
|
||||
* 12
|
||||
)
|
||||
|
||||
WEATHER_TOOL = {
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get the current weather for a city.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"city": {"type": "string", "description": "City name, e.g. Berlin"},
|
||||
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
|
||||
},
|
||||
"required": ["city"],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def post(base, path, body, stream=False):
|
||||
req = urllib.request.Request(
|
||||
base + path, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}
|
||||
)
|
||||
resp = urllib.request.urlopen(req, timeout=300)
|
||||
if not stream:
|
||||
return json.loads(resp.read())
|
||||
events = []
|
||||
for line in resp:
|
||||
line = line.decode().strip()
|
||||
if line.startswith("data: ") and line != "data: [DONE]":
|
||||
events.append(json.loads(line[6:]))
|
||||
return events
|
||||
|
||||
|
||||
def chat(base, messages, **kw):
|
||||
body = {"model": MODEL, "messages": messages, "max_tokens": 2048, **SAMPLING, **kw}
|
||||
t0 = time.time()
|
||||
r = post(base, "/chat/completions", body)
|
||||
return r, time.time() - t0
|
||||
|
||||
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
RESULTS.append((name, bool(cond)))
|
||||
print(f"{'PASS' if cond else 'FAIL'} {name}" + (f" -- {detail}" if detail else ""))
|
||||
|
||||
|
||||
def msg_reasoning(m):
|
||||
# vLLM 0.32 uses "reasoning"; older releases "reasoning_content"
|
||||
return m.get("reasoning") or m.get("reasoning_content")
|
||||
|
||||
|
||||
def test_chat_reasoning(base):
|
||||
r, dt = chat(base, [{"role": "user", "content": "What is 17 * 23? Reply with just the number."}])
|
||||
m = r["choices"][0]["message"]
|
||||
reasoning, content = msg_reasoning(m), m.get("content") or ""
|
||||
print(f" reasoning[:200]={str(reasoning)[:200]!r}\n content={content!r} ({dt:.1f}s, {r['usage']})")
|
||||
check("chat: reasoning split off", reasoning and len(reasoning) > 10)
|
||||
check("chat: content has no think tags", "<think>" not in content and "</think>" not in content)
|
||||
check("chat: correct answer 391", "391" in content, content)
|
||||
|
||||
|
||||
def test_no_thinking(base):
|
||||
r, _ = chat(
|
||||
base,
|
||||
[{"role": "user", "content": "Name three primary colors. One line."}],
|
||||
chat_template_kwargs={"enable_thinking": False},
|
||||
)
|
||||
m = r["choices"][0]["message"]
|
||||
print(f" reasoning={msg_reasoning(m)!r}\n content={m.get('content')!r}")
|
||||
check("no-think: content present", m.get("content"))
|
||||
|
||||
|
||||
def test_stream(base):
|
||||
body = {
|
||||
"model": MODEL, "stream": True, "max_tokens": 1024, **SAMPLING,
|
||||
"messages": [{"role": "user", "content": "Give me one fun fact about octopuses."}],
|
||||
}
|
||||
ev = post(base, "/chat/completions", body, stream=True)
|
||||
reasoning = "".join(
|
||||
(e["choices"][0]["delta"].get("reasoning") or e["choices"][0]["delta"].get("reasoning_content") or "")
|
||||
for e in ev if e.get("choices")
|
||||
)
|
||||
content = "".join((e["choices"][0]["delta"].get("content") or "") for e in ev if e.get("choices"))
|
||||
print(f" stream: {len(ev)} events, reasoning {len(reasoning)} chars, content={content[:200]!r}")
|
||||
check("stream: reasoning and content deltas", reasoning and content)
|
||||
|
||||
|
||||
def test_tool_call(base):
|
||||
messages = [{"role": "user", "content": "What's the weather like in Berlin right now?"}]
|
||||
r, _ = chat(base, messages, tools=[WEATHER_TOOL], tool_choice="auto")
|
||||
m = r["choices"][0]["message"]
|
||||
calls = m.get("tool_calls") or []
|
||||
print(f" finish_reason={r['choices'][0]['finish_reason']} tool_calls={json.dumps(calls)}")
|
||||
print(f" content={m.get('content')!r}")
|
||||
ok = len(calls) == 1 and calls[0]["function"]["name"] == "get_weather"
|
||||
args = json.loads(calls[0]["function"]["arguments"]) if ok else {}
|
||||
check("tool: get_weather called", ok)
|
||||
check("tool: city=Berlin", str(args.get("city", "")).lower() == "berlin", args)
|
||||
check("tool: finish_reason tool_calls", r["choices"][0]["finish_reason"] == "tool_calls")
|
||||
if not ok:
|
||||
return
|
||||
messages += [
|
||||
{"role": "assistant", "content": m.get("content") or "", "tool_calls": calls},
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": calls[0]["id"],
|
||||
"content": json.dumps({"city": "Berlin", "temperature": 14, "unit": "celsius", "sky": "light rain"}),
|
||||
},
|
||||
]
|
||||
r, _ = chat(base, messages, tools=[WEATHER_TOOL])
|
||||
content = r["choices"][0]["message"].get("content") or ""
|
||||
print(f" follow-up content={content!r}")
|
||||
check("tool: follow-up uses result (14 / rain)", "14" in content or "rain" in content.lower())
|
||||
|
||||
|
||||
def test_long_prompt(base):
|
||||
q = LONG_TEXT + "\n\nQuestion: In which year was the draisine introduced, according to the text? Answer with the year only."
|
||||
r, dt = chat(base, [{"role": "user", "content": q}])
|
||||
content = r["choices"][0]["message"].get("content") or ""
|
||||
pt = r["usage"]["prompt_tokens"]
|
||||
print(f" prompt_tokens={pt} content={content!r} ({dt:.1f}s)")
|
||||
check("long: prompt > 256 tokens (sliding window active)", pt > 256, pt)
|
||||
check("long: retrieves fact from the start (1817)", "1817" in content, content)
|
||||
|
||||
|
||||
def prefix_cache_hits(base):
|
||||
text = urllib.request.urlopen(base.replace("/v1", "") + "/metrics").read().decode()
|
||||
return sum(
|
||||
float(line.split()[-1]) for line in text.splitlines()
|
||||
if line.startswith("vllm:prefix_cache_hits_total")
|
||||
)
|
||||
|
||||
|
||||
def test_prefix_cache(base):
|
||||
# Prefix caching runs the conv state in mamba_cache_mode="align": a cached request
|
||||
# restores the conv state from a block checkpoint. Greedy output must not change.
|
||||
body = {
|
||||
"model": MODEL, "max_tokens": 64, "temperature": 0.0,
|
||||
"prompt": LONG_TEXT * 2 + "\n\nIn one sentence, the text is about",
|
||||
}
|
||||
hits0 = prefix_cache_hits(base)
|
||||
cold = post(base, "/completions", body)["choices"][0]["text"]
|
||||
warm = post(base, "/completions", body)["choices"][0]["text"]
|
||||
hits = prefix_cache_hits(base) - hits0
|
||||
print(f" prefix-cache hit tokens: {hits:.0f}\n cold={cold[:120]!r}\n warm={warm[:120]!r}")
|
||||
check("prefix cache: second request hits the cache", hits > 256, hits)
|
||||
check("prefix cache: cached output identical to cold output", cold == warm)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base", default="http://127.0.0.1:8000/v1")
|
||||
a = ap.parse_args()
|
||||
print(json.dumps(json.loads(urllib.request.urlopen(a.base + "/models").read()))[:300])
|
||||
for t in (test_chat_reasoning, test_no_thinking, test_stream, test_tool_call, test_long_prompt, test_prefix_cache):
|
||||
print(f"\n== {t.__name__}")
|
||||
try:
|
||||
t(a.base)
|
||||
except Exception as e: # noqa: BLE001
|
||||
check(t.__name__, False, f"{type(e).__name__}: {e}")
|
||||
n_ok = sum(ok for _, ok in RESULTS)
|
||||
print(f"\n{n_ok}/{len(RESULTS)} checks passed")
|
||||
sys.exit(0 if n_ok == len(RESULTS) else 1)
|
||||
@@ -0,0 +1,173 @@
|
||||
"""Isolated test of width-7 causal conv1d on XPU.
|
||||
|
||||
Compares against an independent per-sequence F.conv1d reference in fp32:
|
||||
* vLLM's stock Triton causal_conv1d_fn / causal_conv1d_update (expected to be wrong at width 7)
|
||||
* vllm_lfm3.conv_ops torch and triton paths, for both conv-state layouts (SD, DS),
|
||||
for prefill (fresh + continued chunks, sequences shorter than the state) and decode.
|
||||
|
||||
Run inside the container: python /work/tests/test_conv_kernel.py
|
||||
"""
|
||||
|
||||
import sys
|
||||
import time
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
sys.path.insert(0, "/work")
|
||||
from vllm_lfm3 import conv_ops # noqa: E402
|
||||
|
||||
torch.manual_seed(0)
|
||||
DEV = "xpu" if torch.xpu.is_available() else "cpu"
|
||||
DT = torch.bfloat16
|
||||
D, K = 2048, 7
|
||||
L = K - 1
|
||||
NUM_BLOCKS = 16
|
||||
|
||||
|
||||
def ref_conv(x_seq, state, w, bias):
|
||||
"""x_seq (T, D) fp32, state (L, D) fp32 -> out (T, D), new_state (L, D)."""
|
||||
full = torch.cat([state, x_seq], 0) # (L+T, D)
|
||||
out = F.conv1d(full.T[None], w[:, None, :], bias, groups=D)[0].T # (T, D)
|
||||
return out, full[-L:]
|
||||
|
||||
|
||||
def make_case(lens, has_init, layout):
|
||||
w = torch.randn(D, K, device=DEV, dtype=DT) * 0.3
|
||||
x = torch.randn(sum(lens), D, device=DEV, dtype=DT)
|
||||
if layout == "SD":
|
||||
state = torch.randn(NUM_BLOCKS, L, D, device=DEV, dtype=DT)
|
||||
state_view = state
|
||||
else: # DS storage, viewed token-major
|
||||
state = torch.randn(NUM_BLOCKS, D, L, device=DEV, dtype=DT)
|
||||
state_view = state.transpose(1, 2)
|
||||
slots = torch.tensor([3, 7, 1, 12, 5][: len(lens)], device=DEV, dtype=torch.int32)
|
||||
qsl = torch.zeros(len(lens) + 1, dtype=torch.int32, device=DEV)
|
||||
qsl[1:] = torch.cumsum(torch.tensor(lens, device=DEV), 0)
|
||||
hi = torch.tensor(has_init, device=DEV, dtype=torch.bool)
|
||||
return w, x, state, state_view, slots, qsl, hi
|
||||
|
||||
|
||||
def reference_prefill(w, x, state_view, slots, qsl, hi):
|
||||
outs, states = [], state_view.float().clone()
|
||||
for i in range(len(slots)):
|
||||
a, b = int(qsl[i]), int(qsl[i + 1])
|
||||
init = states[int(slots[i])] if bool(hi[i]) else torch.zeros(L, D, device=DEV)
|
||||
o, ns = ref_conv(x[a:b].float(), init, w.float(), None)
|
||||
outs.append(o)
|
||||
states[int(slots[i])] = ns
|
||||
return torch.cat(outs), states
|
||||
|
||||
|
||||
def check(name, got, want, tol=2e-2):
|
||||
err = (got.float() - want.float()).abs().max().item()
|
||||
ok = err < tol
|
||||
print(f" {'PASS' if ok else 'FAIL'} {name:<44} max_abs_err={err:.3e}")
|
||||
return ok
|
||||
|
||||
|
||||
def test_ours(impl):
|
||||
ok = True
|
||||
prefill = getattr(conv_ops, f"causal_conv1d_prefill_{impl}")
|
||||
decode = getattr(conv_ops, f"causal_conv1d_decode_{impl}")
|
||||
for layout in ("SD", "DS"):
|
||||
lens, has_init = [37, 3, 1, 300, 6], [False, True, True, False, True]
|
||||
w, x, state, sv, slots, qsl, hi = make_case(lens, has_init, layout)
|
||||
want_out, want_state = reference_prefill(w, x, sv, slots, qsl, hi)
|
||||
out = prefill(x, w, None, sv, qsl, slots, hi)
|
||||
ok &= check(f"{impl}/{layout} prefill out", out, want_out)
|
||||
ok &= check(f"{impl}/{layout} prefill state", sv.float(), want_state)
|
||||
|
||||
# 5 decode steps, with one padded row (-1) that must not corrupt anything
|
||||
for step in range(5):
|
||||
xd = torch.randn(len(lens), D, device=DEV, dtype=DT)
|
||||
want_rows, st = [], sv.float().clone()
|
||||
for i in range(len(lens)):
|
||||
o, ns = ref_conv(xd[i : i + 1].float(), st[int(slots[i])], w.float(), None)
|
||||
want_rows.append(o)
|
||||
st[int(slots[i])] = ns
|
||||
pad_idx = torch.cat([slots, torch.tensor([-1], device=DEV, dtype=torch.int32)])
|
||||
xpad = torch.cat([xd, torch.zeros(1, D, device=DEV, dtype=DT)])
|
||||
out = decode(xpad, w, None, sv, pad_idx)[: len(lens)]
|
||||
ok &= check(f"{impl}/{layout} decode step {step} out", out, torch.cat(want_rows))
|
||||
# block 0 is the null block (written by the pad row); compare all others
|
||||
ok &= check(f"{impl}/{layout} decode step {step} state", sv[1:].float(), st[1:])
|
||||
return ok
|
||||
|
||||
|
||||
def test_stock_vllm():
|
||||
from vllm.model_executor.layers.mamba.ops.causal_conv1d import (
|
||||
causal_conv1d_fn,
|
||||
causal_conv1d_update,
|
||||
)
|
||||
|
||||
lens, has_init = [37, 3, 300], [False, True, False]
|
||||
w, x, state, sv, slots, qsl, hi = make_case(lens, has_init, "DS")
|
||||
want_out, want_state = reference_prefill(w, x, sv, slots, qsl, hi)
|
||||
try:
|
||||
out = causal_conv1d_fn(
|
||||
x.T, w, None, state, qsl, cache_indices=slots, has_initial_state=hi,
|
||||
activation=None,
|
||||
).T
|
||||
check("stock causal_conv1d_fn out (width 7)", out, want_out)
|
||||
check("stock causal_conv1d_fn state (width 7)", sv.float(), want_state)
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f" ERROR stock causal_conv1d_fn: {type(e).__name__}: {str(e)[:200]}")
|
||||
try:
|
||||
xd = torch.randn(len(lens), D, device=DEV, dtype=DT)
|
||||
st = sv.float().clone()
|
||||
want = []
|
||||
for i in range(len(lens)):
|
||||
o, ns = ref_conv(xd[i : i + 1].float(), st[int(slots[i])], w.float(), None)
|
||||
want.append(o)
|
||||
out = causal_conv1d_update(xd, state, w, None, activation=None, conv_state_indices=slots)
|
||||
check("stock causal_conv1d_update out (width 7)", out, torch.cat(want))
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f" ERROR stock causal_conv1d_update: {type(e).__name__}: {str(e)[:200]}")
|
||||
|
||||
|
||||
def bench():
|
||||
print("\nTiming (bf16, D=2048):")
|
||||
for impl in ("torch", "triton"):
|
||||
prefill = getattr(conv_ops, f"causal_conv1d_prefill_{impl}")
|
||||
decode = getattr(conv_ops, f"causal_conv1d_decode_{impl}")
|
||||
for lens in ([2048], [512] * 16):
|
||||
w, x, state, sv, slots, qsl, hi = make_case(lens[:5] if len(lens) > 5 else lens, [False] * min(5, len(lens)), "SD")
|
||||
if len(lens) > 5:
|
||||
x = torch.randn(sum(lens), D, device=DEV, dtype=DT)
|
||||
slots = torch.arange(len(lens), device=DEV, dtype=torch.int32) % NUM_BLOCKS
|
||||
qsl = torch.arange(len(lens) + 1, device=DEV, dtype=torch.int32) * lens[0]
|
||||
hi = torch.zeros(len(lens), dtype=torch.bool, device=DEV)
|
||||
for _ in range(3):
|
||||
prefill(x, w, None, sv, qsl, slots, hi)
|
||||
torch.xpu.synchronize()
|
||||
t0 = time.perf_counter()
|
||||
for _ in range(20):
|
||||
prefill(x, w, None, sv, qsl, slots, hi)
|
||||
torch.xpu.synchronize()
|
||||
print(f" {impl:<6} prefill {len(lens)}x{lens[0]:<5} {1e3 * (time.perf_counter() - t0) / 20:.3f} ms")
|
||||
for n in (1, 16):
|
||||
xd = torch.randn(n, D, device=DEV, dtype=DT)
|
||||
idx = torch.arange(n, device=DEV, dtype=torch.int32) % NUM_BLOCKS
|
||||
for _ in range(3):
|
||||
decode(xd, w, None, sv, idx)
|
||||
torch.xpu.synchronize()
|
||||
t0 = time.perf_counter()
|
||||
for _ in range(100):
|
||||
decode(xd, w, None, sv, idx)
|
||||
torch.xpu.synchronize()
|
||||
print(f" {impl:<6} decode batch {n:<9} {1e3 * (time.perf_counter() - t0) / 100:.3f} ms")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(f"device={DEV} torch={torch.__version__}")
|
||||
print("\n[stock vLLM Triton causal_conv1d at width 7]")
|
||||
test_stock_vllm()
|
||||
all_ok = True
|
||||
for impl in ("torch", "triton"):
|
||||
print(f"\n[vllm_lfm3.conv_ops {impl}]")
|
||||
all_ok &= test_ours(impl)
|
||||
if DEV == "xpu":
|
||||
bench()
|
||||
print("\nRESULT:", "ALL PASS" if all_ok else "FAILURES")
|
||||
sys.exit(0 if all_ok else 1)
|
||||
@@ -0,0 +1,29 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""Out-of-tree vLLM plugin for LiquidAI LFM3 (Lfm3ForCausalLM).
|
||||
|
||||
Loaded through the ``vllm.general_plugins`` entry point in every vLLM process
|
||||
(API server, EngineCore, workers).
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def register() -> None:
|
||||
from vllm import ModelRegistry
|
||||
|
||||
if "Lfm3ForCausalLM" not in ModelRegistry.get_supported_archs():
|
||||
# lazy "module:class" form: the model module is only imported when used
|
||||
ModelRegistry.register_model("Lfm3ForCausalLM", "vllm_lfm3.model:Lfm3ForCausalLM")
|
||||
|
||||
# Lets transformers (and therefore vLLM) parse config.json with model_type "lfm3"
|
||||
# without --trust-remote-code.
|
||||
from transformers import AutoConfig
|
||||
|
||||
from .configuration_lfm3 import Lfm3Config
|
||||
|
||||
try:
|
||||
AutoConfig.register("lfm3", Lfm3Config)
|
||||
except ValueError:
|
||||
pass # already registered (e.g. a future transformers ships lfm3)
|
||||
@@ -0,0 +1,134 @@
|
||||
# Vendored verbatim from /models/LFM3-1.7B/configuration_lfm3.py (LiquidAI / HF, Apache-2.0)
|
||||
# so that config.json parses without --trust-remote-code.
|
||||
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
from huggingface_hub.dataclasses import strict
|
||||
|
||||
from transformers.configuration_utils import PreTrainedConfig
|
||||
from transformers.utils import auto_docstring
|
||||
|
||||
|
||||
@auto_docstring(checkpoint="LiquidAI/LFM3-1.7B-Preview")
|
||||
@strict
|
||||
class Lfm3Config(PreTrainedConfig):
|
||||
r"""
|
||||
rope_parameters (`dict[str, RopeParameters]`, *optional*):
|
||||
RoPE parameters keyed by attention layer type, for example `{"full_attention": {"rope_type": "default",
|
||||
"rope_theta": 1000000.0, "partial_rotary_factor": 0.5}, "sliding_attention": {"rope_type": "default",
|
||||
"rope_theta": 10000.0}}`. `conv` layers do not use RoPE and have no entry. Full-attention layers rotate the
|
||||
first `partial_rotary_factor * head_dim` dimensions and leave the rest unrotated.
|
||||
conv_bias (`bool`, *optional*, defaults to `False`):
|
||||
Whether to use bias in the conv layers.
|
||||
conv_L_cache (`int`, *optional*, defaults to 7):
|
||||
L_cache dim in the conv layers.
|
||||
layer_types (`list[str]`, *optional*):
|
||||
Per-layer operator type, each one of `"full_attention"`, `"sliding_attention"` or `"conv"`. Defaults to the
|
||||
LFM3 pattern of a full-attention layer every fourth layer starting from the third, a sliding-attention layer
|
||||
in between, and gated short convolutions elsewhere.
|
||||
sliding_window (`int`, *optional*, defaults to 256):
|
||||
Sliding-window size of the `sliding_attention` layers.
|
||||
use_sandwich_norm (`bool`, *optional*, defaults to `True`):
|
||||
Whether to apply an RMSNorm to the operator and feed-forward outputs before they enter the residual stream.
|
||||
|
||||
```python
|
||||
>>> from transformers import Lfm3Model, Lfm3Config
|
||||
|
||||
>>> # Initializing a LFM3 model
|
||||
>>> configuration = Lfm3Config()
|
||||
|
||||
>>> # Initializing a model from the LFM3-1.7B style configuration
|
||||
>>> model = Lfm3Model(configuration)
|
||||
|
||||
>>> # Accessing the model configuration
|
||||
>>> configuration = model.config
|
||||
```
|
||||
"""
|
||||
|
||||
model_type = "lfm3"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
default_theta = 1000000.0
|
||||
|
||||
vocab_size: int = 128_000
|
||||
hidden_size: int = 2048
|
||||
intermediate_size: int = 7680
|
||||
num_hidden_layers: int = 24
|
||||
num_attention_heads: int = 16
|
||||
num_key_value_heads: int = 4
|
||||
max_position_embeddings: int = 128_000
|
||||
initializer_range: float = 0.02
|
||||
norm_eps: float = 0.00001
|
||||
use_cache: bool = True
|
||||
pad_token_id: int | None = 124_893
|
||||
bos_token_id: int | None = 124_894
|
||||
eos_token_id: int | list[int] | None = 124_900
|
||||
tie_word_embeddings: bool = True
|
||||
rope_parameters: dict | None = None
|
||||
conv_bias: bool = False
|
||||
conv_L_cache: int = 7
|
||||
layer_types: list[str] | None = None
|
||||
_attention_layer_types = ("full_attention", "sliding_attention")
|
||||
head_dim: int | None = None
|
||||
sliding_window: int | None = 256
|
||||
use_sandwich_norm: bool = True
|
||||
|
||||
def __post_init__(self, **kwargs):
|
||||
if self.head_dim is None:
|
||||
self.head_dim = self.hidden_size // self.num_attention_heads
|
||||
if self.rope_parameters is None:
|
||||
self.rope_parameters = {
|
||||
"full_attention": {"rope_type": "default", "rope_theta": 1_000_000.0, "partial_rotary_factor": 0.5},
|
||||
"sliding_attention": {"rope_type": "default", "rope_theta": 10_000.0},
|
||||
}
|
||||
if self.layer_types is None:
|
||||
self.layer_types = [
|
||||
"full_attention" if i % 4 == 2 else "sliding_attention" if i % 4 == 0 and i > 0 else "conv"
|
||||
for i in range(self.num_hidden_layers)
|
||||
]
|
||||
|
||||
self.tie_word_embeddings = kwargs.pop("tie_embedding", self.tie_word_embeddings)
|
||||
super().__post_init__(**kwargs)
|
||||
|
||||
def validate_architecture(self):
|
||||
"""Part of ``@strict``-powered validation."""
|
||||
if len(self.layer_types) != self.num_hidden_layers:
|
||||
raise ValueError(
|
||||
f"`layer_types` has {len(self.layer_types)} entries but `num_hidden_layers` is {self.num_hidden_layers}."
|
||||
)
|
||||
allowed_layer_types = (*self._attention_layer_types, "conv")
|
||||
invalid_layer_types = [layer_type for layer_type in self.layer_types if layer_type not in allowed_layer_types]
|
||||
if invalid_layer_types:
|
||||
raise ValueError(f"`layer_types` entries must be one of {allowed_layer_types}; got {invalid_layer_types}.")
|
||||
if "sliding_attention" in self.layer_types and self.sliding_window is None:
|
||||
raise ValueError("`layer_types` has `sliding_attention` layers but `sliding_window` is None.")
|
||||
missing_rope = [
|
||||
layer_type
|
||||
for layer_type in self._attention_layer_types
|
||||
if layer_type in self.layer_types and layer_type not in self.rope_parameters
|
||||
]
|
||||
if missing_rope:
|
||||
raise ValueError(f"`rope_parameters` has no entry for the {missing_rope} layers in `layer_types`.")
|
||||
for layer_type, rope_params in self.rope_parameters.items():
|
||||
if not isinstance(rope_params, dict):
|
||||
continue
|
||||
if (
|
||||
rope_params.get("rope_type", "default") in ("dynamic", "longrope")
|
||||
and rope_params.get("partial_rotary_factor", 1.0) < 1
|
||||
):
|
||||
raise ValueError(
|
||||
f"`{rope_params['rope_type']}` RoPE recomputes its frequencies during the forward pass over the "
|
||||
f"rotated dimension only and cannot keep LFM3's partial rotation on `{layer_type}` layers."
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["Lfm3Config"]
|
||||
@@ -0,0 +1,343 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""Causal depthwise conv1d of arbitrary width for LFM3's short-conv layers.
|
||||
|
||||
vLLM's Triton ``causal_conv1d_fn`` / ``causal_conv1d_update`` are hand-unrolled for
|
||||
widths <= 4 / <= 6, and LFM3 uses width 7. This module provides:
|
||||
|
||||
* ``*_torch``: vectorized PyTorch implementations (no per-sequence Python loop, no
|
||||
host sync), used as reference and fallback;
|
||||
* ``*_triton``: Triton kernels (work on XPU through triton-xpu), the default.
|
||||
|
||||
Layouts (token-major, like vLLM's ShortConv after ``in_proj``):
|
||||
x (num_tokens, dim)
|
||||
weight (dim, width)
|
||||
conv_state (num_blocks, width - 1, dim) -- vLLM's "SD" conv state layout; any
|
||||
strides are accepted, so a transposed "DS" cache works as well.
|
||||
Row ``width - 2`` holds the most recent input.
|
||||
All accumulation is done in fp32.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import torch
|
||||
|
||||
try:
|
||||
import triton
|
||||
import triton.language as tl
|
||||
|
||||
HAS_TRITON = True
|
||||
except ImportError: # pragma: no cover
|
||||
HAS_TRITON = False
|
||||
|
||||
# LFM3_CONV_IMPL=torch forces the PyTorch path (debugging / kernel A/B tests).
|
||||
_IMPL = os.environ.get("LFM3_CONV_IMPL", "triton")
|
||||
|
||||
|
||||
def use_triton() -> bool:
|
||||
return HAS_TRITON and _IMPL == "triton"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# PyTorch implementations
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _prefill_source_indices(
|
||||
query_start_loc: torch.Tensor,
|
||||
num_tokens: int,
|
||||
state_len: int,
|
||||
width: int,
|
||||
):
|
||||
"""Per-token indices into ``cat([initial_states.flatten(0, 1), x])``.
|
||||
|
||||
Returns (tap_idx (num_tokens, width), new_state_idx (num_seqs, state_len)).
|
||||
"""
|
||||
device = query_start_loc.device
|
||||
qsl = query_start_loc.long()
|
||||
num_seqs = qsl.numel() - 1
|
||||
lens = qsl[1:] - qsl[:-1]
|
||||
seq_id = torch.repeat_interleave(
|
||||
torch.arange(num_seqs, device=device), lens, output_size=num_tokens
|
||||
)
|
||||
tok = torch.arange(num_tokens, device=device)
|
||||
pos = tok - qsl[seq_id]
|
||||
x_base = num_seqs * state_len
|
||||
|
||||
# tap k reads relative position p = pos + k - (width - 1)
|
||||
rel = torch.arange(width, device=device) - (width - 1)
|
||||
p = pos[:, None] + rel[None, :]
|
||||
tap_idx = torch.where(
|
||||
p >= 0,
|
||||
x_base + tok[:, None] + rel[None, :],
|
||||
seq_id[:, None] * state_len + state_len + p,
|
||||
)
|
||||
|
||||
# the new state is the last state_len inputs of (initial_state ++ x_seq)
|
||||
q = lens[:, None] - state_len + torch.arange(state_len, device=device)[None, :]
|
||||
seqs = torch.arange(num_seqs, device=device)[:, None]
|
||||
new_state_idx = torch.where(
|
||||
q >= 0, x_base + qsl[:-1, None] + q, seqs * state_len + state_len + q
|
||||
)
|
||||
return tap_idx, new_state_idx
|
||||
|
||||
|
||||
def causal_conv1d_prefill_torch(
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
bias: torch.Tensor | None,
|
||||
conv_state: torch.Tensor,
|
||||
query_start_loc: torch.Tensor,
|
||||
state_indices: torch.Tensor,
|
||||
has_initial_state: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
num_tokens, dim = x.shape
|
||||
width = weight.shape[1]
|
||||
state_len = width - 1
|
||||
num_seqs = query_start_loc.numel() - 1
|
||||
slots = state_indices.long()
|
||||
|
||||
init = conv_state[slots].to(x.dtype) # (S, L, D)
|
||||
init = init * has_initial_state.view(-1, 1, 1).to(init.dtype)
|
||||
src = torch.cat([init.reshape(num_seqs * state_len, dim), x], dim=0)
|
||||
|
||||
tap_idx, new_state_idx = _prefill_source_indices(
|
||||
query_start_loc, num_tokens, state_len, width
|
||||
)
|
||||
w = weight.float()
|
||||
out = torch.zeros(num_tokens, dim, dtype=torch.float32, device=x.device)
|
||||
for k in range(width):
|
||||
out += src[tap_idx[:, k]].float() * w[:, k]
|
||||
if bias is not None:
|
||||
out += bias.float()
|
||||
|
||||
conv_state[slots] = src[new_state_idx].to(conv_state.dtype)
|
||||
return out.to(x.dtype)
|
||||
|
||||
|
||||
def causal_conv1d_decode_torch(
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
bias: torch.Tensor | None,
|
||||
conv_state: torch.Tensor,
|
||||
state_indices: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
# padded rows (PAD_SLOT_ID = -1) are redirected to the null block 0
|
||||
slots = state_indices.long().clamp_min(0)
|
||||
window = torch.cat([conv_state[slots].to(x.dtype), x[:, None, :]], dim=1)
|
||||
out = torch.einsum("nkd,dk->nd", window.float(), weight.float())
|
||||
if bias is not None:
|
||||
out += bias.float()
|
||||
conv_state[slots] = window[:, 1:].to(conv_state.dtype)
|
||||
return out.to(x.dtype)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Triton implementations
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
if HAS_TRITON:
|
||||
|
||||
@triton.jit
|
||||
def _prefill_kernel(
|
||||
X, W, BIAS, STATE, SLOTS, HAS_INIT, QSL, SEQ_ID, Y,
|
||||
T, D,
|
||||
sx_t, sx_d,
|
||||
sw_d, sw_k,
|
||||
ss_b, ss_l, ss_d,
|
||||
sy_t, sy_d,
|
||||
K: tl.constexpr,
|
||||
HAS_BIAS: tl.constexpr,
|
||||
BLOCK_T: tl.constexpr,
|
||||
BLOCK_D: tl.constexpr,
|
||||
):
|
||||
t = tl.program_id(0) * BLOCK_T + tl.arange(0, BLOCK_T)
|
||||
d = tl.program_id(1) * BLOCK_D + tl.arange(0, BLOCK_D)
|
||||
tm = t < T
|
||||
dm = d < D
|
||||
seq = tl.load(SEQ_ID + t, mask=tm, other=0)
|
||||
start = tl.load(QSL + seq, mask=tm, other=0)
|
||||
pos = t - start
|
||||
slot = tl.load(SLOTS + seq, mask=tm, other=0).to(tl.int64)
|
||||
init = tl.load(HAS_INIT + seq, mask=tm, other=0) != 0
|
||||
|
||||
acc = tl.zeros((BLOCK_T, BLOCK_D), dtype=tl.float32)
|
||||
for k in tl.static_range(K):
|
||||
p = pos + (k - (K - 1))
|
||||
from_x = p >= 0
|
||||
from_s = (p < 0) & init
|
||||
xv = tl.load(
|
||||
X + (t + (k - (K - 1)))[:, None].to(tl.int64) * sx_t + d[None, :] * sx_d,
|
||||
mask=(tm & from_x)[:, None] & dm[None, :],
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
sv = tl.load(
|
||||
STATE + slot[:, None] * ss_b + (K - 1 + p)[:, None] * ss_l + d[None, :] * ss_d,
|
||||
mask=(tm & from_s)[:, None] & dm[None, :],
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
w = tl.load(W + d * sw_d + k * sw_k, mask=dm, other=0.0).to(tl.float32)
|
||||
acc += (xv + sv) * w[None, :]
|
||||
if HAS_BIAS:
|
||||
acc += tl.load(BIAS + d, mask=dm, other=0.0).to(tl.float32)[None, :]
|
||||
tl.store(
|
||||
Y + t[:, None].to(tl.int64) * sy_t + d[None, :] * sy_d,
|
||||
acc.to(Y.dtype.element_ty),
|
||||
mask=tm[:, None] & dm[None, :],
|
||||
)
|
||||
|
||||
@triton.jit
|
||||
def _prefill_state_kernel(
|
||||
X, STATE, SLOTS, HAS_INIT, QSL,
|
||||
D,
|
||||
sx_t, sx_d,
|
||||
ss_b, ss_l, ss_d,
|
||||
L: tl.constexpr,
|
||||
L_PAD: tl.constexpr,
|
||||
BLOCK_D: tl.constexpr,
|
||||
):
|
||||
s = tl.program_id(0)
|
||||
d = tl.program_id(1) * BLOCK_D + tl.arange(0, BLOCK_D)
|
||||
dm = d < D
|
||||
l = tl.arange(0, L_PAD)
|
||||
lm = l < L
|
||||
start = tl.load(QSL + s)
|
||||
length = tl.load(QSL + s + 1) - start
|
||||
slot = tl.load(SLOTS + s).to(tl.int64)
|
||||
init = tl.load(HAS_INIT + s) != 0
|
||||
# new row l holds relative position q = length - L + l
|
||||
q = length - L + l
|
||||
from_x = q >= 0
|
||||
xv = tl.load(
|
||||
X + (start + q)[:, None].to(tl.int64) * sx_t + d[None, :] * sx_d,
|
||||
mask=(lm & from_x)[:, None] & dm[None, :],
|
||||
other=0.0,
|
||||
)
|
||||
sv = tl.load(
|
||||
STATE + slot * ss_b + (L + q)[:, None] * ss_l + d[None, :] * ss_d,
|
||||
mask=(lm & (q < 0) & init)[:, None] & dm[None, :],
|
||||
other=0.0,
|
||||
)
|
||||
new = tl.where(from_x[:, None], xv, sv)
|
||||
# all loads above happen before the store: in-place update is safe
|
||||
tl.store(
|
||||
STATE + slot * ss_b + l[:, None] * ss_l + d[None, :] * ss_d,
|
||||
new.to(STATE.dtype.element_ty),
|
||||
mask=lm[:, None] & dm[None, :],
|
||||
)
|
||||
|
||||
@triton.jit
|
||||
def _decode_kernel(
|
||||
X, W, BIAS, STATE, SLOTS, Y,
|
||||
D,
|
||||
sx_n, sx_d,
|
||||
sw_d, sw_k,
|
||||
ss_b, ss_l, ss_d,
|
||||
sy_n, sy_d,
|
||||
L: tl.constexpr,
|
||||
L_PAD: tl.constexpr,
|
||||
HAS_BIAS: tl.constexpr,
|
||||
BLOCK_D: tl.constexpr,
|
||||
):
|
||||
n = tl.program_id(0)
|
||||
d = tl.program_id(1) * BLOCK_D + tl.arange(0, BLOCK_D)
|
||||
dm = d < D
|
||||
l = tl.arange(0, L_PAD)
|
||||
lm = l < L
|
||||
slot = tl.load(SLOTS + n).to(tl.int64)
|
||||
slot = tl.where(slot < 0, 0, slot) # PAD_SLOT_ID -> null block
|
||||
|
||||
base = STATE + slot * ss_b + d[None, :] * ss_d
|
||||
old = tl.load(base + l[:, None] * ss_l, mask=lm[:, None] & dm[None, :], other=0.0)
|
||||
nxt = tl.load(
|
||||
base + (l + 1)[:, None] * ss_l,
|
||||
mask=((l + 1) < L)[:, None] & dm[None, :],
|
||||
other=0.0,
|
||||
)
|
||||
x = tl.load(X + n * sx_n + d * sx_d, mask=dm, other=0.0)
|
||||
|
||||
w_state = tl.load(
|
||||
W + d[None, :] * sw_d + l[:, None] * sw_k,
|
||||
mask=lm[:, None] & dm[None, :],
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
w_last = tl.load(W + d * sw_d + L * sw_k, mask=dm, other=0.0).to(tl.float32)
|
||||
acc = tl.sum(old.to(tl.float32) * w_state, axis=0) + x.to(tl.float32) * w_last
|
||||
if HAS_BIAS:
|
||||
acc += tl.load(BIAS + d, mask=dm, other=0.0).to(tl.float32)
|
||||
|
||||
new = tl.where((l == L - 1)[:, None], x[None, :].to(old.dtype), nxt)
|
||||
tl.store(base + l[:, None] * ss_l, new, mask=lm[:, None] & dm[None, :])
|
||||
tl.store(Y + n * sy_n + d * sy_d, acc.to(Y.dtype.element_ty), mask=dm)
|
||||
|
||||
|
||||
def causal_conv1d_prefill_triton(
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
bias: torch.Tensor | None,
|
||||
conv_state: torch.Tensor,
|
||||
query_start_loc: torch.Tensor,
|
||||
state_indices: torch.Tensor,
|
||||
has_initial_state: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
num_tokens, dim = x.shape
|
||||
width = weight.shape[1]
|
||||
state_len = width - 1
|
||||
num_seqs = query_start_loc.numel() - 1
|
||||
lens = query_start_loc[1:] - query_start_loc[:-1]
|
||||
seq_id = torch.repeat_interleave(
|
||||
torch.arange(num_seqs, device=x.device, dtype=torch.int32),
|
||||
lens,
|
||||
output_size=num_tokens,
|
||||
)
|
||||
has_init = has_initial_state.to(torch.int8)
|
||||
out = torch.empty_like(x)
|
||||
BLOCK_T, BLOCK_D = 32, 64
|
||||
grid = (triton.cdiv(num_tokens, BLOCK_T), triton.cdiv(dim, BLOCK_D))
|
||||
_prefill_kernel[grid](
|
||||
x, weight, bias, conv_state, state_indices, has_init, query_start_loc,
|
||||
seq_id, out,
|
||||
num_tokens, dim,
|
||||
*x.stride(), *weight.stride(), *conv_state.stride(), *out.stride(),
|
||||
K=width, HAS_BIAS=bias is not None, BLOCK_T=BLOCK_T, BLOCK_D=BLOCK_D,
|
||||
)
|
||||
# the conv above read the old states; now overwrite them
|
||||
_prefill_state_kernel[(num_seqs, triton.cdiv(dim, 256))](
|
||||
x, conv_state, state_indices, has_init, query_start_loc,
|
||||
dim,
|
||||
*x.stride(), *conv_state.stride(),
|
||||
L=state_len, L_PAD=triton.next_power_of_2(state_len), BLOCK_D=256,
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def causal_conv1d_decode_triton(
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
bias: torch.Tensor | None,
|
||||
conv_state: torch.Tensor,
|
||||
state_indices: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
num_rows, dim = x.shape
|
||||
state_len = weight.shape[1] - 1
|
||||
out = torch.empty_like(x)
|
||||
BLOCK_D = 256
|
||||
_decode_kernel[(num_rows, triton.cdiv(dim, BLOCK_D))](
|
||||
x, weight, bias, conv_state, state_indices, out,
|
||||
dim,
|
||||
*x.stride(), *weight.stride(), *conv_state.stride(), *out.stride(),
|
||||
L=state_len, L_PAD=triton.next_power_of_2(state_len),
|
||||
HAS_BIAS=bias is not None, BLOCK_D=BLOCK_D,
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def causal_conv1d_prefill(*args, **kwargs) -> torch.Tensor:
|
||||
if use_triton():
|
||||
return causal_conv1d_prefill_triton(*args, **kwargs)
|
||||
return causal_conv1d_prefill_torch(*args, **kwargs)
|
||||
|
||||
|
||||
def causal_conv1d_decode(*args, **kwargs) -> torch.Tensor:
|
||||
if use_triton():
|
||||
return causal_conv1d_decode_triton(*args, **kwargs)
|
||||
return causal_conv1d_decode_torch(*args, **kwargs)
|
||||
@@ -0,0 +1,539 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""vLLM implementation of LiquidAI LFM3 (``Lfm3ForCausalLM``).
|
||||
|
||||
Based on vLLM 0.32's ``lfm2.py``. Differences to LFM2 (see NOTES.md):
|
||||
* three layer types: ``conv`` (gated short conv, width 7), ``full_attention`` and
|
||||
``sliding_attention`` (per-layer sliding window);
|
||||
* sandwich norm (``post_operator_norm`` / ``post_ffn_norm``);
|
||||
* attention with ``q_norm``/``k_norm``, a sigmoid output gate per head and RoPE per
|
||||
layer type, with LFM3's "zero-tail" partial rotation on full-attention layers;
|
||||
* plain SwiGLU MLP (no ff-dim auto adjustment), ``o_proj`` naming;
|
||||
* a width-7 causal conv1d (vLLM's Triton kernels stop at width 4/6).
|
||||
"""
|
||||
|
||||
from collections.abc import Iterable
|
||||
from itertools import islice
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from vllm.compilation.decorators import support_torch_compile
|
||||
from vllm.config import CacheConfig, ModelConfig, VllmConfig
|
||||
from vllm.distributed import get_pp_group, get_tensor_model_parallel_world_size
|
||||
from vllm.model_executor.layers.activation import SiluAndMul
|
||||
from vllm.model_executor.layers.attention import Attention
|
||||
from vllm.model_executor.layers.layernorm import RMSNorm
|
||||
from vllm.model_executor.layers.linear import (
|
||||
ColumnParallelLinear,
|
||||
MergedColumnParallelLinear,
|
||||
QKVParallelLinear,
|
||||
RowParallelLinear,
|
||||
)
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.layers.mamba.mamba_utils import (
|
||||
MambaStateCopyFunc,
|
||||
MambaStateCopyFuncCalculator,
|
||||
MambaStateDtypeCalculator,
|
||||
MambaStateShapeCalculator,
|
||||
is_conv_state_dim_first,
|
||||
)
|
||||
from vllm.model_executor.layers.mamba.short_conv import ShortConv
|
||||
from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
from vllm.model_executor.layers.rotary_embedding.base import RotaryEmbedding
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
ParallelLMHead,
|
||||
VocabParallelEmbedding,
|
||||
)
|
||||
from vllm.model_executor.models.interfaces import (
|
||||
HasInnerState,
|
||||
IsHybrid,
|
||||
SupportsPP,
|
||||
SupportsQuant,
|
||||
)
|
||||
from vllm.model_executor.models.utils import (
|
||||
AutoWeightsLoader,
|
||||
PPMissingLayer,
|
||||
WeightsMapper,
|
||||
extract_layer_index,
|
||||
make_empty_intermediate_tensors_factory,
|
||||
make_layers,
|
||||
maybe_prefix,
|
||||
)
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.sequence import IntermediateTensors
|
||||
from vllm.v1.attention.backends.short_conv_attn import ShortConvAttentionMetadata
|
||||
|
||||
from .conv_ops import causal_conv1d_decode, causal_conv1d_prefill
|
||||
|
||||
ATTENTION_LAYER_TYPES = ("full_attention", "sliding_attention")
|
||||
|
||||
|
||||
class Lfm3RotaryEmbedding(RotaryEmbedding):
|
||||
"""Neox RoPE over the full head dim with LFM3's zero-tail partial rotation.
|
||||
|
||||
The first ``partial_rotary_factor * head_dim // 2`` frequencies follow the
|
||||
progression of the *full* head dim, the rest are zero (cos=1, sin=0). This is not
|
||||
vLLM's ``partial_rotary_factor``, which rotates a prefix with its own progression.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
head_size: int,
|
||||
max_position_embeddings: int,
|
||||
base: float,
|
||||
partial_rotary_factor: float,
|
||||
dtype: torch.dtype,
|
||||
) -> None:
|
||||
self.partial_rotary_factor = partial_rotary_factor
|
||||
super().__init__(
|
||||
head_size=head_size,
|
||||
rotary_dim=head_size,
|
||||
max_position_embeddings=max_position_embeddings,
|
||||
base=base,
|
||||
is_neox_style=True,
|
||||
dtype=dtype,
|
||||
)
|
||||
|
||||
def _compute_inv_freq(self, base: float) -> torch.Tensor:
|
||||
dim = self.head_size
|
||||
rope_angles = int(self.partial_rotary_factor * dim) // 2
|
||||
inv_freq = 1.0 / (
|
||||
base ** (torch.arange(0, 2 * rope_angles, 2, dtype=torch.float) / dim)
|
||||
)
|
||||
return torch.cat((inv_freq, torch.zeros(dim // 2 - rope_angles)))
|
||||
|
||||
|
||||
class Lfm3MLP(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_size: int,
|
||||
intermediate_size: int,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
self.w13 = MergedColumnParallelLinear(
|
||||
input_size=hidden_size,
|
||||
output_sizes=[intermediate_size] * 2,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.w13",
|
||||
)
|
||||
self.w2 = RowParallelLinear(
|
||||
input_size=intermediate_size,
|
||||
output_size=hidden_size,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.w2",
|
||||
)
|
||||
self.act_fn = SiluAndMul()
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
gate_up, _ = self.w13(x)
|
||||
x = self.act_fn(gate_up)
|
||||
x, _ = self.w2(x)
|
||||
return x
|
||||
|
||||
|
||||
class Lfm3Attention(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
config,
|
||||
layer_idx: int,
|
||||
rotary_emb: Lfm3RotaryEmbedding,
|
||||
cache_config: CacheConfig | None = None,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.layer_idx = layer_idx
|
||||
self.hidden_size = config.hidden_size
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
self.total_num_heads = config.num_attention_heads
|
||||
assert self.total_num_heads % tp_size == 0
|
||||
self.num_heads = self.total_num_heads // tp_size
|
||||
self.total_num_kv_heads = config.num_key_value_heads
|
||||
if self.total_num_kv_heads >= tp_size:
|
||||
assert self.total_num_kv_heads % tp_size == 0
|
||||
else:
|
||||
assert tp_size % self.total_num_kv_heads == 0
|
||||
self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
|
||||
self.head_dim = config.head_dim
|
||||
self.q_size = self.num_heads * self.head_dim
|
||||
self.kv_size = self.num_kv_heads * self.head_dim
|
||||
self.scaling = self.head_dim**-0.5
|
||||
|
||||
self.qkv_proj = QKVParallelLinear(
|
||||
hidden_size=self.hidden_size,
|
||||
head_size=self.head_dim,
|
||||
total_num_heads=self.total_num_heads,
|
||||
total_num_kv_heads=self.total_num_kv_heads,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.qkv_proj",
|
||||
)
|
||||
self.o_proj = RowParallelLinear(
|
||||
input_size=self.total_num_heads * self.head_dim,
|
||||
output_size=self.hidden_size,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.o_proj",
|
||||
)
|
||||
# one sigmoid gate per head; tiny, kept unquantized
|
||||
self.gate_proj = ColumnParallelLinear(
|
||||
input_size=self.hidden_size,
|
||||
output_size=self.total_num_heads,
|
||||
bias=False,
|
||||
gather_output=False,
|
||||
prefix=f"{prefix}.gate_proj",
|
||||
)
|
||||
self.q_norm = RMSNorm(self.head_dim, eps=config.norm_eps)
|
||||
self.k_norm = RMSNorm(self.head_dim, eps=config.norm_eps)
|
||||
self.rotary_emb = rotary_emb
|
||||
|
||||
is_sliding = config.layer_types[layer_idx] == "sliding_attention"
|
||||
self.attn = Attention(
|
||||
self.num_heads,
|
||||
self.head_dim,
|
||||
self.scaling,
|
||||
num_kv_heads=self.num_kv_heads,
|
||||
cache_config=cache_config,
|
||||
per_layer_sliding_window=config.sliding_window if is_sliding else None,
|
||||
prefix=f"{prefix}.attn",
|
||||
)
|
||||
|
||||
def forward(self, positions: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
n_tokens = hidden_states.shape[0]
|
||||
qkv, _ = self.qkv_proj(hidden_states)
|
||||
q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
|
||||
q = self.q_norm(q.view(n_tokens, self.num_heads, self.head_dim))
|
||||
k = self.k_norm(k.view(n_tokens, self.num_kv_heads, self.head_dim))
|
||||
q, k = self.rotary_emb(positions, q, k)
|
||||
attn_output = self.attn(
|
||||
q.reshape(n_tokens, self.q_size), k.reshape(n_tokens, self.kv_size), v
|
||||
)
|
||||
gate, _ = self.gate_proj(hidden_states)
|
||||
attn_output = attn_output.view(n_tokens, self.num_heads, self.head_dim)
|
||||
attn_output = attn_output * torch.sigmoid(gate).unsqueeze(-1)
|
||||
output, _ = self.o_proj(attn_output.view(n_tokens, self.q_size))
|
||||
return output
|
||||
|
||||
|
||||
class Lfm3ShortConv(ShortConv):
|
||||
"""vLLM ShortConv with an arbitrary-width (here 7) causal conv.
|
||||
|
||||
Only ``forward_cuda`` (used on every non-CPU platform, including XPU) is replaced;
|
||||
projections, state shape/dtype and metadata handling are inherited.
|
||||
"""
|
||||
|
||||
def forward_cuda(self, hidden_states: torch.Tensor, output: torch.Tensor):
|
||||
attn_metadata = get_forward_context().attn_metadata
|
||||
if attn_metadata is not None:
|
||||
assert isinstance(attn_metadata, dict)
|
||||
attn_metadata = attn_metadata.get(self.prefix)
|
||||
|
||||
BCx, _ = self.in_proj(hidden_states)
|
||||
B, C, x = BCx.chunk(3, dim=-1)
|
||||
|
||||
if attn_metadata is None:
|
||||
# profile run: values don't matter, shapes do
|
||||
output[: hidden_states.shape[0]], _ = self.out_proj(C * (B * x))
|
||||
return
|
||||
|
||||
assert isinstance(attn_metadata, ShortConvAttentionMetadata)
|
||||
if attn_metadata.num_accepted_tokens is not None:
|
||||
raise NotImplementedError("LFM3 short conv: speculative decoding is not supported")
|
||||
|
||||
# token-major view (num_blocks, width - 1, dim) of the conv state cache
|
||||
conv_state = self.kv_cache[0]
|
||||
if is_conv_state_dim_first():
|
||||
conv_state = conv_state.transpose(-1, -2)
|
||||
conv_weights = self.conv.weight.view(self.conv.weight.size(0), self.conv.weight.size(2))
|
||||
|
||||
num_decodes = attn_metadata.num_decode_tokens
|
||||
num_prefill_tokens = attn_metadata.num_prefill_tokens
|
||||
num_actual_tokens = num_decodes + num_prefill_tokens
|
||||
Bx = B[:num_actual_tokens] * x[:num_actual_tokens]
|
||||
Bx_d, Bx_p = torch.split(Bx, [num_decodes, num_prefill_tokens], dim=0)
|
||||
|
||||
conv_out = []
|
||||
if num_decodes > 0:
|
||||
state_indices_d = attn_metadata.state_indices_tensor_d
|
||||
if state_indices_d.dim() > 1:
|
||||
state_indices_d = state_indices_d[:, 0]
|
||||
conv_out.append(
|
||||
causal_conv1d_decode(
|
||||
Bx_d, conv_weights, self.conv.bias, conv_state,
|
||||
state_indices_d[:num_decodes],
|
||||
)
|
||||
)
|
||||
if attn_metadata.num_prefills > 0:
|
||||
conv_out.append(
|
||||
causal_conv1d_prefill(
|
||||
Bx_p, conv_weights, self.conv.bias, conv_state,
|
||||
attn_metadata.query_start_loc_p,
|
||||
attn_metadata.state_indices_tensor_p,
|
||||
attn_metadata.has_initial_states_p,
|
||||
)
|
||||
)
|
||||
y = conv_out[0] if len(conv_out) == 1 else torch.cat(conv_out, dim=0)
|
||||
output[:num_actual_tokens], _ = self.out_proj(C[:num_actual_tokens] * y)
|
||||
|
||||
|
||||
class Lfm3DecoderLayer(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
config,
|
||||
layer_idx: int,
|
||||
rotary_embs: dict[str, Lfm3RotaryEmbedding],
|
||||
model_config: ModelConfig | None = None,
|
||||
cache_config: CacheConfig | None = None,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.layer_idx = layer_idx
|
||||
self.layer_type = config.layer_types[layer_idx]
|
||||
self.is_attention_layer = self.layer_type in ATTENTION_LAYER_TYPES
|
||||
|
||||
if self.is_attention_layer:
|
||||
self.self_attn = Lfm3Attention(
|
||||
config,
|
||||
layer_idx,
|
||||
rotary_embs[self.layer_type],
|
||||
cache_config=cache_config,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.self_attn",
|
||||
)
|
||||
else:
|
||||
# HF's ".conv." is mapped to ".short_conv." (see hf_to_vllm_mapper)
|
||||
self.short_conv = Lfm3ShortConv(
|
||||
config=config,
|
||||
dim=config.hidden_size,
|
||||
layer_idx=layer_idx,
|
||||
model_config=model_config,
|
||||
cache_config=cache_config,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.short_conv",
|
||||
)
|
||||
self.feed_forward = Lfm3MLP(
|
||||
config.hidden_size,
|
||||
config.intermediate_size,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.feed_forward",
|
||||
)
|
||||
self.operator_norm = RMSNorm(config.hidden_size, eps=config.norm_eps)
|
||||
self.ffn_norm = RMSNorm(config.hidden_size, eps=config.norm_eps)
|
||||
self.use_sandwich_norm = config.use_sandwich_norm
|
||||
if self.use_sandwich_norm:
|
||||
self.post_operator_norm = RMSNorm(config.hidden_size, eps=config.norm_eps)
|
||||
self.post_ffn_norm = RMSNorm(config.hidden_size, eps=config.norm_eps)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
positions: torch.Tensor,
|
||||
hidden_states: torch.Tensor,
|
||||
residual: torch.Tensor | None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
# `hidden_states` is the previous layer's (post-normed) FFN output, not yet
|
||||
# added to `residual`; the fused add+norm performs the residual add.
|
||||
if residual is None:
|
||||
residual = hidden_states
|
||||
hidden_states = self.operator_norm(hidden_states)
|
||||
else:
|
||||
hidden_states, residual = self.operator_norm(hidden_states, residual)
|
||||
|
||||
if self.is_attention_layer:
|
||||
hidden_states = self.self_attn(positions=positions, hidden_states=hidden_states)
|
||||
else:
|
||||
output = torch.empty_like(hidden_states)
|
||||
self.short_conv(hidden_states, output)
|
||||
hidden_states = output
|
||||
if self.use_sandwich_norm:
|
||||
hidden_states = self.post_operator_norm(hidden_states)
|
||||
|
||||
hidden_states, residual = self.ffn_norm(hidden_states, residual)
|
||||
hidden_states = self.feed_forward(hidden_states)
|
||||
if self.use_sandwich_norm:
|
||||
hidden_states = self.post_ffn_norm(hidden_states)
|
||||
return hidden_states, residual
|
||||
|
||||
|
||||
@support_torch_compile
|
||||
class Lfm3Model(nn.Module):
|
||||
hf_to_vllm_mapper = WeightsMapper(
|
||||
orig_to_new_substr={".conv.": ".short_conv."},
|
||||
orig_to_new_stacked={
|
||||
".q_proj": (".qkv_proj", "q"),
|
||||
".k_proj": (".qkv_proj", "k"),
|
||||
".v_proj": (".qkv_proj", "v"),
|
||||
".w1": (".w13", 0),
|
||||
".w3": (".w13", 1),
|
||||
},
|
||||
)
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
|
||||
super().__init__()
|
||||
config = vllm_config.model_config.hf_config
|
||||
model_config = vllm_config.model_config
|
||||
cache_config = vllm_config.cache_config
|
||||
quant_config = vllm_config.quant_config
|
||||
self.config = config
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
for t in config.layer_types:
|
||||
if t not in (*ATTENTION_LAYER_TYPES, "conv"):
|
||||
raise ValueError(f"LFM3: unsupported layer type {t!r}")
|
||||
|
||||
self.embed_tokens = VocabParallelEmbedding(
|
||||
self.vocab_size, config.hidden_size, org_num_embeddings=config.vocab_size
|
||||
)
|
||||
|
||||
# one RoPE (cos/sin cache) per attention layer type, shared by its layers
|
||||
rotary_embs: dict[str, Lfm3RotaryEmbedding] = {}
|
||||
for layer_type in sorted(set(config.layer_types) & set(ATTENTION_LAYER_TYPES)):
|
||||
rope = config.rope_parameters[layer_type]
|
||||
if rope.get("rope_type", "default") != "default":
|
||||
raise NotImplementedError(f"LFM3: rope_type {rope['rope_type']!r}")
|
||||
rotary_embs[layer_type] = Lfm3RotaryEmbedding(
|
||||
head_size=config.head_dim,
|
||||
max_position_embeddings=model_config.max_model_len,
|
||||
base=rope["rope_theta"],
|
||||
partial_rotary_factor=rope.get("partial_rotary_factor", 1.0),
|
||||
dtype=torch.get_default_dtype(),
|
||||
)
|
||||
|
||||
def get_layer(prefix: str):
|
||||
layer_idx = extract_layer_index(prefix)
|
||||
return Lfm3DecoderLayer(
|
||||
config,
|
||||
layer_idx,
|
||||
rotary_embs,
|
||||
model_config,
|
||||
cache_config,
|
||||
quant_config=quant_config,
|
||||
prefix=prefix,
|
||||
)
|
||||
|
||||
self.start_layer, self.end_layer, self.layers = make_layers(
|
||||
config.num_hidden_layers, get_layer, prefix=f"{prefix}.layers"
|
||||
)
|
||||
self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory(
|
||||
["hidden_states", "residual"], config.hidden_size
|
||||
)
|
||||
# despite its name, LFM3's `embedding_norm` is the final norm after the last layer
|
||||
if get_pp_group().is_last_rank:
|
||||
self.embedding_norm = RMSNorm(config.hidden_size, eps=config.norm_eps)
|
||||
else:
|
||||
self.embedding_norm = PPMissingLayer()
|
||||
|
||||
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||
return self.embed_tokens(input_ids)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor | None,
|
||||
positions: torch.Tensor,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
) -> torch.Tensor | IntermediateTensors:
|
||||
if get_pp_group().is_first_rank:
|
||||
if inputs_embeds is not None:
|
||||
hidden_states = inputs_embeds
|
||||
else:
|
||||
hidden_states = self.embed_input_ids(input_ids)
|
||||
residual = None
|
||||
else:
|
||||
assert intermediate_tensors is not None
|
||||
hidden_states = intermediate_tensors["hidden_states"]
|
||||
residual = intermediate_tensors["residual"]
|
||||
|
||||
for layer in islice(self.layers, self.start_layer, self.end_layer):
|
||||
hidden_states, residual = layer(
|
||||
positions=positions, hidden_states=hidden_states, residual=residual
|
||||
)
|
||||
if not get_pp_group().is_last_rank:
|
||||
return IntermediateTensors({"hidden_states": hidden_states, "residual": residual})
|
||||
hidden_states, _ = self.embedding_norm(hidden_states, residual)
|
||||
return hidden_states
|
||||
|
||||
|
||||
class Lfm3ForCausalLM(nn.Module, HasInnerState, SupportsPP, IsHybrid, SupportsQuant):
|
||||
packed_modules_mapping = {
|
||||
"qkv_proj": ["q_proj", "k_proj", "v_proj"],
|
||||
"w13": ["w1", "w3"],
|
||||
"in_proj": ["in_proj"],
|
||||
}
|
||||
hf_to_vllm_mapper = Lfm3Model.hf_to_vllm_mapper
|
||||
|
||||
@classmethod
|
||||
def get_mamba_state_dtype_from_config(cls, vllm_config: VllmConfig) -> tuple[torch.dtype, ...]:
|
||||
return MambaStateDtypeCalculator.short_conv_state_dtype(
|
||||
vllm_config.model_config.dtype,
|
||||
vllm_config.cache_config.mamba_cache_dtype,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_mamba_state_shape_from_config(cls, vllm_config: VllmConfig) -> tuple[tuple[int, int]]:
|
||||
hf_config = vllm_config.model_config.hf_config
|
||||
return MambaStateShapeCalculator.short_conv_state_shape(
|
||||
tp_world_size=vllm_config.parallel_config.tensor_parallel_size,
|
||||
intermediate_size=hf_config.hidden_size,
|
||||
conv_kernel=hf_config.conv_L_cache,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_mamba_state_copy_func(cls) -> tuple[MambaStateCopyFunc]:
|
||||
return MambaStateCopyFuncCalculator.short_conv_state_copy_func()
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
|
||||
super().__init__()
|
||||
config = vllm_config.model_config.hf_config
|
||||
quant_config = vllm_config.quant_config
|
||||
self.config = config
|
||||
self.model = Lfm3Model(vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model"))
|
||||
|
||||
if get_pp_group().is_last_rank:
|
||||
self.lm_head = ParallelLMHead(
|
||||
config.vocab_size,
|
||||
config.hidden_size,
|
||||
quant_config=quant_config,
|
||||
prefix=maybe_prefix(prefix, "lm_head"),
|
||||
)
|
||||
if config.tie_word_embeddings:
|
||||
self.lm_head = self.lm_head.tie_weights(self.model.embed_tokens)
|
||||
else:
|
||||
self.lm_head = PPMissingLayer()
|
||||
|
||||
self.logits_processor = LogitsProcessor(config.vocab_size)
|
||||
self.make_empty_intermediate_tensors = self.model.make_empty_intermediate_tensors
|
||||
|
||||
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||
return self.model.embed_input_ids(input_ids)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor | None,
|
||||
positions: torch.Tensor,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
**kwargs,
|
||||
) -> torch.Tensor | IntermediateTensors:
|
||||
return self.model(input_ids, positions, intermediate_tensors, inputs_embeds)
|
||||
|
||||
def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
return self.logits_processor(self.lm_head, hidden_states)
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
# Unknown checkpoint names make AutoWeightsLoader raise; missing ones are
|
||||
# checked below. `lm_head` is tied to `embed_tokens` and not in the checkpoint.
|
||||
loader = AutoWeightsLoader(self)
|
||||
loaded = loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
|
||||
|
||||
# tied lm_head.weight is deduplicated into model.embed_tokens.weight here
|
||||
missing = sorted({name for name, _ in self.named_parameters()} - loaded)
|
||||
if missing:
|
||||
raise ValueError(
|
||||
f"LFM3: {len(missing)} parameters not found in checkpoint: {missing[:20]}"
|
||||
)
|
||||
return loaded
|
||||
Reference in new issue
Block a user