core/mm: GLM-5.3's processor -- a canvas within a token budget, padded rather than stretched

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>
This commit is contained in:
NunzeandClaude Opus 5.5 authored and StillDeadcode committed 2026-10-22 11:06:34 +02:00
1 parent 69f4906a5c
commit b0bcb74c5b
7 files changed
+575 -8

No files matched your search

+3 -2
View File
@@ -240,8 +240,9 @@ static const Flag g_flags[] = {
{ "--video-max-frames", "N", "the most frames sampled from a video" },
{ "--video-max-frame-tokens", "N", "the most prompt tokens one video frame may become; 0 is no cap (a token\n"
" budget processor -- Gemma 4's -- takes 70, 140, 280, 560 or 1120)" },
{ "--image-tokens", "N", "a token-budget processor's image budget (Gemma 4: 70, 140, 280, 560, 1120;\n"
" default the container's); a request's `image_tokens` overrides it" },
{ "--image-tokens", "N", "a token-budget processor's image budget (Gemma 4: 70, 140, 280, 560, 1120,\n"
" which a request's `image_tokens` overrides; GLM-5.3: the most tokens an\n"
" image becomes, at most --mm-max-patches / 4; default the container's)" },
{ "--max-source-pixels", "N", "the largest image or video frame the decoder accepts, before any resize\n"
" (default 67108864). The media flags above default to what the container\n"
" states, and do nothing for a model that takes no media" },
+32 -1
View File
@@ -2231,7 +2231,7 @@ int Engine::run_server() {
* are refused by name: LFM2-VL takes pictures only, and a token-budget processor (Gemma
* 4's) sizes by soft tokens (--image-tokens, --video-max-frame-tokens), not pixel
* bands. */
if (vc.family == mm::Family::Lfm2 &&
if ((vc.family == mm::Family::Lfm2 || vc.family == mm::Family::Glm5Next) &&
(cfg_.video_min_pixels || cfg_.video_max_pixels || cfg_.video_min_frames ||
cfg_.video_max_frames || cfg_.video_fps || cfg_.video_max_frame_tokens)) {
RAD_ERR("media: this model's processor takes pictures, not video, so the --video-* "
@@ -2249,6 +2249,16 @@ int Engine::run_server() {
}
if (cfg_.image_tokens) vc.image_soft_tokens = *cfg_.image_tokens;
if (cfg_.video_max_frame_tokens) vc.video_soft_tokens = *cfg_.video_max_frame_tokens;
} else if (vc.family == mm::Family::Glm5Next) {
/* GLM-5.3 budgets an image in tokens (max_image_tokens), so --image-tokens is its
* ceiling and the pixel bands do not apply. */
if (cfg_.image_min_pixels || cfg_.image_max_pixels) {
RAD_ERR("media: this model's processor sizes images by a token budget, so "
"--image-min-pixels and --image-max-pixels do nothing; use "
"--image-tokens");
return RAD_E_INVAL;
}
if (cfg_.image_tokens) vc.max_image_tokens = *cfg_.image_tokens;
} else {
if (cfg_.image_tokens) {
RAD_ERR("media: --image-tokens is a token budget, and this model's processor "
@@ -2284,6 +2294,16 @@ int Engine::run_server() {
(long long)encd.patch_dim, (long long)encd.merge);
return RAD_E_INVAL;
}
/* An explicit budget past one pass is refused; the container's is lowered to fit
* (Processor::init), as a pixel band is. */
if (vc.family == mm::Family::Glm5Next && cfg_.image_tokens &&
(int64_t)*cfg_.image_tokens * vc.merge * vc.merge > encd.max_patches) {
RAD_ERR("media: --image-tokens %d is more patches than one encoder pass holds "
"(--mm-max-patches %lld, %lld tokens)", *cfg_.image_tokens,
(long long)encd.max_patches,
(long long)(encd.max_patches / ((int64_t)vc.merge * vc.merge)));
return RAD_E_INVAL;
}
if (vc.family == mm::Family::Gemma4 &&
(int64_t)std::max(vc.image_soft_tokens, vc.video_soft_tokens) * vc.merge * vc.merge >
encd.max_patches) {
@@ -2320,6 +2340,17 @@ int Engine::run_server() {
mm_proc->config().max_pixels_tolerance, mm_proc->config().min_tiles,
mm_proc->config().max_tiles, mm_proc->config().tile,
(long long)encd.max_patches);
else if (mm_proc->config().family == mm::Family::Glm5Next) {
RAD_INFO("media: images through '%s'; an image becomes %d..%d tokens, padded to its "
"canvas rather than stretched; %lld patches a pass",
ranks_[0]->program.encoder_name.c_str(), mm_proc->config().min_image_tokens,
mm_proc->config().max_image_tokens, (long long)encd.max_patches);
if (mm_proc->config().max_image_tokens < vc.max_image_tokens)
RAD_INFO("media: the budget of %d tokens an image is lowered to %d, what one "
"encoder pass holds; --mm-max-patches %lld serves it whole",
vc.max_image_tokens, mm_proc->config().max_image_tokens,
(long long)vc.max_image_tokens * vc.merge * vc.merge);
}
else if (mm_proc->config().family == mm::Family::Gemma4)
RAD_INFO("media: %s%s through '%s'; an image becomes at most %d soft tokens (a "
"request's image_tokens may ask for 70..1120), a video %d a frame at %.3g "
+166 -1
View File
@@ -90,6 +90,65 @@ int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
return RAD_OK;
}
const char* mt = rad_meta_gets(&m, "vision_config.model_type", "");
/* GLM-5.3 states its processor only in processor_config.json's image_processor, with a token
* budget and no pixel band; the tower's geometry is the fallback, as the processor class
* defaults to it. */
if (mt && !std::strcmp(mt, "glm5_next_vision")) {
family = Family::Glm5Next;
auto geti = [&](const char* k, const char* tower, int64_t dflt) {
const std::string key = std::string("processor.image_processor.") + k;
return rad_meta_geti(&m, key.c_str(), rad_meta_geti(&m, tower, dflt));
};
patch = (int32_t)geti("patch_size", "vision_config.patch_size", 0);
temporal = (int32_t)geti("temporal_patch_size", "vision_config.temporal_patch_size", 0);
merge = (int32_t)geti("merge_size", "vision_config.spatial_merge_size", 0);
if (patch <= 0 || temporal <= 0 || merge <= 0) {
if (why) *why = "the container states no vision tower geometry (vision_config."
"patch_size, temporal_patch_size, spatial_merge_size)";
return RAD_E_NOTFOUND;
}
/* The expand factor multiplies the canvas's alignment without changing the patches; the
* checkpoints ship 1, and another one is a canvas this processor does not make. */
const int64_t expand =
rad_meta_geti(&m, "processor.image_processor.patch_expand_factor", 1);
if (expand != 1) {
if (why) *why = "processor.image_processor.patch_expand_factor is " +
std::to_string(expand) + "; this processor serves 1";
return RAD_E_UNSUPPORTED;
}
tok_image = (int32_t)rad_meta_geti(&m, "image_token_id", -1);
tok_video = (int32_t)rad_meta_geti(&m, "video_token_id", -1);
tok_start = (int32_t)rad_meta_geti(&m, "image_start_token_id", -1);
tok_end = (int32_t)rad_meta_geti(&m, "image_end_token_id", -1);
if (tok_image < 0 || tok_start < 0 || tok_end < 0) {
if (why) *why = "the container states no media token ids (image_token_id, "
"image_start_token_id, image_end_token_id)";
return RAD_E_NOTFOUND;
}
min_image_tokens = (int32_t)rad_meta_geti(&m, "processor.image_processor.min_image_tokens",
16);
max_image_tokens = (int32_t)rad_meta_geti(&m, "processor.image_processor.max_image_tokens",
8000);
/* OpenAI CLIP's, the processor class's default. */
const float clip_mean[3] = { 0.48145466f, 0.4578275f, 0.40821073f };
const float clip_std[3] = { 0.26862954f, 0.26130258f, 0.27577711f };
std::copy(clip_mean, clip_mean + 3, mean);
std::copy(clip_std, clip_std + 3, stdv);
read_triple(m, "processor.image_processor.image_mean", mean);
read_triple(m, "processor.image_processor.image_std", stdv);
/* The pixel bands are QwenVL's; here they only have to be consistent for check(). */
const int64_t f2 = (int64_t)factor() * factor();
image_min_pixels = video_min_pixels = std::max<int64_t>(1, min_image_tokens) * f2;
image_max_pixels = video_max_pixels =
std::max<int64_t>(image_min_pixels, (int64_t)max_image_tokens * f2);
std::string bad;
if (check(&bad) < 0) {
if (why)
*why = "the container's GLM-5.3 processor configuration is inconsistent: " + bad;
return RAD_E_INVAL;
}
return RAD_OK;
}
if (mt && !std::strcmp(mt, "gemma4_vision")) {
family = Family::Gemma4;
patch = (int32_t)rad_meta_geti(&m, "vision_config.patch_size", 0);
@@ -200,6 +259,9 @@ int VisionConfig::check(std::string* why) const {
if (!(max_pixels_tolerance > 0.0) || max_segment_patches <= 0)
return no("max_pixels_tolerance and max_num_patches must be positive");
}
if (family == Family::Glm5Next && (min_image_tokens < 1 || max_image_tokens < min_image_tokens))
return no("the image token band [" + std::to_string(min_image_tokens) + ", " +
std::to_string(max_image_tokens) + "] is empty");
if (family == Family::Gemma4) {
if (!soft_budget_ok(image_soft_tokens))
return no("the image soft-token budget " + std::to_string(image_soft_tokens) +
@@ -323,6 +385,51 @@ int gemma4_size(int64_t h, int64_t w, int32_t patch, int32_t pool, int64_t max_p
return RAD_OK;
}
/* Glm5NextImageProcessor's smart_resize and the size its resize() gives the picture, in Python's
* doubles. A token is `temporal` frames of factor x factor pixels, and a picture counts as
* `temporal` frames. The canvas's sides are rounded up to whole factors; under the floor the
* picture is scaled up by the area ratio and rounded up again; over the budget a binary search over
* the picture's height finds the largest canvas inside it. The picture then scales by the smaller
* side ratio, never up while it reaches the floor, truncated. */
int glm5next_size(int64_t h, int64_t w, int32_t temporal, int32_t factor, int64_t min_tok,
int64_t max_tok, int64_t* oh, int64_t* ow, int64_t* ch, int64_t* cw,
std::string* why) {
if (h <= 0 || w <= 0) { if (why) *why = "the picture has no size"; return RAD_E_INVAL; }
const int64_t per_tok = (int64_t)temporal * factor * factor;
const int64_t min_px = min_tok * per_tok, max_px = max_tok * per_tok;
if (max_px < per_tok) {
if (why) *why = "the token budget is less than one merged patch";
return RAD_E_INVAL;
}
auto align = [factor](int64_t v) { return (v + factor - 1) / factor * factor; };
int64_t ah = align(h), aw = align(w);
if (temporal * ah * aw < min_px) {
const double scale = std::sqrt((double)min_px / ((double)temporal * (double)h * (double)w));
ah = align(std::max<int64_t>(1, (int64_t)std::ceil((double)h * scale)));
aw = align(std::max<int64_t>(1, (int64_t)std::ceil((double)w * scale)));
}
if (temporal * ah * aw > max_px) {
int64_t lo = 1, hi = h, bh = factor, bw = factor;
while (lo <= hi) {
const int64_t mid = (lo + hi) / 2;
const int64_t wid = std::max<int64_t>(1, (int64_t)std::floor((double)(w * mid) /
(double)h));
const int64_t th = align(mid), tw = align(wid);
if (temporal * th * tw <= max_px) { bh = th; bw = tw; lo = mid + 1; }
else hi = mid - 1;
}
ah = bh;
aw = bw;
}
double scale = std::min((double)ah / (double)h, (double)aw / (double)w);
if (temporal * h * w >= per_tok * min_tok) scale = std::min(1.0, scale);
*oh = ah;
*ow = aw;
*ch = std::max<int64_t>(1, std::min<int64_t>(ah, (int64_t)std::floor((double)h * scale)));
*cw = std::max<int64_t>(1, std::min<int64_t>(aw, (int64_t)std::floor((double)w * scale)));
return RAD_OK;
}
/* The reference's (EmbeddingGemma2VideoProcessor.sample_frames): the stream's duration at `fps`,
* one frame each 1/fps seconds as int(i * native_fps / fps), then `max_frames` of those chosen by
* numpy's linspace truncated to integers. */
@@ -670,6 +777,15 @@ int Processor::init(const VisionConfig& cfg,
encode_text_ = std::move(encode_text);
return RAD_OK;
}
if (cfg.family == Family::Glm5Next) {
/* A token is merge^2 patches and an image is one segment of one pass, so the budget is
* lowered to what a pass holds. */
const int64_t pass_tok = cfg.max_patches / ((int64_t)cfg.merge * cfg.merge);
if (pass_tok < cfg.min_image_tokens) return RAD_E_INVAL;
if (cfg_.max_image_tokens > pass_tok) cfg_.max_image_tokens = (int32_t)pass_tok;
encode_text_ = std::move(encode_text);
return RAD_OK;
}
if (cfg.family == Family::Gemma4) {
/* A budget is a patch count, and an image is one segment of one pass. */
if ((int64_t)cfg.image_soft_tokens * cfg.merge * cfg.merge > cfg.max_patches ||
@@ -804,10 +920,50 @@ int Processor::image_lfm2(const Frame& f, std::shared_ptr<Item>* out, std::strin
return RAD_OK;
}
/* GLM-5.3's image processor (transformers' Glm5NextImageProcessor, torchvision backend): the
* picture, resized only when its size changes, 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. */
int Processor::image_glm5next(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const {
const VisionConfig& c = cfg_;
int64_t h = 0, w = 0, ch = 0, cw = 0;
RAD_TRY(glm5next_size(f.h, f.w, c.temporal, c.factor(), c.min_image_tokens,
c.max_image_tokens, &h, &w, &ch, &cw, why));
Frame r;
const Frame* src = &f;
if (ch != f.h || cw != f.w) {
resize_bicubic_torch(f, (int32_t)cw, (int32_t)ch, &r);
src = &r;
}
Frame canvas;
canvas.w = (int32_t)w;
canvas.h = (int32_t)h;
canvas.rgb.assign((size_t)w * h * 3, 0);
for (int64_t y = 0; y < ch; ++y)
std::memcpy(canvas.rgb.data() + (size_t)y * w * 3, src->rgb.data() + (size_t)y * cw * 3,
(size_t)cw * 3);
auto it = std::make_shared<Item>();
it->kind = Kind::Image;
it->grid_t = 1;
it->grid_h = (int32_t)(h / c.patch);
it->grid_w = (int32_t)(w / c.patch);
it->rope_1d = true;
finish_item(c, it.get());
if (it->n_patch > c.max_patches) {
if (why) *why = "the image resizes to more patches than one encoder pass holds";
return RAD_E_INVAL;
}
std::vector<const Frame*> frames((size_t)c.temporal, &canvas);
patchify(c, frames, it.get());
one_run(it.get(), c.tok_start, it->seg_rows, c.tok_image, c.tok_end);
*out = std::move(it);
return RAD_OK;
}
int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const {
const VisionConfig& c = cfg_;
if (c.family == Family::Gemma4) return image_gemma4(f, c.image_soft_tokens, out, why);
if (c.family == Family::Lfm2) return image_lfm2(f, out, why);
if (c.family == Family::Glm5Next) return image_glm5next(f, out, why);
int64_t h = 0, w = 0;
RAD_TRY(smart_resize_image(f.h, f.w, c.factor(), c.image_min_pixels, c.image_max_pixels,
&h, &w, why));
@@ -900,6 +1056,10 @@ int Processor::video_gemma4(const Video& v, std::shared_ptr<Item>* out, std::str
int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::string* why) const {
const VisionConfig& c = cfg_;
if (c.family == Family::Gemma4) return video_gemma4(v, out, why);
if (c.family == Family::Glm5Next) {
if (why) *why = "this model's processor takes pictures, not video";
return RAD_E_UNSUPPORTED;
}
if (v.frames.empty()) { if (why) *why = "the video decoded to no frames"; return RAD_E_INVAL; }
/* Pad the frames and their indices to whole temporal groups by repeating the last; a clip
* shorter than one group becomes one group. */
@@ -981,6 +1141,11 @@ int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::strin
int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens,
std::shared_ptr<Item>* out, std::string* why, int64_t max_pixels) const {
if (image_tokens != 0) {
if (cfg_.family == Family::Glm5Next) {
if (why) *why = "this model's image token budget is the server's (--image-tokens), "
"not a request's";
return RAD_E_UNSUPPORTED;
}
if (cfg_.family != Family::Gemma4) {
if (why) *why = "this model's processor sizes an image by its pixels, not by a token "
"budget";
@@ -1017,7 +1182,7 @@ std::vector<int64_t> sample_cb(const VideoInfo& info, const void* user) {
int Processor::video(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out,
std::string* why) const {
if (cfg_.family == Family::Lfm2) {
if (cfg_.family == Family::Lfm2 || cfg_.family == Family::Glm5Next) {
if (why) *why = "this model's processor takes pictures, not video";
return RAD_E_UNSUPPORTED;
}
+19 -2
View File
@@ -55,8 +55,16 @@ enum class Kind { Image, Video, Audio };
* is cut into tile x tile crops, min_tiles..max_tiles of them in the ratio nearest its
* own, followed by the whole picture at the budgeted size as a thumbnail. Patches
* (y, x, channel) normalised by the mean and deviation, resized with torchvision's
* fixed-point bicubic; images only, and the tokens rotate at their positions. */
enum class Family { QwenVL, Gemma4, Lfm2 };
* fixed-point bicubic; images only, and the tokens rotate at their positions.
* Glm5Next GLM-5.3's: a canvas whose sides are multiples of patch * merge and whose tokens fall
* in [min_image_tokens, max_image_tokens] (the sides rounded up, a picture under the
* floor grown, one over the budget fitted by the reference's search); the picture keeps
* its aspect ratio, is never enlarged above the floor, and is resized with torchvision's
* fixed-point bicubic only when its size changes; the rest of the canvas, right and
* bottom, is zero bytes. Patches as QwenVL's. Images only, spelled <begin_of_image>
* placeholders <end_of_image>, the tokens at their positions (the language model has no
* rotary). */
enum class Family { QwenVL, Gemma4, Lfm2, Glm5Next };
struct VisionConfig {
Family family = Family::QwenVL;
@@ -66,6 +74,8 @@ struct VisionConfig {
int32_t image_soft_tokens = 0, video_soft_tokens = 0;
int64_t image_min_pixels = 0, image_max_pixels = 0;
int64_t video_min_pixels = 0, video_max_pixels = 0;
/* Glm5Next: the band an image's canvas falls in, in output rows (tokens). */
int32_t min_image_tokens = 0, max_image_tokens = 0;
double fps = 2.0;
int32_t min_frames = 4, max_frames = 768;
/* Per-frame ceiling on a video's resolution, in output rows (the reference processor's
@@ -332,6 +342,7 @@ private:
int image_gemma4(const Frame& f, int32_t soft, std::shared_ptr<Item>* out,
std::string* why) const;
int image_lfm2(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
int image_glm5next(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
/* Lfm2's markers: <|img_thumbnail|>, and <|img_row_R_col_C|> at (R-1) * max_tiles + C-1. */
int32_t tok_thumbnail_ = -1;
std::vector<int32_t> tok_tiles_;
@@ -373,6 +384,12 @@ void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out);
/* ...and torchvision's on a uint8 tensor (ATen's CPU kernel), which is the same filter with the
* coefficients at the most precision 16 bits hold, chosen per axis, rather than PIL's 22. */
void resize_bicubic_torch(const Frame& in, int32_t w, int32_t h, Frame* out);
/* GLM-5.3's smart_resize: the (oh, ow) canvas, multiples of `factor`, for an h x w picture whose
* `temporal` frames take [min_tok, max_tok] tokens of temporal * factor^2 pixels each; and the
* (ch, cw) the picture is resized to inside it, top left, aspect ratio kept. */
int glm5next_size(int64_t h, int64_t w, int32_t temporal, int32_t factor, int64_t min_tok,
int64_t max_tok, int64_t* oh, int64_t* ow, int64_t* ch, int64_t* cw,
std::string* why);
/* LFM2-VL's smart_resize: (height, width) to multiples of `factor`, at least one each, pixels
* within [min_px, max_px] where the rounding left them outside. */
void lfm2_size(int64_t h, int64_t w, int32_t factor, int64_t min_px, int64_t max_px,
+73
View File
@@ -0,0 +1,73 @@
/* glm5_golden.h -- GENERATED by mkglm5golden.py from transformers 5.21.0.dev0; do not edit. */
#pragma once
#include <cstdint>
static const int32_t kGlm5Patch = 14, kGlm5Merge = 2, kGlm5Temporal = 2, kGlm5MinTok = 16, kGlm5MaxTok = 8000;
static const int32_t kGlm5Image = 154854, kGlm5Start = 154830, kGlm5End = 154831;
static const float kGlm5Mean[3] = { 0.48145466f, 0.4578275f, 0.40821073f }, kGlm5Std[3] = { 0.26862954f, 0.26130258f, 0.27577711f };
struct GoldGlm5Size { int64_t h, w; int32_t budget; int64_t oh, ow, patches; };
static const GoldGlm5Size kGoldGlm5Size[] = {
{ 1, 1, 8000, 112, 112, 64 },
{ 1, 1, 4096, 112, 112, 64 },
{ 100, 100, 8000, 112, 112, 64 },
{ 100, 100, 4096, 112, 112, 64 },
{ 61, 97, 8000, 112, 168, 96 },
{ 61, 97, 4096, 112, 168, 96 },
{ 3, 4000, 8000, 28, 4004, 572 },
{ 3, 4000, 4096, 28, 4004, 572 },
{ 448, 448, 8000, 448, 448, 1024 },
{ 448, 448, 4096, 448, 448, 1024 },
{ 300, 500, 8000, 308, 504, 792 },
{ 300, 500, 4096, 308, 504, 792 },
{ 768, 1024, 8000, 784, 1036, 4144 },
{ 768, 1024, 4096, 784, 1036, 4144 },
{ 1080, 1920, 8000, 1092, 1932, 10764 },
{ 1080, 1920, 4096, 1092, 1932, 10764 },
{ 2048, 2048, 8000, 2072, 2072, 21904 },
{ 2048, 2048, 4096, 1792, 1792, 16384 },
{ 3000, 4000, 8000, 2156, 2884, 31724 },
{ 3000, 4000, 4096, 1540, 2072, 16280 },
{ 4000, 3000, 8000, 2884, 2156, 31724 },
{ 4000, 3000, 4096, 2072, 1540, 16280 },
{ 20, 1500, 8000, 28, 1512, 216 },
{ 20, 1500, 4096, 28, 1512, 216 },
{ 1500, 20, 8000, 1512, 28, 216 },
{ 1500, 20, 4096, 1512, 28, 216 },
{ 111, 113, 8000, 112, 140, 80 },
{ 111, 113, 4096, 112, 140, 80 },
{ 112, 112, 8000, 112, 112, 64 },
{ 112, 112, 4096, 112, 112, 64 },
{ 113, 111, 8000, 140, 112, 80 },
{ 113, 111, 4096, 140, 112, 80 },
{ 2300, 2900, 8000, 2240, 2800, 32000 },
{ 2300, 2900, 4096, 1596, 1988, 16188 },
{ 7000, 120, 8000, 7000, 140, 5000 },
{ 7000, 120, 4096, 7000, 140, 5000 },
{ 120, 7000, 8000, 140, 7000, 5000 },
{ 120, 7000, 4096, 140, 7000, 5000 },
{ 5000, 5000, 8000, 2492, 2492, 31684 },
{ 5000, 5000, 4096, 1792, 1792, 16384 },
{ 12000, 9000, 8000, 2884, 2156, 31724 },
{ 12000, 9000, 4096, 2072, 1540, 16280 },
{ 2160, 3840, 8000, 1876, 3332, 31892 },
{ 2160, 3840, 4096, 1344, 2380, 16320 },
{ 1, 30000, 8000, 28, 30016, 4288 },
{ 1, 30000, 4096, 28, 30016, 4288 },
{ 900, 1400, 8000, 924, 1400, 6600 },
{ 900, 1400, 4096, 924, 1400, 6600 },
};
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]; };
static const GoldGlm5Pic kGoldGlm5Pics[] = {
{ 0, 448, 448, 8000, 32, 32, 0xd1a1afd8f20ac789ull, 258, 0x72139e1c3f39bf1cull, { 0xbf1c, 0xbfc0, 0x3e0a, 0x3fc6, 0xbf7d, 0x3e64, 0x3f8e, 0x3f87 } },
{ 1, 300, 500, 8000, 22, 36, 0x7be72496cfec045dull, 200, 0x255584700075589cull, { 0x3f0b, 0xbe30, 0xbf91, 0x3fdb, 0xbfe2, 0xbe6c, 0x3f4b, 0x3fa7 } },
{ 2, 61, 97, 8000, 8, 12, 0xfedf63278fd84bf1ull, 26, 0x257747e49c4ee91cull, { 0x3ff1, 0x3fce, 0x3f96, 0x3fa9, 0x3fb2, 0x3f4e, 0x3f13, 0x3f47 } },
{ 3, 3, 400, 8000, 2, 94, 0x26cc3ab47053bc9dull, 49, 0xfbf168ec084616acull, { 0xbfe5, 0xbfda, 0xbf5f, 0x3ef8, 0x3fe3, 0x3ff7, 0x3fdf, 0x3f96 } },
{ 4, 20, 1500, 8000, 2, 108, 0x2fd52c52ec4a00a9ull, 56, 0x47537633a0505c9cull, { 0x3f94, 0xbeb2, 0xbf3e, 0x3e64, 0xbfc9, 0xbed0, 0x3f5a, 0xbf41 } },
{ 5, 900, 1400, 256, 26, 38, 0x398290b8912d19d9ull, 249, 0x355dfb37a793d4acull, { 0x3f34, 0xbec1, 0xbf11, 0xbe12, 0xbe85, 0x3d9c, 0x3c93, 0x3f29 } },
{ 6, 1200, 1700, 4096, 86, 122, 0x5fd09cd1af13ba41ull, 2625, 0xf9b8b842d63572acull, { 0xbf8f, 0x3fa5, 0xbf6b, 0x3f61, 0x3fac, 0xbf67, 0xbf18, 0x3df6 } },
{ 7, 2300, 2900, 8000, 160, 200, 0x267b44f24a266119ull, 8002, 0x41e705bec95caf1cull, { 0xbf3a, 0x3fc1, 0xbe94, 0xbfc0, 0xbfa0, 0xbe94, 0xbf7a, 0xbf9b } },
{ 8, 1, 1, 8000, 8, 8, 0xb8835c50fee76f25ull, 18, 0xb05a4c2103cd9b1cull, { 0xbfb1, 0xbfb1, 0xbfb1, 0xbfb1, 0xbfb1, 0xbfb1, 0xbfb1, 0xbfb1 } },
{ 9, 113, 111, 8000, 10, 8, 0x4ae29fe59e7b4e15ull, 22, 0xd734c8e25ac1621cull, { 0xbfba, 0x3fe4, 0xbf11, 0xbf33, 0x3ed3, 0x3f43, 0xbfc9, 0xbfbc } },
};
+118
View File
@@ -0,0 +1,118 @@
"""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())
+164 -2
View File
@@ -2,8 +2,9 @@
*
* Every expected value in mm_golden.h comes from transformers' own code (tests/mkgolden.py names
* the function behind each table), in lfm2_golden.h from its LFM2-VL processor
* (tests/mklfm2golden.py) and in gemma4_golden.h from its Gemma 4 processors
* (tests/mkgemma4golden.py): smart_resize in both forms, the frames a video keeps, the patches of a
* (tests/mklfm2golden.py), in gemma4_golden.h from its Gemma 4 processors
* (tests/mkgemma4golden.py) and in glm5_golden.h from its GLM-5.3 processor
* (tests/mkglm5golden.py): smart_resize in both forms, the frames a video keeps, the patches of a
* picture and a clip, the timestamps between a clip's groups, and get_rope_index's positions over
* a prompt carrying both. A mistake in any of these still yields a model that answers, about a
* slightly different picture or with positions a row off, so only this file can catch it.
@@ -21,10 +22,12 @@
#include "mm/media.h"
#include "mm/processor.h"
#include "gemma4_golden.h"
#include "glm5_golden.h"
#include "imaging_golden.h"
#include "lfm2_golden.h"
#include "mm/resample.h"
#include "mm_golden.h"
#include "rad_builder.h"
#include "rad_plugin.h"
#include <algorithm>
@@ -726,6 +729,165 @@ TEST(gemma4_frames_are_sampled_as_the_reference_does) {
}
}
/* ================================================================== GLM-5.3's processor
*
* glm5_golden.h: Glm5NextProcessor as the checkpoint's processor_config.json sets it up
* (Glm5NextImageProcessor, torchvision backend): canvases, patch counts, patches as the tower reads
* them, and the token ids around a picture. The reference's patches are in merge-block order, as
* this processor's are, so they compare without reordering. */
namespace {
VisionConfig glm5_cfg(int32_t max_tok, int64_t max_patches) {
VisionConfig c;
c.family = Family::Glm5Next;
c.patch = kGlm5Patch;
c.merge = kGlm5Merge;
c.temporal = kGlm5Temporal;
c.min_image_tokens = kGlm5MinTok;
c.max_image_tokens = max_tok;
for (int i = 0; i < 3; ++i) {
c.mean[i] = kGlm5Mean[i];
c.stdv[i] = kGlm5Std[i];
}
const int64_t f2 = (int64_t)c.factor() * c.factor();
c.image_min_pixels = c.video_min_pixels = kGlm5MinTok * f2;
c.image_max_pixels = c.video_max_pixels = (int64_t)max_tok * f2;
c.tok_image = kGlm5Image;
c.tok_video = 154855;
c.tok_start = kGlm5Start;
c.tok_end = kGlm5End;
c.max_patches = max_patches;
return c;
}
} /* namespace */
/* Canvases: sides rounded up to 28, grown under 16 tokens, the budget's binary search over 8000
* and over the 4096 a pass of 16384 patches holds, aspect ratios to 30000:1. */
TEST(glm5_canvases_are_the_references) {
for (const GoldGlm5Size& g : kGoldGlm5Size) {
int64_t oh = 0, ow = 0, ch = 0, cw = 0;
std::string why;
CHECK_OK(glm5next_size(g.h, g.w, kGlm5Temporal, kGlm5Patch * kGlm5Merge, kGlm5MinTok,
g.budget, &oh, &ow, &ch, &cw, &why));
if (oh != g.oh || ow != g.ow)
std::fprintf(stderr, " %lld x %lld at %d tokens: %lld x %lld, reference %lld x "
"%lld\n", (long long)g.h, (long long)g.w, g.budget, (long long)oh,
(long long)ow, (long long)g.oh, (long long)g.ow);
CHECK_EQ(oh, g.oh);
CHECK_EQ(ow, g.ow);
CHECK_EQ((oh / kGlm5Patch) * (ow / kGlm5Patch), g.patches);
CHECK(ch <= oh && cw <= ow);
}
}
/* Whole pictures: padded only (448 x 448 is the one with no padding), grown under the floor (the
* 1 x 1, 61 x 97 and 3 x 400 ones), shrunk to a budget (900 x 1400 at 256 tokens, 2300 x 2900 at
* 8000), every patch value exactly, and <|begin_of_image|>, one <|image|> a token,
* <|end_of_image|>, as the reference processor expands the template's triple. */
TEST(glm5_pictures_are_the_references) {
for (const GoldGlm5Pic& g : kGoldGlm5Pics) {
Processor p;
REQUIRE_EQ(p.init(glm5_cfg(g.budget, 32768), [](const std::string&) {
return std::vector<int32_t>{};
}), RAD_OK);
std::shared_ptr<Item> it;
std::string why;
CHECK_OK(p.image_from(frame(g.f, g.h, g.w), &it, &why));
REQUIRE(it != nullptr);
CHECK_EQ(it->grid_t, 1);
CHECK_EQ(it->grid_h, g.grid_h);
CHECK_EQ(it->grid_w, g.grid_w);
CHECK(it->rope_1d);
REQUIRE_EQ(it->patch_dim, (int64_t)3 * kGlm5Temporal * kGlm5Patch * kGlm5Patch);
REQUIRE_EQ(it->pixels.size(), (size_t)it->n_patch * (size_t)it->patch_dim);
for (int i = 0; i < 8; ++i) CHECK_EQ(it->pixels[(size_t)i], g.head[i]);
if (fnv(it->pixels) != g.fnv)
std::fprintf(stderr, " picture %d x %d at %d tokens: patches differ\n", g.h, g.w,
g.budget);
CHECK_EQ(fnv(it->pixels), g.fnv);
const int64_t rows = (int64_t)g.grid_h * g.grid_w / (kGlm5Merge * kGlm5Merge);
CHECK_EQ(it->n_rows(), rows);
CHECK_EQ((int32_t)it->expand.size(), g.n_ids);
CHECK_EQ(fnv(it->expand), g.ids_fnv);
REQUIRE_EQ(it->expand.size(), (size_t)rows + 2);
CHECK_EQ(it->expand.front(), kGlm5Start);
CHECK_EQ(it->expand.back(), kGlm5End);
CHECK_EQ((int64_t)std::count(it->expand.begin(), it->expand.end(), kGlm5Image), rows);
REQUIRE_EQ(it->seg_at.size(), (size_t)1);
CHECK_EQ(it->seg_at[0], 1);
}
}
/* The checkpoint's budget is lowered to what one encoder pass holds (a token is four patches),
* as a pixel band is; a pass that holds less than the floor is refused. Video and a request's own
* budget are refused by name. */
TEST(glm5_budget_is_one_pass_and_pictures_only) {
Processor p;
REQUIRE_EQ(p.init(glm5_cfg(kGlm5MaxTok, 16384), [](const std::string&) {
return std::vector<int32_t>{};
}), RAD_OK);
CHECK_EQ(p.config().max_image_tokens, 4096);
std::shared_ptr<Item> it;
std::string why;
CHECK_OK(p.image_from(frame(0, 2048, 2048), &it, &why));
REQUIRE(it != nullptr);
CHECK_EQ(it->grid_h, 128);
CHECK_EQ(it->grid_w, 128);
CHECK_EQ(it->n_rows(), (int64_t)4096);
Processor q;
CHECK_EQ(q.init(glm5_cfg(kGlm5MaxTok, 60), [](const std::string&) {
return std::vector<int32_t>{};
}), RAD_E_INVAL);
Video v;
v.frames.push_back(frame(0, 64, 64));
v.frames.push_back(frame(1, 64, 64));
CHECK_EQ(p.video_from(v, &it, &why), RAD_E_UNSUPPORTED);
CHECK(why.find("pictures, not video") != std::string::npos);
const uint8_t png_magic[8] = { 0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a };
CHECK_EQ(p.image(png_magic, sizeof png_magic, 280, &it, &why), RAD_E_UNSUPPORTED);
CHECK(why.find("--image-tokens") != std::string::npos);
}
/* A converted GLM-5.3 container states the processor under `processor.image_processor.*` and
* the media ids under their own names, not Qwen's vision_start / vision_end. */
TEST(glm5_reads_its_processor_from_the_container) {
const char* keys[] = {
"vision_config.model_type", "vision_config.patch_size", "vision_config.temporal_patch_size",
"vision_config.spatial_merge_size", "image_token_id", "video_token_id",
"image_start_token_id", "image_end_token_id", "processor.image_processor.min_image_tokens",
"processor.image_processor.max_image_tokens", "processor.image_processor.image_mean",
"processor.image_processor.image_std", "processor.image_processor.patch_expand_factor",
};
const char* vals[] = {
"glm5_next_vision", "14", "2", "2", "154854", "154855", "154830", "154831", "16", "8000",
"0.48145465999999998 0.4578275 0.40821073000000002",
"0.26862954 0.26130258000000001 0.27577710999999999", "1",
};
RadModelMeta m{};
m.n_kv = (int)(sizeof(keys) / sizeof(keys[0]));
m.kv_key = keys;
m.kv_val = vals;
VisionConfig c;
std::string why;
CHECK_OK(c.from_meta(m, &why));
CHECK(c.family == Family::Glm5Next);
CHECK_EQ(c.patch_dim(), (int64_t)1176);
CHECK_EQ(c.factor(), 28);
CHECK_EQ(c.min_image_tokens, 16);
CHECK_EQ(c.max_image_tokens, 8000);
CHECK_EQ(c.tok_image, kGlm5Image);
CHECK_EQ(c.tok_start, kGlm5Start);
CHECK_EQ(c.tok_end, kGlm5End);
for (int i = 0; i < 3; ++i) {
CHECK_EQ(c.mean[i], kGlm5Mean[i]);
CHECK_EQ(c.stdv[i], kGlm5Std[i]);
}
vals[12] = "2";
CHECK_EQ(c.from_meta(m, &why), RAD_E_UNSUPPORTED);
CHECK(why.find("patch_expand_factor") != std::string::npos);
}
/* ================================================================== Pillow's arithmetic
*
* imaging_golden.h: Image.resize(LANCZOS) of an RGBA splitmix picture at sizes that shrink, grow,