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

st.h: resolve duplicate tensor names through model.safetensors.index.json

JustVugg57e5115ac872
diff --git a/c/Makefile b/c/Makefile
index a2233128..8cb7706a 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -1233,6 +1233,9 @@ tests/test_st$(EXE): tests/test_st.c st.h json.h compat.h
tests/test_st_mirror$(EXE): tests/test_st_mirror.c st.h json.h compat.h
$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
+tests/test_st_overlay$(EXE): tests/test_st_overlay.c st.h json.h compat.h
+ $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
+
tests/test_tier$(EXE): tests/test_tier.c tier.h
$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
diff --git a/c/st.h b/c/st.h
index 4a4a4d0c..7fadfd37 100644
--- a/c/st.h
+++ b/c/st.h
@@ -427,7 +427,70 @@ static const char *st_fmt_stamp(shards *S, const char *name) {
return NULL;
}
+/* model.safetensors.index.json, consulted only when two indexed shards carry the
+ * same tensor name. Checkpoints distributed with an "overlay" shard (a community
+ * abliteration, say) keep the superseded tensors physically in the base shards
+ * and let the index say which copy is authoritative; HF transformers honours
+ * the index, and refusing the directory outright (#1479) made such checkpoints
+ * unloadable without rewriting their shards. Loaded lazily: a clean container
+ * never pays the parse (the Qwen3.8 index alone is 17 MB), and a container
+ * without an index keeps the old refusal, because then nothing says which
+ * bytes a name should resolve to. */
+typedef struct { jval *root, *map; char *arena; int *h; int hcap; int tried; } st_index;
+
+static const char *st_basename(const char *p) {
+ const char *b = strrchr(p, '/');
+#ifdef _WIN32
+ const char *b2 = strrchr(p, '\\');
+ if (b2 && (!b || b2 > b)) b = b2;
+#endif
+ return b ? b + 1 : p;
+}
+static void st_index_load(st_index *ix, const char *dir) {
+ if (ix->tried) return;
+ ix->tried = 1;
+ char path[1200]; snprintf(path, sizeof(path), "%s/model.safetensors.index.json", dir);
+ FILE *f = fopen(path, "rb");
+ if (!f) return;
+ fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET);
+ if (size <= 0 || size > (256l << 20)) { fclose(f); return; }
+ char *text = malloc((size_t)size + 1);
+ if (!text || fread(text, 1, (size_t)size, f) != (size_t)size) { free(text); fclose(f); return; }
+ text[size] = 0; fclose(f);
+ ix->root = json_parse(text, &ix->arena);
+ free(text);
+ jval *map = ix->root ? json_get(ix->root, "weight_map") : NULL;
+ if (!map || map->t != J_OBJ) { json_free(ix->root); ix->root = NULL; free(ix->arena); ix->arena = NULL; return; }
+ ix->map = map;
+ ix->hcap = 1; while (ix->hcap < map->len * 2) ix->hcap <<= 1;
+ ix->h = malloc((size_t)ix->hcap * sizeof(int));
+ if (!ix->h) { fprintf(stderr, "OOM indexing model.safetensors.index.json\n"); exit(1); }
+ for (int i = 0; i < ix->hcap; i++) ix->h[i] = -1;
+ for (int i = 0; i < map->len; i++) {
+ uint64_t hh = st_hash(map->keys[i]) & (ix->hcap - 1);
+ while (ix->h[hh] >= 0) hh = (hh + 1) & (ix->hcap - 1);
+ ix->h[hh] = i;
+ }
+}
+/* the shard basename the index declares for `name`, or NULL (no index, or name absent) */
+static const char *st_index_shard(st_index *ix, const char *name) {
+ if (!ix->map) return NULL;
+ uint64_t hh = st_hash(name) & (ix->hcap - 1);
+ while (ix->h[hh] >= 0) {
+ int i = ix->h[hh];
+ if (!strcmp(ix->map->keys[i], name))
+ return ix->map->kids[i]->t == J_STR ? ix->map->kids[i]->str : NULL;
+ hh = (hh + 1) & (ix->hcap - 1);
+ }
+ return NULL;
+}
+static void st_index_free(st_index *ix) {
+ json_free(ix->root); free(ix->arena); free(ix->h);
+ memset(ix, 0, sizeof(*ix));
+}
+
/* Scan one directory for *.safetensors shards, appending to files[] (dedup by
+
* basename, so a list of directories acts as a SEARCH PATH: the same shard
* present on two drives is taken from the first-listed one only). *added
* returns how many shards this dir contributed. */
@@ -512,6 +575,8 @@ static void st_init_multi(shards *S, const char *snap_dir, const char *extra_dir
for (int a = 0; a < nf; a++) for (int b = a+1; b < nf; b++)
if (strcmp(files[a], files[b]) > 0) { char tmp[1024]; memcpy(tmp, files[a], 1024); memcpy(files[a], files[b], 1024); memcpy(files[b], tmp, 1024); }
+ st_index ix; memset(&ix, 0, sizeof(ix));
+ int n_overlay = 0;
for (int fi = 0; fi < nf; fi++) {
int fd = st_open_fd(S, files[fi]);
int fidx = st_fidx(S, fd);
@@ -583,26 +648,45 @@ static void st_init_multi(shards *S, const char *snap_dir, const char *extra_dir
if (bad_shape) {
fprintf(stderr, "%s: tensor '%s' shape overflows int64 — refusing (hostile or corrupt file)\n",
files[fi], name); exit(1); }
- /* Refuse if `name` was already indexed from an earlier shard (see the
- * detector's block comment near the top of this function). Must run before
- * this tensor is appended, and is intentionally NOT the same check as
- * st_fmt_stamp_ingest's -- that one only ever sees the small subset of names a
- * stamping tool chose to annotate; this one sees every tensor. */
+ /* `name` already indexed from an earlier shard? The checkpoint's own index
+ * decides: the copy the index maps the name to is read, the other one is
+ * ignored (an overlay shard superseding base-shard tensors, #1479). No index,
+ * or an index that names neither shard, keeps the refusal: a directory
+ * holding both would silently read one shard's bytes for this name while
+ * any __metadata__["colibri.fmt"] stamp for it still applies uniformly. This
+ * is intentionally NOT the same check as st_fmt_stamp_ingest's -- that one
+ * only ever sees the small subset of names a stamping tool chose to
+ * annotate; this one sees every tensor. */
+ int replace_idx = -1, skip = 0;
{
uint64_t dh = st_hash(name) & (dup_cap - 1);
while (dup_idx[dh] >= 0) {
if (!strcmp(S->t[dup_idx[dh]].name, name)) {
- int prev_fidx = st_fidx(S, S->t[dup_idx[dh]].fd);
- fprintf(stderr, "%s: tensor '%s' is also indexed from shard '%s' -- duplicate "
- "tensor name across indexed shards, refusing (a directory holding both "
- "would silently read one shard's bytes for this name while any "
- "__metadata__[\"colibri.fmt\"] stamp for it still applies uniformly)\n",
- files[fi], name, prev_fidx >= 0 ? S->paths[prev_fidx] : "<unknown>");
- exit(1);
+ int prev = dup_idx[dh];
+ int prev_fidx = st_fidx(S, S->t[prev].fd);
+ const char *prev_path = prev_fidx >= 0 ? S->paths[prev_fidx] : "<unknown>";
+ st_index_load(&ix, snap_dir);
+ const char *auth = st_index_shard(&ix, name);
+ if (auth && !strcmp(auth, st_basename(files[fi]))) { replace_idx = prev; n_overlay++; }
+ else if (auth && !strcmp(auth, st_basename(prev_path))) { skip = 1; n_overlay++; }
+ else {
+ fprintf(stderr, "%s: tensor '%s' is also indexed from shard '%s' -- duplicate "
+ "tensor name across indexed shards, refusing (a directory holding both "
+ "would silently read one shard's bytes for this name while any "
+ "__metadata__[\"colibri.fmt\"] stamp for it still applies uniformly).\n"
+ " %s\n",
+ files[fi], name, prev_path,
+ ix.map ? (auth ? "model.safetensors.index.json maps it to a third shard; the index and the files disagree"
+ : "model.safetensors.index.json does not list this tensor, so it cannot say which copy is authoritative")
+ : "no model.safetensors.index.json here to say which copy is authoritative; the checkpoint's index would resolve this");
+ exit(1);
+ }
+ break;
}
dh = (dh + 1) & (dup_cap - 1);
}
}
+ if (skip) continue;
if (S->n == S->cap) {
S->cap *= 2;
st_tensor *nt = (st_tensor*)realloc(S->t, S->cap * sizeof(st_tensor));
@@ -623,14 +707,18 @@ static void st_init_multi(shards *S, const char *snap_dir, const char *extra_dir
}
free(dup_idx); dup_idx = ndup; dup_cap = new_dup_cap;
}
- st_tensor *t = &S->t[S->n++];
+ st_tensor *t;
+ if (replace_idx >= 0) { t = &S->t[replace_idx]; free(t->name); } /* overlay wins: same slot, new bytes */
+ else t = &S->t[S->n++];
memset(t, 0, sizeof(*t));
t->name = strdup(name); t->fd = fd; t->off = data_start + a0;
t->nbytes = b0 - a0; t->dtype = st_dtype_code(dt->str); t->numel = numel;
t->rank = shp->len;
/* Register this name in the duplicate detector now that t->name is
- * stable, so the next shard's scan (above) sees it. */
- { uint64_t dh = st_hash(t->name) & (dup_cap - 1);
+ * stable, so the next shard's scan (above) sees it. A replaced entry
+ * is already registered at the same index. */
+ if (replace_idx < 0) {
+ uint64_t dh = st_hash(t->name) & (dup_cap - 1);
while (dup_idx[dh] >= 0) dh = (dh + 1) & (dup_cap - 1);
dup_idx[dh] = S->n - 1; }
for (int k = 0; k < t->rank; k++) t->shape[k] = (int64_t)shp->kids[k]->num;
@@ -649,6 +737,10 @@ static void st_init_multi(shards *S, const char *snap_dir, const char *extra_dir
free(arena);
free(hdr);
}
+ if (n_overlay)
+ fprintf(stderr, "[st] %d tensor name(s) present in two shards, resolved by model.safetensors.index.json "
+ "(the copy the index maps each name to is read, the other ignored)\n", n_overlay);
+ st_index_free(&ix);
free(dup_idx); /* duplicate detector: one-time-startup scratch, superseded by S->hidx below */
/* indice hash costruito a fine indicizzazione (gli indici restano validi dopo i realloc) */
S->hcap = 1; while (S->hcap < S->n * 2) S->hcap <<= 1;
diff --git a/c/tests/test_st_overlay.c b/c/tests/test_st_overlay.c
new file mode 100644
index 00000000..01be1670
--- /dev/null
+++ b/c/tests/test_st_overlay.c
@@ -0,0 +1,108 @@
+/* #1479: two shards carrying the same tensor name are resolved by the
+ * checkpoint's model.safetensors.index.json (the copy the index maps the name
+ * to is read, the other ignored), whichever order the directory scan meets
+ * them in; without an index, or with an index that does not settle it, the
+ * historical refusal stands. */
+#include <stdio.h>
+#include <stdint.h>
+#include <string.h>
+#include <stdlib.h>
+#ifdef _WIN32
+#include <direct.h>
+#define MKDIR(p) _mkdir(p)
+#define RMDIR(p) _rmdir(p)
+#else
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#define MKDIR(p) mkdir(p, 0755)
+#define RMDIR(p) rmdir(p)
+#endif
+#include "../st.h"
+
+#define CHECK(c) do { if (!(c)) { fprintf(stderr, "%s:%d: check failed: %s\n", __FILE__, __LINE__, #c); return 1; } } while (0)
+
+/* one safetensors file with tensor `n1` = base+0..7 and, if n2, `n2` = base2+0..7 */
+static int write_shard(const char *dir, const char *file, const char *n1, float base, const char *n2, float base2) {
+ char hdr[512], path[512];
+ int hl = n2 ? snprintf(hdr, sizeof hdr, "{\"%s\":{\"dtype\":\"F32\",\"shape\":[8],\"data_offsets\":[0,32]},"
+ "\"%s\":{\"dtype\":\"F32\",\"shape\":[8],\"data_offsets\":[32,64]}}", n1, n2)
+ : snprintf(hdr, sizeof hdr, "{\"%s\":{\"dtype\":\"F32\",\"shape\":[8],\"data_offsets\":[0,32]}}", n1);
+ snprintf(path, sizeof path, "%s/%s", dir, file);
+ FILE *f = fopen(path, "wb"); if (!f) { perror(path); return -1; }
+ uint64_t n = (uint64_t)hl; fwrite(&n, 8, 1, f); fwrite(hdr, 1, (size_t)hl, f);
+ float d[8]; for (int i = 0; i < 8; i++) d[i] = base + i; fwrite(d, 4, 8, f);
+ if (n2) { for (int i = 0; i < 8; i++) d[i] = base2 + i; fwrite(d, 4, 8, f); }
+ fclose(f); return 0;
+}
+static int write_index(const char *dir, const char *json) {
+ char path[512]; snprintf(path, sizeof path, "%s/model.safetensors.index.json", dir);
+ FILE *f = fopen(path, "wb"); if (!f) return -1;
+ fputs(json, f); fclose(f); return 0;
+}
+static void wipe(const char *dir) {
+ const char *names[] = { "model-00001-of-00001.safetensors", "model-overlay-00001.safetensors",
+ "aaa-overlay.safetensors", "model.safetensors.index.json" };
+ for (int i = 0; i < 4; i++) { char p[512]; snprintf(p, sizeof p, "%s/%s", dir, names[i]); remove(p); }
+ RMDIR(dir);
+}
+static int read8(shards *S, const char *name, float *out) { return st_read_f32(S, name, out, 0) == 8; }
+
+int main(void) {
+ const char *D = "tmp_overlay";
+ float v[8];
+
+ /* 1. base scanned first, overlay second: the index points at the overlay -> replace in place */
+ wipe(D); CHECK(MKDIR(D) == 0);
+ CHECK(write_shard(D, "model-00001-of-00001.safetensors", "a", 1.f, "b", 10.f) == 0);
+ CHECK(write_shard(D, "model-overlay-00001.safetensors", "a", 100.f, NULL, 0) == 0);
+ CHECK(write_index(D, "{\"metadata\":{},\"weight_map\":{\"a\":\"model-overlay-00001.safetensors\",\"b\":\"model-00001-of-00001.safetensors\"}}") == 0);
+ { shards S; memset(&S, 0, sizeof S); st_init(&S, D);
+ CHECK(S.n == 2);
+ CHECK(read8(&S, "a", v) && v[0] == 100.f && v[7] == 107.f);
+ CHECK(read8(&S, "b", v) && v[0] == 10.f);
+ st_destroy(&S); }
+ puts("overlay after base: index copy read, stale copy ignored");
+
+ /* 2. overlay scanned first (sorts before "model-"): the stale base copy is skipped */
+ wipe(D); CHECK(MKDIR(D) == 0);
+ CHECK(write_shard(D, "aaa-overlay.safetensors", "a", 100.f, NULL, 0) == 0);
+ CHECK(write_shard(D, "model-00001-of-00001.safetensors", "a", 1.f, "b", 10.f) == 0);
+ CHECK(write_index(D, "{\"weight_map\":{\"a\":\"aaa-overlay.safetensors\",\"b\":\"model-00001-of-00001.safetensors\"}}") == 0);
+ { shards S; memset(&S, 0, sizeof S); st_init(&S, D);
+ CHECK(S.n == 2);
+ CHECK(read8(&S, "a", v) && v[0] == 100.f);
+ CHECK(read8(&S, "b", v) && v[0] == 10.f);
+ st_destroy(&S); }
+ puts("overlay before base: index copy read, stale copy ignored");
+
+ /* 3. the index keeps the base copy: the overlay's is the one ignored */
+ wipe(D); CHECK(MKDIR(D) == 0);
+ CHECK(write_shard(D, "model-00001-of-00001.safetensors", "a", 1.f, "b", 10.f) == 0);
+ CHECK(write_shard(D, "model-overlay-00001.safetensors", "a", 100.f, NULL, 0) == 0);
+ CHECK(write_index(D, "{\"weight_map\":{\"a\":\"model-00001-of-00001.safetensors\",\"b\":\"model-00001-of-00001.safetensors\"}}") == 0);
+ { shards S; memset(&S, 0, sizeof S); st_init(&S, D);
+ CHECK(S.n == 2);
+ CHECK(read8(&S, "a", v) && v[0] == 1.f);
+ st_destroy(&S); }
+ puts("index prefers the base: overlay copy ignored");
+
+#ifndef _WIN32
+ /* 4. no index, and 5. an index that does not list the name: still refused (exit 1) */
+ for (int variant = 0; variant < 2; variant++) {
+ wipe(D); CHECK(MKDIR(D) == 0);
+ CHECK(write_shard(D, "model-00001-of-00001.safetensors", "a", 1.f, "b", 10.f) == 0);
+ CHECK(write_shard(D, "model-overlay-00001.safetensors", "a", 100.f, NULL, 0) == 0);
+ if (variant == 1) CHECK(write_index(D, "{\"weight_map\":{\"b\":\"model-00001-of-00001.safetensors\"}}") == 0);
+ fflush(stdout); fflush(stderr); /* the child inherits the buffers: flush, or it replays them */
+ pid_t pid = fork(); CHECK(pid >= 0);
+ if (pid == 0) { if (!freopen("/dev/null", "w", stderr)) _exit(2); shards S; memset(&S, 0, sizeof S); st_init(&S, D); _exit(0); }
+ int status = 0; CHECK(waitpid(pid, &status, 0) == pid);
+ CHECK(WIFEXITED(status) && WEXITSTATUS(status) == 1);
+ }
+ puts("no index / index silent on the name: duplicate still refused");
+#endif
+ wipe(D);
+ puts("safetensors overlay tests: ok");
+ return 0;
+}