"""mklfm2golden.py MODELDIR OUT.h -- goldens for the LFM2-VL processor in tests/mm_test.cpp, every number from transformers' own Lfm2VlProcessor as MODELDIR's processor_config.json sets it up: smart_resize, the tile grid and the too-large test, and whole pictures -- each segment's patches and the tokens that replace the picture's -- including one scaled down first by PIL's bicubic to an area cap, as d1's runner does before the processor.""" import sys, math, json import numpy as np, torch from PIL import Image from transformers import AutoProcessor model_dir, out = sys.argv[1], sys.argv[2] P = AutoProcessor.from_pretrained(model_dir) IP = P.image_processor tok = P.tokenizer L = ["/* lfm2_golden.h -- GENERATED by mklfm2golden.py from transformers %s; do not edit. */" % __import__("transformers").__version__, "#pragma once", "#include ", ""] cfg = dict(downsample_factor=IP.downsample_factor, min_image_tokens=IP.min_image_tokens, max_image_tokens=IP.max_image_tokens, encoder_patch_size=IP.encoder_patch_size) L.append(f"static const int32_t kLfm2Patch = {IP.encoder_patch_size}, kLfm2Merge = {IP.downsample_factor}, " f"kLfm2MinTok = {IP.min_image_tokens}, kLfm2MaxTok = {IP.max_image_tokens};") L.append(f"static const int32_t kLfm2MinTiles = {IP.min_tiles}, kLfm2MaxTiles = {IP.max_tiles}, " f"kLfm2Tile = {IP.tile_size}, kLfm2MaxPatches = {IP.max_num_patches};") L.append(f"static const double kLfm2Tolerance = {IP.max_pixels_tolerance!r};") # ---- smart_resize (returns width, height) and the tiling decision sizes = [(1, 1), (40, 30), (300, 500), (700, 700), (900, 1400), (2000, 600), (515, 1031), (512, 1024), (1080, 1920), (4000, 300), (31, 4000), (777, 333), (1024, 1024), (1023, 2047), (64, 64), (100, 5000), (3000, 3000), (720, 1280)] L.append("struct GoldLfm2Size { int64_t h, w, oh, ow; int32_t large, cols, rows; };") L.append("static const GoldLfm2Size kGoldLfm2Size[] = {") for h, w in sizes: ow, oh = IP.smart_resize(height=h, width=w, **cfg) large = IP._is_image_too_large(height=h, width=w, max_image_tokens=IP.max_image_tokens, encoder_patch_size=IP.encoder_patch_size, downsample_factor=IP.downsample_factor, max_pixels_tolerance=IP.max_pixels_tolerance) gw, gh, *_ = IP._get_grid_layout(h, w, min_tiles=IP.min_tiles, max_tiles=IP.max_tiles, tile_size=IP.tile_size) L.append(f" {{ {h}, {w}, {oh}, {ow}, {int(large)}, {gw}, {gh} }},") L.append("};") # ---- the markers, by name, for a token_id lookup with no tokenizer behind it names = ["<|image_start|>", "<|image_end|>", "<|img_thumbnail|>"] names += [f"<|img_row_{r}_col_{c}|>" for r in range(1, IP.max_tiles + 1) for c in range(1, IP.max_tiles + 1) if r * c <= IP.max_tiles] L.append("struct GoldLfm2Marker { const char* name; int32_t id; };") L.append("static const GoldLfm2Marker kGoldLfm2Markers[] = {") for n in names: L.append(f' {{ "{n}", {tok.convert_tokens_to_ids(n)} }},') L.append("};") L.append(f"static const int32_t kLfm2ImageToken = {P.image_token_id};") # ---- whole pictures: splitmix pixels (as mkgolden.py's), optionally area-capped by PIL first def frame(f, h, w): y, x, c = np.meshgrid(np.arange(h, dtype=np.uint64), np.arange(w, dtype=np.uint64), np.arange(3, dtype=np.uint64), indexing="ij") with np.errstate(over="ignore"): z = (np.uint64(f) * np.uint64(0x9E3779B97F4A7C15) + y * np.uint64(0xBF58476D1CE4E5B9) + x * np.uint64(0x94D049BB133111EB) + c * np.uint64(0x2545F4914F6CDD1D) + np.uint64(12345)) z = (z ^ (z >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9) z = (z ^ (z >> np.uint64(27))) * np.uint64(0x94D049BB133111EB) z = z ^ (z >> np.uint64(31)) return (z & np.uint64(255)).astype(np.uint8) def fnv(b): a = np.frombuffer(b, dtype=np.uint8).astype(np.uint64) h = 0xcbf29ce484222325 for v in a.tolist(): h = ((h ^ v) * 0x100000001b3) & (2**64 - 1) return h def cap(im, max_pixels): # d1's runner, cap_pixels w, h = im.size if not max_pixels or w * h <= max_pixels: return im s = math.sqrt(max_pixels / (w * h)) return im.resize((max(1, int(w * s)), max(1, int(h * s))), Image.Resampling.BICUBIC) pics = [(0, 40, 30, 0), (1, 300, 500, 0), (2, 700, 700, 0), (3, 900, 1400, 0), (4, 2000, 600, 0), (5, 1800, 1200, 1048576), (6, 515, 1031, 0)] segs, idsall = [], [] L.append("struct GoldLfm2Pic { int32_t f, h, w; int64_t cap; int32_t cols, rows, n_seg, seg0; " "int32_t n_ids; uint64_t ids_fnv; };") rows = [] for f, h, w, mp in pics: im = cap(Image.fromarray(frame(f, h, w)), mp) o = P(text=[""], images=[[im]], return_tensors="pt", add_special_tokens=False) ids = o["input_ids"][0].to(torch.int32).numpy() mask = o["pixel_attention_mask"] shapes = o["spatial_shapes"].tolist() rc = IP(images=[[im]], return_row_col_info=True) pv = o["pixel_values"].to(torch.bfloat16).view(torch.int16).numpy().astype(np.uint16) seg0 = len(segs) for s, (gh, gw) in enumerate(shapes): n = int(mask[s].sum()) assert n == gh * gw segs.append((gh, gw, fnv(pv[s, :n].tobytes()))) rows.append(f" {{ {f}, {h}, {w}, {mp}, {rc['image_cols'][0]}, {rc['image_rows'][0]}, {len(shapes)}, {seg0}, {len(ids)}, " f"0x{fnv(ids.astype('