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:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-28 22:06:44 +01:00
commit 4e7a7ce903
26 files changed
+21423

No files matched your search

+117
View File
@@ -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()
+30
View File
@@ -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)}")
+15
View File
@@ -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")
+224
View File
@@ -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)
+191
View File
@@ -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)
+173
View File
@@ -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)