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

192 lines
7.6 KiB
Python

#!/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)