Archived
A fourth processor family beside Qwen-VL, Gemma 4 and LFM2-VL, chosen by vision_config.model_type
glm5_next_vision, as transformers' Glm5NextImageProcessor (torchvision backend) computes it:
- The canvas: both sides rounded up to patch * merge (28), grown by the area ratio under
min_image_tokens, and fitted by the reference's binary search over the picture's height past
max_image_tokens, a token being two frames of 28 x 28 pixels.
- The picture keeps its aspect ratio, is never enlarged while it reaches the floor, is resized
with torchvision's fixed-point bicubic only when its size changes, and sits in the top left of a
canvas of zero bytes, which the normalisation turns into each channel's -mean / std as it does
the reference's padding. Patches as Qwen-VL's (merge-block order, (channel, frame, y, x), the
picture in both frames, CLIP's mean and deviation from processor_config.json).
- <|begin_of_image|>, one <|image|> a token, <|end_of_image|>; the tokens rotate at their
positions (the language model has no rotary). Pictures only.
The budget is in tokens and comes from processor.image_processor.{min,max}_image_tokens; one
encoder pass bounds it, so it is lowered to max_patches / merge^2, as a Qwen-VL pixel band is
(4096 tokens at --mm-max-patches auto, the checkpoint's 8000 at 32000). --image-tokens sets the
ceiling; the pixel-band and video flags, a request's image_tokens and a video are refused by name.
tests/mkglm5golden.py writes glm5_golden.h from Glm5NextProcessor; mm_test checks canvases over a
grid of sizes and both budgets, and whole pictures (padded only, grown under the floor, shrunk to
a budget) patch for patch and token for token, all bit-exact, and the processor read from a
container's keys.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
119 lines
6.3 KiB
Python
119 lines
6.3 KiB
Python
"""mkglm5golden.py MODELDIR OUT.h -- goldens for tests/mm_test.cpp's GLM-5.3 vision cases, every number
|
|
from transformers' own Glm5NextProcessor as MODELDIR's processor_config.json sets it up (run in a
|
|
venv with a transformers that has glm5_next, torch, torchvision, numpy and Pillow).
|
|
|
|
The reference is the processor AutoProcessor loads: Glm5NextImageProcessor, transformers' torchvision
|
|
backend, which resizes the uint8 picture with torchvision's antialiased bicubic (ATen's fixed-point
|
|
kernel), pads it right and bottom with zero bytes, and normalises in float32 with the rescale fused
|
|
into the mean and deviation.
|
|
|
|
* smart_resize over a grid of picture sizes and two token budgets (the checkpoint's 8000, and
|
|
the 4096 an encoder pass of 16384 patches holds): the canvas and the patch count, the latter
|
|
from get_number_of_image_patches;
|
|
* whole pictures, some only padded, some grown under the token floor, some shrunk to a budget:
|
|
the patch grid and the FNV-1a of every patch as the tower reads it (float32, then bfloat16),
|
|
in the reference's own order, which is merge-block order; and the token ids Glm5NextProcessor
|
|
makes of <|begin_of_image|><|image|><|end_of_image|>.
|
|
|
|
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 transformers import AutoProcessor
|
|
from transformers.models.glm5_next.image_processing_glm5_next import smart_resize
|
|
|
|
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 fnv(data):
|
|
h = 0xcbf29ce484222325
|
|
for b in np.frombuffer(data, dtype=np.uint8).tolist():
|
|
h = ((h ^ b) * 0x100000001b3) & ((1 << 64) - 1)
|
|
return h
|
|
|
|
|
|
def main():
|
|
model_dir, out = sys.argv[1], sys.argv[2]
|
|
P = AutoProcessor.from_pretrained(model_dir)
|
|
IP = P.image_processor
|
|
tok = P.tokenizer
|
|
T, F = IP.temporal_patch_size, IP.patch_size * IP.merge_size * IP.patch_expand_factor
|
|
L = ["/* glm5_golden.h -- GENERATED by mkglm5golden.py from transformers %s; do not edit. */"
|
|
% transformers.__version__, "#pragma once", "#include <cstdint>", ""]
|
|
L.append(f"static const int32_t kGlm5Patch = {IP.patch_size}, kGlm5Merge = {IP.merge_size}, "
|
|
f"kGlm5Temporal = {T}, kGlm5MinTok = {IP.min_image_tokens}, "
|
|
f"kGlm5MaxTok = {IP.max_image_tokens};")
|
|
ids = [tok.convert_tokens_to_ids(t) for t in ("<|image|>", "<|begin_of_image|>", "<|end_of_image|>")]
|
|
L.append(f"static const int32_t kGlm5Image = {ids[0]}, kGlm5Start = {ids[1]}, kGlm5End = {ids[2]};")
|
|
L.append("static const float kGlm5Mean[3] = { %s }, kGlm5Std[3] = { %s };" %
|
|
(", ".join(f"{v!r}f" for v in IP.image_mean), ", ".join(f"{v!r}f" for v in IP.image_std)))
|
|
L.append("")
|
|
|
|
# ---- smart_resize: the canvas, and the patch count the processor reports for it
|
|
sizes = [(1, 1), (100, 100), (61, 97), (3, 4000), (448, 448), (300, 500), (768, 1024),
|
|
(1080, 1920), (2048, 2048), (3000, 4000), (4000, 3000), (20, 1500), (1500, 20),
|
|
(111, 113), (112, 112), (113, 111), (2300, 2900), (7000, 120), (120, 7000),
|
|
(5000, 5000), (12000, 9000), (2160, 3840), (1, 30000), (900, 1400)]
|
|
L.append("struct GoldGlm5Size { int64_t h, w; int32_t budget; int64_t oh, ow, patches; };")
|
|
L.append("static const GoldGlm5Size kGoldGlm5Size[] = {")
|
|
for h, w in sizes:
|
|
for budget in (IP.max_image_tokens, 4096):
|
|
oh, ow = smart_resize(num_frames=T, height=h, width=w, temporal_factor=T, factor=F,
|
|
min_pixels=IP.min_image_tokens, max_pixels=budget)
|
|
n = IP.get_number_of_image_patches(h, w, {"max_image_tokens": budget})
|
|
assert n == (oh // IP.patch_size) * (ow // IP.patch_size)
|
|
L.append(f" {{ {h}, {w}, {budget}, {oh}, {ow}, {n} }},")
|
|
L.append("};")
|
|
L.append("")
|
|
|
|
# ---- whole pictures: padded only, grown under the floor, shrunk to a budget
|
|
pics = [(0, 448, 448, IP.max_image_tokens), (1, 300, 500, IP.max_image_tokens),
|
|
(2, 61, 97, IP.max_image_tokens), (3, 3, 400, IP.max_image_tokens),
|
|
(4, 20, 1500, IP.max_image_tokens), (5, 900, 1400, 256), (6, 1200, 1700, 4096),
|
|
(7, 2300, 2900, IP.max_image_tokens), (8, 1, 1, IP.max_image_tokens),
|
|
(9, 113, 111, IP.max_image_tokens)]
|
|
L.append("struct GoldGlm5Pic { int32_t f, h, w, budget, grid_h, grid_w; uint64_t fnv; "
|
|
"int32_t n_ids; uint64_t ids_fnv; uint16_t head[8]; };")
|
|
L.append("static const GoldGlm5Pic kGoldGlm5Pics[] = {")
|
|
for f, h, w, budget in pics:
|
|
im = picture(f, h, w)
|
|
o = IP(images=[torch.from_numpy(im).permute(2, 0, 1)], max_image_tokens=budget,
|
|
return_tensors="pt")
|
|
thw = o["image_grid_thw"][0].tolist()
|
|
assert thw[0] == 1
|
|
pv = o["pixel_values"].to(torch.bfloat16).view(torch.int16).numpy().astype(np.uint16)
|
|
assert pv.shape == (thw[1] * thw[2], 3 * T * IP.patch_size ** 2)
|
|
po = P(text=["<|begin_of_image|><|image|><|end_of_image|>"],
|
|
images=[torch.from_numpy(im).permute(2, 0, 1)], max_image_tokens=budget,
|
|
return_tensors="pt")
|
|
tid = po["input_ids"][0].to(torch.int32).numpy().astype("<i4")
|
|
assert np.array_equal(po["pixel_values"].to(torch.bfloat16).view(torch.int16).numpy()
|
|
.astype(np.uint16), pv)
|
|
head = ", ".join(f"0x{v:04x}" for v in pv.ravel()[:8].tolist())
|
|
L.append(f" {{ {f}, {h}, {w}, {budget}, {thw[1]}, {thw[2]}, "
|
|
f"0x{fnv(pv.astype('<u2').tobytes()):016x}ull, {len(tid)}, "
|
|
f"0x{fnv(tid.tobytes()):016x}ull, {{ {head} }} }},")
|
|
L.append("};")
|
|
open(out, "w").write("\n".join(L) + "\n")
|
|
print("wrote", out, len(L), "lines")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|