lfm3: online FP8 (W8A16) support, graph-mode and FP8 benchmarks
- load_weights: run the strict missing-parameter check only for unquantized models; vLLM's loader checks quantized ones and knows the params a checkpoint cannot carry (online-FP8 weight_scale). BF16 output unchanged. - tests: variant launcher, greedy and quality comparisons, BetterBench table + ITL 1% low recompute, Discord notify helper. - NOTES: round 2 (eager vs default vs FULL_DECODE_ONLY, default kept) and round 3 (FP8 W8A16: +49% decode, +35% @8, answers unchanged); llama-swap snippet now FP8. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4e7a7ce903
commit
3b85c03761
29 files changed
+87117
-18
No files matched your search
Executable
+22
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env bash
|
||||
# Render BetterBench results.json files and pull the headline metrics into one markdown table.
|
||||
# tests/bb_table.sh LABEL=path/results.json ...
|
||||
# Columns follow BetterBench's own report: combined decode / ITL 1% low / TTFT p50, concurrency
|
||||
# level-8 aggregate, prefill median at target depth 32000. Bandwidth = 3.47 GB x decode t/s.
|
||||
cd "$(dirname "$0")/.."
|
||||
echo "| variant | decode t/s | eff. bandwidth | ITL 1% low t/s | TTFT p50 ms | aggregate @8 t/s | prefill @32k t/s |"
|
||||
echo "|---|--:|--:|--:|--:|--:|--:|"
|
||||
for arg in "$@"; do
|
||||
label=${arg%%=*}; f=${arg#*=}
|
||||
BETTERBENCH_HOME=$PWD/.betterbench .venv-bench/bin/betterbench report "$f" 2>/dev/null | python3 -c '
|
||||
import re, sys
|
||||
t = sys.stdin.read(); label = sys.argv[1]
|
||||
m = re.search(r"decode t/s median ≈ \*\*([\d.]+)\*\*, ITL 1%-low ≈ \*\*([\d.]+) t/s\*\*, TTFT p50 ≈ \*\*([\d.]+) ms", t)
|
||||
c8 = re.search(r"^\| 8 \| [^|]+\| ([\d.]+) \|", t, re.M)
|
||||
p32 = re.search(r"^\| 32000 \|(?:[^|]+\|){3} ([\d.]+) \|", t, re.M)
|
||||
na = "—"
|
||||
cell = lambda x, i=1: x.group(i) if x else na
|
||||
bw = "%.0f GB/s (%.0f%%)" % (3.47 * float(m.group(1)), 3.47 * float(m.group(1)) / 6.08) if m else na
|
||||
print(f"| {label} | {cell(m)} | {bw} | {cell(m, 2)} | {cell(m, 3)} | {cell(c8)} | {cell(p32)} |")
|
||||
' "$label"
|
||||
done
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Greedy-decode 64 tokens for the ref_compare prompts (token ids in results/ref_prompts.json) on a running server and save them;
|
||||
optionally compare with another variant's saved run (normally the eager one).
|
||||
At the first differing token, prints the reference run's top-2 logprob margin there, so
|
||||
near-ties (bf16 noise) can be told apart from real divergence.
|
||||
|
||||
python3 tests/greedy_variant.py PORT OUT.json [REF.json] [--concurrent]
|
||||
"""
|
||||
import json, sys, urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
args = [a for a in sys.argv[1:] if not a.startswith("--")]
|
||||
port, out_path = int(args[0]), args[1]
|
||||
ref_path = args[2] if len(args) > 2 else None
|
||||
prompts = {k: v["prompt_ids"] for k, v in json.load(open("results/ref_prompts.json"))["results"].items()}
|
||||
N = 64
|
||||
|
||||
def gen(item):
|
||||
name, ids = item
|
||||
body = {"model": "lfm3-1.7b", "prompt": ids, "max_tokens": N, "temperature": 0.0,
|
||||
"repetition_penalty": 1.0, "ignore_eos": True, "logprobs": 2,
|
||||
"return_tokens_as_token_ids": True}
|
||||
req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/completions", json.dumps(body).encode(),
|
||||
{"Content-Type": "application/json"})
|
||||
lp = json.loads(urllib.request.urlopen(req, timeout=600).read())["choices"][0]["logprobs"]
|
||||
toks = [int(t.split(":")[1]) for t in lp["tokens"]]
|
||||
margins = [v[0] - v[1] if len(v) > 1 else None
|
||||
for v in (sorted(top.values(), reverse=True) for top in lp["top_logprobs"])]
|
||||
return name, {"tokens": toks, "margins": margins}
|
||||
|
||||
workers = len(prompts) if "--concurrent" in sys.argv else 1
|
||||
with ThreadPoolExecutor(workers) as ex:
|
||||
res = dict(ex.map(gen, prompts.items()))
|
||||
json.dump(res, open(out_path, "w"))
|
||||
|
||||
if ref_path:
|
||||
ref = json.load(open(ref_path))
|
||||
total = 0
|
||||
for name, r in res.items():
|
||||
want = ref[name]["tokens"]
|
||||
same = next((i for i, (a, b) in enumerate(zip(r["tokens"], want)) if a != b), len(want))
|
||||
total += same == len(want)
|
||||
note = "" if same == len(want) else f" (ref top-2 margin at pos {same}: {ref[name]['margins'][same]:.3f})"
|
||||
print(f"{name:<15} identical prefix {same}/{len(want)}{note}")
|
||||
print(f"{total}/{len(res)} prompts identical for all {N} tokens")
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Recompute BetterBench's combined 'ITL 1% low' (t/s) for runs where BetterBench dropped it
|
||||
because one stream update carried >1 token (it then shows 'update p99' instead). Uses
|
||||
BetterBench's own functions (metrics.itl_to_rate_samples + summarize(rate_like=True)) per
|
||||
category, weighted with the run's config weights, ignoring only the 'batched' flag.
|
||||
.venv-bench/bin/python tests/itl_low.py results.json ...
|
||||
"""
|
||||
import json, sys
|
||||
from betterbench.metrics import itl_to_rate_samples, summarize
|
||||
for f in sys.argv[1:]:
|
||||
d = json.load(open(f)); w = d["config"]["weights"]
|
||||
per = {c: summarize(itl_to_rate_samples([g for r in runs if r["ok"] for g in r["update_gaps_ms"]]),
|
||||
rate_like=True).low_1pct for c, runs in d["single_stream"].items()}
|
||||
comb = sum(w[c] * per[c] for c in w) / sum(w.values())
|
||||
print(f"{comb:.1f}\t{f}")
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
# Post a message to the Discord webhook stored in ./.discord_webhook (not committed).
|
||||
# tests/notify.sh "text" (max 2000 chars per Discord message)
|
||||
cd "$(dirname "$0")/.."
|
||||
python3 -c 'import json,sys; print(json.dumps({"username": "Claude (lfm3-vllm-port)", "content": sys.argv[1][:2000]}))' "$1" |
|
||||
curl -sS -o /dev/null -w '%{http_code}\n' -H 'Content-Type: application/json' -d @- "$(cat .discord_webhook)"
|
||||
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Greedy chat decode of 5 varied prompts (math, code, German, tool call, summary) on a running
|
||||
server; saves tokens + text. With REF.json, compares token by token and prints the first
|
||||
divergence (with the reference's top-2 margin there) and both final answers.
|
||||
|
||||
python3 tests/quality_prompts.py PORT OUT.json [REF.json]
|
||||
"""
|
||||
import json, sys, urllib.request
|
||||
|
||||
port, out_path = int(sys.argv[1]), sys.argv[2]
|
||||
ref_path = sys.argv[3] if len(sys.argv) > 3 else None
|
||||
|
||||
WEATHER_TOOL = {"type": "function", "function": {
|
||||
"name": "get_weather", "description": "Get the current weather for a city.",
|
||||
"parameters": {"type": "object", "properties": {"city": {"type": "string"},
|
||||
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}},
|
||||
"required": ["city"]}}}
|
||||
PROMPTS = {
|
||||
"math": {"messages": [{"role": "user", "content":
|
||||
"A train leaves at 09:40 and arrives at 13:15. It stops twice for 7 minutes each. "
|
||||
"How many minutes is it actually moving? Answer with the number."}]},
|
||||
"code": {"messages": [{"role": "user", "content":
|
||||
"Write a Python function is_palindrome(s) that ignores case and non-alphanumeric "
|
||||
"characters. Only the code."}]},
|
||||
"german": {"messages": [{"role": "user", "content":
|
||||
"Erkläre in zwei Sätzen, warum der Himmel blau ist. Antworte auf Deutsch."}]},
|
||||
"tool_call": {"messages": [{"role": "user", "content":
|
||||
"What's the weather in Hamburg right now, in celsius?"}], "tools": [WEATHER_TOOL]},
|
||||
"summary": {"messages": [{"role": "user", "content":
|
||||
"Summarize in one sentence: The city council voted 7 to 2 on Tuesday to convert the "
|
||||
"old freight depot into a public library and community workshop. Construction starts "
|
||||
"next spring and is funded by a state grant of 4.2 million euros plus 800,000 euros "
|
||||
"from the city budget. Opponents argued the site should be sold to reduce debt."}]},
|
||||
}
|
||||
|
||||
def run(name, p):
|
||||
body = {"model": "lfm3-1.7b", "max_tokens": 1500, "temperature": 0.0,
|
||||
"repetition_penalty": 1.0, "logprobs": True, "top_logprobs": 2, **p}
|
||||
req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions",
|
||||
json.dumps(body).encode(), {"Content-Type": "application/json"})
|
||||
r = json.loads(urllib.request.urlopen(req, timeout=600).read())
|
||||
c = r["choices"][0]; m = c["message"]
|
||||
lp = (c.get("logprobs") or {}).get("content") or []
|
||||
return {"tokens": [t["token"] for t in lp],
|
||||
"margins": [(t["top_logprobs"][0]["logprob"] - t["top_logprobs"][1]["logprob"])
|
||||
if len(t["top_logprobs"]) > 1 else None for t in lp],
|
||||
"reasoning": m.get("reasoning"), "content": m.get("content"),
|
||||
"tool_calls": [tc["function"] for tc in (m.get("tool_calls") or [])],
|
||||
"finish_reason": c["finish_reason"], "completion_tokens": r["usage"]["completion_tokens"]}
|
||||
|
||||
res = {name: run(name, p) for name, p in PROMPTS.items()}
|
||||
json.dump(res, open(out_path, "w"), ensure_ascii=False, indent=1)
|
||||
|
||||
def answer(r):
|
||||
return json.dumps(r["tool_calls"], ensure_ascii=False) if r["tool_calls"] else (r["content"] or "").strip()
|
||||
|
||||
if ref_path:
|
||||
ref = json.load(open(ref_path))
|
||||
for name, r in res.items():
|
||||
a, b = ref[name]["tokens"], r["tokens"]
|
||||
div = next((i for i, (x, y) in enumerate(zip(a, b)) if x != y), None)
|
||||
if div is None and len(a) == len(b):
|
||||
print(f"== {name}: identical ({len(a)} tokens)")
|
||||
else:
|
||||
div = div if div is not None else min(len(a), len(b))
|
||||
mg = ref[name]["margins"][div] if div < len(ref[name]["margins"]) else None
|
||||
print(f"== {name}: diverges at token {div}/{len(a)} (ref top-2 margin {mg if mg is None else round(mg, 3)}); "
|
||||
f"ref {a[div:div+1]} vs new {b[div:div+1]}")
|
||||
print(f" ref answer: {answer(ref[name])[:300]!r}")
|
||||
print(f" new answer: {answer(r)[:300]!r}")
|
||||
Executable
+43
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env bash
|
||||
# Start one LFM3 vLLM variant on a test port, wait until ready, record startup time + VRAM.
|
||||
# tests/variant.sh NAME [--fresh] [extra vllm args...]
|
||||
# Container: lfm3-var-NAME on 127.0.0.1:${PORT:-8001}; image ${IMAGE:-lfm3-vllm-xpu:v0.32.0-lfm3};
|
||||
# compile cache: ./.cache/NAME (--fresh wipes it; files are root-owned, so via the container).
|
||||
# Writes logs/variant_NAME.log (server log) and appends one line to results/variants_startup.tsv.
|
||||
# Stop with: docker stop lfm3-var-NAME
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
NAME=$1; shift
|
||||
PORT=${PORT:-8001}
|
||||
IMAGE=${IMAGE:-lfm3-vllm-xpu:v0.32.0-lfm3}
|
||||
CACHE=$PWD/.cache/$NAME
|
||||
if [[ "${1:-}" == "--fresh" ]]; then
|
||||
shift
|
||||
[[ -d "$CACHE" ]] && docker run --rm -v "$CACHE":/c --entrypoint find "$IMAGE" /c -mindepth 1 -delete
|
||||
fi
|
||||
mkdir -p "$CACHE" logs results
|
||||
|
||||
t0=$(date +%s.%N)
|
||||
docker run -d --rm --name "lfm3-var-$NAME" \
|
||||
--device /dev/dri --group-add 991 --ipc=host --shm-size=16g \
|
||||
-p 127.0.0.1:${PORT}:8000 \
|
||||
-v /dev/dri:/dev/dri -v /dev/dri/by-path:/dev/dri/by-path:ro \
|
||||
-v /models/LFM3-1.7B:/model:ro \
|
||||
-v "$CACHE":/root/.cache/vllm \
|
||||
-e HF_HUB_OFFLINE=1 -e TRANSFORMERS_OFFLINE=1 \
|
||||
"$IMAGE" /model --host=0.0.0.0 --port=8000 --served-model-name=lfm3-1.7b \
|
||||
--gpu-memory-utilization=0.5 --dtype=bfloat16 --max-model-len=32768 \
|
||||
--enable-auto-tool-choice --tool-call-parser=qwen3_coder --reasoning-parser=qwen3 \
|
||||
"$@" >/dev/null
|
||||
docker logs -f "lfm3-var-$NAME" > "logs/variant_$NAME.log" 2>&1 &
|
||||
|
||||
until curl -sf "127.0.0.1:${PORT}/v1/models" >/dev/null; do
|
||||
if ! docker inspect "lfm3-var-$NAME" >/dev/null 2>&1; then
|
||||
echo "$NAME: container exited during startup (see logs/variant_$NAME.log)"; exit 1
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
t=$(echo "$(date +%s.%N) - $t0" | bc)
|
||||
vram=$(xpu-smi stats -d 0 | sed -n 's/.*GPU Memory Used (MiB).*current: \([0-9]*\).*/\1/p')
|
||||
printf '%s\t%s\t%.0f\t%s\t%s\n' "$(date +%FT%T)" "$NAME" "$t" "$vram" "$*" >> results/variants_startup.tsv
|
||||
echo "$NAME ready in ${t%.*} s, VRAM used ${vram} MiB"
|
||||
Reference in new issue
Block a user