Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

feat(glm53): wire the vision tower into the engine, validated end to end

JustVuggd85799dbbed0
diff --git a/c/glm53.c b/c/glm53.c
index fcbf39db..66f3fd4b 100644
--- a/c/glm53.c
+++ b/c/glm53.c
@@ -574,6 +574,7 @@ int main(int argc, char **argv) {
* che i token siano quelli giusti, provati contro l'oracolo. */
#include "delta_attention.h"
#include "sparse_index.h"
+#include "vision_tower.h"
typedef struct { const float *w; int rows, columns; } Mat;
@@ -601,6 +602,10 @@ typedef struct {
const float *embed, *final_norm, *head;
GLayer *layer;
char prefix[64];
+ /* torre vision: presente solo se il checkpoint la porta */
+ int has_vision;
+ ColiVisionTower vision;
+ ColiVisionBlock *vblocks;
} GModel;
static const float *load_f32(GModel *m, const char *fmt, ...) {
@@ -774,6 +779,15 @@ static void mla_layer(const Cfg *c, const GLayer *l, const float *x, int tokens,
c->index_kpool_tail)) {
fprintf(stderr, "selezione indexer fallita\n"); exit(1);
}
+ /* GLM53_DUMP_INDEX=1 stampa le righe scelte dall'indexer: e' il primo
+ * posto da guardare quando il motore diverge solo su certe lunghezze. */
+ if (getenv("GLM53_DUMP_INDEX")) {
+ for (int t = 0; t < tokens; t++) {
+ fprintf(stderr, "index q=%d ->", t);
+ for (int i = 0; i < width; i++) fprintf(stderr, " %d", selected[(size_t)t * width + i]);
+ fprintf(stderr, "\n");
+ }
+ }
float *context = malloc((size_t)tokens * H * V * sizeof(float));
if (coli_sparse_attention(context, queries, keys, values, selected,
tokens, width, H, QK, V)) {
@@ -841,6 +855,8 @@ static void ffn_layer(const Cfg *c, const GLayer *l, int index, const float *x,
}
/* ---------- caricamento ---------- */
+static void vision_load(GModel *m);
+
static void model_load(GModel *m, const char *dir) {
load_cfg(&m->c, dir);
st_init(&m->S, dir);
@@ -935,10 +951,111 @@ static void model_load(GModel *m, const char *dir) {
}
}
}
+ vision_load(m);
}
-/* ---------- il passaggio completo ---------- */
-static float *forward(GModel *m, const int *tokens, int n) {
+/* ---------- vision ----------
+ * La torre e' in vision_tower.h e non sa nulla di GLM: qui si riempiono solo i
+ * puntatori ai pesi e si traduce la config. Il checkpoint solo-testo non porta
+ * `model.visual.*` e allora has_vision resta 0: l'engine funziona identico. */
+static void vision_load(GModel *m) {
+ const Cfg *c = &m->c;
+ m->has_vision = 0;
+ if (c->vis_layers <= 0) return;
+ if (!st_find(&m->S, "model.visual.patch_embed.proj.weight")) return;
+ const char *V = "model.visual.";
+
+ m->vision.config = (ColiVisionConfig){
+ .depth = c->vis_layers, .hidden = c->vis_hidden, .heads = c->vis_heads,
+ .head_dim = c->vis_hidden / c->vis_heads, .intermediate = c->vis_inter,
+ .patch = c->vis_patch, .temporal = c->vis_temporal, .merge = c->vis_merge,
+ .in_channels = c->vis_in_ch, .out_hidden = c->vis_out_hidden,
+ .proj_intermediate = c->vis_proj_inter ? c->vis_proj_inter : c->vis_inter,
+ .eps = c->vis_eps, .swiglu_limit = c->vis_swiglu_limit,
+ .rope_theta = 10000.0f,
+ };
+ m->vision.patch_w = load_f32(m, "%spatch_embed.proj.weight", V);
+ m->vision.patch_b = load_f32(m, "%spatch_embed.proj.bias", V);
+ m->vision.post_norm = load_f32(m, "%spost_layernorm.weight", V);
+ m->vision.down_w = load_f32(m, "%sdownsample.weight", V);
+ m->vision.down_b = load_f32(m, "%sdownsample.bias", V);
+ m->vision.merger_proj = load_f32(m, "%smerger.proj.weight", V);
+ m->vision.merger_norm_w = load_f32(m, "%smerger.post_projection_norm.weight", V);
+ m->vision.merger_norm_b = load_f32(m, "%smerger.post_projection_norm.bias", V);
+ m->vision.merger_gate = load_f32(m, "%smerger.gate_proj.weight", V);
+ m->vision.merger_up = load_f32(m, "%smerger.up_proj.weight", V);
+ m->vision.merger_down = load_f32(m, "%smerger.down_proj.weight", V);
+
+ m->vblocks = calloc((size_t)c->vis_layers, sizeof(*m->vblocks));
+ if (!m->vblocks) { fprintf(stderr, "OOM sui blocchi vision\n"); exit(1); }
+ for (int b = 0; b < c->vis_layers; b++) {
+ ColiVisionBlock *vb = &m->vblocks[b];
+ vb->norm1 = load_f32(m, "%sblocks.%d.norm1.weight", V, b);
+ vb->norm2 = load_f32(m, "%sblocks.%d.norm2.weight", V, b);
+ vb->qkv_w = load_f32(m, "%sblocks.%d.attn.qkv.weight", V, b);
+ vb->qkv_b = load_f32(m, "%sblocks.%d.attn.qkv.bias", V, b);
+ vb->q_norm = load_f32(m, "%sblocks.%d.attn.q_norm.weight", V, b);
+ vb->k_norm = load_f32(m, "%sblocks.%d.attn.k_norm.weight", V, b);
+ vb->proj_w = load_f32(m, "%sblocks.%d.attn.proj.weight", V, b);
+ vb->proj_b = load_f32(m, "%sblocks.%d.attn.proj.bias", V, b);
+ vb->gate_w = load_f32(m, "%sblocks.%d.mlp.gate_proj.weight", V, b);
+ vb->gate_b = load_f32(m, "%sblocks.%d.mlp.gate_proj.bias", V, b);
+ vb->up_w = load_f32(m, "%sblocks.%d.mlp.up_proj.weight", V, b);
+ vb->up_b = load_f32(m, "%sblocks.%d.mlp.up_proj.bias", V, b);
+ vb->down_w = load_f32(m, "%sblocks.%d.mlp.down_proj.weight", V, b);
+ vb->down_b = load_f32(m, "%sblocks.%d.mlp.down_proj.bias", V, b);
+ }
+ m->vision.blocks = m->vblocks;
+ m->has_vision = 1;
+}
+
+/* Un'immagine gia' in patch -> embedding pronti per il flusso testuale.
+ *
+ * `patches` e' [grid_h*grid_w, in_channels*temporal*patch*patch] nell'ordine in
+ * cui il processore li produce; la torre restituisce
+ * grid_h/merge * grid_w/merge righe da out_hidden. Il chiamante possiede il
+ * buffer restituito. */
+static float *vision_encode(GModel *m, const float *patches,
+ int grid_h, int grid_w, int *out_tokens) {
+ if (!m->has_vision) {
+ fprintf(stderr, "questo checkpoint non porta la torre vision\n");
+ exit(1);
+ }
+ const int tokens = coli_vision_output_tokens(&m->vision.config, grid_h, grid_w);
+ if (tokens <= 0) {
+ fprintf(stderr, "griglia %dx%d non divisibile per merge %d\n",
+ grid_h, grid_w, m->vision.config.merge);
+ exit(1);
+ }
+ float *out = malloc((size_t)tokens * m->vision.config.out_hidden * sizeof(float));
+ if (!out) { fprintf(stderr, "OOM sugli embedding vision\n"); exit(1); }
+ if (coli_vision_forward(out, &m->vision, patches, grid_h, grid_w) != 0) {
+ fprintf(stderr, "la torre vision ha rifiutato l'ingresso\n");
+ exit(1);
+ }
+ /* La torre esce a out_hidden; il flusso testuale vuole hidden. Il
+ * checkpoint li dichiara uguali (4096) e il merger e' proprio il pezzo che
+ * fa combaciare i due, quindi una differenza qui e' una config sbagliata,
+ * non qualcosa da rattoppare in silenzio. */
+ if (m->vision.config.out_hidden != m->c.hidden) {
+ fprintf(stderr, "vision out_hidden %d != hidden %d\n",
+ m->vision.config.out_hidden, m->c.hidden);
+ exit(1);
+ }
+ *out_tokens = tokens;
+ return out;
+}
+
+/* ---------- il passaggio completo ----------
+ *
+ * `vision` sono gli embedding usciti dalla torre, `n_vision` quanti sono: uno
+ * per ogni token immagine presente in `tokens`, nello stesso ordine. Il
+ * processore ha gia' espanso ogni immagine in altrettanti segnaposto
+ * `image_token_id`, quindi qui non c'e' nulla da inserire: si sostituisce la
+ * riga dell'embedding testuale con quella della torre e le posizioni restano
+ * quelle che sono. Prompt di solo testo passano vision=NULL, n_vision=0. */
+static float *forward(GModel *m, const int *tokens, int n,
+ const float *vision, int n_vision) {
const Cfg *c = &m->c;
const int H = c->hc_mult, D = c->hidden;
float *streams = malloc((size_t)n * H * D * sizeof(float));
@@ -948,11 +1065,32 @@ static float *forward(GModel *m, const int *tokens, int n) {
float *branch = malloc((size_t)n * D * sizeof(float));
float *post = malloc((size_t)n * H * sizeof(float));
float *comb = malloc((size_t)n * H * H * sizeof(float));
- /* l'embedding entra replicato in ognuno degli H flussi residui */
- for (int t = 0; t < n; t++)
+ /* l'embedding entra replicato in ognuno degli H flussi residui; sui token
+ * immagine la riga viene dalla torre invece che dalla tabella */
+ int consumed = 0;
+ for (int t = 0; t < n; t++) {
+ const float *row;
+ if (vision && c->image_token >= 0 && tokens[t] == c->image_token) {
+ if (consumed >= n_vision) {
+ fprintf(stderr, "il prompt ha piu' token immagine (%d+) degli "
+ "embedding forniti (%d)\n", consumed + 1, n_vision);
+ exit(1);
+ }
+ row = vision + (size_t)consumed++ * D;
+ } else {
+ row = m->embed + (size_t)tokens[t] * D;
+ }
for (int h = 0; h < H; h++)
- memcpy(streams + ((size_t)t * H + h) * D,
- m->embed + (size_t)tokens[t] * D, (size_t)D * sizeof(float));
+ memcpy(streams + ((size_t)t * H + h) * D, row, (size_t)D * sizeof(float));
+ }
+ /* Avanzare in silenzio con embedding non consumati vorrebbe dire mandare al
+ * modello un'immagine diversa da quella che il chiamante crede di aver
+ * passato: e' un errore, non un caso limite. */
+ if (consumed != n_vision) {
+ fprintf(stderr, "%d embedding vision forniti ma solo %d token immagine "
+ "nel prompt\n", n_vision, consumed);
+ exit(1);
+ }
float *state = NULL, *window = NULL, *scratch = NULL;
if (c->kda_proj) {
@@ -1024,17 +1162,25 @@ static int argmax(const float *v, int n) {
}
int main(int argc, char **argv) {
- const char *dir = NULL, *ids = NULL;
- int greedy = 0, show_logits = 0;
+ const char *dir = NULL, *ids = NULL, *patch_file = NULL;
+ int greedy = 0, show_logits = 0, grid_h = 0, grid_w = 0;
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "--model") && i + 1 < argc) dir = argv[++i];
else if (!strcmp(argv[i], "--ids") && i + 1 < argc) ids = argv[++i];
else if (!strcmp(argv[i], "--greedy") && i + 1 < argc) greedy = atoi(argv[++i]);
else if (!strcmp(argv[i], "--logits")) show_logits = 1;
+ else if (!strcmp(argv[i], "--patches") && i + 1 < argc) patch_file = argv[++i];
+ else if (!strcmp(argv[i], "--grid") && i + 1 < argc &&
+ sscanf(argv[++i], "%dx%d", &grid_h, &grid_w) == 2) continue;
else { fprintf(stderr, "argomento sconosciuto: %s\n", argv[i]); return 2; }
}
if (!dir || !ids) {
- fprintf(stderr, "uso: %s --model DIR --ids a,b,c [--greedy N] [--logits]\n", argv[0]);
+ fprintf(stderr, "uso: %s --model DIR --ids a,b,c [--greedy N] [--logits]\n"
+ " [--patches FILE.f32 --grid HxW]\n", argv[0]);
+ return 2;
+ }
+ if (!!patch_file != (grid_h > 0 && grid_w > 0)) {
+ fprintf(stderr, "--patches e --grid vanno insieme\n");
return 2;
}
int capacity = 1024, count = 0;
@@ -1053,7 +1199,35 @@ int main(int argc, char **argv) {
model_load(&model, dir);
if (getenv("GLM53_VERBOSE")) cfg_report(&model.c);
- float *logits = forward(&model, tokens, count);
+ float *vision = NULL;
+ int n_vision = 0;
+ if (patch_file) {
+ const ColiVisionConfig *vc = &model.vision.config;
+ if (!model.has_vision) {
+ fprintf(stderr, "--patches ma il checkpoint non porta la torre vision\n");
+ return 2;
+ }
+ const size_t per_patch = (size_t)vc->in_channels * vc->temporal * vc->patch * vc->patch;
+ const size_t wanted = (size_t)grid_h * grid_w * per_patch;
+ FILE *f = fopen(patch_file, "rb");
+ if (!f) { fprintf(stderr, "non apro %s\n", patch_file); return 2; }
+ float *patches = malloc(wanted * sizeof(float));
+ if (!patches) { fprintf(stderr, "OOM sulle patch\n"); return 2; }
+ size_t got = fread(patches, sizeof(float), wanted, f);
+ /* Una patch corta darebbe comunque un'uscita, con la coda letta da
+ * memoria non inizializzata: meglio fermarsi e dire di quanto. */
+ if (got != wanted) {
+ fprintf(stderr, "%s: %zu float su %zu attesi per una griglia %dx%d\n",
+ patch_file, got, wanted, grid_h, grid_w);
+ return 2;
+ }
+ fclose(f);
+ vision = vision_encode(&model, patches, grid_h, grid_w, &n_vision);
+ free(patches);
+ printf("vision_tokens %d\n", n_vision);
+ }
+
+ float *logits = forward(&model, tokens, count, vision, n_vision);
printf("teacher_forcing");
for (int t = 0; t < count; t++)
printf(" %d", argmax(logits + (size_t)t * model.c.vocab, model.c.vocab));
@@ -1071,7 +1245,9 @@ int main(int argc, char **argv) {
printf("greedy");
for (int step = 0; step < greedy; step++) {
free(logits);
- logits = forward(&model, sequence, total);
+ /* i token immagine restano nel prefisso a ogni passo, quindi la
+ * torre si rifornisce identica: non si riesegue e non si sposta */
+ logits = forward(&model, sequence, total, vision, n_vision);
int next = argmax(logits + (size_t)(total - 1) * model.c.vocab, model.c.vocab);
sequence[total++] = next;
printf(" %d", next);
@@ -1080,6 +1256,7 @@ int main(int argc, char **argv) {
free(sequence);
}
free(logits);
+ free(vision);
free(tokens);
return 0;
}
diff --git a/c/tests/test_glm53_multimodal_tiny.py b/c/tests/test_glm53_multimodal_tiny.py
new file mode 100644
index 00000000..7cdc32bf
--- /dev/null
+++ b/c/tests/test_glm53_multimodal_tiny.py
@@ -0,0 +1,81 @@
+#!/usr/bin/env python3
+"""Il motore GLM-5.3 con un'immagine, contro l'oracolo di transformers.
+
+Il test sul testo prova la meta' testuale, quello sul tower prova la meta'
+vision. Questo prova il punto in cui si incontrano: le patch passano per la
+torre, gli embedding che ne escono sostituiscono le posizioni dei token
+segnaposto, e il modello risponde. Un motore che prenda quegli embedding
+nell'ordine sbagliato, o li allinei di una posizione, resta un modello che
+parla: solo il confronto coi token dell'oracolo se ne accorge.
+
+La traccia greedy si confronta fino a `greedy_exact_steps`. Oltre quel punto la
+selezione dei pool dell'indexer e' passata da un pareggio: il punteggio passa
+per una ReLU, i pool che non piacciono a nessuna testa valgono esattamente 0, e
+quale di quelli entri nella selezione lo decide l'ordine interno di torch.topk,
+che non e' specificato. La nostra regola (indice piu' basso) e' deterministica e
+riproducibile; quella di torch cambia fra backend. Da li' in poi la traccia non
+sarebbe un bersaglio legittimo per nessuna implementazione, nemmeno per una
+seconda esecuzione di torch su un'altra macchina.
+"""
+import argparse
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--binary", required=True)
+ parser.add_argument("--fixture", type=Path, required=True)
+ parser.add_argument("--logit-tolerance", type=float, default=2e-5)
+ arguments = parser.parse_args()
+
+ reference = json.loads((arguments.fixture / "ref.json").read_text())
+ prompt = ",".join(str(token) for token in reference["prompt"])
+ grid_h, grid_w = reference["grid"]
+ expected_forcing = reference["teacher_forcing"]
+ expected_greedy = reference["greedy"]
+ comparable = reference.get("greedy_exact_steps", len(expected_greedy))
+
+ result = subprocess.run(
+ [arguments.binary, "--model", str(arguments.fixture), "--ids", prompt,
+ "--patches", str(arguments.fixture / "patches.f32"),
+ "--grid", f"{grid_h}x{grid_w}",
+ "--greedy", str(len(expected_greedy)), "--logits"],
+ capture_output=True, text=True, check=True)
+
+ lines = {line.split()[0]: line.split()[1:]
+ for line in result.stdout.splitlines() if line.strip()}
+ tokens = int(lines["vision_tokens"][0])
+ forcing = [int(value) for value in lines["teacher_forcing"]]
+ greedy = [int(value) for value in lines["greedy"]]
+ logits = [float(value) for value in lines["last_logits"]]
+
+ if tokens != reference["image_tokens"]:
+ print(f"FAIL token immagine: {tokens}, attesi {reference['image_tokens']}")
+ return 1
+ if forcing != expected_forcing:
+ print(f"FAIL teacher forcing\n ottenuto: {forcing}\n atteso: {expected_forcing}")
+ return 1
+ if greedy[:comparable] != expected_greedy[:comparable]:
+ print(f"FAIL greedy nei primi {comparable} passi\n"
+ f" ottenuto: {greedy[:comparable]}\n"
+ f" atteso: {expected_greedy[:comparable]}")
+ return 1
+ worst = max(abs(a - b) for a, b in zip(logits, reference["last_logits"], strict=True))
+ if worst > arguments.logit_tolerance:
+ print(f"FAIL logit: max abs {worst:.3g} oltre {arguments.logit_tolerance:.3g}")
+ return 1
+
+ skipped = ("" if comparable == len(expected_greedy) else
+ f", {len(expected_greedy) - comparable} passi greedy non "
+ f"confrontabili (pareggio nella selezione dei pool)")
+ print(f"PASS GLM-5.3 multimodale: {tokens} token immagine, "
+ f"{len(forcing)} posizioni teacher-forced esatte, "
+ f"{comparable} token greedy esatti, logit entro {worst:.3g}{skipped}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/c/tools/make_glm53_multimodal_tiny.py b/c/tools/make_glm53_multimodal_tiny.py
new file mode 100644
index 00000000..181f4d82
--- /dev/null
+++ b/c/tools/make_glm53_multimodal_tiny.py
@@ -0,0 +1,307 @@
+#!/usr/bin/env python3
+"""Oracolo tiny di GLM-5.3-Flash completo: testo piu' immagine.
+
+Gli altri due oracoli coprono le meta' separate - il testo da solo e la torre
+vision da sola. Nessuno dei due tocca il punto in cui si incontrano, cioe' la
+sostituzione degli embedding dell'immagine nelle posizioni dei token segnaposto.
+E' esattamente il punto dove un motore puo' sembrare giusto e non esserlo:
+prendere gli embedding nell'ordine sbagliato, o allinearli sulla posizione
+sbagliata, produce comunque un modello che parla.
+
+Il riferimento e' il `Glm5NextForConditionalGeneration` ufficiale, che innesta
+l'immagine con `inputs_embeds.masked_scatter(input_ids == image_token_id,
+image_embeds)`: gli embedding entrano in ordine, uno per segnaposto, e le
+posizioni non si spostano.
+
+Il fixture porta anche le patch grezze in un file .f32 separato, cosi' la CLI
+del motore puo' rileggerle senza dipendere da safetensors.
+
+USO:
+ python3 tools/make_glm53_multimodal_tiny.py --output ~/glm53_mm_tiny
+"""
+from __future__ import annotations
+
+import argparse
+import json
+from contextlib import contextmanager
+from pathlib import Path
+
+EXPECTED_TRANSFORMERS = "5.16.1"
+SEED = 1253
+
+# La torre esce a OUT_HIDDEN e il flusso testuale entra a HIDDEN: il merger e'
+# il pezzo che li fa combaciare, quindi devono essere lo stesso numero.
+HIDDEN = 128
+VOCAB = 128
+IMAGE_TOKEN = 100
+
+VIS_DEPTH, VIS_HIDDEN, VIS_HEADS, VIS_INTER = 2, 64, 4, 128
+PATCH, TEMPORAL, MERGE, IN_CHANNELS = 4, 2, 2, 3
+GRID_H, GRID_W = 4, 4 # 4x4 patch, merge 2 -> 4 token immagine
+
+TEXT_CONFIG = {
+ "vocab_size": VOCAB,
+ "hidden_size": HIDDEN,
+ "intermediate_size": 256,
+ "moe_intermediate_size": 128,
+ "num_hidden_layers": 4,
+ "num_attention_heads": 4,
+ "num_key_value_heads": 4,
+ "n_shared_experts": 1,
+ "n_routed_experts": 4,
+ "num_experts_per_tok": 2,
+ "kv_lora_rank": 64,
+ "q_lora_rank": 128,
+ "qk_rope_head_dim": 0,
+ "qk_nope_head_dim": 32,
+ "v_head_dim": 32,
+ "max_position_embeddings": 128,
+ "layer_types": ["linear_attention", "linear_attention",
+ "linear_attention", "deepseek_sparse_attention"],
+ "mlp_layer_types": ["dense", "dense", "dense", "sparse"],
+ "indexer_types": ["full", "full", "full", "full"],
+ "index_topk": 4,
+ "index_kpool": 2,
+ "index_head_dim": 32,
+ "index_n_heads": 2,
+ "linear_head_dim": 32,
+ "linear_num_heads": 4,
+ "linear_conv_kernel_dim": 4,
+ "hc_mult": 2,
+ "hc_sinkhorn_iters": 3,
+ "hc_eps": 1e-06,
+ "rms_norm_eps": 1e-05,
+ "routed_scaling_factor": 2.5,
+ "swiglu_limit": 10.0,
+ "pad_token_id": None, # il default della classe cade fuori da VOCAB
+ "bos_token_id": 0,
+ "eos_token_id": 1,
+ "tie_word_embeddings": False,
+ "linear_attn_config": {
+ "num_heads": 4, "head_dim": 32, "short_conv_kernel_size": 4,
+ "gate_lower_bound": -5.0, "kda_layers": [0, 1, 2],
+ },
+ "num_nextn_predict_layers": 0,
+}
+
+# 8 posizioni, 4 delle quali sono l'immagine, e non all'inizio: se il motore
+# sbagliasse allineamento con un offset costante, un blocco in testa lo
+# nasconderebbe.
+PROMPT = [2, 3, IMAGE_TOKEN, IMAGE_TOKEN, IMAGE_TOKEN, IMAGE_TOKEN, 5, 6]
+GREEDY_STEPS = 4
+
+
+@contextmanager
+def tie_watch(torch, length, select_k):
+ """Segnala se l'indexer ha scelto i pool con un pareggio sul bordo.
+
+ Intercetta le chiamate a topk sui punteggi dei pool per l'ultima posizione,
+ che e' quella che decide il token successivo. Se il k-esimo punteggio e il
+ (k+1)-esimo sono identici, quale pool entri non lo decide il modello."""
+ tied = [False]
+ original = torch.Tensor.topk
+
+ def watched(self, k, *args, **kwargs):
+ if (self.dim() == 3 and self.shape[0] == 1 and self.shape[1] == length
+ and self.shape[2] <= 2 * select_k + 4):
+ row = sorted((float(v) for v in self[0, length - 1]), reverse=True)
+ if len(row) > select_k and row[select_k - 1] == row[select_k]:
+ tied[0] = True
+ return original(self, k, *args, **kwargs)
+
+ torch.Tensor.topk = watched
+ try:
+ yield tied
+ finally:
+ torch.Tensor.topk = original
+
+
+def to_checkpoint_names(tensors, torch):
+ """state_dict di transformers -> nomi del checkpoint pubblicato.
+
+ L'albero dei moduli e il checkpoint su Hugging Face non si chiamano allo
+ stesso modo, e due tensori sono anche fusi: la conv corta tiene q, k e v in
+ un unico banco depthwise, e gli esperti stanno impilati per layer. Il
+ motore legge il checkpoint, quindi e' il fixture che deve adeguarsi."""
+ import re
+ renamed = {}
+ for name, tensor in tensors.items():
+ match = re.match(r"(model\.language_model\.layers\.\d+\.)(.*)", name)
+ if not match:
+ renamed[name] = tensor
+ continue
+ prefix, rest = match.group(1), match.group(2)
+ if rest.startswith("attn_hc."):
+ renamed[prefix + "hc_attn_" + rest.split(".", 1)[1]] = tensor
+ elif rest.startswith("ffn_hc."):
+ renamed[prefix + "hc_ffn_" + rest.split(".", 1)[1]] = tensor
+ elif rest.startswith("self_attn.forget_gate."):
+ renamed[prefix + "self_attn." + rest.split("forget_gate.", 1)[1]] = tensor
+ elif rest == "self_attn.conv1d.weight":
+ # [3*qkv, 1, K], nell'ordine in cui il modulo poi la rilegge:
+ # torch.split(mixed_qkv, [qkv_dim]*3) da' query, key, value.
+ third = tensor.shape[0] // 3
+ for slot, part in enumerate(("q", "k", "v")):
+ renamed[f"{prefix}self_attn.{part}_conv1d.weight"] = \
+ tensor[slot * third:(slot + 1) * third].contiguous()
+ elif rest == "mlp.experts.gate_up_proj":
+ # [esperti, 2*inter, hidden]; _apply_gate fa chunk(2, dim=-1)
+ # sull'uscita, quindi la prima meta' delle righe e' il gate.
+ inter = tensor.shape[1] // 2
+ for expert in range(tensor.shape[0]):
+ renamed[f"{prefix}mlp.experts.{expert}.gate_proj.weight"] = \
+ tensor[expert, :inter].contiguous()
+ renamed[f"{prefix}mlp.experts.{expert}.up_proj.weight"] = \
+ tensor[expert, inter:].contiguous()
+ elif rest == "mlp.experts.down_proj":
+ # [esperti, hidden, inter], gia' nel verso [uscita, ingresso]
+ for expert in range(tensor.shape[0]):
+ renamed[f"{prefix}mlp.experts.{expert}.down_proj.weight"] = \
+ tensor[expert].contiguous()
+ else:
+ renamed[name] = tensor
+ return renamed
+
+
+def build(output: Path) -> int:
+ import torch
+ import transformers
+ from safetensors.torch import save_file
+ from transformers.models.glm5_next.configuration_glm5_next import (
+ Glm5NextConfig, Glm5NextTextConfig, Glm5NextVisionConfig)
+ from transformers.models.glm5_next.modeling_glm5_next import (
+ Glm5NextForConditionalGeneration)
+
+ if transformers.__version__ != EXPECTED_TRANSFORMERS:
+ print(f"expected Transformers {EXPECTED_TRANSFORMERS}, "
+ f"found {transformers.__version__}")
+ return 2
+
+ torch.manual_seed(SEED)
+ vision_config = Glm5NextVisionConfig(
+ depth=VIS_DEPTH, hidden_size=VIS_HIDDEN, num_heads=VIS_HEADS,
+ intermediate_size=VIS_INTER, patch_size=PATCH,
+ temporal_patch_size=TEMPORAL, spatial_merge_size=MERGE,
+ out_hidden_size=HIDDEN, projection_intermediate_size=VIS_INTER,
+ in_channels=IN_CHANNELS, image_size=PATCH * GRID_H,
+ )
+ config = Glm5NextConfig(
+ text_config=Glm5NextTextConfig(**TEXT_CONFIG),
+ vision_config=vision_config,
+ image_token_id=IMAGE_TOKEN,
+ )
+ # Pesi dall'init nativo di transformers sotto seme fisso, non riempiti a
+ # mano: un riempimento uniforme ignora il fan-in, il segnale si spegne
+ # strato dopo strato e l'immagine finisce per spostare i logit di 1e-05.
+ # Con l'init vero l'immagine cambia davvero la risposta, che e' la sola
+ # condizione per cui questo fixture prova qualcosa. I pesi finiscono nel
+ # model.safetensors, quindi il test non dipende dal fatto che una torch
+ # diversa rigeneri gli stessi numeri: dipende solo da questo file.
+ model = Glm5NextForConditionalGeneration(config).eval()
+
+ n_patches = GRID_H * GRID_W
+ width = IN_CHANNELS * TEMPORAL * PATCH * PATCH
+ pixels = torch.linspace(-1.0, 1.0, n_patches * width,
+ dtype=torch.float32).view(n_patches, width)
+ grid_thw = torch.tensor([[1, GRID_H, GRID_W]], dtype=torch.long)
+ ids = torch.tensor([PROMPT], dtype=torch.long)
+
+ expected_image_tokens = (GRID_H // MERGE) * (GRID_W // MERGE)
+ placeholders = sum(1 for t in PROMPT if t == IMAGE_TOKEN)
+ if placeholders != expected_image_tokens:
+ print(f"il prompt ha {placeholders} segnaposto ma la griglia "
+ f"{GRID_H}x{GRID_W} con merge {MERGE} ne produce "
+ f"{expected_image_tokens}")
+ return 2
+
+ with torch.no_grad():
+ logits = model(input_ids=ids, pixel_values=pixels,
+ image_grid_thw=grid_thw).logits[0].float()
+ forcing = logits.argmax(-1).tolist()
+
+ sequence = list(PROMPT)
+ greedy = []
+ exact_steps = GREEDY_STEPS
+ select_k = TEXT_CONFIG["index_topk"] // TEXT_CONFIG["index_kpool"]
+ for step in range(GREEDY_STEPS):
+ with tie_watch(torch, len(sequence), select_k) as tied:
+ out = model(input_ids=torch.tensor([sequence], dtype=torch.long),
+ pixel_values=pixels, image_grid_thw=grid_thw).logits[0]
+ # Il punteggio dei pool passa per una ReLU, quindi ogni pool che non
+ # piace a nessuna testa vale esattamente 0 e i pareggi sono comuni.
+ # Su un pareggio al bordo della selezione, quale pool entri lo
+ # decide l'ordine interno di torch.topk, che non e' specificato e
+ # cambia fra backend: da li' in poi questa traccia non e' piu' un
+ # bersaglio legittimo per nessuna implementazione, nemmeno per una
+ # seconda esecuzione di torch su un'altra macchina.
+ if tied[0] and exact_steps == GREEDY_STEPS:
+ exact_steps = step
+ nxt = int(out[-1].argmax())
+ greedy.append(nxt)
+ sequence.append(nxt)
+
+ # Guardia: un'altra immagine deve dare un'altra risposta. Se non
+ # cambia nulla, questo fixture non e' in grado di accorgersi di una
+ # vision rotta e non va scritto, per quanto passi.
+ other = model(input_ids=ids, pixel_values=-pixels,
+ image_grid_thw=grid_thw).logits[0].argmax(-1).tolist()
+
+ if forcing == other:
+ print("il fixture non distingue due immagini opposte: sarebbe un test "
+ "del solo testo travestito da test vision")
+ return 2
+ if len(set(forcing + greedy)) < 3:
+ print(f"uscita degenere ({sorted(set(forcing + greedy))}): un motore "
+ "sbagliato passerebbe lo stesso")
+ return 2
+
+ output.mkdir(parents=True, exist_ok=True)
+ tensors = to_checkpoint_names(
+ {name: parameter.detach().contiguous().to(torch.float32)
+ for name, parameter in model.state_dict().items()
+ if parameter.dtype.is_floating_point}, torch)
+ save_file(tensors, str(output / "model.safetensors"), metadata={"format": "pt"})
+ (output / "patches.f32").write_bytes(pixels.contiguous().numpy().tobytes())
+
+ payload = config.to_dict()
+ payload["architectures"] = ["Glm5NextForConditionalGeneration"]
+ (output / "config.json").write_text(
+ json.dumps(payload, indent=2, sort_keys=True, default=str), encoding="utf-8")
+
+ reference = {
+ "schema_version": 1,
+ "source": "transformers",
+ "transformers_version": transformers.__version__,
+ "torch_version": torch.__version__,
+ "seed": SEED,
+ "prompt": PROMPT,
+ "image_token_id": IMAGE_TOKEN,
+ "grid": [GRID_H, GRID_W],
+ "patch_shape": list(pixels.shape),
+ "image_tokens": expected_image_tokens,
+ "teacher_forcing": forcing,
+ "greedy": greedy,
+ # Fin dove la traccia greedy e' un bersaglio legittimo: oltre, la
+ # selezione dell'indexer e' passata da un pareggio e il seguito
+ # dipende dall'ordine interno di torch.topk, non dal modello.
+ "greedy_exact_steps": exact_steps,
+ "last_logits": logits[-1].tolist(),
+ }
+ (output / "ref.json").write_text(json.dumps(reference, indent=2), encoding="utf-8")
+ note = ("" if exact_steps == GREEDY_STEPS else
+ f"; greedy confrontabile solo per {exact_steps} passi su "
+ f"{GREEDY_STEPS} (pareggio nella selezione dei pool)")
+ print(f"wrote {output} ({len(tensors)} tensors, {expected_image_tokens} "
+ f"token immagine su {len(PROMPT)} posizioni{note})")
+ return 0
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--output", type=Path, required=True)
+ arguments = parser.parse_args()
+ return build(arguments.output)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())