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