Commit 489b7443e for llama.cpp
commit 489b7443e8611f256bef3bdd0d3344ec4510060d
Author: Xuan-Son Nguyen <son@huggingface.co>
Date: Sat Dec 5 14:06:40 2026 +0100
mtmd: enforce no_realloc (#33377)
* no relloc init
* mtmd: enforce no_realloc
* lift TAG_MTMD_NO_REALLOC
* show warn if default is less than max supported by model
* fix ci
* better default value (better ux)
* mtmd: build zero padding and the img_break rows without uninitialized tensors
A ggml_new_tensor scaled by 0 is not zero: the buffer is never written,
so a NaN left by a previous graph comes out as NaN.
Use ggml_pad_ext for the paddings and ggml_repeat_4d for img_break.
* tests: pin the tiny_voca F0 in test-mtmd-model
The pulse train turns a small F0 difference between backends
into a phase drift, CUDA vs CPU gave NMSE 5.7e-2.
Only the F0 bias is set so that F0 clamps the same everywhere,
voicing and energy stay random.
* nits
* VOXTRAL removed from audio_has_avgpool(), nemotron_omni now calls set_default_max_patches()
* fix drama3 tower attention
* fix ci
* fix ci (2)
* fic ci (3)
---------
Co-authored-by: Pascal <admin@serveurperso.com>
diff --git a/.github/workflows/server-sanitize.yml b/.github/workflows/server-sanitize.yml
index aececfe2f..4202c31e7 100644
--- a/.github/workflows/server-sanitize.yml
+++ b/.github/workflows/server-sanitize.yml
@@ -42,8 +42,6 @@ env:
LLAMA_ARG_LOG_PREFIX: 1
LLAMA_ARG_LOG_TIMESTAMPS: 1
LLAMA_ARG_LOG_VERBOSITY: 10
- # [TAG_MTMD_NO_REALLOC] must match -DGGML_SCHED_NO_REALLOC=ON below, skips tests that are known to realloc
- GGML_SCHED_NO_REALLOC: ON
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.head_ref || github.run_id }}
diff --git a/.github/workflows/server-self-hosted.yml b/.github/workflows/server-self-hosted.yml
index e54469964..c5dd86449 100644
--- a/.github/workflows/server-self-hosted.yml
+++ b/.github/workflows/server-self-hosted.yml
@@ -39,8 +39,6 @@ env:
LLAMA_ARG_LOG_PREFIX: 1
LLAMA_ARG_LOG_TIMESTAMPS: 1
LLAMA_ARG_LOG_VERBOSITY: 10
- # [TAG_MTMD_NO_REALLOC] must match -DGGML_SCHED_NO_REALLOC=ON below, skips tests that are known to realloc
- GGML_SCHED_NO_REALLOC: ON
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.head_ref || github.run_id }}
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 46fd38d5f..906600858 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -410,6 +410,8 @@ llama_build_and_test(test-mtmd-c-api.c LABEL behavior LINK mtmd)
llama_build_and_test(test-mtmd-impl.cpp LABEL behavior LINK mtmd llama-common)
+llama_build_and_test(test-mtmd-model.cpp LABEL "behavior backend" LINK mtmd)
+
# GGUF model data fetcher library for tests that need real model metadata
# Only compile when cpp-httplib has SSL support (CPPHTTPLIB_OPENSSL_SUPPORT)
if (TARGET cpp-httplib)
diff --git a/tests/test-mtmd-impl.cpp b/tests/test-mtmd-impl.cpp
index 51de24402..c954773f5 100644
--- a/tests/test-mtmd-impl.cpp
+++ b/tests/test-mtmd-impl.cpp
@@ -859,7 +859,7 @@ MAKE_TEST(test_audio_log_mel_blocks) {
const int n_mel = 80;
const int n_fft = 400;
const int hop = 160;
- const int n_frames = 8192 + 100; // long audio is split into blocks of 8192 frames
+ const int n_frames = 8192 + 100; // long audio is split into blocks, 8192 is a block boundary
mtmd_audio_cache cache;
cache.fill_sin_cos_table(n_fft);
diff --git a/tests/test-mtmd-model.cpp b/tests/test-mtmd-model.cpp
new file mode 100644
index 000000000..0c00999b3
--- /dev/null
+++ b/tests/test-mtmd-model.cpp
@@ -0,0 +1,4896 @@
+#include "ggml.h"
+#include "ggml-backend.h"
+#include "ggml-cpp.h"
+#include "gguf.h"
+#include "llama.h"
+#include "llama-cpp.h"
+#include "mtmd.h"
+#include "mtmd-impl.h"
+
+#include <cinttypes>
+#include <cstdarg>
+#include <cmath>
+#include <cstdio>
+#include <cstring>
+#include <filesystem>
+#include <functional>
+#include <random>
+#include <regex>
+#include <string>
+#include <vector>
+
+// end-to-end test of the mtmd projectors with random weights, see tools/mtmd/README-dev.md
+// for each projector:
+// - build a small mmproj from a hand-written table of hparams and tensor shapes, write it to a temp GGUF
+// - load it on each backend, then encode a set of inputs (image sizes up to the default cap, audio lengths),
+// run an audio stream, or drive a few audio generation steps
+// - check that no step grows the compute buffers reserved by the warmup (no realloc)
+// - check that the outputs are finite and match the CPU output (NMSE)
+// a case with tm.todo set is a known failure, it is skipped
+
+//
+// random data
+//
+
+// M_PI is not defined on Windows without _USE_MATH_DEFINES
+static const float TEST_PI = 3.14159265358979323846f;
+
+static std::vector<float> g_normal_pool;
+static const size_t NORMAL_POOL_SIZE = 4 * 1024 * 1024;
+
+static void init_normal_pool(size_t seed) {
+ g_normal_pool.resize(NORMAL_POOL_SIZE);
+ std::mt19937 gen(seed);
+ std::normal_distribution<float> dist(0.0f, 1.0f);
+ for (float & v : g_normal_pool) {
+ v = dist(gen);
+ }
+}
+
+// a draw keyed on the name, so that each tensor gets the same values on every run
+static void fill_normal(float * dst, size_t n, const std::string & key, float mean, float stdev) {
+ const size_t start = std::hash<std::string>{}(key) % NORMAL_POOL_SIZE;
+ for (size_t i = 0; i < n; i++) {
+ dst[i] = mean + stdev * g_normal_pool[(start + i) % NORMAL_POOL_SIZE];
+ }
+}
+
+// normalized mean squared error = mse(a, b) / mse(a, 0)
+static double nmse(const std::vector<float> & a, const std::vector<float> & b) {
+ GGML_ASSERT(a.size() == b.size());
+ double mse_a_b = 0.0;
+ double mse_a_0 = 0.0;
+ for (size_t i = 0; i < a.size(); i++) {
+ mse_a_b += (a[i] - b[i]) * (a[i] - b[i]);
+ mse_a_0 += a[i] * a[i];
+ }
+ return mse_a_b / mse_a_0;
+}
+
+//
+// mmproj writer
+//
+
+struct mmproj_writer {
+ gguf_context_ptr gguf;
+ std::vector<ggml_context_ptr> ctxs; // tensor data must stay alive until the file is written
+ float stdev = 0.05f;
+
+ mmproj_writer() : gguf(gguf_init_empty()) {}
+
+ void kv(const std::string & key, uint32_t v) { gguf_set_val_u32 (gguf.get(), key.c_str(), v); }
+ void kv(const std::string & key, int32_t v) { gguf_set_val_i32 (gguf.get(), key.c_str(), v); }
+ void kv(const std::string & key, float v) { gguf_set_val_f32 (gguf.get(), key.c_str(), v); }
+ void kv(const std::string & key, bool v) { gguf_set_val_bool(gguf.get(), key.c_str(), v); }
+ void kv(const std::string & key, const char * v) { gguf_set_val_str (gguf.get(), key.c_str(), v); }
+ void kv(const std::string & key, const std::vector<float> & v) {
+ gguf_set_arr_data(gguf.get(), key.c_str(), GGUF_TYPE_FLOAT32, v.data(), v.size());
+ }
+ void kv(const std::string & key, const std::vector<int32_t> & v) {
+ gguf_set_arr_data(gguf.get(), key.c_str(), GGUF_TYPE_INT32, v.data(), v.size());
+ }
+
+ // mean = 1 for norm weights, so the activations keep their scale
+ // returns the data, written to the file at the end, so that a case can set some values
+ float * tensor(const std::string & name, const std::vector<int64_t> & ne, float mean = 0.0f) {
+ GGML_ASSERT(!ne.empty() && ne.size() <= 4);
+ ggml_init_params params = {
+ /*.mem_size =*/ ggml_tensor_overhead() + sizeof(float),
+ /*.mem_buffer =*/ nullptr,
+ /*.no_alloc =*/ false,
+ };
+ int64_t n = 1;
+ for (int64_t v : ne) {
+ n *= v;
+ }
+ params.mem_size += n * sizeof(float);
+ ggml_context * ctx = ggml_init(params);
+ ctxs.emplace_back(ctx);
+ int64_t dims[4] = {1, 1, 1, 1};
+ for (size_t i = 0; i < ne.size(); i++) {
+ dims[i] = ne[i];
+ }
+ ggml_tensor * t = ggml_new_tensor(ctx, GGML_TYPE_F32, (int) ne.size(), dims);
+ ggml_set_name(t, name.c_str());
+ fill_normal((float *) t->data, n, name, mean, stdev);
+ gguf_add_tensor(gguf.get(), t);
+ return (float *) t->data;
+ }
+
+ void norm(const std::string & name, int64_t n) {
+ tensor(name, {n}, 1.0f);
+ }
+};
+
+static std::string fmt(const char * f, ...) {
+ va_list ap;
+ va_start(ap, f);
+ char buf[256];
+ vsnprintf(buf, sizeof(buf), f, ap);
+ va_end(ap);
+ return buf;
+}
+
+//
+// shared blocks
+//
+
+struct vit_opts {
+ bool ln_bias = true; // false: RMS norm
+ bool qkv_bias = true;
+ bool k_bias = true; // whisper has no k bias
+ bool o_bias = true;
+ bool ffn_gate = false;
+ bool ffn_bias = true;
+ bool post_ln = true;
+};
+
+static void add_vit(mmproj_writer & w, const char * prefix, int n_layer, int64_t n_embd, int64_t n_ff, const vit_opts & o) {
+ for (int il = 0; il < n_layer; il++) {
+ for (const char * x : {"q", "k", "v"}) {
+ w.tensor(fmt("%s.blk.%d.attn_%s.weight", prefix, il, x), {n_embd, n_embd});
+ const bool bias = o.qkv_bias && (o.k_bias || strcmp(x, "k") != 0);
+ if (bias) {
+ w.tensor(fmt("%s.blk.%d.attn_%s.bias", prefix, il, x), {n_embd});
+ }
+ }
+ w.tensor(fmt(TN_ATTN_OUTPUT, prefix, il, "weight"), {n_embd, n_embd});
+ if (o.o_bias) {
+ w.tensor(fmt(TN_ATTN_OUTPUT, prefix, il, "bias"), {n_embd});
+ }
+ w.norm(fmt(TN_LN_1, prefix, il, "weight"), n_embd);
+ w.norm(fmt(TN_LN_2, prefix, il, "weight"), n_embd);
+ if (o.ln_bias) {
+ w.tensor(fmt(TN_LN_1, prefix, il, "bias"), {n_embd});
+ w.tensor(fmt(TN_LN_2, prefix, il, "bias"), {n_embd});
+ }
+ w.tensor(fmt(TN_FFN_UP, prefix, il, "weight"), {n_embd, n_ff});
+ w.tensor(fmt(TN_FFN_DOWN, prefix, il, "weight"), {n_ff, n_embd});
+ if (o.ffn_gate) {
+ w.tensor(fmt(TN_FFN_GATE, prefix, il, "weight"), {n_embd, n_ff});
+ }
+ if (o.ffn_bias) {
+ w.tensor(fmt(TN_FFN_UP, prefix, il, "bias"), {n_ff});
+ w.tensor(fmt(TN_FFN_DOWN, prefix, il, "bias"), {n_embd});
+ if (o.ffn_gate) {
+ w.tensor(fmt(TN_FFN_GATE, prefix, il, "bias"), {n_ff});
+ }
+ }
+ }
+ if (o.post_ln) {
+ w.norm(fmt(TN_LN_POST, prefix, "weight"), n_embd);
+ if (o.ln_bias) {
+ w.tensor(fmt(TN_LN_POST, prefix, "bias"), {n_embd});
+ }
+ }
+}
+
+struct enc_hparams {
+ uint32_t n_embd = 64;
+ uint32_t n_head = 2;
+ uint32_t n_ff = 128;
+ uint32_t n_layer = 2;
+ uint32_t n_proj = 128; // output size, also the text model n_embd
+ float eps = 1e-6f;
+};
+
+// mixed = true for an mmproj with several modalities, each has its own projector type key
+static void add_vision_kv(mmproj_writer & w, projector_type proj, const enc_hparams & hp, uint32_t image_size, uint32_t patch_size, bool mixed = false) {
+ w.kv(KEY_HAS_VISION_ENC, true);
+ w.kv(mixed ? KEY_VISION_PROJ_TYPE : KEY_PROJ_TYPE, PROJECTOR_TYPE_NAMES[proj].c_str());
+ w.kv(fmt(KEY_N_EMBD, "vision"), hp.n_embd);
+ w.kv(fmt(KEY_N_HEAD, "vision"), hp.n_head);
+ w.kv(fmt(KEY_N_FF, "vision"), hp.n_ff);
+ w.kv(fmt(KEY_N_BLOCK, "vision"), hp.n_layer);
+ w.kv(fmt(KEY_PROJ_DIM, "vision"), hp.n_proj);
+ w.kv(fmt(KEY_LAYER_NORM_EPS, "vision"), hp.eps);
+ w.kv(KEY_IMAGE_SIZE, image_size);
+ w.kv(KEY_PATCH_SIZE, patch_size);
+ w.kv(KEY_IMAGE_MEAN, std::vector<float>{0.5f, 0.5f, 0.5f});
+ w.kv(KEY_IMAGE_STD, std::vector<float>{0.5f, 0.5f, 0.5f});
+}
+
+static void add_audio_kv(mmproj_writer & w, projector_type proj, const enc_hparams & hp, uint32_t n_mel, bool mixed = false) {
+ w.kv(KEY_HAS_AUDIO_ENC, true);
+ w.kv(mixed ? KEY_AUDIO_PROJ_TYPE : KEY_PROJ_TYPE, PROJECTOR_TYPE_NAMES[proj].c_str());
+ w.kv(fmt(KEY_N_EMBD, "audio"), hp.n_embd);
+ w.kv(fmt(KEY_N_HEAD, "audio"), hp.n_head);
+ w.kv(fmt(KEY_N_FF, "audio"), hp.n_ff);
+ w.kv(fmt(KEY_N_BLOCK, "audio"), hp.n_layer);
+ w.kv(fmt(KEY_PROJ_DIM, "audio"), hp.n_proj);
+ w.kv(fmt(KEY_LAYER_NORM_EPS, "audio"), hp.eps);
+ w.kv(KEY_A_NUM_MEL_BINS, n_mel);
+}
+
+static void add_gen_audio_kv(mmproj_writer & w, projector_type proj, const enc_hparams & hp, bool mixed = false) {
+ w.kv(KEY_HAS_GEN_AUDIO_ENC, true);
+ w.kv(mixed ? KEY_GEN_AUDIO_PROJ_TYPE : KEY_PROJ_TYPE, PROJECTOR_TYPE_NAMES[proj].c_str());
+ w.kv(fmt(KEY_N_EMBD, "gen.audio"), hp.n_embd);
+ w.kv(fmt(KEY_N_HEAD, "gen.audio"), hp.n_head);
+ w.kv(fmt(KEY_N_FF, "gen.audio"), hp.n_ff);
+ w.kv(fmt(KEY_N_BLOCK, "gen.audio"), hp.n_layer);
+ w.kv(fmt(KEY_PROJ_DIM, "gen.audio"), hp.n_proj);
+ w.kv(fmt(KEY_LAYER_NORM_EPS, "gen.audio"), hp.eps);
+}
+
+//
+// projector tables
+//
+
+struct test_model {
+ uint32_t n_embd_out = 0; // n_embd of the text model
+ bool vision = false; // encode images
+ bool audio = false; // encode audio clips
+ bool stream = false; // run an mtmd_audio_stream
+ bool text_mrope = false; // the text model uses M-RoPE
+
+ // optional overrides of the inputs, see make_inputs()
+ std::vector<std::pair<int, int>> image_sizes;
+ std::vector<float> audio_seconds;
+
+ // audio generation: run a few steps with fixed inputs, append the outputs to out
+ // the outputs are compared across backends, so they must not depend on random sampling
+ std::function<bool(mtmd_context * ctx, std::vector<float> & out)> gen;
+
+ // non-empty: the case is known to fail, it is skipped and the reason is printed
+ std::string todo;
+
+ // max NMSE of a backend vs CPU
+ double nmse_max = 1e-4;
+};
+
+//
+// group g1: dynamic-resolution vision (qwen-vl like)
+//
+
+struct g1_vit_opts {
+ vit_opts base;
+ bool qkv_fused = false;
+ int64_t n_embd_kv = 0; // GQA: k/v width, 0 = n_embd
+ int64_t qk_norm = 0; // q/k norm size: 0 = none
+ bool qk_norm_b = false;
+};
+
+// like add_vit, with fused qkv, GQA and q/k norm
+static void g1_add_vit(mmproj_writer & w, const char * prefix, int n_layer, int64_t n_embd, int64_t n_ff, const g1_vit_opts & g) {
+ const vit_opts & o = g.base;
+ const int64_t n_kv = g.n_embd_kv > 0 ? g.n_embd_kv : n_embd;
+ if (!g.qkv_fused && n_kv == n_embd && g.qk_norm == 0) {
+ add_vit(w, prefix, n_layer, n_embd, n_ff, o);
+ return;
+ }
+ for (int il = 0; il < n_layer; il++) {
+ if (g.qkv_fused) {
+ w.tensor(fmt(TN_ATTN_QKV, prefix, il, "weight"), {n_embd, n_embd + 2 * n_kv});
+ if (o.qkv_bias) {
+ w.tensor(fmt(TN_ATTN_QKV, prefix, il, "bias"), {n_embd + 2 * n_kv});
+ }
+ } else {
+ w.tensor(fmt(TN_ATTN_Q, prefix, il, "weight"), {n_embd, n_embd});
+ w.tensor(fmt(TN_ATTN_K, prefix, il, "weight"), {n_embd, n_kv});
+ w.tensor(fmt(TN_ATTN_V, prefix, il, "weight"), {n_embd, n_kv});
+ if (o.qkv_bias) {
+ w.tensor(fmt(TN_ATTN_Q, prefix, il, "bias"), {n_embd});
+ if (o.k_bias) {
+ w.tensor(fmt(TN_ATTN_K, prefix, il, "bias"), {n_kv});
+ }
+ w.tensor(fmt(TN_ATTN_V, prefix, il, "bias"), {n_kv});
+ }
+ }
+ if (g.qk_norm > 0) {
+ w.norm(fmt(TN_ATTN_Q_NORM, prefix, il, "weight"), g.qk_norm);
+ w.norm(fmt(TN_ATTN_K_NORM, prefix, il, "weight"), g.qk_norm);
+ if (g.qk_norm_b) {
+ w.tensor(fmt(TN_ATTN_Q_NORM, prefix, il, "bias"), {g.qk_norm});
+ w.tensor(fmt(TN_ATTN_K_NORM, prefix, il, "bias"), {g.qk_norm});
+ }
+ }
+ w.tensor(fmt(TN_ATTN_OUTPUT, prefix, il, "weight"), {n_embd, n_embd});
+ if (o.o_bias) {
+ w.tensor(fmt(TN_ATTN_OUTPUT, prefix, il, "bias"), {n_embd});
+ }
+ w.norm(fmt(TN_LN_1, prefix, il, "weight"), n_embd);
+ w.norm(fmt(TN_LN_2, prefix, il, "weight"), n_embd);
+ if (o.ln_bias) {
+ w.tensor(fmt(TN_LN_1, prefix, il, "bias"), {n_embd});
+ w.tensor(fmt(TN_LN_2, prefix, il, "bias"), {n_embd});
+ }
+ w.tensor(fmt(TN_FFN_UP, prefix, il, "weight"), {n_embd, n_ff});
+ w.tensor(fmt(TN_FFN_DOWN, prefix, il, "weight"), {n_ff, n_embd});
+ if (o.ffn_gate) {
+ w.tensor(fmt(TN_FFN_GATE, prefix, il, "weight"), {n_embd, n_ff});
+ }
+ if (o.ffn_bias) {
+ w.tensor(fmt(TN_FFN_UP, prefix, il, "bias"), {n_ff});
+ w.tensor(fmt(TN_FFN_DOWN, prefix, il, "bias"), {n_embd});
+ if (o.ffn_gate) {
+ w.tensor(fmt(TN_FFN_GATE, prefix, il, "bias"), {n_ff});
+ }
+ }
+ }
+ if (o.post_ln) {
+ w.norm(fmt(TN_LN_POST, prefix, "weight"), n_embd);
+ if (o.ln_bias) {
+ w.tensor(fmt(TN_LN_POST, prefix, "bias"), {n_embd});
+ }
+ }
+}
+
+static bool make_mmproj_g1(projector_type proj, mmproj_writer & w, test_model & tm) {
+ enc_hparams hp;
+ tm.n_embd_out = hp.n_proj;
+ switch (proj) {
+ case PROJECTOR_TYPE_QWEN2VL:
+ {
+ // temporal conv pair, 2x2 merge, M-RoPE
+ const uint32_t patch_size = 14;
+ add_vision_kv(w, proj, hp, 560, patch_size);
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_EMBD_1, {patch_size, patch_size, 3, hp.n_embd});
+ add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, {});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {4 * hp.n_embd, 4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "bias"), {4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {4 * hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+ tm.vision = true;
+ tm.text_mrope = true;
+ } break;
+ case PROJECTOR_TYPE_QWEN3VL:
+ {
+ // fused qkv, learned pos embd, deepstack on layer 0: output = main + deepstack rows
+ const uint32_t patch_size = 16;
+ const int64_t n_out = hp.n_proj / 2;
+ add_vision_kv(w, proj, hp, 768, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_EMBD_1, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_BIAS, {hp.n_embd});
+ w.tensor(fmt(TN_POS_EMBD, "v"), {hp.n_embd, 16 * 16});
+ g1_vit_opts g;
+ g.qkv_fused = true;
+ g1_add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, g);
+ w.norm(fmt(TN_DEEPSTACK_NORM, 0, "weight"), 4 * hp.n_embd);
+ w.tensor(fmt(TN_DEEPSTACK_NORM, 0, "bias"), {4 * hp.n_embd});
+ w.tensor(fmt(TN_DEEPSTACK_FC1, 0, "weight"), {4 * hp.n_embd, 4 * hp.n_embd});
+ w.tensor(fmt(TN_DEEPSTACK_FC1, 0, "bias"), {4 * hp.n_embd});
+ w.tensor(fmt(TN_DEEPSTACK_FC2, 0, "weight"), {4 * hp.n_embd, n_out});
+ w.tensor(fmt(TN_DEEPSTACK_FC2, 0, "bias"), {n_out});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {4 * hp.n_embd, 4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "bias"), {4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {4 * hp.n_embd, n_out});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {n_out});
+ tm.vision = true;
+ tm.text_mrope = true;
+ } break;
+ case PROJECTOR_TYPE_LING3VL:
+ {
+ // qwen3vl tower without deepstack, merger norm before the 2x2 merge
+ const uint32_t patch_size = 16;
+ add_vision_kv(w, proj, hp, 768, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_EMBD_1, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_BIAS, {hp.n_embd});
+ w.tensor(fmt(TN_POS_EMBD, "v"), {hp.n_embd, 16 * 16});
+ g1_vit_opts g;
+ g.qkv_fused = true;
+ g.base.post_ln = false;
+ g1_add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, g);
+ w.norm(TN_MM_INP_NORM, hp.n_embd);
+ w.tensor(TN_MM_INP_NORM_B, {hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {4 * hp.n_embd, 4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "bias"), {4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {4 * hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+ tm.vision = true;
+ tm.text_mrope = true;
+ } break;
+ case PROJECTOR_TYPE_GLM4V:
+ case PROJECTOR_TYPE_GLM5V:
+ {
+ // RMS ViT, conv patch merger, fc + post norm, swiglu ffn projector
+ const uint32_t patch_size = 14;
+ const int64_t n_mid = 96;
+ add_vision_kv(w, proj, hp, 336, patch_size);
+ w.kv(KEY_USE_SILU, true);
+ if (proj == PROJECTOR_TYPE_GLM5V) {
+ w.kv(KEY_SWIGLU_CLAMP, 7.0f);
+ w.kv(KEY_IMAGE_MIN_PIXELS, uint32_t(4 * 28 * 28));
+ w.kv(KEY_IMAGE_MAX_PIXELS, uint32_t(1024 * 28 * 28));
+ }
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_EMBD_1, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_BIAS, {hp.n_embd});
+ w.norm(fmt(TN_NORM_EMBD, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_POS_EMBD, "v"), {hp.n_embd, 24 * 24});
+ vit_opts o;
+ o.ln_bias = false;
+ o.ffn_gate = true;
+ o.o_bias = false;
+ add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, o);
+ w.tensor(fmt(TN_MM_PATCH_MERGER, "weight"), {2, 2, hp.n_embd, n_mid});
+ w.tensor(fmt(TN_MM_PATCH_MERGER, "bias"), {n_mid});
+ w.tensor(fmt(TN_MM_PROJECTOR, "weight"), {n_mid, n_mid});
+ w.norm(fmt(TN_MM_POST_NORM, "weight"), n_mid);
+ w.tensor(fmt(TN_MM_POST_NORM, "bias"), {n_mid});
+ w.tensor(fmt(TN_MM_UP, "weight"), {n_mid, hp.n_ff});
+ w.tensor(fmt(TN_MM_GATE, "weight"), {n_mid, hp.n_ff});
+ w.tensor(fmt(TN_MM_DOWN, "weight"), {hp.n_ff, hp.n_proj});
+ tm.vision = true;
+ tm.text_mrope = true;
+ } break;
+ case PROJECTOR_TYPE_MAGEVL:
+ {
+ // d_head must be a multiple of 32, one rope factor per head dim
+ const uint32_t patch_size = 16;
+ add_vision_kv(w, proj, hp, 512, patch_size);
+ w.kv(KEY_SPATIAL_MERGE_SIZE, uint32_t(2));
+ w.kv(KEY_IMAGE_MIN_PIXELS, uint32_t(4 * 32 * 32));
+ w.kv(KEY_IMAGE_MAX_PIXELS, uint32_t(1024 * 32 * 32));
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ // factors near 1, the rope base is 1 so they set the frequencies
+ w.norm(TN_ROPE_FREQS, hp.n_embd / hp.n_head);
+ add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, {});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {4 * hp.n_embd, 4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "bias"), {4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {4 * hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+ tm.vision = true;
+ tm.text_mrope = true;
+ } break;
+ case PROJECTOR_TYPE_MIMOVL:
+ {
+ // GQA fused qkv, one layer per window mode: row window, col window, full
+ const uint32_t patch_size = 16;
+ const int64_t d_head = 32;
+ hp.n_layer = 3;
+ add_vision_kv(w, proj, hp, 512, patch_size);
+ w.kv(KEY_USE_SILU, true);
+ w.kv(fmt(KEY_N_HEAD_KV, "vision"), uint32_t(1));
+ w.kv(KEY_ATTN_WINDOW_SIZE, uint32_t(8));
+ w.kv(KEY_WA_PATTERN_MODE, std::vector<int32_t>{0, 1, -1});
+ w.kv(KEY_IMAGE_MIN_PIXELS, uint32_t(4 * 32 * 32));
+ w.kv(KEY_IMAGE_MAX_PIXELS, uint32_t(1024 * 32 * 32));
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_EMBD_1, {patch_size, patch_size, 3, hp.n_embd});
+ g1_vit_opts g;
+ g.qkv_fused = true;
+ g.n_embd_kv = d_head;
+ g.base.ln_bias = false;
+ g.base.ffn_gate = true;
+ g1_add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, g);
+ // the post norm of the merger is a LayerNorm with bias
+ w.tensor(fmt(TN_LN_POST, "v", "bias"), {hp.n_embd});
+ for (int il = 0; il < 2; il++) {
+ w.tensor(fmt(TN_ATTN_SINKS, "v", il), {hp.n_head});
+ }
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {4 * hp.n_embd, 4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {4 * hp.n_embd, hp.n_proj});
+ tm.vision = true;
+ tm.text_mrope = true;
+ } break;
+ case PROJECTOR_TYPE_EXAONE4_5:
+ {
+ // qwen2.5vl-like with GQA fused qkv and window attention
+ const uint32_t patch_size = 14;
+ add_vision_kv(w, proj, hp, 560, patch_size);
+ w.kv(KEY_USE_SILU, true);
+ w.kv(fmt(KEY_N_HEAD_KV, "vision"), uint32_t(1));
+ w.kv(KEY_WIN_ATTN_PATTERN, uint32_t(2));
+ w.kv(KEY_IMAGE_MIN_PIXELS, uint32_t(4 * 28 * 28));
+ w.kv(KEY_IMAGE_MAX_PIXELS, uint32_t(1024 * 28 * 28));
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_EMBD_1, {patch_size, patch_size, 3, hp.n_embd});
+ g1_vit_opts g;
+ g.qkv_fused = true;
+ g.n_embd_kv = hp.n_embd / hp.n_head;
+ g.base.ln_bias = false;
+ g.base.ffn_gate = true;
+ g1_add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, g);
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {4 * hp.n_embd, 4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "bias"), {4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {4 * hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+ tm.vision = true;
+ tm.text_mrope = true;
+ } break;
+ case PROJECTOR_TYPE_YOUTUVL:
+ {
+ // linear patch embd, window attention except on wa_layer_indexes, RMS merger norm
+ const uint32_t patch_size = 16;
+ add_vision_kv(w, proj, hp, 512, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ w.kv(KEY_ATTN_WINDOW_SIZE, uint32_t(64));
+ w.kv(KEY_WIN_ATTN_LAYER_INDEXES, std::vector<int32_t>{1});
+ w.tensor(TN_PATCH_EMBD, {3 * patch_size * patch_size, hp.n_embd});
+ w.tensor(TN_PATCH_BIAS, {hp.n_embd});
+ add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, {});
+ w.norm(TN_MM_INP_NORM, hp.n_embd);
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {4 * hp.n_embd, 4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "bias"), {4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {4 * hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_HUNYUANVL:
+ case PROJECTOR_TYPE_HY_V4_FLASH:
+ {
+ // pos embd resampled on the host, conv merger with a newline column
+ const bool is_hy = proj == PROJECTOR_TYPE_HUNYUANVL;
+ const uint32_t patch_size = 16;
+ const int64_t n_mid = 2 * hp.n_embd;
+ const int64_t n_conv_out = is_hy ? 4 * hp.n_embd : int64_t(hp.n_proj);
+ add_vision_kv(w, proj, hp, 512, patch_size);
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_BIAS, {hp.n_embd});
+ w.tensor(fmt(TN_POS_EMBD, "v"), {hp.n_embd, 16 * 16});
+ vit_opts o;
+ o.post_ln = false;
+ add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, o);
+ w.norm(fmt(TN_MM_PRE_NORM, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {2, 2, hp.n_embd, n_mid});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "bias"), {n_mid});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {1, 1, n_mid, n_conv_out});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {n_conv_out});
+ w.tensor(TN_IMAGE_NEWLINE, {n_conv_out});
+ if (is_hy) {
+ w.tensor(fmt(TN_MM_PROJECTOR, "weight"), {n_conv_out, hp.n_proj});
+ w.tensor(fmt(TN_MM_PROJECTOR, "bias"), {hp.n_proj});
+ w.norm(fmt(TN_MM_POST_NORM, "weight"), hp.n_proj);
+ w.tensor(TN_MM_IMG_BEGIN, {hp.n_proj});
+ w.tensor(TN_MM_IMG_END, {hp.n_proj});
+ }
+ // the token count check of hunyuanvl reads the M-RoPE grid size
+ tm.vision = true;
+ tm.text_mrope = true;
+ } break;
+ case PROJECTOR_TYPE_PADDLEOCR:
+ {
+ // siglip-like ViT with learned pos embd + 2D rope, 2x2 merge mlp
+ const uint32_t patch_size = 14;
+ add_vision_kv(w, proj, hp, 336, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ w.kv(KEY_IMAGE_MIN_PIXELS, uint32_t(4 * 28 * 28));
+ w.kv(KEY_IMAGE_MAX_PIXELS, uint32_t(1024 * 28 * 28));
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_BIAS, {hp.n_embd});
+ w.tensor(fmt(TN_POS_EMBD, "v"), {hp.n_embd, 24 * 24});
+ add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, {});
+ w.norm(TN_MM_INP_NORM, hp.n_embd);
+ w.tensor(TN_MM_INP_NORM_B, {hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "weight"), {4 * hp.n_embd, 4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "bias"), {4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {4 * hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+ tm.vision = true;
+ tm.text_mrope = true;
+ } break;
+ case PROJECTOR_TYPE_KIMIVL:
+ case PROJECTOR_TYPE_KIMIK25:
+ case PROJECTOR_TYPE_KIMIK31:
+ {
+ // learned pos embd + 2D rope, 2x2 patch merge mlp
+ const bool is_k31 = proj == PROJECTOR_TYPE_KIMIK31;
+ const uint32_t patch_size = 14;
+ add_vision_kv(w, proj, hp, 448, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ w.kv(KEY_PROJ_SCALE_FACTOR, uint32_t(2));
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_BIAS, {hp.n_embd});
+ if (proj == PROJECTOR_TYPE_KIMIVL) {
+ w.tensor(fmt(TN_POS_EMBD, "v"), {hp.n_embd, 16 * 16});
+ } else {
+ // stored as [C, W, H]
+ w.tensor(fmt(TN_POS_EMBD, "v"), {hp.n_embd, 16, 16});
+ }
+ vit_opts o;
+ o.ln_bias = !is_k31;
+ add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, o);
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "weight"), {4 * hp.n_embd, 4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {4 * hp.n_embd, hp.n_proj});
+ if (is_k31) {
+ w.norm(fmt(TN_MM_POST_NORM, "weight"), hp.n_proj);
+ } else {
+ w.norm(TN_MM_INP_NORM, hp.n_embd);
+ w.tensor(TN_MM_INP_NORM_B, {hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "bias"), {4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+ }
+ tm.vision = true;
+ if (proj != PROJECTOR_TYPE_KIMIVL) {
+ tm.todo = "REALLOC: kimik25 preprocessor scales with floor(w/ps), then aligns up, 4000x4000 gives one merged row/col more than the warmup (k25 65x65 vs 64x64, k31 47x47 vs 46x46)";
+ }
+ } break;
+ case PROJECTOR_TYPE_DOTS_OCR:
+ case PROJECTOR_TYPE_DOTS3NOTE_V:
+ {
+ // RMS ViT with 2D rope, post trunk norm, 2x2 merge mlp
+ // dots3note: layer 1 is a sigmoid-routed MoE ffn
+ const bool is_moe = proj == PROJECTOR_TYPE_DOTS3NOTE_V;
+ const uint32_t patch_size = 14;
+ const int64_t n_expert = 4;
+ add_vision_kv(w, proj, hp, 336, patch_size);
+ w.kv(KEY_USE_SILU, true);
+ if (is_moe) {
+ w.kv(KEY_SPATIAL_MERGE_SIZE, uint32_t(2));
+ w.kv(KEY_VISION_N_EXPERT_USED, uint32_t(2));
+ } else {
+ w.kv(KEY_PROJ_SCALE_FACTOR, uint32_t(2));
+ }
+ w.kv(KEY_IMAGE_MIN_PIXELS, uint32_t(4 * 28 * 28));
+ w.kv(KEY_IMAGE_MAX_PIXELS, uint32_t(1024 * 28 * 28));
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_BIAS, {hp.n_embd});
+ vit_opts o;
+ o.ln_bias = false;
+ o.qkv_bias = false;
+ o.o_bias = false;
+ o.ffn_gate = true;
+ o.ffn_bias = false;
+ o.post_ln = false;
+ add_vit(w, "v", is_moe ? 1 : hp.n_layer, hp.n_embd, hp.n_ff, o);
+ if (is_moe) {
+ const int il = 1;
+ for (const char * x : {"q", "k", "v"}) {
+ w.tensor(fmt("v.blk.%d.attn_%s.weight", il, x), {hp.n_embd, hp.n_embd});
+ }
+ w.tensor(fmt(TN_ATTN_OUTPUT, "v", il, "weight"), {hp.n_embd, hp.n_embd});
+ w.norm(fmt(TN_LN_1, "v", il, "weight"), hp.n_embd);
+ w.norm(fmt(TN_LN_2, "v", il, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_FFN_GATE_INP, "v", il, "weight"), {hp.n_embd, n_expert});
+ w.tensor(fmt(TN_FFN_GATE_EXPS, "v", il, "weight"), {hp.n_embd, hp.n_ff, n_expert});
+ w.tensor(fmt(TN_FFN_UP_EXPS, "v", il, "weight"), {hp.n_embd, hp.n_ff, n_expert});
+ w.tensor(fmt(TN_FFN_DOWN_EXPS, "v", il, "weight"), {hp.n_ff, hp.n_embd, n_expert});
+ w.tensor(fmt(TN_FFN_EXP_PROBS_B, "v", il, "weight"), {n_expert});
+ }
+ w.norm(fmt(TN_MM_POST_NORM, "weight"), hp.n_embd);
+ w.norm(TN_MM_INP_NORM, hp.n_embd);
+ w.tensor(TN_MM_INP_NORM_B, {hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {4 * hp.n_embd, 4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "bias"), {4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {4 * hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+ tm.vision = true;
+ if (is_moe) {
+ // Vulkan coopmat F16 matmuls give NMSE 1.02e-4
+ tm.nmse_max = 2e-4;
+ }
+ } break;
+ case PROJECTOR_TYPE_SENSENOVA_U1:
+ {
+ // no transformer blocks: patch embd, gelu, 2D rope, conv merge to the text width
+ const uint32_t patch_size = 16;
+ hp.n_layer = 0;
+ hp.n_head = 1;
+ hp.n_ff = 0;
+ add_vision_kv(w, proj, hp, 0, patch_size);
+ w.kv(fmt(KEY_N_EMBD_HEAD, "vision"), hp.n_embd);
+ w.kv(KEY_SPATIAL_MERGE_SIZE, uint32_t(2));
+ w.kv(KEY_IMAGE_MIN_PIXELS, uint32_t(4 * 32 * 32));
+ w.kv(KEY_IMAGE_MAX_PIXELS, uint32_t(1024 * 32 * 32));
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_BIAS, {hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {2, 2, hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "bias"), {hp.n_proj});
+ tm.vision = true;
+ tm.text_mrope = true;
+ } break;
+ case PROJECTOR_TYPE_MINIMAX_M3:
+ {
+ // temporal conv pair, h/w neox rope on 3 axes, per-patch mlp then 2x2 merge mlp
+ const uint32_t patch_size = 14;
+ const int64_t n_mid = 96;
+ add_vision_kv(w, proj, hp, 336, patch_size);
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_EMBD_1, {patch_size, patch_size, 3, hp.n_embd});
+ vit_opts o;
+ o.post_ln = false;
+ add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, o);
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "weight"), {hp.n_embd, n_mid});
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "bias"), {n_mid});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {n_mid, n_mid});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {n_mid});
+ w.tensor(fmt(TN_MM_MERGER_FC1, "weight"), {4 * n_mid, n_mid});
+ w.tensor(fmt(TN_MM_MERGER_FC1, "bias"), {n_mid});
+ w.tensor(fmt(TN_MM_MERGER_FC2, "weight"), {n_mid, hp.n_proj});
+ w.tensor(fmt(TN_MM_MERGER_FC2, "bias"), {hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_MUSE_GLIMMER:
+ {
+ // the pos embd grid side (8) is also the sparse window size; layer 0 sparse, layer 1 global
+ const uint32_t patch_size = 16;
+ const int64_t n_mid = 96;
+ add_vision_kv(w, proj, hp, 256, patch_size);
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_BIAS, {hp.n_embd});
+ w.tensor(fmt(TN_POS_EMBD, "v"), {hp.n_embd, 8 * 8});
+ w.norm(fmt(TN_LN_PRE, "v", "weight"), hp.n_embd);
+ w.tensor(fmt(TN_LN_PRE, "v", "bias"), {hp.n_embd});
+ add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, {});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {4 * hp.n_embd, n_mid});
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "weight"), {n_mid, n_mid});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {n_mid, hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_INKLING2V:
+ {
+ // CLS token with its own pos embd, learned pos embd + 2D rope, 2x2 merge mlp
+ const uint32_t patch_size = 14;
+ add_vision_kv(w, proj, hp, 224, patch_size);
+ w.kv(KEY_SPATIAL_MERGE_SIZE, uint32_t(2));
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_CLASS_EMBD, {hp.n_embd});
+ w.tensor(TN_CLASS_POS_EMBD, {hp.n_embd});
+ w.tensor(fmt(TN_POS_EMBD, "v"), {hp.n_embd, 16 * 16});
+ w.norm(fmt(TN_LN_PRE, "v", "weight"), hp.n_embd);
+ w.tensor(fmt(TN_LN_PRE, "v", "bias"), {hp.n_embd});
+ vit_opts o;
+ o.post_ln = false;
+ add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, o);
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "weight"), {4 * hp.n_embd, 4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "bias"), {4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {4 * hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+ tm.vision = true;
+ } break;
+ default:
+ return false;
+ }
+ return true;
+}
+
+//
+// group g2: llava-style, siglip/clip, tiled / llava-uhd vision
+//
+
+// patch embedding + learned position embedding with n_pos rows + ViT layers
+static void g2_add_tower(mmproj_writer & w, const enc_hparams & hp, uint32_t patch_size, int64_t n_pos, bool patch_bias, const vit_opts & o) {
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ if (patch_bias) {
+ w.tensor(TN_PATCH_BIAS, {hp.n_embd});
+ }
+ if (n_pos > 0) {
+ w.tensor(fmt(TN_POS_EMBD, "v"), {hp.n_embd, n_pos});
+ }
+ add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, o);
+}
+
+static bool make_mmproj_g2(projector_type proj, mmproj_writer & w, test_model & tm) {
+ enc_hparams hp;
+ tm.n_embd_out = hp.n_proj;
+ const int64_t H = hp.n_proj;
+ switch (proj) {
+ case PROJECTOR_TYPE_MLP:
+ {
+ // clip with CLS + pre_ln, the last layer is skipped by the graph
+ const uint32_t image_size = 64;
+ const uint32_t patch_size = 16;
+ const int64_t n_patches = (image_size / patch_size) * (image_size / patch_size);
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.tensor(TN_CLASS_EMBD, {hp.n_embd});
+ w.norm(fmt(TN_LN_PRE, "v", "weight"), hp.n_embd);
+ w.tensor(fmt(TN_LN_PRE, "v", "bias"), {hp.n_embd});
+ vit_opts o;
+ o.post_ln = false;
+ g2_add_tower(w, hp, patch_size, n_patches + 1, false, o);
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {hp.n_embd, H});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "bias"), {H});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {H, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_LDP:
+ case PROJECTOR_TYPE_LDPV2:
+ {
+ // the projector assumes a 24x24 patch grid
+ const uint32_t patch_size = 4;
+ const uint32_t image_size = 24 * patch_size;
+ const int64_t n_patches = 24 * 24;
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ vit_opts o;
+ o.post_ln = false;
+ g2_add_tower(w, hp, patch_size, n_patches, false, o);
+ if (proj == PROJECTOR_TYPE_LDP) {
+ w.tensor(fmt(TN_MVLM_PROJ_MLP, 1, "weight"), {hp.n_embd, H});
+ w.tensor(fmt(TN_MVLM_PROJ_MLP, 1, "bias"), {H});
+ w.tensor(fmt(TN_MVLM_PROJ_MLP, 3, "weight"), {H, H});
+ w.tensor(fmt(TN_MVLM_PROJ_MLP, 3, "bias"), {H});
+ for (int b = 1; b <= 2; b++) {
+ w.tensor(fmt(TN_MVLM_PROJ_BLOCK, b, 0, "0.weight"), {3, 3, 1, H});
+ w.norm (fmt(TN_MVLM_PROJ_BLOCK, b, 0, "1.weight"), H);
+ w.tensor(fmt(TN_MVLM_PROJ_BLOCK, b, 0, "1.bias"), {H});
+ w.tensor(fmt(TN_MVLM_PROJ_BLOCK, b, 1, "fc1.weight"), {H, H / 4});
+ w.tensor(fmt(TN_MVLM_PROJ_BLOCK, b, 1, "fc1.bias"), {H / 4});
+ w.tensor(fmt(TN_MVLM_PROJ_BLOCK, b, 1, "fc2.weight"), {H / 4, H});
+ w.tensor(fmt(TN_MVLM_PROJ_BLOCK, b, 1, "fc2.bias"), {H});
+ w.tensor(fmt(TN_MVLM_PROJ_BLOCK, b, 2, "0.weight"), {H, H});
+ w.norm (fmt(TN_MVLM_PROJ_BLOCK, b, 2, "1.weight"), H);
+ w.tensor(fmt(TN_MVLM_PROJ_BLOCK, b, 2, "1.bias"), {H});
+ }
+ } else {
+ w.tensor(fmt(TN_MVLM_PROJ_MLP, 0, "weight"), {hp.n_embd, H});
+ w.tensor(fmt(TN_MVLM_PROJ_MLP, 0, "bias"), {H});
+ w.tensor(fmt(TN_MVLM_PROJ_MLP, 2, "weight"), {H, H});
+ w.tensor(fmt(TN_MVLM_PROJ_MLP, 2, "bias"), {H});
+ w.tensor(fmt(TN_MVLM_PROJ_PEG, 0, "weight"), {3, 3, 1, H});
+ w.tensor(fmt(TN_MVLM_PROJ_PEG, 0, "bias"), {H});
+ }
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_GLM_EDGE:
+ {
+ // 4x4 patches, stride-2 conv -> 2x2 tokens + boi/eoi
+ const uint32_t image_size = 64;
+ const uint32_t patch_size = 16;
+ const int64_t n_patches = (image_size / patch_size) * (image_size / patch_size);
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ g2_add_tower(w, hp, patch_size, n_patches, true, {});
+ w.tensor(fmt(TN_GLM_ADAPER_CONV, "weight"), {2, 2, hp.n_embd, H});
+ w.tensor(fmt(TN_GLM_ADAPER_CONV, "bias"), {H});
+ w.tensor(fmt(TN_GLM_ADAPTER_LINEAR, "weight"), {H, H});
+ w.norm (fmt(TN_GLM_ADAPTER_NORM_1, "weight"), H);
+ w.tensor(fmt(TN_GLM_ADAPTER_NORM_1, "bias"), {H});
+ w.tensor(fmt(TN_GLM_ADAPTER_D_H_2_4H, "weight"), {H, 2 * H});
+ w.tensor(fmt(TN_GLM_ADAPTER_GATE, "weight"), {H, 2 * H});
+ w.tensor(fmt(TN_GLM_ADAPTER_D_4H_2_H, "weight"), {2 * H, hp.n_proj});
+ w.tensor(TN_TOK_GLM_BOI, {hp.n_proj, 1});
+ w.tensor(TN_TOK_GLM_EOI, {hp.n_proj, 1});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_JANUS_PRO:
+ {
+ // siglip, fixed size
+ const uint32_t image_size = 64;
+ const uint32_t patch_size = 16;
+ const int64_t n_patches = (image_size / patch_size) * (image_size / patch_size);
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ g2_add_tower(w, hp, patch_size, n_patches, true, {});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {hp.n_embd, H});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "bias"), {H});
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "weight"), {H, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "bias"), {hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_PHI4:
+ {
+ // siglip2 naflex, dynamic size with resized position embeddings
+ const uint32_t image_size = 256;
+ const uint32_t patch_size = 16;
+ const int64_t n_side = image_size / patch_size;
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ w.kv(KEY_IMAGE_MIN_PIXELS, uint32_t(16 * patch_size * patch_size));
+ w.kv(KEY_IMAGE_MAX_PIXELS, uint32_t(256 * patch_size * patch_size));
+ g2_add_tower(w, hp, patch_size, n_side * n_side, true, {});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {hp.n_embd, H});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "bias"), {H});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {H, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_IDEFICS3:
+ {
+ // siglip tiles + global image, pixel shuffle by 2
+ const uint32_t image_size = 64;
+ const uint32_t patch_size = 16;
+ const uint32_t n_merge = 2;
+ const int64_t n_patches = (image_size / patch_size) * (image_size / patch_size);
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ w.kv(KEY_PROJ_SCALE_FACTOR, n_merge);
+ w.kv(KEY_PREPROC_IMAGE_SIZE, uint32_t(4 * image_size));
+ g2_add_tower(w, hp, patch_size, n_patches, true, {});
+ w.tensor(fmt(TN_MM_PROJECTOR, "weight"), {n_merge * n_merge * hp.n_embd, hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_COHERE2V:
+ {
+ // siglip tiles + thumbnail, pixel shuffle by 2, swiglu projector
+ const uint32_t image_size = 64;
+ const uint32_t patch_size = 16;
+ const uint32_t n_merge = 2;
+ const int64_t n_patches = (image_size / patch_size) * (image_size / patch_size);
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ w.kv(KEY_PROJ_SCALE_FACTOR, n_merge);
+ w.kv(KEY_PREPROC_MAX_TILES, uint32_t(6));
+ g2_add_tower(w, hp, patch_size, n_patches, true, {});
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "weight"), {n_merge * n_merge * hp.n_embd, 2 * H});
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "bias"), {2 * H});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {H, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_LFM2:
+ case PROJECTOR_TYPE_D1OMNI_V:
+ {
+ // siglip2 naflex tiles + thumbnail, pixel unshuffle by 2
+ const uint32_t image_size = 256;
+ const uint32_t patch_size = 16;
+ const uint32_t n_merge = 2;
+ const int64_t n_side = image_size / patch_size;
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ w.kv(KEY_PROJ_SCALE_FACTOR, n_merge);
+ w.kv(KEY_PREPROC_TILE_SIZE, image_size);
+ g2_add_tower(w, hp, patch_size, n_side * n_side, true, {});
+ w.norm (TN_MM_INP_NORM, n_merge * n_merge * hp.n_embd);
+ w.tensor(TN_MM_INP_NORM_B, {n_merge * n_merge * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "weight"), {n_merge * n_merge * hp.n_embd, H});
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "bias"), {H});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {H, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_INTERNVL:
+ {
+ // intern-vit with CLS, tiles + thumbnail, pixel shuffle by 2
+ const uint32_t image_size = 64;
+ const uint32_t patch_size = 16;
+ const uint32_t n_merge = 2;
+ const int64_t n_patches = (image_size / patch_size) * (image_size / patch_size);
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ w.kv(KEY_PROJ_SCALE_FACTOR, n_merge);
+ w.kv(KEY_PREPROC_MAX_TILES, uint32_t(6));
+ w.tensor(TN_CLASS_EMBD, {hp.n_embd});
+ vit_opts o;
+ o.post_ln = false;
+ g2_add_tower(w, hp, patch_size, n_patches + 1, true, o);
+ for (int il = 0; il < (int) hp.n_layer; il++) {
+ w.tensor(fmt(TN_LS_1, "v", il, "weight"), {hp.n_embd}, 1.0f);
+ w.tensor(fmt(TN_LS_2, "v", il, "weight"), {hp.n_embd}, 1.0f);
+ }
+ w.norm (fmt(TN_MVLM_PROJ_MLP, 0, "weight"), n_merge * n_merge * hp.n_embd);
+ w.tensor(fmt(TN_MVLM_PROJ_MLP, 0, "bias"), {n_merge * n_merge * hp.n_embd});
+ w.tensor(fmt(TN_MVLM_PROJ_MLP, 1, "weight"), {n_merge * n_merge * hp.n_embd, H});
+ w.tensor(fmt(TN_MVLM_PROJ_MLP, 1, "bias"), {H});
+ w.tensor(fmt(TN_MVLM_PROJ_MLP, 3, "weight"), {H, hp.n_proj});
+ w.tensor(fmt(TN_MVLM_PROJ_MLP, 3, "bias"), {hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_NEMOTRON_V2_VL:
+ case PROJECTOR_TYPE_NEMOTRON_OMNI:
+ {
+ // radio vit with register tokens, pixel shuffle by 2, relu^2 projector
+ const bool omni = proj == PROJECTOR_TYPE_NEMOTRON_OMNI;
+ const uint32_t image_size = 64;
+ const uint32_t patch_size = 16;
+ const uint32_t n_merge = 2;
+ const int64_t n_side = image_size / patch_size;
+ const int64_t n_reg = 2;
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.kv(KEY_PROJ_SCALE_FACTOR, n_merge);
+ if (omni) {
+ w.kv(KEY_IMAGE_MIN_PIXELS, uint32_t(16 * patch_size * patch_size));
+ w.kv(KEY_IMAGE_MAX_PIXELS, uint32_t(256 * patch_size * patch_size));
+ }
+ w.tensor(TN_CLASS_EMBD, {hp.n_embd, n_reg});
+ vit_opts o;
+ o.post_ln = false;
+ g2_add_tower(w, hp, patch_size, n_side * n_side, false, o);
+ if (omni) {
+ // video tubelet: 2 frames x 3 channels
+ w.tensor(TN_PATCH_EMBD_1, {patch_size, patch_size, 6, hp.n_embd});
+ }
+ w.norm (fmt(TN_MVLM_PROJ_MLP, 0, "weight"), n_merge * n_merge * hp.n_embd);
+ w.tensor(fmt(TN_MVLM_PROJ_MLP, 1, "weight"), {n_merge * n_merge * hp.n_embd, H});
+ w.tensor(fmt(TN_MVLM_PROJ_MLP, 3, "weight"), {H, hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_MINICPMV:
+ {
+ // siglip + llava-uhd slices, resampler with 16 queries
+ // the resampler has d_head = 128 and pos embd buckets on a 70x70 grid
+ const uint32_t image_size = 64;
+ const uint32_t patch_size = 16;
+ const int64_t n_query = 16;
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.kv(KEY_MINICPMV_VERSION, int32_t(3));
+ w.kv(KEY_MINICPMV_QUERY_NUM, uint32_t(n_query));
+ g2_add_tower(w, hp, patch_size, 70 * 70, true, {});
+ w.tensor(TN_MINICPMV_QUERY, {H, n_query});
+ w.tensor(TN_MINICPMV_KV_PROJ, {hp.n_embd, H});
+ w.tensor(TN_MINICPMV_POS_EMBD_K, {H, 70 * 70});
+ for (const char * x : {"q", "k", "v", "out"}) {
+ w.tensor(fmt(TN_MINICPMV_ATTN, x, "weight"), {H, H});
+ w.tensor(fmt(TN_MINICPMV_ATTN, x, "bias"), {H});
+ }
+ for (const char * x : {"q", "kv", "post"}) {
+ w.norm (fmt(TN_MINICPMV_LN, x, "weight"), H);
+ w.tensor(fmt(TN_MINICPMV_LN, x, "bias"), {H});
+ }
+ w.tensor(TN_MINICPMV_PROJ, {H, hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_MINICPMV4_6:
+ case PROJECTOR_TYPE_MINICPMV4_7:
+ case PROJECTOR_TYPE_MINICPM_OCR_1_0:
+ {
+ // siglip + llava-uhd slices, vit merger after layer 0 then final merger (2x2 each)
+ const uint32_t image_size = 256;
+ const uint32_t patch_size = 16;
+ const int64_t n_ff_m = 2 * hp.n_embd;
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ w.kv(KEY_WIN_ATTN_LAYER_INDEXES, std::vector<int32_t>{0});
+ g2_add_tower(w, hp, patch_size, 70 * 70, true, {});
+ w.norm (fmt(TN_VIT_MERGER_LN1, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_VIT_MERGER_LN1, "bias"), {hp.n_embd});
+ for (const char * x : {TN_VIT_MERGER_ATTN_Q, TN_VIT_MERGER_ATTN_K, TN_VIT_MERGER_ATTN_V, TN_VIT_MERGER_ATTN_O}) {
+ w.tensor(fmt(x, "weight"), {hp.n_embd, hp.n_embd});
+ w.tensor(fmt(x, "bias"), {hp.n_embd});
+ }
+ w.norm (fmt(TN_VIT_MERGER_DS_LN, "weight"), 4 * hp.n_embd);
+ w.tensor(fmt(TN_VIT_MERGER_DS_LN, "bias"), {4 * hp.n_embd});
+ w.tensor(fmt(TN_VIT_MERGER_DS_UP, "weight"), {4 * hp.n_embd, n_ff_m});
+ w.tensor(fmt(TN_VIT_MERGER_DS_UP, "bias"), {n_ff_m});
+ w.tensor(fmt(TN_VIT_MERGER_DS_DOWN, "weight"), {n_ff_m, hp.n_embd});
+ w.tensor(fmt(TN_VIT_MERGER_DS_DOWN, "bias"), {hp.n_embd});
+ w.norm (TN_MM_INP_NORM, 4 * hp.n_embd);
+ w.tensor(TN_MM_INP_NORM_B, {4 * hp.n_embd});
+ w.tensor(fmt(TN_MM_UP, "weight"), {4 * hp.n_embd, H});
+ w.tensor(fmt(TN_MM_UP, "bias"), {H});
+ w.tensor(fmt(TN_MM_DOWN, "weight"), {H, hp.n_proj});
+ w.tensor(fmt(TN_MM_DOWN, "bias"), {hp.n_proj});
+ if (proj == PROJECTOR_TYPE_MINICPMV4_7) {
+ // separator rows: </image>, <slice>, </slice>, \n
+ w.tensor(TN_TOK_EMBD_SEP, {hp.n_proj, 4});
+ }
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_PIXTRAL:
+ case PROJECTOR_TYPE_LIGHTONOCR:
+ {
+ // rms-norm vit with 2D rope, mistral 3.1 patch merger (2x2)
+ const uint32_t image_size = 256;
+ const uint32_t patch_size = 16;
+ const uint32_t n_merge = 2;
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.kv(KEY_USE_SILU, true);
+ w.kv(KEY_SPATIAL_MERGE_SIZE, n_merge);
+ w.norm(fmt(TN_LN_PRE, "v", "weight"), hp.n_embd);
+ vit_opts o;
+ o.ln_bias = false;
+ o.qkv_bias = false;
+ o.o_bias = false;
+ o.ffn_gate = true;
+ o.ffn_bias = false;
+ o.post_ln = false;
+ g2_add_tower(w, hp, patch_size, 0, false, o);
+ w.norm (TN_MM_INP_NORM, hp.n_embd);
+ w.tensor(fmt(TN_MM_PATCH_MERGER, "weight"), {n_merge * n_merge * hp.n_embd, hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "weight"), {hp.n_embd, H});
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "bias"), {H});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {H, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+ if (proj == PROJECTOR_TYPE_PIXTRAL) {
+ w.tensor(TN_TOK_IMG_BREAK, {hp.n_proj});
+ }
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_LLAMA4:
+ {
+ // unfold-conv patch embd, CLS, 2D rope, pixel shuffle by 2, llava-uhd tiles
+ const uint32_t image_size = 64;
+ const uint32_t patch_size = 16;
+ const uint32_t n_merge = 2;
+ const int64_t n_patches = (image_size / patch_size) * (image_size / patch_size);
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ w.kv(KEY_PROJ_SCALE_FACTOR, n_merge);
+ // the patch embd is a linear layer on the unfolded patches
+ w.tensor(TN_PATCH_EMBD, {patch_size * patch_size * 3, hp.n_embd});
+ w.tensor(TN_CLASS_EMBD, {hp.n_embd});
+ w.tensor(fmt(TN_POS_EMBD, "v"), {hp.n_embd, n_patches + 1});
+ w.norm (fmt(TN_LN_PRE, "v", "weight"), hp.n_embd);
+ w.tensor(fmt(TN_LN_PRE, "v", "bias"), {hp.n_embd});
+ add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, {});
+ w.tensor(fmt(TN_MVLM_PROJ_MLP, 1, "weight"), {n_merge * n_merge * hp.n_embd, H});
+ w.tensor(fmt(TN_MVLM_PROJ_MLP, 2, "weight"), {H, H});
+ w.tensor(fmt(TN_MM_PROJECTOR, "weight"), {H, hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_COGVLM:
+ {
+ // eva-clip with CLS, fused qkv and post-norm blocks, swiglu projector + boi/eoi
+ const uint32_t image_size = 64;
+ const uint32_t patch_size = 16;
+ const int64_t n_patches = (image_size / patch_size) * (image_size / patch_size);
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_BIAS, {hp.n_embd});
+ w.tensor(TN_CLASS_EMBD, {hp.n_embd});
+ w.tensor(fmt(TN_POS_EMBD, "v"), {hp.n_embd, n_patches + 1});
+ for (int il = 0; il < (int) hp.n_layer; il++) {
+ w.tensor(fmt(TN_ATTN_QKV, "v", il, "weight"), {hp.n_embd, 3 * hp.n_embd});
+ w.tensor(fmt(TN_ATTN_QKV, "v", il, "bias"), {3 * hp.n_embd});
+ w.tensor(fmt(TN_ATTN_OUTPUT, "v", il, "weight"), {hp.n_embd, hp.n_embd});
+ w.tensor(fmt(TN_ATTN_OUTPUT, "v", il, "bias"), {hp.n_embd});
+ w.norm (fmt(TN_LN_1, "v", il, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_LN_1, "v", il, "bias"), {hp.n_embd});
+ w.norm (fmt(TN_LN_2, "v", il, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_LN_2, "v", il, "bias"), {hp.n_embd});
+ w.tensor(fmt(TN_FFN_UP, "v", il, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_FFN_UP, "v", il, "bias"), {hp.n_ff});
+ w.tensor(fmt(TN_FFN_DOWN, "v", il, "weight"), {hp.n_ff, hp.n_embd});
+ w.tensor(fmt(TN_FFN_DOWN, "v", il, "bias"), {hp.n_embd});
+ }
+ w.tensor(fmt(TN_MM_PROJECTOR, "weight"), {hp.n_embd, H});
+ w.norm (fmt(TN_MM_POST_FC_NORM, "weight"), H);
+ w.tensor(fmt(TN_MM_POST_FC_NORM, "bias"), {H});
+ w.tensor(fmt(TN_MM_H_TO_4H, "weight"), {H, 2 * H});
+ w.tensor(fmt(TN_MM_GATE, "weight"), {H, 2 * H});
+ w.tensor(fmt(TN_MM_4H_TO_H, "weight"), {2 * H, hp.n_proj});
+ w.tensor(TN_TOK_BOI, {hp.n_proj});
+ w.tensor(TN_TOK_EOI, {hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_STEP3VL:
+ {
+ // 2D rope vit, two stride-2 conv downsamplers, 504x504 crops + overview
+ // the crops have a fixed size of 504, the overview (image_size) must be larger for the warmup
+ const uint32_t image_size = 560;
+ const uint32_t patch_size = 14;
+ const int64_t n_side = image_size / patch_size;
+ const int64_t C1 = 2 * hp.n_embd;
+ const int64_t C2 = 2 * C1;
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ // limit the number of crops
+ w.kv(KEY_PREPROC_IMAGE_SIZE, uint32_t(1008));
+ g2_add_tower(w, hp, patch_size, n_side * n_side, true, {});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {3, 3, hp.n_embd, C1});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "bias"), {C1});
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "weight"), {3, 3, C1, C2});
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "bias"), {C2});
+ w.tensor(fmt(TN_MM_PROJECTOR, "weight"), {C2, hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_YASA2:
+ {
+ // convnext v2: patchify 4x4, stage 0 at C0, stage 1 downsample to C1, pooled to 8x8 tokens
+ hp.n_layer = 0;
+ const uint32_t image_size = 64;
+ const uint32_t patch_size = 4;
+ const int64_t C0 = hp.n_embd / 2;
+ const int64_t C1 = hp.n_embd;
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, C0});
+ w.tensor(TN_PATCH_BIAS, {C0});
+ w.norm (TN_YASA_PATCH_LN_W, C0);
+ w.tensor(TN_YASA_PATCH_LN_B, {C0});
+ auto add_blocks = [&](int s, int64_t C) {
+ w.tensor(fmt(TN_YASA_STAGE_BLK, s, 0, "dw", "weight"), {7, 7, 1, C});
+ w.tensor(fmt(TN_YASA_STAGE_BLK, s, 0, "dw", "bias"), {C});
+ w.norm (fmt(TN_YASA_STAGE_BLK, s, 0, "ln", "weight"), C);
+ w.tensor(fmt(TN_YASA_STAGE_BLK, s, 0, "ln", "bias"), {C});
+ w.tensor(fmt(TN_YASA_STAGE_BLK, s, 0, "pw1", "weight"), {C, 4 * C});
+ w.tensor(fmt(TN_YASA_STAGE_BLK, s, 0, "pw1", "bias"), {4 * C});
+ w.tensor(fmt(TN_YASA_STAGE_BLK, s, 0, "grn", "weight"), {4 * C});
+ w.tensor(fmt(TN_YASA_STAGE_BLK, s, 0, "grn", "bias"), {4 * C});
+ w.tensor(fmt(TN_YASA_STAGE_BLK, s, 0, "pw2", "weight"), {4 * C, C});
+ w.tensor(fmt(TN_YASA_STAGE_BLK, s, 0, "pw2", "bias"), {C});
+ };
+ add_blocks(0, C0);
+ w.norm (fmt(TN_YASA_STAGE_DOWN_LN, 1, "weight"), C0);
+ w.tensor(fmt(TN_YASA_STAGE_DOWN_LN, 1, "bias"), {C0});
+ w.tensor(fmt(TN_YASA_STAGE_DOWN_CONV, 1, "weight"), {2, 2, C0, C1});
+ w.tensor(fmt(TN_YASA_STAGE_DOWN_CONV, 1, "bias"), {C1});
+ add_blocks(1, C1);
+ w.norm (TN_YASA_BACKBONE_LN_W, C1);
+ w.tensor(TN_YASA_BACKBONE_LN_B, {C1});
+ w.tensor(TN_YASA_POS_EMBD, {C1, 64});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {C1, H});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "bias"), {H});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {H, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_LFM3VL:
+ {
+ // layer 0: gated 3x3 depthwise conv block, layer 1: GQA attention with qk-norm and 2D mrope
+ const uint32_t image_size = 256;
+ const uint32_t patch_size = 16;
+ const uint32_t n_head_kv = 1;
+ const int64_t d_head = hp.n_embd / hp.n_head;
+ const int64_t patch_area = 4 * patch_size * patch_size;
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.kv(KEY_USE_SILU, true);
+ w.kv(fmt(KEY_N_HEAD_KV, "vision"), n_head_kv);
+ w.kv(KEY_SPATIAL_MERGE_SIZE, uint32_t(2));
+ w.kv(KEY_IMAGE_MIN_PIXELS, uint32_t(16 * patch_area));
+ w.kv(KEY_IMAGE_MAX_PIXELS, uint32_t(256 * patch_area));
+ w.kv(KEY_IMAGE_RESIZE_ALGO, "bilinear");
+ // one patchifier kernel per temporal slice
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_EMBD_1, {patch_size, patch_size, 3, hp.n_embd});
+ w.norm(fmt(TN_LFM3VL_EMBEDDING_NORM, "v", "weight"), hp.n_embd);
+ for (int il = 0; il < (int) hp.n_layer; il++) {
+ w.norm(fmt(TN_LN_1, "v", il, "weight"), hp.n_embd);
+ w.norm(fmt(TN_LN_2, "v", il, "weight"), hp.n_embd);
+ if (il == 0) {
+ w.tensor(fmt(TN_LFM3VL_CONV2D_IN_PROJ, "v", il, "weight"), {hp.n_embd, 3 * hp.n_embd});
+ w.tensor(fmt(TN_LFM3VL_CONV2D_SPATIAL, "v", il, "weight"), {3, 3, 1, hp.n_embd});
+ w.tensor(fmt(TN_LFM3VL_CONV2D_OUT_PROJ, "v", il, "weight"), {hp.n_embd, hp.n_embd});
+ } else {
+ w.tensor(fmt(TN_ATTN_Q, "v", il, "weight"), {hp.n_embd, hp.n_embd});
+ w.tensor(fmt(TN_ATTN_K, "v", il, "weight"), {hp.n_embd, n_head_kv * d_head});
+ w.tensor(fmt(TN_ATTN_V, "v", il, "weight"), {hp.n_embd, n_head_kv * d_head});
+ w.tensor(fmt(TN_ATTN_OUTPUT, "v", il, "weight"), {hp.n_embd, hp.n_embd});
+ w.norm (fmt(TN_ATTN_Q_NORM, "v", il, "weight"), d_head);
+ w.norm (fmt(TN_ATTN_K_NORM, "v", il, "weight"), d_head);
+ }
+ w.tensor(fmt(TN_FFN_UP, "v", il, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_FFN_GATE, "v", il, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_FFN_DOWN, "v", il, "weight"), {hp.n_ff, hp.n_embd});
+ }
+ w.norm (TN_MM_INP_NORM, hp.n_embd);
+ w.tensor(TN_MM_INP_NORM_B, {hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {4 * hp.n_embd, H});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "bias"), {H});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {H, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_GRANITE4_VISION:
+ {
+ // siglip on llava-next anyres tiles, one window qformer per feature layer
+ // block 0 downsamples by interpolation, block 1 by a spatial gather (offset 0)
+ // the qformer has d_head = 64
+ const uint32_t image_size = 128;
+ const uint32_t patch_size = 16;
+ const int64_t tile_side = image_size / patch_size;
+ const int64_t window_side = 4;
+ const int64_t query_side = 2;
+ const int64_t n_blocks = 2;
+ hp.n_proj = hp.n_proj / n_blocks;
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ w.kv(KEY_IMAGE_GRID_PINPOINTS, std::vector<int32_t>{128, 256, 256, 128, 256, 256});
+ w.kv(fmt(KEY_FEATURE_LAYERS, "vision"), std::vector<int32_t>{0, 1});
+ w.kv(KEY_PROJ_SPATIAL_OFFSETS, std::vector<int32_t>{-1, 0});
+ w.kv(KEY_PROJ_SAMPLE_QUERY_SIDE, uint32_t(query_side));
+ w.kv(KEY_PROJ_SAMPLE_WINDOW_SIDE, uint32_t(window_side));
+ vit_opts o;
+ o.post_ln = false;
+ g2_add_tower(w, hp, patch_size, tile_side * tile_side, true, o);
+ w.tensor(TN_IMAGE_NEWLINE, {hp.n_proj});
+ const char * p = "v";
+ for (int b = 0; b < (int) n_blocks; b++) {
+ w.tensor(fmt(TN_MULTI_PROJ_IMG_POS, b), {hp.n_embd, window_side * window_side});
+ w.tensor(fmt(TN_MULTI_PROJ_QUERY, p, b), {hp.n_embd, query_side * query_side});
+ w.tensor(fmt(TN_MULTI_PROJ_LINEAR, p, b, "weight"), {hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_MULTI_PROJ_LINEAR, p, b, "bias"), {hp.n_proj});
+ for (const char * n : {TN_MULTI_PROJ_NORM, TN_MULTI_PROJ_POST_NORM, TN_QF_SELF_ATTN_N, TN_QF_CROSS_ATTN_N, TN_QF_FFN_NORM}) {
+ w.norm (fmt(n, p, b, "weight"), hp.n_embd);
+ w.tensor(fmt(n, p, b, "bias"), {hp.n_embd});
+ }
+ for (const char * n : {TN_QF_SELF_ATTN_Q, TN_QF_SELF_ATTN_K, TN_QF_SELF_ATTN_V, TN_QF_SELF_ATTN_O,
+ TN_QF_CROSS_ATTN_Q, TN_QF_CROSS_ATTN_K, TN_QF_CROSS_ATTN_V, TN_QF_CROSS_ATTN_O}) {
+ w.tensor(fmt(n, p, b, "weight"), {hp.n_embd, hp.n_embd});
+ w.tensor(fmt(n, p, b, "bias"), {hp.n_embd});
+ }
+ w.tensor(fmt(TN_QF_FFN_UP, p, b, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_QF_FFN_UP, p, b, "bias"), {hp.n_ff});
+ w.tensor(fmt(TN_QF_FFN_DOWN, p, b, "weight"), {hp.n_ff, hp.n_embd});
+ w.tensor(fmt(TN_QF_FFN_DOWN, p, b, "bias"), {hp.n_embd});
+ }
+ tm.n_embd_out = n_blocks * hp.n_proj;
+ tm.vision = true;
+ tm.todo = "REALLOC: warmup reserves one 128x128 tile, the anyres image stacks overview + up to 4 grid tiles in one graph (1.88 MiB vs 0.28 MiB on CPU)";
+ } break;
+ default:
+ return false;
+ }
+ return true;
+}
+
+//
+// group g3: vision models with custom encoders, and the legacy omni type
+//
+
+// SAM encoder of deepseek-ocr: 1024 px / 16 = 64x64 patches, window attention, one global layer, neck, 2 stride-2 convs
+// returns the number of output channels
+static int64_t g3_add_sam(mmproj_writer & w, int64_t c_out) {
+ const int64_t n_embd = 32;
+ const int64_t n_head = 2;
+ const int64_t d_head = n_embd / n_head;
+ const int64_t n_ff = 2 * n_embd;
+ const int64_t c_neck = 16;
+ const uint32_t window = 14;
+ // the layer 2 is the first global attention layer
+ const uint32_t n_layer = 3;
+ w.kv(KEY_SAM_N_BLOCK, n_layer);
+ w.kv(KEY_SAM_N_HEAD, uint32_t(n_head));
+ w.kv(KEY_SAM_N_EMBD, uint32_t(n_embd));
+ w.kv(KEY_ATTN_WINDOW_SIZE, window);
+ w.tensor(fmt(TN_SAM_PATCH_EMBD, "weight"), {16, 16, 3, n_embd});
+ w.tensor(fmt(TN_SAM_PATCH_EMBD, "bias"), {n_embd});
+ w.tensor(fmt(TN_SAM_POS_EMBD, "weight"), {n_embd, 64, 64});
+ for (int il = 0; il < (int) n_layer; il++) {
+ const int64_t n_rel = il == 2 ? 2 * 64 - 1 : 2 * window - 1;
+ w.tensor(fmt(TN_SAM_ATTN_QKV, il, "weight"), {n_embd, 3 * n_embd});
+ w.tensor(fmt(TN_SAM_ATTN_QKV, il, "bias"), {3 * n_embd});
+ w.tensor(fmt(TN_SAM_ATTN_OUT, il, "weight"), {n_embd, n_embd});
+ w.tensor(fmt(TN_SAM_ATTN_OUT, il, "bias"), {n_embd});
+ w.norm (fmt(TN_SAM_PRE_NORM, il, "weight"), n_embd);
+ w.tensor(fmt(TN_SAM_PRE_NORM, il, "bias"), {n_embd});
+ w.norm (fmt(TN_SAM_POST_NORM, il, "weight"), n_embd);
+ w.tensor(fmt(TN_SAM_POST_NORM, il, "bias"), {n_embd});
+ w.tensor(fmt(TN_SAM_ATTN_POS_H, il, "weight"), {d_head, n_rel});
+ w.tensor(fmt(TN_SAM_ATTN_POS_W, il, "weight"), {d_head, n_rel});
+ w.tensor(fmt(TN_SAM_FFN_UP, il, "weight"), {n_embd, n_ff});
+ w.tensor(fmt(TN_SAM_FFN_UP, il, "bias"), {n_ff});
+ w.tensor(fmt(TN_SAM_FFN_DOWN, il, "weight"), {n_ff, n_embd});
+ w.tensor(fmt(TN_SAM_FFN_DOWN, il, "bias"), {n_embd});
+ }
+ w.tensor(fmt(TN_SAM_NECK, 0, "weight"), {1, 1, n_embd, c_neck});
+ w.norm (fmt(TN_SAM_NECK, 1, "weight"), c_neck);
+ w.tensor(fmt(TN_SAM_NECK, 1, "bias"), {c_neck});
+ w.tensor(fmt(TN_SAM_NECK, 2, "weight"), {3, 3, c_neck, c_neck});
+ w.norm (fmt(TN_SAM_NECK, 3, "weight"), c_neck);
+ w.tensor(fmt(TN_SAM_NECK, 3, "bias"), {c_neck});
+ w.tensor(fmt(TN_SAM_NET, 2, "weight"), {3, 3, c_neck, 2 * c_neck});
+ w.tensor(fmt(TN_SAM_NET, 3, "weight"), {3, 3, 2 * c_neck, c_out});
+ return c_out;
+}
+
+static bool make_mmproj_g3(projector_type proj, mmproj_writer & w, test_model & tm) {
+ enc_hparams hp;
+ tm.n_embd_out = hp.n_proj;
+ switch (proj) {
+ case PROJECTOR_TYPE_QWEN25O:
+ {
+ // one projector type for both encoders: qwen2.5vl vision + qwen2 audio (whisper, avgpool, fc)
+ const uint32_t patch_size = 14;
+ const uint32_t n_mel = 128;
+ add_vision_kv(w, proj, hp, 560, patch_size);
+ add_audio_kv(w, proj, hp, n_mel);
+ w.kv(KEY_USE_SILU, true);
+ w.kv(KEY_WIN_ATTN_PATTERN, uint32_t(2));
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_EMBD_1, {patch_size, patch_size, 3, hp.n_embd});
+ vit_opts ov;
+ ov.ln_bias = false;
+ ov.ffn_gate = true;
+ add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, ov);
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {4 * hp.n_embd, 4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "bias"), {4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {4 * hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+
+ w.tensor(fmt(TN_CONV1D, 1, "weight"), {3, n_mel, hp.n_embd});
+ w.tensor(fmt(TN_CONV1D, 1, "bias"), {1, hp.n_embd});
+ w.tensor(fmt(TN_CONV1D, 2, "weight"), {3, hp.n_embd, hp.n_embd});
+ w.tensor(fmt(TN_CONV1D, 2, "bias"), {1, hp.n_embd});
+ w.tensor(fmt(TN_POS_EMBD, "a"), {hp.n_embd, 1500});
+ vit_opts oa;
+ oa.k_bias = false;
+ add_vit(w, "a", hp.n_layer, hp.n_embd, hp.n_ff, oa);
+ w.tensor(fmt(TN_MM_AUDIO_FC, "weight"), {hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_FC, "bias"), {hp.n_proj});
+ tm.vision = true;
+ tm.audio = true;
+ tm.text_mrope = true;
+ } break;
+ case PROJECTOR_TYPE_GEMMA4V:
+ {
+ // learned 2D pos tables + 2D rope, rms norms with post norms, 3x3 avg pooling
+ const uint32_t patch_size = 16;
+ const int64_t pos_size = 1024;
+ const int64_t d_head = hp.n_embd / hp.n_head;
+ add_vision_kv(w, proj, hp, 224, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(fmt(TN_POS_EMBD, "v"), {hp.n_embd, pos_size, 2});
+ for (int il = 0; il < (int) hp.n_layer; il++) {
+ for (const char * x : {"q", "k", "v"}) {
+ w.tensor(fmt("v.blk.%d.attn_%s.weight", il, x), {hp.n_embd, hp.n_embd});
+ }
+ w.norm(fmt(TN_ATTN_Q_NORM, "v", il, "weight"), d_head);
+ w.norm(fmt(TN_ATTN_K_NORM, "v", il, "weight"), d_head);
+ w.tensor(fmt(TN_ATTN_OUTPUT, "v", il, "weight"), {hp.n_embd, hp.n_embd});
+ w.norm(fmt(TN_LN_1, "v", il, "weight"), hp.n_embd);
+ w.norm(fmt(TN_LN_2, "v", il, "weight"), hp.n_embd);
+ w.norm(fmt(TN_ATTN_POST_NORM, "v", il, "weight"), hp.n_embd);
+ w.norm(fmt(TN_FFN_POST_NORM, "v", il, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_FFN_UP, "v", il, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_FFN_GATE, "v", il, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_FFN_DOWN, "v", il, "weight"), {hp.n_ff, hp.n_embd});
+ w.tensor(fmt(TN_LS_OUT, "v", il, "weight"), {1}, 1.0f);
+ }
+ // clippable linear: clamp scalars on one layer weight and on the projector
+ for (const std::string & base : {fmt("v.blk.%d.attn_q", 0), std::string("mm.input_projection")}) {
+ w.tensor(base + ".input_min", {1}, -1.0f);
+ w.tensor(base + ".input_max", {1}, 1.0f);
+ w.tensor(base + ".output_min", {1}, -1.0f);
+ w.tensor(base + ".output_max", {1}, 1.0f);
+ }
+ w.tensor(TN_STD_BIAS, {hp.n_embd});
+ w.tensor(TN_STD_SCALE, {hp.n_embd}, 1.0f);
+ w.tensor(TN_MM_INP_PROJ, {hp.n_embd, hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_GEMMA4UV:
+ {
+ // no transformer: im2col + norm + linear on 48x48 patches (16 x pooling 3), pos tables, norm
+ const uint32_t patch_size = 16;
+ const int64_t p = patch_size * 3;
+ const int64_t pos_size = 256;
+ hp.n_head = 0;
+ hp.n_ff = 0;
+ hp.n_layer = 0;
+ add_vision_kv(w, proj, hp, 224, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ w.tensor(TN_PATCH_EMBD, {p * p * 3, hp.n_embd});
+ w.tensor(TN_PATCH_BIAS, {hp.n_embd});
+ w.tensor(fmt(TN_POS_EMBD, "v"), {hp.n_embd, pos_size, 2});
+ for (int i = 1; i <= 3; i++) {
+ const int64_t n = i == 1 ? p * p * 3 : hp.n_embd;
+ w.norm(fmt(TN_PATCH_NORM, i, "weight"), n);
+ w.tensor(fmt(TN_PATCH_NORM, i, "bias"), {n});
+ }
+ w.tensor(TN_MM_INP_PROJ, {hp.n_embd, hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_GEMMA3NV:
+ {
+ // mobilenetv5: stem, 4 stages (edge residual, inverted residual, MQA), multi-scale fusion -> 16x16 tokens
+ // 512 px: stem 256, stages 128/64/32/16, fusion at 32 then avg pool 2 -> 16x16 = image_size / patch_size
+ const uint32_t image_size = 512;
+ const uint32_t patch_size = 2;
+ // n_mmproj_embd() reads ne[0] of the input projection, so it must be square
+ hp.n_proj = hp.n_embd;
+ tm.n_embd_out = hp.n_proj;
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.kv(KEY_IMAGE_MEAN, std::vector<float>{0.0f, 0.0f, 0.0f});
+ w.kv(KEY_IMAGE_STD, std::vector<float>{1.0f, 1.0f, 1.0f});
+
+ auto conv = [&](const std::string & name, int64_t k, int64_t c_in, int64_t c_out) {
+ w.tensor(name, {k, k, c_in, c_out});
+ };
+ auto blk = [&](int s, int b, const char * suffix) {
+ return fmt("v.blk.%d.%d.%s", s, b, suffix);
+ };
+ // edge residual: 3x3 expand conv + 1x1 linear conv
+ auto edge = [&](int s, int b, int64_t c_in, int64_t c_out) {
+ const int64_t c_exp = 2 * c_in;
+ conv(blk(s, b, "conv_exp.weight"), 3, c_in, c_exp);
+ w.norm(blk(s, b, "bn1.weight"), c_exp);
+ conv(blk(s, b, "conv_pwl.weight"), 1, c_exp, c_out);
+ w.norm(blk(s, b, "bn2.weight"), c_out);
+ };
+ // universal inverted residual, the stride of a stage start is on dw_mid
+ auto uir = [&](int s, int b, int64_t c_in, int64_t c_out, bool dw_start, bool dw_mid) {
+ const int64_t c_exp = 2 * c_in;
+ if (dw_start) {
+ conv(blk(s, b, "dw_start.conv.weight"), 3, 1, c_in);
+ w.norm(blk(s, b, "dw_start.bn.weight"), c_in);
+ }
+ conv(blk(s, b, "pw_exp.conv.weight"), 1, c_in, c_exp);
+ w.norm(blk(s, b, "pw_exp.bn.weight"), c_exp);
+ if (dw_mid) {
+ conv(blk(s, b, "dw_mid.conv.weight"), 5, 1, c_exp);
+ w.norm(blk(s, b, "dw_mid.bn.weight"), c_exp);
+ }
+ conv(blk(s, b, "pw_proj.conv.weight"), 1, c_exp, c_out);
+ w.norm(blk(s, b, "pw_proj.bn.weight"), c_out);
+ w.tensor(blk(s, b, "layer_scale.gamma"), {1, 1, c_out}, 1.0f);
+ };
+ // multi-query attention with stride-2 downsampled k/v
+ auto mqa = [&](int s, int b, int64_t c) {
+ const int64_t d = 16;
+ const int64_t n_head = 2;
+ w.norm(blk(s, b, "norm.weight"), c);
+ conv(blk(s, b, "attn.query.proj.weight"), 1, c, d * n_head);
+ conv(blk(s, b, "attn.key.down_conv.weight"), 3, 1, c);
+ w.norm(blk(s, b, "attn.key.norm.weight"), c);
+ conv(blk(s, b, "attn.key.proj.weight"), 1, c, d);
+ conv(blk(s, b, "attn.value.down_conv.weight"), 3, 1, c);
+ w.norm(blk(s, b, "attn.value.norm.weight"), c);
+ conv(blk(s, b, "attn.value.proj.weight"), 1, c, d);
+ conv(blk(s, b, "attn.output.proj.weight"), 1, d * n_head, c);
+ w.tensor(blk(s, b, "layer_scale.gamma"), {1, 1, c}, 1.0f);
+ };
+
+ const int64_t c0 = 8, c1 = 16, c2 = 16, c3 = 32, c4 = 32;
+ conv(TN_MNV5_STEM_CONV, 3, 3, c0);
+ w.tensor(TN_MNV5_STEM_BIAS, {1, 1, c0});
+ w.norm(TN_MNV5_STEM_BN, c0);
+ edge(0, 0, c0, c1);
+ edge(0, 1, c1, c1);
+ uir(1, 0, c1, c2, true, true);
+ uir(1, 1, c2, c2, false, false);
+ uir(2, 0, c2, c3, true, true);
+ mqa(2, 1, c3);
+ uir(3, 0, c3, c4, false, true);
+ mqa(3, 1, c4);
+
+ const int64_t c_msfa = 2 * hp.n_embd;
+ conv(TN_MNV5_MSFA_FFN_EXP_W, 1, c3 + c4, c_msfa);
+ w.norm(TN_MNV5_MSFA_FFN_EXP_BN, c_msfa);
+ conv(TN_MNV5_MSFA_FFN_PROJ_W, 1, c_msfa, hp.n_embd);
+ w.norm(TN_MNV5_MSFA_FFN_PROJ_BN, hp.n_embd);
+ w.norm(TN_MNV5_MSFA_NORM, hp.n_embd);
+
+ w.norm(TN_MM_SOFT_EMB_N, hp.n_embd);
+ w.tensor(TN_MM_INP_PROJ, {hp.n_embd, hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_DEEPSEEKOCR:
+ {
+ // SAM -> CLIP on the 16x16 SAM grid (+ CLS), concat CLIP and SAM features -> fc, newline + view separator
+ // the loader fixes the sizes: 1024 px global view, 640 px tiles fused per row
+ const int64_t c_sam = g3_add_sam(w, hp.n_embd);
+ add_vision_kv(w, proj, hp, 1024, 16);
+ w.tensor(TN_CLASS_EMBD, {hp.n_embd});
+ w.tensor(fmt(TN_POS_EMBD, "v"), {hp.n_embd, 16 * 16 + 1});
+ w.norm(fmt(TN_LN_PRE, "v", "weight"), hp.n_embd);
+ w.tensor(fmt(TN_LN_PRE, "v", "bias"), {hp.n_embd});
+ vit_opts o;
+ o.post_ln = false;
+ add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, o);
+ w.tensor(fmt(TN_MM_PROJECTOR, "weight"), {hp.n_embd + c_sam, hp.n_proj});
+ w.tensor(fmt(TN_MM_PROJECTOR, "bias"), {hp.n_proj});
+ w.tensor(TN_IMAGE_NEWLINE, {hp.n_proj});
+ w.tensor(TN_IMAGE_SEPERATOR, {hp.n_proj});
+ tm.vision = true;
+ tm.todo = "REALLOC: warmup reserves the 1024x1024 global view, a fused row of 9 640px tiles (4000x300 input, 640x5760) grows the SAM graph";
+ } break;
+ case PROJECTOR_TYPE_DEEPSEEKOCR2:
+ {
+ // SAM -> qwen2 encoder (GQA, rope) over SAM tokens + learned queries, causal over the queries -> fc
+ // 1024 px global view (256 queries), 768 px tiles (144 queries)
+ g3_add_sam(w, hp.n_embd);
+ add_vision_kv(w, proj, hp, 1024, 16);
+ w.kv(fmt(KEY_N_HEAD_KV, "vision"), uint32_t(1));
+ const int64_t n_embd_kv = hp.n_embd / hp.n_head;
+ for (int il = 0; il < (int) hp.n_layer; il++) {
+ w.tensor(fmt(TN_ATTN_Q, "v", il, "weight"), {hp.n_embd, hp.n_embd});
+ w.tensor(fmt(TN_ATTN_Q, "v", il, "bias"), {hp.n_embd});
+ w.tensor(fmt(TN_ATTN_K, "v", il, "weight"), {hp.n_embd, n_embd_kv});
+ w.tensor(fmt(TN_ATTN_K, "v", il, "bias"), {n_embd_kv});
+ w.tensor(fmt(TN_ATTN_V, "v", il, "weight"), {hp.n_embd, n_embd_kv});
+ w.tensor(fmt(TN_ATTN_V, "v", il, "bias"), {n_embd_kv});
+ w.tensor(fmt(TN_ATTN_OUTPUT, "v", il, "weight"), {hp.n_embd, hp.n_embd});
+ w.norm(fmt(TN_LN_1, "v", il, "weight"), hp.n_embd);
+ w.norm(fmt(TN_LN_2, "v", il, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_FFN_UP, "v", il, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_FFN_GATE, "v", il, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_FFN_DOWN, "v", il, "weight"), {hp.n_ff, hp.n_embd});
+ }
+ w.norm(fmt(TN_LN_POST, "v", "weight"), hp.n_embd);
+ w.tensor(fmt(TN_RESMPL_QUERY, 1024, "weight"), {hp.n_embd, 256});
+ w.tensor(fmt(TN_RESMPL_QUERY, 768, "weight"), {hp.n_embd, 144});
+ w.tensor(fmt(TN_MM_PROJECTOR, "weight"), {hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_MM_PROJECTOR, "bias"), {hp.n_proj});
+ w.tensor(TN_IMAGE_SEPERATOR, {hp.n_proj});
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_DEEPSEEK4V:
+ case PROJECTOR_TYPE_DEEPSEEK41V:
+ {
+ // native-resolution ViT (fused qkv, 2D rope, swiglu) + 3x3 unfold merge + gelu MLP + learned sentinel rows
+ const uint32_t patch_size = 16;
+ const uint32_t n_merge = 3;
+ const int64_t n_mid = 2 * hp.n_embd;
+ add_vision_kv(w, proj, hp, patch_size * n_merge * 16, patch_size);
+ w.kv(KEY_USE_SILU, true);
+ w.kv(KEY_PROJ_SCALE_FACTOR, n_merge);
+ w.kv(KEY_IMAGE_MIN_PIXELS, uint32_t(16 * patch_size * patch_size * n_merge * n_merge));
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_BIAS, {hp.n_embd});
+ for (int il = 0; il < (int) hp.n_layer; il++) {
+ w.tensor(fmt(TN_ATTN_QKV, "v", il, "weight"), {hp.n_embd, 3 * hp.n_embd});
+ w.tensor(fmt(TN_ATTN_OUTPUT, "v", il, "weight"), {hp.n_embd, hp.n_embd});
+ w.norm(fmt(TN_LN_1, "v", il, "weight"), hp.n_embd);
+ w.norm(fmt(TN_LN_2, "v", il, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_FFN_UP, "v", il, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_FFN_GATE, "v", il, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_FFN_DOWN, "v", il, "weight"), {hp.n_ff, hp.n_embd});
+ }
+ w.norm(fmt(TN_LN_POST, "v", "weight"), hp.n_embd);
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "weight"), {n_merge * n_merge * hp.n_embd, n_mid});
+ w.tensor(fmt(TN_LLAVA_PROJ, 1, "bias"), {n_mid});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {n_mid, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+ w.tensor(TN_IMAGE_NEWLINE, {hp.n_proj});
+ w.tensor(TN_TOK_IMG_START, {hp.n_proj});
+ w.tensor(TN_TOK_IMG_END, {hp.n_proj});
+ if (proj == PROJECTOR_TYPE_DEEPSEEK4V) {
+ w.tensor(TN_TOK_IMG_PAD, {hp.n_proj});
+ }
+ tm.vision = true;
+ } break;
+ default:
+ return false;
+ }
+ return true;
+}
+
+//
+// group g4: audio input encoders, including streaming
+//
+
+// whisper conv stem + transformer, no k bias
+static void g4_add_whisper(mmproj_writer & w, const enc_hparams & hp, uint32_t n_mel, int64_t n_pos = 1500) {
+ w.tensor(fmt(TN_CONV1D, 1, "weight"), {3, n_mel, hp.n_embd});
+ w.tensor(fmt(TN_CONV1D, 1, "bias"), {1, hp.n_embd});
+ w.tensor(fmt(TN_CONV1D, 2, "weight"), {3, hp.n_embd, hp.n_embd});
+ w.tensor(fmt(TN_CONV1D, 2, "bias"), {1, hp.n_embd});
+ w.tensor(fmt(TN_POS_EMBD, "a"), {hp.n_embd, n_pos});
+ vit_opts o;
+ o.k_bias = false;
+ add_vit(w, "a", hp.n_layer, hp.n_embd, hp.n_ff, o);
+}
+
+// tensor with explicit values, for the frontend tensors that need valid values (mel filters, window)
+static void g4_tensor_data(mmproj_writer & w, const std::string & name, const std::vector<float> & data) {
+ ggml_init_params params = {
+ /*.mem_size =*/ ggml_tensor_overhead() + data.size() * sizeof(float),
+ /*.mem_buffer =*/ nullptr,
+ /*.no_alloc =*/ false,
+ };
+ ggml_context * ctx = ggml_init(params);
+ w.ctxs.emplace_back(ctx);
+ ggml_tensor * t = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, (int64_t) data.size());
+ ggml_set_name(t, name.c_str());
+ memcpy(t->data, data.data(), ggml_nbytes(t));
+ gguf_add_tensor(w.gguf.get(), t);
+}
+
+// non-negative mel filterbank [n_mel, n_fft/2 + 1] and hann window
+static void g4_add_mel_frontend(mmproj_writer & w, uint32_t n_mel, int n_fft, int n_window) {
+ std::vector<float> filters((size_t) n_mel * (n_fft / 2 + 1));
+ fill_normal(filters.data(), filters.size(), TN_MEL_FILTERS, 0.0f, 0.01f);
+ for (float & v : filters) {
+ v = fabsf(v);
+ }
+ g4_tensor_data(w, TN_MEL_FILTERS, filters);
+ std::vector<float> window(n_window);
+ for (int i = 0; i < n_window; i++) {
+ window[i] = 0.5f - 0.5f * cosf(2.0f * TEST_PI * i / n_window);
+ }
+ g4_tensor_data(w, TN_WINDOW, window);
+}
+
+// nemo conv subsampling: conv2d s2, dw s2 + pw, dw s2 + pw, then a linear layer
+static void g4_add_pre_encode(mmproj_writer & w, const enc_hparams & hp, uint32_t n_mel, int64_t n_ch) {
+ w.tensor(fmt(TN_CONV1D, 0, "weight"), {3, 3, 1, n_ch});
+ w.tensor(fmt(TN_CONV1D, 0, "bias"), {1, 1, n_ch});
+ for (int i : {2, 5}) {
+ w.tensor(fmt(TN_CONV1D, i, "weight"), {3, 3, 1, n_ch});
+ w.tensor(fmt(TN_CONV1D, i, "bias"), {1, 1, n_ch});
+ w.tensor(fmt(TN_CONV1D, i + 1, "weight"), {1, 1, n_ch, n_ch});
+ w.tensor(fmt(TN_CONV1D, i + 1, "bias"), {1, 1, n_ch});
+ }
+ w.tensor(fmt(TN_PRE_ENCODE_OUT, "weight"), {(n_mel / 8) * n_ch, hp.n_embd});
+ w.tensor(fmt(TN_PRE_ENCODE_OUT, "bias"), {hp.n_embd});
+}
+
+// conformer block: macaron ffn, rel-pos attention, conv module
+static void g4_add_conformer(mmproj_writer & w, const enc_hparams & hp, int64_t n_pos_in, int64_t k_dw, bool lin_bias, bool bn_stats) {
+ const int64_t d_head = hp.n_embd / hp.n_head;
+ for (int il = 0; il < (int) hp.n_layer; il++) {
+ auto lin = [&](const char * tn, int64_t n_in, int64_t n_out, bool bias) {
+ w.tensor(fmt(tn, "a", il, "weight"), {n_in, n_out});
+ if (bias) {
+ w.tensor(fmt(tn, "a", il, "bias"), {n_out});
+ }
+ };
+ auto ln = [&](const char * tn) {
+ w.norm(fmt(tn, "a", il, "weight"), hp.n_embd);
+ w.tensor(fmt(tn, "a", il, "bias"), {hp.n_embd});
+ };
+ for (const char * tn : {TN_FFN_NORM, TN_LN_1, TN_NORM_CONV, TN_FFN_NORM_1, TN_LN_2}) {
+ ln(tn);
+ }
+ lin(TN_FFN_UP, hp.n_embd, hp.n_ff, lin_bias);
+ lin(TN_FFN_DOWN, hp.n_ff, hp.n_embd, lin_bias);
+ lin(TN_FFN_UP_1, hp.n_embd, hp.n_ff, lin_bias);
+ lin(TN_FFN_DOWN_1, hp.n_ff, hp.n_embd, lin_bias);
+ for (const char * tn : {TN_ATTN_Q, TN_ATTN_K, TN_ATTN_V, TN_ATTN_OUTPUT}) {
+ lin(tn, hp.n_embd, hp.n_embd, lin_bias);
+ }
+ lin(TN_LINEAR_POS, n_pos_in, hp.n_embd, false);
+ w.tensor(fmt(TN_POS_BIAS_U, "a", il), {d_head, hp.n_head});
+ w.tensor(fmt(TN_POS_BIAS_V, "a", il), {d_head, hp.n_head});
+ lin(TN_CONV_PW1, hp.n_embd, 2 * hp.n_embd, lin_bias);
+ lin(TN_CONV_PW2, hp.n_embd, hp.n_embd, lin_bias);
+ w.tensor(fmt(TN_CONV_DW, "a", il, "weight"), {k_dw, hp.n_embd});
+ if (lin_bias) {
+ w.tensor(fmt(TN_CONV_DW, "a", il, "bias"), {hp.n_embd});
+ }
+ ln(TN_CONV_NORM);
+ if (bn_stats) {
+ w.tensor(fmt(TN_CONV_NORM_MEAN, "a", il), {hp.n_embd});
+ w.tensor(fmt(TN_CONV_NORM_VAR, "a", il), {hp.n_embd}, 1.0f);
+ }
+ }
+}
+
+static bool make_mmproj_g4(projector_type proj, mmproj_writer & w, test_model & tm) {
+ enc_hparams hp;
+ tm.n_embd_out = hp.n_proj;
+ switch (proj) {
+ case PROJECTOR_TYPE_GEMMA3NA:
+ {
+ tm.audio = true;
+ tm.todo = "not implemented: the converter emits gemma3na for the gemma3n audio tower, but mtmd has no loader or graph for it (load_hparams throws unknown projector type)";
+ } break;
+ case PROJECTOR_TYPE_QWEN2A:
+ {
+ add_audio_kv(w, proj, hp, 128);
+ g4_add_whisper(w, hp, 128);
+ w.tensor(fmt(TN_MM_AUDIO_FC, "weight"), {hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_FC, "bias"), {hp.n_proj});
+ tm.audio = true;
+ } break;
+ case PROJECTOR_TYPE_VOXTRAL:
+ {
+ const uint32_t n_stack = 4;
+ add_audio_kv(w, proj, hp, 128);
+ w.kv(KEY_A_PROJ_STACK_FACTOR, n_stack);
+ g4_add_whisper(w, hp, 128);
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "weight"), {n_stack * hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2, "weight"), {hp.n_proj, hp.n_proj});
+ tm.audio = true;
+ } break;
+ case PROJECTOR_TYPE_MUSIC_FLAMINGO:
+ {
+ add_audio_kv(w, proj, hp, 128);
+ g4_add_whisper(w, hp, 128);
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "weight"), {hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "bias"), {hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2, "weight"), {hp.n_proj, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2, "bias"), {hp.n_proj});
+ tm.audio = true;
+ } break;
+ case PROJECTOR_TYPE_MERALION:
+ {
+ const uint32_t n_stack = 3;
+ const int64_t n_in = n_stack * hp.n_embd;
+ const int64_t n_mid = 2 * hp.n_embd;
+ add_audio_kv(w, proj, hp, 80);
+ w.kv(KEY_A_PROJ_STACK_FACTOR, n_stack);
+ g4_add_whisper(w, hp, 80);
+ w.norm(fmt(TN_MM_NORM_PRE, "weight"), n_in);
+ w.tensor(fmt(TN_MM_NORM_PRE, "bias"), {n_in});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 0, "weight"), {n_in, n_mid});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 0, "bias"), {n_mid});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "weight"), {n_mid, n_mid});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "bias"), {n_mid});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2, "weight"), {n_mid, n_mid});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2, "bias"), {n_mid});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 3, "weight"), {n_mid, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 3, "bias"), {hp.n_proj});
+ tm.audio = true;
+ } break;
+ case PROJECTOR_TYPE_GLMA:
+ {
+ const uint32_t n_stack = 4;
+ add_audio_kv(w, proj, hp, 128);
+ w.kv(KEY_A_PROJ_STACK_FACTOR, n_stack);
+ g4_add_whisper(w, hp, 128);
+ w.norm(fmt(TN_MM_NORM_PRE, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_MM_NORM_PRE, "bias"), {hp.n_embd});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "weight"), {n_stack * hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "bias"), {hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2, "weight"), {hp.n_proj, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2, "bias"), {hp.n_proj});
+ w.tensor(TN_TOK_BOI, {hp.n_proj});
+ w.tensor(TN_TOK_EOI, {hp.n_proj});
+ tm.audio = true;
+ } break;
+ case PROJECTOR_TYPE_HIGGS_AUDIO:
+ {
+ add_audio_kv(w, proj, hp, 128);
+ g4_add_whisper(w, hp, 128);
+ w.tensor(fmt(TN_A_DOWNSAMPLE_CONV, "weight"), {3, 1, hp.n_embd});
+ w.tensor(fmt(TN_A_DOWNSAMPLE_CONV, "bias"), {hp.n_embd});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "weight"), {hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "bias"), {hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2, "weight"), {hp.n_proj, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2, "bias"), {hp.n_proj});
+ tm.audio = true;
+ tm.stream = true;
+ } break;
+ case PROJECTOR_TYPE_QWEN3A:
+ case PROJECTOR_TYPE_DOTS3NOTE_A:
+ {
+ // 3x conv2d stride 2 over (frames, mel): 128 mel -> 16 rows
+ const uint32_t n_mel = 128;
+ const int64_t n_ch = 8;
+ add_audio_kv(w, proj, hp, n_mel);
+ for (int i = 1; i <= 3; i++) {
+ w.tensor(fmt(TN_CONV2D, i, "weight"), {3, 3, i == 1 ? 1 : n_ch, n_ch});
+ w.tensor(fmt(TN_CONV2D, i, "bias"), {n_ch});
+ }
+ w.tensor(fmt(TN_CONV_OUT, "weight"), {(n_mel / 8) * n_ch, hp.n_embd});
+ if (proj == PROJECTOR_TYPE_QWEN3A) {
+ w.tensor(fmt(TN_POS_EMBD, "a"), {hp.n_embd, 64});
+ add_vit(w, "a", hp.n_layer, hp.n_embd, hp.n_ff, {});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "weight"), {hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "bias"), {hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2, "weight"), {hp.n_proj, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2, "bias"), {hp.n_proj});
+ } else {
+ // rms norm, swiglu ffn
+ w.kv(KEY_USE_SILU, true);
+ vit_opts o;
+ o.ln_bias = false;
+ o.k_bias = false;
+ o.ffn_gate = true;
+ add_vit(w, "a", hp.n_layer, hp.n_embd, hp.n_ff, o);
+ w.norm(fmt(TN_MM_NORM_PRE, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_MM_NORM_PRE, "bias"), {hp.n_embd});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "weight"), {hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "bias"), {hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 3, "weight"), {hp.n_proj, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 3, "bias"), {hp.n_proj});
+ }
+ tm.audio = true;
+ } break;
+ case PROJECTOR_TYPE_MIMO_AUDIO:
+ {
+ // the graph takes a skip connection from layer 2, so 3 layers at least
+ const uint32_t n_mel = 128;
+ const uint32_t n_group = 4;
+ const int32_t n_bins = 32;
+ hp.n_layer = 3;
+ add_audio_kv(w, proj, hp, n_mel);
+ w.kv(KEY_A_RVQ_NUM_QUANTIZERS, uint32_t(2));
+ w.kv(KEY_A_RVQ_CODEBOOK_SIZE, std::vector<int32_t>{n_bins, n_bins / 2});
+ w.kv(KEY_A_ATTN_WINDOW_SIZE, uint32_t(16));
+ w.kv(KEY_A_WA_PATTERN_MODE, std::vector<int32_t>{0, -1, 0});
+ w.kv(KEY_A_LOCAL_BLOCK_COUNT, uint32_t(1));
+ w.kv(KEY_A_LOCAL_GROUP_SIZE, n_group);
+ w.tensor(fmt(TN_CONV1D, 1, "weight"), {3, n_mel, hp.n_embd});
+ w.tensor(fmt(TN_CONV1D, 1, "bias"), {1, hp.n_embd});
+ w.tensor(fmt(TN_CONV1D, 2, "weight"), {3, hp.n_embd, hp.n_embd});
+ w.tensor(fmt(TN_CONV1D, 2, "bias"), {1, hp.n_embd});
+ add_vit(w, "a", hp.n_layer, hp.n_embd, hp.n_ff, {});
+ w.tensor(fmt(TN_A_DOWNSAMPLE_CONV, "weight"), {2, hp.n_embd, hp.n_embd});
+ w.norm(fmt(TN_A_DOWNSAMPLE_NORM, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_A_DOWNSAMPLE_NORM, "bias"), {hp.n_embd});
+ w.tensor(fmt(TN_A_RVQ_CODEBOOK, "weight"), {hp.n_embd, n_bins, 2});
+ w.tensor(fmt(TN_MM_A_CODE_EMBD, "weight"), {hp.n_embd, n_bins, 2});
+ for (const char * x : {TN_MM_A_LOCAL_ATTN_Q, TN_MM_A_LOCAL_ATTN_K, TN_MM_A_LOCAL_ATTN_V}) {
+ w.tensor(fmt(x, 0, "weight"), {hp.n_embd, hp.n_embd});
+ w.tensor(fmt(x, 0, "bias"), {hp.n_embd});
+ }
+ w.tensor(fmt(TN_MM_A_LOCAL_ATTN_OUT, 0, "weight"), {hp.n_embd, hp.n_embd});
+ w.tensor(fmt(TN_MM_A_LOCAL_FFN_GATE, 0, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_MM_A_LOCAL_FFN_UP, 0, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_MM_A_LOCAL_FFN_DOWN, 0, "weight"), {hp.n_ff, hp.n_embd});
+ w.norm(fmt(TN_MM_A_LOCAL_LN1, 0, "weight"), hp.n_embd);
+ w.norm(fmt(TN_MM_A_LOCAL_LN2, 0, "weight"), hp.n_embd);
+ w.norm(fmt(TN_MM_A_LOCAL_NORM, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "weight"), {n_group * hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2, "weight"), {hp.n_proj, hp.n_proj});
+ tm.audio = true;
+ tm.todo = "Metal and CUDA vs CPU mismatch: the RVQ argmax flips a few codes of the 30 s and 45 s clips (NMSE ~4.5e-3 on Metal, ~1e-3 on CUDA), the 1 s clip matches";
+ } break;
+ case PROJECTOR_TYPE_LFM2A:
+ case PROJECTOR_TYPE_D1OMNI_A:
+ {
+ const uint32_t n_mel = 128;
+ add_audio_kv(w, proj, hp, n_mel);
+ g4_add_pre_encode(w, hp, n_mel, 8);
+ // the rel-pos input width is fixed to 512 in the graph, conv_dw has 9 taps
+ g4_add_conformer(w, hp, 512, 9, true, false);
+ const int64_t n_mid = 2 * hp.n_proj;
+ w.norm(fmt(TN_MM_AUDIO_MLP, 0, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 0, "bias"), {hp.n_embd});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "weight"), {hp.n_embd, n_mid});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "bias"), {n_mid});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 3, "weight"), {n_mid, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 3, "bias"), {hp.n_proj});
+ if (proj == PROJECTOR_TYPE_LFM2A) {
+ // the audio code embeddings, only used for n_mmproj_embd and a length check
+ w.tensor(fmt(TN_POS_EMBD, "a"), {hp.n_proj, 4096});
+ } else {
+ w.norm(fmt(TN_MM_AUDIO_MLP, 4, "weight"), hp.n_proj);
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 4, "bias"), {hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 5, "weight"), {hp.n_proj, n_mid});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 5, "bias"), {n_mid});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 6, "weight"), {n_mid, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 6, "bias"), {hp.n_proj});
+ }
+ tm.audio = true;
+ } break;
+ case PROJECTOR_TYPE_PARAKEET:
+ {
+ const uint32_t n_mel = 128;
+ const uint32_t k_dw = 9;
+ add_audio_kv(w, proj, hp, n_mel);
+ w.kv(KEY_AUDIO_SUBSMPL_FACTOR, uint32_t(8));
+ w.kv(KEY_A_CONV_KERNEL_SIZE, k_dw);
+ g4_add_mel_frontend(w, n_mel, 512, 400);
+ g4_add_pre_encode(w, hp, n_mel, 8);
+ g4_add_conformer(w, hp, hp.n_embd, k_dw, false, true);
+ w.norm(fmt(TN_MM_NORM_PRE, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "weight"), {hp.n_embd, 2 * hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2, "weight"), {2 * hp.n_proj, hp.n_proj});
+ // loaded but not used by the graph
+ for (int i : {0, 1, 3}) {
+ w.tensor(fmt(TN_MVLM_PROJ_MLP, i, "weight"), {hp.n_embd, hp.n_embd});
+ }
+ tm.audio = true;
+ } break;
+ case PROJECTOR_TYPE_NEMOTRON_TRANSCRIBE:
+ {
+ // ASR expert (fused qkv, per-head qk norm, partial rope) + speaker expert + Sortformer head
+ const uint32_t n_mel = 128;
+ const uint32_t sub = 8;
+ const int64_t d_head = hp.n_embd / hp.n_head;
+ const int64_t n_spk_e = 64;
+ const int64_t d_tf = 32;
+ const int64_t n_spk = 4;
+ add_audio_kv(w, proj, hp, n_mel);
+ w.kv(KEY_AUDIO_SUBSMPL_FACTOR, sub);
+ w.kv(KEY_A_ROPE_DIMS, uint32_t(d_head / 2));
+ w.kv(KEY_A_SPK_N_BLOCK, uint32_t(1));
+ w.kv(KEY_A_SPK_N_HEAD, uint32_t(2));
+ g4_add_mel_frontend(w, n_mel, 512, 400);
+ w.tensor(fmt(TN_INP_PROJ, "weight"), {sub * n_mel, hp.n_embd});
+ w.norm(fmt(TN_LN_PRE, "a", "weight"), hp.n_embd);
+ w.tensor(fmt(TN_LN_PRE, "a", "bias"), {hp.n_embd});
+ for (int il = 0; il < (int) hp.n_layer; il++) {
+ w.tensor(fmt(TN_ATTN_QKV, "a", il, "weight"), {hp.n_embd, 3 * hp.n_embd});
+ w.tensor(fmt(TN_ATTN_OUTPUT, "a", il, "weight"), {hp.n_embd, hp.n_embd});
+ w.tensor(fmt(TN_ATTN_OUTPUT, "a", il, "bias"), {hp.n_embd});
+ for (const char * tn : {TN_ATTN_Q_NORM, TN_ATTN_K_NORM}) {
+ w.norm(fmt(tn, "a", il, "weight"), d_head);
+ w.tensor(fmt(tn, "a", il, "bias"), {d_head});
+ }
+ for (const char * tn : {TN_LN_1, TN_LN_2}) {
+ w.norm(fmt(tn, "a", il, "weight"), hp.n_embd);
+ w.tensor(fmt(tn, "a", il, "bias"), {hp.n_embd});
+ }
+ w.tensor(fmt(TN_FFN_UP, "a", il, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_FFN_UP, "a", il, "bias"), {hp.n_ff});
+ w.tensor(fmt(TN_FFN_DOWN, "a", il, "weight"), {hp.n_ff, hp.n_embd});
+ w.tensor(fmt(TN_FFN_DOWN, "a", il, "bias"), {hp.n_embd});
+ }
+ w.norm(fmt(TN_LN_POST, "a", "weight"), hp.n_embd);
+ w.tensor(fmt(TN_LN_POST, "a", "bias"), {hp.n_embd});
+
+ const char * sp = "a.spk";
+ w.tensor(fmt(TN_A_SPK_INP_PROJ, "weight"), {sub * n_mel, n_spk_e});
+ for (const char * tn : {TN_LN_PRE, TN_LN_POST}) {
+ w.norm(fmt(tn, sp, "weight"), n_spk_e);
+ w.tensor(fmt(tn, sp, "bias"), {n_spk_e});
+ }
+ for (const char * tn : {TN_LN_1, TN_LN_2}) {
+ w.norm(fmt(tn, sp, 0, "weight"), n_spk_e);
+ w.tensor(fmt(tn, sp, 0, "bias"), {n_spk_e});
+ }
+ w.tensor(fmt(TN_ATTN_QKV, sp, 0, "weight"), {n_spk_e, 3 * n_spk_e});
+ w.tensor(fmt(TN_ATTN_OUTPUT, sp, 0, "weight"), {n_spk_e, n_spk_e});
+ w.tensor(fmt(TN_ATTN_OUTPUT, sp, 0, "bias"), {n_spk_e});
+ w.tensor(fmt(TN_FFN_UP, sp, 0, "weight"), {n_spk_e, 2 * n_spk_e});
+ w.tensor(fmt(TN_FFN_UP, sp, 0, "bias"), {2 * n_spk_e});
+ w.tensor(fmt(TN_FFN_DOWN, sp, 0, "weight"), {2 * n_spk_e, n_spk_e});
+ w.tensor(fmt(TN_FFN_DOWN, sp, 0, "bias"), {n_spk_e});
+
+ w.tensor(fmt(TN_A_SPK_HEAD, "proj", "weight"), {n_spk_e, d_tf});
+ w.tensor(fmt(TN_A_SPK_HEAD, "proj", "bias"), {d_tf});
+ // conv1d k=3 p=1 to sub*d_tf channels, then unfolded to sub frames
+ w.tensor(fmt(TN_A_SPK_HEAD, "upsample", "weight"), {3, d_tf, sub * d_tf});
+ w.tensor(fmt(TN_A_SPK_HEAD, "upsample", "bias"), {sub * d_tf});
+ w.tensor(fmt(TN_A_SPK_HEAD, "fc1", "weight"), {d_tf, d_tf});
+ w.tensor(fmt(TN_A_SPK_HEAD, "fc1", "bias"), {d_tf});
+ w.tensor(fmt(TN_A_SPK_HEAD, "fc2", "weight"), {d_tf, n_spk});
+ w.tensor(fmt(TN_A_SPK_HEAD, "fc2", "bias"), {n_spk});
+ w.tensor(TN_A_SPK_SIL_EMB, {n_spk_e});
+ w.norm(fmt(TN_A_FUSION_NORM, "asr_norm", "weight"), hp.n_embd);
+ w.tensor(fmt(TN_A_FUSION_NORM, "asr_norm", "bias"), {hp.n_embd});
+ w.norm(fmt(TN_A_FUSION_NORM, "spk_norm", "weight"), n_spk);
+ w.tensor(fmt(TN_A_FUSION_NORM, "spk_norm", "bias"), {n_spk});
+ w.tensor(TN_A_FUSION_KERNEL, {n_spk, hp.n_embd});
+ w.tensor(fmt(TN_MM_AUDIO_FC, "weight"), {hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_FC, "bias"), {hp.n_proj});
+ tm.audio = true;
+ } break;
+ case PROJECTOR_TYPE_GRANITE_SPEECH:
+ {
+ // conformer with block-local Shaw rel-pos attention, CTC branch, windowed QFormer projector
+ const uint32_t n_mel = 160; // 80 mel bins, 2 frames stacked
+ const uint32_t ctx_size = 20;
+ const uint32_t max_pos = 32;
+ const uint32_t k_dw = 5;
+ const uint32_t win = 15;
+ const uint32_t n_query = win / 5;
+ const int64_t d_head = hp.n_embd / hp.n_head;
+ const int64_t n_vocab = 32;
+ const int64_t n_enc_out = 2 * hp.n_embd; // output of layer 1, concat with the last layer
+ add_audio_kv(w, proj, hp, n_mel);
+ w.kv(KEY_A_CHUNK_SIZE, ctx_size);
+ w.kv(KEY_A_CONV_KERNEL_SIZE, k_dw);
+ w.kv(KEY_A_MAX_POS_EMB, max_pos);
+ w.kv(KEY_A_PROJ_WINDOW_SIZE, win);
+ w.kv(KEY_A_PROJ_DOWNSAMPLE_RATE, uint32_t(5));
+ w.kv(KEY_A_PROJ_HEAD_COUNT, uint32_t(2));
+ w.kv(fmt(KEY_FEATURE_LAYERS, "audio"), std::vector<int32_t>{1});
+ w.tensor(fmt(TN_INP_PROJ, "weight"), {n_mel, hp.n_embd});
+ w.tensor(fmt(TN_INP_PROJ, "bias"), {hp.n_embd});
+ for (int il = 0; il < (int) hp.n_layer; il++) {
+ auto lin = [&](const char * tn, int64_t n_in, int64_t n_out, bool bias) {
+ w.tensor(fmt(tn, "a", il, "weight"), {n_in, n_out});
+ if (bias) {
+ w.tensor(fmt(tn, "a", il, "bias"), {n_out});
+ }
+ };
+ for (const char * tn : {TN_FFN_NORM, TN_LN_1, TN_NORM_CONV, TN_CONV_NORM, TN_FFN_NORM_1, TN_LN_2}) {
+ w.norm(fmt(tn, "a", il, "weight"), hp.n_embd);
+ w.tensor(fmt(tn, "a", il, "bias"), {hp.n_embd});
+ }
+ lin(TN_FFN_UP, hp.n_embd, hp.n_ff, true);
+ lin(TN_FFN_DOWN, hp.n_ff, hp.n_embd, true);
+ lin(TN_FFN_UP_1, hp.n_embd, hp.n_ff, true);
+ lin(TN_FFN_DOWN_1, hp.n_ff, hp.n_embd, true);
+ lin(TN_ATTN_Q, hp.n_embd, hp.n_embd, false);
+ lin(TN_ATTN_K, hp.n_embd, hp.n_embd, false);
+ lin(TN_ATTN_V, hp.n_embd, hp.n_embd, false);
+ lin(TN_ATTN_OUTPUT, hp.n_embd, hp.n_embd, true);
+ lin(TN_CONV_PW1, hp.n_embd, 2 * hp.n_embd, true);
+ lin(TN_CONV_PW2, hp.n_embd, hp.n_embd, true);
+ w.tensor(fmt(TN_CONV_DW, "a", il, "weight"), {k_dw, hp.n_embd});
+ w.tensor(fmt(TN_ATTN_REL_POS_EMB, "a", il), {d_head, 2 * max_pos + 1});
+ }
+ w.tensor(fmt(TN_CTC_OUT, "weight"), {hp.n_embd, n_vocab});
+ w.tensor(fmt(TN_CTC_OUT, "bias"), {n_vocab});
+ w.tensor(fmt(TN_CTC_OUT_MID, "weight"), {n_vocab, hp.n_embd});
+ w.tensor(fmt(TN_CTC_OUT_MID, "bias"), {hp.n_embd});
+
+ w.tensor(fmt(TN_QF_PROJ_QUERY, "a"), {hp.n_embd, n_query});
+ w.norm(fmt(TN_QF_PROJ_NORM, "a", "weight"), hp.n_embd);
+ w.tensor(fmt(TN_QF_PROJ_NORM, "a", "bias"), {hp.n_embd});
+ w.tensor(fmt(TN_QF_PROJ_LINEAR, "a", "weight"), {hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_QF_PROJ_LINEAR, "a", "bias"), {hp.n_proj});
+ for (int il = 0; il < 2; il++) {
+ auto lin = [&](const char * tn, int64_t n_in, int64_t n_out) {
+ w.tensor(fmt(tn, "a", il, "weight"), {n_in, n_out});
+ w.tensor(fmt(tn, "a", il, "bias"), {n_out});
+ };
+ for (const char * tn : {TN_QF_SELF_ATTN_Q, TN_QF_SELF_ATTN_K, TN_QF_SELF_ATTN_V, TN_QF_SELF_ATTN_O, TN_QF_CROSS_ATTN_Q, TN_QF_CROSS_ATTN_O}) {
+ lin(tn, hp.n_embd, hp.n_embd);
+ }
+ lin(TN_QF_CROSS_ATTN_K, n_enc_out, hp.n_embd);
+ lin(TN_QF_CROSS_ATTN_V, n_enc_out, hp.n_embd);
+ lin(TN_QF_FFN_UP, hp.n_embd, hp.n_ff);
+ lin(TN_QF_FFN_DOWN, hp.n_ff, hp.n_embd);
+ for (const char * tn : {TN_QF_SELF_ATTN_N, TN_QF_CROSS_ATTN_N, TN_QF_FFN_NORM}) {
+ w.norm(fmt(tn, "a", il, "weight"), hp.n_embd);
+ w.tensor(fmt(tn, "a", il, "bias"), {hp.n_embd});
+ }
+ }
+ tm.audio = true;
+ } break;
+ case PROJECTOR_TYPE_GEMMA4A:
+ {
+ // conformer with chunked local attention, causal conv, rms norms everywhere
+ const uint32_t n_mel = 128;
+ const int64_t n_ch = 8;
+ const int64_t d_head = hp.n_embd / hp.n_head;
+ const int64_t k_dw = 5;
+ add_audio_kv(w, proj, hp, n_mel);
+ for (int i = 0; i < 2; i++) {
+ w.tensor(fmt(TN_A_CONV1D, i, "weight"), {3, 3, i == 0 ? 1 : n_ch, n_ch});
+ w.norm(fmt(TN_A_CONV1D_NORM, i, "weight"), n_ch);
+ }
+ w.tensor(fmt(TN_A_INP_PROJ, "weight"), {n_ch * (n_mel / 4), hp.n_embd});
+ for (int il = 0; il < (int) hp.n_layer; il++) {
+ auto lin = [&](const char * tn, int64_t n_in, int64_t n_out) {
+ w.tensor(fmt(tn, "a", il, "weight"), {n_in, n_out});
+ };
+ for (const char * tn : {TN_FFN_NORM, TN_FFN_POST_NORM, TN_A_ATTN_PRE_NORM, TN_ATTN_POST_NORM,
+ TN_CONV_NORM, TN_NORM_CONV, TN_FFN_NORM_1, TN_A_FFN_POST_NORM_1, TN_LN_2}) {
+ w.norm(fmt(tn, "a", il, "weight"), hp.n_embd);
+ }
+ lin(TN_FFN_UP, hp.n_embd, hp.n_ff);
+ lin(TN_FFN_DOWN, hp.n_ff, hp.n_embd);
+ lin(TN_FFN_UP_1, hp.n_embd, hp.n_ff);
+ lin(TN_FFN_DOWN_1, hp.n_ff, hp.n_embd);
+ lin(TN_ATTN_Q, hp.n_embd, hp.n_embd);
+ lin(TN_ATTN_K, hp.n_embd, hp.n_embd);
+ lin(TN_ATTN_V, hp.n_embd, hp.n_embd);
+ lin(TN_ATTN_OUTPUT, hp.n_embd, hp.n_embd);
+ lin(TN_A_ATTN_K_REL, hp.n_embd, hp.n_embd);
+ lin(TN_CONV_PW1, hp.n_embd, 2 * hp.n_embd);
+ lin(TN_CONV_PW2, hp.n_embd, hp.n_embd);
+ w.norm(fmt(TN_A_PER_DIM_SCALE, "a", il, "weight"), d_head);
+ w.norm(fmt(TN_A_PER_DIM_K_SCALE, "a", il, "weight"), d_head);
+ w.tensor(fmt(TN_CONV_DW, "a", il, "weight"), {k_dw, hp.n_embd});
+ }
+ // clippable linear on one weight
+ const std::string q0 = fmt(TN_ATTN_Q, "a", 0, "");
+ g4_tensor_data(w, q0 + "input_min", {-4.0f});
+ g4_tensor_data(w, q0 + "input_max", { 4.0f});
+ g4_tensor_data(w, q0 + "output_min", {-4.0f});
+ g4_tensor_data(w, q0 + "output_max", { 4.0f});
+ w.tensor(fmt(TN_A_OUT_PROJ, "weight"), {hp.n_embd, hp.n_embd});
+ w.tensor(fmt(TN_A_OUT_PROJ, "bias"), {hp.n_embd});
+ w.norm(fmt(TN_A_MM_SOFT_EMB_N, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_A_MM_INP_PROJ, "weight"), {hp.n_embd, hp.n_proj});
+ tm.audio = true;
+ tm.stream = true;
+ } break;
+ case PROJECTOR_TYPE_GEMMA4UA:
+ {
+ // encoder-free: rms norm + projection of raw 640-sample frames
+ hp.n_layer = 0;
+ add_audio_kv(w, proj, hp, 640);
+ w.tensor(fmt(TN_A_MM_INP_PROJ, "weight"), {640, hp.n_proj});
+ tm.audio = true;
+ } break;
+ case PROJECTOR_TYPE_LFM3A:
+ {
+ // causal conv downsampler, then a short-conv layer and a sliding-window attention layer
+ const uint32_t n_mel = 128;
+ const int64_t n_ch = 8;
+ const int64_t d_head = hp.n_embd / hp.n_head;
+ add_audio_kv(w, proj, hp, n_mel);
+ w.kv(KEY_A_ATTN_WINDOW_SIZE, uint32_t(16));
+ g4_add_pre_encode(w, hp, n_mel, n_ch);
+ for (int il = 0; il < (int) hp.n_layer; il++) {
+ auto lin = [&](const char * tn, int64_t n_in, int64_t n_out) {
+ w.tensor(fmt(tn, "a", il, "weight"), {n_in, n_out});
+ };
+ w.norm(fmt(TN_LN_1, "a", il, "weight"), hp.n_embd);
+ w.norm(fmt(TN_LN_2, "a", il, "weight"), hp.n_embd);
+ if (il == 0) {
+ lin(TN_CONV_PW1, hp.n_embd, 3 * hp.n_embd);
+ lin(TN_CONV_PW2, hp.n_embd, hp.n_embd);
+ w.tensor(fmt(TN_CONV_DW, "a", il, "weight"), {3, hp.n_embd});
+ } else {
+ for (const char * tn : {TN_ATTN_Q, TN_ATTN_K, TN_ATTN_V, TN_ATTN_OUTPUT}) {
+ lin(tn, hp.n_embd, hp.n_embd);
+ }
+ w.norm(fmt(TN_ATTN_Q_NORM, "a", il, "weight"), d_head);
+ w.norm(fmt(TN_ATTN_K_NORM, "a", il, "weight"), d_head);
+ }
+ lin(TN_FFN_GATE, hp.n_embd, hp.n_ff);
+ lin(TN_FFN_UP, hp.n_embd, hp.n_ff);
+ lin(TN_FFN_DOWN, hp.n_ff, hp.n_embd);
+ }
+ w.norm(fmt(TN_LN_POST, "a", "weight"), hp.n_embd);
+ const int64_t n_mid = 2 * hp.n_proj;
+ w.norm(fmt(TN_MM_AUDIO_MLP, 0, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 0, "bias"), {hp.n_embd});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "weight"), {hp.n_embd, n_mid});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "bias"), {n_mid});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 3, "weight"), {n_mid, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 3, "bias"), {hp.n_proj});
+ tm.audio = true;
+ tm.stream = true;
+ } break;
+ case PROJECTOR_TYPE_VOXTRAL_RT:
+ {
+ // causal whisper-like encoder with a sliding-window kv ring, only usable as a stream
+ const uint32_t n_mel = 128;
+ const uint32_t n_stack = 4;
+ add_audio_kv(w, proj, hp, n_mel);
+ w.kv(KEY_A_PROJ_STACK_FACTOR, n_stack);
+ w.kv(KEY_A_ATTN_WINDOW_SIZE, uint32_t(32));
+ w.tensor(fmt(TN_CONV1D, 1, "weight"), {3, n_mel, hp.n_embd});
+ w.tensor(fmt(TN_CONV1D, 1, "bias"), {1, hp.n_embd});
+ w.tensor(fmt(TN_CONV1D, 2, "weight"), {3, hp.n_embd, hp.n_embd});
+ w.tensor(fmt(TN_CONV1D, 2, "bias"), {1, hp.n_embd});
+ vit_opts o;
+ o.ln_bias = false;
+ o.k_bias = false;
+ o.ffn_gate = true;
+ o.ffn_bias = false;
+ add_vit(w, "a", hp.n_layer, hp.n_embd, hp.n_ff, o);
+ for (int il = 0; il < (int) hp.n_layer; il++) {
+ w.tensor(fmt(TN_FFN_DOWN, "a", il, "bias"), {hp.n_embd});
+ }
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "weight"), {n_stack * hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2, "weight"), {hp.n_proj, hp.n_proj});
+ tm.stream = true;
+ } break;
+ case PROJECTOR_TYPE_VIBEVOICE_ASR:
+ {
+ // two causal ConvNeXt pyramids over the raw waveform (acoustic, semantic), 3200 samples per token
+ const int32_t k_conv = 7;
+ const std::vector<int32_t> patches = {4, 8, 10, 10};
+ const std::vector<int32_t> depths = {1, 0, 0, 1};
+ const std::vector<int64_t> n_ch = {16, 16, 32, 32};
+ const int64_t n_lat[] = {16, 24};
+ hp.n_layer = 2;
+ add_audio_kv(w, proj, hp, 1);
+ w.kv(KEY_A_CONV_KERNEL_SIZE, uint32_t(k_conv));
+ w.kv(KEY_A_PATCH_SIZES, patches);
+ w.kv(KEY_A_DEPTHS, depths);
+ for (int e = 0; e < 2; e++) {
+ int bid = 0;
+ for (size_t i = 0; i < patches.size(); i++) {
+ const int64_t k = i == 0 ? k_conv : 2 * patches[i];
+ const int64_t n_in = i == 0 ? 1 : n_ch[i - 1];
+ w.tensor(fmt(TN_A_CNX_CONV, e, (int) i, "weight"), {k, n_in, n_ch[i]});
+ w.tensor(fmt(TN_A_CNX_CONV, e, (int) i, "bias"), {n_ch[i]});
+ for (int d = 0; d < depths[i]; d++, bid++) {
+ const int64_t c = n_ch[i];
+ w.norm(fmt(TN_A_CNX_NORM, e, bid, "weight"), c);
+ w.tensor(fmt(TN_A_CNX_DW, e, bid, "weight"), {k_conv, c});
+ w.tensor(fmt(TN_A_CNX_DW, e, bid, "bias"), {c});
+ w.tensor(fmt(TN_A_CNX_LS1, e, bid, "weight"), {c});
+ w.norm(fmt(TN_A_CNX_FFN_NORM, e, bid, "weight"), c);
+ w.tensor(fmt(TN_A_CNX_FFN_UP, e, bid, "weight"), {c, 4 * c});
+ w.tensor(fmt(TN_A_CNX_FFN_UP, e, bid, "bias"), {4 * c});
+ w.tensor(fmt(TN_A_CNX_FFN_DOWN, e, bid, "weight"), {4 * c, c});
+ w.tensor(fmt(TN_A_CNX_FFN_DOWN, e, bid, "bias"), {c});
+ w.tensor(fmt(TN_A_CNX_LS2, e, bid, "weight"), {c});
+ }
+ }
+ w.tensor(fmt(TN_A_CNX_CONV, e, (int) patches.size(), "weight"), {k_conv, n_ch.back(), n_lat[e]});
+ w.tensor(fmt(TN_A_CNX_CONV, e, (int) patches.size(), "bias"), {n_lat[e]});
+ // acoustic connector: mlp 0 -> norm -> mlp 1, semantic connector: mlp 2 -> norm -> mlp 3
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2 * e, "weight"), {n_lat[e], hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2 * e, "bias"), {hp.n_proj});
+ w.norm(fmt(TN_MM_AUDIO_MLP_NORM, 2 * e, "weight"), hp.n_proj);
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2 * e + 1, "weight"), {hp.n_proj, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2 * e + 1, "bias"), {hp.n_proj});
+ }
+ tm.audio = true;
+ tm.stream = true;
+ // the first stage has one row per 4 samples, Vulkan rms_norm dispatches one workgroup per row (max 65535 on some GPUs)
+ tm.audio_seconds = {1.0f, 10.0f};
+ } break;
+ case PROJECTOR_TYPE_MUSE_SPARK_AUDIO:
+ {
+ // conv pyramid over the raw waveform, each stage folds `patch` samples into the channels
+ const std::vector<int32_t> patches = {8, 20, 20};
+ const std::vector<int32_t> hidden = {16, 32, 64};
+ const std::vector<int32_t> depths = {1, 0, 1};
+ const uint32_t k_conv = 5;
+ hp.n_layer = 2;
+ add_audio_kv(w, proj, hp, 1);
+ w.kv(KEY_A_CONV_KERNEL_SIZE, k_conv);
+ w.kv(KEY_A_HIDDEN_SIZES, hidden);
+ w.kv(KEY_A_PATCH_SIZES, patches);
+ w.kv(KEY_A_DEPTHS, depths);
+ int bid = 0;
+ for (size_t i = 0; i < patches.size(); i++) {
+ const int64_t n_in = (i == 0 ? 1 : hidden[i - 1]) * (int64_t) patches[i];
+ const int64_t c = hidden[i];
+ w.tensor(fmt(TN_A_PATCH, (int) i, "weight"), {n_in, c});
+ w.tensor(fmt(TN_A_PATCH, (int) i, "bias"), {c});
+ w.norm(fmt(TN_A_PATCH_NORM, (int) i, "weight"), c);
+ for (int d = 0; d < depths[i]; d++, bid++) {
+ w.tensor(fmt(TN_CONV1D, bid, "weight"), {k_conv, 1, c});
+ w.tensor(fmt(TN_CONV1D, bid, "bias"), {c});
+ w.norm(fmt(TN_A_CONV1D_NORM, bid, "weight"), c);
+ w.tensor(fmt(TN_FFN_UP, "a", bid, "weight"), {c, 4 * c});
+ w.tensor(fmt(TN_FFN_UP, "a", bid, "bias"), {4 * c});
+ w.tensor(fmt(TN_FFN_DOWN, "a", bid, "weight"), {4 * c, c});
+ w.tensor(fmt(TN_FFN_DOWN, "a", bid, "bias"), {c});
+ }
+ }
+ w.norm(fmt(TN_LN_PRE, "a", "weight"), hidden.back());
+ w.tensor(fmt(TN_MM_AUDIO_FC, "weight"), {hidden.back(), hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_FC, "bias"), {hp.n_proj});
+ w.norm(fmt(TN_LN_POST, "a", "weight"), hp.n_proj);
+ tm.audio = true;
+ } break;
+ case PROJECTOR_TYPE_MOSHI:
+ {
+ // streaming mimi encoder (seanet ratios 4,5,6,8 then 2x downsample), split RVQ, backbone code embeddings
+ const int ratios[] = {4, 5, 6, 8};
+ const int64_t n_bins = 32;
+ const int64_t d_cb = 16;
+ const int64_t n_q = 4;
+ int64_t n_ch = 4;
+ add_audio_kv(w, proj, hp, 1);
+ w.tensor(fmt(TN_A_SEANET_CONV_IN, "weight"), {7, 1, n_ch});
+ w.tensor(fmt(TN_A_SEANET_CONV_IN, "bias"), {n_ch});
+ for (int i = 0; i < 4; i++) {
+ w.tensor(fmt(TN_A_SEANET_RES_CONV1, i, "weight"), {3, n_ch, n_ch / 2});
+ w.tensor(fmt(TN_A_SEANET_RES_CONV1, i, "bias"), {n_ch / 2});
+ w.tensor(fmt(TN_A_SEANET_RES_CONV2, i, "weight"), {1, n_ch / 2, n_ch});
+ w.tensor(fmt(TN_A_SEANET_RES_CONV2, i, "bias"), {n_ch});
+ w.tensor(fmt(TN_A_SEANET_SCALE_CONV, i, "weight"), {2 * ratios[i], n_ch, 2 * n_ch});
+ w.tensor(fmt(TN_A_SEANET_SCALE_CONV, i, "bias"), {2 * n_ch});
+ n_ch *= 2;
+ }
+ w.tensor(fmt(TN_A_SEANET_CONV_OUT, "weight"), {3, n_ch, hp.n_embd});
+ w.tensor(fmt(TN_A_SEANET_CONV_OUT, "bias"), {hp.n_embd});
+ for (int il = 0; il < (int) hp.n_layer; il++) {
+ for (const char * tn : {TN_ATTN_Q, TN_ATTN_K, TN_ATTN_V, TN_ATTN_OUTPUT}) {
+ w.tensor(fmt(tn, "a", il, "weight"), {hp.n_embd, hp.n_embd});
+ }
+ for (const char * tn : {TN_LN_1, TN_LN_2}) {
+ w.norm(fmt(tn, "a", il, "weight"), hp.n_embd);
+ w.tensor(fmt(tn, "a", il, "bias"), {hp.n_embd});
+ }
+ w.tensor(fmt(TN_LS_1, "a", il, "weight"), {hp.n_embd});
+ w.tensor(fmt(TN_LS_2, "a", il, "weight"), {hp.n_embd});
+ w.tensor(fmt(TN_FFN_UP, "a", il, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_FFN_DOWN, "a", il, "weight"), {hp.n_ff, hp.n_embd});
+ }
+ w.tensor(fmt(TN_A_DOWNSAMPLE_CONV, "weight"), {4, hp.n_embd, hp.n_embd});
+ w.tensor(fmt(TN_A_CODEC_VQ_FIRST_IN, "weight"), {hp.n_embd, d_cb});
+ w.tensor(fmt(TN_A_CODEC_VQ_FIRST_CB, "weight"), {d_cb, n_bins});
+ w.tensor(fmt(TN_A_CODEC_VQ_REST_IN, "weight"), {hp.n_embd, d_cb});
+ w.tensor(fmt(TN_A_CODEC_VQ_REST_CB, "weight"), {d_cb, n_bins, n_q - 1});
+ // one extra row per table for the initial code
+ w.tensor(fmt(TN_MM_A_CODE_EMBD, "weight"), {hp.n_proj, n_bins + 1, n_q});
+ tm.stream = true;
+ } break;
+ default:
+ return false;
+ }
+ return true;
+}
+
+//
+// group g5: audio generation / TTS, part 1
+//
+
+// ECAPA-TDNN speaker encoder, mixed = true when it is the audio part of a gen mmproj
+static void g5_add_qwen3tts_spkenc(mmproj_writer & w, const enc_hparams & hp, bool mixed) {
+ const uint32_t n_mel = 128;
+ const int64_t C = hp.n_embd;
+ const int64_t Cs = C / 8; // res2net scale 8
+ const int64_t n_se = 32;
+ const int64_t n_attn = 32;
+ enc_hparams ha = hp;
+ ha.n_layer = 3; // 3 SE-Res2Net blocks
+ add_audio_kv(w, PROJECTOR_TYPE_QWEN3TTS_SPKENC, ha, n_mel, mixed);
+ w.tensor(fmt(TN_CONV1D, 0, "weight"), {5, n_mel, C});
+ w.tensor(fmt(TN_CONV1D, 0, "bias"), {C});
+ for (int bid = 1; bid <= 3; bid++) {
+ w.tensor(fmt(TN_CONV_PW1, "a", bid, "weight"), {1, C, C});
+ w.tensor(fmt(TN_CONV_PW1, "a", bid, "bias"), {C});
+ w.tensor(fmt(TN_CONV_PW2, "a", bid, "weight"), {1, C, C});
+ w.tensor(fmt(TN_CONV_PW2, "a", bid, "bias"), {C});
+ w.tensor(fmt(TN_A_SE_CONV1, bid, "weight"), {1, C, n_se});
+ w.tensor(fmt(TN_A_SE_CONV1, bid, "bias"), {n_se});
+ w.tensor(fmt(TN_A_SE_CONV2, bid, "weight"), {1, n_se, C});
+ w.tensor(fmt(TN_A_SE_CONV2, bid, "bias"), {C});
+ for (int xid = 0; xid < 7; xid++) {
+ w.tensor(fmt(TN_A_CONV_RES2, bid, xid, "weight"), {3, Cs, Cs});
+ w.tensor(fmt(TN_A_CONV_RES2, bid, xid, "bias"), {Cs});
+ }
+ }
+ w.tensor(fmt(TN_CONV_OUT, "weight"), {1, 3 * C, 3 * C});
+ w.tensor(fmt(TN_CONV_OUT, "bias"), {3 * C});
+ w.tensor(fmt(TN_A_ASP_TDNN, "weight"), {1, 9 * C, n_attn});
+ w.tensor(fmt(TN_A_ASP_TDNN, "bias"), {n_attn});
+ w.tensor(fmt(TN_A_ASP_ATTN, "weight"), {1, n_attn, 3 * C});
+ w.tensor(fmt(TN_A_ASP_ATTN, "bias"), {3 * C});
+ w.tensor(fmt(TN_MM_AUDIO_FC, "weight"), {1, 6 * C, hp.n_proj});
+ w.tensor(fmt(TN_MM_AUDIO_FC, "bias"), {hp.n_proj});
+}
+
+// SEANet stack of mimi, channels C0 -> C0 << n_stage -> dim (encoder), mirrored for the decoder
+// ratios only set the kernel sizes of the resampling convs (2 * stride)
+static void g5_add_seanet(mmproj_writer & w, bool decoder, const std::vector<int> & ratios, int64_t C0, int64_t dim) {
+ const int n_stage = (int) ratios.size();
+ const int64_t C_top = C0 << n_stage;
+ if (!decoder) {
+ w.tensor(fmt(TN_A_SEANET_CONV_IN, "weight"), {7, 1, C0});
+ w.tensor(fmt(TN_A_SEANET_CONV_IN, "bias"), {C0});
+ for (int i = 0; i < n_stage; i++) {
+ const int64_t C = C0 << i;
+ w.tensor(fmt(TN_A_SEANET_RES_CONV1, i, "weight"), {3, C, C / 2});
+ w.tensor(fmt(TN_A_SEANET_RES_CONV1, i, "bias"), {C / 2});
+ w.tensor(fmt(TN_A_SEANET_RES_CONV2, i, "weight"), {1, C / 2, C});
+ w.tensor(fmt(TN_A_SEANET_RES_CONV2, i, "bias"), {C});
+ w.tensor(fmt(TN_A_SEANET_SCALE_CONV, i, "weight"), {2 * ratios[i], C, 2 * C});
+ w.tensor(fmt(TN_A_SEANET_SCALE_CONV, i, "bias"), {2 * C});
+ }
+ w.tensor(fmt(TN_A_SEANET_CONV_OUT, "weight"), {3, C_top, dim});
+ w.tensor(fmt(TN_A_SEANET_CONV_OUT, "bias"), {dim});
+ } else {
+ w.tensor(fmt(TN_A_GEN_WAV_SEANET_CONV_IN, "weight"), {7, dim, C_top});
+ w.tensor(fmt(TN_A_GEN_WAV_SEANET_CONV_IN, "bias"), {C_top});
+ for (int i = 0; i < n_stage; i++) {
+ const int64_t C = C_top >> (i + 1); // output channels of the stage
+ const int r = ratios[n_stage - 1 - i];
+ // transposed conv kernel: [K, OC, IC]
+ w.tensor(fmt(TN_A_GEN_WAV_SEANET_SCALE_CONV, i, "weight"), {2 * r, C, 2 * C});
+ w.tensor(fmt(TN_A_GEN_WAV_SEANET_SCALE_CONV, i, "bias"), {C});
+ w.tensor(fmt(TN_A_GEN_WAV_SEANET_RES_CONV1, i, "weight"), {3, C, C / 2});
+ w.tensor(fmt(TN_A_GEN_WAV_SEANET_RES_CONV1, i, "bias"), {C / 2});
+ w.tensor(fmt(TN_A_GEN_WAV_SEANET_RES_CONV2, i, "weight"), {1, C / 2, C});
+ w.tensor(fmt(TN_A_GEN_WAV_SEANET_RES_CONV2, i, "bias"), {C});
+ }
+ w.tensor(fmt(TN_A_GEN_WAV_SEANET_CONV_OUT, "weight"), {3, C0, 1});
+ w.tensor(fmt(TN_A_GEN_WAV_SEANET_CONV_OUT, "bias"), {1});
+ }
+}
+
+// mimi transformer block: pre-norm with bias, no attn/ffn bias, layer scale on both paths
+static void g5_add_mimi_tfm(mmproj_writer & w, const char * prefix, int n_layer, int64_t dim, int64_t n_ff) {
+ vit_opts o;
+ o.qkv_bias = false;
+ o.o_bias = false;
+ o.ffn_bias = false;
+ o.post_ln = false;
+ add_vit(w, prefix, n_layer, dim, n_ff, o);
+ for (int il = 0; il < n_layer; il++) {
+ w.tensor(fmt(TN_LS_1, prefix, il, "weight"), {dim});
+ w.tensor(fmt(TN_LS_2, prefix, il, "weight"), {dim});
+ }
+}
+
+static void g5_add_pockettts_spkenc(mmproj_writer & w, const enc_hparams & hp, bool mixed) {
+ add_audio_kv(w, PROJECTOR_TYPE_POCKETTTS_SPKENC, hp, 1, mixed); // raw waveform, one "mel" row
+ g5_add_seanet(w, false, {4, 5, 6}, 8, hp.n_embd);
+ g5_add_mimi_tfm(w, "a", hp.n_layer, hp.n_embd, hp.n_ff);
+ w.tensor(fmt(TN_A_DOWNSAMPLE_CONV, "weight"), {32, hp.n_embd, hp.n_embd}); // stride 16
+ w.tensor(fmt(TN_A_SPEAKER_PROJ, "weight"), {hp.n_embd, hp.n_proj});
+}
+
+// one gen state with a fixed seed, as the helper does per generation
+static mtmd::gen_state_ptr g5_gen_state(mtmd_context * ctx) {
+ mtmd_gen_state_params sp = mtmd_gen_state_params_default();
+ sp.seed = 42;
+ return mtmd::gen_state_ptr(mtmd_gen_state_init(ctx, sp));
+}
+
+static bool g5_gen_wav_feats(mtmd_context * ctx, mtmd_gen_state * st, const std::vector<float> & feats, std::vector<float> & out) {
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.type = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
+ inp.feats = feats.data();
+ inp.n_feats = feats.size();
+ mtmd_gen_out res{};
+ if (mtmd_gen_audio_process(ctx, st, &inp, &res) != 0 || res.n_samples == 0) {
+ return false;
+ }
+ out.insert(out.end(), res.audio, res.audio + res.n_samples);
+ return true;
+}
+
+// GEN_CODE with a fixed hidden state per step, appends the float outputs (feats, embd)
+static bool g5_gen_code(mtmd_context * ctx, mtmd_gen_state * st, mtmd_gen_inp inp, int step, size_t n_embd,
+ std::vector<float> & out, mtmd_gen_out & res) {
+ std::vector<float> h(n_embd);
+ fill_normal(h.data(), h.size(), "g5.h_state." + std::to_string(step), 0.0f, 1.0f);
+ inp.type = MTMD_GEN_PROCESS_TYPE_GEN_CODE;
+ inp.embd = h.data();
+ res = {};
+ if (mtmd_gen_audio_process(ctx, st, &inp, &res) != 0) {
+ return false;
+ }
+ if (res.feats) {
+ out.insert(out.end(), res.feats, res.feats + res.n_feats);
+ }
+ if (res.embd) {
+ out.insert(out.end(), res.embd, res.embd + n_embd);
+ }
+ return true;
+}
+
+static bool g5_gen_wav_codes(mtmd_context * ctx, mtmd_gen_state * st, std::vector<int32_t> & codes, std::vector<float> & out) {
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.type = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
+ inp.codes = codes.data();
+ inp.n_codes = codes.size();
+ mtmd_gen_out res{};
+ if (mtmd_gen_audio_process(ctx, st, &inp, &res) != 0 || res.n_samples == 0) {
+ return false;
+ }
+ out.insert(out.end(), res.audio, res.audio + res.n_samples);
+ return true;
+}
+
+// code2wav of Qwen3-TTS / Fish DAC: RVQ decode, pre conv (qwen3tts only), transformer, ConvNeXt upsample, DAC decoder
+// n_tfm_layer, n_up and the DAC block count are fixed by the loader
+static void g5_add_code2wav(mmproj_writer & w, bool with_proj, int n_cb, int64_t vocab, int n_tfm_layer, int64_t tfm_dim, int64_t n_ff, int n_up, int64_t C) {
+ // without projections, the codebook entries are already transformer rows (drama3: out_proj folded at conversion)
+ const int64_t cb_dim = with_proj ? 16 : tfm_dim;
+ const int64_t n_rest = n_cb - 1;
+ w.tensor(fmt(TN_A_GEN_WAV_QUANT_FIRST_CB, "weight"), {cb_dim, vocab});
+ w.tensor(fmt(TN_A_GEN_WAV_QUANT_REST_CB, "weight"), {cb_dim, vocab, n_rest});
+ if (with_proj) {
+ const int64_t q_dim = 64;
+ w.tensor(fmt(TN_A_GEN_WAV_QUANT_FIRST_IN, "weight"), {q_dim, cb_dim});
+ w.tensor(fmt(TN_A_GEN_WAV_QUANT_FIRST_OUT, "weight"), {cb_dim, q_dim});
+ w.tensor(fmt(TN_A_GEN_WAV_QUANT_REST_IN, "weight"), {q_dim, cb_dim});
+ w.tensor(fmt(TN_A_GEN_WAV_QUANT_REST_OUT, "weight"), {cb_dim, q_dim});
+ w.tensor(fmt(TN_A_GEN_WAV_PRE_CONV, "weight"), {3, q_dim, C});
+ w.tensor(fmt(TN_A_GEN_WAV_PRE_CONV, "bias"), {C});
+ w.tensor(fmt(TN_A_GEN_WAV_TFM_IN_PROJ, "weight"), {C, tfm_dim});
+ w.tensor(fmt(TN_A_GEN_WAV_TFM_IN_PROJ, "bias"), {tfm_dim});
+ w.tensor(fmt(TN_A_GEN_WAV_TFM_OUT_PROJ, "weight"), {tfm_dim, C});
+ w.tensor(fmt(TN_A_GEN_WAV_TFM_OUT_PROJ, "bias"), {C});
+ }
+ w.norm(fmt(TN_A_GEN_WAV_TFM_OUT_NORM, "weight"), tfm_dim);
+ for (int il = 0; il < n_tfm_layer; il++) {
+ const char * p = "a.gen.wav.tfm";
+ for (const char * x : {TN_ATTN_Q, TN_ATTN_K, TN_ATTN_V, TN_ATTN_OUTPUT}) {
+ w.tensor(fmt(x, p, il, "weight"), {tfm_dim, tfm_dim});
+ }
+ w.norm (fmt(TN_LN_1, p, il, "weight"), tfm_dim);
+ w.norm (fmt(TN_LN_2, p, il, "weight"), tfm_dim);
+ w.tensor(fmt(TN_LS_1, p, il, "weight"), {tfm_dim});
+ w.tensor(fmt(TN_LS_2, p, il, "weight"), {tfm_dim});
+ w.tensor(fmt(TN_FFN_GATE, p, il, "weight"), {tfm_dim, n_ff});
+ w.tensor(fmt(TN_FFN_UP, p, il, "weight"), {tfm_dim, n_ff});
+ w.tensor(fmt(TN_FFN_DOWN, p, il, "weight"), {n_ff, tfm_dim});
+ }
+ for (int il = 0; il < n_up; il++) {
+ // stride-2 transposed conv, kernel 2: [K, OC, IC]
+ w.tensor(fmt(TN_A_GEN_WAV_UP_CONV, il, "weight"), {2, C, C});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_CONV, il, "bias"), {C});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_DWCONV, il, "weight"), {7, 1, C});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_DWCONV, il, "bias"), {C});
+ w.norm (fmt(TN_A_GEN_WAV_UP_NORM, il, "weight"), C);
+ w.tensor(fmt(TN_A_GEN_WAV_UP_NORM, il, "bias"), {C});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_PW1, il, "weight"), {C, 2 * C});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_PW1, il, "bias"), {2 * C});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_PW2, il, "weight"), {2 * C, C});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_PW2, il, "bias"), {C});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_GAMMA, il), {C});
+ }
+ // DAC: strides 8, 5, 4, 3 (kernel = 2 * stride), channels halve per block
+ const int strides[4] = {8, 5, 4, 3};
+ const int64_t C_dac = 64;
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_ENTRY, "weight"), {7, C, C_dac});
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_ENTRY, "bias"), {C_dac});
+ for (int il = 0; il < 4; il++) {
+ const int64_t ic = C_dac >> il;
+ const int64_t oc = ic / 2;
+ w.norm (fmt(TN_A_GEN_WAV_DAC_SNAKE, il, "alpha"), ic);
+ w.norm (fmt(TN_A_GEN_WAV_DAC_SNAKE, il, "beta"), ic);
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_CONV, il, "weight"), {2 * strides[il], oc, ic});
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_CONV, il, "bias"), {oc});
+ for (int ir = 0; ir < 3; ir++) {
+ w.norm (fmt(TN_A_GEN_WAV_DAC_RES_ACT1, il, ir, "alpha"), oc);
+ w.norm (fmt(TN_A_GEN_WAV_DAC_RES_ACT1, il, ir, "beta"), oc);
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_RES_CONV1, il, ir, "weight"), {7, oc, oc});
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_RES_CONV1, il, ir, "bias"), {oc});
+ w.norm (fmt(TN_A_GEN_WAV_DAC_RES_ACT2, il, ir, "alpha"), oc);
+ w.norm (fmt(TN_A_GEN_WAV_DAC_RES_ACT2, il, ir, "beta"), oc);
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_RES_CONV2, il, ir, "weight"), {1, oc, oc});
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_RES_CONV2, il, ir, "bias"), {oc});
+ }
+ }
+ const int64_t C_out = C_dac >> 4;
+ w.norm (fmt(TN_A_GEN_WAV_DAC_POST_SNAKE, "alpha"), C_out);
+ w.norm (fmt(TN_A_GEN_WAV_DAC_POST_SNAKE, "beta"), C_out);
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_POST_CONV, "weight"), {7, C_out, 1});
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_POST_CONV, "bias"), {1});
+}
+
+// kokoro: AdainResBlk1d (upsample: depthwise transposed conv "pool", weight as [C, 3])
+static void g5_kokoro_resblk(mmproj_writer & w, const std::string & p, int64_t c_in, int64_t c_out, bool upsample) {
+ const int64_t n_style = 128;
+ w.tensor(p + ".norm1.fc.weight", {n_style, 2 * c_in});
+ w.tensor(p + ".norm1.fc.bias", {2 * c_in});
+ w.tensor(p + ".conv1.weight", {3, c_in, c_out});
+ w.tensor(p + ".conv1.bias", {c_out});
+ w.tensor(p + ".norm2.fc.weight", {n_style, 2 * c_out});
+ w.tensor(p + ".norm2.fc.bias", {2 * c_out});
+ w.tensor(p + ".conv2.weight", {3, c_out, c_out});
+ w.tensor(p + ".conv2.bias", {c_out});
+ if (c_in != c_out) {
+ w.tensor(p + ".conv1x1.weight", {1, c_in, c_out});
+ }
+ if (upsample) {
+ w.tensor(p + ".pool.weight", {c_in, 3});
+ w.tensor(p + ".pool.bias", {c_in});
+ }
+}
+
+// kokoro: AdaINResBlock1 of the generator, snake alphas must not be 0
+static void g5_kokoro_gen_resblk(mmproj_writer & w, const std::string & p, int64_t C, int64_t k) {
+ const int64_t n_style = 128;
+ for (int j = 0; j < 3; j++) {
+ const std::string js = std::to_string(j);
+ for (const char * a : {".adain1.", ".adain2."}) {
+ w.tensor(p + a + js + ".fc.weight", {n_style, 2 * C});
+ w.tensor(p + a + js + ".fc.bias", {2 * C});
+ }
+ w.norm (p + ".alpha1." + js, C);
+ w.norm (p + ".alpha2." + js, C);
+ w.tensor(p + ".convs1." + js + ".weight", {k, C, C});
+ w.tensor(p + ".convs1." + js + ".bias", {C});
+ w.tensor(p + ".convs2." + js + ".weight", {k, C, C});
+ w.tensor(p + ".convs2." + js + ".bias", {C});
+ }
+}
+
+// kokoro: bidirectional LSTM in torch layout, read on the host
+static void g5_kokoro_lstm(mmproj_writer & w, const std::string & p, int64_t n_in) {
+ const int64_t n_h = 256;
+ for (const char * sfx : {"", "_reverse"}) {
+ w.tensor(p + ".weight_ih_l0" + sfx, {n_in, 4 * n_h});
+ w.tensor(p + ".weight_hh_l0" + sfx, {n_h, 4 * n_h});
+ w.tensor(p + ".bias_l0" + sfx, {4 * n_h});
+ }
+}
+
+// tiny-voca: one bidirectional stack, run by libllama (arch tiny-voca), so the tensors keep the libllama names
+static void g5_tiny_voca_stack(mmproj_writer & w, const std::string & p, int n_layer, int64_t n_embd, int64_t n_ff) {
+ for (int il = 0; il < n_layer; il++) {
+ const std::string b = p + "blk." + std::to_string(il) + ".";
+ for (const char * n : {"attn_norm", "ffn_norm"}) {
+ w.norm (b + n + ".weight", n_embd);
+ w.tensor(b + n + ".bias", {n_embd});
+ }
+ for (const char * n : {"attn_q", "attn_k", "attn_v", "attn_output"}) {
+ w.tensor(b + n + ".weight", {n_embd, n_embd});
+ w.tensor(b + n + ".bias", {n_embd});
+ }
+ w.tensor(b + "ssm_conv1d.weight", {7, n_embd});
+ w.tensor(b + "ssm_conv1d.bias", {n_embd});
+ w.tensor(b + "ffn_up.weight", {n_embd, n_ff});
+ w.tensor(b + "ffn_up.bias", {n_ff});
+ w.tensor(b + "ffn_down.weight", {n_ff, n_embd});
+ w.tensor(b + "ffn_down.bias", {n_embd});
+ }
+ w.norm (p + "output_norm.weight", n_embd);
+ w.tensor(p + "output_norm.bias", {n_embd});
+}
+
+static bool make_mmproj_g5(projector_type proj, mmproj_writer & w, test_model & tm) {
+ enc_hparams hp;
+ tm.n_embd_out = hp.n_proj;
+ switch (proj) {
+ case PROJECTOR_TYPE_QWEN3TTS_SPKENC:
+ {
+ g5_add_qwen3tts_spkenc(w, hp, false);
+ tm.audio = true;
+ } break;
+ case PROJECTOR_TYPE_POCKETTTS_SPKENC:
+ {
+ g5_add_pockettts_spkenc(w, hp, false);
+ tm.audio = true;
+ } break;
+ case PROJECTOR_TYPE_SOPRANO:
+ {
+ // vocos decoder over backbone hidden states, n_fft from the head (2050 = 2 * (1024 + 1))
+ const int64_t n_inp = hp.n_proj;
+ const int64_t n_head_out = 2050;
+ add_gen_audio_kv(w, proj, hp);
+ w.tensor(fmt(TN_A_GEN_WAV_INPUT, "weight"), {3, n_inp, hp.n_embd});
+ w.tensor(fmt(TN_A_GEN_WAV_INPUT, "bias"), {hp.n_embd});
+ w.norm (fmt(TN_A_GEN_WAV_NORM, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_A_GEN_WAV_NORM, "bias"), {hp.n_embd});
+ for (int il = 0; il < (int) hp.n_layer; il++) {
+ w.tensor(fmt(TN_A_GEN_WAV_UP_DWCONV, il, "weight"), {7, 1, hp.n_embd});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_DWCONV, il, "bias"), {hp.n_embd});
+ w.norm (fmt(TN_A_GEN_WAV_UP_NORM, il, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_A_GEN_WAV_UP_NORM, il, "bias"), {hp.n_embd});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_PW1, il, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_PW1, il, "bias"), {hp.n_ff});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_PW2, il, "weight"), {hp.n_ff, hp.n_embd});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_PW2, il, "bias"), {hp.n_embd});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_GAMMA, il), {hp.n_embd});
+ }
+ w.norm (fmt(TN_A_GEN_WAV_OUTPUT_NORM, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_A_GEN_WAV_OUTPUT_NORM, "bias"), {hp.n_embd});
+ w.tensor(fmt(TN_A_GEN_WAV_OUTPUT, "weight"), {hp.n_embd, n_head_out});
+ w.tensor(fmt(TN_A_GEN_WAV_OUTPUT, "bias"), {n_head_out});
+ // the whole utterance is decoded at once from the hidden states of the generated tokens
+ tm.gen = [n_inp](mtmd_context * ctx, std::vector<float> & out) {
+ auto st = g5_gen_state(ctx);
+ if (!st) {
+ return false;
+ }
+ std::vector<float> feats(8 * n_inp);
+ fill_normal(feats.data(), feats.size(), "soprano.feats", 0.0f, 1.0f);
+ return g5_gen_wav_feats(ctx, st.get(), feats, out);
+ };
+ } break;
+ case PROJECTOR_TYPE_POCKETTTS_GEN:
+ {
+ // flow net + eos head, then the mimi decoder (upsample, transformer, SEANet)
+ const int64_t n_latent = 32;
+ const int64_t n_ch = 64;
+ const int64_t n_freq = 16;
+ const int64_t n_proj = hp.n_proj;
+ add_gen_audio_kv(w, proj, hp);
+ w.tensor(fmt(TN_A_GEN_FLOW_INPUT_PROJ, "weight"), {n_latent, n_ch});
+ w.tensor(fmt(TN_A_GEN_FLOW_INPUT_PROJ, "bias"), {n_ch});
+ w.tensor(fmt(TN_A_GEN_FLOW_COND_EMBD, "weight"), {n_proj, n_ch});
+ w.tensor(fmt(TN_A_GEN_FLOW_COND_EMBD, "bias"), {n_ch});
+ for (int i = 0; i < 2; i++) {
+ w.tensor(fmt(TN_A_GEN_FLOW_TIME_FREQS, i), {n_freq});
+ w.tensor(fmt(TN_A_GEN_FLOW_TIME_UP, i, "weight"), {2 * n_freq, n_ch});
+ w.tensor(fmt(TN_A_GEN_FLOW_TIME_UP, i, "bias"), {n_ch});
+ w.tensor(fmt(TN_A_GEN_FLOW_TIME_DOWN, i, "weight"), {n_ch, n_ch});
+ w.tensor(fmt(TN_A_GEN_FLOW_TIME_DOWN, i, "bias"), {n_ch});
+ w.norm (fmt(TN_A_GEN_FLOW_TIME_NORM, i), n_ch);
+ }
+ for (int il = 0; il < 2; il++) {
+ w.norm (fmt(TN_A_GEN_FLOW_BLK_NORM, il, "weight"), n_ch);
+ w.tensor(fmt(TN_A_GEN_FLOW_BLK_NORM, il, "bias"), {n_ch});
+ w.tensor(fmt(TN_A_GEN_FLOW_BLK_UP, il, "weight"), {n_ch, n_ch});
+ w.tensor(fmt(TN_A_GEN_FLOW_BLK_UP, il, "bias"), {n_ch});
+ w.tensor(fmt(TN_A_GEN_FLOW_BLK_DOWN, il, "weight"), {n_ch, n_ch});
+ w.tensor(fmt(TN_A_GEN_FLOW_BLK_DOWN, il, "bias"), {n_ch});
+ w.tensor(fmt(TN_A_GEN_FLOW_BLK_ADA, il, "weight"), {n_ch, 3 * n_ch});
+ w.tensor(fmt(TN_A_GEN_FLOW_BLK_ADA, il, "bias"), {3 * n_ch});
+ }
+ w.tensor(fmt(TN_A_GEN_FLOW_FINAL_ADA, "weight"), {n_ch, 2 * n_ch});
+ w.tensor(fmt(TN_A_GEN_FLOW_FINAL_ADA, "bias"), {2 * n_ch});
+ w.tensor(fmt(TN_A_GEN_FLOW_FINAL_PROJ, "weight"), {n_ch, n_latent});
+ w.tensor(fmt(TN_A_GEN_FLOW_FINAL_PROJ, "bias"), {n_latent});
+ w.tensor(fmt(TN_A_GEN_OUT_EOS, "weight"), {n_proj, 1});
+ w.tensor(fmt(TN_A_GEN_OUT_EOS, "bias"), {1});
+ w.tensor(fmt(TN_A_GEN_INPUT_LINEAR, "weight"), {n_latent, n_proj});
+ w.tensor(TN_A_GEN_EMB_MEAN, {n_latent});
+ w.norm (TN_A_GEN_EMB_STD, n_latent);
+ // mimi decoder, depthwise upsample by 16
+ w.tensor(fmt(TN_A_GEN_WAV_QUANT_OUT, "weight"), {n_latent, hp.n_embd});
+ w.tensor(fmt(TN_A_GEN_WAV_UPSAMPLE, "weight"), {32, 1, hp.n_embd});
+ g5_add_mimi_tfm(w, "a.gen.wav.tfm", hp.n_layer, hp.n_embd, hp.n_ff);
+ g5_add_seanet(w, true, {4, 5, 6}, 8, hp.n_embd);
+ // temp 0: no flow noise; latents are decoded 8 at a time like the helper, the decoder state bridges the windows
+ tm.gen = [n_proj](mtmd_context * ctx, std::vector<float> & out) {
+ auto st = g5_gen_state(ctx);
+ if (!st) {
+ return false;
+ }
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.temp = 0.0f;
+ std::vector<float> feats;
+ for (int step = 0; step < 16; step++) {
+ mtmd_gen_out res;
+ if (!g5_gen_code(ctx, st.get(), inp, step, n_proj, out, res) || res.n_feats == 0) {
+ return false;
+ }
+ feats.insert(feats.end(), res.feats, res.feats + res.n_feats);
+ if (feats.size() == 8 * res.n_feats) {
+ if (!g5_gen_wav_feats(ctx, st.get(), feats, out)) {
+ return false;
+ }
+ feats.clear();
+ }
+ }
+ return true;
+ };
+ } break;
+ case PROJECTOR_TYPE_QWEN3TTS_GEN:
+ {
+ // code predictor (one token per acoustic codebook), then code2wav
+ const int n_acoustic = 3;
+ const int64_t vocab = 64; // above the default top_k (50) of the warmup graph
+ const int64_t n_talker = hp.n_proj;
+ const int64_t d_head = hp.n_embd / hp.n_head;
+ add_gen_audio_kv(w, proj, hp);
+ for (int il = 0; il < (int) hp.n_layer; il++) {
+ const char * p = "a.gen.code";
+ for (const char * x : {TN_ATTN_Q, TN_ATTN_K, TN_ATTN_V, TN_ATTN_OUTPUT}) {
+ w.tensor(fmt(x, p, il, "weight"), {hp.n_embd, hp.n_embd});
+ }
+ w.norm (fmt(TN_ATTN_Q_NORM, p, il, "weight"), d_head);
+ w.norm (fmt(TN_ATTN_K_NORM, p, il, "weight"), d_head);
+ w.norm (fmt(TN_LN_1, p, il, "weight"), hp.n_embd);
+ w.norm (fmt(TN_LN_2, p, il, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_FFN_GATE, p, il, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_FFN_UP, p, il, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_FFN_DOWN, p, il, "weight"), {hp.n_ff, hp.n_embd});
+ }
+ w.tensor(fmt(TN_A_GEN_CODE_PROJ_IN, "weight"), {n_talker, hp.n_embd});
+ w.tensor(fmt(TN_A_GEN_CODE_PROJ_IN, "bias"), {hp.n_embd});
+ w.tensor(fmt(TN_A_GEN_CODE_EMBD, "weight"), {n_talker, vocab, n_acoustic});
+ w.tensor(fmt(TN_A_GEN_CODE_HEAD, "weight"), {hp.n_embd, vocab, n_acoustic});
+ w.tensor(fmt(TN_A_GEN_CODE_OUT_EMBD, "weight"), {n_talker, vocab});
+ w.norm (fmt(TN_A_GEN_CODE_NORM, "weight"), hp.n_embd);
+ // 8 layers with 16 heads are fixed by the loader, d_head 32 like the real model
+ g5_add_code2wav(w, true, n_acoustic + 1, vocab, 8, 512, 128, 2, 128);
+ // greedy code predictor; codes are buffered and decoded in 2 windows like the helper
+ tm.gen = [n_talker](mtmd_context * ctx, std::vector<float> & out) {
+ auto st = g5_gen_state(ctx);
+ if (!st) {
+ return false;
+ }
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.top_k = 1;
+ inp.temp = 0.0f;
+ std::vector<int32_t> codes;
+ for (int step = 0; step < 8; step++) {
+ inp.code0 = (step * 7 + 3) % 64;
+ mtmd_gen_out res;
+ if (!g5_gen_code(ctx, st.get(), inp, step, n_talker, out, res) || res.n_codes == 0) {
+ return false;
+ }
+ codes.insert(codes.end(), res.codes, res.codes + res.n_codes);
+ if (step % 4 == 3) {
+ if (!g5_gen_wav_codes(ctx, st.get(), codes, out)) {
+ return false;
+ }
+ codes.clear();
+ }
+ }
+ return true;
+ };
+ } break;
+ case PROJECTOR_TYPE_MOSHI_GEN:
+ {
+ // depformer with per-step weights (stacked on dim 2), then RVQ decode + mimi decoder
+ const int n_q = 4;
+ const int n_w = 3; // steps past the last weight set reuse it
+ const int64_t n_cb = 2048;
+ const int64_t n_text = 64;
+ const int64_t n_mimi = 256; // 8 heads fixed by the graph
+ const int64_t n_talker = hp.n_proj;
+ add_gen_audio_kv(w, proj, hp);
+ for (int il = 0; il < (int) hp.n_layer; il++) {
+ const char * p = "a.gen.code";
+ for (const char * x : {TN_ATTN_Q, TN_ATTN_K, TN_ATTN_V, TN_ATTN_OUTPUT}) {
+ w.tensor(fmt(x, p, il, "weight"), {hp.n_embd, hp.n_embd, n_w});
+ }
+ w.norm (fmt(TN_LN_1, p, il, "weight"), hp.n_embd);
+ w.norm (fmt(TN_LN_2, p, il, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_FFN_GATE, p, il, "weight"), {hp.n_embd, hp.n_ff, n_w});
+ w.tensor(fmt(TN_FFN_UP, p, il, "weight"), {hp.n_embd, hp.n_ff, n_w});
+ w.tensor(fmt(TN_FFN_DOWN, p, il, "weight"), {hp.n_ff, hp.n_embd, n_w});
+ }
+ w.tensor(fmt(TN_A_GEN_CODE_PROJ_IN, "weight"), {n_talker, hp.n_embd, n_w});
+ w.tensor(fmt(TN_A_GEN_CODE_TOK_EMBD, "weight"), {hp.n_embd, n_text});
+ w.tensor(fmt(TN_A_GEN_CODE_EMBD, "weight"), {hp.n_embd, n_cb, n_q - 1});
+ w.tensor(fmt(TN_A_GEN_CODE_HEAD, "weight"), {hp.n_embd, n_cb, n_q});
+ // one extra row per table: the initial code (2048) used by the helper at the stream start
+ w.tensor(fmt(TN_A_GEN_CODE_OUT_EMBD, "weight"), {n_talker, n_cb + 1, n_q});
+ const int64_t cb_dim = 16;
+ w.tensor(fmt(TN_A_GEN_WAV_QUANT_FIRST_CB, "weight"), {cb_dim, n_cb});
+ w.tensor(fmt(TN_A_GEN_WAV_QUANT_REST_CB, "weight"), {cb_dim, n_cb, n_q - 1});
+ w.tensor(fmt(TN_A_GEN_WAV_QUANT_FIRST_OUT, "weight"), {cb_dim, n_mimi});
+ w.tensor(fmt(TN_A_GEN_WAV_QUANT_REST_OUT, "weight"), {cb_dim, n_mimi});
+ // mimi decoder: depthwise upsample by 2, 8 transformer layers (fixed), SEANet
+ w.tensor(fmt(TN_A_GEN_WAV_UPSAMPLE, "weight"), {4, 1, n_mimi});
+ g5_add_mimi_tfm(w, "a.gen.wav.tfm", 8, n_mimi, 256);
+ g5_add_seanet(w, true, {4, 5, 6, 8}, 8, n_mimi);
+ // greedy depformer (temp 0); same step order as the helper: the first frames feed back
+ // the initial acoustic codes, and frame f is decoded with the acoustic codes of step f + 2
+ tm.gen = [n_talker](mtmd_context * ctx, std::vector<float> & out) {
+ const int acoustic_delay = 2;
+ const int32_t code_initial = 2048;
+ auto st = g5_gen_state(ctx);
+ if (!st) {
+ return false;
+ }
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.temp = 0.0f;
+ std::vector<int32_t> cb0_hist;
+ for (int step = 0; step < 6; step++) {
+ inp.code0 = (step * 5 + 1) % 64;
+ inp.codes = nullptr;
+ inp.n_codes = 0;
+ mtmd_gen_out res;
+ if (!g5_gen_code(ctx, st.get(), inp, step, n_talker, out, res) || res.n_codes == 0) {
+ return false;
+ }
+ std::vector<int32_t> codes(res.codes, res.codes + res.n_codes);
+ if (step + 1 <= acoustic_delay) {
+ std::vector<int32_t> fb = codes;
+ std::fill(fb.begin() + 1, fb.end(), code_initial);
+ inp.codes = fb.data();
+ inp.n_codes = fb.size();
+ if (!g5_gen_code(ctx, st.get(), inp, step, n_talker, out, res)) {
+ return false;
+ }
+ }
+ cb0_hist.push_back(codes[0]);
+ if ((int) cb0_hist.size() > acoustic_delay) {
+ codes[0] = cb0_hist.front();
+ cb0_hist.erase(cb0_hist.begin());
+ if (!g5_gen_wav_codes(ctx, st.get(), codes, out)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ };
+ } break;
+ case PROJECTOR_TYPE_LFM3A_GEN:
+ {
+ // MaskGIT depthformer (12 codebooks, fixed by the helper), then the LFM codec decoder (+ host ISTFT)
+ const int n_cb = 12;
+ const int64_t n_vocab = 64; // FSQ codes + the end-of-audio code
+ const int64_t n_lvl = 4;
+ const int64_t n_talker = hp.n_proj;
+ const int64_t d_head = hp.n_embd / hp.n_head;
+ add_gen_audio_kv(w, proj, hp);
+ for (int il = 0; il < (int) hp.n_layer; il++) {
+ const char * p = "a.gen.code";
+ for (const char * x : {TN_ATTN_Q, TN_ATTN_K, TN_ATTN_V, TN_ATTN_OUTPUT}) {
+ w.tensor(fmt(x, p, il, "weight"), {hp.n_embd, hp.n_embd});
+ }
+ w.tensor(fmt(TN_ATTN_GATE, p, il, "weight"), {hp.n_embd, hp.n_head});
+ w.norm (fmt(TN_ATTN_Q_NORM, p, il, "weight"), d_head);
+ w.norm (fmt(TN_ATTN_K_NORM, p, il, "weight"), d_head);
+ w.norm (fmt(TN_LN_1, p, il, "weight"), hp.n_embd);
+ w.norm (fmt(TN_LN_2, p, il, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_FFN_GATE, p, il, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_FFN_UP, p, il, "weight"), {hp.n_embd, hp.n_ff});
+ w.tensor(fmt(TN_FFN_DOWN, p, il, "weight"), {hp.n_ff, hp.n_embd});
+ }
+ w.tensor(fmt(TN_A_GEN_CODE_PROJ_IN, "weight"), {n_talker, hp.n_embd * n_cb});
+ w.tensor(fmt(TN_A_GEN_CODE_PROJ_IN, "bias"), {hp.n_embd * n_cb});
+ w.tensor(fmt(TN_A_GEN_CODE_EMBD, "weight"), {hp.n_embd, n_vocab, n_cb});
+ w.tensor(fmt(TN_A_GEN_CODE_OUT_EMBD, "weight"), {n_talker, n_vocab * n_cb});
+ w.norm (fmt(TN_A_GEN_CODE_NORM, "weight"), hp.n_embd);
+ w.tensor(fmt(TN_A_GEN_CODE_HEAD_NORM, "weight"), {hp.n_embd, n_cb}, 1.0f);
+ w.tensor(TN_A_GEN_CODE_MASK_EMBD, {hp.n_embd});
+ // codec decoder: 8 layers and width 512 are fixed by the loader, n_fft 1280 -> 641 bins
+ const int64_t n_dec = 512;
+ const int64_t n_q = 64;
+ const int64_t n_dhead = 64;
+ w.tensor(fmt(TN_A_GEN_WAV_QUANT_FIRST_CB, "weight"), {n_lvl, n_vocab - 1});
+ w.tensor(fmt(TN_A_GEN_WAV_QUANT_FIRST_OUT, "weight"), {n_lvl * n_cb, n_q});
+ w.tensor(fmt(TN_A_GEN_WAV_QUANT_FIRST_OUT, "bias"), {n_q});
+ w.tensor(fmt(TN_A_GEN_WAV_TFM_IN_PROJ, "weight"), {n_q, n_dec});
+ w.tensor(fmt(TN_A_GEN_WAV_TFM_IN_PROJ, "bias"), {n_dec});
+ w.tensor(fmt(TN_A_GEN_WAV_TFM_OUT_PROJ, "weight"), {n_dec, 2 * 641});
+ w.tensor(fmt(TN_A_GEN_WAV_TFM_OUT_PROJ, "bias"), {2 * 641});
+ w.norm (fmt(TN_A_GEN_WAV_TFM_OUT_NORM, "weight"), n_dec);
+ for (int il = 0; il < 8; il++) {
+ const char * p = "a.gen.wav.tfm";
+ w.norm (fmt(TN_LN_1, p, il, "weight"), n_dec);
+ w.norm (fmt(TN_ATTN_POST_NORM, p, il, "weight"), n_dec);
+ w.norm (fmt(TN_LN_2, p, il, "weight"), n_dec);
+ w.norm (fmt(TN_FFN_POST_NORM, p, il, "weight"), n_dec);
+ w.tensor(fmt(TN_FFN_GATE, p, il, "weight"), {n_dec, 128});
+ w.tensor(fmt(TN_FFN_UP, p, il, "weight"), {n_dec, 128});
+ w.tensor(fmt(TN_FFN_DOWN, p, il, "weight"), {128, n_dec});
+ if (il % 4 == 3) {
+ // gated attention, GQA 8/2 heads
+ w.tensor(fmt(TN_ATTN_Q, p, il, "weight"), {n_dec, 8 * n_dhead});
+ w.tensor(fmt(TN_ATTN_K, p, il, "weight"), {n_dec, 2 * n_dhead});
+ w.tensor(fmt(TN_ATTN_V, p, il, "weight"), {n_dec, 2 * n_dhead});
+ w.tensor(fmt(TN_ATTN_OUTPUT, p, il, "weight"), {8 * n_dhead, n_dec});
+ w.norm (fmt(TN_ATTN_Q_NORM, p, il, "weight"), n_dhead);
+ w.norm (fmt(TN_ATTN_K_NORM, p, il, "weight"), n_dhead);
+ w.tensor(fmt(TN_ATTN_GATE, p, il, "weight"), {n_dec, 8});
+ } else {
+ // short conv
+ w.tensor(fmt(TN_CONV_PW1, p, il, "weight"), {n_dec, 3 * n_dec});
+ w.tensor(fmt(TN_CONV_DW, p, il, "weight"), {3, n_dec});
+ w.tensor(fmt(TN_CONV_PW2, p, il, "weight"), {n_dec, n_dec});
+ }
+ }
+ // greedy MaskGIT in a fixed codebook order (4 per pass), each frame is decoded right away, then the ISTFT tail
+ tm.gen = [n_talker](mtmd_context * ctx, std::vector<float> & out) {
+ const int n_cb = 12;
+ auto st = g5_gen_state(ctx);
+ if (!st) {
+ return false;
+ }
+ for (int step = 0; step < 4; step++) {
+ std::vector<int32_t> codes(n_cb, -1);
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.codes = codes.data();
+ inp.n_codes = codes.size();
+ mtmd_gen_out res;
+ for (int pass = 0; pass < 3; pass++) {
+ if (!g5_gen_code(ctx, st.get(), inp, step, n_talker, out, res) || res.n_feats % n_cb != 0) {
+ return false;
+ }
+ // the last code (end of audio) is skipped, so every step makes a frame
+ const size_t n_vocab = res.n_feats / n_cb;
+ for (int i = 4 * pass; i < 4 * pass + 4; i++) {
+ const float * l = res.feats + (size_t) i * n_vocab;
+ codes[i] = (int32_t) (std::max_element(l, l + n_vocab - 1) - l);
+ }
+ }
+ // all codes known: only the feedback embedding
+ if (!g5_gen_code(ctx, st.get(), inp, step, n_talker, out, res) ||
+ !g5_gen_wav_codes(ctx, st.get(), codes, out)) {
+ return false;
+ }
+ }
+ mtmd_gen_inp flush = mtmd_gen_inp_default(ctx);
+ flush.type = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
+ mtmd_gen_out res{};
+ if (mtmd_gen_audio_process(ctx, st.get(), &flush, &res) != 0) {
+ return false;
+ }
+ out.insert(out.end(), res.audio, res.audio + res.n_samples);
+ return true;
+ };
+ } break;
+ case PROJECTOR_TYPE_DRAMA3_GEN:
+ {
+ // codebook tower: 1 shared layer + one layer per residual codebook (10 codebooks, fixed by the helper)
+ const int n_cb = 10;
+ const int64_t n_vocab = 64; // above the default top_k (30) of the warmup graph
+ const int64_t D = hp.n_proj; // tower width, same as the backbone rows
+ const int64_t d_head = 64; // the tower rope rotates 64 dims
+ const int64_t n_qkv = d_head * hp.n_head;
+ enc_hparams ht = hp;
+ ht.n_layer = n_cb;
+ add_gen_audio_kv(w, proj, ht);
+ for (int il = 0; il < n_cb; il++) {
+ const char * p = "a.gen.code";
+ w.tensor(fmt(TN_ATTN_Q, p, il, "weight"), {D, n_qkv});
+ w.tensor(fmt(TN_ATTN_K, p, il, "weight"), {D, n_qkv});
+ w.tensor(fmt(TN_ATTN_V, p, il, "weight"), {D, n_qkv});
+ w.tensor(fmt(TN_ATTN_GATE, p, il, "weight"), {D, n_qkv});
+ w.tensor(fmt(TN_ATTN_OUTPUT, p, il, "weight"), {n_qkv, D});
+ w.norm (fmt(TN_ATTN_Q_NORM, p, il, "weight"), d_head);
+ w.norm (fmt(TN_ATTN_K_NORM, p, il, "weight"), d_head);
+ w.norm (fmt(TN_LN_1, p, il, "weight"), D);
+ w.norm (fmt(TN_LN_2, p, il, "weight"), D);
+ w.tensor(fmt(TN_FFN_GATE, p, il, "weight"), {D, hp.n_ff});
+ w.tensor(fmt(TN_FFN_UP, p, il, "weight"), {D, hp.n_ff});
+ w.tensor(fmt(TN_FFN_DOWN, p, il, "weight"), {hp.n_ff, D});
+ w.norm (fmt(TN_A_GEN_CODE_ENORM, il, "weight"), D);
+ w.norm (fmt(TN_A_GEN_CODE_HNORM, il, "weight"), D);
+ w.tensor(fmt(TN_A_GEN_CODE_EH_PROJ, il, "weight"), {2 * D, D});
+ w.tensor(fmt(TN_A_GEN_CODE_BLK_EMBD, il, "weight"), {D, n_vocab});
+ w.norm (fmt(TN_A_GEN_CODE_BLK_OUT_NORM, il, "weight"), D);
+ }
+ w.tensor(fmt(TN_A_GEN_CODE_EMBD, "weight"), {D, n_vocab, n_cb});
+ w.tensor(fmt(TN_A_GEN_CODE_HEAD, "weight"), {D, n_vocab, n_cb - 1});
+ w.tensor(fmt(TN_A_GEN_CODE_OUT_EMBD, "weight"), {D, n_vocab});
+ // Fish DAC: 8 layers with 16 heads fixed by the loader, d_head 32
+ g5_add_code2wav(w, false, n_cb, n_vocab, 8, 512, 128, 2, 512);
+ // like the helper: tower rows of the text prompt, then greedy frames from fixed main codes,
+ // each tower row reads the codes of the previous frame; the frames go through the codec in 2 calls
+ tm.gen = [D](mtmd_context * ctx, std::vector<float> & out) {
+ auto st = g5_gen_state(ctx);
+ if (!st) {
+ return false;
+ }
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.top_k = 1;
+ mtmd_gen_out res;
+ for (int row = 0; row < 3; row++) {
+ inp.code0 = -1;
+ if (!g5_gen_code(ctx, st.get(), inp, row, D, out, res)) {
+ return false;
+ }
+ }
+ std::vector<int32_t> frame;
+ std::vector<int32_t> codes;
+ for (int step = 0; step < 6; step++) {
+ inp.code0 = (step * 11 + 1) % 64;
+ inp.codes = frame.empty() ? nullptr : frame.data();
+ inp.n_codes = frame.size();
+ if (!g5_gen_code(ctx, st.get(), inp, 3 + step, D, out, res) || res.n_codes == 0) {
+ return false;
+ }
+ frame.assign(res.codes, res.codes + res.n_codes);
+ codes.insert(codes.end(), frame.begin(), frame.end());
+ if (step % 3 == 2) {
+ if (!g5_gen_wav_codes(ctx, st.get(), codes, out)) {
+ return false;
+ }
+ codes.clear();
+ }
+ }
+ return true;
+ };
+ // Vulkan F16 matmuls give NMSE 1.3e-4
+ tm.nmse_max = 5e-4;
+ } break;
+ case PROJECTOR_TYPE_KOKORO:
+ {
+ // StyleTTS2 predictor + iSTFTNet decoder; hidden 512 and style 128 are fixed by the graph,
+ // the generator strides (10, 6) must match the 300 samples per F0 step of the source
+ const int64_t n_h = 512;
+ const int64_t n_style = 128;
+ const int64_t n_cat = n_h + n_style;
+ const int64_t n_phon = 16;
+ const int64_t n_bert = hp.n_proj; // backbone width
+ add_gen_audio_kv(w, proj, hp);
+ // text encoder
+ w.tensor("a.gen.text.embedding.weight", {n_h, n_phon});
+ w.tensor("a.gen.text.cnn.0.0.weight", {5, n_h, n_h});
+ w.tensor("a.gen.text.cnn.0.0.bias", {n_h});
+ w.tensor("a.gen.text.cnn.0.1.gamma", {n_h}, 1.0f);
+ w.tensor("a.gen.text.cnn.0.1.beta", {n_h});
+ g5_kokoro_lstm(w, "a.gen.text.lstm", n_h);
+ // prosody predictor
+ w.tensor("a.gen.bert_enc.weight", {n_bert, n_h});
+ w.tensor("a.gen.bert_enc.bias", {n_h});
+ g5_kokoro_lstm(w, "a.gen.pred.text_encoder.lstms.0", n_cat);
+ w.tensor("a.gen.pred.text_encoder.lstms.1.fc.weight", {n_style, 2 * n_h});
+ w.tensor("a.gen.pred.text_encoder.lstms.1.fc.bias", {2 * n_h});
+ g5_kokoro_lstm(w, "a.gen.pred.lstm", n_cat);
+ w.tensor("a.gen.pred.duration_proj.linear_layer.weight", {n_h, 4});
+ w.tensor("a.gen.pred.duration_proj.linear_layer.bias", {4});
+ g5_kokoro_lstm(w, "a.gen.pred.shared", n_cat);
+ for (const char * curve : {"F0", "N"}) {
+ const std::string q = std::string("a.gen.pred.") + curve;
+ g5_kokoro_resblk(w, q + ".0", n_h, n_h, false);
+ g5_kokoro_resblk(w, q + ".1", n_h, n_h / 2, true);
+ g5_kokoro_resblk(w, q + ".2", n_h / 2, n_h / 2, false);
+ w.tensor(q + "_proj.weight", {1, n_h / 2, 1});
+ w.tensor(q + "_proj.bias", {1});
+ }
+ // decoder
+ const int64_t n_dec = 64;
+ const int64_t n_res = 64;
+ w.tensor("a.gen.dec.F0_conv.weight", {3, 1, 1});
+ w.tensor("a.gen.dec.F0_conv.bias", {1});
+ w.tensor("a.gen.dec.N_conv.weight", {3, 1, 1});
+ w.tensor("a.gen.dec.N_conv.bias", {1});
+ g5_kokoro_resblk(w, "a.gen.dec.encode", n_h + 2, n_dec, false);
+ w.tensor("a.gen.dec.asr_res.0.weight", {1, n_h, n_res});
+ w.tensor("a.gen.dec.asr_res.0.bias", {n_res});
+ g5_kokoro_resblk(w, "a.gen.dec.decode.0", n_dec + n_res + 2, n_dec, true);
+ const std::string g = "a.gen.dec.generator.";
+ w.tensor(g + "m_source.l_linear.weight", {9, 1});
+ w.tensor(g + "m_source.l_linear.bias", {1});
+ const int strides[2] = {10, 6};
+ const int64_t src_k[2] = {12, 1};
+ const int64_t res_k[3] = {3, 7, 11};
+ int64_t C = n_dec;
+ for (int i = 0; i < 2; i++) {
+ const std::string is = std::to_string(i);
+ // transposed conv kernel [K, OC, IC]
+ w.tensor(g + "ups." + is + ".weight", {2 * strides[i], C / 2, C});
+ w.tensor(g + "ups." + is + ".bias", {C / 2});
+ C /= 2;
+ w.tensor(g + "noise_convs." + is + ".weight", {src_k[i], 22, C});
+ w.tensor(g + "noise_convs." + is + ".bias", {C});
+ g5_kokoro_gen_resblk(w, g + "noise_res." + is, C, i == 0 ? 7 : 11);
+ for (int j = 0; j < 3; j++) {
+ g5_kokoro_gen_resblk(w, g + "resblocks." + std::to_string(i * 3 + j), C, res_k[j]);
+ }
+ }
+ w.tensor(g + "conv_post.weight", {7, C, 22});
+ w.tensor(g + "conv_post.bias", {22});
+ // a voice is a table of style rows (decoder style, then predictor style), picked by the phoneme count
+ w.tensor("voice.test", {2 * n_style, 8});
+ // like the helper: one segment of padded phonemes, the voice row of its length, then the backbone states
+ tm.gen = [n_bert](mtmd_context * ctx, std::vector<float> & out) {
+ const size_t n_voice_row = 256;
+ auto st = g5_gen_state(ctx);
+ const char * voice = mtmd_gen_audio_voice_name(ctx, 0);
+ if (!st || !voice) {
+ return false;
+ }
+ const std::string name = std::string("voice.") + voice;
+ std::vector<float> table(mtmd_gen_audio_read_tensor(ctx, name.c_str(), nullptr, 0));
+ if (table.size() < n_voice_row || mtmd_gen_audio_read_tensor(ctx, name.c_str(), table.data(), table.size()) != table.size()) {
+ return false;
+ }
+ std::vector<int32_t> tokens = {0, 3, 7, 11, 2, 9, 0};
+ const size_t row = std::min(tokens.size() - 3, table.size() / n_voice_row - 1);
+ std::vector<float> feats(table.begin() + row * n_voice_row, table.begin() + (row + 1) * n_voice_row);
+ std::vector<float> h(tokens.size() * n_bert);
+ fill_normal(h.data(), h.size(), "kokoro.h_state", 0.0f, 1.0f);
+ feats.insert(feats.end(), h.begin(), h.end());
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.type = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
+ inp.codes = tokens.data();
+ inp.n_codes = tokens.size();
+ inp.feats = feats.data();
+ inp.n_feats = feats.size();
+ mtmd_gen_out res{};
+ if (mtmd_gen_audio_process(ctx, st.get(), &inp, &res) != 0 || res.n_samples == 0) {
+ return false;
+ }
+ out.insert(out.end(), res.audio, res.audio + res.n_samples);
+ return true;
+ };
+ } break;
+ case PROJECTOR_TYPE_TINY_VOCA:
+ {
+ // duration predictor and source-filter heads in mtmd graphs, the prosody (2 layers) and
+ // acoustic (5 layers) stacks on mtmd-owned llama contexts, the synthesis on the host
+ const int64_t n_embd = hp.n_embd;
+ const int64_t n_tokv = 32;
+ const int64_t n_dur = 32;
+ enc_hparams ht = hp;
+ ht.n_proj = (uint32_t) n_embd; // the backbone (phoneme encoder) has the width of the stacks
+ tm.n_embd_out = ht.n_proj;
+ add_gen_audio_kv(w, proj, ht);
+ w.tensor("a.gen.dur.conv1.weight", {3, n_embd, n_dur});
+ w.tensor("a.gen.dur.conv1.bias", {n_dur});
+ w.norm ("a.gen.dur.norm1.weight", n_dur);
+ w.tensor("a.gen.dur.norm1.bias", {n_dur});
+ w.tensor("a.gen.dur.conv2.weight", {3, n_dur, n_dur});
+ w.tensor("a.gen.dur.conv2.bias", {n_dur});
+ w.norm ("a.gen.dur.norm2.weight", n_dur);
+ w.tensor("a.gen.dur.norm2.bias", {n_dur});
+ w.tensor("a.gen.dur.out.weight", {n_dur, 2});
+ w.tensor("a.gen.dur.out.bias", {2});
+ // heads: 80 + 16 cepstra + 2 gains, 32 noise cepstra + 4 gains
+ w.tensor("a.gen.voc.harmonic.weight", {n_embd, 98});
+ w.tensor("a.gen.voc.harmonic.bias", {98});
+ w.tensor("a.gen.voc.noise.weight", {n_embd, 36});
+ w.tensor("a.gen.voc.noise.bias", {36});
+ w.tensor("a.gen.tok_embd.weight", {n_embd, n_tokv});
+ w.tensor("a.gen.stress_embd.weight", {n_embd, 4});
+ // class > 0: every token is a phone, so it lasts at least one frame
+ w.tensor("a.gen.token_class", {n_tokv}, 1.0f);
+ w.tensor("a.gen.frame_pos.weight", {3, n_embd});
+ w.tensor("a.gen.frame_pos.bias", {n_embd});
+ w.tensor("a.gen.prosody_head.weight", {n_embd, 3});
+ // log F0 above log(f0_max / f0_ref), so that F0 clamps to the same value on every backend: the pulse train turns any F0 difference into a phase drift
+ w.tensor("a.gen.prosody_head.bias", {3})[0] = 4.0f;
+ w.tensor("a.gen.prosody_proj.weight", {3, n_embd});
+ w.tensor("a.gen.prosody_proj.bias", {n_embd});
+ g5_tiny_voca_stack(w, "a.gen.prosody.", 2, n_embd, hp.n_ff);
+ g5_tiny_voca_stack(w, "a.gen.acoustic.", 5, n_embd, hp.n_ff);
+ // encoder row, then frame row
+ w.tensor("voice.test", {2 * n_embd});
+ // like the helper: one sentence of tokens, the voice row, then the encoder state of each token
+ tm.gen = [n_embd](mtmd_context * ctx, std::vector<float> & out) {
+ auto st = g5_gen_state(ctx);
+ const char * voice = mtmd_gen_audio_voice_name(ctx, 0);
+ if (!st || !voice) {
+ return false;
+ }
+ const std::string name = std::string("voice.") + voice;
+ std::vector<float> feats(2 * n_embd);
+ if (mtmd_gen_audio_read_tensor(ctx, name.c_str(), feats.data(), feats.size()) != feats.size()) {
+ return false;
+ }
+ std::vector<int32_t> tokens = {1, 5, 9, 13, 2, 7, 1};
+ std::vector<float> h(tokens.size() * n_embd);
+ fill_normal(h.data(), h.size(), "tiny_voca.h_state", 0.0f, 1.0f);
+ feats.insert(feats.end(), h.begin(), h.end());
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.type = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
+ inp.codes = tokens.data();
+ inp.n_codes = tokens.size();
+ inp.feats = feats.data();
+ inp.n_feats = feats.size();
+ mtmd_gen_out res{};
+ if (mtmd_gen_audio_process(ctx, st.get(), &inp, &res) != 0 || res.n_samples == 0) {
+ return false;
+ }
+ out.insert(out.end(), res.audio, res.audio + res.n_samples);
+ return true;
+ };
+ } break;
+ default:
+ return false;
+ }
+ return true;
+}
+
+//
+// group g6: audio generation / TTS, part 2
+//
+
+// fixed pseudo-random codes in [0, n_vocab)
+static std::vector<int32_t> g6_codes(size_t n, int32_t n_vocab, uint32_t seed) {
+ std::vector<int32_t> res(n);
+ uint32_t s = seed;
+ for (auto & c : res) {
+ s = s * 1664525u + 1013904223u;
+ c = (int32_t) ((s >> 8) % (uint32_t) n_vocab);
+ }
+ return res;
+}
+
+static std::vector<float> g6_normal(size_t n, const std::string & key, float stdev = 1.0f) {
+ std::vector<float> res(n);
+ fill_normal(res.data(), n, key, 0.0f, stdev);
+ return res;
+}
+
+static mtmd::gen_state_ptr g6_gen_state(mtmd_context * ctx) {
+ mtmd_gen_state_params sp = mtmd_gen_state_params_default();
+ sp.seed = 42;
+ return mtmd::gen_state_ptr(mtmd_gen_state_init(ctx, sp));
+}
+
+// zonos3 speaker encoder: MECT-B2 stages, the layout is hard-coded in the graph
+static void g6_zonos3_spkenc(mmproj_writer & w, int64_t n_proj) {
+ const int64_t n_feat = 2560; // F * C of every block
+ const int64_t n_hid = 64;
+ auto bn = [&](const std::string & p, int64_t c) {
+ w.norm(p + ".scale", c);
+ w.tensor(p + ".shift", {c});
+ };
+ // res block: depthwise conv1, pointwise, grouped conv2 (2 input slots per group), pointwise, optional shortcut
+ auto res = [&](const std::string & q, int64_t c_in, int64_t c_out, bool sc) {
+ w.tensor(q + "conv1.w0", {3, 3, 1, c_in});
+ w.tensor(q + "pw1.weight", {1, 1, c_in, c_out});
+ w.tensor(q + "pw1.bias", {c_out});
+ bn(q + "bn1", c_out);
+ w.tensor(q + "conv2.w0", {3, 3, 1, c_out});
+ w.tensor(q + "conv2.w1", {3, 3, 1, c_out});
+ w.tensor(q + "pw2.weight", {1, 1, c_out, c_out});
+ w.tensor(q + "pw2.bias", {c_out});
+ bn(q + "bn2", c_out);
+ if (sc) {
+ w.tensor(q + "sc.weight", {1, 1, c_in, c_out});
+ bn(q + "sc.bn", c_out);
+ }
+ };
+ w.tensor("a.spk.fe.head.conv.weight", {3, 3, 1, 32});
+ w.tensor("a.spk.fe.head.conv.bias", {32});
+ bn("a.spk.fe.head.bn", 32);
+ // cnn depth, stride f, stride t of each block, see mect_b2() in zonos3-spkenc.cpp
+ struct blk { int cnn, s_f, s_t; };
+ const std::vector<std::vector<blk>> stages = {
+ { {3, 1, 1}, {3, 1, 1} },
+ { {3, 2, 1}, {3, 1, 2}, {3, 1, 2}, {3, 1, 2} },
+ { {3, 2, 1}, {3, 1, 2}, {3, 1, 2}, {3, 1, 2}, {3, 1, 2} },
+ { {3, 2, 1}, {2, 1, 2}, {2, 1, 2} },
+ };
+ int64_t c = 32;
+ for (size_t s = 0; s < stages.size(); s++) {
+ for (size_t k = 0; k < stages[s].size(); k++) {
+ const auto & b = stages[s][k];
+ const std::string p = fmt("a.spk.fe.b%zu.%zu.", s + 1, k);
+ // the first block expands the channels, then reduces them back
+ const bool expand = s == 0 && k == 0;
+ const int64_t c_out = expand ? 2 * c : c * b.s_f;
+ for (int r = 0; r < b.cnn; r++) {
+ const bool first = r == 0;
+ res(p + fmt("cnn.%d.", r), first ? c : c_out, c_out, first && (c_out != c || b.s_t > 1));
+ }
+ if (expand) {
+ w.tensor(p + "reduce.weight", {1, 1, c_out, c});
+ w.tensor(p + "reduce.bias", {c});
+ bn(p + "reduce.bn", c);
+ } else {
+ c = c_out;
+ }
+ w.tensor(p + "rproj.weight", {n_feat, n_hid});
+ w.tensor(p + "rproj.bias", {n_hid});
+ w.norm(p + "rproj.ln.weight", n_hid);
+ w.tensor(p + "rproj.ln.bias", {n_hid});
+ w.tensor(p + "pos.dw.weight", {113, n_hid});
+ w.tensor(p + "pos.dw.bias", {n_hid});
+ w.norm(p + "pos.bn.scale", n_hid);
+ w.tensor(p + "pos.bn.shift", {n_hid});
+ w.tensor(p + "pos.pw.weight", {n_hid, n_hid});
+ w.tensor(p + "pos.pw.bias", {n_hid});
+ for (const char * x : {"q", "k", "v", "o"}) {
+ w.tensor(p + fmt("attn.%s.weight", x), {n_hid, n_hid});
+ w.tensor(p + fmt("attn.%s.bias", x), {n_hid});
+ }
+ w.norm(p + "ln1.weight", n_hid);
+ w.tensor(p + "ln1.bias", {n_hid});
+ w.tensor(p + "moe.gate.weight", {n_hid, 4});
+ w.tensor(p + "moe.experts.weight", {n_hid, 4 * n_hid});
+ w.tensor(p + "ffn_out.weight", {n_hid, n_hid});
+ w.tensor(p + "ffn_out.bias", {n_hid});
+ w.norm(p + "ln2.weight", n_hid);
+ w.tensor(p + "ln2.bias", {n_hid});
+ w.tensor(p + "eproj.weight", {n_hid, n_feat});
+ w.tensor(p + "eproj.bias", {n_feat});
+ }
+ }
+ w.tensor("a.spk.fe.dense_w", {n_feat, 4});
+ w.tensor("a.spk.pool.l1.weight", {n_feat, 32});
+ w.tensor("a.spk.pool.l1.bias", {32});
+ w.tensor("a.spk.pool.l2.weight", {32, n_feat});
+ w.tensor("a.spk.pool.l2.bias", {n_feat});
+ bn("a.spk.bn", 2 * n_feat);
+ w.tensor("a.spk.linear.weight", {2 * n_feat, 192});
+ w.tensor("a.spk.proj.weight", {192, n_proj});
+ w.tensor("a.spk.proj.bias", {n_proj});
+}
+
+// fish_s2: 4 codebooks over a codec of width 64, the tables are shared by the gen model and the speaker encoder
+static const int64_t g6_fish_n_cb = 4;
+static const int64_t g6_fish_n_vocab = 32;
+static const int64_t g6_fish_dim = 64;
+
+static void g6_fish_tables(mmproj_writer & w, int64_t n_embd) {
+ const int64_t n_cb = g6_fish_n_cb;
+ w.tensor(fmt(TN_A_GEN_WAV_QUANT_FIRST_CB, "weight"), {g6_fish_dim, g6_fish_n_vocab});
+ w.tensor(fmt(TN_A_GEN_WAV_QUANT_REST_CB, "weight"), {g6_fish_dim, 16, n_cb - 1});
+ w.tensor(fmt(TN_A_GEN_CODE_EMBD, "weight"), {n_embd, g6_fish_n_vocab, n_cb});
+ w.tensor(fmt(TN_A_GEN_CODE_OUT_EMBD, "weight"), {n_embd, g6_fish_n_vocab});
+}
+
+// windowed transformer layer of the fish codec: 16 heads of 32
+static void g6_fish_tfm_layer(mmproj_writer & w, const char * prefix, int il, int64_t dim) {
+ const int64_t n_qkv = 16 * 32;
+ w.norm(fmt(TN_LN_1, prefix, il, "weight"), dim);
+ w.tensor(fmt(TN_ATTN_Q, prefix, il, "weight"), {dim, n_qkv});
+ w.tensor(fmt(TN_ATTN_K, prefix, il, "weight"), {dim, n_qkv});
+ w.tensor(fmt(TN_ATTN_V, prefix, il, "weight"), {dim, n_qkv});
+ w.tensor(fmt(TN_ATTN_OUTPUT, prefix, il, "weight"), {n_qkv, dim});
+ w.tensor(fmt(TN_LS_1, prefix, il, "weight"), {dim});
+ w.norm(fmt(TN_LN_2, prefix, il, "weight"), dim);
+ w.tensor(fmt(TN_FFN_GATE, prefix, il, "weight"), {dim, 2 * dim});
+ w.tensor(fmt(TN_FFN_UP, prefix, il, "weight"), {dim, 2 * dim});
+ w.tensor(fmt(TN_FFN_DOWN, prefix, il, "weight"), {2 * dim, dim});
+ w.tensor(fmt(TN_LS_2, prefix, il, "weight"), {dim});
+}
+
+// DAC residual unit of the voxcpm2 AudioVAE: depthwise dilated conv, then k = 1
+static void g6_dac_res(mmproj_writer & w, const std::string & q, int64_t c) {
+ w.norm(q + ".snake1.alpha", c);
+ w.norm(q + ".snake1.beta", c);
+ w.tensor(q + ".conv1.weight", {7, 1, c});
+ w.tensor(q + ".conv1.bias", {c});
+ w.norm(q + ".snake2.alpha", c);
+ w.norm(q + ".snake2.beta", c);
+ w.tensor(q + ".conv2.weight", {1, c, c});
+ w.tensor(q + ".conv2.bias", {c});
+}
+
+// voxcpm2: LocEnc + LocDiT (heads of 128), FSQ, stop head, residual LM (granite, a.gen.res.*), AudioVAE decoder
+static void g6_voxcpm2_gen(mmproj_writer & w, const enc_hparams & hp0, bool mixed) {
+ const int64_t n_text = hp0.n_proj;
+ const int64_t n_lat = 64; // feat_dim, fixed
+ const int64_t hd = 128;
+ enc_hparams hp = hp0;
+ hp.n_embd = 64;
+ hp.n_head = 1;
+ hp.n_layer = 1;
+ add_gen_audio_kv(w, PROJECTOR_TYPE_VOXCPM2_GEN, hp, mixed);
+ const int64_t n_embd = hp.n_embd;
+ auto layer = [&](const char * p, int il) {
+ w.norm(fmt(TN_LN_1, p, il, "weight"), n_embd);
+ w.tensor(fmt(TN_ATTN_Q, p, il, "weight"), {n_embd, hd});
+ w.tensor(fmt(TN_ATTN_K, p, il, "weight"), {n_embd, hd});
+ w.tensor(fmt(TN_ATTN_V, p, il, "weight"), {n_embd, hd});
+ w.tensor(fmt(TN_ATTN_OUTPUT, p, il, "weight"), {hd, n_embd});
+ w.norm(fmt(TN_LN_2, p, il, "weight"), n_embd);
+ w.tensor(fmt(TN_FFN_GATE, p, il, "weight"), {n_embd, hp.n_ff});
+ w.tensor(fmt(TN_FFN_UP, p, il, "weight"), {n_embd, hp.n_ff});
+ w.tensor(fmt(TN_FFN_DOWN, p, il, "weight"), {hp.n_ff, n_embd});
+ };
+ layer("a.gen.code", 0);
+ layer("a.gen.enc", 0);
+ w.norm(fmt(TN_LN_POST, "a.gen.code", "weight"), n_embd);
+ w.norm("a.gen.rope_factors", hd / 2);
+ w.tensor("a.gen.enc.special_token", {n_embd});
+ w.tensor("a.gen.enc.in_proj.weight", {n_lat, n_embd});
+ w.tensor("a.gen.enc.in_proj.bias", {n_embd});
+ w.norm("a.gen.enc.post_ln.weight", n_embd);
+ w.tensor("a.gen.enc_to_lm.weight", {n_embd, n_text});
+ w.tensor("a.gen.enc_to_lm.bias", {n_text});
+ w.tensor("a.gen.dit.in_proj.weight", {n_lat, n_embd});
+ w.tensor("a.gen.dit.in_proj.bias", {n_embd});
+ w.tensor("a.gen.dit.cond_proj.weight", {n_lat, n_embd});
+ w.tensor("a.gen.dit.cond_proj.bias", {n_embd});
+ w.tensor("a.gen.dit.out_proj.weight", {n_embd, n_lat});
+ w.tensor("a.gen.dit.out_proj.bias", {n_lat});
+ w.tensor("a.gen.dit.time_mlp.0.weight", {n_embd, 2 * n_embd});
+ w.tensor("a.gen.dit.time_mlp.0.bias", {2 * n_embd});
+ w.tensor("a.gen.dit.time_mlp.1.weight", {2 * n_embd, n_embd});
+ w.tensor("a.gen.dit.time_mlp.1.bias", {n_embd});
+ w.tensor("a.gen.lm_to_dit.weight", {n_text, n_embd});
+ w.tensor("a.gen.lm_to_dit.bias", {n_embd});
+ w.tensor("a.gen.res_to_dit.weight", {n_text, n_embd});
+ w.tensor("a.gen.res_to_dit.bias", {n_embd});
+ w.tensor("a.gen.fsq.in.weight", {n_text, 16});
+ w.tensor("a.gen.fsq.in.bias", {16});
+ w.tensor("a.gen.fsq.out.weight", {16, n_text});
+ w.tensor("a.gen.fsq.out.bias", {n_text});
+ w.tensor("a.gen.fusion.weight", {2 * n_text, n_text});
+ w.tensor("a.gen.fusion.bias", {n_text});
+ w.tensor("a.gen.stop_proj.weight", {n_text, 32});
+ w.tensor("a.gen.stop_proj.bias", {32});
+ w.tensor("a.gen.stop_head.weight", {32, 2});
+ // residual LM: libllama names, n_embd = n_text, one head of 128
+ for (int il = 0; il < 1; il++) {
+ const std::string p = fmt("a.gen.res.blk.%d.", il);
+ w.norm(p + "attn_norm.weight", n_text);
+ w.tensor(p + "attn_q.weight", {n_text, hd});
+ w.tensor(p + "attn_k.weight", {n_text, hd});
+ w.tensor(p + "attn_v.weight", {n_text, hd});
+ w.tensor(p + "attn_output.weight", {hd, n_text});
+ w.norm(p + "ffn_norm.weight", n_text);
+ w.tensor(p + "ffn_gate.weight", {n_text, 2 * n_text});
+ w.tensor(p + "ffn_up.weight", {n_text, 2 * n_text});
+ w.tensor(p + "ffn_down.weight", {2 * n_text, n_text});
+ }
+ w.norm("a.gen.res.output_norm.weight", n_text);
+ // AudioVAE decoder: strides 8, 8, 5, 6 = 1920 samples per latent
+ const std::string p = "a.gen.vae";
+ const int strides[4] = { 8, 8, 5, 6 };
+ const int64_t ch[5] = { 32, 16, 16, 8, 8 };
+ w.tensor(p + ".conv_in_dw.weight", {7, 1, n_lat});
+ w.tensor(p + ".conv_in_dw.bias", {n_lat});
+ w.tensor(p + ".conv_in.weight", {1, n_lat, ch[0]});
+ w.tensor(p + ".conv_in.bias", {ch[0]});
+ for (int b = 0; b < 4; b++) {
+ const std::string q = fmt("%s.blk.%d", p.c_str(), b);
+ w.norm(q + ".sr_scale", ch[b]);
+ w.tensor(q + ".sr_bias", {ch[b]});
+ w.norm(q + ".snake.alpha", ch[b]);
+ w.norm(q + ".snake.beta", ch[b]);
+ w.tensor(q + ".up.weight", {2 * strides[b], ch[b + 1], ch[b]});
+ w.tensor(q + ".up.bias", {ch[b + 1]});
+ for (int r = 0; r < 3; r++) {
+ g6_dac_res(w, fmt("%s.res.%d", q.c_str(), r), ch[b + 1]);
+ }
+ }
+ w.norm(p + ".post_snake.alpha", ch[4]);
+ w.norm(p + ".post_snake.beta", ch[4]);
+ w.tensor(p + ".conv_out.weight", {7, ch[4], 1});
+ w.tensor(p + ".conv_out.bias", {1});
+}
+
+static bool g6_voxcpm2_run(mtmd_context * ctx, std::vector<float> & out) {
+ auto st = g6_gen_state(ctx);
+ if (!st) {
+ return false;
+ }
+ const int n_text = 128;
+ const int n_frame = 64 * 4;
+ mtmd_gen_out o{};
+ auto step = [&](int32_t code0, int n_rows, const float * x, const std::string & key) {
+ std::vector<float> h = g6_normal((size_t) n_rows * n_text, key);
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.type = MTMD_GEN_PROCESS_TYPE_GEN_CODE;
+ inp.code0 = code0;
+ inp.embd = h.data();
+ inp.feats = x;
+ inp.n_feats = x ? (size_t) n_rows * n_text : 0;
+ inp.n_codes = (size_t) n_rows;
+ inp.temp = 0.0f; // no noise
+ o = {};
+ return mtmd_gen_audio_process(ctx, st.get(), &inp, &o) == 0;
+ };
+ // prompt: 3 text rows, then 2 audio rows
+ std::vector<float> x_prompt = g6_normal(2 * n_text, "voxcpm2.x");
+ if (!step(-1, 3, nullptr, "voxcpm2.h0") || !step(-1, 2, x_prompt.data(), "voxcpm2.h1")) {
+ return false;
+ }
+ // frames: the first one from a text row, then the LocEnc row of the previous frame as input row
+ std::vector<float> latents;
+ std::vector<float> x;
+ for (int f = 0; f < 3; f++) {
+ if (!step(0, 1, x.empty() ? nullptr : x.data(), fmt("voxcpm2.f%d", f)) || o.n_feats != (size_t) n_frame || !o.embd) {
+ return false;
+ }
+ out.insert(out.end(), o.feats, o.feats + o.n_feats);
+ out.insert(out.end(), o.embd, o.embd + n_text);
+ latents.insert(latents.end(), o.feats, o.feats + o.n_feats);
+ x.assign(o.embd, o.embd + n_text);
+ }
+ // AudioVAE: 2 frames, then 1, the decoder keeps its state across calls
+ for (int i = 0; i < 2; i++) {
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.type = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
+ inp.feats = latents.data() + (i == 0 ? 0 : 2 * n_frame);
+ inp.n_feats = (size_t) (i == 0 ? 2 : 1) * n_frame;
+ o = {};
+ if (mtmd_gen_audio_process(ctx, st.get(), &inp, &o) != 0 || o.n_samples == 0) {
+ return false;
+ }
+ out.insert(out.end(), o.audio, o.audio + o.n_samples);
+ }
+ return true;
+}
+
+static llama_model_ptr make_text_model(uint32_t n_embd, bool mrope);
+
+// snake VAE decoder (a.gen.vae.*), one block per stride
+static void g6_snake_vae(mmproj_writer & w, int64_t n_latent, int64_t n_out, const std::vector<int> & strides) {
+ const std::string p = "a.gen.vae";
+ const int64_t ch[5] = { 32, 16, 16, 8, 8 };
+ const int n_blk = (int) strides.size();
+ auto snake = [&](const std::string & q, int64_t c) {
+ w.norm(q + ".alpha", c);
+ w.norm(q + ".beta", c);
+ };
+ w.tensor(p + ".conv_in.weight", {7, n_latent, ch[0]});
+ w.tensor(p + ".conv_in.bias", {ch[0]});
+ for (int b = 0; b < n_blk; b++) {
+ const std::string q = fmt("%s.blk.%d", p.c_str(), b);
+ snake(q + ".snake", ch[b]);
+ w.tensor(q + ".up.weight", {2 * strides[b], ch[b + 1], ch[b]});
+ w.tensor(q + ".up.bias", {ch[b + 1]});
+ for (int r = 0; r < 3; r++) {
+ const std::string rq = fmt("%s.res.%d", q.c_str(), r);
+ snake(rq + ".snake1", ch[b + 1]);
+ w.tensor(rq + ".conv1.weight", {7, ch[b + 1], ch[b + 1]});
+ w.tensor(rq + ".conv1.bias", {ch[b + 1]});
+ snake(rq + ".snake2", ch[b + 1]);
+ w.tensor(rq + ".conv2.weight", {1, ch[b + 1], ch[b + 1]});
+ w.tensor(rq + ".conv2.bias", {ch[b + 1]});
+ }
+ }
+ snake(p + ".post_snake", ch[n_blk]);
+ w.tensor(p + ".conv_out.weight", {7, ch[n_blk], n_out});
+}
+
+// backbone keys/values of a few prompt tokens, from a text model with the same KV layout as the stage
+static std::vector<uint8_t> g6_backbone_state(uint32_t n_embd, int n_past) {
+ llama_model_ptr model = make_text_model(n_embd, false);
+ llama_context_params cparams = llama_context_default_params();
+ cparams.n_ctx = 64;
+ cparams.n_batch = 64;
+ cparams.n_threads = 4;
+ cparams.no_perf = true;
+ llama_context_ptr lctx(llama_init_from_model(model.get(), cparams));
+ if (!lctx) {
+ return {};
+ }
+ llama_batch_ext_ptr batch(llama_batch_ext_init(lctx.get()));
+ for (int i = 0; i < n_past; i++) {
+ const int32_t idx = llama_batch_ext_add_token(batch.get(), 0, 1 + 7 * i % 60);
+ const llama_pos pos = i;
+ if (idx < 0 || !llama_batch_ext_set_pos(batch.get(), idx, &pos)) {
+ return {};
+ }
+ }
+ if (llama_process(lctx.get(), LLAMA_PROCESS_TYPE_DECODE, batch.get()) != 0) {
+ return {};
+ }
+ std::vector<uint8_t> state(llama_state_seq_get_size(lctx.get(), 0));
+ state.resize(llama_state_seq_get_data(lctx.get(), state.data(), state.size(), 0));
+ return state;
+}
+
+// a tensor with given values, for data read on the host (ids, voices)
+static void g6_tensor_data(mmproj_writer & w, const std::string & name, const std::vector<int64_t> & ne, const std::vector<float> & data) {
+ ggml_init_params params = {
+ /*.mem_size =*/ ggml_tensor_overhead() + data.size() * sizeof(float),
+ /*.mem_buffer =*/ nullptr,
+ /*.no_alloc =*/ false,
+ };
+ ggml_context * ctx = ggml_init(params);
+ w.ctxs.emplace_back(ctx);
+ int64_t dims[4] = {1, 1, 1, 1};
+ for (size_t i = 0; i < ne.size(); i++) {
+ dims[i] = ne[i];
+ }
+ ggml_tensor * t = ggml_new_tensor(ctx, GGML_TYPE_F32, (int) ne.size(), dims);
+ GGML_ASSERT((size_t) ggml_nelements(t) == data.size());
+ ggml_set_name(t, name.c_str());
+ memcpy(t->data, data.data(), ggml_nbytes(t));
+ gguf_add_tensor(w.gguf.get(), t);
+}
+
+// chatterbox s3gen: flow encoder (512 wide, 8 heads of 64), cfm estimator, hift vocoder, s3 tokenizer (20 heads of 64)
+// n_codes: speech tokens; the reference path needs all 3^8 fsq codes
+static void g6_chatterbox_gen(mmproj_writer & w, const enc_hparams & hp, int64_t n_codes, int n_s3tok_blk, bool meanflow, bool mixed) {
+ add_gen_audio_kv(w, PROJECTOR_TYPE_CHATTERBOX, hp, mixed);
+ const int64_t d = 512;
+ auto lin = [&](const std::string & p, int64_t n_in, int64_t n_out, bool bias = true) {
+ w.tensor(p + ".weight", {n_in, n_out});
+ if (bias) {
+ w.tensor(p + ".bias", {n_out});
+ }
+ };
+ auto conv = [&](const std::string & p, int64_t k, int64_t n_in, int64_t n_out, bool bias = true) {
+ w.tensor(p + ".weight", {k, n_in, n_out});
+ if (bias) {
+ w.tensor(p + ".bias", {n_out});
+ }
+ };
+ auto norm = [&](const std::string & p, int64_t n) {
+ w.norm(p + ".weight", n);
+ w.tensor(p + ".bias", {n});
+ };
+ auto enc_layer = [&](const std::string & p) {
+ norm(p + ".norm_mha", d);
+ lin(p + ".self_attn.linear_q", d, d);
+ lin(p + ".self_attn.linear_k", d, d);
+ lin(p + ".self_attn.linear_v", d, d);
+ lin(p + ".self_attn.linear_pos", d, d, false);
+ w.tensor(p + ".self_attn.pos_bias_u", {64, 8});
+ w.tensor(p + ".self_attn.pos_bias_v", {64, 8});
+ lin(p + ".self_attn.linear_out", d, d);
+ norm(p + ".norm_ff", d);
+ lin(p + ".feed_forward.w_1", d, 64);
+ lin(p + ".feed_forward.w_2", 64, d);
+ };
+
+ // flow encoder
+ w.tensor("a.gen.flow.input_embedding.weight", {d, n_codes});
+ lin("a.gen.flow.spk_embed_affine_layer", 192, 80);
+ lin("a.gen.fenc.embed.out.0", d, d);
+ norm("a.gen.fenc.embed.out.1", d);
+ conv("a.gen.fenc.pre_lookahead_layer.conv1", 4, d, 32);
+ conv("a.gen.fenc.pre_lookahead_layer.conv2", 3, 32, d);
+ enc_layer("a.gen.fenc.encoders.0");
+ conv("a.gen.fenc.up_layer.conv", 5, d, 32);
+ lin("a.gen.fenc.up_embed.out.0", 32, d);
+ norm("a.gen.fenc.up_embed.out.1", d);
+ enc_layer("a.gen.fenc.up_encoders.0");
+ norm("a.gen.fenc.after_norm", d);
+ lin("a.gen.flow.encoder_proj", d, 80);
+
+ // cfm estimator: down, mid, up with skip; the input is [noise, mu, spks, cond] = 4 x 80 channels
+ const int64_t c = 64;
+ const int64_t td = 64; // time embedding
+ lin("a.gen.est.time_mlp.linear_1", 320, 64);
+ lin("a.gen.est.time_mlp.linear_2", 64, td);
+ if (meanflow) {
+ lin("a.gen.est.time_embed_mixer", 2 * td, td, false);
+ }
+ auto causal = [&](const std::string & p, int64_t n_in) {
+ conv(p + ".block.0", 3, n_in, c);
+ norm(p + ".block.2", c);
+ };
+ auto resnet = [&](const std::string & p, int64_t n_in) {
+ causal(p + ".block1", n_in);
+ causal(p + ".block2", c);
+ lin(p + ".mlp.1", td, c);
+ conv(p + ".res_conv", 1, n_in, c);
+ };
+ auto tfm = [&](const std::string & p) {
+ norm(p + ".norm1", c);
+ lin(p + ".attn1.to_q", c, d, false);
+ lin(p + ".attn1.to_k", c, d, false);
+ lin(p + ".attn1.to_v", c, d, false);
+ lin(p + ".attn1.to_out.0", d, c);
+ norm(p + ".norm3", c);
+ lin(p + ".ff.net.0.proj", c, 2 * c);
+ lin(p + ".ff.net.2", 2 * c, c);
+ };
+ resnet("a.gen.est.down_blocks.0.0", 320);
+ tfm("a.gen.est.down_blocks.0.1.0");
+ conv("a.gen.est.down_blocks.0.2", 3, c, c);
+ resnet("a.gen.est.mid_blocks.0.0", c);
+ tfm("a.gen.est.mid_blocks.0.1.0");
+ resnet("a.gen.est.up_blocks.0.0", 2 * c);
+ tfm("a.gen.est.up_blocks.0.1.0");
+ conv("a.gen.est.up_blocks.0.2", 3, c, c);
+ causal("a.gen.est.final_block", c);
+ conv("a.gen.est.final_proj", 1, c, 80);
+
+ // hift: upsample x8, x5, x3 (120 stft frames per mel frame), the source stft is downsampled to each stage
+ const int64_t ups_k[3] = { 16, 11, 7 };
+ const int64_t down_k[3] = { 30, 6, 1 };
+ const int64_t ch[4] = { 32, 16, 8, 4 };
+ auto hres = [&](const std::string & p, int64_t n) {
+ for (int j = 0; j < 3; j++) {
+ w.norm(fmt("%s.activations1.%d.alpha", p.c_str(), j), n);
+ w.norm(fmt("%s.activations2.%d.alpha", p.c_str(), j), n);
+ conv(fmt("%s.convs1.%d", p.c_str(), j), 3, n, n);
+ conv(fmt("%s.convs2.%d", p.c_str(), j), 3, n, n);
+ }
+ };
+ conv("a.gen.hift.conv_pre", 7, 80, ch[0]);
+ for (int i = 0; i < 3; i++) {
+ w.tensor(fmt("a.gen.hift.ups.%d.weight", i), {ups_k[i], ch[i + 1], ch[i]});
+ w.tensor(fmt("a.gen.hift.ups.%d.bias", i), {ch[i + 1]});
+ conv(fmt("a.gen.hift.source_downs.%d", i), down_k[i], 18, ch[i + 1]);
+ hres(fmt("a.gen.hift.source_resblocks.%d", i), ch[i + 1]);
+ for (int j = 0; j < 3; j++) {
+ hres(fmt("a.gen.hift.resblocks.%d", 3 * i + j), ch[i + 1]);
+ }
+ }
+ conv("a.gen.hift.conv_post", 7, ch[3], 18);
+ conv("a.gen.hift.f0_predictor.condnet.0", 3, 80, 16);
+ conv("a.gen.hift.f0_predictor.condnet.2", 3, 16, 16);
+ lin("a.gen.hift.f0_predictor.classifier", 16, 1);
+ w.tensor("a.gen.hift.m_source.l_linear.weight", {9});
+ w.tensor("a.gen.hift.m_source.l_linear.bias", {1});
+
+ // s3 tokenizer, 1280 wide
+ const int64_t ds = 1280;
+ conv("a.s3tok.encoder.conv1", 3, 128, 32);
+ conv("a.s3tok.encoder.conv2", 3, 32, ds);
+ for (int i = 0; i < n_s3tok_blk; i++) {
+ const std::string p = fmt("a.s3tok.encoder.blocks.%d", i);
+ norm(p + ".attn_ln", ds);
+ lin(p + ".attn.query", ds, ds);
+ lin(p + ".attn.key", ds, ds, false);
+ lin(p + ".attn.value", ds, ds);
+ w.tensor(p + ".attn.fsmn_block.weight", {5, 1, ds});
+ lin(p + ".attn.out", ds, ds);
+ norm(p + ".mlp_ln", ds);
+ lin(p + ".mlp.0", ds, 32);
+ lin(p + ".mlp.2", 32, ds);
+ }
+ lin("a.s3tok.quantizer._codebook.project_down", ds, 8);
+
+ // talker speech table, its width is the backbone width
+ w.tensor(fmt(TN_A_GEN_CODE_OUT_EMBD, "weight"), {hp.n_proj, n_codes});
+}
+
+static bool make_mmproj_g6(projector_type proj, mmproj_writer & w, test_model & tm) {
+ enc_hparams hp;
+ tm.n_embd_out = hp.n_proj;
+ switch (proj) {
+ case PROJECTOR_TYPE_ZONOS3_SPKENC:
+ {
+ enc_hparams ha = hp;
+ ha.n_embd = 192;
+ ha.n_layer = 0;
+ add_audio_kv(w, proj, ha, 80);
+ g6_zonos3_spkenc(w, hp.n_proj);
+ tm.audio = true;
+ } break;
+ case PROJECTOR_TYPE_ZONOS3_GEN:
+ {
+ // codebook heads + ZAC codec decoder, 5 stages upsampled x2 between them
+ const int64_t n_vocab = 16; // per codebook, the codec tables have 4096 rows
+ const int64_t n_cb = 10;
+ const int64_t n_sem = 16;
+ const int64_t n_lat = 16;
+ const int64_t d = 64; // one head of 64
+ hp.n_embd = hp.n_proj;
+ hp.n_layer = 0;
+ add_gen_audio_kv(w, proj, hp);
+ w.tensor(fmt(TN_A_GEN_CODE_HEAD, "weight"), {hp.n_proj, n_vocab * n_cb});
+ w.tensor(fmt(TN_A_GEN_CODE_OUT_EMBD, "weight"), {hp.n_proj, n_vocab * n_cb});
+ auto convnext = [&](const std::string & q, int64_t c) {
+ w.tensor(q + ".dw.weight", {7, c});
+ w.tensor(q + ".dw.bias", {c});
+ w.norm(q + ".norm.weight", c);
+ w.tensor(q + ".norm.bias", {c});
+ w.tensor(q + ".pw1.weight", {c, 2 * c});
+ w.tensor(q + ".pw1.bias", {2 * c});
+ w.tensor(q + ".pw2.weight", {2 * c, c});
+ w.tensor(q + ".pw2.bias", {c});
+ };
+ const std::string p = "a.gen.wav";
+ w.tensor(p + ".sem.table", {n_sem, 4096});
+ w.tensor(p + ".sem.bias", {n_sem});
+ convnext(p + ".sem.0", n_sem);
+ w.tensor(p + ".sem.out.weight", {n_sem, n_lat});
+ w.tensor(p + ".sem.out.bias", {n_lat});
+ w.tensor(p + ".res.table", {n_lat, 4096 * (n_cb - 1)});
+ w.tensor(p + ".res.bias", {n_lat, n_cb - 1});
+ int64_t c = n_lat;
+ for (int s = 0; s < 5; s++) {
+ const std::string q = fmt("%s.stage.%d", p.c_str(), s);
+ w.tensor(q + ".in.weight", {c, d});
+ const std::string b = q + ".blk.0";
+ w.norm(b + ".norm1.weight", d);
+ w.tensor(b + ".norm1.bias", {d});
+ w.tensor(b + ".qkv.weight", {d, 3 * d});
+ w.tensor(b + ".wo.weight", {d, d});
+ w.norm(b + ".attn_scale", d);
+ w.norm(b + ".norm2.weight", d);
+ w.tensor(b + ".norm2.bias", {d});
+ w.tensor(b + ".ffn1.weight", {d, 2 * d});
+ w.tensor(b + ".ffn2.weight", {2 * d, d});
+ w.norm(b + ".ffn_scale", d);
+ // the last stage has no output projection
+ if (s < 4) {
+ w.tensor(q + ".out.weight", {d, d});
+ c = d / 2;
+ } else {
+ c = d;
+ }
+ }
+ convnext(p + ".head.0", c);
+ w.norm(p + ".head.norm.weight", c);
+ w.tensor(p + ".head.norm.bias", {c});
+ w.tensor(p + ".head.out.weight", {c, 736 + 2208 + 4});
+ w.tensor(p + ".head.out.bias", {736 + 2208 + 4});
+ w.tensor(p + ".mixer.weight", {5, 2});
+ w.tensor(p + ".resample.weight", {738, 735});
+ tm.gen = [](mtmd_context * ctx, std::vector<float> & out) {
+ auto st = g6_gen_state(ctx);
+ if (!st) {
+ return false;
+ }
+ const int n_embd = 128;
+ std::vector<float> h = g6_normal(n_embd, "zonos3.h");
+ for (int step = 0; step < 3; step++) {
+ // codebook logits, then the backbone row of fixed codes (sampled codes could differ across backends)
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.type = MTMD_GEN_PROCESS_TYPE_GEN_CODE;
+ inp.embd = h.data();
+ mtmd_gen_out o{};
+ if (mtmd_gen_audio_process(ctx, st.get(), &inp, &o) != 0 || o.n_feats != (size_t) (n_vocab * n_cb)) {
+ return false;
+ }
+ out.insert(out.end(), o.feats, o.feats + o.n_feats);
+ std::vector<int32_t> codes = g6_codes(n_cb, (int32_t) n_vocab, 100 + step);
+ inp = mtmd_gen_inp_default(ctx);
+ inp.type = MTMD_GEN_PROCESS_TYPE_GEN_CODE;
+ inp.codes = codes.data();
+ inp.n_codes = codes.size();
+ if (mtmd_gen_audio_process(ctx, st.get(), &inp, &o) != 0 || !o.embd) {
+ return false;
+ }
+ out.insert(out.end(), o.embd, o.embd + n_embd);
+ h.assign(o.embd, o.embd + n_embd);
+ }
+ // codec: 4 frames, then 2 frames with residual codes not known yet (-1), then the flush
+ std::vector<int32_t> c1 = g6_codes(4 * n_cb, 4096, 1);
+ std::vector<int32_t> c2 = g6_codes(2 * n_cb, 4096, 2);
+ for (int cb = 5; cb < n_cb; cb++) {
+ c2[n_cb + cb] = -1;
+ }
+ for (auto * codes : { &c1, &c2, (std::vector<int32_t> *) nullptr }) {
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.type = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
+ inp.codes = codes ? codes->data() : nullptr;
+ inp.n_codes = codes ? codes->size() : 0;
+ mtmd_gen_out o{};
+ if (mtmd_gen_audio_process(ctx, st.get(), &inp, &o) != 0) {
+ return false;
+ }
+ out.insert(out.end(), o.audio, o.audio + o.n_samples);
+ }
+ return true;
+ };
+ } break;
+ case PROJECTOR_TYPE_FISH_S2_GEN:
+ {
+ // fast AR over the backbone width, then the Fish DAC decoder (8 tfm layers, 2 upsample, 4 DAC blocks are fixed)
+ const int64_t n_embd = hp.n_proj;
+ const int64_t dim = g6_fish_dim;
+ hp.n_embd = n_embd;
+ add_gen_audio_kv(w, proj, hp);
+ add_vit(w, "a.gen.code", hp.n_layer, n_embd, hp.n_ff, [] {
+ vit_opts o;
+ o.ln_bias = false;
+ o.qkv_bias = false;
+ o.o_bias = false;
+ o.ffn_gate = true;
+ o.ffn_bias = false;
+ o.post_ln = false;
+ return o;
+ }());
+ w.tensor(fmt(TN_A_GEN_CODE_TOK_EMBD, "weight"), {n_embd, g6_fish_n_vocab});
+ w.tensor(fmt(TN_A_GEN_CODE_HEAD, "weight"), {n_embd, g6_fish_n_vocab});
+ w.norm(fmt(TN_A_GEN_CODE_NORM, "weight"), n_embd);
+ g6_fish_tables(w, n_embd);
+ for (int il = 0; il < 8; il++) {
+ g6_fish_tfm_layer(w, "a.gen.wav.tfm", il, dim);
+ }
+ w.norm(fmt(TN_A_GEN_WAV_TFM_OUT_NORM, "weight"), dim);
+ for (int il = 0; il < 2; il++) {
+ w.tensor(fmt(TN_A_GEN_WAV_UP_CONV, il, "weight"), {2, dim, dim});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_CONV, il, "bias"), {dim});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_DWCONV, il, "weight"), {7, 1, dim});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_DWCONV, il, "bias"), {dim});
+ w.norm(fmt(TN_A_GEN_WAV_UP_NORM, il, "weight"), dim);
+ w.tensor(fmt(TN_A_GEN_WAV_UP_NORM, il, "bias"), {dim});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_PW1, il, "weight"), {dim, 2 * dim});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_PW1, il, "bias"), {2 * dim});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_PW2, il, "weight"), {2 * dim, dim});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_PW2, il, "bias"), {dim});
+ w.tensor(fmt(TN_A_GEN_WAV_UP_GAMMA, il), {dim});
+ }
+ // DAC: strides 8, 8, 4, 2 (x4 upsample before), 2048 samples per frame
+ const int strides[4] = { 8, 8, 4, 2 };
+ const int64_t ch[5] = { 32, 16, 16, 8, 8 };
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_ENTRY, "weight"), {7, dim, ch[0]});
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_ENTRY, "bias"), {ch[0]});
+ for (int il = 0; il < 4; il++) {
+ const int64_t c = ch[il + 1];
+ w.norm(fmt(TN_A_GEN_WAV_DAC_SNAKE, il, "alpha"), ch[il]);
+ w.norm(fmt(TN_A_GEN_WAV_DAC_SNAKE, il, "beta"), ch[il]);
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_CONV, il, "weight"), {2 * strides[il], c, ch[il]});
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_CONV, il, "bias"), {c});
+ for (int ir = 0; ir < 3; ir++) {
+ w.norm(fmt(TN_A_GEN_WAV_DAC_RES_ACT1, il, ir, "alpha"), c);
+ w.norm(fmt(TN_A_GEN_WAV_DAC_RES_ACT1, il, ir, "beta"), c);
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_RES_CONV1, il, ir, "weight"), {7, c, c});
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_RES_CONV1, il, ir, "bias"), {c});
+ w.norm(fmt(TN_A_GEN_WAV_DAC_RES_ACT2, il, ir, "alpha"), c);
+ w.norm(fmt(TN_A_GEN_WAV_DAC_RES_ACT2, il, ir, "beta"), c);
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_RES_CONV2, il, ir, "weight"), {1, c, c});
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_RES_CONV2, il, ir, "bias"), {c});
+ }
+ }
+ w.norm(fmt(TN_A_GEN_WAV_DAC_POST_SNAKE, "alpha"), ch[4]);
+ w.norm(fmt(TN_A_GEN_WAV_DAC_POST_SNAKE, "beta"), ch[4]);
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_POST_CONV, "weight"), {7, ch[4], 1});
+ w.tensor(fmt(TN_A_GEN_WAV_DAC_POST_CONV, "bias"), {1});
+ tm.gen = [](mtmd_context * ctx, std::vector<float> & out) {
+ auto st = g6_gen_state(ctx);
+ if (!st) {
+ return false;
+ }
+ const int n_embd = 128;
+ const int n_cb = (int) g6_fish_n_cb;
+ std::vector<float> h = g6_normal(n_embd, "fish_s2.h");
+ for (int step = 0; step < 3; step++) {
+ // greedy fast AR: codes of the frame and the next backbone input
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.type = MTMD_GEN_PROCESS_TYPE_GEN_CODE;
+ inp.code0 = 3 + 5 * step;
+ inp.embd = h.data();
+ mtmd_gen_out o{};
+ if (mtmd_gen_audio_process(ctx, st.get(), &inp, &o) != 0 || o.n_codes != (size_t) n_cb || !o.embd) {
+ return false;
+ }
+ out.insert(out.end(), o.embd, o.embd + n_embd);
+ h = g6_normal(n_embd, fmt("fish_s2.h%d", step));
+ }
+ // codec: 3 frames then 2 more, the decoder keeps its state across calls
+ for (int n_frames : { 3, 2 }) {
+ std::vector<int32_t> codes = g6_codes((size_t) n_frames * n_cb, (int32_t) g6_fish_n_vocab, n_frames);
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.type = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
+ inp.codes = codes.data();
+ inp.n_codes = codes.size();
+ mtmd_gen_out o{};
+ if (mtmd_gen_audio_process(ctx, st.get(), &inp, &o) != 0 || o.n_samples == 0) {
+ return false;
+ }
+ out.insert(out.end(), o.audio, o.audio + o.n_samples);
+ }
+ return true;
+ };
+ } break;
+ case PROJECTOR_TYPE_FISH_S2_SPKENC:
+ {
+ // Fish DAC encoder (4 blocks, 4 tfm layers) + quantizer (2 downsample blocks, 8 tfm layers) + VQ
+ // convs are taps-major [stride * IC, OC, n_tap]
+ const int64_t dim = g6_fish_dim;
+ enc_hparams ha = hp;
+ ha.n_embd = dim;
+ ha.n_layer = 12;
+ add_audio_kv(w, proj, ha, 1);
+ const int strides[4] = { 2, 4, 8, 8 };
+ const int64_t ch[5] = { 4, 8, 16, 32, dim };
+ w.tensor(fmt(TN_A_CODEC_ENC_ENTRY, "weight"), {1, ch[0], 7});
+ w.tensor(fmt(TN_A_CODEC_ENC_ENTRY, "bias"), {ch[0]});
+ for (int il = 0; il < 4; il++) {
+ const int64_t c = ch[il];
+ for (int ir = 0; ir < 3; ir++) {
+ w.norm(fmt(TN_A_CODEC_ENC_RES_ACT1, il, ir, "alpha"), c);
+ w.norm(fmt(TN_A_CODEC_ENC_RES_ACT1, il, ir, "beta"), c);
+ w.tensor(fmt(TN_A_CODEC_ENC_RES_CONV1, il, ir, "weight"), {c, c, 7});
+ w.tensor(fmt(TN_A_CODEC_ENC_RES_CONV1, il, ir, "bias"), {c});
+ w.norm(fmt(TN_A_CODEC_ENC_RES_ACT2, il, ir, "alpha"), c);
+ w.norm(fmt(TN_A_CODEC_ENC_RES_ACT2, il, ir, "beta"), c);
+ w.tensor(fmt(TN_A_CODEC_ENC_RES_CONV2, il, ir, "weight"), {c, c, 1});
+ w.tensor(fmt(TN_A_CODEC_ENC_RES_CONV2, il, ir, "bias"), {c});
+ }
+ w.norm(fmt(TN_A_CODEC_ENC_SNAKE, il, "alpha"), c);
+ w.norm(fmt(TN_A_CODEC_ENC_SNAKE, il, "beta"), c);
+ // kernel 2 * stride: 2 taps
+ w.tensor(fmt(TN_A_CODEC_ENC_CONV, il, "weight"), {strides[il] * c, ch[il + 1], 2});
+ w.tensor(fmt(TN_A_CODEC_ENC_CONV, il, "bias"), {ch[il + 1]});
+ }
+ for (int il = 0; il < 12; il++) {
+ g6_fish_tfm_layer(w, "a", il, dim);
+ }
+ w.norm(fmt(TN_LN_POST, "a", "weight"), dim);
+ w.norm(fmt(TN_A_CODEC_ENC_POST_SNAKE, "alpha"), dim);
+ w.norm(fmt(TN_A_CODEC_ENC_POST_SNAKE, "beta"), dim);
+ w.tensor(fmt(TN_A_CODEC_ENC_POST_CONV, "weight"), {dim, dim, 1});
+ w.tensor(fmt(TN_A_CODEC_ENC_POST_CONV, "bias"), {dim});
+ for (int il = 0; il < 2; il++) {
+ w.tensor(fmt(TN_A_CODEC_DOWN_CONV, il, "weight"), {2 * dim, dim, 1});
+ w.tensor(fmt(TN_A_CODEC_DOWN_CONV, il, "bias"), {dim});
+ w.tensor(fmt(TN_A_CODEC_DOWN_DWCONV, il, "weight"), {dim, 7});
+ w.tensor(fmt(TN_A_CODEC_DOWN_DWCONV, il, "bias"), {dim});
+ w.norm(fmt(TN_A_CODEC_DOWN_NORM, il, "weight"), dim);
+ w.tensor(fmt(TN_A_CODEC_DOWN_NORM, il, "bias"), {dim});
+ w.tensor(fmt(TN_A_CODEC_DOWN_PW1, il, "weight"), {dim, 2 * dim});
+ w.tensor(fmt(TN_A_CODEC_DOWN_PW1, il, "bias"), {2 * dim});
+ w.tensor(fmt(TN_A_CODEC_DOWN_PW2, il, "weight"), {2 * dim, dim});
+ w.tensor(fmt(TN_A_CODEC_DOWN_PW2, il, "bias"), {dim});
+ w.tensor(fmt(TN_A_CODEC_DOWN_GAMMA, il), {dim});
+ }
+ w.norm(fmt(TN_A_CODEC_PRE_NORM, "weight"), dim);
+ const int64_t n_vq = 8;
+ w.tensor(fmt(TN_A_CODEC_VQ_FIRST_IN, "weight"), {dim, n_vq});
+ w.tensor(fmt(TN_A_CODEC_VQ_FIRST_IN, "bias"), {n_vq});
+ w.tensor(fmt(TN_A_CODEC_VQ_FIRST_CB, "weight"), {n_vq, g6_fish_n_vocab});
+ w.tensor(fmt(TN_A_CODEC_VQ_REST_IN, "weight"), {dim, n_vq, g6_fish_n_cb - 1});
+ w.tensor(fmt(TN_A_CODEC_VQ_REST_IN, "bias"), {n_vq, g6_fish_n_cb - 1});
+ w.tensor(fmt(TN_A_CODEC_VQ_REST_CB, "weight"), {n_vq, 16, g6_fish_n_cb - 1});
+ g6_fish_tables(w, hp.n_proj);
+ tm.audio = true;
+ tm.todo = "Metal vs CPU: residual VQ codes flip on the 30 s and 45 s clips (NMSE 8.6e-3 and 1.4e-2), the 1 s clip matches; see the fast-math sin TODO in fish-s2-spkenc.cpp";
+ } break;
+ case PROJECTOR_TYPE_VOXCPM2_GEN:
+ {
+ g6_voxcpm2_gen(w, hp, false);
+ tm.gen = g6_voxcpm2_run;
+ } break;
+ case PROJECTOR_TYPE_VOXCPM2_SPKENC:
+ {
+ // AudioVAE encoder, the reference rows come from LocEnc of the gen model
+ g6_voxcpm2_gen(w, hp, true);
+ enc_hparams ha = hp;
+ ha.n_layer = 0;
+ add_audio_kv(w, proj, ha, 1, true);
+ const std::string p = "a.vae.enc";
+ const int strides[4] = { 2, 5, 8, 8 };
+ const int64_t ch[5] = { 4, 8, 8, 16, 16 };
+ w.tensor(p + ".conv_in.weight", {7, 1, ch[0]});
+ w.tensor(p + ".conv_in.bias", {ch[0]});
+ for (int b = 0; b < 4; b++) {
+ const std::string q = fmt("%s.blk.%d", p.c_str(), b);
+ for (int r = 0; r < 3; r++) {
+ g6_dac_res(w, fmt("%s.res.%d", q.c_str(), r), ch[b]);
+ }
+ w.norm(q + ".snake.alpha", ch[b]);
+ w.norm(q + ".snake.beta", ch[b]);
+ w.tensor(q + ".down.weight", {2 * strides[b], ch[b], ch[b + 1]});
+ w.tensor(q + ".down.bias", {ch[b + 1]});
+ }
+ w.tensor(p + ".fc_mu.weight", {3, ch[4], 64});
+ w.tensor(p + ".fc_mu.bias", {64});
+ tm.audio = true;
+ } break;
+ case PROJECTOR_TYPE_YUE2_GEN:
+ {
+ // latent projections + time embedder around the NAR (qwen3 layers, a.gen.nar.*), then the VAE
+ // the NAR reads the backbone keys/values: same layer count and KV rows as the text model (1 layer, 2 heads)
+ const int64_t n_embd = hp.n_proj;
+ const int64_t n_lat = 64;
+ const int64_t d_head = n_embd / hp.n_head;
+ hp.n_embd = n_embd;
+ hp.n_layer = 1;
+ add_gen_audio_kv(w, proj, hp);
+ w.tensor("a.gen.nar.inp.weight", {n_lat, n_embd});
+ w.tensor("a.gen.nar.inp.bias", {n_embd});
+ w.tensor("a.gen.nar.out.weight", {n_embd, n_lat});
+ w.tensor("a.gen.nar.out.bias", {n_lat});
+ w.tensor("a.gen.nar.time.0.weight", {256, n_embd});
+ w.tensor("a.gen.nar.time.0.bias", {n_embd});
+ w.tensor("a.gen.nar.time.2.weight", {n_embd, n_embd});
+ w.tensor("a.gen.nar.time.2.bias", {n_embd});
+ for (int il = 0; il < (int) hp.n_layer; il++) {
+ const std::string p = fmt("a.gen.nar.blk.%d.", il);
+ w.norm(p + "attn_norm.weight", n_embd);
+ w.tensor(p + "attn_q.weight", {n_embd, n_embd});
+ w.tensor(p + "attn_k.weight", {n_embd, n_embd});
+ w.tensor(p + "attn_v.weight", {n_embd, n_embd});
+ w.tensor(p + "attn_output.weight", {n_embd, n_embd});
+ w.norm(p + "attn_q_norm.weight", d_head);
+ w.norm(p + "attn_k_norm.weight", d_head);
+ w.norm(p + "ffn_norm.weight", n_embd);
+ w.tensor(p + "ffn_gate.weight", {n_embd, hp.n_ff});
+ w.tensor(p + "ffn_up.weight", {n_embd, hp.n_ff});
+ w.tensor(p + "ffn_down.weight", {hp.n_ff, n_embd});
+ }
+ w.norm("a.gen.nar.output_norm.weight", n_embd);
+ // 1920 samples per latent
+ g6_snake_vae(w, n_lat, 2, {8, 8, 5, 6});
+ tm.gen = [](mtmd_context * ctx, std::vector<float> & out) {
+ auto st = g6_gen_state(ctx);
+ const int n_past = 6;
+ const std::vector<uint8_t> state = g6_backbone_state(128, n_past);
+ if (!st || state.empty()) {
+ return false;
+ }
+ // flow matching of 4 frames on the backbone keys/values, the noise comes from the seeded state
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.type = MTMD_GEN_PROCESS_TYPE_GEN_CODE;
+ inp.n_codes = 4;
+ inp.backbone_state = state.data();
+ inp.backbone_state_size = state.size();
+ inp.backbone_n_past = n_past;
+ inp.n_steps = 4;
+ mtmd_gen_out o{};
+ if (mtmd_gen_audio_process(ctx, st.get(), &inp, &o) != 0 || o.n_feats != 4 * 64) {
+ return false;
+ }
+ out.insert(out.end(), o.feats, o.feats + o.n_feats);
+ const std::vector<float> latents(o.feats, o.feats + o.n_feats);
+ inp = mtmd_gen_inp_default(ctx);
+ inp.type = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
+ inp.feats = latents.data();
+ inp.n_feats = latents.size();
+ if (mtmd_gen_audio_process(ctx, st.get(), &inp, &o) != 0 || o.n_samples == 0) {
+ return false;
+ }
+ out.insert(out.end(), o.audio, o.audio + o.n_samples);
+ return true;
+ };
+ } break;
+ case PROJECTOR_TYPE_MINIMAX_MUSIC3_GEN:
+ {
+ // depth decoder (generic a.gen.code layers), condition encoder, DiT (heads of 64), DAC vocoder per channel
+ const int64_t n_embd = hp.n_proj;
+ const int64_t n_cb = 3; // residual codebooks
+ const int64_t n_voc = 16;
+ const int64_t n_cond = 32;
+ const int64_t n_in = 2 * 128 + n_cond; // [latent, zeros, condition]
+ const int64_t n_dit = 64;
+ hp.n_embd = n_embd;
+ hp.n_layer = 1;
+ add_gen_audio_kv(w, proj, hp);
+ vit_opts o;
+ o.ln_bias = false;
+ o.qkv_bias = false;
+ o.o_bias = false;
+ o.ffn_gate = true;
+ o.ffn_bias = false;
+ add_vit(w, "a.gen.code", hp.n_layer, n_embd, hp.n_ff, o);
+ w.tensor(fmt(TN_POS_EMBD, "a.gen.code"), {n_embd, n_cb + 1});
+ w.tensor(fmt(TN_A_GEN_CODE_PROJ_IN, "weight"), {n_embd, n_embd});
+ w.tensor(fmt(TN_A_GEN_CODE_EMBD, "weight"), {n_embd, n_voc, n_cb});
+ w.tensor(fmt(TN_A_GEN_CODE_HEAD, "weight"), {n_embd, n_voc, n_cb});
+ w.tensor(fmt(TN_A_GEN_CODE_OUT_EMBD, "weight"), {n_embd, n_voc});
+ w.tensor("a.gen.cond.layer_w", {n_cb + 1});
+ w.tensor("a.gen.cond.proj.weight", {3, n_embd, n_cond});
+ w.tensor("a.gen.cond.proj.bias", {n_cond});
+ w.tensor("a.gen.flow.time_freq", {16});
+ w.tensor("a.gen.flow.time_in.weight", {32, 64});
+ w.tensor("a.gen.flow.time_in.bias", {64});
+ w.tensor("a.gen.flow.time_out.weight", {64, n_dit});
+ w.tensor("a.gen.flow.time_out.bias", {n_dit});
+ w.tensor("a.gen.flow.pre.weight", {n_in, n_in});
+ w.tensor("a.gen.flow.proj_in.weight", {n_in, n_dit});
+ w.tensor("a.gen.flow.proj_out.weight", {n_dit, 128});
+ w.tensor("a.gen.flow.post.weight", {128, 128});
+ add_vit(w, "a.gen.flow", 1, n_dit, 2 * n_dit, [] {
+ vit_opts o;
+ o.ln_bias = true;
+ o.qkv_bias = false;
+ o.o_bias = false;
+ o.ffn_gate = true;
+ o.ffn_bias = true;
+ o.post_ln = false;
+ return o;
+ }());
+ // each channel is a mono stream of 64 latents, 512 samples per latent
+ g6_snake_vae(w, 64, 1, {8, 8, 8});
+ tm.gen = [](mtmd_context * ctx, std::vector<float> & out) {
+ auto st = g6_gen_state(ctx);
+ if (!st) {
+ return false;
+ }
+ const int n_embd = 128;
+ // depth decoder with guidance (cond and uncond rows), greedy
+ std::vector<float> cond_rows;
+ for (int f = 0; f < 5; f++) {
+ std::vector<float> rows = g6_normal(2 * n_embd, fmt("music3.h%d", f));
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.type = MTMD_GEN_PROCESS_TYPE_GEN_CODE;
+ inp.code0 = 1 + 3 * f;
+ inp.feats = rows.data();
+ inp.n_feats = rows.size();
+ inp.temp = 0.0f;
+ mtmd_gen_out o{};
+ if (mtmd_gen_audio_process(ctx, st.get(), &inp, &o) != 0 || o.n_feats != (size_t) n_embd || !o.embd) {
+ return false;
+ }
+ out.insert(out.end(), o.embd, o.embd + n_embd);
+ out.insert(out.end(), o.feats, o.feats + o.n_feats);
+ cond_rows.insert(cond_rows.end(), o.feats, o.feats + o.n_feats);
+ }
+ // two windows of flow matching + vocoder, the noise comes from the seeded state
+ for (int n_rows : { 3, 5 }) {
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.type = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
+ inp.feats = cond_rows.data();
+ inp.n_feats = (size_t) n_rows * n_embd;
+ inp.n_steps = 4;
+ mtmd_gen_out o{};
+ if (mtmd_gen_audio_process(ctx, st.get(), &inp, &o) != 0 || o.n_samples == 0) {
+ return false;
+ }
+ out.insert(out.end(), o.audio, o.audio + o.n_samples);
+ }
+ return true;
+ };
+ } break;
+ case PROJECTOR_TYPE_CHATTERBOX:
+ {
+ // flow decoder + vocoder from a predefined voice, the meanflow variant (2 steps, time embed mixer)
+ const int64_t n_codes = 64;
+ const int n_tok = 4;
+ g6_chatterbox_gen(w, hp, n_codes, 0, true, false);
+ std::vector<int32_t> ids = g6_codes(n_tok, (int32_t) n_codes, 7);
+ g6_tensor_data(w, "voice.v0", {hp.n_proj, 2}, g6_normal(2 * hp.n_proj, "cbx.voice.rows"));
+ g6_tensor_data(w, "voice.v0.ref_tokens", {n_tok}, std::vector<float>(ids.begin(), ids.end()));
+ g6_tensor_data(w, "voice.v0.ref_feat", {80, 2 * n_tok}, g6_normal(80 * 2 * n_tok, "cbx.voice.feat"));
+ g6_tensor_data(w, "voice.v0.ref_spk", {192}, g6_normal(192, "cbx.voice.spk"));
+ tm.gen = [](mtmd_context * ctx, std::vector<float> & out) {
+ auto st = g6_gen_state(ctx);
+ mtmd::bitmap voice(mtmd_gen_audio_get_voice(ctx, "v0"));
+ if (!st || !voice.ptr) {
+ return false;
+ }
+ // the voice encode gives the talker rows, set_ref keeps the flow decoder reference
+ mtmd::input_chunks chunks(mtmd_input_chunks_init());
+ const std::string text = mtmd_default_marker();
+ mtmd_input_text txt = { text.c_str(), text.size(), false, true };
+ const mtmd_bitmap * bmp = voice.ptr.get();
+ if (mtmd_tokenize(ctx, chunks.ptr.get(), &txt, &bmp, 1) != 0) {
+ return false;
+ }
+ for (size_t i = 0; i < chunks.size(); i++) {
+ if (mtmd_input_chunk_get_type(chunks[i]) == MTMD_INPUT_CHUNK_TYPE_AUDIO && mtmd_encode_chunk(ctx, chunks[i]) != 0) {
+ return false;
+ }
+ }
+ if (mtmd_gen_state_set_ref(ctx, st.get()) != 0) {
+ return false;
+ }
+ for (int n : { 4, 3 }) {
+ std::vector<int32_t> codes = g6_codes(n, (int32_t) n_codes, 10 + n);
+ mtmd_gen_inp inp = mtmd_gen_inp_default(ctx);
+ inp.type = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
+ inp.codes = codes.data();
+ inp.n_codes = codes.size();
+ mtmd_gen_out o{};
+ if (mtmd_gen_audio_process(ctx, st.get(), &inp, &o) != 0 || o.n_samples == 0) {
+ return false;
+ }
+ out.insert(out.end(), o.audio, o.audio + o.n_samples);
+ }
+ return true;
+ };
+ } break;
+ case PROJECTOR_TYPE_CHATTERBOX_SPKENC:
+ {
+ // CAMPPlus x-vector (a.spk.*), voice encoder lstm (a.ve.*, host) and speaker projection (a.cenc.*, host)
+ // the reference also runs the s3 tokenizer of the gen model, the classic cfm variant is used here
+ g6_chatterbox_gen(w, hp, 6561, 1, false, true);
+ enc_hparams ha = hp;
+ ha.n_layer = 0;
+ add_audio_kv(w, proj, ha, 80, true);
+ auto bn = [&](const std::string & p, int64_t n) {
+ w.tensor(p + ".running_mean", {n});
+ w.norm(p + ".running_var", n);
+ w.norm(p + ".weight", n);
+ w.tensor(p + ".bias", {n});
+ };
+ auto res2d = [&](const std::string & p, bool shortcut) {
+ w.tensor(p + ".conv1.weight", {3, 3, 32, 32});
+ bn(p + ".bn1", 32);
+ w.tensor(p + ".conv2.weight", {3, 3, 32, 32});
+ bn(p + ".bn2", 32);
+ if (shortcut) {
+ w.tensor(p + ".shortcut.0.weight", {1, 1, 32, 32});
+ bn(p + ".shortcut.1", 32);
+ }
+ };
+ // fcm front: 32 channels, the frequency axis 80 -> 10 gives 320 rows
+ w.tensor("a.spk.head.conv1.weight", {3, 3, 1, 32});
+ bn("a.spk.head.bn1", 32);
+ res2d("a.spk.head.layer1.0", true);
+ res2d("a.spk.head.layer1.1", false);
+ res2d("a.spk.head.layer2.0", true);
+ res2d("a.spk.head.layer2.1", false);
+ w.tensor("a.spk.head.conv2.weight", {3, 3, 32, 32});
+ bn("a.spk.head.bn2", 32);
+ w.tensor("a.spk.xvector.tdnn.linear.weight", {5, 320, 128});
+ bn("a.spk.xvector.tdnn.nonlinear.batchnorm", 128);
+ // one cam layer per block (growth 32), the last transit gives the 512 channels of the stats pooling
+ const int64_t transit_out[3] = { 128, 128, 512 };
+ int64_t n_ch = 128;
+ for (int b = 1; b <= 3; b++) {
+ const std::string p = fmt("a.spk.xvector.block%d.tdnnd1", b);
+ bn(p + ".nonlinear1.batchnorm", n_ch);
+ w.tensor(p + ".linear1.weight", {1, n_ch, 64});
+ bn(p + ".nonlinear2.batchnorm", 64);
+ w.tensor(p + ".cam_layer.linear_local.weight", {3, 64, 32});
+ w.tensor(p + ".cam_layer.linear1.weight", {1, 64, 32});
+ w.tensor(p + ".cam_layer.linear1.bias", {32});
+ w.tensor(p + ".cam_layer.linear2.weight", {1, 32, 32});
+ w.tensor(p + ".cam_layer.linear2.bias", {32});
+ const std::string t = fmt("a.spk.xvector.transit%d", b);
+ bn(t + ".nonlinear.batchnorm", n_ch + 32);
+ w.tensor(t + ".linear.weight", {1, n_ch + 32, transit_out[b - 1]});
+ n_ch = transit_out[b - 1];
+ }
+ bn("a.spk.xvector.out_nonlinear.batchnorm", 512);
+ w.tensor("a.spk.xvector.dense.linear.weight", {1, 1024, 192});
+ bn("a.spk.xvector.dense.nonlinear.batchnorm", 192);
+ // voice encoder: 3-layer lstm (40 mel, 256 hidden)
+ for (int l = 0; l < 3; l++) {
+ w.tensor(fmt("a.ve.lstm.weight_ih_l%d", l), {l == 0 ? 40 : 256, 1024});
+ w.tensor(fmt("a.ve.lstm.weight_hh_l%d", l), {256, 1024});
+ w.tensor(fmt("a.ve.lstm.bias_ih_l%d", l), {1024});
+ w.tensor(fmt("a.ve.lstm.bias_hh_l%d", l), {1024});
+ }
+ w.tensor("a.ve.proj.weight", {256, 256});
+ w.tensor("a.ve.proj.bias", {256});
+ w.tensor("a.cenc.spkr_enc.weight", {256, hp.n_proj});
+ w.tensor("a.cenc.spkr_enc.bias", {hp.n_proj});
+ tm.audio = true;
+ tm.todo = "Metal vs CPU: the s3 tokenizer FSQ values of the 10 s / 15 s clips fall within 3e-5..1e-3 of the rounding boundary (|h| = 0.5), so Metal flips some codes and their t3 rows (NMSE 5e-3 at 30 s, 1.6e-2 at 45 s); 1 s matches";
+ } break;
+ default:
+ return false;
+ }
+ return true;
+}
+
+// returns false if the projector is not covered yet
+static bool make_mmproj(projector_type proj, mmproj_writer & w, test_model & tm) {
+ enc_hparams hp;
+ tm.n_embd_out = hp.n_proj;
+
+ switch (proj) {
+ case PROJECTOR_TYPE_GEMMA3:
+ {
+ // siglip, fixed size: 8x8 patches pooled by 2 -> 16 tokens
+ const uint32_t image_size = 128;
+ const uint32_t patch_size = 16;
+ const int64_t n_pos = (image_size / patch_size) * (image_size / patch_size);
+ add_vision_kv(w, proj, hp, image_size, patch_size);
+ w.kv(KEY_USE_GELU, true);
+ w.kv(KEY_PROJ_SCALE_FACTOR, uint32_t(2));
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_BIAS, {hp.n_embd});
+ w.tensor(fmt(TN_POS_EMBD, "v"), {hp.n_embd, n_pos});
+ add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, {});
+ w.tensor(TN_MM_INP_PROJ, {hp.n_proj, hp.n_embd});
+ w.norm(TN_MM_SOFT_EMB_N, hp.n_embd);
+ tm.vision = true;
+ } break;
+ case PROJECTOR_TYPE_QWEN25VL:
+ {
+ // dynamic size with window attention, 2x2 merge
+ const uint32_t patch_size = 14;
+ add_vision_kv(w, proj, hp, 560, patch_size);
+ w.kv(KEY_USE_SILU, true);
+ w.kv(KEY_WIN_ATTN_PATTERN, uint32_t(2));
+ w.tensor(TN_PATCH_EMBD, {patch_size, patch_size, 3, hp.n_embd});
+ w.tensor(TN_PATCH_EMBD_1, {patch_size, patch_size, 3, hp.n_embd});
+ vit_opts o;
+ o.ln_bias = false;
+ o.ffn_gate = true;
+ add_vit(w, "v", hp.n_layer, hp.n_embd, hp.n_ff, o);
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "weight"), {4 * hp.n_embd, 4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 0, "bias"), {4 * hp.n_embd});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "weight"), {4 * hp.n_embd, hp.n_proj});
+ w.tensor(fmt(TN_LLAVA_PROJ, 2, "bias"), {hp.n_proj});
+ tm.vision = true;
+ tm.text_mrope = true;
+ } break;
+ case PROJECTOR_TYPE_ULTRAVOX:
+ {
+ // whisper encoder + stacked frames + swiglu projector
+ const uint32_t n_mel = 128;
+ const uint32_t n_stack = 8;
+ const int64_t n_mid = 2 * hp.n_embd;
+ add_audio_kv(w, proj, hp, n_mel);
+ w.kv(KEY_A_PROJ_STACK_FACTOR, n_stack);
+ w.tensor(fmt(TN_CONV1D, 1, "weight"), {3, n_mel, hp.n_embd});
+ w.tensor(fmt(TN_CONV1D, 1, "bias"), {1, hp.n_embd});
+ w.tensor(fmt(TN_CONV1D, 2, "weight"), {3, hp.n_embd, hp.n_embd});
+ w.tensor(fmt(TN_CONV1D, 2, "bias"), {1, hp.n_embd});
+ w.tensor(fmt(TN_POS_EMBD, "a"), {hp.n_embd, 1500});
+ vit_opts o;
+ o.k_bias = false;
+ add_vit(w, "a", hp.n_layer, hp.n_embd, hp.n_ff, o);
+ w.norm(fmt(TN_MM_NORM_PRE, "weight"), n_stack * hp.n_embd);
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 1, "weight"), {n_stack * hp.n_embd, 2 * n_mid});
+ w.norm(fmt(TN_MM_NORM_MID, "weight"), n_mid);
+ w.tensor(fmt(TN_MM_AUDIO_MLP, 2, "weight"), {n_mid, hp.n_proj});
+ tm.audio = true;
+ } break;
+ default:
+ return make_mmproj_g1(proj, w, tm) || make_mmproj_g2(proj, w, tm) || make_mmproj_g3(proj, w, tm) ||
+ make_mmproj_g4(proj, w, tm) || make_mmproj_g5(proj, w, tm) || make_mmproj_g6(proj, w, tm);
+ }
+ return true;
+}
+
+//
+// text model, only used for the tokenizer and the n_embd check of mtmd
+//
+
+static void text_set_tensor_data(ggml_tensor * t, void * /*userdata*/) {
+ std::vector<float> data(ggml_nelements(t));
+ fill_normal(data.data(), data.size(), ggml_get_name(t), 0.0f, 0.05f);
+ GGML_ASSERT(t->type == GGML_TYPE_F32);
+ ggml_backend_tensor_set(t, data.data(), 0, ggml_nbytes(t));
+}
+
+static llama_model_ptr make_text_model(uint32_t n_embd, bool mrope) {
+ gguf_context_ptr g(gguf_init_empty());
+ const uint32_t n_vocab = 64;
+ // qwen2vl: a text model with M-RoPE, 2 heads -> 4 sections over n_rot/2
+ const std::string arch = mrope ? "qwen2vl" : "llama";
+ auto key = [&](const char * k) { return arch + "." + k; };
+ gguf_set_val_str(g.get(), "general.architecture", arch.c_str());
+ gguf_set_val_u32(g.get(), key("context_length").c_str(), 256);
+ gguf_set_val_u32(g.get(), key("embedding_length").c_str(), n_embd);
+ gguf_set_val_u32(g.get(), key("feed_forward_length").c_str(), n_embd);
+ gguf_set_val_u32(g.get(), key("block_count").c_str(), 1);
+ gguf_set_val_u32(g.get(), key("attention.head_count").c_str(), 2);
+ gguf_set_val_f32(g.get(), key("attention.layer_norm_rms_epsilon").c_str(), 1e-5f);
+ if (mrope) {
+ const int32_t n_rot = (int32_t) n_embd / 2;
+ const int32_t sections[4] = { n_rot / 4, n_rot / 8, n_rot / 8, 0 };
+ gguf_set_arr_data(g.get(), key("rope.dimension_sections").c_str(), GGUF_TYPE_INT32, sections, 4);
+ }
+ gguf_set_val_str(g.get(), "tokenizer.ggml.model", "test");
+ // control tokens looked up by name, e.g. by the audio streams
+ const std::vector<std::string> specials = { "<s>", "[STREAMING_PAD]", "<|text_start|>" };
+ std::vector<std::string> list(n_vocab);
+ std::vector<const char *> ptrs(n_vocab);
+ std::vector<float> scores(n_vocab, 0.0f);
+ std::vector<int32_t> types(n_vocab, LLAMA_TOKEN_TYPE_NORMAL);
+ for (uint32_t i = 0; i < n_vocab; i++) {
+ list[i] = "tok_" + std::to_string(i);
+ if (i < specials.size()) {
+ list[i] = specials[i];
+ types[i] = LLAMA_TOKEN_TYPE_CONTROL;
+ }
+ ptrs[i] = list[i].c_str();
+ }
+ gguf_set_arr_str (g.get(), "tokenizer.ggml.tokens", ptrs.data(), ptrs.size());
+ gguf_set_arr_data(g.get(), "tokenizer.ggml.scores", GGUF_TYPE_FLOAT32, scores.data(), scores.size());
+ gguf_set_arr_data(g.get(), "tokenizer.ggml.token_type", GGUF_TYPE_INT32, types.data(), types.size());
+ gguf_set_val_u32 (g.get(), "tokenizer.ggml.bos_token_id", 0);
+
+ llama_model_params mparams = llama_model_default_params();
+ mparams.n_gpu_layers = 0;
+ llama_model_ptr model(llama_model_init_from_user(g.get(), text_set_tensor_data, nullptr, mparams));
+ if (!model) {
+ throw std::runtime_error("failed to create the text model");
+ }
+ return model;
+}
+
+//
+// inputs
+//
+
+struct test_input {
+ std::string name;
+ mtmd::bitmap bmp;
+};
+
+static std::vector<test_input> make_inputs(const test_model & tm) {
+ std::vector<test_input> res;
+ auto add_image = [&](int nx, int ny) {
+ std::vector<uint8_t> rgb((size_t) nx * ny * 3);
+ for (size_t i = 0; i < rgb.size(); i++) {
+ rgb[i] = (uint8_t) ((i * 2654435761u) >> 24);
+ }
+ res.push_back({fmt("image %dx%d", nx, ny), mtmd::bitmap(nx, ny, rgb.data())});
+ };
+ auto add_audio = [&](float seconds) {
+ std::vector<float> pcm((size_t) (seconds * 16000));
+ for (size_t i = 0; i < pcm.size(); i++) {
+ pcm[i] = 0.3f * sinf(2.0f * TEST_PI * 440.0f * i / 16000.0f) + 0.05f * g_normal_pool[i % NORMAL_POOL_SIZE];
+ }
+ res.push_back({fmt("audio %.1fs", seconds), mtmd::bitmap(mtmd_bitmap_init_from_audio(pcm.size(), pcm.data()))});
+ };
+ if (tm.vision) {
+ // small, then shapes above the default cap, so the preprocessor has to clamp them
+ std::vector<std::pair<int, int>> sizes = tm.image_sizes;
+ if (sizes.empty()) {
+ sizes = {{32, 32}, {4000, 4000}, {4000, 300}, {300, 4000}, {1999, 1501}};
+ }
+ for (const auto & [nx, ny] : sizes) {
+ add_image(nx, ny);
+ }
+ }
+ if (tm.audio) {
+ std::vector<float> seconds = tm.audio_seconds;
+ if (seconds.empty()) {
+ seconds = {1.0f, 30.0f, 45.0f};
+ }
+ for (float sec : seconds) {
+ add_audio(sec);
+ }
+ }
+ return res;
+}
+
+//
+// runner
+//
+
+static std::string get_tmp_gguf_path() {
+ static size_t id = 0;
+ // a random id per process avoids clashes between processes that run at the same time
+ static const unsigned int proc_id = std::random_device{}();
+ return (std::filesystem::temp_directory_path() / ("test-mtmd-model-" + std::to_string(proc_id) + "-" + std::to_string(++id) + ".gguf")).string();
+}
+
+struct backend_config {
+ std::string name;
+ ggml_backend_dev_t dev; // nullptr = CPU
+};
+
+static int g_verbosity = 0;
+
+// dump the outputs to a dir, or compare them with a previous dump, to check that a change keeps the outputs
+static std::string g_dump_dir;
+static std::string g_cmp_dir;
+
+static std::string get_dump_path(const std::string & dir, const std::string & proj, const std::string & backend, size_t i) {
+ return (std::filesystem::path(dir) / (proj + "-" + backend + "-" + std::to_string(i) + ".bin")).string();
+}
+
+// returns false if the output does not match the dump
+static bool dump_or_compare(const std::string & proj, const std::string & backend, size_t i, const std::vector<float> & out) {
+ if (!g_dump_dir.empty()) {
+ FILE * f = fopen(get_dump_path(g_dump_dir, proj, backend, i).c_str(), "wb");
+ GGML_ASSERT(f != nullptr);
+ fwrite(out.data(), sizeof(float), out.size(), f);
+ fclose(f);
+ }
+ if (!g_cmp_dir.empty()) {
+ const std::string path = get_dump_path(g_cmp_dir, proj, backend, i);
+ FILE * f = fopen(path.c_str(), "rb");
+ if (f == nullptr) {
+ printf(" %s: output %zu: no dump to compare with (%s)\n", backend.c_str(), i, path.c_str());
+ return true;
+ }
+ std::vector<float> ref(std::filesystem::file_size(path) / sizeof(float));
+ const size_t n_read = fread(ref.data(), sizeof(float), ref.size(), f);
+ fclose(f);
+ if (n_read != ref.size() || ref.size() != out.size()) {
+ printf(" %s: output %zu: size %zu vs dump %zu\n", backend.c_str(), i, out.size(), ref.size());
+ return false;
+ }
+ const double err = nmse(ref, out);
+ if (g_verbosity > 0 || !(err <= 1e-6)) {
+ printf(" %s: output %zu: NMSE vs dump = %.3e\n", backend.c_str(), i, err);
+ }
+ return err <= 1e-6;
+ }
+ return true;
+}
+
+struct run_ctx {
+ const backend_config & bc;
+ mtmd_context * ctx;
+ size_t buf_size_warmup;
+ std::vector<std::vector<float>> & outputs;
+ bool ok = true;
+
+ // check one output: finite, and the compute buffers did not grow since the warmup
+ void check(const std::string & name, std::vector<float> && out, size_t n_rows) {
+ const size_t buf_size = mtmd_get_compute_buffer_size(ctx);
+ bool finite = !out.empty();
+ for (float v : out) {
+ finite = finite && std::isfinite(v);
+ }
+ const bool realloc = buf_size != buf_size_warmup || mtmd_get_n_reallocs_unexpected(ctx) != 0;
+ if (g_verbosity > 0 || realloc || !finite) {
+ printf(" %s: %-20s rows = %8zu, compute buffer = %8.2f MiB (warmup %8.2f MiB), unexpected reallocs = %d%s%s\n",
+ bc.name.c_str(), name.c_str(), n_rows,
+ buf_size / 1024.0 / 1024.0, buf_size_warmup / 1024.0 / 1024.0, mtmd_get_n_reallocs_unexpected(ctx),
+ realloc ? " REALLOC" : "", finite ? "" : (out.empty() ? " EMPTY" : " NON-FINITE"));
+ }
+ ok = ok && !realloc && finite;
+ outputs.push_back(std::move(out));
+ }
+
+ void fail(const std::string & name, const char * what) {
+ printf(" %s: %s: %s\n", bc.name.c_str(), name.c_str(), what);
+ ok = false;
+ }
+};
+
+// encode every media chunk of every input, concatenated
+static void run_encode(run_ctx & rc, const test_model & tm) {
+ auto inputs = make_inputs(tm);
+ for (auto & inp : inputs) {
+ mtmd::input_chunks chunks(mtmd_input_chunks_init());
+ const std::string text = mtmd_default_marker();
+ mtmd_input_text txt = { text.c_str(), text.size(), false, true };
+ const mtmd_bitmap * bmp = inp.bmp.ptr.get();
+ if (mtmd_tokenize(rc.ctx, chunks.ptr.get(), &txt, &bmp, 1) != 0) {
+ rc.fail(inp.name, "failed to tokenize");
+ return;
+ }
+
+ std::vector<float> out;
+ for (size_t i = 0; i < chunks.size(); i++) {
+ const mtmd_input_chunk * chunk = chunks[i];
+ if (mtmd_input_chunk_get_type(chunk) == MTMD_INPUT_CHUNK_TYPE_TEXT) {
+ continue;
+ }
+ if (mtmd_encode_chunk(rc.ctx, chunk) != 0) {
+ rc.fail(inp.name, "failed to encode");
+ return;
+ }
+ const size_t n = mtmd_input_chunk_get_n_tokens(chunk) * (size_t) tm.n_embd_out;
+ const float * embd = mtmd_get_output_embd(rc.ctx);
+ out.insert(out.end(), embd, embd + n);
+ }
+ const size_t n_rows = out.size() / tm.n_embd_out;
+ rc.check(inp.name, std::move(out), n_rows);
+ }
+}
+
+// push a few seconds of audio in pieces, then read every row
+static void run_stream(run_ctx & rc, const test_model & tm) {
+ const std::string name = "stream";
+ mtmd_audio_stream_params sparams = mtmd_audio_stream_params_default();
+ mtmd::audio_stream_ptr stream(mtmd_audio_stream_init(rc.ctx, sparams));
+ if (!stream) {
+ rc.fail(name, "failed to init the stream");
+ return;
+ }
+ const int sample_rate = mtmd_get_audio_sample_rate(rc.ctx);
+ std::vector<float> pcm((size_t) sample_rate * 3);
+ for (size_t i = 0; i < pcm.size(); i++) {
+ pcm[i] = 0.3f * sinf(2.0f * TEST_PI * 440.0f * i / sample_rate) + 0.05f * g_normal_pool[i % NORMAL_POOL_SIZE];
+ }
+
+ std::vector<float> out;
+ auto drain = [&]() -> bool {
+ for (int it = 0; it < 100000; it++) {
+ const int32_t n = mtmd_audio_stream_step(stream.get(), 0);
+ if (n == 0 || n == -1) {
+ return true;
+ }
+ if (n < 0) {
+ return false;
+ }
+ const float * embd = mtmd_audio_stream_get_output_embd(stream.get());
+ out.insert(out.end(), embd, embd + (size_t) n * tm.n_embd_out);
+ }
+ return false;
+ };
+ // uneven pieces, so the steps see different amounts of pending audio
+ const size_t piece = (size_t) sample_rate * 7 / 10;
+ for (size_t off = 0; off < pcm.size(); off += piece) {
+ const size_t n = std::min(piece, pcm.size() - off);
+ if (mtmd_audio_stream_push(stream.get(), pcm.data() + off, n) != 0 || !drain()) {
+ rc.fail(name, "failed to push");
+ return;
+ }
+ }
+ if (mtmd_audio_stream_flush(stream.get(), true) != 0 || !drain()) {
+ rc.fail(name, "failed to flush");
+ return;
+ }
+ const size_t n_rows = out.size() / tm.n_embd_out;
+ rc.check(name, std::move(out), n_rows);
+}
+
+// returns false on error, if an output is not finite, or if a step grows the compute buffers
+static bool run_model(const std::string & fname, llama_model * text_model, const test_model & tm,
+ const backend_config & bc, std::vector<std::vector<float>> & outputs) {
+ mtmd_context_params params = mtmd_context_params_default();
+ params.use_gpu = bc.dev != nullptr;
+ params.device = bc.dev;
+ params.print_timings = false;
+ params.n_threads = 4;
+ params.warmup = true;
+
+ mtmd::context_ptr ctx(mtmd_init_from_file(fname.c_str(), text_model, params));
+ if (!ctx) {
+ printf(" %s: failed to load\n", bc.name.c_str());
+ return false;
+ }
+
+ outputs.clear();
+ run_ctx rc = { bc, ctx.get(), mtmd_get_compute_buffer_size(ctx.get()), outputs };
+ if (tm.vision || tm.audio) {
+ run_encode(rc, tm);
+ }
+ if (tm.stream) {
+ run_stream(rc, tm);
+ }
+ if (tm.gen) {
+ std::vector<float> out;
+ if (!tm.gen(ctx.get(), out)) {
+ rc.fail("gen", "failed to generate");
+ } else {
+ const size_t n = out.size();
+ rc.check("gen", std::move(out), n);
+ }
+ }
+ return rc.ok;
+}
+
+static void usage(char ** argv) {
+ printf("usage: %s [-p <projector regex>] [-v] [-s <seed>] [-t] [-d <dir>] [-c <dir>]\n", argv[0]);
+ printf(" -t also run the cases marked TODO\n");
+ printf(" -d DIR dump the outputs to DIR\n");
+ printf(" -c DIR compare the outputs with the dump in DIR (NMSE <= 1e-6)\n");
+ printf(" -v print one line per input and the warnings, -v -v also prints the info logs\n");
+}
+
+int main(int argc, char ** argv) {
+ std::string filter;
+ size_t seed = 1234;
+ bool run_todo = false;
+ for (int i = 1; i < argc; i++) {
+ if (strcmp(argv[i], "-p") == 0 && i + 1 < argc) {
+ filter = argv[++i];
+ } else if (strcmp(argv[i], "-v") == 0) {
+ g_verbosity++;
+ } else if (strcmp(argv[i], "-t") == 0) {
+ run_todo = true;
+ } else if (strcmp(argv[i], "-d") == 0 && i + 1 < argc) {
+ g_dump_dir = argv[++i];
+ } else if (strcmp(argv[i], "-c") == 0 && i + 1 < argc) {
+ g_cmp_dir = argv[++i];
+ } else if (strcmp(argv[i], "-s") == 0 && i + 1 < argc) {
+ seed = std::stoul(argv[++i]);
+ } else {
+ usage(argv);
+ return 1;
+ }
+ }
+
+ auto quiet_log = [](ggml_log_level level, const char * text, void *) {
+ if (level == GGML_LOG_LEVEL_ERROR || (level == GGML_LOG_LEVEL_WARN && g_verbosity > 0) || g_verbosity > 1) {
+ fputs(text, stderr);
+ }
+ };
+ llama_log_set(quiet_log, nullptr);
+ mtmd_log_set(quiet_log, nullptr);
+ ggml_backend_load_all();
+ init_normal_pool(seed);
+
+ // like llama.cpp, use the IGPU devices only if there is no GPU device
+ bool has_gpu = false;
+ for (size_t i = 0; i < ggml_backend_dev_count(); i++) {
+ has_gpu = has_gpu || ggml_backend_dev_type(ggml_backend_dev_get(i)) == GGML_BACKEND_DEVICE_TYPE_GPU;
+ }
+ std::vector<backend_config> backends = {{"CPU", nullptr}};
+ for (size_t i = 0; i < ggml_backend_dev_count(); i++) {
+ ggml_backend_dev_t dev = ggml_backend_dev_get(i);
+ const auto type = ggml_backend_dev_type(dev);
+ if (type == GGML_BACKEND_DEVICE_TYPE_GPU || (!has_gpu && type == GGML_BACKEND_DEVICE_TYPE_IGPU)) {
+ backends.push_back({ggml_backend_dev_name(dev), dev});
+ }
+ }
+
+ int n_ok = 0;
+ int n_fail = 0;
+ int n_skip = 0;
+ int n_todo = 0;
+ for (const auto & [proj, name] : PROJECTOR_TYPE_NAMES) {
+ if (!filter.empty() && !std::regex_search(name, std::regex(filter))) {
+ continue;
+ }
+ mmproj_writer w;
+ test_model tm;
+ if (!make_mmproj(proj, w, tm)) {
+ n_skip++;
+ continue;
+ }
+ printf("%s\n", name.c_str());
+ if (!tm.todo.empty() && !run_todo) {
+ printf(" TODO: %s\n", tm.todo.c_str());
+ n_todo++;
+ continue;
+ }
+
+ const std::string fname = get_tmp_gguf_path();
+ gguf_write_to_file(w.gguf.get(), fname.c_str(), false);
+ llama_model_ptr text_model = make_text_model(tm.n_embd_out, tm.text_mrope);
+
+ bool ok = true;
+ std::vector<std::vector<float>> out_ref;
+ for (size_t ib = 0; ib < backends.size(); ib++) {
+ std::vector<std::vector<float>> out;
+ bool res = false;
+ try {
+ res = run_model(fname, text_model.get(), tm, backends[ib], out);
+ } catch (const std::exception & e) {
+ printf(" %s: exception: %s\n", backends[ib].name.c_str(), e.what());
+ }
+ ok = ok && res;
+ for (size_t i = 0; i < out.size(); i++) {
+ ok = dump_or_compare(name, backends[ib].name, i, out[i]) && ok;
+ }
+ if (!res) {
+ continue;
+ }
+ if (ib == 0) {
+ out_ref = std::move(out);
+ continue;
+ }
+ for (size_t i = 0; i < out.size() && i < out_ref.size(); i++) {
+ if (out[i].size() != out_ref[i].size()) {
+ printf(" %s: input %zu: n_tokens mismatch vs CPU\n", backends[ib].name.c_str(), i);
+ ok = false;
+ continue;
+ }
+ const double err = nmse(out_ref[i], out[i]);
+ if (!(err <= tm.nmse_max)) {
+ printf(" %s: input %zu: NMSE vs CPU = %.3e\n", backends[ib].name.c_str(), i, err);
+ ok = false;
+ }
+ }
+ }
+ std::filesystem::remove(fname);
+
+ printf(" %s\n", ok ? "OK" : "FAIL");
+ ok ? n_ok++ : n_fail++;
+ }
+
+ printf("\n%d OK, %d FAIL, %d TODO, %d not covered\n", n_ok, n_fail, n_todo, n_skip);
+ return n_fail == 0 ? 0 : 1;
+}
diff --git a/tools/mtmd/README-dev.md b/tools/mtmd/README-dev.md
index c7fec16fa..ad36813ee 100644
--- a/tools/mtmd/README-dev.md
+++ b/tools/mtmd/README-dev.md
@@ -61,6 +61,30 @@ We provide a set of helper functions via `mtmd_helper` to make using libmtmd eas
- Image, audio and video file decoding (for example, decode raw JPEG into RGB bitmap)
- Manage `llama_batch` and calls to `llama_decode`
+## Testing a new model (`test-mtmd-model`)
+
+`tests/test-mtmd-model.cpp` runs every projector type end-to-end with random weights, similar to `tests/test-llama-archs.cpp` on the libllama side. A new projector type must come with a case in this test.
+
+For each projector, the test:
+- builds a tiny mmproj from a hand-written table of GGUF KVs and tensor shapes (`make_mmproj()`), writes it to a temp GGUF and loads it with `mtmd_init_from_file()`, on the CPU and on each GPU backend
+- encodes images and audio clips, runs an `mtmd_audio_stream`, or drives a few audio generation steps
+- fails if a step grows the compute buffer reserved by the warmup (`REALLOC`), if an output is not finite, or if a GPU output differs from the CPU output (NMSE > 1e-4)
+
+Run it with `test-mtmd-model -p <projector regex> -v` (`-v -v` also prints the mtmd logs).
+
+Adding a case:
+1. Write the table from the loader (`load_hparams()` and `load_tensors()` in `mtmd-model.cpp`: a key or tensor without `false` is required) and from the graph in `models/`. Keep the model tiny (n_embd 64, 2 heads, 1-2 layers) but keep the real structure: patch size, merge factors, and at least one layer of each type
+2. Set what the test runs and checks:
+ - `tm.vision` / `tm.audio`: encode the default inputs, which include images above the default cap and audio longer than one chunk. Override them with `tm.image_sizes` / `tm.audio_seconds` only if the model needs it
+ - `tm.stream`: for the models supported by `mtmd_support_audio_stream()`
+ - `tm.gen`: a driver that runs the real pipeline for a few steps, the same way `mtmd-helper-gen.cpp` does (GEN_CODE then GEN_WAV), with fixed inputs in place of the backbone. It must be deterministic (fixed seed, greedy), so that the backends can be compared
+ - `tm.n_embd_out`: the output size, also used as `n_embd` of the test text model. Set `tm.text_mrope` if the projector needs an M-RoPE text model
+3. For an mmproj with several modalities (e.g. a gen model with its speaker encoder), use the `mixed = true` argument of `add_vision_kv()` / `add_audio_kv()` / `add_gen_audio_kv()`
+
+The no-realloc rule: the warmup must reserve the worst-case graph of every step the model can run. The image size is capped by `set_default_max_tokens()`, and the warmup uses that cap. Audio and gen steps must have a bounded size (chunking, fixed blocks), and the warmup must reserve their largest graph.
+
+A case that fails because of a known bug in mtmd keeps its table and sets `tm.todo = "reason"`: it is skipped and the reason is printed. The reason must be precise (which graph or step, which sizes), so that it can be fixed in a follow-up. A new model must not add a TODO.
+
## Audio generation support
Audio generation is added to mtmd in PR [#26254](https://github.com/ggml-org/llama.cpp/pull/26254)
@@ -145,9 +169,10 @@ G2P in jinja has limits, mostly for languages other than English (no lexicon, or
- 60% changes inside `mtmd-helper-gen.cpp`
- 10% changes inside `libmtmd` core (`mtmd-model`, `mtmd-subcontext`, `models/`)
- The rest downstream code (CLI, server) should have no changes at all
-5. Validate with several concurrent requests on `llama-server` (e.g. `-np 2`, one plain and one streaming request at the same time), not only with `llama-tts`
+5. Add a case in `tests/test-mtmd-model.cpp`, see [Testing a new model](#testing-a-new-model-test-mtmd-model)
+6. Validate with several concurrent requests on `llama-server` (e.g. `-np 2`, one plain and one streaming request at the same time), not only with `llama-tts`
- The server interleaves the slots on one `llama_context`, so a pipeline must copy what it needs (hidden state, logits) right after its own decode, not read it at the next step
-6. Update usage documentation in `docs/multimodal/tts.md`
+7. Update usage documentation in `docs/multimodal/tts.md`
IMPORTANT: If your model needs changes that don't fit the existing infrastructure, **open an issue first for discussion**.
diff --git a/tools/mtmd/models/chatterbox-gen.cpp b/tools/mtmd/models/chatterbox-gen.cpp
index 017329bf4..bae5be71c 100644
--- a/tools/mtmd/models/chatterbox-gen.cpp
+++ b/tools/mtmd/models/chatterbox-gen.cpp
@@ -15,15 +15,8 @@ ggml_tensor * mtmd_graph_chatterbox_base::cbx_linear(ggml_tensor * w, ggml_tenso
ggml_tensor * mtmd_graph_chatterbox_base::cbx_conv1d(ggml_tensor * k, ggml_tensor * b, ggml_tensor * x,
int stride, int pad_l, int pad_r) const {
ggml_tensor * xt = ggml_cont(ctx0, ggml_transpose(ctx0, x)); // [T, C]
- if (pad_l > 0) {
- ggml_tensor * z = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, pad_l, xt->ne[1]);
- z = ggml_scale(ctx0, z, 0.0f);
- xt = ggml_concat(ctx0, z, xt, 0);
- }
- if (pad_r > 0) {
- ggml_tensor * z = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, pad_r, xt->ne[1]);
- z = ggml_scale(ctx0, z, 0.0f);
- xt = ggml_concat(ctx0, xt, z, 0);
+ if (pad_l > 0 || pad_r > 0) {
+ xt = ggml_pad_ext(ctx0, xt, pad_l, pad_r, 0, 0, 0, 0, 0, 0);
}
ggml_tensor * y = ggml_conv_1d(ctx0, k, xt, stride, 0, 1); // [T_out, OC]
y = ggml_cont(ctx0, ggml_transpose(ctx0, y)); // [OC, T_out]
@@ -49,9 +42,7 @@ ggml_tensor * mtmd_graph_chatterbox_base::cbx_conv1d_dil(ggml_tensor * k, ggml_t
// same buffer walk as the espnet rel_shift: pad one column, drop the first row, keep the first T columns
static ggml_tensor * cbx_rel_shift(ggml_context * ctx0, ggml_tensor * bd, int T) {
const int H = (int) bd->ne[2];
- ggml_tensor * z = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, 1, T, H);
- z = ggml_scale(ctx0, z, 0.0f);
- ggml_tensor * p = ggml_cont(ctx0, ggml_concat(ctx0, z, bd, 0)); // [2T, T, H]
+ ggml_tensor * p = ggml_pad_ext(ctx0, bd, 1, 0, 0, 0, 0, 0, 0, 0); // [2T, T, H]
p = ggml_reshape_3d(ctx0, p, T, 2 * T, H); // [T, 2T, H]
p = ggml_view_3d(ctx0, p, T, 2 * T - 1, H, p->nb[1], p->nb[2], p->nb[1]); // drop first row
p = ggml_cont(ctx0, p);
@@ -325,9 +316,7 @@ ggml_cgraph * mtmd_graph_chatterbox::build() {
{
ggml_tensor * xt = ggml_cont(ctx0, ggml_transpose(ctx0, x)); // [T1, 512]
xt = ggml_interpolate(ctx0, xt, 2 * T1, 512, 1, 1, GGML_SCALE_MODE_NEAREST);
- ggml_tensor * z = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 4, 512);
- z = ggml_scale(ctx0, z, 0.0f);
- xt = ggml_concat(ctx0, z, xt, 0);
+ xt = ggml_pad_ext(ctx0, xt, 4, 0, 0, 0, 0, 0, 0, 0);
ggml_tensor * y = ggml_conv_1d(ctx0, c.up_conv_w, xt, 1, 0, 1);
x = ggml_cont(ctx0, ggml_transpose(ctx0, y)); // [512, T2]
x = ggml_add(ctx0, x, c.up_conv_b);
@@ -391,9 +380,7 @@ ggml_cgraph * mtmd_graph_chatterbox::build() {
ggml_tensor * pf = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 80, n_prompt_mel);
ggml_set_name(pf, "inp_prompt_feat");
ggml_set_input(pf);
- ggml_tensor * zc = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 80, T2 - n_prompt_mel);
- zc = ggml_scale(ctx0, zc, 0.0f);
- ggml_tensor * cond = ggml_concat(ctx0, pf, zc, 1); // [80, T2]
+ ggml_tensor * cond = ggml_pad_ext(ctx0, pf, 0, 0, 0, T2 - n_prompt_mel, 0, 0, 0, 0); // [80, T2]
// raw 192-dim campplus x-vector, normalized then through the flow speaker affine
ggml_tensor * xvec = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 192);
ggml_set_name(xvec, "inp_xvec");
diff --git a/tools/mtmd/models/chatterbox-spkenc.cpp b/tools/mtmd/models/chatterbox-spkenc.cpp
index fc73aa805..01ffcf26e 100644
--- a/tools/mtmd/models/chatterbox-spkenc.cpp
+++ b/tools/mtmd/models/chatterbox-spkenc.cpp
@@ -68,9 +68,7 @@ ggml_tensor * mtmd_graph_chatterbox_spkenc::cam_layer(const mtmd_chatterbox::spk
{
ggml_tensor * padded = ht;
if (S * 100 != T) {
- ggml_tensor * z = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, S * 100 - T, C);
- z = ggml_scale(ctx0, z, 0.0f);
- padded = ggml_concat(ctx0, ht, z, 0);
+ padded = ggml_pad_ext(ctx0, ht, 0, S * 100 - T, 0, 0, 0, 0, 0, 0);
}
ggml_tensor * pooled = ggml_pool_1d(ctx0, padded, GGML_OP_POOL_AVG, 100, 100, 0); // [S, C]
pooled = ggml_mul(ctx0, pooled, segfix);
diff --git a/tools/mtmd/models/drama3-gen.cpp b/tools/mtmd/models/drama3-gen.cpp
index 41d8c22b1..63bf00379 100644
--- a/tools/mtmd/models/drama3-gen.cpp
+++ b/tools/mtmd/models/drama3-gen.cpp
@@ -1,6 +1,7 @@
#include "models.h"
#include <cmath>
+#include <map>
#include <string>
// tower RoPE: interleaved, first 64 dims of each head
@@ -23,7 +24,7 @@ std::vector<c2w_state_slot> list_drama3_state_slots(const mtmd_hparams & hparams
// h_out = out_norm(Block(eh_proj([enorm(mask * E[code] + extra); hnorm(h_in)])))
ggml_tensor * mtmd_graph_drama3_gen::tower_layer(ggml_tensor * x, int il, ggml_tensor * code, ggml_tensor * mask, ggml_tensor * extra,
- ggml_tensor * inp_pos, ggml_tensor * k_slot, ggml_tensor * v_slot, int pos) {
+ ggml_tensor * inp_pos, ggml_tensor * kq_mask, ggml_tensor * k_slot, ggml_tensor * v_slot, int pos) {
const auto & layer = model.layers[il];
const auto & tl = model.drama3_layers[il];
const int n_head = hparams.n_head;
@@ -31,6 +32,7 @@ ggml_tensor * mtmd_graph_drama3_gen::tower_layer(ggml_tensor * x, int il, ggml_t
const int64_t d_head = layer.q_w->ne[1] / n_head;
const int64_t n_kv = d_head * n_head_kv;
const float eps = hparams.eps;
+ const int64_t n_rows = kq_mask->ne[0];
ggml_tensor * e = ggml_mul(ctx0, ggml_get_rows(ctx0, tl.embd_w, code), mask);
if (extra) {
@@ -51,22 +53,16 @@ ggml_tensor * mtmd_graph_drama3_gen::tower_layer(ggml_tensor * x, int il, ggml_t
q = ggml_rope_ext(ctx0, q, inp_pos, nullptr, DRAMA3_N_ROT, GGML_ROPE_TYPE_NORMAL, 0, DRAMA3_ROPE_THETA, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f);
k = ggml_rope_ext(ctx0, k, inp_pos, nullptr, DRAMA3_N_ROT, GGML_ROPE_TYPE_NORMAL, 0, DRAMA3_ROPE_THETA, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f);
- // write K/V of this row to the slot, attention uses the cached rows + this row
+ // write K/V of this row to the slot, the mask hides the rows after pos
ggml_tensor * k_new = ggml_reshape_2d(ctx0, k, n_kv, 1);
ggml_build_forward_expand(gf, ggml_cpy(ctx0, k_new, ggml_view_2d(ctx0, k_slot, n_kv, 1, k_slot->nb[1], (size_t) pos * k_slot->nb[1])));
ggml_build_forward_expand(gf, ggml_cpy(ctx0, v, ggml_view_2d(ctx0, v_slot, n_kv, 1, v_slot->nb[1], (size_t) pos * v_slot->nb[1])));
- ggml_tensor * k_all = k_new;
- ggml_tensor * v_all = v;
- if (pos > 0) {
- k_all = ggml_concat(ctx0, ggml_view_2d(ctx0, k_slot, n_kv, pos, k_slot->nb[1], 0), k_new, 1);
- v_all = ggml_concat(ctx0, ggml_view_2d(ctx0, v_slot, n_kv, pos, v_slot->nb[1], 0), v, 1);
- }
ggml_tensor * attn = build_attn(nullptr, nullptr,
- ggml_reshape_4d(ctx0, q, d_head, n_head, 1, 1),
- ggml_reshape_4d(ctx0, k_all, d_head, n_head_kv, pos + 1, 1),
- ggml_reshape_4d(ctx0, v_all, d_head, n_head_kv, pos + 1, 1),
- nullptr, 1.0f / sqrtf((float) d_head), il);
+ ggml_reshape_4d(ctx0, q, d_head, n_head, 1, 1),
+ ggml_view_4d(ctx0, k_slot, d_head, n_head_kv, n_rows, 1, d_head * k_slot->nb[0], k_slot->nb[1], n_rows * k_slot->nb[1], 0),
+ ggml_view_4d(ctx0, v_slot, d_head, n_head_kv, n_rows, 1, d_head * v_slot->nb[0], v_slot->nb[1], n_rows * v_slot->nb[1], 0),
+ kq_mask, 1.0f / sqrtf((float) d_head), il);
attn = ggml_mul(ctx0, attn, ggml_sigmoid(ctx0, gate));
cur = ggml_add(ctx0, mixed, ggml_mul_mat(ctx0, layer.o_w, attn));
@@ -96,12 +92,17 @@ ggml_cgraph * mtmd_graph_drama3_gen::build_tower() {
pos = (int) pos_f;
slots = gen_state->slots;
} else {
- // buffer reserve: no gen state, use stand-in slots
+ // buffer reserve: no gen state, use stand-in slots, one per shape as the data is not read
+ std::map<std::pair<int64_t, int64_t>, ggml_tensor *> stand_in;
for (const auto & slot : slot_list) {
ggml_tensor * t = nullptr;
if (slot.in_place) {
- t = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, slot.ne0, slot.ne1);
- ggml_set_input(t);
+ ggml_tensor *& s = stand_in[{slot.ne0, slot.ne1}];
+ if (!s) {
+ s = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, slot.ne0, slot.ne1);
+ ggml_set_input(s);
+ }
+ t = s;
}
slots.push_back(t);
}
@@ -130,6 +131,8 @@ ggml_cgraph * mtmd_graph_drama3_gen::build_tower() {
ggml_set_name(inp_pos, "inp_pos");
ggml_set_input(inp_pos);
+ ggml_tensor * kq_mask = build_inp_attn_mask(n_kv_read(gen_state ? pos : -1), 1);
+
// teacher forcing (reference rows of a voice clone): codes 1.. of the frame are given, nothing is sampled
const bool forced = n_frames == 2;
ggml_tensor * inp_rand = nullptr;
@@ -157,7 +160,7 @@ ggml_cgraph * mtmd_graph_drama3_gen::build_tower() {
ggml_tensor * code = inp_code0;
ggml_tensor * x = ggml_reshape_2d(ctx0, h, n_mmproj_embd, 1);
for (int il = 0; il < n_layer; il++) {
- x = tower_layer(x, il, code, mask, il == 0 ? extra : nullptr, inp_pos, slots[1 + 2 * il], slots[2 + 2 * il], pos);
+ x = tower_layer(x, il, code, mask, il == 0 ? extra : nullptr, inp_pos, kq_mask, slots[1 + 2 * il], slots[2 + 2 * il], pos);
if (il < n_shared) {
continue;
}
diff --git a/tools/mtmd/models/kokoro.cpp b/tools/mtmd/models/kokoro.cpp
index 1379701c3..7f34e9fae 100644
--- a/tools/mtmd/models/kokoro.cpp
+++ b/tools/mtmd/models/kokoro.cpp
@@ -439,6 +439,7 @@ int mtmd_graph_kokoro::har_source(const mtmd_model & model, const std::vector<fl
// STFT: periodic hann window, centered with reflect padding
const int n_bins = KOKORO_N_FFT / 2 + 1;
const int n_har = (int) (n_wav / KOKORO_HOP) + 1;
+ GGML_ASSERT(n_f0 % 2 == 0 && n_har == n_har_of(n_f0 / 2));
float win[KOKORO_N_FFT], tab_cos[KOKORO_N_FFT], tab_sin[KOKORO_N_FFT];
for (int i = 0; i < KOKORO_N_FFT; i++) {
win[i] = 0.5f - 0.5f * cosf(2.0f * (float) M_PI * i / KOKORO_N_FFT);
@@ -473,6 +474,11 @@ int mtmd_graph_kokoro::har_source(const mtmd_model & model, const std::vector<fl
return n_har;
}
+// F0 has 2 steps per frame
+int mtmd_graph_kokoro::n_har_of(int n_frames) {
+ return 2 * n_frames * KOKORO_UPS / KOKORO_HOP + 1;
+}
+
// conv_post rows [n_frames, 22] -> waveform: magnitude exp(x), phase sin(x), hann overlap-add
void mtmd_graph_kokoro::istft(const std::vector<float> & spec, std::vector<float> & audio) {
const int n_bins = KOKORO_N_FFT / 2 + 1;
diff --git a/tools/mtmd/models/lfm3a.cpp b/tools/mtmd/models/lfm3a.cpp
index d96aca934..0c0f3b332 100644
--- a/tools/mtmd/models/lfm3a.cpp
+++ b/tools/mtmd/models/lfm3a.cpp
@@ -1,5 +1,8 @@
#include "models.h"
+#include <algorithm>
+#include <memory>
+
// streaming encoder state: base position, conv left context, short-conv taps and attention window
// a zero state gives the same result as encoding the whole clip
std::vector<c2w_state_slot> list_lfm3a_state_slots(const mtmd_hparams & hparams, const mtmd_model & model) {
@@ -187,3 +190,56 @@ ggml_cgraph * mtmd_graph_lfm3a::build() {
return gf;
}
+
+bool mtmd_graph_lfm3a::encode_pieces(mtmd_subcontext * ctx, mtmd_subctx_encode_params * params) {
+ GGML_ASSERT(params->imgs->entries.size() == 1 && params->out_embd != nullptr);
+ const mtmd_image_f32 & clip = params->imgs->entries[0];
+ const auto & buf = clip.get_ro_buf();
+ const int64_t n_frames = clip.nx();
+ const int64_t n_mel = clip.ny();
+ const int64_t n_embd = ctx->model.n_mmproj_embd();
+ GGML_ASSERT((int64_t) buf.size() == n_frames * n_mel);
+
+ auto & out = *params->out_embd;
+ GGML_ASSERT(out.size() == (size_t) n_embd * ctx->model.n_output_tokens(&clip));
+
+ // without a stream, a zero state encodes the clip from its start
+ std::unique_ptr<mtmd_subctx_enc_state> own;
+ mtmd_subctx_enc_state * st = params->enc_state;
+ if (st == nullptr) {
+ own.reset(ctx->enc_state_init(0));
+ if (!own) {
+ return false;
+ }
+ st = own.get();
+ }
+
+ size_t n_out = 0;
+ for (int64_t off = 0; off < n_frames; off += max_frames) {
+ const int64_t n_cur = std::min<int64_t>(max_frames, n_frames - off);
+
+ std::vector<float> data((size_t) n_cur * n_mel);
+ for (int64_t r = 0; r < n_mel; r++) {
+ std::copy_n(buf.data() + r * n_frames + off, n_cur, data.data() + r * n_cur);
+ }
+ mtmd_image_f32_batch batch;
+ batch.is_audio = true;
+ batch.entries.emplace_back();
+ batch.entries[0].set_size({(int) n_cur, (int) n_mel}, false, true);
+ batch.entries[0].cpy_buf(data);
+
+ std::vector<float> embd((size_t) n_embd * ctx->model.n_output_tokens(&batch.entries[0]));
+ mtmd_subctx_encode_params pp = *params;
+ pp.imgs = &batch;
+ pp.out_embd = &embd;
+ pp.enc_state = st;
+ if (!ctx->encode(&pp)) {
+ return false;
+ }
+ GGML_ASSERT(n_out + embd.size() <= out.size());
+ std::copy(embd.begin(), embd.end(), out.begin() + n_out);
+ n_out += embd.size();
+ }
+ GGML_ASSERT(n_out == out.size());
+ return true;
+}
diff --git a/tools/mtmd/models/models.h b/tools/mtmd/models/models.h
index b47574157..adc1c0922 100644
--- a/tools/mtmd/models/models.h
+++ b/tools/mtmd/models/models.h
@@ -207,6 +207,9 @@ struct mtmd_graph_deepseekocr2 : mtmd_graph_deepseekocr {
};
struct mtmd_graph_conformer : mtmd_graph {
+ // full attention over the clip, longer audio is cut in chunks of at most this length
+ static constexpr int max_chunk_seconds = 30;
+
mtmd_graph_conformer(mtmd_subcontext * ctx, const mtmd_image_f32 & img) : mtmd_graph(ctx, img) {}
ggml_cgraph * build() override;
};
@@ -235,6 +238,17 @@ struct mtmd_graph_chatterbox_spkenc : mtmd_graph_chatterbox_base {
};
struct mtmd_graph_chatterbox : mtmd_graph_chatterbox_base {
+ // reference clip caps in seconds: flow tokens and x-vector (DEC_COND_LEN), then the t3 tokens
+ static constexpr int ref_sec_max = 10;
+ static constexpr int t3_ref_sec_max_turbo = 15;
+ static constexpr int t3_ref_sec_max_mtl = 6;
+ static constexpr int s3tok_frames_per_sec = 100; // 16 kHz log-mel, hop 160
+ static constexpr int s3tok_tokens_per_sec = 25;
+ static constexpr int n_ref_tokens_max = ref_sec_max * s3tok_tokens_per_sec;
+ // max_new_tokens of the reference t3, plus the 3 silence tokens that turbo appends
+ static constexpr int n_gen_tokens_max = 1000 + 3;
+ static constexpr int vocode_stft_per_mel = 120; // 480 samples per mel frame, stft hop 4
+
mtmd_subctx_gen_process gen_process = MTMD_SUBCTX_GEN_PROCESS_GEN_CODE;
int n_tokens = 0;
int n_prompt_mel = 0;
@@ -265,6 +279,9 @@ struct mtmd_graph_kokoro : mtmd_graph {
STAGE_DEC, // aligned features + source STFT -> STFT coefficients
};
static constexpr int n_style = 128; // a voice row is the decoder style, then the predictor style
+ // AdaIN normalizes over the whole utterance, so it cannot be split: one call holds at most this
+ static constexpr int n_tok_max = 512; // context_length of the reference
+ static constexpr int n_frames_max = 2048;
stage_type stage;
int n_tok = 0;
@@ -281,6 +298,7 @@ struct mtmd_graph_kokoro : mtmd_graph {
const float * style, float speed, std::vector<float> & shared, std::vector<float> & asr);
// fills har as [n_har, 22], returns n_har
static int har_source(const mtmd_model & model, const std::vector<float> & f0, std::mt19937 & rng, std::vector<float> & har);
+ static int n_har_of(int n_frames);
static void istft(const std::vector<float> & spec, std::vector<float> & audio);
private:
@@ -300,8 +318,14 @@ struct mtmd_graph_kokoro : mtmd_graph {
};
struct mtmd_graph_lfm3a : mtmd_graph {
+ // 30 s, a multiple of the 8x downsampling so that the pieces of a clip join without a seam
+ static constexpr int max_frames = 3000;
+
mtmd_graph_lfm3a(mtmd_subcontext * ctx, const mtmd_image_f32 & img) : mtmd_graph(ctx, img) {}
ggml_cgraph * build() override;
+
+ // a clip longer than max_frames is encoded in pieces, the streaming state carried between them
+ static bool encode_pieces(mtmd_subcontext * ctx, mtmd_subctx_encode_params * params);
};
struct mtmd_graph_granite_speech : mtmd_graph {
@@ -322,6 +346,9 @@ struct mtmd_graph_vibevoice_asr : mtmd_graph {
};
struct mtmd_graph_muse_spark_audio : mtmd_graph {
+ // new samples per chunk, each chunk also re-reads its causal context, see mtmd_hparams::audio_n_ctx
+ static constexpr int chunk_seconds = 30;
+
mtmd_graph_muse_spark_audio(mtmd_subcontext * ctx, const mtmd_image_f32 & img) : mtmd_graph(ctx, img) {}
ggml_cgraph * build() override;
};
@@ -399,6 +426,9 @@ struct mtmd_graph_qwen3a : mtmd_graph {
};
struct mtmd_graph_mimo_audio : mtmd_graph {
+ // the reference encodes the mel in segments of 6000 frames (60 s)
+ static constexpr int segment_seconds = 60;
+
mtmd_graph_mimo_audio(mtmd_subcontext * ctx, const mtmd_image_f32 & img) : mtmd_graph(ctx, img) {}
ggml_cgraph * build() override;
};
@@ -608,6 +638,9 @@ struct mtmd_graph_pockettts_gen : mtmd_graph {
: mtmd_graph(ctx, img), gen_process(gen_process), n_step(n_step), n_frames(n_frames) {}
ggml_cgraph * build() override;
+ // GEN_WAV: latents per graph, a longer input is decoded in pieces
+ static constexpr int n_frames_max = 8;
+
mtmd_subctx_gen_process gen_process;
int n_step; // lsd_decode steps, fixed at graph-build time
int n_frames; // GEN_WAV only: number of latents to decode
@@ -644,6 +677,8 @@ struct mtmd_graph_moshi_gen : mtmd_graph {
static constexpr int mimi_n_head = 8;
static constexpr float mimi_eps = 1e-5f;
static constexpr int n_q_max = 32;
+ // GEN_WAV: frames per graph, a longer input is decoded in pieces
+ static constexpr int n_frames_max = 1;
mtmd_subctx_gen_process gen_process;
bool fb_only;
@@ -686,6 +721,11 @@ struct mtmd_graph_drama3_gen : mtmd_graph {
// tower KV rows, shared by the prompt and the generated frames
static constexpr int n_pos_max = 4096;
+ // the attention reads the first rows of the slot, rounded up to a bucket; the reserve (pos < 0) reads all rows
+ static constexpr int n_kv_bucket = 256;
+ static int n_kv_read(int pos) { return pos < 0 ? n_pos_max : std::min(n_pos_max, (pos / n_kv_bucket + 1) * n_kv_bucket); }
+ // GEN_WAV frames per graph, a longer input is decoded in pieces (the decoder is stateful)
+ static constexpr int n_wav_frames_max = 64;
mtmd_subctx_gen_process gen_process;
mtmd_subctx_gen_state * gen_state; // nullptr on buffer reserve
@@ -697,7 +737,7 @@ struct mtmd_graph_drama3_gen : mtmd_graph {
ggml_cgraph * build_tower();
ggml_cgraph * build_codec();
ggml_tensor * tower_layer(ggml_tensor * x, int il, ggml_tensor * code, ggml_tensor * mask, ggml_tensor * extra,
- ggml_tensor * inp_pos, ggml_tensor * k_slot, ggml_tensor * v_slot, int pos);
+ ggml_tensor * inp_pos, ggml_tensor * kq_mask, ggml_tensor * k_slot, ggml_tensor * v_slot, int pos);
};
//
@@ -709,6 +749,9 @@ struct mtmd_graph_fish_s2_gen : mtmd_graph_drama3_gen {
using mtmd_graph_drama3_gen::mtmd_graph_drama3_gen;
ggml_cgraph * build() override;
+ // GEN_WAV frames of one pass, a longer input is decoded in pieces
+ static constexpr int n_wav_frames_max = 64;
+
ggml_cgraph * build_fast_ar();
};
@@ -751,6 +794,7 @@ struct mtmd_graph_zonos3_gen : mtmd_graph {
static constexpr int rs_orig = 736; // 44160 -> 44100 Hz
static constexpr int rs_new = 735;
static constexpr int samples_per_frame = 2940;
+ static constexpr int n_wav_frames_max = 64; // GEN_WAV frames of one pass, a longer input is decoded in pieces
mtmd_subctx_gen_process gen_process;
bool all_known; // GEN_CODE: only the backbone row
@@ -797,6 +841,8 @@ struct mtmd_graph_yue2_gen : mtmd_graph_snake_vae {
static constexpr float rope_theta = 1000000.0f;
static constexpr int n_ctx_max = 24576; // the AR prefix and the NAR rows of one chunk
static constexpr int ode_steps = 32; // midpoint solver
+ static constexpr int n_proj_rows_max = 512; // rows per LATENT_IN / LATENT_OUT pass, longer inputs are split
+ static constexpr int n_vae_rows_max = 128 + 2 * 16; // one tile of decode_tiled() in the reference: core + halo on both sides
mtmd_subctx_gen_process gen_process;
int n_rows;
@@ -829,6 +875,7 @@ struct mtmd_graph_music3_gen : mtmd_graph_snake_vae {
static constexpr float dit_cfg = 1.7f;
static constexpr int flow_steps = 30;
static constexpr int n_overlap = 172; // latent frames shared by neighboring windows
+ static constexpr int n_win_frames_max = 200; // condition rows of one GEN_WAV window (before_denoise.py)
mtmd_subctx_gen_process gen_process;
int n_rows; // GEN_CODE: backbone rows, FLOW_COND: frames, FLOW_STEP and GEN_WAV: latent frames
@@ -869,6 +916,8 @@ struct mtmd_graph_voxcpm2_gen : mtmd_graph {
static constexpr float cfg_default = 2.0f; // cfg_value
static constexpr int n_ctx_res = 8192; // residual LM positions of one sequence, max_length of the reference
static constexpr int dec_ratio = 1920; // decoder samples per latent
+ static constexpr int n_wav_frames_max = 16; // GEN_WAV patches of one pass, a longer input is decoded in pieces
+ static constexpr int n_rows_max = 64; // RES_INP and LATENT_IN rows of one pass, the rows are independent
static constexpr int res_dilations[3] = { 1, 3, 9 };
// t of the Euler steps with sway sampling, n_steps + 1 values from 1 to 0
@@ -914,6 +963,7 @@ struct mtmd_graph_tiny_voca : mtmd_graph {
static constexpr int n_prosody_layer = 2;
static constexpr int n_acoustic_layer = 5;
+ static constexpr int n_max_tokens = 512;
static constexpr int n_max_frames = 3000;
static constexpr int hop = 256; // samples per frame
static constexpr int n_cep_causal = 80;
@@ -956,6 +1006,8 @@ struct mtmd_graph_soprano : mtmd_graph {
static void decode_spectrum(const mtmd_model & model, const std::vector<float> & spectrum, std::vector<float> & pcm);
// SopranoDecoder default
static constexpr int upscale = 4;
+ // frames per graph, a longer input is decoded in overlapping pieces
+ static constexpr int n_frames_max = 128;
int n_frames;
};
@@ -969,6 +1021,9 @@ struct mtmd_graph_lfm3a_gen : mtmd_graph {
: mtmd_graph(ctx, img), gen_process(gen_process), all_known(all_known), n_frames(n_frames) {}
ggml_cgraph * build() override;
+ // GEN_WAV: frames per graph, a longer input is decoded in pieces
+ static constexpr int n_frames_max = 1;
+
mtmd_subctx_gen_process gen_process;
bool all_known; // GEN_CODE only
int n_frames; // GEN_WAV only
@@ -1006,6 +1061,9 @@ struct mtmd_graph_kimik25 : mtmd_graph {
};
struct mtmd_graph_parakeet : mtmd_graph {
+ // full attention over the clip, longer audio is cut in chunks of at most this length
+ static constexpr int max_chunk_seconds = 30;
+
mtmd_graph_parakeet(mtmd_subcontext * ctx, const mtmd_image_f32 & img) : mtmd_graph(ctx, img) {}
ggml_cgraph * build() override;
};
diff --git a/tools/mtmd/models/muse-spark-audio.cpp b/tools/mtmd/models/muse-spark-audio.cpp
index 20e770ef8..efe11bb93 100644
--- a/tools/mtmd/models/muse-spark-audio.cpp
+++ b/tools/mtmd/models/muse-spark-audio.cpp
@@ -52,6 +52,13 @@ ggml_cgraph * mtmd_graph_muse_spark_audio::build() {
}
}
+ // the leading context tokens only warm up the causal convs
+ const int64_t n_ctx = img.audio_n_ctx / hparams.audio_samples_per_token();
+ GGML_ASSERT(img.audio_n_ctx % hparams.audio_samples_per_token() == 0 && n_ctx < cur->ne[1]);
+ if (n_ctx > 0) {
+ cur = ggml_view_2d(ctx0, cur, cur->ne[0], cur->ne[1] - n_ctx, cur->nb[1], n_ctx * cur->nb[1]);
+ }
+
cur = build_norm(cur, model.pre_ln_w, nullptr, NORM_TYPE_RMS, hparams.eps, -1);
cb(cur, "enc_norm", -1);
diff --git a/tools/mtmd/models/pixtral.cpp b/tools/mtmd/models/pixtral.cpp
index 6d3f01de0..3cc42acbd 100644
--- a/tools/mtmd/models/pixtral.cpp
+++ b/tools/mtmd/models/pixtral.cpp
@@ -70,9 +70,7 @@ ggml_cgraph * mtmd_graph_pixtral::build() {
const int n_tokens_output = p_total + p_y - 1; // one [IMG_BREAK] per row, except the last row
ggml_tensor * tmp = ggml_reshape_3d(ctx0, cur, n_embd_text, p_x, p_y);
- ggml_tensor * tok = ggml_new_tensor_3d(ctx0, tmp->type, n_embd_text, 1, p_y);
- tok = ggml_scale(ctx0, tok, 0.0); // clear the tensor
- tok = ggml_add(ctx0, tok, model.token_embd_img_break);
+ ggml_tensor * tok = ggml_repeat_4d(ctx0, model.token_embd_img_break, n_embd_text, 1, p_y, 1);
tmp = ggml_concat(ctx0, tmp, tok, 1);
cur = ggml_view_2d(ctx0, tmp,
n_embd_text, n_tokens_output,
diff --git a/tools/mtmd/mtmd-audio.cpp b/tools/mtmd/mtmd-audio.cpp
index 952f83b91..f7599ac09 100644
--- a/tools/mtmd/mtmd-audio.cpp
+++ b/tools/mtmd/mtmd-audio.cpp
@@ -1,5 +1,6 @@
#include "mtmd-audio.h"
#include "mtmd-subcontext.h"
+#include "models/models.h"
#include <cfloat>
#include <cmath>
@@ -874,7 +875,28 @@ bool mtmd_audio_preprocessor_mimo_audio::process(const float * s
return false;
}
- output.push_back(std::move(out));
+ // the reference cuts the mel of the whole clip in segments and encodes each one on its own
+ const int64_t n_seg = (int64_t) hparams.audio_chunk_len * hparams.audio_sample_rate / hparams.audio_hop_len;
+ if (n_seg <= 0 || out.n_len <= n_seg) {
+ output.push_back(std::move(out));
+ return true;
+ }
+ for (int64_t off = 0; off < out.n_len; off += n_seg) {
+ const int64_t n_len = std::min(n_seg, out.n_len - off);
+ // a tail under 3 frames gives no token after the stride-2 convs, the reference drops it too
+ if (n_len < 3) {
+ break;
+ }
+ mtmd_audio_mel seg;
+ seg.n_mel = out.n_mel;
+ seg.n_len = n_len;
+ seg.n_len_org = n_len;
+ seg.data.resize((size_t) seg.n_mel * n_len);
+ for (int64_t m = 0; m < out.n_mel; m++) {
+ std::copy_n(out.data.begin() + (size_t) m * out.n_len + off, n_len, seg.data.begin() + (size_t) m * n_len);
+ }
+ output.push_back(std::move(seg));
+ }
return true;
}
@@ -1341,10 +1363,14 @@ bool mtmd_audio_preprocessor_chatterbox_ref::process(const float *
}
}
- // entry 0: torchaudio kaldi.fbank of CAMPPlus
+ using cbx = mtmd_graph_chatterbox;
+ const size_t gen_cap = (size_t) cbx::ref_sec_max * sr;
+ const size_t t3_cap = (size_t) (is_mtl ? cbx::t3_ref_sec_max_mtl : cbx::t3_ref_sec_max_turbo) * sr;
+
+ // entry 0: torchaudio kaldi.fbank of CAMPPlus, on the flow-capped clip like the reference x-vector
{
mtmd_audio_mel out;
- if (!mtmd_audio_kaldi_fbank(fbank_cache, pcm.data(), pcm.size(), hparams.n_mel_bins, 1.0f, out)) {
+ if (!mtmd_audio_kaldi_fbank(fbank_cache, pcm.data(), std::min(pcm.size(), gen_cap), hparams.n_mel_bins, 1.0f, out)) {
return false;
}
output.push_back(std::move(out));
@@ -1367,8 +1393,6 @@ bool mtmd_audio_preprocessor_chatterbox_ref::process(const float *
output.push_back(std::move(out));
return true;
};
- const size_t gen_cap = (size_t) 10 * sr;
- const size_t t3_cap = (size_t) (is_mtl ? 6 : 15) * sr;
if (!s3tok_entry(gen_cap) || !s3tok_entry(t3_cap)) {
return false;
}
@@ -1424,6 +1448,17 @@ bool mtmd_audio_preprocessor_chatterbox_ref::process(const float *
return true;
}
+// length of the chunks when n_samples is cut in equal chunks of at most max_samples, so that no chunk is a short tail
+// max_samples <= 0: no chunking
+static size_t mtmd_audio_even_chunk_len(size_t n_samples, int64_t max_samples) {
+ if (max_samples <= 0 || n_samples <= (size_t) max_samples) {
+ return n_samples;
+ }
+ const size_t n_max = (size_t) max_samples;
+ const size_t n_chunks = (n_samples + n_max - 1) / n_max;
+ return (n_samples + n_chunks - 1) / n_chunks;
+}
+
//
// mtmd_audio_preprocessor_conformer
//
@@ -1462,13 +1497,15 @@ bool mtmd_audio_preprocessor_conformer::process(const float * sa
GGML_ASSERT(!cache.cos_vals.empty());
GGML_ASSERT(!cache.filters.data.empty());
- mtmd_audio_mel out_full;
- bool ok = log_mel_spectrogram(samples, n_samples, mel_config, shape_only, out_full);
- if (!ok) {
- return false;
+ // each chunk is normalized and encoded on its own
+ const size_t n_chunk = mtmd_audio_even_chunk_len(n_samples, (int64_t) hparams.audio_chunk_len * hparams.audio_sample_rate);
+ for (size_t start = 0; start < n_samples; start += n_chunk) {
+ mtmd_audio_mel out;
+ if (!log_mel_spectrogram(samples + start, std::min(n_chunk, n_samples - start), mel_config, shape_only, out)) {
+ return false;
+ }
+ output.push_back(std::move(out));
}
-
- output.push_back(std::move(out_full));
return true;
}
@@ -1816,43 +1853,49 @@ bool mtmd_audio_preprocessor_parakeet::process(const float * samples,
return false;
}
- mtmd_audio_mel out_full;
- if (!log_mel(samples, n_samples_in, out_full, shape_only)) {
- return false;
- }
+ // each chunk is normalized and encoded on its own
+ const size_t n_chunk = mtmd_audio_even_chunk_len(n_samples_in, (int64_t) hparams.audio_chunk_len * hparams.audio_sample_rate);
+ for (size_t start = 0; start < n_samples_in; start += n_chunk) {
+ const size_t n_cur = std::min(n_chunk, n_samples_in - start);
- // Per-feature normalization (only on valid frames)
- {
- const double eps = 1e-5;
- int valid_frames = n_samples_in / hparams.audio_hop_len;
+ mtmd_audio_mel out_full;
+ if (!log_mel(samples + start, n_cur, out_full, shape_only)) {
+ return false;
+ }
- for (int j = 0; j < out_full.n_mel; j++) {
- double sum = 0.0;
- double sq_diff_sum = 0.0;
+ // Per-feature normalization (only on valid frames)
+ {
+ const double eps = 1e-5;
+ int valid_frames = n_cur / hparams.audio_hop_len;
- // Calculate Mean ONLY on valid audio frames
- for (int i = 0; i < valid_frames; i++) {
- sum += (double)out_full.data[j * out_full.n_len + i];
- }
- double mean = sum / valid_frames;
+ for (int j = 0; j < out_full.n_mel; j++) {
+ double sum = 0.0;
+ double sq_diff_sum = 0.0;
- // Calculate Variance ONLY on valid audio frames
- for (int i = 0; i < valid_frames; i++) {
- double diff = (double)out_full.data[j * out_full.n_len + i] - mean;
- sq_diff_sum += diff * diff;
- }
+ // Calculate Mean ONLY on valid audio frames
+ for (int i = 0; i < valid_frames; i++) {
+ sum += (double)out_full.data[j * out_full.n_len + i];
+ }
+ double mean = sum / valid_frames;
+
+ // Calculate Variance ONLY on valid audio frames
+ for (int i = 0; i < valid_frames; i++) {
+ double diff = (double)out_full.data[j * out_full.n_len + i] - mean;
+ sq_diff_sum += diff * diff;
+ }
- double std_dev = std::sqrt(sq_diff_sum / (valid_frames - 1.0));
- double denominator = std_dev + eps;
+ double std_dev = std::sqrt(sq_diff_sum / (valid_frames - 1.0));
+ double denominator = std_dev + eps;
- // Apply to ALL frames (including the padded ones)
- for (int i = 0; i < out_full.n_len; i++) {
- out_full.data[j * out_full.n_len + i] = (float)((out_full.data[j * out_full.n_len + i] - mean) / denominator);
+ // Apply to ALL frames (including the padded ones)
+ for (int i = 0; i < out_full.n_len; i++) {
+ out_full.data[j * out_full.n_len + i] = (float)((out_full.data[j * out_full.n_len + i] - mean) / denominator);
+ }
}
}
- }
- output.push_back(std::move(out_full));
+ output.push_back(std::move(out_full));
+ }
return true;
}
@@ -1934,8 +1977,8 @@ void mtmd_audio_preprocessor_zonos3_spk::initialize() {
bool mtmd_audio_preprocessor_zonos3_spk::process(const float * samples, size_t n_samples, std::vector<mtmd_audio_mel> & output,
bool /*shape_only*/) const {
- // the reference uses the first 60 s, on the int16 sample scale
- const size_t n = std::min(n_samples, (size_t) hparams.audio_sample_rate * 60);
+ // on the int16 sample scale
+ const size_t n = std::min(n_samples, (size_t) hparams.audio_sample_rate * mtmd_hparams::zonos3_max_spk_seconds);
mtmd_audio_mel out;
if (!mtmd_audio_kaldi_fbank(cache, samples, n, hparams.n_mel_bins, 32768.0f, out)) {
return false;
@@ -2336,14 +2379,38 @@ bool mtmd_audio_preprocessor_muse_spark_audio::process(
const int64_t fold = hparams.audio_samples_per_token();
const int64_t n_padded = ((int64_t) n_samples + fold - 1) / fold * fold;
- mtmd_audio_mel mel;
- mel.n_len = n_padded;
- mel.n_len_org = (int64_t) n_samples;
- mel.n_mel = 1;
- mel.data.assign((size_t) n_padded, 0.0f);
- std::copy(samples, samples + n_samples, mel.data.begin());
-
output.clear();
- output.push_back(std::move(mel));
+ if (hparams.audio_chunk_len <= 0) {
+ // speaker references (spk_ref) are not chunked
+ mtmd_audio_mel mel;
+ mel.n_len = n_padded;
+ mel.n_len_org = (int64_t) n_samples;
+ mel.n_mel = 1;
+ mel.data.assign((size_t) n_padded, 0.0f);
+ std::copy(samples, samples + n_samples, mel.data.begin());
+ output.push_back(std::move(mel));
+ return true;
+ }
+
+ // each chunk re-reads audio_n_ctx samples before its start, so the causal convs give the same output as one pass
+ const int64_t n_ctx = hparams.audio_n_ctx;
+ const int64_t n_chunk = (int64_t) hparams.audio_chunk_len * hparams.audio_sample_rate / fold * fold;
+ GGML_ASSERT(n_chunk > 0 && n_ctx % fold == 0);
+
+ std::vector<float> audio((size_t) n_padded, 0.0f);
+ std::copy(samples, samples + n_samples, audio.begin());
+
+ for (int64_t start = 0; start < n_padded; start += n_chunk) {
+ const int64_t beg = std::max<int64_t>(0, start - n_ctx);
+ const int64_t end = std::min(n_padded, start + n_chunk);
+
+ mtmd_audio_mel mel;
+ mel.n_len = end - beg;
+ mel.n_len_org = end - beg;
+ mel.n_mel = 1;
+ mel.n_ctx = start - beg;
+ mel.data.assign(audio.begin() + beg, audio.begin() + end);
+ output.push_back(std::move(mel));
+ }
return true;
}
diff --git a/tools/mtmd/mtmd-audio.h b/tools/mtmd/mtmd-audio.h
index 5322c0ae8..a4c62469b 100644
--- a/tools/mtmd/mtmd-audio.h
+++ b/tools/mtmd/mtmd-audio.h
@@ -261,7 +261,7 @@ struct mtmd_audio_preprocessor_pockettts : mtmd_audio_preprocessor {
};
// chatterbox reference front-end: one clip gives five entries, used by position in mtmd.cpp
-// 0: CAMPPlus kaldi fbank [80 x n_frames] (mel major)
+// 0: CAMPPlus kaldi fbank, flow cap [80 x n_frames] (mel major)
// 1: s3 tokenizer log-mel, flow cap [n_mel x n_frames] (mel major)
// 2: s3 tokenizer log-mel, t3 cap [n_mel x n_frames] (mel major)
// 3: s3gen prompt features [n_frames x 80] (frame major, 24 kHz mel rate)
diff --git a/tools/mtmd/mtmd-helper-gen.cpp b/tools/mtmd/mtmd-helper-gen.cpp
index 5ad139262..34011eeb5 100644
--- a/tools/mtmd/mtmd-helper-gen.cpp
+++ b/tools/mtmd/mtmd-helper-gen.cpp
@@ -2521,7 +2521,8 @@ public:
}
// the speech stop token is the backbone eos, the multilingual speech positions end the stream too
- if (llama_vocab_is_eog(vocab, sampled) || (mtl && (size_t) ar_idx >= speech_pos.size() / (size_t) n_embd)) {
+ if (llama_vocab_is_eog(vocab, sampled) || (int) codes_buf.size() >= max_new_tokens ||
+ (mtl && (size_t) ar_idx >= speech_pos.size() / (size_t) n_embd)) {
*out_stop = true;
*h_state_out = nullptr;
return 0;
@@ -2708,6 +2709,8 @@ private:
// start_text_token and stop_text_token of the reference, only the multilingual prompt uses them
static constexpr llama_token text_start = 255;
static constexpr llama_token text_stop = 0;
+ // max_new_tokens of the reference t3, see mtmd_graph_chatterbox::n_gen_tokens_max
+ static constexpr int max_new_tokens = 1000;
// per-generation state, cleared by reset()
llama_seq_id seq_id = 0;
@@ -4250,6 +4253,7 @@ private:
static constexpr int64_t n_ctx_max = 24576;
static constexpr size_t stream_chunk = 750; // 30 s
static constexpr size_t n_latent = 64;
+ // a tile (vae_core + 2 * vae_halo) must fit in mtmd_graph_yue2_gen::n_vae_rows_max
static constexpr size_t vae_core = 128; // frames kept per tile
static constexpr size_t vae_halo = 16; // frames of context on each side
static constexpr size_t vae_ratio = 1920;
@@ -4813,7 +4817,7 @@ private:
static constexpr int32_t top_k = 50;
// windows of the flow matching and their crop, see before_denoise.py and decoders.py of the reference
- static constexpr size_t win_frames = 200;
+ static constexpr size_t win_frames = 200; // see mtmd_graph_music3_gen::n_win_frames_max
static constexpr size_t win_hop = 100;
static constexpr size_t crop_left = 86; // latent frames
static constexpr size_t crop_right = 344 - 86; // latent frames
diff --git a/tools/mtmd/mtmd-impl.h b/tools/mtmd/mtmd-impl.h
index d6b32fae4..9c4783505 100644
--- a/tools/mtmd/mtmd-impl.h
+++ b/tools/mtmd/mtmd-impl.h
@@ -1293,3 +1293,8 @@ static void print_tensor_data(ggml_tensor * t, uint8_t * data, int64_t n) {
}
}
+// total size of the compute buffers shared by the subcontexts, used by tests to check that no encode grows them after the warmup
+size_t mtmd_get_compute_buffer_size(const mtmd_context * ctx);
+
+// number of reallocations of a graph with the same size as the previous one, the GGML_SCHED_NO_REALLOC builds abort on them
+int32_t mtmd_get_n_reallocs_unexpected(const mtmd_context * ctx);
diff --git a/tools/mtmd/mtmd-model.cpp b/tools/mtmd/mtmd-model.cpp
index 508dfbe94..889efe108 100644
--- a/tools/mtmd/mtmd-model.cpp
+++ b/tools/mtmd/mtmd-model.cpp
@@ -374,7 +374,7 @@ struct mtmd_model_loader {
get_u32(KEY_PROJ_SCALE_FACTOR, hparams.n_merge);
get_u32(KEY_IMAGE_MIN_PIXELS, hparams.image_min_pixels);
get_u32(KEY_IMAGE_MAX_PIXELS, hparams.image_max_pixels);
- hparams.warmup_image_size = hparams.image_size;
+ hparams.set_default_max_patches();
} break;
case PROJECTOR_TYPE_PARAKEET:
{
@@ -384,11 +384,13 @@ struct mtmd_model_loader {
get_u32(KEY_A_CONV_KERNEL_SIZE, hparams.audio_conv_kernel_size);
GGML_ASSERT(hparams.audio_conv_kernel_size > 0 && hparams.audio_conv_kernel_size % 2 == 1 &&
"audio_conv_kernel_size must be a positive odd integer");
- hparams.audio_chunk_len = 0;
+ hparams.audio_chunk_len = mtmd_graph_parakeet::max_chunk_seconds;
hparams.audio_sample_rate = 16000;
hparams.audio_n_fft = 512;
hparams.audio_window_len = 400;
hparams.audio_hop_len = 160;
+ // centered padding adds one frame
+ hparams.warmup_audio_size = hparams.audio_chunk_len * hparams.audio_sample_rate / hparams.audio_hop_len + 1;
} break;
case PROJECTOR_TYPE_NEMOTRON_TRANSCRIBE:
{
@@ -468,7 +470,7 @@ struct mtmd_model_loader {
hparams.image_resize_algo = RESIZE_ALGO_BILINEAR;
get_u32(KEY_IMAGE_MIN_PIXELS, hparams.image_min_pixels);
get_u32(KEY_IMAGE_MAX_PIXELS, hparams.image_max_pixels);
- hparams.set_warmup_n_tokens(16*16);
+ hparams.set_default_max_patches();
} break;
case PROJECTOR_TYPE_PIXTRAL:
{
@@ -495,7 +497,7 @@ struct mtmd_model_loader {
} else {
hparams.set_limit_image_tokens(8, 1024);
}
- hparams.set_warmup_n_tokens(256); // avoid OOM on warmup
+ hparams.set_default_max_patches();
} break;
case PROJECTOR_TYPE_LIGHTONOCR:
{
@@ -506,7 +508,7 @@ struct mtmd_model_loader {
hparams.image_longest_edge = hparams.image_size;
get_u32(KEY_PREPROC_IMAGE_SIZE, hparams.image_longest_edge, false);
hparams.set_limit_image_tokens();
- hparams.set_warmup_n_tokens(256); // avoid OOM on warmup
+ hparams.set_default_max_patches();
} break;
case PROJECTOR_TYPE_DOTS_OCR:
{
@@ -516,7 +518,7 @@ struct mtmd_model_loader {
get_u32(KEY_PROJ_SCALE_FACTOR, hparams.n_merge);
get_u32(KEY_IMAGE_MIN_PIXELS, hparams.image_min_pixels);
get_u32(KEY_IMAGE_MAX_PIXELS, hparams.image_max_pixels);
- hparams.set_warmup_n_tokens(46*46); // avoid OOM on warmup
+ hparams.set_default_max_tokens(46*46);
} break;
case PROJECTOR_TYPE_DOTS3NOTE_V:
{
@@ -526,7 +528,7 @@ struct mtmd_model_loader {
get_u32(KEY_IMAGE_MIN_PIXELS, hparams.image_min_pixels);
get_u32(KEY_IMAGE_MAX_PIXELS, hparams.image_max_pixels);
get_u32(KEY_VISION_N_EXPERT_USED, hparams.n_expert_used);
- hparams.set_warmup_n_tokens(46*46); // avoid OOM on warmup
+ hparams.set_default_max_tokens(46*46);
} break;
case PROJECTOR_TYPE_DOTS3NOTE_A:
{
@@ -536,6 +538,7 @@ struct mtmd_model_loader {
hparams.audio_n_fft = 400;
hparams.audio_window_len = 400;
hparams.audio_hop_len = 160;
+ hparams.warmup_audio_size = hparams.audio_chunk_len * hparams.audio_sample_rate / hparams.audio_hop_len;
} break;
case PROJECTOR_TYPE_KIMIVL:
{
@@ -544,7 +547,7 @@ struct mtmd_model_loader {
get_u32(KEY_PROJ_SCALE_FACTOR, hparams.n_merge, false);
// TODO: check kimivl preprocessor for exact values
hparams.set_limit_image_tokens(8, 1024);
- hparams.set_warmup_n_tokens(256); // avoid OOM on warmup
+ hparams.set_default_max_patches();
} break;
case PROJECTOR_TYPE_KIMIK25:
case PROJECTOR_TYPE_KIMIK31:
@@ -564,7 +567,7 @@ struct mtmd_model_loader {
hparams.set_limit_image_tokens(2, 4096);
}
if (model.proj_type == PROJECTOR_TYPE_KIMIK31) {
- hparams.set_warmup_n_tokens(46*46); // avoid OOM on warmup
+ hparams.set_default_max_tokens(46*46);
}
} break;
case PROJECTOR_TYPE_DEEPSEEK4V:
@@ -588,9 +591,9 @@ struct mtmd_model_loader {
hparams.image_max_pixels = hparams.dsv4_max_n_token * patch_area;
// a small custom max token count also lowers the min-pixel upscale threshold
hparams.image_min_pixels = std::min(hparams.image_min_pixels, hparams.image_max_pixels);
- // avoid OOM on warmup
- const int warmup_side = (int) std::sqrt((double) std::min(256, hparams.dsv4_max_n_token));
- hparams.set_warmup_n_tokens(warmup_side * warmup_side);
+ // the preprocessor reads dsv4_max_n_token, keep it in sync with the default cap
+ hparams.set_default_max_patches();
+ hparams.dsv4_max_n_token = hparams.image_max_pixels / patch_area;
} break;
case PROJECTOR_TYPE_DEEPSEEK41V:
{
@@ -613,8 +616,9 @@ struct mtmd_model_loader {
}
hparams.image_max_pixels = hparams.dsv4_max_n_token * patch_area;
hparams.image_min_pixels = std::min(hparams.image_min_pixels, hparams.image_max_pixels);
- const int warmup_side = (int) std::sqrt((double) std::min(256, hparams.dsv4_max_n_token));
- hparams.set_warmup_n_tokens(warmup_side * warmup_side);
+ // the preprocessor reads dsv4_max_n_token, keep it in sync with the default cap
+ hparams.set_default_max_patches();
+ hparams.dsv4_max_n_token = hparams.image_max_pixels / patch_area;
} break;
case PROJECTOR_TYPE_GEMMA3:
{
@@ -642,7 +646,7 @@ struct mtmd_model_loader {
hparams.n_merge = 1;
}
hparams.set_limit_image_tokens(70, 1120);
- hparams.set_warmup_n_tokens(256); // avoid OOM on warmup
+ hparams.set_default_max_tokens(280); // max_soft_tokens of the HF processor
} break;
case PROJECTOR_TYPE_GEMMA3NV:
@@ -677,7 +681,7 @@ struct mtmd_model_loader {
if (hparams.custom_image_max_tokens <= 0) {
get_u32(KEY_IMAGE_MAX_PIXELS, hparams.image_max_pixels, false);
}
- hparams.set_warmup_n_tokens(46*46); // avoid OOM on warmup
+ hparams.set_default_max_tokens(46*46);
const int warn_min_pixels = 1024 * hparams.n_merge * hparams.n_merge * hparams.patch_size * hparams.patch_size;
if (hparams.image_min_pixels < warn_min_pixels) {
LOG_WRN("%s: Qwen-VL models require at minimum 1024 image tokens to function correctly on grounding tasks\n", __func__);
@@ -695,7 +699,7 @@ struct mtmd_model_loader {
get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.n_merge);
get_u32(KEY_IMAGE_MIN_PIXELS, hparams.image_min_pixels);
get_u32(KEY_IMAGE_MAX_PIXELS, hparams.image_max_pixels);
- hparams.set_warmup_n_tokens(46*46); // avoid OOM on warmup
+ hparams.set_default_max_tokens(46*46);
} break;
case PROJECTOR_TYPE_SENSENOVA_U1:
{
@@ -709,7 +713,7 @@ struct mtmd_model_loader {
if (hparams.n_merge != 2) {
throw std::runtime_error(mtmd_format("%s: SenseNova U1 requires spatial_merge_size=2, got %u", __func__, hparams.n_merge));
}
- hparams.set_warmup_n_tokens(16*16);
+ hparams.set_default_max_patches();
} break;
case PROJECTOR_TYPE_LFM3VL:
{
@@ -742,7 +746,7 @@ struct mtmd_model_loader {
}
const int patch_area = hparams.patch_size * hparams.patch_size * hparams.n_merge * hparams.n_merge;
hparams.set_limit_image_tokens(min_pixels / patch_area, std::min(4096, max_pixels / patch_area));
- hparams.set_warmup_n_tokens(46*46); // avoid OOM on warmup
+ hparams.set_default_max_tokens(46*46);
} break;
case PROJECTOR_TYPE_MINIMAX_M3:
{
@@ -756,7 +760,7 @@ struct mtmd_model_loader {
hparams.rope_theta = 10000.0f; // vision_config.rope_theta
// MiniMax-M3: max_pixels 451584 (=672^2) -> 576 merged tokens (image_seq_length)
hparams.set_limit_image_tokens(8, 576);
- hparams.set_warmup_n_tokens(16*16);
+ hparams.set_default_max_tokens(576); // image_seq_length, fixed by the model
} break;
case PROJECTOR_TYPE_MUSE_SPARK_AUDIO:
{
@@ -774,16 +778,29 @@ struct mtmd_model_loader {
GGML_ASSERT(hparams.n_mel_bins == 1);
GGML_ASSERT(hparams.audio_conv_kernel_size >= 1);
+ // receptive field: the causal depthwise convs of the blocks, each at the hop of its stage
+ const int64_t k = hparams.audio_conv_kernel_size;
+ int64_t hop = 1;
+ int64_t rf = 0;
int64_t n_blocks = 0;
for (size_t i = 0; i < n_stage; ++i) {
GGML_ASSERT(hparams.audio_hidden_sizes[i] >= 1);
GGML_ASSERT(hparams.audio_depths[i] >= 0);
+ GGML_ASSERT(hparams.audio_patch_sizes[i] >= 1);
n_blocks += hparams.audio_depths[i];
+ hop *= hparams.audio_patch_sizes[i];
+ GGML_ASSERT(hop <= (1 << 20));
+ rf += hparams.audio_depths[i] * (k - 1) * hop;
}
if (n_blocks != hparams.n_layer) {
throw std::runtime_error(mtmd_format("%s: sum of audio depths (%" PRId64 ") does not match n_layer (%d)\n", __func__, n_blocks, hparams.n_layer));
}
- hparams.warmup_audio_size = hparams.audio_samples_per_token();
+ if (rf > 60 * hparams.audio_sample_rate) {
+ throw std::runtime_error(mtmd_format("%s: muse spark audio receptive field of %" PRId64 " samples is too long\n", __func__, rf));
+ }
+ hparams.audio_chunk_len = mtmd_graph_muse_spark_audio::chunk_seconds;
+ hparams.audio_n_ctx = (int32_t) ((rf + hop - 1) / hop * hop);
+ hparams.warmup_audio_size = (int32_t) ((int64_t) hparams.audio_chunk_len * hparams.audio_sample_rate / hop * hop) + hparams.audio_n_ctx;
} break;
case PROJECTOR_TYPE_VIBEVOICE_ASR:
{
@@ -832,7 +849,7 @@ struct mtmd_model_loader {
get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.n_merge);
hparams.rope_theta = 10000.0f;
hparams.set_limit_image_tokens(1, 4096);
- hparams.set_warmup_n_tokens(32*32); // avoid OOM on warmup
+ hparams.set_default_max_tokens(32*32);
} break;
case PROJECTOR_TYPE_MUSE_GLIMMER:
{
@@ -843,7 +860,7 @@ struct mtmd_model_loader {
hparams.muse_glimmer_sparse_factor = 4; // 3 sparse layers + 1 global, repeating
get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.n_merge, false);
hparams.set_limit_image_tokens(1, 4096);
- hparams.set_warmup_n_tokens(32*32);
+ hparams.set_default_max_tokens(32*32);
} break;
case PROJECTOR_TYPE_MIMOVL:
{
@@ -861,7 +878,7 @@ struct mtmd_model_loader {
hparams.wa_pattern_mode.assign(pat.begin(), pat.end());
get_u32(KEY_IMAGE_MIN_PIXELS, hparams.image_min_pixels);
get_u32(KEY_IMAGE_MAX_PIXELS, hparams.image_max_pixels);
- hparams.set_warmup_n_tokens(46*46); // avoid OOM on warmup
+ hparams.set_default_max_tokens(46*46);
} break;
case PROJECTOR_TYPE_STEP3VL:
{
@@ -889,7 +906,7 @@ struct mtmd_model_loader {
}
// support max_height * max_width = 8000 * 8000. 8000/16/2 = 250 image tokens
hparams.set_limit_image_tokens(1, 62500);
- hparams.set_warmup_n_tokens(16*16); // avoid OOM on warmup
+ hparams.set_default_max_patches();
} break;
case PROJECTOR_TYPE_YASA2:
{
@@ -908,7 +925,7 @@ struct mtmd_model_loader {
hparams.image_resize_algo = RESIZE_ALGO_BICUBIC;
get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.n_merge, false);
hparams.set_limit_image_tokens(8, 4096);
- hparams.set_warmup_n_tokens(46*46); // avoid OOM on warmup
+ hparams.set_default_max_tokens(46*46);
} break;
case PROJECTOR_TYPE_GLM5V:
{
@@ -921,7 +938,7 @@ struct mtmd_model_loader {
get_u32(KEY_IMAGE_MIN_PIXELS, hparams.image_min_pixels);
get_u32(KEY_IMAGE_MAX_PIXELS, hparams.image_max_pixels);
hparams.set_limit_image_tokens();
- hparams.set_warmup_n_tokens(46*46); // avoid OOM on warmup
+ hparams.set_default_max_tokens(46*46);
} break;
case PROJECTOR_TYPE_LLAMA4:
{
@@ -993,10 +1010,12 @@ struct mtmd_model_loader {
hparams.rope_theta = 10000.0f;
// audio preprocessing params (mel spectrogram)
+ hparams.audio_chunk_len = mtmd_graph_mimo_audio::segment_seconds;
hparams.audio_sample_rate = 24000;
hparams.audio_n_fft = 960;
hparams.audio_window_len = 960;
hparams.audio_hop_len = 240;
+ hparams.warmup_audio_size = hparams.audio_chunk_len * hparams.audio_sample_rate / hparams.audio_hop_len;
get_u32(KEY_A_ATTN_WINDOW_SIZE, hparams.attn_window_size);
std::vector<int> wa_pattern;
@@ -1022,7 +1041,8 @@ struct mtmd_model_loader {
hparams.audio_n_fft = 512;
hparams.audio_window_len = 400;
hparams.audio_hop_len = 160;
- hparams.warmup_audio_size = 1000;
+ // fbank frames of the longest reference
+ hparams.warmup_audio_size = 1 + (mtmd_hparams::zonos3_max_spk_seconds * hparams.audio_sample_rate - hparams.audio_window_len) / hparams.audio_hop_len;
} break;
case PROJECTOR_TYPE_QWEN3TTS_SPKENC:
{
@@ -1039,6 +1059,8 @@ struct mtmd_model_loader {
hparams.audio_n_fft = 512;
hparams.audio_window_len = 400;
hparams.audio_hop_len = 160;
+ // the fbank clip is capped like the flow reference
+ hparams.warmup_audio_size = 1 + (mtmd_graph_chatterbox::ref_sec_max * hparams.audio_sample_rate - hparams.audio_window_len) / hparams.audio_hop_len;
} break;
case PROJECTOR_TYPE_LFM3A_GEN:
{
@@ -1147,6 +1169,15 @@ struct mtmd_model_loader {
// matches the reference transformer's "context"
hparams.mimi_tfm_context = 250;
hparams.rope_theta = 10000.0f;
+ {
+ // the longest reference kept by the preprocessor, padded to whole frames
+ int32_t frame_size = hparams.mimi_downsample;
+ for (int32_t r : hparams.seanet_ratios) {
+ frame_size *= r;
+ }
+ const int32_t max_samples = mtmd_hparams::pockettts_max_spk_seconds * hparams.audio_sample_rate;
+ hparams.warmup_audio_size = (max_samples + frame_size - 1) / frame_size * frame_size;
+ }
// flow_lm defaults, see pocket_tts/default_parameters.py
hparams.flow_n_step = 1;
hparams.gen_eos_threshold = -4.0f;
@@ -1170,8 +1201,9 @@ struct mtmd_model_loader {
// AudioVAE encoder, one backbone row per patch of latents (checked against the strides at load)
hparams.audio_sample_rate = 16000;
hparams.audio_patch_sizes = { 2, 5, 8, 8, mtmd_graph_voxcpm2_gen::n_patch };
- // whole patches, about 10 s like a typical reference clip
- hparams.warmup_audio_size = hparams.audio_samples_per_token() * 63;
+ // whole patches of the longest reference
+ const int32_t fold = hparams.audio_samples_per_token();
+ hparams.warmup_audio_size = (mtmd_hparams::voxcpm2_max_spk_seconds * hparams.audio_sample_rate + fold - 1) / fold * fold;
} break;
case PROJECTOR_TYPE_FISH_S2_SPKENC:
{
@@ -1179,8 +1211,9 @@ struct mtmd_model_loader {
// one row per 2048 samples: encoder strides, then the quantizer downsample
hparams.audio_sample_rate = 44100;
hparams.audio_patch_sizes = { 2, 4, 8, 8, 2, 2 };
- // whole frames, about 10 s like a typical reference clip
- hparams.warmup_audio_size = hparams.audio_samples_per_token() * 215;
+ // whole frames of the longest reference
+ const int32_t fold = hparams.audio_samples_per_token();
+ hparams.warmup_audio_size = (mtmd_hparams::fish_s2_max_spk_seconds * hparams.audio_sample_rate + fold - 1) / fold * fold;
hparams.wav_tfm_n_head = 16;
hparams.wav_tfm_n_head_kv = 16;
hparams.wav_tfm_eps = 1e-5f;
@@ -1216,7 +1249,7 @@ struct mtmd_model_loader {
get_u32(KEY_IMAGE_MIN_PIXELS, hparams.image_min_pixels);
get_u32(KEY_IMAGE_MAX_PIXELS, hparams.image_max_pixels);
- hparams.set_warmup_n_tokens(28*28); // avoid OOM on warmup
+ hparams.set_default_max_patches();
} break;
case PROJECTOR_TYPE_DEEPSEEKOCR:
case PROJECTOR_TYPE_DEEPSEEKOCR2:
@@ -1261,7 +1294,7 @@ struct mtmd_model_loader {
get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.n_merge, false);
get_u32(KEY_IMAGE_MIN_PIXELS, hparams.image_min_pixels, false);
get_u32(KEY_IMAGE_MAX_PIXELS, hparams.image_max_pixels, false);
- hparams.set_warmup_n_tokens(32*32);
+ hparams.set_default_max_patches();
} break;
case PROJECTOR_TYPE_HY_V4_FLASH:
{
@@ -1278,17 +1311,19 @@ struct mtmd_model_loader {
hparams.set_limit_image_tokens(4, 4096);
get_u32(KEY_IMAGE_MIN_PIXELS, hparams.image_min_pixels, false);
get_u32(KEY_IMAGE_MAX_PIXELS, hparams.image_max_pixels, false);
- hparams.set_warmup_n_tokens(46*46); // avoid OOM on warmup
+ hparams.set_default_max_tokens(46*46);
} break;
case PROJECTOR_TYPE_LFM2A:
case PROJECTOR_TYPE_D1OMNI_A:
{
// audio preprocessing params
- hparams.audio_chunk_len = 1; // in seconds
+ hparams.audio_chunk_len = mtmd_graph_conformer::max_chunk_seconds;
hparams.audio_sample_rate = 16000;
hparams.audio_n_fft = 512;
hparams.audio_window_len = 400;
hparams.audio_hop_len = 160;
+ // centered padding adds one frame
+ hparams.warmup_audio_size = hparams.audio_chunk_len * hparams.audio_sample_rate / hparams.audio_hop_len + 1;
} break;
case PROJECTOR_TYPE_LFM3A:
{
@@ -1303,6 +1338,7 @@ struct mtmd_model_loader {
hparams.audio_n_fft = 400;
hparams.audio_window_len = 400;
hparams.audio_hop_len = 160;
+ hparams.warmup_audio_size = mtmd_graph_lfm3a::max_frames;
} break;
case PROJECTOR_TYPE_EXAONE4_5:
{
@@ -1313,7 +1349,7 @@ struct mtmd_model_loader {
get_u32(KEY_WIN_ATTN_PATTERN, hparams.n_wa_pattern, false);
get_u32(KEY_IMAGE_MIN_PIXELS, hparams.image_min_pixels);
get_u32(KEY_IMAGE_MAX_PIXELS, hparams.image_max_pixels);
- hparams.set_warmup_n_tokens(46 * 46);
+ hparams.set_default_max_tokens(46 * 46);
if (hparams.rope_theta <= 0.0f) {
hparams.rope_theta = 10000.0f;
}
@@ -1439,6 +1475,11 @@ struct mtmd_model_loader {
if (hparams.image_max_pixels > 0) {
LOG_INF("%s: image_max_pixels: %d%s\n", __func__, hparams.image_max_pixels, hparams.custom_image_max_tokens > 0 ? " (custom value)" : "");
}
+ if (hparams.model_image_max_tokens > 0) {
+ LOG_WRN("%s: image max tokens is capped to %d by default, the model supports up to %d\n",
+ __func__, model.image_max_tokens(), hparams.model_image_max_tokens);
+ LOG_WRN("%s: use --image-max-tokens to raise it, this needs more memory\n", __func__);
+ }
if (hparams.preproc_max_tiles > 0) {
LOG_INF("%s: preproc_tiles: %d - %d\n", __func__, hparams.preproc_min_tiles, hparams.preproc_max_tiles);
}
@@ -4952,7 +4993,7 @@ int mtmd_model::n_output_tokens(const mtmd_image_f32 * img) const {
case PROJECTOR_TYPE_MUSE_SPARK_AUDIO:
{
const int64_t fold = hparams.audio_samples_per_token();
- n_patches = (int) ((img->nx() + fold - 1) / fold);
+ n_patches = (int) ((img->nx() - img->audio_n_ctx + fold - 1) / fold);
} break;
case PROJECTOR_TYPE_VIBEVOICE_ASR:
{
@@ -4964,7 +5005,8 @@ int mtmd_model::n_output_tokens(const mtmd_image_f32 * img) const {
case PROJECTOR_TYPE_MERALION:
case PROJECTOR_TYPE_MUSIC_FLAMINGO:
{
- n_patches = img->nx();
+ // whisper downscales input token by half after conv1d, then the frames are stacked
+ n_patches = (img->nx() + 1) / 2;
const int proj_stack_factor = hparams.proj_stack_factor;
if (audio_has_stack_frames()) {
@@ -4973,9 +5015,6 @@ int mtmd_model::n_output_tokens(const mtmd_image_f32 * img) const {
n_patches = n_len / proj_stack_factor;
}
- // whisper downscales input token by half after conv1d
- n_patches /= 2;
-
if (audio_has_avgpool()) {
// divide by 2 because of nn.AvgPool1d(2, stride=2)
n_patches /= 2;
diff --git a/tools/mtmd/mtmd-model.h b/tools/mtmd/mtmd-model.h
index 10c3154e8..9c6bd3748 100644
--- a/tools/mtmd/mtmd-model.h
+++ b/tools/mtmd/mtmd-model.h
@@ -219,6 +219,8 @@ struct mtmd_hparams {
static constexpr int32_t fish_s2_max_spk_seconds = 30;
// voxcpm2: the AudioVAE encoder runs at 16 kHz, memory grows with the clip
static constexpr int32_t voxcpm2_max_spk_seconds = 30;
+ // zonos3: the reference uses the first 60 s
+ static constexpr int32_t zonos3_max_spk_seconds = 60;
int32_t seanet_n_stage = 0;
std::vector<int32_t> seanet_ratios; // encoder order (reversed compared to the config)
int32_t mimi_downsample = 0; // encoder frame rate / model frame rate
@@ -256,6 +258,9 @@ struct mtmd_hparams {
int32_t custom_image_min_tokens = -1;
int32_t custom_image_max_tokens = -1;
+ // max image tokens of the model, set if set_default_max_tokens() lowered it, -1 otherwise
+ int32_t model_image_max_tokens = -1;
+
void set_image_resize_algo(resize_algo algo, bool torch = false) {
GGML_ASSERT(!(torch && algo == RESIZE_ALGO_LANCZOS) && "torchvision has no lanczos");
image_resize_algo = static_cast<resize_algo>(torch ? algo | RESIZE_ALGO_FLAG_TORCH : algo);
@@ -279,14 +284,31 @@ struct mtmd_hparams {
}
}
- void set_warmup_n_tokens(int n_tokens) {
- int n_tok_per_side = static_cast<int>(std::sqrt(n_tokens));
- GGML_ASSERT(n_tok_per_side * n_tok_per_side == n_tokens && "n_tokens must be n*n");
- // do not warmup with more tokens than the max allowed
- if (custom_image_max_tokens > 0 && n_tokens > custom_image_max_tokens) {
- n_tok_per_side = std::max(1, static_cast<int>(std::sqrt(custom_image_max_tokens)));
+ // encoder patches of the default image cap: the cost of qwen-vl at 46x46 merged tokens
+ static constexpr int default_max_patches = 46 * 46 * 4;
+
+ // cap the max image tokens so that the encoder sees at most default_max_patches patches
+ void set_default_max_patches() {
+ const int merge = std::max(1, n_merge);
+ set_default_max_tokens(default_max_patches / (merge * merge));
+ }
+
+ // cap the max image tokens to n_tokens, unless the user sets a custom max
+ // warmup reserves the final max, so no image needs a bigger compute buffer than the warmup
+ void set_default_max_tokens(int n_tokens) {
+ GGML_ASSERT(n_tokens > 0);
+ const int merge = std::max(1, n_merge);
+ const int patch_area = patch_size * patch_size * merge * merge;
+ if (custom_image_max_tokens <= 0 && (image_max_pixels <= 0 || image_max_pixels > n_tokens * patch_area)) {
+ if (image_max_pixels > 0) {
+ model_image_max_tokens = image_max_pixels / patch_area;
+ }
+ image_max_pixels = n_tokens * patch_area;
}
- warmup_image_size = n_tok_per_side * patch_size * n_merge;
+ image_min_pixels = std::min(image_min_pixels, image_max_pixels);
+ const int n_max_tokens = image_max_pixels > 0 ? image_max_pixels / patch_area : n_tokens;
+ const int n_tok_per_side = static_cast<int>(std::ceil(std::sqrt(static_cast<double>(n_max_tokens))));
+ warmup_image_size = n_tok_per_side * patch_size * merge;
}
// sam vit deepseek-ocr
std::vector<int32_t> global_attn_indices() const {
@@ -1565,7 +1587,6 @@ struct mtmd_model {
bool audio_has_avgpool() const {
return proj_type == PROJECTOR_TYPE_QWEN2A
|| proj_type == PROJECTOR_TYPE_HIGGS_AUDIO
- || proj_type == PROJECTOR_TYPE_VOXTRAL
|| proj_type == PROJECTOR_TYPE_MUSIC_FLAMINGO;
}
diff --git a/tools/mtmd/mtmd-subcontext.cpp b/tools/mtmd/mtmd-subcontext.cpp
index 640950c5c..42e6265fd 100644
--- a/tools/mtmd/mtmd-subcontext.cpp
+++ b/tools/mtmd/mtmd-subcontext.cpp
@@ -18,6 +18,7 @@
#include <memory>
#include <random>
#include <stdexcept>
+#include <utility>
#include <vector>
// ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
@@ -100,11 +101,58 @@ mtmd_backends::mtmd_backends(ggml_backend_dev_t device, int n_threads, int max_n
bufts.push_back(ggml_backend_get_default_buffer_type(backend_cpu));
sched.reset(ggml_backend_sched_new(ptrs.data(), bufts.data(), ptrs.size(), max_nodes, false, true));
+ ggml_backend_sched_set_realloc_callback(sched.get(), [](ggml_backend_sched_t, ggml_cgraph *, bool backend_ids_changed, bool graph_size_changed, void * user_data) {
+ if (!backend_ids_changed && !graph_size_changed) {
+ static_cast<mtmd_backends *>(user_data)->n_reallocs_unexpected++;
+ }
+ }, this);
if (cb_eval != nullptr) {
ggml_backend_sched_set_eval_callback(sched.get(), cb_eval, cb_eval_user_data);
}
}
+// hash of the op, type and shape of every node and its sources
+// TODO: this is a stopgap: no single input is the worst case of every node (e.g. wide vs tall images),
+// so a graph with the same node count can need another layout than the last one
+// remove it once gallocr keeps the per-node max size over several reserved graphs of the same topology,
+// then the warmup can reserve a few extreme shapes (see also the n_seqs > 1 TODO in llama_context::sched_reserve)
+static uint64_t mtmd_graph_signature(ggml_cgraph * gf) {
+ uint64_t sig = 0xcbf29ce484222325ull; // FNV-1a
+ auto mix = [&sig](uint64_t v) {
+ sig = (sig ^ v) * 1099511628211ull;
+ };
+ auto mix_tensor = [&mix](const ggml_tensor * t) {
+ mix((uint64_t) t->op);
+ mix((uint64_t) t->type);
+ for (int i = 0; i < GGML_MAX_DIMS; i++) {
+ mix((uint64_t) t->ne[i]);
+ }
+ };
+ const int n_nodes = ggml_graph_n_nodes(gf);
+ mix((uint64_t) n_nodes);
+ for (int i = 0; i < n_nodes; i++) {
+ const ggml_tensor * node = ggml_graph_node(gf, i);
+ mix_tensor(node);
+ for (int j = 0; j < GGML_MAX_SRC && node->src[j]; j++) {
+ mix_tensor(node->src[j]);
+ }
+ }
+ return sig;
+}
+
+ggml_cgraph * mtmd_backends::alloc_graph(const std::function<ggml_cgraph * ()> & build) {
+ ggml_cgraph * gf = build();
+ const uint64_t sig = mtmd_graph_signature(gf);
+ if (sig != last_graph_sig) {
+ if (!ggml_backend_sched_reserve(sched.get(), gf)) {
+ return nullptr;
+ }
+ last_graph_sig = sig;
+ gf = build();
+ }
+ return ggml_backend_sched_alloc_graph(sched.get(), gf) ? gf : nullptr;
+}
+
mtmd_backends::~mtmd_backends() {
// before the backends it uses
sched.reset();
@@ -207,6 +255,8 @@ void mtmd_subcontext::warmup(const mtmd_image_f32_batch & batch) {
}
}
+ warmup_steps();
+
is_allocated = true; // mark buffers as allocated
LOG_INF("%s: flash attention is %s\n", __func__,
@@ -240,9 +290,286 @@ void mtmd_subcontext::warmup(const mtmd_image_f32_batch & batch) {
}
}
+void mtmd_subcontext::reserve_step(const mtmd_image_f32_batch & imgs, const mtmd_subctx_encode_params & params) {
+ ggml_backend_sched_reserve(backends.sched.get(), mtmd_get_graph_builder(this, imgs, ¶ms)->build());
+ backends.last_graph_sig = 0;
+}
+
+void mtmd_subcontext::warmup_steps() {
+ // the graphs only read the sizes of the inputs, so they can be zeros
+ auto make_batch = [](int nx, int ny) {
+ mtmd_image_f32 img;
+ img.set_size({nx, ny}, false, true);
+ mtmd_image_f32_batch batch;
+ batch.is_audio = true;
+ batch.entries.push_back(std::move(img));
+ return batch;
+ };
+ const auto batch1 = make_batch(1, 1);
+
+ switch (model.proj_type) {
+ case PROJECTOR_TYPE_QWEN3TTS_GEN:
+ {
+ // one gen-audio step, the input of every gen step
+ const auto imgs = get_dummy_batch();
+ // GEN_CODE and GEN_WAV share one graph, the sampling params change the GEN_CODE part
+ const int n_vocab = (int) model.gen_code_head_w->ne[1];
+ mtmd_subctx_encode_params p;
+ p.gen_process = MTMD_SUBCTX_GEN_PROCESS_GEN_WAV;
+ reserve_step(imgs, p);
+ // greedy, then top-k + top-p over almost all and over all the vocab
+ p.gen_process = MTMD_SUBCTX_GEN_PROCESS_GEN_CODE;
+ for (auto [top_k, top_p] : {std::pair<int, float>{1, 1.0f}, {n_vocab - 1, 0.5f}, {0, 0.5f}}) {
+ p.top_k = top_k;
+ p.top_p = top_p;
+ reserve_step(imgs, p);
+ }
+ } break;
+ case PROJECTOR_TYPE_POCKETTTS_GEN:
+ {
+ // one gen-audio step, the input of every gen step
+ const auto imgs = get_dummy_batch();
+ const std::vector<float> feats((size_t) mtmd_graph_pockettts_gen::n_frames_max * model.gen_input_lin_w->ne[0]);
+ mtmd_subctx_encode_params p;
+ p.gen_process = MTMD_SUBCTX_GEN_PROCESS_GEN_WAV;
+ p.feats = &feats;
+ reserve_step(imgs, p);
+ } break;
+ case PROJECTOR_TYPE_MOSHI_GEN:
+ {
+ // one gen-audio step, the input of every gen step
+ const auto imgs = get_dummy_batch();
+ const int64_t n_q = model.gen_code_head_w->ne[2];
+ const int n_vocab = (int) model.gen_code_head_w->ne[1];
+ const std::vector<int32_t> codes_wav((size_t) mtmd_graph_moshi_gen::n_frames_max * n_q);
+ const std::vector<int32_t> codes_fb((size_t) n_q);
+ mtmd_subctx_encode_params p;
+ p.gen_process = MTMD_SUBCTX_GEN_PROCESS_GEN_WAV;
+ p.codes = &codes_wav;
+ reserve_step(imgs, p);
+ p.gen_process = MTMD_SUBCTX_GEN_PROCESS_GEN_CODE;
+ p.codes = &codes_fb;
+ reserve_step(imgs, p);
+ // greedy, then sampling with top-k over almost all and over all the vocab
+ p.codes = nullptr;
+ for (auto [top_k, temp] : {std::pair<int, float>{0, 0.0f}, {n_vocab - 1, 0.5f}, {0, 0.5f}}) {
+ p.top_k = top_k;
+ p.temp = temp;
+ reserve_step(imgs, p);
+ }
+ } break;
+ case PROJECTOR_TYPE_LFM3A_GEN:
+ {
+ // one gen-audio step, the input of every gen step
+ const auto imgs = get_dummy_batch();
+ const int64_t n_cb = model.gen_code_embd_w->ne[2];
+ const std::vector<int32_t> codes_wav((size_t) mtmd_graph_lfm3a_gen::n_frames_max * n_cb);
+ const std::vector<int32_t> codes_fb((size_t) n_cb);
+ mtmd_subctx_encode_params p;
+ p.gen_process = MTMD_SUBCTX_GEN_PROCESS_GEN_WAV;
+ p.codes = &codes_wav;
+ reserve_step(imgs, p);
+ // all codes known: only the feedback embedding
+ p.gen_process = MTMD_SUBCTX_GEN_PROCESS_GEN_CODE;
+ p.codes = &codes_fb;
+ reserve_step(imgs, p);
+ } break;
+ case PROJECTOR_TYPE_SOPRANO:
+ {
+ const std::vector<float> feats((size_t) mtmd_graph_soprano::n_frames_max * model.hparams.projection_dim, 0.0f);
+ mtmd_subctx_encode_params params;
+ params.gen_process = MTMD_SUBCTX_GEN_PROCESS_GEN_WAV;
+ params.feats = &feats;
+ reserve_step(batch1, params);
+ } break;
+ case PROJECTOR_TYPE_KOKORO:
+ {
+ using g = mtmd_graph_kokoro;
+ mtmd_subctx_encode_params params;
+ params.gen_process = MTMD_SUBCTX_GEN_PROCESS_GEN_WAV;
+ mtmd_subctx_kokoro_io io;
+ params.kokoro = &io;
+ io.stage = g::STAGE_TEXT;
+ io.n_tok = g::n_tok_max;
+ reserve_step(batch1, params);
+ io.stage = g::STAGE_F0N;
+ io.n_frames = g::n_frames_max;
+ reserve_step(batch1, params);
+ io.stage = g::STAGE_DEC;
+ io.n_har = g::n_har_of(g::n_frames_max);
+ reserve_step(batch1, params);
+ } break;
+ case PROJECTOR_TYPE_TINY_VOCA:
+ {
+ using g = mtmd_graph_tiny_voca;
+ const std::vector<float> tokens((size_t) g::n_max_tokens * model.hparams.n_embd, 0.0f);
+ const std::vector<float> frames((size_t) g::n_max_frames * model.hparams.n_embd, 0.0f);
+ mtmd_subctx_encode_params params;
+ params.gen_process = MTMD_SUBCTX_GEN_PROCESS_LATENT_IN;
+ params.feats = &tokens;
+ reserve_step(batch1, params);
+ params.gen_process = MTMD_SUBCTX_GEN_PROCESS_LATENT_OUT;
+ params.feats = &frames;
+ reserve_step(batch1, params);
+ } break;
+ case PROJECTOR_TYPE_DRAMA3_GEN:
+ {
+ using g = mtmd_graph_drama3_gen;
+ const size_t n_cb = (size_t) model.gen_code_embd_w->ne[2];
+ const std::vector<int32_t> forced(2 * n_cb, 0);
+ const std::vector<int32_t> frames(g::n_wav_frames_max * n_cb, 0);
+ mtmd_subctx_encode_params params;
+ // tower row with top-p over the whole vocab, then with the codes given (teacher forcing)
+ params.gen_process = MTMD_SUBCTX_GEN_PROCESS_GEN_CODE;
+ params.top_k = 0;
+ params.top_p = 0.5f;
+ reserve_step(batch1, params);
+ params.codes = &forced;
+ reserve_step(batch1, params);
+ params.gen_process = MTMD_SUBCTX_GEN_PROCESS_GEN_WAV;
+ params.codes = &frames;
+ reserve_step(batch1, params);
+ } break;
+ case PROJECTOR_TYPE_ZONOS3_GEN:
+ {
+ mtmd_subctx_encode_params params;
+ params.imgs = &batch1;
+ using g = mtmd_graph_zonos3_gen;
+ const std::vector<int32_t> codes((size_t) g::n_wav_frames_max * g::n_codebooks, 0);
+ params.codes = &codes;
+ params.gen_process = MTMD_SUBCTX_GEN_PROCESS_GEN_WAV;
+ reserve_step(batch1, params);
+ } break;
+ case PROJECTOR_TYPE_FISH_S2_GEN:
+ {
+ mtmd_subctx_encode_params params;
+ params.imgs = &batch1;
+ using g = mtmd_graph_fish_s2_gen;
+ const std::vector<int32_t> codes((size_t) g::n_wav_frames_max * model.gen_code_embd_w->ne[2], 0);
+ params.codes = &codes;
+ params.gen_process = MTMD_SUBCTX_GEN_PROCESS_GEN_WAV;
+ reserve_step(batch1, params);
+ } break;
+ case PROJECTOR_TYPE_VOXCPM2_GEN:
+ {
+ mtmd_subctx_encode_params params;
+ params.imgs = &batch1;
+ using g = mtmd_graph_voxcpm2_gen;
+ const int64_t n_text = model.n_mmproj_embd();
+ // RES_INP: n_rows_max audio rows, then the single row with the stop head
+ for (int n_rows : { g::n_rows_max, 1 }) {
+ mtmd_image_f32 rows;
+ rows.set_size({(int) n_text, n_rows}, false, true);
+ mtmd_image_f32_batch rows_batch;
+ rows_batch.is_audio = true;
+ rows_batch.entries.push_back(rows);
+ const std::vector<float> x((size_t) n_text * n_rows, 0.0f);
+ mtmd_subctx_encode_params p = params;
+ p.imgs = &rows_batch;
+ p.gen_process = MTMD_SUBCTX_GEN_PROCESS_RES_INP;
+ p.feats = &x;
+ reserve_step(rows_batch, p);
+ }
+ params.gen_process = MTMD_SUBCTX_GEN_PROCESS_GEN_CODE;
+ params.n_steps = g::n_steps_max;
+ reserve_step(batch1, params);
+ const std::vector<float> latent_in((size_t) g::n_rows_max * g::n_latent * g::n_patch, 0.0f);
+ params.gen_process = MTMD_SUBCTX_GEN_PROCESS_LATENT_IN;
+ params.feats = &latent_in;
+ reserve_step(batch1, params);
+ const std::vector<float> latents((size_t) g::n_wav_frames_max * g::n_latent * g::n_patch, 0.0f);
+ params.gen_process = MTMD_SUBCTX_GEN_PROCESS_GEN_WAV;
+ params.feats = &latents;
+ reserve_step(batch1, params);
+ } break;
+ case PROJECTOR_TYPE_CHATTERBOX:
+ {
+ using cbx = mtmd_graph_chatterbox;
+ const auto & batch = batch1;
+
+ // s3 tokenizer of the longest t3 reference clip
+ {
+ const auto mel = make_batch(cbx::t3_ref_sec_max_turbo * cbx::s3tok_frames_per_sec, 128);
+ mtmd_subctx_encode_params p;
+ p.imgs = &mel;
+ p.gen_process = MTMD_SUBCTX_GEN_PROCESS_TOKENIZE;
+ reserve_step(mel, p);
+ }
+
+ // flow + cfm over the longest reference and utterance
+ mtmd_gen_ref ref;
+ ref.tokens.resize(cbx::n_ref_tokens_max);
+ ref.feat.resize((size_t) 2 * 80 * cbx::n_ref_tokens_max);
+ const std::vector<int32_t> codes(cbx::n_gen_tokens_max);
+ {
+ mtmd_subctx_encode_params p;
+ p.imgs = &batch;
+ p.gen_process = MTMD_SUBCTX_GEN_PROCESS_TTS;
+ p.codes = &codes;
+ p.ref = &ref;
+ reserve_step(batch, p);
+ }
+
+ // vocoder of the generated mel frames
+ {
+ mtmd_subctx_encode_params p;
+ p.imgs = &batch;
+ p.gen_process = MTMD_SUBCTX_GEN_PROCESS_TTS_VOCODE;
+ p.vocode_n_mel = 2 * cbx::n_gen_tokens_max;
+ p.vocode_n_stft = p.vocode_n_mel * cbx::vocode_stft_per_mel + 1;
+ reserve_step(batch, p);
+ }
+ } break;
+ case PROJECTOR_TYPE_YUE2_GEN:
+ {
+ using g = mtmd_graph_yue2_gen;
+ const auto & batch = batch1;
+ auto reserve_rows = [&](mtmd_subctx_gen_process proc, size_t n_col, int n_rows) {
+ const std::vector<float> feats(n_col * n_rows);
+ mtmd_subctx_encode_params p;
+ p.imgs = &batch;
+ p.gen_process = proc;
+ p.feats = &feats;
+ reserve_step(batch, p);
+ };
+ reserve_rows(MTMD_SUBCTX_GEN_PROCESS_LATENT_IN, g::n_latent, g::n_proj_rows_max);
+ reserve_rows(MTMD_SUBCTX_GEN_PROCESS_LATENT_OUT, model.yue2.out_w->ne[0], g::n_proj_rows_max);
+ reserve_rows(MTMD_SUBCTX_GEN_PROCESS_GEN_WAV, g::n_latent, g::n_vae_rows_max);
+ } break;
+ case PROJECTOR_TYPE_MINIMAX_MUSIC3_GEN:
+ {
+ using g = mtmd_graph_music3_gen;
+ const auto & m = model.music3;
+ const auto & batch = batch1;
+ const size_t n_embd = (size_t) model.hparams.n_embd;
+ const size_t n_lat = (size_t) g::latent_frames(g::n_win_frames_max);
+ auto reserve_rows = [&](mtmd_subctx_gen_process proc, size_t n_values, float cfg_scale, float temp) {
+ const std::vector<float> feats(n_values);
+ mtmd_subctx_encode_params p;
+ p.imgs = &batch;
+ p.gen_process = proc;
+ p.feats = &feats;
+ p.cfg_scale = cfg_scale;
+ p.temp = temp;
+ reserve_step(batch, p);
+ };
+ // depth decoder with guidance (cond and uncond rows), greedy and sampling
+ reserve_rows(MTMD_SUBCTX_GEN_PROCESS_GEN_CODE, 2 * n_embd, g::depth_cfg, 0.0f);
+ reserve_rows(MTMD_SUBCTX_GEN_PROCESS_GEN_CODE, 2 * n_embd, g::depth_cfg, 1.0f);
+ // one window: condition, DiT step (cond and uncond batches), vocoder
+ reserve_rows(MTMD_SUBCTX_GEN_PROCESS_FLOW_COND, g::n_win_frames_max * n_embd, 1.0f, 1.0f);
+ reserve_rows(MTMD_SUBCTX_GEN_PROCESS_FLOW_STEP, n_lat * 2 * (size_t) m.pre_w->ne[0], g::dit_cfg, 1.0f);
+ reserve_rows(MTMD_SUBCTX_GEN_PROCESS_GEN_WAV, n_lat * g::n_latent, 1.0f, 1.0f);
+ } break;
+ default:
+ break;
+ }
+}
+
mtmd_subcontext::support_info_graph mtmd_subcontext::reserve_compute_meta(const mtmd_image_f32_batch & batch) {
ggml_cgraph * gf = mtmd_get_graph_builder(this, batch)->build();
ggml_backend_sched_reserve(backends.sched.get(), gf);
+ backends.last_graph_sig = 0;
const int n_splits = ggml_backend_sched_get_n_splits(backends.sched.get());
const int n_nodes = ggml_graph_n_nodes(gf);
@@ -271,6 +598,75 @@ mtmd_subcontext::support_info_graph mtmd_subcontext::reserve_compute_meta(const
return res;
}
+// the log-mel graph always has this many frames, so its compute buffer does not depend on the audio length
+static const int64_t MTMD_LOG_MEL_N_FRAMES = 2048;
+
+struct mtmd_log_mel_graph {
+ ggml_context_ptr ctx;
+ ggml_cgraph * gf = nullptr;
+ ggml_tensor * inp_samples = nullptr;
+ ggml_tensor * inp_dft = nullptr;
+ ggml_tensor * inp_filters = nullptr;
+ ggml_tensor * out = nullptr; // [MTMD_LOG_MEL_N_FRAMES, n_mel]
+};
+
+static mtmd_log_mel_graph mtmd_log_mel_build(const mtmd_audio_mel_config & config) {
+ const int64_t n_fft_bins = config.n_fft_bins;
+ const int64_t frame_size = (n_fft_bins - 1) * 2;
+ const int64_t n_mel = config.n_mel;
+ const int64_t n_frames = MTMD_LOG_MEL_N_FRAMES;
+
+ mtmd_log_mel_graph g;
+ ggml_init_params params = {
+ /*.mem_size =*/ ggml_tensor_overhead() * 32 + ggml_graph_overhead(),
+ /*.mem_buffer =*/ nullptr,
+ /*.no_alloc =*/ true,
+ };
+ g.ctx.reset(ggml_init(params));
+ ggml_context * ctx0 = g.ctx.get();
+
+ g.inp_samples = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, (n_frames - 1) * config.hop_length + frame_size);
+ g.inp_dft = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, frame_size, 2 * n_fft_bins);
+ g.inp_filters = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_fft_bins, n_mel);
+ ggml_set_input(g.inp_samples);
+ ggml_set_input(g.inp_dft);
+ ggml_set_input(g.inp_filters);
+
+ ggml_tensor * cur = ggml_cont(ctx0, ggml_view_2d(ctx0, g.inp_samples, frame_size, n_frames, config.hop_length * ggml_element_size(g.inp_samples), 0));
+ cur = ggml_mul_mat(ctx0, g.inp_dft, cur); // [2 * n_fft_bins, n_frames]
+ ggml_prec_set_src(cur, GGML_PREC_F32, 1);
+
+ cur = ggml_sqr(ctx0, cur);
+ cur = ggml_add(ctx0,
+ ggml_view_2d(ctx0, cur, n_fft_bins, n_frames, cur->nb[1], 0),
+ ggml_view_2d(ctx0, cur, n_fft_bins, n_frames, cur->nb[1], n_fft_bins * ggml_element_size(cur)));
+ if (config.use_magnitude) {
+ cur = ggml_sqrt(ctx0, cur);
+ }
+
+ cur = ggml_mul_mat(ctx0, cur, g.inp_filters); // [n_frames, n_mel]
+ ggml_prec_set_src(cur, GGML_PREC_F32, 1);
+ cur = config.mel_floor_add
+ ? ggml_scale_bias(ctx0, cur, 1.0f, config.mel_floor)
+ : ggml_clamp(ctx0, cur, config.mel_floor, FLT_MAX);
+ cur = ggml_log(ctx0, cur);
+ if (!config.use_natural_log) {
+ cur = ggml_scale(ctx0, cur, 1.0f / logf(10.0f));
+ }
+ ggml_set_output(cur);
+ g.out = cur;
+
+ g.gf = ggml_new_graph(ctx0);
+ ggml_build_forward_expand(g.gf, cur);
+ return g;
+}
+
+void mtmd_audio_log_mel_reserve(const mtmd_audio_mel_config & config) {
+ GGML_ASSERT(config.sched != nullptr && config.n_fft_bins > 0 && config.n_mel > 0 && config.hop_length > 0);
+ auto g = mtmd_log_mel_build(config);
+ ggml_backend_sched_reserve(config.sched, g.gf);
+}
+
bool mtmd_audio_log_mel(const mtmd_audio_mel_config & config, const float * samples, const float * window, int64_t n_frames, float * out) {
ggml_backend_sched_t sched = config.sched;
ggml_backend_t backend_cpu = ggml_backend_sched_get_backend(sched, ggml_backend_sched_get_n_backends(sched) - 1);
@@ -294,71 +690,39 @@ bool mtmd_audio_log_mel(const mtmd_audio_mel_config & config, const float * samp
}
}
- // the spectrum is several times larger than the result, so long audio is processed in blocks
- const int64_t n_frames_max = 8192;
-
- for (int64_t off = 0; off < n_frames; off += n_frames_max) {
- const int64_t n_cur = std::min(n_frames_max, n_frames - off);
-
- ggml_init_params params = {
- /*.mem_size =*/ ggml_tensor_overhead() * 32 + ggml_graph_overhead(),
- /*.mem_buffer =*/ nullptr,
- /*.no_alloc =*/ true,
- };
- ggml_context_ptr ctx_ptr(ggml_init(params));
- ggml_context * ctx0 = ctx_ptr.get();
-
- ggml_tensor * inp_samples = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, (n_cur - 1) * config.hop_length + frame_size);
- ggml_tensor * inp_dft = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, frame_size, 2 * n_fft_bins);
- ggml_tensor * inp_filters = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_fft_bins, n_mel);
- ggml_set_input(inp_samples);
- ggml_set_input(inp_dft);
- ggml_set_input(inp_filters);
-
- ggml_tensor * cur = ggml_cont(ctx0, ggml_view_2d(ctx0, inp_samples, frame_size, n_cur, config.hop_length * ggml_element_size(inp_samples), 0));
- cur = ggml_mul_mat(ctx0, inp_dft, cur); // [2 * n_fft_bins, n_cur]
- ggml_prec_set_src(cur, GGML_PREC_F32, 1);
-
- cur = ggml_sqr(ctx0, cur);
- cur = ggml_add(ctx0,
- ggml_view_2d(ctx0, cur, n_fft_bins, n_cur, cur->nb[1], 0),
- ggml_view_2d(ctx0, cur, n_fft_bins, n_cur, cur->nb[1], n_fft_bins * ggml_element_size(cur)));
- if (config.use_magnitude) {
- cur = ggml_sqrt(ctx0, cur);
- }
-
- cur = ggml_mul_mat(ctx0, cur, inp_filters); // [n_cur, n_mel]
- ggml_prec_set_src(cur, GGML_PREC_F32, 1);
- cur = config.mel_floor_add
- ? ggml_scale_bias(ctx0, cur, 1.0f, config.mel_floor)
- : ggml_clamp(ctx0, cur, config.mel_floor, FLT_MAX);
- cur = ggml_log(ctx0, cur);
- if (!config.use_natural_log) {
- cur = ggml_scale(ctx0, cur, 1.0f / logf(10.0f));
- }
- ggml_set_output(cur);
-
- ggml_cgraph * gf = ggml_new_graph(ctx0);
- ggml_build_forward_expand(gf, cur);
-
- ggml_backend_sched_reset(sched);
- if (!ggml_backend_sched_alloc_graph(sched, gf)) {
- LOG_ERR("%s: failed to allocate compute graph\n", __func__);
- return false;
- }
-
- ggml_backend_tensor_set(inp_samples, samples + off * config.hop_length, 0, ggml_nbytes(inp_samples));
- ggml_backend_tensor_set(inp_dft, dft.data(), 0, ggml_nbytes(inp_dft));
- ggml_backend_tensor_set(inp_filters, filters.data(), 0, ggml_nbytes(inp_filters));
+ // the graph is small, plan its layout every time: the last graph on the shared scheduler can have the same size
+ // the reserve splits the graph in place, so the graph to allocate is built again
+ if (!ggml_backend_sched_reserve(sched, mtmd_log_mel_build(config).gf)) {
+ LOG_ERR("%s: failed to reserve compute graph\n", __func__);
+ return false;
+ }
+ auto g = mtmd_log_mel_build(config);
+ ggml_backend_sched_reset(sched);
+ if (!ggml_backend_sched_alloc_graph(sched, g.gf)) {
+ LOG_ERR("%s: failed to allocate compute graph\n", __func__);
+ return false;
+ }
- auto status = ggml_backend_sched_graph_compute(sched, gf);
+ // the last block is zero-padded, only its first n_cur frames are read back
+ std::vector<float> block(ggml_nelements(g.inp_samples));
+ for (int64_t off = 0; off < n_frames; off += MTMD_LOG_MEL_N_FRAMES) {
+ const int64_t n_cur = std::min(MTMD_LOG_MEL_N_FRAMES, n_frames - off);
+ const size_t n_samples = (size_t) ((n_cur - 1) * config.hop_length + frame_size);
+ std::fill(block.begin(), block.end(), 0.0f);
+ std::copy(samples + off * config.hop_length, samples + off * config.hop_length + n_samples, block.begin());
+ ggml_backend_tensor_set(g.inp_samples, block.data(), 0, ggml_nbytes(g.inp_samples));
+ // the input buffers may be reused by later nodes, so set all the inputs for each block
+ ggml_backend_tensor_set(g.inp_dft, dft.data(), 0, ggml_nbytes(g.inp_dft));
+ ggml_backend_tensor_set(g.inp_filters, filters.data(), 0, ggml_nbytes(g.inp_filters));
+
+ auto status = ggml_backend_sched_graph_compute(sched, g.gf);
if (status != GGML_STATUS_SUCCESS) {
LOG_ERR("%s: ggml_backend_sched_graph_compute failed with error %d\n", __func__, status);
return false;
}
for (int64_t j = 0; j < n_mel; j++) {
- ggml_backend_tensor_get(cur, out + j * n_frames + off, j * cur->nb[1], n_cur * ggml_element_size(cur));
+ ggml_backend_tensor_get(g.out, out + j * n_frames + off, j * g.out->nb[1], n_cur * ggml_element_size(g.out));
}
}
@@ -539,6 +903,10 @@ bool mtmd_subcontext::encode_kokoro(mtmd_subctx_encode_params * params) {
LOG_ERR("%s: expected a voice row of %d values, then %d values for each of the %d tokens\n", __func__, 2 * n_style, n_embd, n_tok);
return false;
}
+ if (n_tok > mtmd_graph_kokoro::n_tok_max) {
+ LOG_ERR("%s: %d tokens, at most %d are allowed, split the text\n", __func__, n_tok, mtmd_graph_kokoro::n_tok_max);
+ return false;
+ }
const int64_t n_vocab = model.cbx_tensors.at("a.gen.text.embedding.weight")->ne[1];
for (int32_t t : tokens) {
if (t < 0 || t >= n_vocab) {
@@ -571,6 +939,10 @@ bool mtmd_subcontext::encode_kokoro(mtmd_subctx_encode_params * params) {
std::vector<float> shared, asr;
const int n_frames = mtmd_graph_kokoro::prosody(model, bert, n_embd, text_cnn.data(), n_tok, style_pred.data(), params->speed, shared, asr);
+ if (n_frames > mtmd_graph_kokoro::n_frames_max) {
+ LOG_ERR("%s: the utterance has %d frames, at most %d are allowed, split the text or raise the speed\n", __func__, n_frames, mtmd_graph_kokoro::n_frames_max);
+ return false;
+ }
std::vector<float> f0, en;
{
@@ -606,6 +978,56 @@ bool mtmd_subcontext::encode_kokoro(mtmd_subctx_encode_params * params) {
return true;
}
+// max number of input values (codes or feats) of one GEN_WAV graph, 0 = no bound
+static size_t gen_wav_piece_size(const mtmd_model & model) {
+ switch (model.proj_type) {
+ case PROJECTOR_TYPE_POCKETTTS_GEN: return (size_t) mtmd_graph_pockettts_gen::n_frames_max * model.gen_input_lin_w->ne[0];
+ case PROJECTOR_TYPE_MOSHI_GEN: return (size_t) mtmd_graph_moshi_gen::n_frames_max * model.gen_code_head_w->ne[2];
+ case PROJECTOR_TYPE_LFM3A_GEN: return (size_t) mtmd_graph_lfm3a_gen::n_frames_max * model.gen_code_embd_w->ne[2];
+ case PROJECTOR_TYPE_DRAMA3_GEN: return (size_t) mtmd_graph_drama3_gen::n_wav_frames_max * model.gen_code_embd_w->ne[2];
+ case PROJECTOR_TYPE_ZONOS3_GEN: return (size_t) mtmd_graph_zonos3_gen::n_wav_frames_max * mtmd_graph_zonos3_gen::n_codebooks;
+ case PROJECTOR_TYPE_FISH_S2_GEN: return (size_t) mtmd_graph_fish_s2_gen::n_wav_frames_max * model.gen_code_embd_w->ne[2];
+ case PROJECTOR_TYPE_VOXCPM2_GEN: return (size_t) mtmd_graph_voxcpm2_gen::n_wav_frames_max * mtmd_graph_voxcpm2_gen::n_latent * mtmd_graph_voxcpm2_gen::n_patch;
+ default: return 0;
+ }
+}
+
+// the decoder is streaming, so the gen state carries over between the pieces
+bool mtmd_subcontext::encode_gen_wav_pieces(mtmd_subctx_encode_params * params, size_t n_piece) {
+ const size_t n_in = params->feats ? params->feats->size() : params->codes->size();
+ std::vector<float> audio;
+ std::vector<float> feats;
+ for (size_t off = 0; off < n_in; off += n_piece) {
+ const size_t n = std::min(n_piece, n_in - off);
+ std::vector<float> in_feats;
+ std::vector<int32_t> in_codes;
+ std::vector<float> out_audio;
+ std::vector<float> out_feats;
+ mtmd_subctx_encode_params p = *params;
+ if (params->feats) {
+ in_feats.assign(params->feats->begin() + off, params->feats->begin() + off + n);
+ p.feats = &in_feats;
+ } else {
+ in_codes.assign(params->codes->begin() + off, params->codes->begin() + off + n);
+ p.codes = &in_codes;
+ }
+ p.out_audio = params->out_audio ? &out_audio : nullptr;
+ p.out_feats = params->out_feats ? &out_feats : nullptr;
+ if (!encode(&p)) {
+ return false;
+ }
+ audio.insert(audio.end(), out_audio.begin(), out_audio.end());
+ feats.insert(feats.end(), out_feats.begin(), out_feats.end());
+ }
+ if (params->out_audio) {
+ *params->out_audio = std::move(audio);
+ }
+ if (params->out_feats) {
+ *params->out_feats = std::move(feats);
+ }
+ return true;
+}
+
bool mtmd_subcontext::encode(mtmd_subctx_encode_params * params) {
const mtmd_image_f32_batch & imgs = *params->imgs;
int n_batch_cur = imgs.entries.size();
@@ -624,6 +1046,17 @@ bool mtmd_subcontext::encode(mtmd_subctx_encode_params * params) {
if (model.proj_type == PROJECTOR_TYPE_KOKORO && !params->kokoro) {
return encode_kokoro(params);
}
+ if (model.proj_type == PROJECTOR_TYPE_LFM3A && imgs.entries[0].nx() > mtmd_graph_lfm3a::max_frames) {
+ return mtmd_graph_lfm3a::encode_pieces(this, params);
+ }
+
+ if (params->gen_process == MTMD_SUBCTX_GEN_PROCESS_GEN_WAV) {
+ const size_t n_piece = gen_wav_piece_size(model);
+ const size_t n_in = params->feats ? params->feats->size() : params->codes ? params->codes->size() : 0;
+ if (n_piece > 0 && n_in > n_piece) {
+ return encode_gen_wav_pieces(params, n_piece);
+ }
+ }
const bool needs_gen_state = params->gen_process == MTMD_SUBCTX_GEN_PROCESS_GEN_CODE ||
params->gen_process == MTMD_SUBCTX_GEN_PROCESS_GEN_WAV ||
@@ -642,14 +1075,16 @@ bool mtmd_subcontext::encode(mtmd_subctx_encode_params * params) {
}
// build the inference graph
- ggml_backend_sched_reset(backends.sched.get());
- ggml_cgraph * gf = mtmd_get_graph_builder(this, imgs, params)->build();
-
// the last node is the embedding tensor, code2wav has no out_embd
// read it before scheduling: backends may reorder the nodes of graphs with several outputs (Metal)
- ggml_tensor * embeddings = params->out_embd ? ggml_graph_node(gf, -1) : nullptr;
-
- if (!ggml_backend_sched_alloc_graph(backends.sched.get(), gf)) {
+ ggml_tensor * embeddings = nullptr;
+ ggml_backend_sched_reset(backends.sched.get());
+ ggml_cgraph * gf = backends.alloc_graph([&]() {
+ ggml_cgraph * g = mtmd_get_graph_builder(this, imgs, params)->build();
+ embeddings = params->out_embd ? ggml_graph_node(g, -1) : nullptr;
+ return g;
+ });
+ if (!gf) {
LOG_ERR("%s: failed to allocate compute graph\n", __func__);
return false;
}
@@ -2037,6 +2472,10 @@ bool mtmd_subcontext::encode(mtmd_subctx_encode_params * params) {
std::vector<int32_t> inp_pos = { (int32_t) pos };
set_input_i32("inp_pos", inp_pos);
+ std::vector<float> mask(mtmd_graph_drama3_gen::n_kv_read((int) pos), -INFINITY);
+ std::fill(mask.begin(), mask.begin() + (int) pos + 1, 0.0f);
+ set_input_attn_mask(mask);
+
if (forced) {
std::vector<int32_t> force(model.gen_code_head_w->ne[2]);
for (size_t ih = 0; ih < force.size(); ih++) {
@@ -2513,9 +2952,10 @@ bool mtmd_subcontext::encode(mtmd_subctx_encode_params * params) {
std::vector<float> mask((size_t) context_size * (size_t) context_size * (size_t) num_blocks, 0.0f);
const float neg_inf = -INFINITY;
const size_t last_block_offset = (size_t) (num_blocks - 1) * (size_t) context_size * (size_t) context_size;
+ // mask only the padding keys: a fully masked row gives NaN, the padding queries are dropped after the attention
for (int q = 0; q < context_size; q++) {
for (int k = 0; k < context_size; k++) {
- if (q >= remainder || k >= remainder) {
+ if (k >= remainder) {
mask[last_block_offset + (size_t) q * (size_t) context_size + (size_t) k] = neg_inf;
}
}
@@ -2942,11 +3382,6 @@ bool mtmd_subcontext::encode(mtmd_subctx_encode_params * params) {
out_audio.resize(ggml_nelements(audio));
ggml_backend_tensor_get(audio, out_audio.data(), 0, ggml_nbytes(audio));
- if (model.proj_type == PROJECTOR_TYPE_SOPRANO) {
- std::vector<float> spectrum = std::move(out_audio);
- mtmd_graph_soprano::decode_spectrum(model, spectrum, out_audio);
- }
-
// drop the tail audio that comes from the code-0 rear padding, drama3, fish_s2, yue2 and minimax_music3 have no padding
if (model.proj_type != PROJECTOR_TYPE_DRAMA3_GEN && model.proj_type != PROJECTOR_TYPE_FISH_S2_GEN && model.proj_type != PROJECTOR_TYPE_YUE2_GEN &&
model.proj_type != PROJECTOR_TYPE_MINIMAX_MUSIC3_GEN) {
diff --git a/tools/mtmd/mtmd-subcontext.h b/tools/mtmd/mtmd-subcontext.h
index 853268bc8..d4503a14b 100644
--- a/tools/mtmd/mtmd-subcontext.h
+++ b/tools/mtmd/mtmd-subcontext.h
@@ -12,6 +12,7 @@
#include <map>
#include <memory>
#include <random>
+#include <functional>
#include <vector>
// !!! Internal header, to be used by mtmd only !!!
@@ -46,6 +47,18 @@ struct mtmd_backends {
// its buffers fit the largest graph reserved by the subcontexts
ggml_backend_sched_ptr sched;
+ // reallocations of a graph with the same size as the previous one, the GGML_SCHED_NO_REALLOC builds abort on them
+ int32_t n_reallocs_unexpected = 0;
+
+ // shapes of the last allocated graph, see alloc_graph()
+ uint64_t last_graph_sig = 0;
+
+ // build a graph and allocate it in the buffers reserved by the warmup
+ // the graphs change shape with the input, so a graph can need another layout than the last graph with the same size:
+ // in that case its layout is planned first, the buffers only grow if the graph is bigger than the warmup graphs
+ // the reserve splits the graph in place, so the graph to allocate is built again after it
+ ggml_cgraph * alloc_graph(const std::function<ggml_cgraph * ()> & build);
+
// device nullptr means CPU
mtmd_backends(ggml_backend_dev_t device, int n_threads, int max_nodes,
ggml_backend_sched_eval_callback cb_eval, void * cb_eval_user_data);
@@ -62,6 +75,9 @@ struct mtmd_backends {
struct mtmd_audio_mel_config;
bool mtmd_audio_log_mel(const mtmd_audio_mel_config & config, const float * samples, const float * window, int64_t n_frames, float * out);
+// reserve the compute buffer of the log-mel graph, call it during the warmup
+void mtmd_audio_log_mel_reserve(const mtmd_audio_mel_config & config);
+
enum mtmd_subctx_gen_process {
MTMD_SUBCTX_GEN_PROCESS_GEN_UNKNOWN,
MTMD_SUBCTX_GEN_PROCESS_GEN_CODE, // h_state to codes
@@ -230,6 +246,14 @@ private:
// kokoro GEN_WAV: codes are the phoneme tokens, feats the voice row followed by the backbone state of each token
bool encode_kokoro(mtmd_subctx_encode_params * params);
+ // GEN_WAV input longer than the reserved graph: n_piece input values per graph
+ bool encode_gen_wav_pieces(mtmd_subctx_encode_params * params, size_t n_piece);
+
// only initialize backend buffers, but do not allocate them yet
support_info_graph reserve_compute_meta(const mtmd_image_f32_batch & batch);
+
+ // reserve the worst-case graph of every step the model can run, besides the one of get_dummy_batch()
+ // each step is reserved with reserve_step(), so that no encode() needs a bigger compute buffer than the warmup
+ void warmup_steps();
+ void reserve_step(const mtmd_image_f32_batch & imgs, const mtmd_subctx_encode_params & params);
};
diff --git a/tools/mtmd/mtmd.cpp b/tools/mtmd/mtmd.cpp
index 5c5c671d0..0be3e2596 100644
--- a/tools/mtmd/mtmd.cpp
+++ b/tools/mtmd/mtmd.cpp
@@ -1039,7 +1039,7 @@ struct mtmd_context {
init_vision();
}
if (ctx_a) {
- init_audio();
+ init_audio(ctx_params.warmup);
}
}
@@ -1427,7 +1427,7 @@ struct mtmd_context {
GGML_ASSERT(image_preproc != nullptr);
}
- void init_audio() {
+ void init_audio(bool warmup) {
GGML_ASSERT(ctx_a != nullptr);
audio_preproc.reset();
@@ -1581,6 +1581,10 @@ struct mtmd_context {
audio_preproc->mel_config.n_threads = n_threads;
audio_preproc->mel_config.sched = backends->sched.get();
audio_preproc->initialize();
+ // only the preprocessors that use the log-mel graph fill n_fft_bins
+ if (audio_preproc->mel_config.n_fft_bins > 0 && warmup) {
+ mtmd_audio_log_mel_reserve(audio_preproc->mel_config);
+ }
}
}
@@ -3279,15 +3283,24 @@ static int32_t voxcpm2_ref_encode(mtmd_context * ctx, const mtmd_audio_tokens *
batch.is_audio = true;
batch.entries.push_back(std::move(dummy));
- mtmd_subctx_encode_params params;
- params.imgs = &batch;
- params.n_threads = ctx->n_threads;
- params.gen_process = MTMD_SUBCTX_GEN_PROCESS_LATENT_IN;
- params.feats = &latents;
- params.out_feats = &out_embd;
- if (!ctx->ctx_gen_a->encode(¶ms)) {
- LOG_ERR("%s: encode failed (LocEnc)\n", __func__);
- return 1;
+ // LocEnc reads each patch alone, so the patches go in pieces of n_rows_max
+ const size_t n_frame = g::n_latent * g::n_patch;
+ out_embd.clear();
+ for (size_t i = 0; i < latents.size(); i += n_frame * g::n_rows_max) {
+ const size_t n = std::min(n_frame * g::n_rows_max, latents.size() - i);
+ const std::vector<float> piece(latents.begin() + i, latents.begin() + i + n);
+ std::vector<float> piece_out;
+ mtmd_subctx_encode_params params;
+ params.imgs = &batch;
+ params.n_threads = ctx->n_threads;
+ params.gen_process = MTMD_SUBCTX_GEN_PROCESS_LATENT_IN;
+ params.feats = &piece;
+ params.out_feats = &piece_out;
+ if (!ctx->ctx_gen_a->encode(¶ms)) {
+ LOG_ERR("%s: encode failed (LocEnc)\n", __func__);
+ return 1;
+ }
+ out_embd.insert(out_embd.end(), piece_out.begin(), piece_out.end());
}
return 0;
}
@@ -3754,12 +3767,28 @@ static int32_t mtmd_gen_flow_yue2(mtmd_context * ctx, mtmd_gen_state * state, co
return o;
};
+ // the projections are per row, run them in passes of at most n_proj_rows_max rows
+ std::vector<float> piece_in, piece_out;
+ auto encode_rows = [&](mtmd_subctx_gen_process proc, const std::vector<float> & in, std::vector<float> & res) -> bool {
+ const size_t n_col = in.size() / (size_t) n_rows;
+ res.clear();
+ for (int64_t r0 = 0; r0 < n_rows; r0 += g::n_proj_rows_max) {
+ const int64_t r1 = std::min<int64_t>(r0 + g::n_proj_rows_max, n_rows);
+ piece_in.assign(in.begin() + r0 * n_col, in.begin() + r1 * n_col);
+ if (!gen_encode_rows(ctx, state, proc, piece_in, piece_out)) {
+ return false;
+ }
+ res.insert(res.end(), piece_out.begin(), piece_out.end());
+ }
+ return true;
+ };
+
llama_batch_ext_ptr batch(llama_batch_ext_init(lctx.get()));
std::vector<float> x_rows((size_t) (n_rows * g::n_latent), 0.0f);
std::vector<float> embd, hidden, vel;
auto velocity = [&](const std::vector<float> & x, double t, std::vector<float> & v) -> bool {
std::copy(x.begin(), x.end(), x_rows.begin() + g::n_latent); // the start and end rows stay 0
- if (!gen_encode_rows(ctx, state, MTMD_SUBCTX_GEN_PROCESS_LATENT_IN, x_rows, embd)) {
+ if (!encode_rows(MTMD_SUBCTX_GEN_PROCESS_LATENT_IN, x_rows, embd)) {
return false;
}
const std::vector<float> temb = time_embd(t);
@@ -3785,7 +3814,7 @@ static int32_t mtmd_gen_flow_yue2(mtmd_context * ctx, mtmd_gen_state * state, co
const float * h = llama_get_embeddings(lctx.get());
hidden.assign(h, h + n_rows * n_embd);
llama_memory_seq_rm(mem, 0, (llama_pos) n_past, -1);
- if (!gen_encode_rows(ctx, state, MTMD_SUBCTX_GEN_PROCESS_LATENT_OUT, hidden, vel)) {
+ if (!encode_rows(MTMD_SUBCTX_GEN_PROCESS_LATENT_OUT, hidden, vel)) {
return false;
}
v.assign(vel.begin() + g::n_latent, vel.end() - g::n_latent);
@@ -3881,6 +3910,10 @@ static int32_t mtmd_gen_wav_tiny_voca(mtmd_context * ctx, mtmd_gen_state * state
LOG_ERR("%s: tiny_voca requires the phoneme tokens, the voice row and the encoder state of each token\n", __func__);
return 1;
}
+ if (n_tok > g::n_max_tokens) {
+ LOG_ERR("%s: the utterance has %lld tokens, at most %d are allowed, split the text\n", __func__, (long long) n_tok, g::n_max_tokens);
+ return 1;
+ }
if (!std::isfinite(inp->speed) || inp->speed < 0.25f || inp->speed > 4.0f) {
LOG_ERR("%s: speed must be between 0.25 and 4\n", __func__);
return 1;
@@ -3978,6 +4011,54 @@ static int32_t mtmd_gen_wav_tiny_voca(mtmd_context * ctx, mtmd_gen_state * state
return 0;
}
+// soprano GEN_WAV: hidden states -> STFT frames -> waveform
+// a long input is decoded in pieces, each with enough context frames on both sides to match one pass over the whole input
+static int32_t mtmd_gen_wav_soprano(mtmd_context * ctx, mtmd_gen_state * state, const mtmd_gen_inp * inp, mtmd_gen_out * out) {
+ using g = mtmd_graph_soprano;
+ const auto & model = ctx->ctx_gen_a->model;
+ const size_t n_embd = (size_t) model.n_mmproj_embd();
+ if (inp->type != MTMD_GEN_PROCESS_TYPE_GEN_WAV || !inp->feats || inp->n_feats < 2 * n_embd || inp->n_feats % n_embd != 0 || inp->codes) {
+ LOG_ERR("%s: soprano requires at least 2 frames of features, without codes\n", __func__);
+ return 1;
+ }
+ const int64_t n_frames = (int64_t) (inp->n_feats / n_embd);
+ const int64_t n_row = model.vocos.output_w->ne[1];
+
+ // receptive field of the convs on the upsampled frames, then in input frames
+ int64_t n_ctx_up = ggml_n_dims(model.vocos.input_w) == 3 ? model.vocos.input_w->ne[0] / 2 : 0;
+ for (const auto & b : model.vocos.blocks) {
+ n_ctx_up += b.dwconv_w->ne[0] / 2;
+ }
+ const int64_t n_ctx = (n_ctx_up + g::upscale - 1) / g::upscale;
+ const int64_t n_core = g::n_frames_max - 2 * n_ctx - 1;
+ GGML_ASSERT(n_core > 0);
+
+ // a piece outputs the upsampled frames [upscale * s, upscale * e), the last one also the final frame
+ std::vector<float> spectrum;
+ std::vector<float> spec;
+ for (int64_t s = 0; s < n_frames - 1;) {
+ const int64_t a = std::max<int64_t>(0, s - n_ctx);
+ const bool last = n_frames - a <= g::n_frames_max;
+ const int64_t e = last ? n_frames - 1 : s + n_core;
+ const int64_t b = std::min(n_frames - 1, e + n_ctx);
+ const std::vector<float> feats(inp->feats + a * n_embd, inp->feats + (b + 1) * n_embd);
+ if (!gen_encode_rows(ctx, state, MTMD_SUBCTX_GEN_PROCESS_GEN_WAV, feats, spec)) {
+ LOG_ERR("%s: encode failed (gen_wav)\n", __func__);
+ return 1;
+ }
+ const int64_t r0 = g::upscale * (s - a);
+ const int64_t r1 = g::upscale * (e - a) + (last ? 1 : 0);
+ GGML_ASSERT((int64_t) spec.size() >= r1 * n_row);
+ spectrum.insert(spectrum.end(), spec.begin() + r0 * n_row, spec.begin() + r1 * n_row);
+ s = e;
+ }
+
+ g::decode_spectrum(model, spectrum, state->out_audio);
+ out->audio = state->out_audio.data();
+ out->n_samples = state->out_audio.size();
+ return 0;
+}
+
// yue2 GEN_WAV: latents -> interleaved stereo PCM in one VAE pass, the caller splits a long song into tiles
static int32_t mtmd_gen_wav_yue2(mtmd_context * ctx, mtmd_gen_state * state, const mtmd_gen_inp * inp, mtmd_gen_out * out) {
using g = mtmd_graph_yue2_gen;
@@ -3985,6 +4066,11 @@ static int32_t mtmd_gen_wav_yue2(mtmd_context * ctx, mtmd_gen_state * state, con
LOG_ERR("%s: yue2 needs whole latent frames\n", __func__);
return 1;
}
+ // the VAE has no state across calls, the caller tiles a long song with overlaps
+ if (inp->n_feats / g::n_latent > (size_t) g::n_vae_rows_max) {
+ LOG_ERR("%s: too many latent frames (%zu, max %d per call)\n", __func__, inp->n_feats / g::n_latent, g::n_vae_rows_max);
+ return 1;
+ }
const std::vector<float> feats(inp->feats, inp->feats + inp->n_feats);
auto & audio = state->out_audio;
if (!gen_encode_rows(ctx, state, MTMD_SUBCTX_GEN_PROCESS_GEN_WAV, feats, audio)) {
@@ -4034,25 +4120,34 @@ static int32_t mtmd_gen_code_voxcpm2(mtmd_context * ctx, mtmd_gen_state * state,
};
// FSQ (audio rows), residual LM inputs, and the stop score of a single row
- mtmd_image_f32_batch batch = make_batch(inp->embd, n_rows);
- std::vector<float> x_rows;
- if (inp->feats) {
- x_rows.assign(inp->feats, inp->feats + n_text * n_rows);
- }
+ // the rows are independent, so the prompt rows go in pieces of n_rows_max
std::vector<float> res_out; // residual LM input rows, then the (FSQ'd) hidden states
bool is_eos = false;
{
- mtmd_subctx_encode_params params;
- params.imgs = &batch;
- params.n_threads = ctx->n_threads;
- params.gen_process = MTMD_SUBCTX_GEN_PROCESS_RES_INP;
- params.feats = inp->feats ? &x_rows : nullptr;
- params.out_feats = &res_out;
- params.out_is_eos = &is_eos;
- if (!sctx->encode(¶ms)) {
- LOG_ERR("%s: encode failed (res_inp)\n", __func__);
- return 1;
+ std::vector<float> h_rows;
+ for (int i0 = 0; i0 < n_rows; i0 += g::n_rows_max) {
+ const int n = std::min(g::n_rows_max, n_rows - i0);
+ mtmd_image_f32_batch piece = make_batch(inp->embd + (size_t) i0 * n_text, n);
+ std::vector<float> x_rows;
+ if (inp->feats) {
+ x_rows.assign(inp->feats + (size_t) i0 * n_text, inp->feats + (size_t) (i0 + n) * n_text);
+ }
+ std::vector<float> piece_out;
+ mtmd_subctx_encode_params params;
+ params.imgs = &piece;
+ params.n_threads = ctx->n_threads;
+ params.gen_process = MTMD_SUBCTX_GEN_PROCESS_RES_INP;
+ params.feats = inp->feats ? &x_rows : nullptr;
+ params.out_feats = &piece_out;
+ params.out_is_eos = &is_eos;
+ if (!sctx->encode(¶ms)) {
+ LOG_ERR("%s: encode failed (res_inp)\n", __func__);
+ return 1;
+ }
+ res_out.insert(res_out.end(), piece_out.begin(), piece_out.begin() + (size_t) n * n_text);
+ h_rows.insert(h_rows.end(), piece_out.begin() + (size_t) n * n_text, piece_out.end());
}
+ res_out.insert(res_out.end(), h_rows.begin(), h_rows.end());
}
// residual LM, causal over all the rows of the sequence
@@ -4087,7 +4182,7 @@ static int32_t mtmd_gen_code_voxcpm2(mtmd_context * ctx, mtmd_gen_state * state,
const float * r = llama_get_embeddings_ith(lctx, -1);
std::vector<float> rows(res_out.begin() + n_text, res_out.end());
rows.insert(rows.end(), r, r + n_text);
- batch = make_batch(rows.data(), 2);
+ mtmd_image_f32_batch batch = make_batch(rows.data(), 2);
std::vector<float> next_embd(n_text);
std::vector<float> patch;
{
@@ -4183,6 +4278,11 @@ static int32_t mtmd_gen_wav_music3(mtmd_context * ctx, mtmd_gen_state * state, c
LOG_ERR("%s: minimax_music3 needs whole condition rows\n", __func__);
return 1;
}
+ // the DiT attends over the whole window, the caller splits a song into overlapping windows
+ if (inp->n_feats / n_embd > (size_t) g::n_win_frames_max) {
+ LOG_ERR("%s: window too long (%zu frames, max %d)\n", __func__, inp->n_feats / n_embd, g::n_win_frames_max);
+ return 1;
+ }
const std::vector<float> rows(inp->feats, inp->feats + inp->n_feats);
std::vector<float> cond;
@@ -4328,11 +4428,7 @@ static int32_t mtmd_gen_audio_process_impl(mtmd_context * ctx, mtmd_gen_state *
}
if (sctx->model.proj_type == PROJECTOR_TYPE_SOPRANO) {
- const size_t n_embd = (size_t) sctx->model.n_mmproj_embd();
- if (inp->type != MTMD_GEN_PROCESS_TYPE_GEN_WAV || !inp->feats || inp->n_feats < 2 * n_embd || inp->n_feats % n_embd != 0 || inp->codes) {
- LOG_ERR("%s: soprano requires at least 2 frames of features, without codes\n", __func__);
- return 1;
- }
+ return mtmd_gen_wav_soprano(ctx, state, inp, out);
}
if (sctx->model.proj_type == PROJECTOR_TYPE_KOKORO) {
@@ -4447,6 +4543,17 @@ static int32_t mtmd_gen_audio_process_impl(mtmd_context * ctx, mtmd_gen_state *
LOG_ERR("%s: gen_wav needs a voice reference, see mtmd_gen_state_set_ref()\n", __func__);
return 1;
}
+ // the flow decoder runs the whole utterance in one graph, its size is bounded at warmup
+ using cbx = mtmd_graph_chatterbox;
+ if (inp->n_codes > (size_t) cbx::n_gen_tokens_max) {
+ LOG_ERR("%s: too many speech tokens (%zu, max %d)\n", __func__, inp->n_codes, cbx::n_gen_tokens_max);
+ return 1;
+ }
+ if (state->ref.tokens.size() > (size_t) cbx::n_ref_tokens_max || state->ref.feat.size() != 2 * 80 * state->ref.tokens.size()) {
+ LOG_ERR("%s: unexpected voice reference (%zu tokens, max %d, %zu mel values)\n", __func__,
+ state->ref.tokens.size(), cbx::n_ref_tokens_max, state->ref.feat.size());
+ return 1;
+ }
std::vector<int32_t> in_codes(inp->codes, inp->codes + inp->n_codes);
// the batch entry is unused, present to satisfy the encode interface
@@ -5366,6 +5473,18 @@ static void stub_log_callback(enum ggml_log_level, const char *, void *) {
// do nothing
}
+int32_t mtmd_get_n_reallocs_unexpected(const mtmd_context * ctx) {
+ return ctx->backends->n_reallocs_unexpected;
+}
+
+size_t mtmd_get_compute_buffer_size(const mtmd_context * ctx) {
+ size_t res = 0;
+ for (const auto & [dev, size] : ctx->backends->get_mem_compute()) {
+ res += size;
+ }
+ return res;
+}
+
mtmd_memory_usage mtmd_get_memory_usage(const char * mmproj_fname,
struct mtmd_context_params ctx_params) {
mtmd::context_ptr ctx;
diff --git a/tools/server/tests/unit/test_realtime.py b/tools/server/tests/unit/test_realtime.py
index c22d58128..5af63a98e 100644
--- a/tools/server/tests/unit/test_realtime.py
+++ b/tools/server/tests/unit/test_realtime.py
@@ -81,14 +81,11 @@ def session_update(ws: Connection, **session) -> dict:
# live transcription
#
-# [TAG_MTMD_NO_REALLOC] TODO: mtmd reallocs its graphs on audio stream steps
-skip_no_realloc = pytest.mark.skipif(is_no_realloc(), reason="mtmd: graph realloc on audio stream step")
-
LIVE_ASR = [
# a chat model with an "asr" chat template, live only in sessions opened with ?intent=transcription
("tinylfm3omni", "/v1/realtime?intent=transcription"),
# no chat, the text follows the audio by a few tokens
- pytest.param("tinyvoxtralrt", "/v1/realtime", marks=skip_no_realloc),
+ ("tinyvoxtralrt", "/v1/realtime"),
]
@@ -122,7 +119,6 @@ def test_live_asr(preset: str, path: str):
assert all(len(text) > 0 for _, text in transcripts)
-@skip_no_realloc
@pytest.mark.parametrize("preset,path", LIVE_ASR)
def test_live_asr_chunked_audio(preset: str, path: str):
start_live_asr(preset)
@@ -172,7 +168,6 @@ def test_live_asr_invalid_events(preset: str, path: str):
assert len(get_transcripts(recv_all(ws))) == 1
-@skip_no_realloc
def test_live_asr_depends_on_audio():
# the random weights of this model give a different text for each input
start_live_asr("tinyvoxtralrt")
diff --git a/tools/server/tests/utils.py b/tools/server/tests/utils.py
index a67aa8117..ff7158362 100644
--- a/tools/server/tests/utils.py
+++ b/tools/server/tests/utils.py
@@ -927,11 +927,6 @@ def is_slow_test_allowed():
return os.environ.get("SLOW_TESTS") == "1" or os.environ.get("SLOW_TESTS") == "ON"
-# [TAG_MTMD_NO_REALLOC] TODO @ngxson : remove when mtmd side is fixed
-def is_no_realloc():
- return os.environ.get("GGML_SCHED_NO_REALLOC") in ("1", "ON") or os.environ.get("GGML_SCHED_DEBUG_REALLOC", "0") != "0"
-
-
def make_pcm16(seconds: float = 1.0, rate: int = 16000, freq: float = 440.0) -> bytes:
""" sine tone as raw PCM16 mono samples """
n = int(seconds * rate)