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

security(glm53): refuse matrices whose shape differs from the config

Marcello Costagliola48b8ee22113a
diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml
index 1940b3ec..6eb1284d 100644
--- a/.github/workflows/check.yml
+++ b/.github/workflows/check.yml
@@ -158,6 +158,7 @@ jobs:
cd c && COLI_GLM53_FIXTURE=/tmp/glm53_stream-i4 python -m unittest -v tests.test_glm53_dashboard
COLI_GLM53_FIXTURE=/tmp/glm53_stream-i4 python -m unittest -v tests.test_glm53_context_exceeded
COLI_GLM53_FIXTURE=/tmp/glm53_stream-i4 python -m unittest -v tests.test_glm53_hostile_weights
+ COLI_GLM53_FIXTURE=/tmp/glm53_mm python -m unittest -v tests.test_glm53_hostile_weights.Glm53MatrixShapeTest
# The two stdlib-only oracles used to be argparse scripts that `make
# test-python` collected as zero tests (#1700). They run here, on the
# fixtures generated above, token-exact against transformers in f32.
diff --git a/c/glm53.c b/c/glm53.c
index d539a069..05b4cf05 100644
--- a/c/glm53.c
+++ b/c/glm53.c
@@ -362,6 +362,14 @@ static void load_cfg(Cfg *c, const char *snap) {
c->hc_mult < 1 || c->hc_mult > 8) {
fprintf(stderr, "config.json: dimension out of range\n"); exit(1);
}
+ /* L'esperto condiviso e' largo moe_inter * n_shared, e il FFN gli da' i
+ * buffer del piu' largo fra denso e routed (ffn_layer_ex, glm53_chain.h). */
+ if (c->n_shared < 1 || (int64_t)c->moe_inter * c->n_shared >
+ (c->dense_inter > c->moe_inter ? c->dense_inter : c->moe_inter)) {
+ fprintf(stderr, "config.json: n_shared_experts=%d does not fit the FFN buffers\n",
+ c->n_shared);
+ exit(1);
+ }
/* qk_rope must be zero: a rotary GLM-5.3 would need position handling this
* engine deliberately does not have, and silently ignoring the rotation
* would produce a model that answers fluently and wrongly. */
@@ -882,7 +890,12 @@ static void absorb_kvb(GModel *m, GLayer *l, const char *name) {
l->kvb_v = quantize_loaded(vv, H * V, L);
}
-static Mat load_mat(GModel *m, const char *fmt, ...) {
+/* rows x columns e' la forma con cui il forward usa la matrice, contata dalla
+ * config: mm() scrive w->rows valori per token e ne legge w->columns. Presa
+ * dall'header senza confronto, una riga in piu' scriveva oltre il buffer
+ * d'uscita e una colonna in piu' leggeva oltre quello d'ingresso. A differenza
+ * di load_f32 la forma deve tornare esatta: piu' colonne spostano ogni riga. */
+static Mat load_mat(GModel *m, int64_t rows, int64_t columns, const char *fmt, ...) {
char name[512];
va_list args; va_start(args, fmt); vsnprintf(name, sizeof(name), fmt, args); va_end(args);
st_tensor *t = st_find(&m->S, name);
@@ -922,8 +935,14 @@ static Mat load_mat(GModel *m, const char *fmt, ...) {
"the shape is not stored in the file and cannot be inferred\n", name);
exit(1);
}
- mat.rows = (int)t->shape[0];
- mat.columns = (int)(values / t->shape[0]);
+ if (t->shape[0] != rows || values != rows * columns) {
+ fprintf(stderr, "%s: %lld rows and %lld values, the config needs %lld x %lld\n",
+ name, (long long)t->shape[0], (long long)values,
+ (long long)rows, (long long)columns);
+ exit(1);
+ }
+ mat.rows = (int)rows;
+ mat.columns = (int)columns;
if (mat.columns % 64) {
fprintf(stderr, "%s: %d columns are not multiples of 64\n", name, mat.columns);
exit(1);
@@ -938,11 +957,17 @@ static Mat load_mat(GModel *m, const char *fmt, ...) {
}
if (t->rank != 2) { fprintf(stderr, "%s: rank %d, expected 2\n", name, t->rank); exit(1); }
+ if (t->shape[0] != rows || t->shape[1] != columns) {
+ fprintf(stderr, "%s: %lld x %lld, the config needs %lld x %lld\n", name,
+ (long long)t->shape[0], (long long)t->shape[1],
+ (long long)rows, (long long)columns);
+ exit(1);
+ }
float *buffer = malloc((size_t)t->numel * sizeof(float));
if (!buffer) { fprintf(stderr, "OOM on %s\n", name); exit(1); }
st_read_f32_cap(&m->S, name, buffer, t->numel, 1);
- mat.rows = (int)t->shape[0];
- mat.columns = (int)t->shape[1];
+ mat.rows = (int)rows;
+ mat.columns = (int)columns;
mat = quantize_loaded(buffer, mat.rows, mat.columns);
return mat;
@@ -2275,10 +2300,12 @@ static void model_load_range(GModel *m, const char *dir, int layer_begin,
snprintf(probe, sizeof(probe), "%sembed_tokens.weight", m->prefix);
if (!st_find(&m->S, probe)) snprintf(m->prefix, sizeof(m->prefix), "model.");
const char *P = m->prefix;
- /* Le misure con cui il forward legge i vettori f32 (vedi load_f32). Le
- * matrici mHC sono [(2+hc)*hc, hc*hidden], come in hyper_connections.h. */
+ /* Le misure con cui il forward legge i vettori f32 (vedi load_f32) e le
+ * forme delle matrici (vedi load_mat). Le matrici mHC sono
+ * [(2+hc)*hc, hc*hidden], come in hyper_connections.h. */
const Cfg *c = &m->c;
const int64_t D = c->hidden, hc = c->hc_mult, hc_mix = (2 + hc) * hc;
+ const int64_t H = c->n_heads, IH = c->index_nh, shared = (int64_t)c->moe_inter * c->n_shared;
if (layer_end < 0 || layer_end > m->c.n_layers) layer_end = m->c.n_layers;
if (layer_begin < 0) layer_begin = 0;
@@ -2298,7 +2325,7 @@ static void model_load_range(GModel *m, const char *dir, int layer_begin,
* layer non la carica proprio: non ha logit da produrre. */
if (load_io) {
if (st_find(&m->S, "lm_head.weight")) {
- m->head = load_mat(m, "lm_head.weight");
+ m->head = load_mat(m, c->vocab, D, "lm_head.weight");
} else {
memset(&m->head, 0, sizeof(m->head));
m->head.f = m->embed;
@@ -2335,10 +2362,10 @@ static void model_load_range(GModel *m, const char *dir, int layer_begin,
l->hc_ffn_base = load_f32(m, hc_mix, "%slayers.%d.hc_ffn_base", P, i);
l->hc_ffn_scale = load_f32(m, 3, "%slayers.%d.hc_ffn_scale", P, i);
if (m->c.is_full[i]) {
- l->qa = load_mat(m, "%slayers.%d.self_attn.q_a_proj.weight", P, i);
+ l->qa = load_mat(m, c->q_lora, D, "%slayers.%d.self_attn.q_a_proj.weight", P, i);
l->qa_ln = load_f32(m, c->q_lora, "%slayers.%d.self_attn.q_a_layernorm.weight", P, i);
- l->qb = load_mat(m, "%slayers.%d.self_attn.q_b_proj.weight", P, i);
- l->kva = load_mat(m, "%slayers.%d.self_attn.kv_a_proj_with_mqa.weight", P, i);
+ l->qb = load_mat(m, H * c->qk_nope, c->q_lora, "%slayers.%d.self_attn.q_b_proj.weight", P, i);
+ l->kva = load_mat(m, c->kv_lora, D, "%slayers.%d.self_attn.kv_a_proj_with_mqa.weight", P, i);
l->kva_ln = load_f32(m, c->kv_lora, "%slayers.%d.self_attn.kv_a_layernorm.weight", P, i);
{
char kvb_name[512];
@@ -2346,27 +2373,27 @@ static void model_load_range(GModel *m, const char *dir, int layer_begin,
"%slayers.%d.self_attn.kv_b_proj.weight", P, i);
absorb_kvb(m, l, kvb_name);
}
- l->o = load_mat(m, "%slayers.%d.self_attn.o_proj.weight", P, i);
- l->iwq = load_mat(m, "%slayers.%d.self_attn.indexer.wq_b.weight", P, i);
- l->iwk = load_mat(m, "%slayers.%d.self_attn.indexer.wk.weight", P, i);
- l->iwp = load_mat(m, "%slayers.%d.self_attn.indexer.weights_proj.weight", P, i);
+ l->o = load_mat(m, D, H * c->v_head, "%slayers.%d.self_attn.o_proj.weight", P, i);
+ l->iwq = load_mat(m, IH * c->index_hd, c->q_lora, "%slayers.%d.self_attn.indexer.wq_b.weight", P, i);
+ l->iwk = load_mat(m, c->index_hd, D, "%slayers.%d.self_attn.indexer.wk.weight", P, i);
+ l->iwp = load_mat(m, IH, D, "%slayers.%d.self_attn.indexer.weights_proj.weight", P, i);
l->ik_nw = load_f32(m, c->index_hd, "%slayers.%d.self_attn.indexer.k_norm.weight", P, i);
l->ik_nb = load_f32(m, c->index_hd, "%slayers.%d.self_attn.indexer.k_norm.bias", P, i);
if (m->c.index_kpool > 1) {
l->ikpa = load_f32(m, (int64_t)c->index_kpool * c->index_hd,
"%slayers.%d.self_attn.indexer.index_kpool_compress_ape", P, i);
- l->ikpg = load_mat(m, "%slayers.%d.self_attn.indexer.index_kpool_compress_gate", P, i);
+ l->ikpg = load_mat(m, c->index_hd, D, "%slayers.%d.self_attn.indexer.index_kpool_compress_gate", P, i);
}
} else {
- l->kq = load_mat(m, "%slayers.%d.self_attn.q_proj.weight", P, i);
- l->kk = load_mat(m, "%slayers.%d.self_attn.k_proj.weight", P, i);
- l->kv = load_mat(m, "%slayers.%d.self_attn.v_proj.weight", P, i);
- l->ko = load_mat(m, "%slayers.%d.self_attn.o_proj.weight", P, i);
- l->kga = load_mat(m, "%slayers.%d.self_attn.g_a_proj.weight", P, i);
- l->kgb = load_mat(m, "%slayers.%d.self_attn.g_b_proj.weight", P, i);
- l->kfa = load_mat(m, "%slayers.%d.self_attn.f_a_proj.weight", P, i);
- l->kfb = load_mat(m, "%slayers.%d.self_attn.f_b_proj.weight", P, i);
- l->kb = load_mat(m, "%slayers.%d.self_attn.b_proj.weight", P, i);
+ l->kq = load_mat(m, c->kda_proj, D, "%slayers.%d.self_attn.q_proj.weight", P, i);
+ l->kk = load_mat(m, c->kda_proj, D, "%slayers.%d.self_attn.k_proj.weight", P, i);
+ l->kv = load_mat(m, c->kda_proj, D, "%slayers.%d.self_attn.v_proj.weight", P, i);
+ l->ko = load_mat(m, D, c->kda_proj, "%slayers.%d.self_attn.o_proj.weight", P, i);
+ l->kga = load_mat(m, c->kda_hd, D, "%slayers.%d.self_attn.g_a_proj.weight", P, i);
+ l->kgb = load_mat(m, c->kda_proj, c->kda_hd, "%slayers.%d.self_attn.g_b_proj.weight", P, i);
+ l->kfa = load_mat(m, c->kda_hd, D, "%slayers.%d.self_attn.f_a_proj.weight", P, i);
+ l->kfb = load_mat(m, c->kda_proj, c->kda_hd, "%slayers.%d.self_attn.f_b_proj.weight", P, i);
+ l->kb = load_mat(m, c->kda_heads, D, "%slayers.%d.self_attn.b_proj.weight", P, i);
l->dt = load_f32(m, c->kda_proj, "%slayers.%d.self_attn.dt_bias", P, i);
l->alog = load_f32(m, c->kda_heads, "%slayers.%d.self_attn.A_log", P, i);
l->onorm = load_f32(m, c->kda_hd, "%slayers.%d.self_attn.o_norm.weight", P, i);
@@ -2386,17 +2413,17 @@ static void model_load_range(GModel *m, const char *dir, int layer_begin,
}
}
if (i < m->c.first_dense) {
- l->dg = load_mat(m, "%slayers.%d.mlp.gate_proj.weight", P, i);
- l->du = load_mat(m, "%slayers.%d.mlp.up_proj.weight", P, i);
- l->dd = load_mat(m, "%slayers.%d.mlp.down_proj.weight", P, i);
+ l->dg = load_mat(m, c->dense_inter, D, "%slayers.%d.mlp.gate_proj.weight", P, i);
+ l->du = load_mat(m, c->dense_inter, D, "%slayers.%d.mlp.up_proj.weight", P, i);
+ l->dd = load_mat(m, D, c->dense_inter, "%slayers.%d.mlp.down_proj.weight", P, i);
} else {
l->router = load_f32(m, c->n_experts * D, "%slayers.%d.mlp.gate.weight", P, i);
l->rbias = st_find(&m->S, (snprintf(probe, sizeof(probe),
"%slayers.%d.mlp.gate.e_score_correction_bias", P, i), probe))
? load_f32(m, c->n_experts, "%s", probe) : NULL;
- l->rg = load_mat(m, "%slayers.%d.mlp.shared_experts.gate_proj.weight", P, i);
- l->ru = load_mat(m, "%slayers.%d.mlp.shared_experts.up_proj.weight", P, i);
- l->rd = load_mat(m, "%slayers.%d.mlp.shared_experts.down_proj.weight", P, i);
+ l->rg = load_mat(m, shared, D, "%slayers.%d.mlp.shared_experts.gate_proj.weight", P, i);
+ l->ru = load_mat(m, shared, D, "%slayers.%d.mlp.shared_experts.up_proj.weight", P, i);
+ l->rd = load_mat(m, D, shared, "%slayers.%d.mlp.shared_experts.down_proj.weight", P, i);
/* Gli esperti quantizzati restano su disco: sono il 97% dei byte
* e nessuna macchina li tiene in RAM. Un checkpoint f32, come le
* fixture degli oracoli, e' piccolo e si carica tutto. */
@@ -2405,9 +2432,9 @@ static void model_load_range(GModel *m, const char *dir, int layer_begin,
l->eu = malloc((size_t)m->c.n_experts * sizeof(Mat));
l->ed = malloc((size_t)m->c.n_experts * sizeof(Mat));
for (int e = 0; e < m->c.n_experts; e++) {
- l->eg[e] = load_mat(m, "%slayers.%d.mlp.experts.%d.gate_proj.weight", P, i, e);
- l->eu[e] = load_mat(m, "%slayers.%d.mlp.experts.%d.up_proj.weight", P, i, e);
- l->ed[e] = load_mat(m, "%slayers.%d.mlp.experts.%d.down_proj.weight", P, i, e);
+ l->eg[e] = load_mat(m, c->moe_inter, D, "%slayers.%d.mlp.experts.%d.gate_proj.weight", P, i, e);
+ l->eu[e] = load_mat(m, c->moe_inter, D, "%slayers.%d.mlp.experts.%d.up_proj.weight", P, i, e);
+ l->ed[e] = load_mat(m, D, c->moe_inter, "%slayers.%d.mlp.experts.%d.down_proj.weight", P, i, e);
}
}
}
diff --git a/c/tests/safetensors_edit.py b/c/tests/safetensors_edit.py
index 40e6e39e..c433d0ea 100644
--- a/c/tests/safetensors_edit.py
+++ b/c/tests/safetensors_edit.py
@@ -6,6 +6,7 @@ known-good tiny fixture and change exactly one thing, so a test can ask what the
engine does with that one thing.
"""
import json
+import math
import shutil
import struct
from pathlib import Path
@@ -32,6 +33,10 @@ def shape_of(directory, name):
return list(_shard_of(directory, name)[1][name]["shape"])
+def dtype_of(directory, name):
+ return _shard_of(directory, name)[1][name]["dtype"]
+
+
def copy_fixture(source, destination):
shutil.copytree(source, destination)
return Path(destination)
@@ -63,27 +68,48 @@ def add_f32(directory, beside, name, count, value=0x41414141):
+ struct.pack("<I", value) * count)
-def shrink(directory, name, count):
- """Keep the first `count` elements of tensor `name`, declared as a flat vector.
+def tensor_bytes(directory, name):
+ shard, header, start = _shard_of(directory, name)
+ first, last = header[name]["data_offsets"]
+ with open(shard, "rb") as handle:
+ handle.seek(start + first)
+ return handle.read(last - first)
+
- The header stays honest: shape and offsets agree, and the tensors stored after
- it move up so the data section has no hole. Only the length is hostile.
+def put(directory, name, dtype, shape, payload, beside=None):
+ """Store tensor `name` as `dtype`, `shape`, `payload`: in its shard, or beside `beside`.
+
+ The header stays honest: dtype, shape and offsets agree with the bytes, and the
+ other tensors move up so the data section has no hole. Only the values the test
+ chose are hostile.
"""
- shard, header, start = _shard_of(directory, name)
+ shard, header, start = _shard_of(directory, beside or name)
data = shard.read_bytes()[start:]
- width = len(_NAN[header[name]["dtype"]])
tensors = sorted((entry["data_offsets"][0], key) for key, entry in header.items()
- if key != "__metadata__")
+ if key not in ("__metadata__", name))
body, at = [], 0
for _, key in tensors:
- entry = header[key]
- first, last = entry["data_offsets"]
- if key == name:
- last = first + width * count
- entry["shape"] = [count]
+ first, last = header[key]["data_offsets"]
body.append(data[first:last])
- entry["data_offsets"] = [at, at + last - first]
+ header[key]["data_offsets"] = [at, at + last - first]
at += last - first
+ header[name] = {"dtype": dtype, "shape": list(shape),
+ "data_offsets": [at, at + len(payload)]}
encoded = json.dumps(header, separators=(",", ":")).encode()
encoded += b" " * (-len(encoded) % 8)
- shard.write_bytes(struct.pack("<Q", len(encoded)) + encoded + b"".join(body))
+ shard.write_bytes(struct.pack("<Q", len(encoded)) + encoded + b"".join(body) + payload)
+
+
+def shrink(directory, name, count):
+ """Keep the first `count` elements of tensor `name`, declared as a flat vector."""
+ dtype = dtype_of(directory, name)
+ put(directory, name, dtype, [count],
+ tensor_bytes(directory, name)[:len(_NAN[dtype]) * count])
+
+
+def reshape(directory, name, shape):
+ """Declare tensor `name` as `shape`, its data cut or zero-padded to fit."""
+ dtype = dtype_of(directory, name)
+ size = len(_NAN[dtype]) * math.prod(shape)
+ data = tensor_bytes(directory, name)[:size]
+ put(directory, name, dtype, shape, data + bytes(size - len(data)))
diff --git a/c/tests/test_glm53_hostile_weights.py b/c/tests/test_glm53_hostile_weights.py
index 2befe84e..098e4f48 100644
--- a/c/tests/test_glm53_hostile_weights.py
+++ b/c/tests/test_glm53_hostile_weights.py
@@ -9,14 +9,27 @@ A short f32 tensor: load_f32() sized the buffer by the numel the header declares
while the forward pass reads norms, router, mHC and vision weights by the sizes in
config.json. One element short was a heap read past the buffer.
+A matrix of the wrong shape: load_mat() took rows and columns from the header,
+and mm() writes w->rows values per token and reads w->columns. One row more was a
+heap write past the output buffer, one column more a read past the input; the same
+held for a dense int4 container, and for a shared expert wider than the FFN
+buffers, which config.json can ask for through n_shared_experts.
+
Runs in the GLM-5.3 oracle job of check.yml, on the streaming fixture it builds
(the same one test_glm53_context_exceeded uses):
COLI_GLM53_FIXTURE=/tmp/glm53_stream-i4 python -m unittest -v tests.test_glm53_hostile_weights
+
+and the matrix shapes once more on the f32 fixture, whose routed experts are
+resident and so pass through load_mat() too:
+
+ COLI_GLM53_FIXTURE=/tmp/glm53_mm python -m unittest -v \
+ tests.test_glm53_hostile_weights.Glm53MatrixShapeTest
"""
import json
import math
import os
+import struct
import subprocess
import sys
import tempfile
@@ -24,7 +37,8 @@ import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
-from safetensors_edit import copy_fixture, fill_nan, shape_of, shrink # noqa: E402
+from safetensors_edit import (copy_fixture, dtype_of, fill_nan, put, # noqa: E402
+ reshape, shape_of, shrink)
HERE = Path(__file__).resolve().parent.parent
BINARY = next((path for path in (HERE / "glm53.exe", HERE / "glm53") if path.exists()), None)
@@ -61,6 +75,37 @@ F32_TENSORS = ["model.language_model." + name for name in (
"blocks.0.mlp.down_proj.weight", "blocks.0.mlp.down_proj.bias",
)]
+# Every matrix glm53 loads through load_mat(), once per shape rule: layer 0 holds the
+# KDA projections and the dense MLP, layer 3 the MLA + indexer and the shared expert.
+MATRICES = ["lm_head.weight"] + ["model.language_model." + name for name in (
+ "layers.0.self_attn.q_proj.weight", "layers.0.self_attn.k_proj.weight",
+ "layers.0.self_attn.v_proj.weight", "layers.0.self_attn.o_proj.weight",
+ "layers.0.self_attn.g_a_proj.weight", "layers.0.self_attn.g_b_proj.weight",
+ "layers.0.self_attn.f_a_proj.weight", "layers.0.self_attn.f_b_proj.weight",
+ "layers.0.self_attn.b_proj.weight",
+ "layers.0.mlp.gate_proj.weight", "layers.0.mlp.up_proj.weight",
+ "layers.0.mlp.down_proj.weight",
+ "layers.3.self_attn.q_a_proj.weight", "layers.3.self_attn.q_b_proj.weight",
+ "layers.3.self_attn.kv_a_proj_with_mqa.weight", "layers.3.self_attn.o_proj.weight",
+ "layers.3.self_attn.indexer.wq_b.weight", "layers.3.self_attn.indexer.wk.weight",
+ "layers.3.self_attn.indexer.weights_proj.weight",
+ "layers.3.self_attn.indexer.index_kpool_compress_gate",
+ "layers.3.mlp.shared_experts.gate_proj.weight",
+ "layers.3.mlp.shared_experts.up_proj.weight",
+ "layers.3.mlp.shared_experts.down_proj.weight",
+)]
+# A routed expert passes through load_mat() only when the fixture keeps it in f32.
+EXPERTS = ["model.language_model.layers.3.mlp.experts.0." + name + ".weight"
+ for name in ("gate_proj", "up_proj", "down_proj")]
+SHARED = "model.language_model.layers.3.mlp.shared_experts."
+
+
+def to_int4(snapshot, name, rows, columns):
+ """Store `name` as the dense int4 container load_mat() takes as it is."""
+ put(snapshot, name, "U8", [rows, columns // 2], bytes(rows * columns // 2))
+ put(snapshot, name + ".qs", "F32", [rows * columns // 64],
+ struct.pack("<f", 0.01) * (rows * columns // 64), beside=name)
+
def image_run(snapshot):
"""The fixture's own prompt with its image: every text and vision weight is read."""
@@ -153,5 +198,64 @@ class Glm53ShortTensorTest(unittest.TestCase):
self.assertIn("the config needs", result.stderr)
[email protected](BINARY, "glm53 engine is not built")
[email protected](FIXTURE.name and (FIXTURE / "patches.f32").is_file(),
+ "COLI_GLM53_FIXTURE not set to a GLM-5.3-Flash container with an image")
+class Glm53MatrixShapeTest(unittest.TestCase):
+ def assertRefused(self, snapshot, message):
+ result = image_run(snapshot)
+ for marker in SANITIZER:
+ self.assertNotIn(marker, result.stderr, result.stderr[-4000:])
+ self.assertNotEqual(result.returncode, 0, result.stdout)
+ self.assertIn(message, result.stderr)
+
+ def test_a_matrix_one_row_or_column_off_is_refused_at_load(self):
+ resident = [name for name in EXPERTS if dtype_of(FIXTURE, name) == "F32"]
+ for name in MATRICES + resident:
+ rows, columns = shape_of(FIXTURE, name)
+ for shape in ([rows + 1, columns], [rows, columns + 1]):
+ with self.subTest(name=name, shape=shape), \
+ tempfile.TemporaryDirectory() as scratch:
+ snapshot = copy_fixture(FIXTURE, Path(scratch) / "model")
+ reshape(snapshot, name, shape)
+ self.assertRefused(snapshot, f"{name}: {shape[0]} x {shape[1]}, "
+ f"the config needs {rows} x {columns}")
+
+ def test_an_int4_matrix_takes_its_shape_from_the_config(self):
+ name = "model.language_model.layers.3.self_attn.o_proj.weight"
+ rows, columns = shape_of(FIXTURE, name)
+ with tempfile.TemporaryDirectory() as scratch:
+ snapshot = copy_fixture(FIXTURE, Path(scratch) / "model")
+ to_int4(snapshot, name, rows, columns)
+ result = image_run(snapshot)
+ for marker in SANITIZER:
+ self.assertNotIn(marker, result.stderr, result.stderr[-4000:])
+ self.assertEqual(result.returncode, 0, result.stderr[-4000:])
+ # the last one has the right byte count, split into twice the rows
+ for shape in ([rows + 1, columns], [rows, columns + 64], [rows * 2, columns // 2]):
+ with self.subTest(shape=shape), tempfile.TemporaryDirectory() as scratch:
+ snapshot = copy_fixture(FIXTURE, Path(scratch) / "model")
+ to_int4(snapshot, name, *shape)
+ self.assertRefused(snapshot, f"{name}: {shape[0]} rows and "
+ f"{shape[0] * shape[1]} values, "
+ f"the config needs {rows} x {columns}")
+
+ def test_a_shared_expert_wider_than_the_ffn_buffers_is_refused(self):
+ with tempfile.TemporaryDirectory() as scratch:
+ snapshot = copy_fixture(FIXTURE, Path(scratch) / "model")
+ config = json.loads((snapshot / "config.json").read_text())
+ text = config["text_config"]
+ widest = max(text["intermediate_size"], text["moe_intermediate_size"])
+ shared = widest // text["moe_intermediate_size"] + 1
+ text["n_shared_experts"] = shared
+ (snapshot / "config.json").write_text(json.dumps(config))
+ # the file agrees with that config, so only the buffers can stop it
+ hidden, width = text["hidden_size"], text["moe_intermediate_size"] * shared
+ reshape(snapshot, SHARED + "gate_proj.weight", [width, hidden])
+ reshape(snapshot, SHARED + "up_proj.weight", [width, hidden])
+ reshape(snapshot, SHARED + "down_proj.weight", [hidden, width])
+ self.assertRefused(snapshot, f"n_shared_experts={shared} does not fit the FFN buffers")
+
+
if __name__ == "__main__":
unittest.main()