lfm3: add INT4, FP8 per-channel and VL notes, tests, eval and results
Sync the repo with the working directory: full NOTES.md (rounds 4-5, LFM3-VL), VL tests and test images, quality eval, AutoRound W4A16 quantization scripts and calibration recipe, the variant.sh MODEL/DOCKER_ENV options, and the remaining benchmark results. Large regenerable artifacts (INT4 checkpoint, ref_vl.pt, raw logprob dumps) stay out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0412bb1f72
commit
1834792bb8
67 files changed
+119589
-9
No files matched your search
@@ -2,14 +2,15 @@
|
||||
# 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).
|
||||
# model dir ${MODEL:-/models/LFM3-1.7B}; 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
|
||||
# Extra docker env: DOCKER_ENV="-e K=V ...". 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}
|
||||
MODEL=${MODEL:-/models/LFM3-1.7B}
|
||||
CACHE=$PWD/.cache/$NAME
|
||||
if [[ "${1:-}" == "--fresh" ]]; then
|
||||
shift
|
||||
@@ -22,9 +23,9 @@ 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 "$MODEL":/model:ro \
|
||||
-v "$CACHE":/root/.cache/vllm \
|
||||
-e HF_HUB_OFFLINE=1 -e TRANSFORMERS_OFFLINE=1 \
|
||||
-e HF_HUB_OFFLINE=1 -e TRANSFORMERS_OFFLINE=1 ${DOCKER_ENV:-} \
|
||||
"$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 \
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env python3
|
||||
"""OpenAI-API tests against a served lfm3-vl-2b: image by http URL, two images, base64 data URL
|
||||
(what Open WebUI sends), text only, image + tool call, and the rejections (video, > 4 images).
|
||||
|
||||
python3 tests/vl/api_test.py PORT LABEL [IMAGE_BASE_URL] -> results/vl/api_LABEL.json
|
||||
IMAGE_BASE_URL: where tests/vl/images is served over http for the server (default http://172.17.0.1:8765).
|
||||
"""
|
||||
import base64, json, sys, time, urllib.error, urllib.request
|
||||
|
||||
port, label = int(sys.argv[1]), sys.argv[2]
|
||||
base = sys.argv[3] if len(sys.argv) > 3 else "http://172.17.0.1:8765"
|
||||
URL = f"http://127.0.0.1:{port}/v1/chat/completions"
|
||||
IMG = "tests/vl/images"
|
||||
|
||||
|
||||
def data_url(path, mime):
|
||||
return f"data:{mime};base64," + base64.b64encode(open(f"{IMG}/{path}", "rb").read()).decode()
|
||||
|
||||
|
||||
def img(url):
|
||||
return {"type": "image_url", "image_url": {"url": url}}
|
||||
|
||||
|
||||
def chat(content, max_tokens=4096, tools=None, expect_error=False):
|
||||
# no sampling params: the server applies the checkpoint's generation_config.json
|
||||
# (temperature 0.1, top_k 50, repetition_penalty 1.1), as for an Open WebUI request; fixed seed
|
||||
body = {"model": "lfm3-vl-2b", "messages": [{"role": "user", "content": content}],
|
||||
"max_tokens": max_tokens, "seed": 0}
|
||||
if tools:
|
||||
body["tools"] = tools
|
||||
req = urllib.request.Request(URL, json.dumps(body).encode(), {"Content-Type": "application/json"})
|
||||
t0 = time.time()
|
||||
try:
|
||||
r = json.loads(urllib.request.urlopen(req, timeout=600).read())
|
||||
except urllib.error.HTTPError as e:
|
||||
return {"http_status": e.code, "error": json.loads(e.read()).get("error", {}).get("message", "")[:400],
|
||||
"expected_error": expect_error}
|
||||
m = r["choices"][0]["message"]
|
||||
return {"http_status": 200, "expected_error": expect_error, "seconds": round(time.time() - t0, 2),
|
||||
"prompt_tokens": r["usage"]["prompt_tokens"], "completion_tokens": r["usage"]["completion_tokens"],
|
||||
"finish_reason": r["choices"][0]["finish_reason"], "content": m.get("content"),
|
||||
"reasoning": (m.get("reasoning") or "")[:600],
|
||||
"tool_calls": [tc["function"] for tc in (m.get("tool_calls") or [])]}
|
||||
|
||||
|
||||
TOOLS = [{"type": "function", "function": {
|
||||
"name": "search_web", "description": "Search the web.",
|
||||
"parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}}]
|
||||
|
||||
TESTS = {
|
||||
"one_image_url": lambda: chat([img(f"{base}/photo.jpeg"),
|
||||
{"type": "text", "text": "Which newspaper is this and what is the main headline?"}]),
|
||||
"two_images": lambda: chat([img(f"{base}/photo.jpeg"), img(f"{base}/wide_strip.png"),
|
||||
{"type": "text", "text": "Describe the first image in one sentence and the second image in one sentence."}]),
|
||||
"base64_data_url": lambda: chat([{"type": "text", "text": "What kind of document is this? What are the column headers of the first table?"},
|
||||
img(data_url("screenshot.png", "image/png"))]),
|
||||
"text_only": lambda: chat("What is the capital of Australia? Answer in one sentence."),
|
||||
"image_tool_call": lambda: chat([img(data_url("photo.jpeg", "image/jpeg")),
|
||||
{"type": "text", "text": "Find out more about the newspaper in this image: search the web for its name."}],
|
||||
tools=TOOLS),
|
||||
"video_rejected": lambda: chat([{"type": "video_url", "video_url": {"url": f"{base}/clip.mp4"}},
|
||||
{"type": "text", "text": "What happens?"}], expect_error=True),
|
||||
"five_images_rejected": lambda: chat([img(data_url("small.png", "image/png"))] * 5 +
|
||||
[{"type": "text", "text": "How many images?"}], expect_error=True),
|
||||
}
|
||||
|
||||
out = {}
|
||||
for name, fn in TESTS.items():
|
||||
out[name] = fn()
|
||||
r = out[name]
|
||||
ok = (r["http_status"] != 200) == r["expected_error"]
|
||||
print(f"{'OK ' if ok else 'BAD'} {name}: status {r['http_status']}"
|
||||
+ (f", {r['prompt_tokens']} prompt tok, {r['completion_tokens']} out, {r['seconds']} s, finish {r['finish_reason']}"
|
||||
if r["http_status"] == 200 else f": {r['error'][:200]}"), flush=True)
|
||||
if r["http_status"] == 200:
|
||||
print(" content:", repr((r["content"] or "")[:300]), "| tool_calls:", r["tool_calls"], flush=True)
|
||||
json.dump(out, open(f"results/vl/api_{label}.json", "w"), indent=1, ensure_ascii=False)
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Plugin's vendored processor (no trust_remote_code) vs Liquid's remote processor: same ids + pixels.
|
||||
python3 check_processor.py mine|ref OUT.pt (run each in its own process; 'ref' does not import the plugin)"""
|
||||
import sys, torch, numpy as np
|
||||
from PIL import Image
|
||||
from transformers import AutoProcessor
|
||||
which, out = sys.argv[1], sys.argv[2]
|
||||
if which == "mine":
|
||||
import vllm_lfm3
|
||||
vllm_lfm3.register()
|
||||
proc = AutoProcessor.from_pretrained("/vl", trust_remote_code=(which == "ref"))
|
||||
print(which, type(proc).__module__, type(proc.image_processor).__module__)
|
||||
rng = np.random.default_rng(0)
|
||||
res = {}
|
||||
for (w, h) in [(640, 480), (100, 60), (2400, 400), (1024, 1024), (1920, 1080)]:
|
||||
img = Image.fromarray(rng.integers(0, 255, (h, w, 3), dtype=np.uint8))
|
||||
msgs = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "hi"}]}]
|
||||
text = proc.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
|
||||
res[(w, h)] = dict(proc(text=text, images=[img], return_tensors="pt"))
|
||||
torch.save(res, out)
|
||||
if which == "mine":
|
||||
ref = torch.load(out.replace("mine", "ref"))
|
||||
for k, a in res.items():
|
||||
b = ref[k]
|
||||
print(k, "grid", a["image_grid_thw"].tolist(), "image tokens", int((a["input_ids"] == 125030).sum()),
|
||||
"ids equal", torch.equal(a["input_ids"], b["input_ids"]), "pixels equal", torch.equal(a["pixel_values"], b["pixel_values"]))
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env python3
|
||||
"""vLLM (our plugin, XPU, BF16) vs the Transformers reference from ref_vl.py.
|
||||
Per case: image-token count + prompt ids, vision tower / projector max abs diff (on the reference's
|
||||
own pixel_values), first-token top-20 logprobs, 64 greedy tokens (first divergence + top-2 margin
|
||||
of the reference there).
|
||||
|
||||
python3 check_vl.py MODEL_DIR IMAGES_DIR REF.pt OUT.json [extra LLM kwargs as JSON]
|
||||
"""
|
||||
import json, os, sys
|
||||
import torch
|
||||
from PIL import Image
|
||||
from vllm import LLM, SamplingParams
|
||||
|
||||
os.environ.setdefault("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
|
||||
def main():
|
||||
model_dir, img_dir, ref_path, out = sys.argv[1:5]
|
||||
extra = json.loads(sys.argv[5]) if len(sys.argv) > 5 else {}
|
||||
ref = torch.load(ref_path, weights_only=False)
|
||||
FILES = {"photo": "photo.jpeg", "screenshot": "screenshot.png", "small": "small.png", "wide": "wide_strip.png"}
|
||||
|
||||
llm = LLM(model=model_dir, dtype="bfloat16", max_model_len=8192, gpu_memory_utilization=0.4,
|
||||
limit_mm_per_prompt={"image": 4}, **{"enforce_eager": True, **extra})
|
||||
sp = SamplingParams(max_tokens=64, temperature=0.0, logprobs=20, repetition_penalty=1.0)
|
||||
|
||||
|
||||
def encoder_outputs(llm, pv, grid):
|
||||
def run(model):
|
||||
dev = next(model.parameters()).device
|
||||
with torch.no_grad():
|
||||
vis = model.vision_tower(pv.to(dev), grid.tolist())
|
||||
proj = model.multi_modal_projector(vis)
|
||||
path = "/tmp/lfm3_vl_enc.pt" # the worker shares the container's /tmp
|
||||
torch.save((vis.float().cpu(), proj.float().cpu()), path)
|
||||
return path
|
||||
# tensors don't survive the RPC's msgpack serialization intact: hand them over as a file
|
||||
return torch.load(llm.apply_model(run)[0])
|
||||
|
||||
|
||||
report = {}
|
||||
for name, r in ref.items():
|
||||
mm = {"image": Image.open(f"{img_dir}/{FILES[name]}").convert("RGB")} if name in FILES else None
|
||||
prompt = {"prompt": r["text"], **({"multi_modal_data": mm} if mm else {})}
|
||||
o = llm.generate([prompt], sp)[0]
|
||||
ids = list(o.prompt_token_ids)
|
||||
ref_ids = r["input_ids"].tolist()
|
||||
rep = {"prompt_ids_equal": ids == ref_ids, "n_image_tokens": ids.count(125030),
|
||||
"ref_n_image_tokens": ref_ids.count(125030), "prompt_len": len(ids)}
|
||||
if mm:
|
||||
vis, proj = encoder_outputs(llm, r["pixel_values"], r["image_grid_thw"])
|
||||
for key, mine, theirs in (("vision", vis, r["vision_out"]), ("projector", proj, r["proj_out"])):
|
||||
d = (mine - theirs.float()).abs()
|
||||
rep[f"{key}_max_abs_diff"] = float(d.max())
|
||||
rep[f"{key}_mean_abs_diff"] = float(d.mean())
|
||||
rep[f"{key}_ref_absmax"] = float(theirs.abs().max())
|
||||
rep[f"{key}_cos_min"] = float(torch.nn.functional.cosine_similarity(mine, theirs.float(), dim=-1).min())
|
||||
# first-token top-20 logprobs vs reference
|
||||
first = o.outputs[0].logprobs[0]
|
||||
top_vals, top_ids = r["first_top20"]
|
||||
diffs = [abs(first[t].logprob - v) for t, v in zip(top_ids.tolist(), top_vals.tolist()) if t in first]
|
||||
rep["first_tok_top20_overlap"] = len(diffs)
|
||||
rep["first_tok_logprob_max_abs_diff"] = max(diffs) if diffs else None
|
||||
gen = list(o.outputs[0].token_ids)
|
||||
ref_gen = r["gen_ids"].tolist()
|
||||
div = next((i for i, (a, b) in enumerate(zip(gen, ref_gen)) if a != b), None)
|
||||
rep["greedy_identical"] = gen == ref_gen
|
||||
rep["first_divergence"] = div
|
||||
if div is not None:
|
||||
lp = o.outputs[0].logprobs[div]
|
||||
top2 = sorted(lp.values(), key=lambda x: -x.logprob)[:2]
|
||||
rep["vllm_top2_margin_at_div"] = top2[0].logprob - top2[1].logprob
|
||||
rep["text"] = o.outputs[0].text
|
||||
rep["ref_text"] = r["gen_text"]
|
||||
report[name] = rep
|
||||
print(name, json.dumps({k: v for k, v in rep.items() if "text" not in k}), flush=True)
|
||||
|
||||
# mixed-size batch through the encoder (varlen attention, per-frame conv) == one image at a time
|
||||
names = [n for n in ref if "pixel_values" in ref[n]]
|
||||
pv = torch.cat([ref[n]["pixel_values"] for n in names])
|
||||
grid = torch.cat([ref[n]["image_grid_thw"] for n in names])
|
||||
_, proj_batch = encoder_outputs(llm, pv, grid)
|
||||
singles = torch.cat([encoder_outputs(llm, ref[n]["pixel_values"], ref[n]["image_grid_thw"])[1] for n in names])
|
||||
report["batched_vs_single_projector_max_abs_diff"] = float((proj_batch - singles).abs().max())
|
||||
cos = torch.nn.functional.cosine_similarity(proj_batch, singles, dim=-1)
|
||||
sizes = [int(ref[n]["image_grid_thw"].prod()) // 4 for n in names]
|
||||
report["batched_vs_single_per_image"] = {
|
||||
n: {"cos_min": float(c.min()), "cos_mean": float(c.mean())} for n, c in zip(names, cos.split(sizes))}
|
||||
print("batched vs single:", report["batched_vs_single_projector_max_abs_diff"],
|
||||
report["batched_vs_single_per_image"], flush=True)
|
||||
json.dump(report, open(out, "w"), indent=1, ensure_ascii=False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Image cost split: CPU preprocessing (Liquid's processor, vendored) and XPU vision tower + projector
|
||||
(our plugin inside a vLLM engine, via LLM.apply_model, synchronized), per image size.
|
||||
|
||||
python3 encoder_timing.py MODEL_DIR IMAGE OUT.json
|
||||
"""
|
||||
import json, statistics, sys, time
|
||||
import torch
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def main():
|
||||
from vllm import LLM
|
||||
from transformers import AutoProcessor
|
||||
import vllm_lfm3
|
||||
|
||||
model_dir, image, out = sys.argv[1:4]
|
||||
vllm_lfm3.register()
|
||||
proc = AutoProcessor.from_pretrained(model_dir)
|
||||
src = Image.open(image).convert("RGB")
|
||||
sizes = {"512x512": (512, 512), "1024x768": (1024, 768), "1024x1024": (1024, 1024),
|
||||
"1920x1080": (1920, 1080), "2048x2048": (2048, 2048)}
|
||||
llm = LLM(model=model_dir, dtype="bfloat16", max_model_len=8192, gpu_memory_utilization=0.4,
|
||||
limit_mm_per_prompt={"image": 4}, enforce_eager=True)
|
||||
res = {}
|
||||
for name, size in sizes.items():
|
||||
im = src.resize(size, Image.BICUBIC)
|
||||
cpu = []
|
||||
for _ in range(5):
|
||||
t0 = time.perf_counter()
|
||||
x = proc.image_processor(images=[im], return_tensors="pt")
|
||||
cpu.append((time.perf_counter() - t0) * 1000)
|
||||
pv, grid = x["pixel_values"], x["image_grid_thw"]
|
||||
|
||||
def run(model, pv=pv, grid=grid):
|
||||
dev = next(model.parameters()).device
|
||||
pv_d = pv.to(dev)
|
||||
times = []
|
||||
for i in range(8):
|
||||
torch.xpu.synchronize(); t0 = time.perf_counter()
|
||||
with torch.no_grad():
|
||||
model.multi_modal_projector(model.vision_tower(pv_d, grid.tolist()))
|
||||
torch.xpu.synchronize(); times.append((time.perf_counter() - t0) * 1000)
|
||||
return times[2:] # first runs warm up kernels for this shape
|
||||
|
||||
gpu = llm.apply_model(run)[0]
|
||||
res[name] = {"image_tokens": int(grid.prod()) // 4, "patches": int(grid.prod()),
|
||||
"preprocess_cpu_ms": round(statistics.median(cpu), 1),
|
||||
"encoder_xpu_ms": round(statistics.median(gpu), 1)}
|
||||
print(name, res[name], flush=True)
|
||||
json.dump(res, open(out, "w"), indent=1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env python3
|
||||
"""TTFT of a chat request with one ~1024px image vs a text-only request of the same prompt length,
|
||||
streaming, max_tokens 1, sequential. Each image request carries a freshly perturbed image (one pixel
|
||||
changed, base64 PNG data URL as Open WebUI sends it) and each text request a fresh random prefix, so
|
||||
neither vLLM's multimodal cache nor its prefix cache can hit. TTFT(image) - TTFT(text) = image cost
|
||||
(decode base64 + preprocessing + vision encoder + projector).
|
||||
|
||||
python3 tests/vl/image_ttft.py PORT OUT.json [REPS=10]
|
||||
Needs Pillow: run with a python that has it (e.g. the vLLM image).
|
||||
"""
|
||||
import base64, io, json, random, statistics, sys, time, urllib.request
|
||||
from PIL import Image
|
||||
|
||||
port, out = int(sys.argv[1]), sys.argv[2]
|
||||
reps = int(sys.argv[3]) if len(sys.argv) > 3 else 10
|
||||
URL = f"http://127.0.0.1:{port}/v1/chat/completions"
|
||||
rng = random.Random(0)
|
||||
|
||||
src = Image.open("tests/vl/images/photo.jpeg").convert("RGB")
|
||||
SIZES = {"1024x768": (1024, 768), "1024x1024": (1024, 1024)}
|
||||
|
||||
|
||||
def ttft(content):
|
||||
body = {"model": "lfm3-vl-2b", "messages": [{"role": "user", "content": content}], "max_tokens": 1,
|
||||
"stream": True, "stream_options": {"include_usage": True}, "temperature": 0.0}
|
||||
req = urllib.request.Request(URL, json.dumps(body).encode(), {"Content-Type": "application/json"})
|
||||
t0 = time.perf_counter(); first = None; usage = None
|
||||
with urllib.request.urlopen(req, timeout=300) as r:
|
||||
for line in r:
|
||||
line = line.decode().strip()
|
||||
if not line.startswith("data:") or line == "data: [DONE]":
|
||||
continue
|
||||
d = json.loads(line[5:])
|
||||
if first is None and d.get("choices"):
|
||||
first = time.perf_counter() - t0
|
||||
usage = d.get("usage") or usage
|
||||
return first * 1000, usage["prompt_tokens"]
|
||||
|
||||
|
||||
def image_content(size):
|
||||
im = src.resize(size, Image.BICUBIC)
|
||||
im.putpixel((rng.randrange(size[0]), rng.randrange(size[1])), tuple(rng.randrange(256) for _ in range(3)))
|
||||
buf = io.BytesIO(); im.save(buf, "PNG")
|
||||
url = "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()
|
||||
return [{"type": "image_url", "image_url": {"url": url}}, {"type": "text", "text": "Describe this image."}], len(url)
|
||||
|
||||
|
||||
WORDS = "alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa".split()
|
||||
|
||||
|
||||
def text_content(n_tokens):
|
||||
# ~1 token per word for these words; fresh random words → no prefix-cache hit
|
||||
return " ".join(rng.choice(WORDS) for _ in range(n_tokens)) + "\n\nDescribe this text."
|
||||
|
||||
|
||||
res = {}
|
||||
ttft(image_content((640, 480))[0]); ttft("warmup") # warm both paths
|
||||
for name, size in SIZES.items():
|
||||
img_ms, txt_ms = [], []
|
||||
for _ in range(reps):
|
||||
content, b64_len = image_content(size)
|
||||
ms, img_prompt = ttft(content); img_ms.append(ms)
|
||||
# text prompt of about the same length (calibrate once)
|
||||
n = img_prompt
|
||||
for _ in range(3):
|
||||
_, got = ttft(text_content(n)); n += img_prompt - got
|
||||
for _ in range(reps):
|
||||
ms, txt_prompt = ttft(text_content(n)); txt_ms.append(ms)
|
||||
med_i, med_t = statistics.median(img_ms), statistics.median(txt_ms)
|
||||
res[name] = {"image_prompt_tokens": img_prompt, "text_prompt_tokens": txt_prompt, "base64_chars": b64_len,
|
||||
"ttft_image_ms_median": round(med_i, 1), "ttft_image_ms_all": [round(x, 1) for x in img_ms],
|
||||
"ttft_text_ms_median": round(med_t, 1), "ttft_text_ms_all": [round(x, 1) for x in txt_ms],
|
||||
"image_cost_ms": round(med_i - med_t, 1)}
|
||||
print(name, {k: v for k, v in res[name].items() if not k.endswith("_all")}, flush=True)
|
||||
json.dump(res, open(out, "w"), indent=1)
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 121 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 157 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 141 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 61 KiB |
@@ -0,0 +1,18 @@
|
||||
"""Precision baseline: Liquid's vision tower + projector in BF16 (CPU) vs the fp32 reference outputs."""
|
||||
import sys, torch
|
||||
from transformers import AutoModelForImageTextToText
|
||||
ref = torch.load(sys.argv[2], weights_only=False)
|
||||
m = AutoModelForImageTextToText.from_pretrained(sys.argv[1], trust_remote_code=True, dtype=torch.bfloat16,
|
||||
attn_implementation="sdpa").eval()
|
||||
for name, r in ref.items():
|
||||
if "pixel_values" not in r:
|
||||
continue
|
||||
with torch.no_grad():
|
||||
vis = m.model.vision_tower(r["pixel_values"].bfloat16(), grid_thw=r["image_grid_thw"], return_dict=True).last_hidden_state
|
||||
proj = m.model.multi_modal_projector(vis)
|
||||
out = {}
|
||||
for key, mine, theirs in (("vision", vis, r["vision_out"]), ("projector", proj, r["proj_out"])):
|
||||
mine = mine.float()
|
||||
out[f"{key}_max_abs_diff"] = round(float((mine - theirs).abs().max()), 4)
|
||||
out[f"{key}_cos_min"] = round(float(torch.nn.functional.cosine_similarity(mine, theirs, dim=-1).min()), 4)
|
||||
print(name, out, flush=True)
|
||||
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Transformers reference for LFM3-VL (Liquid's remote code, trust_remote_code, CPU fp32, sdpa), no plugin.
|
||||
Per case: prompt ids, pixel_values, grid, vision-tower output, projector output, top-20 logprobs of
|
||||
the first generated token, 64 greedy tokens (no repetition penalty).
|
||||
|
||||
python3 ref_vl.py MODEL_DIR IMAGES_DIR OUT.pt
|
||||
"""
|
||||
import sys, time
|
||||
import torch
|
||||
from PIL import Image
|
||||
from transformers import AutoModelForImageTextToText, AutoProcessor
|
||||
|
||||
model_dir, img_dir, out = sys.argv[1:4]
|
||||
torch.manual_seed(0)
|
||||
CASES = {
|
||||
"photo": ("photo.jpeg", "Describe this image in detail."),
|
||||
"screenshot": ("screenshot.png", "What does this screenshot show? Read the column headers of the table."),
|
||||
"small": ("small.png", "What is in this image?"),
|
||||
"wide": ("wide_strip.png", "Transcribe the text in this image."),
|
||||
"text_only": (None, "What is the capital of Australia? Answer in one sentence."),
|
||||
}
|
||||
|
||||
proc = AutoProcessor.from_pretrained(model_dir, trust_remote_code=True)
|
||||
model = AutoModelForImageTextToText.from_pretrained(
|
||||
model_dir, trust_remote_code=True, dtype=torch.float32, attn_implementation="sdpa").eval()
|
||||
print(type(model).__module__, flush=True)
|
||||
|
||||
res = {}
|
||||
for name, (img_file, question) in CASES.items():
|
||||
t0 = time.time()
|
||||
content = ([{"type": "image"}] if img_file else []) + [{"type": "text", "text": question}]
|
||||
text = proc.apply_chat_template([{"role": "user", "content": content}], add_generation_prompt=True, tokenize=False)
|
||||
images = [Image.open(f"{img_dir}/{img_file}").convert("RGB")] if img_file else None
|
||||
inputs = proc(text=text, images=images, return_tensors="pt")
|
||||
r = {"text": text, "input_ids": inputs["input_ids"][0], "image_size": images[0].size if images else None}
|
||||
with torch.no_grad():
|
||||
if images:
|
||||
r["pixel_values"], r["image_grid_thw"] = inputs["pixel_values"], inputs["image_grid_thw"]
|
||||
vis = model.model.vision_tower(inputs["pixel_values"], grid_thw=inputs["image_grid_thw"], return_dict=True)
|
||||
r["vision_out"] = vis.last_hidden_state
|
||||
r["proj_out"] = model.model.multi_modal_projector(vis.last_hidden_state)
|
||||
logits = model(**inputs).logits[0, -1].float()
|
||||
lp = torch.log_softmax(logits, -1)
|
||||
r["first_top20"] = lp.topk(20)
|
||||
gen = model.generate(**inputs, max_new_tokens=64, do_sample=False, repetition_penalty=1.0)
|
||||
r["gen_ids"] = gen[0, inputs["input_ids"].shape[1]:]
|
||||
r["gen_text"] = proc.decode(r["gen_ids"])
|
||||
res[name] = r
|
||||
print(f"{name}: {r['image_size']} grid {r.get('image_grid_thw', torch.zeros(1)).tolist()} "
|
||||
f"prompt {len(r['input_ids'])} tok, {time.time() - t0:.0f}s\n {r['gen_text']!r}", flush=True)
|
||||
torch.save(res, out)
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env bash
|
||||
# Serve LFM3-VL-2B on a test port, wait until ready, record startup time + VRAM.
|
||||
# tests/vl/serve_vl.sh NAME [--fresh] [extra vllm args...]
|
||||
# Container lfm3-vl-NAME on 127.0.0.1:${PORT:-8002}; image ${IMAGE:-lfm3-vllm-xpu:v0.32.0-lfm3-vl};
|
||||
# model mounted read-only from /mnt/model-library; compile cache ./.cache/vl-NAME. GPU share ${GPU_UTIL:-0.4}
|
||||
# (the daily lfm3 in llama-swap keeps its 0.5). Log: logs/vl_serve_NAME.log. Stop: docker stop lfm3-vl-NAME
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
NAME=$1; shift
|
||||
PORT=${PORT:-8002}
|
||||
IMAGE=${IMAGE:-lfm3-vllm-xpu:v0.32.0-lfm3-vl}
|
||||
MODEL=${MODEL:-/mnt/model-library/LiquidAI/LFM3-VL-2B}
|
||||
CACHE=$PWD/.cache/vl-$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-vl-$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 "$MODEL":/model:ro \
|
||||
-v "$CACHE":/root/.cache/vllm \
|
||||
-e HF_HUB_OFFLINE=1 -e TRANSFORMERS_OFFLINE=1 ${DOCKER_ENV:-} \
|
||||
"$IMAGE" /model --host=0.0.0.0 --port=8000 --served-model-name=lfm3-vl-2b \
|
||||
--gpu-memory-utilization=${GPU_UTIL:-0.4} --dtype=bfloat16 --max-model-len=32768 \
|
||||
--limit-mm-per-prompt='{"image": 4}' \
|
||||
--reasoning-parser=qwen3 --enable-auto-tool-choice --tool-call-parser=qwen3_coder \
|
||||
"$@" >/dev/null
|
||||
docker logs -f "lfm3-vl-$NAME" > "logs/vl_serve_$NAME.log" 2>&1 &
|
||||
until curl -sf "127.0.0.1:${PORT}/v1/models" >/dev/null; do
|
||||
if ! docker inspect "lfm3-vl-$NAME" >/dev/null 2>&1; then
|
||||
echo "$NAME: container exited during startup (see logs/vl_serve_$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\tvl-%s\t%.0f\t%s\t%s\n' "$(date +%FT%T)" "$NAME" "$t" "$vram" "$*" >> results/variants_startup.tsv
|
||||
echo "$NAME ready in ${t%.*} s, GPU memory used (whole card) ${vram} MiB"
|
||||
@@ -0,0 +1,16 @@
|
||||
import sys
|
||||
from PIL import Image
|
||||
from vllm import LLM, SamplingParams
|
||||
|
||||
def main():
|
||||
llm = LLM(model="/vl", dtype="bfloat16", max_model_len=8192, gpu_memory_utilization=0.4,
|
||||
limit_mm_per_prompt={"image": 4}, enforce_eager=True)
|
||||
msgs = [{"role": "user", "content": [{"type": "image_pil", "image_pil": Image.open("/tests/vl/images/photo.jpeg").convert("RGB")},
|
||||
{"type": "text", "text": "What newspaper is this?"}]}]
|
||||
o = llm.chat(msgs, SamplingParams(max_tokens=80, temperature=0.0))[0]
|
||||
print("PROMPT_LEN", len(o.prompt_token_ids), "IMG_TOK", o.prompt_token_ids.count(125030))
|
||||
print("OUT", repr(o.outputs[0].text))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user