Archived
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:
1 parent
9782a9afb5
commit
a00e5e7094
6 files changed
+406
-9
No files matched your search
+7
-1
@@ -3205,7 +3205,13 @@ int Engine::run_server() {
|
||||
return rc;
|
||||
}
|
||||
o.allow_audio = true;
|
||||
if (mm::decoder_available())
|
||||
if (mm::decoder_available() && ac.family == mm::AudioFamily::Gemma4Unified)
|
||||
RAD_INFO("media: audio through '%s'; a clip is cut at %.3g s, a token is a frame of %d "
|
||||
"samples (%d ms); %lld frames a pass",
|
||||
ranks_[0]->program.audio_encoder_name.c_str(),
|
||||
(double)mm_proc->audio_config().max_samples / (double)ac.rate, ac.frame_length,
|
||||
ac.frame_length * 1000 / ac.rate, (long long)aend.max_patches);
|
||||
else if (mm::decoder_available())
|
||||
RAD_INFO("media: audio through '%s'; a clip is cut at %.3g s, %d mel bins a %d ms frame, "
|
||||
"%d frames a token; %lld frames a pass",
|
||||
ranks_[0]->program.audio_encoder_name.c_str(),
|
||||
|
||||
+82
-7
@@ -244,10 +244,16 @@ int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
if (mt && !std::strcmp(mt, "gemma4_vision")) {
|
||||
/* Gemma 4 12B ("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), and its values are u / 255. The sizes are the
|
||||
* same: a window is 48 pixels a side either way. */
|
||||
const bool unified = mt && !std::strcmp(mt, "gemma4_unified_vision");
|
||||
if (mt && (!std::strcmp(mt, "gemma4_vision") || unified)) {
|
||||
family = Family::Gemma4;
|
||||
patch = (int32_t)rad_meta_geti(&m, "vision_config.patch_size", 0);
|
||||
merge = (int32_t)rad_meta_geti(&m, "vision_config.pooling_kernel_size", 0);
|
||||
unit_pixels = unified;
|
||||
patch = (int32_t)rad_meta_geti(&m, unified ? "vision_config.model_patch_size"
|
||||
: "vision_config.patch_size", 0);
|
||||
merge = unified ? 1 : (int32_t)rad_meta_geti(&m, "vision_config.pooling_kernel_size", 0);
|
||||
temporal = 1;
|
||||
if (patch <= 0 || merge <= 0) {
|
||||
if (why) *why = "the container states no vision tower geometry (vision_config."
|
||||
@@ -267,7 +273,8 @@ int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
|
||||
image_soft_tokens = (int32_t)rad_meta_geti(
|
||||
&m, "processor.image_processor.max_soft_tokens",
|
||||
rad_meta_geti(&m, "vision_soft_tokens_per_image",
|
||||
rad_meta_geti(&m, "vision_config.default_output_length", 280)));
|
||||
rad_meta_geti(&m, "vision_config.default_output_length",
|
||||
rad_meta_geti(&m, "vision_config.num_soft_tokens", 280))));
|
||||
video_soft_tokens = (int32_t)rad_meta_geti(&m, "processor.video_processor.max_soft_tokens",
|
||||
70);
|
||||
fps = rad_meta_getf(&m, "processor.video_processor.fps", 1.0);
|
||||
@@ -1071,7 +1078,8 @@ void patchify(const VisionConfig& c, const std::vector<const Frame*>& frames, It
|
||||
* processor's rescale u * (1/255). The processors AutoProcessor loads take that product in f32 for
|
||||
* pictures (Gemma4ImageProcessor) and in double, rounded to f32, for video (Gemma 4's and
|
||||
* EmbeddingGemma 2's video processors); `video` picks which, and the two differ for u = 127. One
|
||||
* frame per segment. */
|
||||
* frame per segment. With `unit_pixels` (the 12B, merge 1: a row is one 48 x 48 window) the value
|
||||
* is p itself, rounded to bf16. */
|
||||
void patchify_gemma4(const VisionConfig& c, const std::vector<const Frame*>& frames, bool video,
|
||||
Item* it) {
|
||||
const int P = c.patch, M = c.merge;
|
||||
@@ -1080,7 +1088,7 @@ void patchify_gemma4(const VisionConfig& c, const std::vector<const Frame*>& fra
|
||||
for (int v = 0; v < 256; ++v) {
|
||||
const float p = video ? (float)((double)v * (1.0 / 255.0))
|
||||
: (float)v * (float)(1.0 / 255.0);
|
||||
lut[v] = rad_f32_to_bf16(2.0f * (p - 0.5f));
|
||||
lut[v] = rad_f32_to_bf16(c.unit_pixels ? p : 2.0f * (p - 0.5f));
|
||||
}
|
||||
const int64_t dim = it->patch_dim;
|
||||
it->pixels.assign((size_t)it->n_patch * (size_t)dim, 0);
|
||||
@@ -2131,12 +2139,40 @@ static int qwen3asr_from_meta(const RadModelMeta& m, AudioConfig* c, std::string
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Gemma4UnifiedAudioFeatureExtractor's framing (Gemma 4 12B): processor_config.json's
|
||||
* `feature_extractor` and the clip cap `audio_seq_length` (in frames). The frame's width is what the
|
||||
* embedder takes, so it stands in `n_mels` as a mel spectrum's bins do. */
|
||||
static int unified_from_meta(const RadModelMeta& m, AudioConfig* c, std::string* why) {
|
||||
c->family = AudioFamily::Gemma4Unified;
|
||||
c->rate = (int32_t)rad_meta_geti(&m, "processor.feature_extractor.sampling_rate", 16000);
|
||||
c->frame_length = (int32_t)rad_meta_geti(
|
||||
&m, "processor.feature_extractor.audio_samples_per_token",
|
||||
rad_meta_geti(&m, "audio_config.audio_samples_per_token",
|
||||
rad_meta_geti(&m, "audio_config.audio_embed_dim", 0)));
|
||||
c->hop = c->frame_length;
|
||||
c->n_mels = c->frame_length;
|
||||
c->max_samples = rad_meta_geti(&m, "processor.audio_seq_length", 750) * c->frame_length;
|
||||
c->tok_audio = (int32_t)rad_meta_geti(&m, "audio_token_id", -1);
|
||||
c->tok_start = (int32_t)rad_meta_geti(&m, "boa_token_id", -1);
|
||||
c->tok_end = (int32_t)rad_meta_geti(&m, "eoa_token_id",
|
||||
rad_meta_geti(&m, "eoa_token_index", -1));
|
||||
if (c->rate <= 0 || c->frame_length <= 0 || c->max_samples <= 0 || c->tok_audio < 0 ||
|
||||
c->tok_start < 0 || c->tok_end < 0) {
|
||||
if (why) *why = "the container's audio framing is incomplete (sampling_rate, "
|
||||
"audio_samples_per_token, audio_seq_length, audio_token_id, boa_token_id, "
|
||||
"eoa_token_id)";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int AudioConfig::from_meta(const RadModelMeta& m, std::string* why) {
|
||||
const char* mt = rad_meta_gets(&m, "audio_config.model_type", "");
|
||||
if (mt && !std::strcmp(mt, "qwen3_asr_encoder")) return qwen3asr_from_meta(m, this, why);
|
||||
if (mt && !std::strcmp(mt, "gemma4_unified_audio")) return unified_from_meta(m, this, why);
|
||||
if (!mt || std::strcmp(mt, "gemma4_audio")) {
|
||||
if (why) *why = "the container states no audio tower this processor knows (audio_config."
|
||||
"model_type gemma4_audio or qwen3_asr_encoder)";
|
||||
"model_type gemma4_audio, gemma4_unified_audio or qwen3_asr_encoder)";
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
/* preprocessor_config.json's keys (`preprocessor.`), else processor_config.json's
|
||||
@@ -2273,6 +2309,12 @@ int Processor::init_audio(const AudioConfig& cfg, std::string* why) {
|
||||
return refuse(RAD_E_INVAL, "the audio encoder's pass (" + std::to_string(cfg.max_frames) +
|
||||
" frames) is not whole rows of " +
|
||||
std::to_string(cfg.merge) + " frames");
|
||||
/* The 12B's frames are samples: no window, no FFT, no mel bank. */
|
||||
if (cfg.family == AudioFamily::Gemma4Unified) {
|
||||
acfg_ = cfg;
|
||||
audio_on_ = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
const bool qwen = cfg.family == AudioFamily::Qwen3ASR;
|
||||
/* Gemma 4's FFT is radix 2; Qwen3-ASR's runs mixed radix over any length. */
|
||||
if (!qwen && (cfg.fft < 2 || (cfg.fft & (cfg.fft - 1)) != 0))
|
||||
@@ -2481,11 +2523,44 @@ int Processor::audio_qwen3asr(const std::vector<float>& samples, std::shared_ptr
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The 12B's clip (AudioFamily::Gemma4Unified): ceil(n / frame_length) frames of samples, the last
|
||||
* zero-padded, each sample rounded to bf16 as the reference casts the frames for its embedder; one
|
||||
* frame a placeholder. The reference cuts nothing; a clip past `max_samples` is cut there. */
|
||||
int Processor::audio_unified(const std::vector<float>& samples, std::shared_ptr<Item>* out,
|
||||
std::string* why) const {
|
||||
const AudioConfig& c = acfg_;
|
||||
const int64_t n = std::min<int64_t>((int64_t)samples.size(), c.max_samples);
|
||||
const int64_t fl = c.frame_length, rows = (n + fl - 1) / fl;
|
||||
if (rows * c.merge > c.max_frames) {
|
||||
if (why) *why = "the clip is more frames than one audio encoder pass holds";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
auto it = std::make_shared<Item>();
|
||||
it->kind = Kind::Audio;
|
||||
it->grid_t = 1;
|
||||
it->grid_h = (int32_t)rows;
|
||||
it->grid_w = 1;
|
||||
it->patch_dim = fl;
|
||||
it->n_patch = rows;
|
||||
it->valid = (int32_t)rows;
|
||||
it->rows_h = (int32_t)rows;
|
||||
it->rows_w = 1;
|
||||
it->seg_rows = (int32_t)rows;
|
||||
it->n_seg = rows > 0 ? 1 : 0;
|
||||
it->pixels.assign((size_t)(rows * fl), 0);
|
||||
for (int64_t i = 0; i < n; ++i) it->pixels[(size_t)i] = rad_f32_to_bf16(samples[(size_t)i]);
|
||||
one_run(it.get(), c.tok_start, rows, c.tok_audio, c.tok_end);
|
||||
if (rows == 0) it->encoded = true;
|
||||
*out = std::move(it);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Processor::audio_from(const std::vector<float>& samples, std::shared_ptr<Item>* out,
|
||||
std::string* why) const {
|
||||
if (!audio_on_) { if (why) *why = "this program declares no audio encoder"; return RAD_E_UNSUPPORTED; }
|
||||
const AudioConfig& c = acfg_;
|
||||
if (c.family == AudioFamily::Qwen3ASR) return audio_qwen3asr(samples, out, why);
|
||||
if (c.family == AudioFamily::Gemma4Unified) return audio_unified(samples, out, why);
|
||||
const int64_t n = std::min<int64_t>((int64_t)samples.size(), c.max_samples);
|
||||
const int64_t real = c.real_frames(n);
|
||||
const int64_t rows = (real + c.merge - 1) / c.merge;
|
||||
|
||||
+10
-1
@@ -50,6 +50,8 @@ enum class Kind { Image, Video, Audio };
|
||||
* channel) as 2 * (u / 255) - 1, the reference model's own input scaling; a video is
|
||||
* frames sampled at `fps` (at most `max_frames`, thinned evenly), each its own segment
|
||||
* at the per-frame budget, each spelled <boi> placeholders <eoi> with no timestamp.
|
||||
* Gemma 4 12B ("unified", no tower) is the same with a whole pooling window as one
|
||||
* patch (patch = 48, merge 1) and its values u / 255 (`unit_pixels`).
|
||||
* Lfm2 LFM2-VL's: a picture within its token budget (times a tolerance) is resized whole --
|
||||
* sides multiples of patch * merge, pixels within the budget's band -- and one past it
|
||||
* is cut into tile x tile crops, min_tiles..max_tiles of them in the ratio nearest its
|
||||
@@ -88,6 +90,8 @@ struct VisionConfig {
|
||||
/* Gemma4: soft tokens (output rows) an image and a video frame may take. One of 70, 140,
|
||||
* 280, 560, 1120, the budgets the model was trained at. */
|
||||
int32_t image_soft_tokens = 0, video_soft_tokens = 0;
|
||||
/* Gemma4: patch values u / 255 rather than 2 * (u / 255) - 1 (the 12B's embedder). */
|
||||
bool unit_pixels = false;
|
||||
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). */
|
||||
@@ -165,6 +169,9 @@ struct ImageMode {
|
||||
* through an fft-point FFT, magnitudes through an HTK mel bank, log(x + mel_floor).
|
||||
* The clip's real frames, then zero frames to whole output rows.
|
||||
*
|
||||
* Gemma4Unified Gemma4UnifiedAudioFeatureExtractor (the 12B's): no spectrum; a frame is
|
||||
* `frame_length` samples as they are, the last zero-padded, one frame a row.
|
||||
*
|
||||
* Qwen3ASR Qwen3ASRFeatureExtractor (Whisper's): a clip shorter than `min_samples` is
|
||||
* zero-padded to it; frames are torch.stft's, centred with a reflected n_fft / 2 at
|
||||
* each end, a periodic Hann window and power spectra, the last frame dropped, so n
|
||||
@@ -176,7 +183,7 @@ struct ImageMode {
|
||||
* padding, and, where that exceeds a whole chunk, frames past it that the encoder
|
||||
* reads as zero. Plane 1 of the coordinates marks those (RadBatch::enc_coord), which
|
||||
* keeps one chunk's convolution from seeing the next. */
|
||||
enum class AudioFamily { Gemma4, Qwen3ASR };
|
||||
enum class AudioFamily { Gemma4, Qwen3ASR, Gemma4Unified };
|
||||
|
||||
/* Audio features, configured from the container: Gemma 4's framing from `preprocessor.*` (the
|
||||
* checkpoint's preprocessor_config.json), Qwen3-ASR's from `processor.feature_extractor.*`
|
||||
@@ -434,6 +441,8 @@ private:
|
||||
bool audio_on_ = false;
|
||||
int audio_qwen3asr(const std::vector<float>& samples, std::shared_ptr<Item>* out,
|
||||
std::string* why) const;
|
||||
int audio_unified(const std::vector<float>& samples, std::shared_ptr<Item>* out,
|
||||
std::string* why) const;
|
||||
|
||||
std::vector<float> hann_; /* the window, float32 as the reference stores it */
|
||||
std::vector<double> mel_; /* [n_mels, fft/2 + 1]: filter b's weight on bin k */
|
||||
|
||||
@@ -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;
|
||||
@@ -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])
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user