"""mkgemma4ugolden.py OUT.h -- goldens for tests/mm_test.cpp's Gemma 4 12B ("unified") cases, every number from transformers' own code (transformers 5.15 or later, torch, torchvision and numpy). The reference is the processors google/gemma-4-12B-it's processor_config.json names, with its settings: Gemma4UnifiedImageProcessor (rescale u / 255, no normalisation), Gemma4UnifiedVideoProcessor (rescale and an identity normalisation, mean 0 and deviation 1) and Gemma4UnifiedAudioFeatureExtractor. * pictures already at their size: the grid of 48-pixel windows, the soft-token count, and the FNV-1a of every merged patch as the embedder reads it (the processor's float32 cast to bfloat16), patches in the reference's order, which is row-major. Exact. * a three-frame clip at a size its budget keeps, every patch value exactly; * a 16037-sample clip of audio: the frames, their count, and the FNV-1a of every sample cast to bfloat16. The sample at i is ((i * 7919) % 2001 - 1000) / 1000 in float32. 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.gemma4.image_processing_pil_gemma4 import get_aspect_ratio_preserving_size from transformers.models.gemma4_unified.feature_extraction_gemma4_unified import \ Gemma4UnifiedAudioFeatureExtractor from transformers.models.gemma4_unified.image_processing_gemma4_unified import Gemma4UnifiedImageProcessor from transformers.models.gemma4_unified.video_processing_gemma4_unified import Gemma4UnifiedVideoProcessor 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 bf16(a): t = torch.from_numpy(np.ascontiguousarray(a, dtype=np.float32)) return t.to(torch.bfloat16).view(torch.int16).numpy().view(np.uint16) def raster_ok(pos, gh, gw): k = np.arange(gh * gw) return (pos[:, 0] == k % gw).all() and (pos[:, 1] == k // gw).all() def main(out): L = ["/* gemma4u_golden.h -- GENERATED by mkgemma4ugolden.py from transformers %s; do not edit. */" % transformers.__version__, "#pragma once", "#include ", ""] ip = Gemma4UnifiedImageProcessor(patch_size=PATCH, pooling_kernel_size=POOL, do_normalize=False, image_mean=[0.0] * 3, image_std=[1.0] * 3) L.append("struct GoldGemma4uPic { int32_t f, h, w, budget, grid_h, grid_w, soft; uint64_t fnv; " "uint16_t head[8]; };") L.append("static const GoldGemma4uPic kGoldGemma4uPics[] = {") 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) r = ip(images=[Image.fromarray(picture(f, h, w), "RGB")], 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 assert raster_ok(pos[real], gh, gw) bits = bf16(np.asarray(r["pixel_values"][0])[real]) L.append(" { %d, %d, %d, %d, %d, %d, %d, 0x%016xull, { %s } }," % (f, h, w, budget, gh, gw, int(r["num_soft_tokens_per_image"][0]), fnv16(bits), ", ".join(str(int(v)) for v in bits.ravel()[:8]))) L.append("};") vp = Gemma4UnifiedVideoProcessor(patch_size=PATCH, pooling_kernel_size=POOL, do_normalize=True, image_mean=[0.0] * 3, image_std=[1.0] * 3) 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]) assert (clip == 127).any(), "the clip holds no byte 127" r = vp(videos=[clip], max_soft_tokens=70, do_sample_frames=False, return_tensors="pt") pv = r["pixel_values_videos"].reshape(len(frames), -1, r["pixel_values_videos"].shape[-1]).numpy() pos = r["video_position_ids"].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 assert all(raster_ok(pos[i, real], gh, gw) for i in range(len(frames))) L.append("static const int32_t kGoldGemma4uClipFrames[] = { %s };" % ", ".join(map(str, frames))) L.append("static const int32_t kGoldGemma4uClipH = %d, kGoldGemma4uClipW = %d, kGoldGemma4uClipGridH " "= %d, kGoldGemma4uClipGridW = %d, kGoldGemma4uClipSoft = %d;" % (fh, fw, gh, gw, int(r["num_soft_tokens_per_video"][0]))) L.append("static const uint64_t kGoldGemma4uClipFnv = 0x%016xull;" % fnv16(bf16(pv[:, real, :]))) fe = Gemma4UnifiedAudioFeatureExtractor(feature_size=640, sampling_rate=16000, audio_samples_per_token=640) n = 16037 x = ((np.arange(n, dtype=np.int64) * 7919 % 2001 - 1000) / 1000.0).astype(np.float32) r = fe(x, return_tensors="np") feats = np.asarray(r["input_features"][0]) assert int(np.asarray(r["input_features_mask"][0]).sum()) == feats.shape[0] L.append("static const int32_t kGoldGemma4uAudioN = %d, kGoldGemma4uAudioFrames = %d;" % (n, feats.shape[0])) L.append("static const uint64_t kGoldGemma4uAudioFnv = 0x%016xull;" % fnv16(bf16(feats))) with open(out, "w") as f: f.write("\n".join(L) + "\n") if __name__ == "__main__": main(sys.argv[1])