mm: Gemma 4 12B's pictures and audio

The 12B (gemma4_unified) has no tower: its embedder takes a whole
48 x 48 pooling window as one patch, so a patch is a row (merge 1),
its values u / 255. Its audio is frames of 640 samples as they are,
one frame a token, the last zero-padded. Goldens from transformers.
This commit is contained in:
keptn42 committed 2026-11-04 07:20:29 +01:00
1 parent 9782a9afb5
commit a00e5e7094
6 files changed
+406 -9

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
/* gemma4u_golden.h -- GENERATED by mkgemma4ugolden.py from transformers 5.15.0; do not edit. */
#pragma once
#include <cstdint>
struct GoldGemma4uPic { int32_t f, h, w, budget, grid_h, grid_w, soft; uint64_t fnv; uint16_t head[8]; };
static const GoldGemma4uPic kGoldGemma4uPics[] = {
{ 2, 336, 480, 70, 7, 10, 70, 0x24f3317a5fdef4e5ull, { 16238, 16186, 16218, 16199, 16083, 15857, 16213, 16219 } },
{ 6, 432, 672, 140, 9, 14, 126, 0x1f2f65633d037b7dull, { 15929, 16244, 16077, 16212, 15665, 16130, 15985, 15993 } },
};
static const int32_t kGoldGemma4uClipFrames[] = { 4, 5, 6 };
static const int32_t kGoldGemma4uClipH = 336, kGoldGemma4uClipW = 432, kGoldGemma4uClipGridH = 7, kGoldGemma4uClipGridW = 9, kGoldGemma4uClipSoft = 63;
static const uint64_t kGoldGemma4uClipFnv = 0xfee282f9d3bab92bull;
static const int32_t kGoldGemma4uAudioN = 16037, kGoldGemma4uAudioFrames = 26;
static const uint64_t kGoldGemma4uAudioFnv = 0x27a5cc012ee3ad6dull;
+116
View File
@@ -0,0 +1,116 @@
"""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 <cstdint>", ""]
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])
+177
View File
@@ -22,6 +22,7 @@
#include "mm/media.h"
#include "mm/processor.h"
#include "gemma4_golden.h"
#include "gemma4u_golden.h"
#include "glm5_golden.h"
#include "imaging_golden.h"
#include "lfm2_golden.h"
@@ -733,6 +734,182 @@ TEST(gemma4_frames_are_sampled_as_the_reference_does) {
}
}
/* ================================================================== Gemma 4 12B's processor
*
* gemma4u_golden.h: the 12B's processors with its processor_config.json's settings
* (Gemma4UnifiedImageProcessor, Gemma4UnifiedVideoProcessor, Gemma4UnifiedAudioFeatureExtractor). A
* patch is a whole 48 x 48 pooling window (merge 1), its values u / 255; the reference's patches are
* row-major, as merge 1 makes this processor's. */
namespace {
VisionConfig gemma4u_cfg(int32_t image_soft, int32_t video_soft) {
VisionConfig c = gemma4_cfg(image_soft, video_soft);
c.patch = kGemma4Patch * kGemma4Pool;
c.merge = 1;
c.unit_pixels = true;
c.max_patches = 1120;
return c;
}
} /* namespace */
/* A 48-pixel window as one patch sizes a picture as the 16-pixel patches pooled 3 x 3 do. */
TEST(gemma4_unified_sizes_are_the_references) {
for (const GoldGemma4Size& g : kGoldGemma4Size) {
int64_t oh = 0, ow = 0;
std::string why;
const int rc = gemma4_size(g.h, g.w, kGemma4Patch * kGemma4Pool, 1, g.budget, &oh, &ow, &why);
if (g.oh == 0) {
CHECK(rc < 0);
continue;
}
CHECK_EQ(rc, RAD_OK);
CHECK_EQ(oh, g.oh);
CHECK_EQ(ow, g.ow);
}
}
TEST(gemma4_unified_pictures_patchify_as_the_reference_does) {
for (const GoldGemma4uPic& g : kGoldGemma4uPics) {
Processor p;
REQUIRE_EQ(p.init(gemma4u_cfg(g.budget, 70), [](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_h, g.grid_h);
CHECK_EQ(it->grid_w, g.grid_w);
REQUIRE_EQ(it->n_seg, 1);
CHECK_EQ(it->n_rows(), (int64_t)g.soft);
REQUIRE_EQ(it->patch_dim, (int64_t)3 * 48 * 48);
const std::vector<uint16_t> r = raster(*it, 0);
CHECK(r == it->pixels);
for (int i = 0; i < 8; ++i) CHECK_EQ(r[(size_t)i], g.head[i]);
if (fnv(r) != g.fnv)
std::fprintf(stderr, " picture %d x %d at %d soft tokens: patches differ\n", g.h, g.w,
g.budget);
CHECK_EQ(fnv(r), g.fnv);
REQUIRE_EQ(it->expand.size(), (size_t)g.soft + 2);
CHECK_EQ(it->expand.front(), 255999);
CHECK_EQ(it->expand.back(), 258882);
CHECK_EQ((int64_t)std::count(it->expand.begin(), it->expand.end(), 258880), (int64_t)g.soft);
}
}
TEST(a_gemma4_unified_clip_patchifies_as_the_reference_does) {
Processor p;
REQUIRE_EQ(p.init(gemma4u_cfg(280, 70), [](const std::string&) {
return std::vector<int32_t>{};
}), RAD_OK);
Video v;
v.info.n_frames = 8;
v.info.fps = 1.0;
v.info.w = kGoldGemma4uClipW;
v.info.h = kGoldGemma4uClipH;
for (int32_t f : kGoldGemma4uClipFrames) {
v.index.push_back(f);
v.frames.push_back(frame(f, kGoldGemma4uClipH, kGoldGemma4uClipW));
}
std::shared_ptr<Item> it;
std::string why;
CHECK_OK(p.video_from(v, &it, &why));
REQUIRE(it != nullptr);
REQUIRE_EQ(it->n_seg, (int32_t)v.frames.size());
CHECK_EQ(it->grid_h, kGoldGemma4uClipGridH);
CHECK_EQ(it->grid_w, kGoldGemma4uClipGridW);
CHECK_EQ(it->seg_rows, kGoldGemma4uClipSoft);
if (fnv(it->pixels) != kGoldGemma4uClipFnv)
std::fprintf(stderr, " unified clip: patches differ\n");
CHECK_EQ(fnv(it->pixels), kGoldGemma4uClipFnv);
}
/* The 12B's audio: frames of 640 samples as they are, the last zero-padded, one placeholder each
* between <boa> and <eoa>; read from what a converted container states. */
TEST(a_gemma4_unified_clip_of_audio_is_its_samples_in_frames) {
const char* keys[] = { "audio_config.model_type", "audio_config.audio_embed_dim",
"processor.feature_extractor.sampling_rate",
"processor.feature_extractor.audio_samples_per_token",
"processor.audio_seq_length", "audio_token_id", "boa_token_id",
"eoa_token_index" };
const char* vals[] = { "gemma4_unified_audio", "640", "16000", "640", "750", "258881", "256000",
"258883" };
RadModelMeta m{};
m.n_kv = (int)(sizeof(keys) / sizeof(keys[0]));
m.kv_key = keys;
m.kv_val = vals;
mm::AudioConfig c;
std::string why;
REQUIRE_EQ(c.from_meta(m, &why), RAD_OK);
CHECK(c.family == mm::AudioFamily::Gemma4Unified);
CHECK_EQ(c.n_mels, 640);
CHECK_EQ(c.max_samples, (int64_t)480000);
CHECK_EQ(c.tok_end, 258883);
c.merge = 1;
c.max_frames = 750;
mm::Processor p;
REQUIRE_EQ(p.init_audio(c, &why), RAD_OK);
const int n = kGoldGemma4uAudioN;
std::vector<float> x((size_t)n);
for (int i = 0; i < n; ++i) x[(size_t)i] = (float)((double)((int64_t)i * 7919 % 2001 - 1000) / 1000.0);
std::shared_ptr<mm::Item> it;
REQUIRE_EQ(p.audio_from(x, &it, &why), RAD_OK);
REQUIRE(it != nullptr);
CHECK_EQ(it->grid_h, kGoldGemma4uAudioFrames);
CHECK_EQ(it->seg_rows, kGoldGemma4uAudioFrames);
CHECK_EQ(it->patch_dim, (int64_t)640);
CHECK_EQ(fnv(it->pixels), kGoldGemma4uAudioFnv);
REQUIRE_EQ(it->expand.size(), (size_t)kGoldGemma4uAudioFrames + 2);
CHECK_EQ(it->expand.front(), 256000);
CHECK_EQ(it->expand[1], 258881);
CHECK_EQ(it->expand.back(), 258883);
/* 30 s at most: a longer clip is cut there; a frame more than a pass holds is refused. */
std::vector<float> longer(480000 + 6400, 0.25f);
REQUIRE_EQ(p.audio_from(longer, &it, &why), RAD_OK);
CHECK_EQ(it->grid_h, 750);
c.max_frames = 100;
mm::Processor q;
REQUIRE_EQ(q.init_audio(c, &why), RAD_OK);
CHECK_EQ(q.audio_from(longer, &it, &why), RAD_E_INVAL);
/* No samples: <boa><eoa> and nothing to encode. */
REQUIRE_EQ(p.audio_from({}, &it, &why), RAD_OK);
CHECK(it->encoded);
CHECK_EQ(it->expand.size(), (size_t)2);
}
/* What a converted 12B container states for its pictures: Gemma 4's family with the window as the
* patch and u / 255 values, the budget from processor_config.json. */
TEST(gemma4_unified_vision_config_from_the_container) {
const char* keys[] = { "vision_config.model_type", "vision_config.patch_size",
"vision_config.pooling_kernel_size", "vision_config.model_patch_size",
"image_token_id", "video_token_id", "boi_token_id", "eoi_token_id",
"processor.image_processor.max_soft_tokens",
"processor.video_processor.max_soft_tokens" };
const char* vals[] = { "gemma4_unified_vision", "16", "3", "48", "258880", "258884", "255999",
"258882", "280", "70" };
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::Gemma4);
CHECK(c.unit_pixels);
CHECK_EQ(c.patch, 48);
CHECK_EQ(c.merge, 1);
CHECK_EQ(c.patch_dim(), (int64_t)6912);
CHECK_EQ(c.image_soft_tokens, 280);
CHECK_EQ(c.video_soft_tokens, 70);
vals[0] = "gemma4_vision";
VisionConfig d;
CHECK_OK(d.from_meta(m, &why));
CHECK(!d.unit_pixels);
CHECK_EQ(d.patch, 16);
CHECK_EQ(d.merge, 3);
}
/* ================================================================== GLM-5.3's processor
*
* glm5_golden.h: Glm5NextProcessor as the checkpoint's processor_config.json sets it up