"""mkglimmergolden.py OUT.h -- goldens for tests/mm_test.cpp's Muse Glimmer cases, every number from the reference itself: transformers' own MuseGlimmerImageProcessor and MuseGlimmerVideoProcessor (transformers 5.23.0.dev0, torch 2.15.0+cpu, torchvision 0.29.2+cpu), run on synthetic splitmix frames, plus their sample_frames and replace_video_token. The resize filter is the real reference path, not a reimplementation: the processor is a TorchvisionBackend whose resize calls tvF.resize on the uint8 pixels with InterpolationMode.LANCZOS and antialias=True on CPU, which torch serves with its native uint8 kernel (int16 fixed-point weights, horizontal pass first, an 8-bit rounded intermediate). The test's C++ side has to reproduce that byte for byte. * the resize table: each picture's grid straight out of image_grid_thw; * two pictures' patch planes: the processor's f32 pixel_values cast to bfloat16, the patch rows in the reference's own raster order (patch row by row), each row (temporal, channel, y, x) as the reference lays it out, and the FNV-1a of the whole plane; * a twelve-frame clip: the grid, the plane's FNV-1a, the per-group stamps (each group's first frame's time, the reference's replace_video_token) and the sampled indices (the reference's sample_frames, torch.linspace(...).long()); * a sampling table: the indices' count, first entry and FNV-1a. The pixel at (frame f, row y, column x, channel c) is mm_test's pix(f, y, x, c) splitmix hash, and pix's frame argument is the SOURCE frame's index, so the test's decoded frames match the processor's sampled ones exactly. """ import sys import numpy as np import torch import transformers import torchvision from PIL import Image from transformers.models.muse_glimmer.image_processing_muse_glimmer import MuseGlimmerImageProcessor from transformers.models.muse_glimmer.video_processing_muse_glimmer import MuseGlimmerVideoProcessor from transformers.video_utils import VideoMetadata PATCH, TEMPORAL, MERGE = 14, 2, 2 MAX_IMAGE_TOKENS = 4096 MAX_VIDEO_FRAME_TOKENS = 144 U = np.uint64 def picture(f, h, w): """[h, w, 3] uint8, mm_test's pix(f, y, x, c).""" y = np.arange(h, dtype=np.uint64)[:, None] x = np.arange(w, dtype=np.uint64)[None, :] c = np.arange(3, dtype=np.uint64)[None, None, :] z = (U(f) * U(0x9E3779B97F4A7C15) + y[:, :, None] * U(0xBF58476D1CE4E5B9) + x[:, :, None] * 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): """FNV-1a over each element's bytes, least significant first (mm_test's fnv).""" h = 0xcbf29ce484222325 for v in np.asarray(bits, dtype=np.uint16).ravel(order="C"): for b in (0, 1): h = ((h ^ U((int(v) >> (8 * b)) & 0xFF)) * U(0x100000001b3)) & U((1 << 64) - 1) return int(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 image_processor(): return MuseGlimmerImageProcessor( patch_size=PATCH, temporal_patch_size=TEMPORAL, merge_size=MERGE, max_image_tokens=MAX_IMAGE_TOKENS, image_mean=[0.5] * 3, image_std=[0.5] * 3) def video_processor(): return MuseGlimmerVideoProcessor( patch_size=PATCH, temporal_patch_size=TEMPORAL, merge_size=MERGE, max_video_frame_tokens=MAX_VIDEO_FRAME_TOKENS, num_frames=96, fps=2.0, image_mean=[0.5] * 3, image_std=[0.5] * 3) def process_image(h, w): pil = Image.fromarray(picture(0, h, w), mode="RGB") out = image_processor()(images=[pil], return_tensors="pt") rows = out["pixel_values"] # [gh*gw, dim] f32, raster order if rows.dim() == 3: rows = rows[0] gt, gh, gw = (int(v) for v in out["image_grid_thw"][0]) assert gt == 1 return bf16(rows.numpy()), gh, gw # raster order, as the reference emits it def main(out): print("transformers", transformers.__version__, "torch", torch.__version__, "torchvision", torchvision.__version__) resize_cases = [ (256, 320), (100, 100), (84, 84), (10, 10), (28, 28), (27, 27), (1, 1), (8000, 8000), (2000, 50), (50, 2000), (300, 500), (640, 427), (1920, 1080), (3, 5000), (500, 3), (1234, 5678), (7, 9), (112, 224), (224, 112), ] L = [f"/* glimmer_golden.h -- GENERATED by mkglimmergolden.py from transformers " f"{transformers.__version__} (MuseGlimmerImageProcessor, MuseGlimmerVideoProcessor, " f"torch {torch.__version__}, torchvision {torchvision.__version__}); do not edit. */", "#pragma once", "#include ", "", "static const int32_t kGoldMusePatch = 14, kGoldMuseTemporal = 2, kGoldMuseMerge = 2;", "static const int32_t kGoldMuseTokImage = 200092, kGoldMuseTokVideo = 200091;", "static const int32_t kGoldMuseTokStart = 200080, kGoldMuseTokEnd = 200081;", "static const int32_t kGoldMuseVidStart = 200082, kGoldMuseVidEnd = 200083;", "static const int32_t kGoldMuseVidSep = 200087;", "", "/* A h x w picture's resize target, in pixels. */", "struct GoldMuseResize { int64_t h, w, oh, ow; };", "static const GoldMuseResize kGoldMuseResize[] = {"] print(" resize table + image patch planes") image_cases = [] for h, w in resize_cases: pil = Image.fromarray(picture(0, h, w), mode="RGB") outi = image_processor()(images=[pil], return_tensors="pt") _, gh, gw = (int(v) for v in outi["image_grid_thw"][0]) L.append(f" {{ {h}, {w}, {gh * PATCH}, {gw * PATCH} }},") L.append("};") L.append("") for h, w in [(100, 100), (256, 320)]: px, gh, gw = process_image(h, w) image_cases.append((h, w, gh, gw, px)) L += ["/* A h x w picture: the grid (in patches), the plane's first 16 bf16 values and the " "FNV-1a of every bf16 value's bytes, patches in the reference's raster order, each row " "(temporal, channel, y, x) as the reference lays it out. */", "struct GoldMuseImage { int64_t h, w; int32_t gh, gw; uint16_t head[16]; uint64_t fnv; };", "static const GoldMuseImage kGoldMuseImage[] = {"] for h, w, gh, gw, px in image_cases: head = ", ".join("0x%04x" % int(v) for v in px[0][:16]) L.append(f" {{ {h}, {w}, {gh}, {gw}, {{{head}}}, {fnv16(px)}ull }},") L.append("};") L.append("") print(" video patch plane + stamps") # A 37-frame source at 6 fps: the reference's sample_frames takes 12 frames at 2 fps, the # indices linspace(0, 36, 12).long(); six temporal groups, one stamp per group, each the # group's first frame's time. total, native_fps, fps = 37, 6.0, 2.0 n = min(int(total * fps / native_fps), 96, total) n = max(TEMPORAL, (n // TEMPORAL) * TEMPORAL) n = min(n, total) idx = torch.linspace(0, total - 1, n).long().tolist() print(" sampled", n, "frames:", idx) src = np.stack([picture(f, 64, 96) for f in idx]) # [T, H, W, 3] md = VideoMetadata(total_num_frames=total, fps=native_fps, width=96, height=64, duration=total / native_fps, video_backend="nil", frames_indices=idx) outv = video_processor()(videos=[torch.from_numpy(src)], return_tensors="pt", video_metadata=[md], do_sample_frames=False) pv = outv["pixel_values_videos"] # [gt*gh*gw, dim] f32 gt, gh, gw = (int(v) for v in outv["video_grid_thw"][0]) print(" grid", gt, gh, gw) plane = np.empty((gt, gh * gw, pv.shape[1]), dtype=np.uint16) for g in range(gt): plane[g] = bf16(pv[(g * gh * gw):(g + 1) * gh * gw].numpy()) flat = plane.reshape(-1) # The stamps: metadata.timestamps[::temporal][:grid_t], each formatted "Time: {t:.1f}s". timestamps = [i / native_fps for i in idx] stamps = [f"Time: {t:.1f}s" for t in timestamps[::TEMPORAL][:gt]] while len(stamps) < gt: stamps.append(stamps[-1] if stamps else "Time: 0.0s") print(" stamps:", stamps) L += ["/* The clip: 37 source frames at 6 fps sampled at 2 fps; the sampled indices, the grid " "(groups x patches), the plane's first 16 bf16 values and FNV-1a, and each group's " "stamp. */", f"static const int64_t kGoldMuseVideoTotal = {total};", f"static const double kGoldMuseVideoFps = {native_fps};", f"static const int32_t kGoldMuseVideoN = {n};", "static const int64_t kGoldMuseVideoIndex[] = {", " " + ", ".join(str(i) for i in idx) + "};", f"static const int32_t kGoldMuseVideoGrid[] = {{ {gt}, {gh}, {gw} }};", "static const uint16_t kGoldMuseVideoHead[16] = {", " " + ", ".join("0x%04x" % int(v) for v in flat[:16]) + "};", f"static const uint64_t kGoldMuseVideoFnv = {fnv16(flat)}ull;", "static const char* const kGoldMuseVideoStamps[] = {", "".join(f' "{s}",\n' for s in stamps) + "};", ""] while L[-1] == "": L.pop() print(" sampling table") sample_cases = [(37, 6.0), (6, 2.0), (96, 24.0), (1, 2.0), (2, 2.0), (5, 12.0), (600, 30.0), (1000, 24.0), (13, 7.0), (4, 1.0)] L += ["/* A source of `total` frames at `fps` sampled at 2 fps: the frame count and the " "FNV-1a of every int64 index's bytes (mm_test's fnv over int64). */", "struct GoldMuseSample { int64_t total; double fps; int32_t n; uint64_t fnv; };", "static const GoldMuseSample kGoldMuseSample[] = {"] proc = video_processor() for total, fps in sample_cases: md = VideoMetadata(total_num_frames=total, fps=fps, width=96, height=64, duration=total / fps, video_backend="nil", frames_indices=None) got = proc.sample_frames(md, temporal_patch_size=TEMPORAL, num_frames=96, fps=2.0).tolist() h = 0xcbf29ce484222325 for i in got: for b in range(8): h = ((h ^ U((int(i) >> (8 * b)) & 0xFF)) * U(0x100000001b3)) & U((1 << 64) - 1) L.append(f" {{ {total}, {fps}, {len(got)}, {h}ull }},") print(f" {total} @ {fps}: {got[:6]}{'...' if len(got) > 6 else ''} ({len(got)})") L.append("};") with open(out, "w") as f: f.write("\n".join(L) + "\n") print("wrote", out) if __name__ == "__main__": main(sys.argv[1])