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