"""mkgemma4golden.py OUT.h -- goldens for tests/mm_test.cpp's Gemma 4 vision cases, every number from transformers' own code (run in a venv with transformers 5.18 or later, torch, torchvision and numpy). The reference is the processor AutoProcessor loads for these checkpoints, which is what transformers and vLLM users run: the checkpoints' processor_config.json names Gemma4ImageProcessor, which transformers 5 resolves to its torchvision backend, and EmbeddingGemma2VideoProcessor (Gemma 4's own video processor rescales the same way). Not the Pillow backend, Gemma4ImageProcessorPil, whose rescale differs in the last float bit for byte 127. * get_aspect_ratio_preserving_size over a grid of picture sizes and soft-token budgets, refusals included; * pictures already at their size: the patch grid, the soft-token count, and the FNV-1a of every patch as the vision tower reads it (2 * (p - 0.5) in float32, the model's own input scaling, then bfloat16), patches row-major. Exact. * resized pictures: the grid, the soft-token count, and every STRIDE-th patch value. radiance resizes with Pillow's bicubic and the reference with torchvision's, so mm_test compares these to a tolerance (a few values one or two pixel levels apart); * a three-frame clip at a size its budget keeps through EmbeddingGemma2VideoProcessor, every patch value exactly. That processor rescales in double where the image processor rescales in float, which differ for byte 127, so the clip is checked to hold that byte; * the video processor's sample_frames with fps and max_frames, overflow_strategy "uniform". The pixel at (frame f, row y, column x, channel c) is mm_test's splitmix hash. """ import sys import numpy as np import torch import transformers from PIL import Image from transformers.models.embedding_gemma2.video_processing_embedding_gemma2 import \ EmbeddingGemma2VideoProcessor from transformers.models.gemma4.image_processing_gemma4 import Gemma4ImageProcessor from transformers.models.gemma4.image_processing_pil_gemma4 import get_aspect_ratio_preserving_size from transformers.video_utils import VideoMetadata PATCH, POOL = 16, 3 U = np.uint64 def picture(f, h, w): """[h, w, 3] uint8, mm_test's pix(f, y, x, c).""" with np.errstate(over="ignore"): y = np.arange(h, dtype=U).reshape(h, 1, 1) x = np.arange(w, dtype=U).reshape(1, w, 1) c = np.arange(3, dtype=U).reshape(1, 1, 3) z = (U(f) * U(0x9E3779B97F4A7C15) + y * U(0xBF58476D1CE4E5B9) + x * U(0x94D049BB133111EB) + c * U(0x2545F4914F6CDD1D) + U(12345)) z = (z ^ (z >> U(30))) * U(0xBF58476D1CE4E5B9) z = (z ^ (z >> U(27))) * U(0x94D049BB133111EB) return ((z ^ (z >> U(31))) & U(255)).astype(np.uint8) def fnv16(bits): h = 0xcbf29ce484222325 for v in bits.astype(np.uint16).ravel().tolist(): for b in (v & 255, v >> 8): h = ((h ^ b) * 0x100000001b3) & ((1 << 64) - 1) return h def tower_bits(pixel_values): """Patch values as the vision tower reads them, as bfloat16 bits.""" t = torch.from_numpy(np.ascontiguousarray(pixel_values, dtype=np.float32)) t = 2 * (t - 0.5) return t.to(torch.bfloat16).view(torch.int16).numpy().view(np.uint16) def rowmajor(arr): """[h, w, 3] bytes to row-major patches of (y, x, channel), as the processors lay them out.""" h, w, _ = arr.shape return arr.reshape(h // PATCH, PATCH, w // PATCH, PATCH, 3).transpose(0, 2, 1, 3, 4) \ .reshape(-1, PATCH * PATCH * 3) def main(out): L = ["/* gemma4_golden.h -- GENERATED by mkgemma4golden.py from transformers %s; do not edit. */" % transformers.__version__, "#pragma once", "#include ", "", "static const int32_t kGemma4Patch = %d, kGemma4Pool = %d;" % (PATCH, POOL), ""] # ---- target sizes; 0 x 0 where the reference refuses L.append("struct GoldGemma4Size { int64_t h, w; int32_t budget; int64_t oh, ow; };") L.append("static const GoldGemma4Size kGoldGemma4Size[] = {") for h, w in [(512, 512), (360, 640), (2160, 3840), (100, 50), (48, 48), (10, 2000), (2000, 10), (1, 1), (47, 4000), (4000, 47), (333, 777), (1080, 1920), (3, 100000), (336, 480), (6000, 4000)]: for budget in (70, 140, 280, 560, 1120): try: oh, ow = get_aspect_ratio_preserving_size(h, w, PATCH, budget * POOL * POOL, POOL) except ValueError: oh, ow = 0, 0 L.append(" { %d, %d, %d, %d, %d }," % (h, w, budget, oh, ow)) L.append("};") # ---- pictures: the processor AutoProcessor loads (Gemma4ImageProcessor, torchvision) proc = Gemma4ImageProcessor(patch_size=PATCH, pooling_kernel_size=POOL) def run_picture(f, h, w, budget): img = Image.fromarray(picture(f, h, w), "RGB") r = proc(images=[img], max_soft_tokens=budget, return_tensors="np") pos = np.asarray(r["image_position_ids"][0]) real = pos[:, 0] >= 0 gw, gh = int(pos[real, 0].max()) + 1, int(pos[real, 1].max()) + 1 bits = tower_bits(np.asarray(r["pixel_values"][0])[real]) return gh, gw, int(r["num_soft_tokens_per_image"][0]), bits L.append("struct GoldGemma4Pic { int32_t f, h, w, budget, grid_h, grid_w, soft; uint64_t fnv; " "uint16_t head[8]; };") L.append("static const GoldGemma4Pic kGoldGemma4Pics[] = {") for f, h, w, budget in [(2, 336, 480, 70), (6, 432, 672, 140)]: assert get_aspect_ratio_preserving_size(h, w, PATCH, budget * POOL * POOL, POOL) == (h, w) gh, gw, soft, bits = run_picture(f, h, w, budget) L.append(" { %d, %d, %d, %d, %d, %d, %d, 0x%016xull, { %s } }," % (f, h, w, budget, gh, gw, soft, fnv16(bits), ", ".join(str(int(v)) for v in bits.ravel()[:8]))) L.append("};") samples = [] L.append("struct GoldGemma4Resized { int32_t f, h, w, budget, grid_h, grid_w, soft, stride, " "first, n; };") L.append("static const GoldGemma4Resized kGoldGemma4Resized[] = {") for f, h, w, budget in [(1, 150, 100, 70), (3, 10, 400, 140)]: assert get_aspect_ratio_preserving_size(h, w, PATCH, budget * POOL * POOL, POOL) != (h, w) gh, gw, soft, bits = run_picture(f, h, w, budget) flat = bits.ravel() stride = len(flat) // 1000 + 1 picked = [int(v) for v in flat[::stride]] L.append(" { %d, %d, %d, %d, %d, %d, %d, %d, %d, %d }," % (f, h, w, budget, gh, gw, soft, stride, len(samples), len(picked))) samples += picked L.append("};") L.append("static const uint16_t kGoldGemma4ResizedValues[] = {") for i in range(0, len(samples), 16): L.append(" " + ", ".join(str(v) for v in samples[i:i + 16]) + ",") L.append("};") # ---- a clip: frames 4..6 of 336 x 432, a size 70 soft tokens a frame keep, sampling done vp = EmbeddingGemma2VideoProcessor(patch_size=PATCH, pooling_kernel_size=POOL) fh, fw, frames = 336, 432, [4, 5, 6] assert get_aspect_ratio_preserving_size(fh, fw, PATCH, 70 * POOL * POOL, POOL) == (fh, fw) clip = np.stack([picture(f, fh, fw) for f in frames]) r = vp(videos=[clip], max_soft_tokens=70, do_sample_frames=False, return_tensors="pt") pv, pos = r["pixel_values_videos"], r["video_position_ids"] pv = pv.reshape(len(frames), -1, pv.shape[-1]).numpy() pos = pos.reshape(len(frames), -1, 2).numpy() real = pos[0, :, 0] >= 0 gw, gh = int(pos[0, real, 0].max()) + 1, int(pos[0, real, 1].max()) + 1 bits = tower_bits(pv[:, real, :]) src = np.stack([rowmajor(picture(f, fh, fw)) for f in frames]) assert (src == 127).any(), "the clip holds no byte 127" L.append("static const int32_t kGoldGemma4ClipFrames[] = { %s };" % ", ".join(map(str, frames))) L.append("static const int32_t kGoldGemma4ClipH = %d, kGoldGemma4ClipW = %d, kGoldGemma4ClipGridH " "= %d, kGoldGemma4ClipGridW = %d, kGoldGemma4ClipSoft = %d;" % (fh, fw, gh, gw, int(r["num_soft_tokens_per_video"][0]))) L.append("static const uint64_t kGoldGemma4ClipFnv = 0x%016xull;" % fnv16(bits)) # ---- sample_frames rows = [] for total, fps, max_frames in [(300, 30.0, 32), (90, 30.0, 32), (10000, 29.97, 32), (5, 25.0, 32), (1, 30.0, 32), (7200, 24.0, 32), (240, 60.0, 4), (1000, 25.0, 10), (700, 30.0, 7), (2001, 23.976, 16), (130, 10.0, 12)]: md = VideoMetadata(total_num_frames=total, fps=fps, duration=total / fps) idx = vp.sample_frames(md, fps=1, max_frames=max_frames, overflow_strategy="uniform") rows.append((total, fps, max_frames, [int(i) for i in idx])) L.append("static const int64_t kGoldGemma4SampleIdx[] = { %s };" % ", ".join(str(i) for _, _, _, idx in rows for i in idx)) L.append("struct GoldGemma4Sample { int64_t total; double fps; int32_t max_frames, first, n; };") L.append("static const GoldGemma4Sample kGoldGemma4Sample[] = {") at = 0 for total, fps, max_frames, idx in rows: L.append(" { %d, %r, %d, %d, %d }," % (total, fps, max_frames, at, len(idx))) at += len(idx) L.append("};") with open(out, "w") as f: f.write("\n".join(L) + "\n") if __name__ == "__main__": main(sys.argv[1])