Archived
121 lines
7.0 KiB
Python
121 lines
7.0 KiB
Python
"""mkgolden.py PROCDIR OUT.h -- goldens for tests/mm_test.cpp, every number from transformers' own
|
|
code: smart_resize (image and video), sample_frames, the patches of an image and a video at sizes
|
|
the resize leaves alone, and get_rope_index over a prompt with an image and a video."""
|
|
import sys, types, io, math, hashlib
|
|
import numpy as np, torch
|
|
from PIL import Image
|
|
from transformers import AutoProcessor
|
|
from transformers.models.qwen2_vl.image_processing_qwen2_vl import smart_resize as sr_img
|
|
from transformers.models.qwen3_vl.video_processing_qwen3_vl import smart_resize as sr_vid
|
|
from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5Model
|
|
from transformers.video_utils import VideoMetadata
|
|
proc_dir, out = sys.argv[1], sys.argv[2]
|
|
P = AutoProcessor.from_pretrained(proc_dir)
|
|
L = ["/* mm_golden.h -- GENERATED by mkgolden.py from transformers %s; do not edit. */" % __import__("transformers").__version__,
|
|
"#pragma once", "#include <cstdint>", ""]
|
|
|
|
# ---- smart_resize, image form
|
|
L.append("struct GoldImageResize { int64_t h, w, min_px, max_px, oh, ow; };")
|
|
L.append("static const GoldImageResize kGoldImageResize[] = {")
|
|
for h, w, mn, mx in [(512, 512, 65536, 16777216), (360, 640, 65536, 16777216), (2160, 3840, 65536, 16777216),
|
|
(2160, 3840, 65536, 4194304), (100, 50, 65536, 16777216), (1, 1, 65536, 16777216),
|
|
(31, 4000, 65536, 16777216), (10000, 10000, 65536, 4194304), (1080, 1920, 65536, 4194304),
|
|
(777, 333, 65536, 4194304), (4000, 3000, 65536, 4194304), (257, 255, 65536, 16777216)]:
|
|
oh, ow = sr_img(h, w, factor=32, min_pixels=mn, max_pixels=mx)
|
|
L.append(f" {{ {h}, {w}, {mn}, {mx}, {oh}, {ow} }},")
|
|
L.append("};")
|
|
|
|
# ---- smart_resize, video form (the caller's per-frame cap already folded into max_px)
|
|
L.append("struct GoldVideoResize { int64_t t, h, w, min_px, max_px, oh, ow; };")
|
|
L.append("static const GoldVideoResize kGoldVideoResize[] = {")
|
|
def cap(nf, mn=4096, mx=25165824, rows=768, factor=32):
|
|
ppf = max(min(rows * factor * factor, mx // nf), int(mn * 1.05))
|
|
return ppf * nf
|
|
for t, h, w in [(18, 512, 512), (16, 360, 640), (4, 1080, 1920), (768, 1080, 1920), (100, 720, 1280),
|
|
(7, 20, 20), (2, 4000, 30), (300, 480, 854)]:
|
|
mx = cap(t)
|
|
oh, ow = sr_vid(t, h, w, temporal_factor=2, factor=32, min_pixels=4096, max_pixels=mx)
|
|
L.append(f" {{ {t}, {h}, {w}, 4096, {mx}, {oh}, {ow} }},")
|
|
L.append("};")
|
|
|
|
# ---- sample_frames
|
|
vp = P.video_processor
|
|
rows = []
|
|
for total, fps in [(270, 30.0), (200, 25.0), (3, 30.0), (10000, 29.97), (50, 0.0), (17, 2.0), (5000, 60.0)]:
|
|
md = VideoMetadata(total_num_frames=total, fps=fps if fps > 0 else None)
|
|
idx = vp.sample_frames(md, fps=2).tolist()
|
|
rows.append((total, fps, idx))
|
|
flat = [i for _, _, idx in rows for i in idx]
|
|
L.append("static const int64_t kGoldSampleIdx[] = { " + ", ".join(map(str, flat)) + " };")
|
|
L.append("struct GoldSample { int64_t total; double fps; int32_t first, n; };")
|
|
L.append("static const GoldSample kGoldSample[] = {")
|
|
at = 0
|
|
for total, fps, idx in rows:
|
|
L.append(f" {{ {total}, {fps!r}, {at}, {len(idx)} }},")
|
|
at += len(idx)
|
|
L.append("};")
|
|
|
|
# ---- patches: a picture and a clip at sizes the resize leaves as they are. The pixel values are a
|
|
# splitmix hash of their coordinates, so a stride that is wrong anywhere changes the result.
|
|
def pix(f, y, x, c):
|
|
z = (f * 0x9E3779B97F4A7C15 + y * 0xBF58476D1CE4E5B9 + x * 0x94D049BB133111EB + c * 0x2545F4914F6CDD1D + 12345) & (2**64 - 1)
|
|
z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & (2**64 - 1)
|
|
z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & (2**64 - 1)
|
|
return (z ^ (z >> 31)) & 255
|
|
def frame(f, h, w):
|
|
return np.array([[[pix(f, y, x, c) for c in range(3)] for x in range(w)] for y in range(h)], dtype=np.uint8)
|
|
def bf16_bits(t):
|
|
a = t.to(torch.bfloat16).view(torch.int16).numpy().astype(np.uint16)
|
|
return a
|
|
def fnv(a):
|
|
h = 0xcbf29ce484222325
|
|
for b in a.tobytes():
|
|
h = ((h ^ b) * 0x100000001b3) & (2**64 - 1)
|
|
return h
|
|
img = frame(0, 256, 320)
|
|
o = P.image_processor(images=[Image.fromarray(img)], return_tensors="pt")
|
|
pv = bf16_bits(o["pixel_values"]); g = o["image_grid_thw"][0].tolist()
|
|
L.append(f"static const int32_t kGoldImageGrid[3] = {{ {g[0]}, {g[1]}, {g[2]} }};")
|
|
L.append(f"static const uint64_t kGoldImageFnv = 0x{fnv(pv):016x}ull;")
|
|
L.append("static const uint16_t kGoldImageHead[16] = { " + ", ".join(str(int(v)) for v in pv.reshape(-1)[:16]) + " };")
|
|
clip = np.stack([frame(f, 64, 96) for f in range(6)])
|
|
md = VideoMetadata(total_num_frames=6, fps=2.0, width=96, height=64, duration=3.0)
|
|
o = P.video_processor(videos=[clip], video_metadata=[md], do_sample_frames=True, fps=2,
|
|
cap_pixels_per_frame=True, return_tensors="pt", return_metadata=True)
|
|
pv = bf16_bits(o["pixel_values_videos"]); g = o["video_grid_thw"][0].tolist()
|
|
L.append(f"static const int32_t kGoldVideoGrid[3] = {{ {g[0]}, {g[1]}, {g[2]} }};")
|
|
L.append(f"static const uint64_t kGoldVideoFnv = 0x{fnv(pv):016x}ull;")
|
|
L.append("static const uint16_t kGoldVideoHead[16] = { " + ", ".join(str(int(v)) for v in pv.reshape(-1)[:16]) + " };")
|
|
mdo = o["video_metadata"][0]
|
|
ts = P._calculate_timestamps(list(mdo.frames_indices), mdo.fps, 2)
|
|
L.append("static const char* const kGoldVideoStamps[] = { " + ", ".join(f'"<{t:.1f} seconds>"' for t in ts) + " };")
|
|
|
|
# ---- get_rope_index over: 3 text, an image of 4 x 6 patches (2 x 3 rows) in its vision pair, 2 text,
|
|
# a video of 2 groups of 4 x 8 patches (2 x 4 rows) each behind its timestamp (5 text tokens here),
|
|
# 4 text. Ids are arbitrary except the pads.
|
|
IMG, VID, VS, VE = 248056, 248057, 248053, 248054
|
|
ids, tt = [], []
|
|
def text(n):
|
|
for i in range(n): ids.append(1000 + len(ids)); tt.append(0)
|
|
text(3); img_at = len(ids)
|
|
ids.append(VS); tt.append(0); ids += [IMG] * 6; tt += [1] * 6; ids.append(VE); tt.append(0)
|
|
text(2); vid_at = len(ids); vid_seg = []
|
|
for f in range(2):
|
|
text(5); ids.append(VS); tt.append(0); vid_seg.append(len(ids) - vid_at)
|
|
ids += [VID] * 8; tt += [2] * 8; ids.append(VE); tt.append(0)
|
|
text(4)
|
|
fake = types.SimpleNamespace(config=types.SimpleNamespace(vision_config=types.SimpleNamespace(spatial_merge_size=2)))
|
|
fake.get_vision_position_ids = types.MethodType(Qwen3_5Model.get_vision_position_ids, fake)
|
|
pos, delta = Qwen3_5Model.get_rope_index(fake, torch.tensor([ids]), torch.tensor([tt]),
|
|
image_grid_thw=torch.tensor([[1, 4, 6]]),
|
|
video_grid_thw=torch.tensor([[2, 4, 8]]))
|
|
pos = pos[:, 0].tolist()
|
|
L.append(f"static const int32_t kGoldRopeN = {len(ids)};")
|
|
L.append(f"static const int32_t kGoldRopeImageAt = {img_at}, kGoldRopeVideoAt = {vid_at};")
|
|
L.append(f"static const int32_t kGoldRopeVideoSeg[2] = {{ {vid_seg[0]}, {vid_seg[1]} }};")
|
|
L.append(f"static const int32_t kGoldRopeDelta = {int(delta[0][0])};")
|
|
for c, name in enumerate("THW"):
|
|
L.append(f"static const int32_t kGoldRope{name}[] = {{ " + ", ".join(map(str, pos[c])) + " };")
|
|
open(out, "w").write("\n".join(L) + "\n")
|
|
print("wrote", out, len(L), "lines")
|