Files
Pascal LinxweilerandClaude Opus 5.5 4e7a7ce903 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>
2026-10-28 22:06:44 +01:00

225 lines
10 KiB
Python

"""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)