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

glm53: stop ids from config.json too, and the converter keeps them

JustVuggd799354391a1
diff --git a/c/Makefile b/c/Makefile
index a2233128..dc1a91eb 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -1124,7 +1124,7 @@ NOCUDA_LDFLAGS = $(filter-out -lcudart -lstdc++ -lcuda -L$(CUDA_HOME)/lib64 \
# GLM-5.3-Flash: routed experts stream from the int4-gs64 container.
# METAL=1 accelerates resident matrices and routed MoE; CPU remains fallback.
-glm53$(EXE): glm53.c cli_args.h st.h json.h tok.h tok_unicode.h tok_unicode_o200k.h compat.h serve_poll.h route_trace.h quant.h hyper_connections.h delta_attention.h sparse_index.h vision_tower.h backend_metal.h backend_vulkan.h edge_adapter_internal.h edge_adapters.h edge_runtime.h segment_adapter_internal.h segment_adapters.h segment_runtime.h $(METAL_OBJ) $(VK_OBJ) $(VK_SPV)
+glm53$(EXE): glm53.c cli_args.h st.h json.h stop_ids.h tok.h tok_unicode.h tok_unicode_o200k.h compat.h serve_poll.h route_trace.h quant.h hyper_connections.h delta_attention.h sparse_index.h vision_tower.h backend_metal.h backend_vulkan.h edge_adapter_internal.h edge_adapters.h edge_runtime.h segment_adapter_internal.h segment_adapters.h segment_runtime.h $(METAL_OBJ) $(VK_OBJ) $(VK_SPV)
$(CC) $(CFLAGS) glm53.c $(METAL_OBJ) $(VK_OBJ) -o glm53$(EXE) $(LDFLAGS)
kimi_k3$(EXE): kimi_k3.c cli_args.h st.h json.h tok.h tok_unicode.h tok_unicode_o200k.h compat.h quant.h omp_tune.h route_trace.h kv_prefix.h serve_codec.h backend_cuda.h backend_metal.h backend_vulkan.h edge_adapters.h edge_runtime.h edge_tok_internal.h hybrid_split.h segment_adapter_internal.h segment_adapters.h segment_runtime.h $(CUDA_OBJ) $(VK_OBJ) $(VK_SPV) $(METAL_OBJ)
@@ -1364,6 +1364,9 @@ tests/test_e8_kernel$(EXE): tests/test_e8_kernel.c quant.h
tests/test_e4m3_vector$(EXE): tests/test_e4m3_vector.c quant.h
$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
+tests/test_stop_ids$(EXE): tests/test_stop_ids.c stop_ids.h json.h
+ $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
+
tests/test_sparse_attn$(EXE): tests/test_sparse_attn.c sparse_attn.h
$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
diff --git a/c/glm53.c b/c/glm53.c
index 3af0f2cd..c0221506 100644
--- a/c/glm53.c
+++ b/c/glm53.c
@@ -68,6 +68,7 @@
#include "cli_args.h"
#include "json.h"
+#include "stop_ids.h"
#include "st.h"
#include "quant.h"
#include "tok.h"
@@ -2331,31 +2332,21 @@ static int argmax(const float *v, int n) {
/* Gli id di fine generazione. GLM ne dichiara piu' di uno (fine turno, fine
* testo, fine blocco strumenti) e fermarsi solo sul primo vuol dire vedere il
- * modello continuare a parlare oltre la sua risposta. */
+ * modello continuare a parlare oltre la sua risposta. Vengono da
+ * generation_config.json, o da config.json (top level o text_config) quando
+ * quel file non c'e': un container convertito senza generation_config.json
+ * non si fermava mai (#1478). */
static int load_stops(const char *dir, int *out, int max) {
- char path[1024];
- snprintf(path, sizeof(path), "%s/generation_config.json", dir);
- FILE *f = fopen(path, "rb");
- if (!f) return 0;
- fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET);
- char *text = malloc((size_t)size + 1);
- if (!text || fread(text, 1, (size_t)size, f) != (size_t)size) {
- free(text); fclose(f); return 0;
- }
- text[size] = 0; fclose(f);
- char *arena = NULL;
- jval *root = json_parse(text, &arena);
- int found = 0;
- if (root && root->t == J_OBJ) {
- jval *eos = json_get(root, "eos_token_id");
- if (eos && eos->t == J_NUM && found < max) out[found++] = (int)eos->num;
- else if (eos && eos->t == J_ARR)
- for (int i = 0; i < eos->len && found < max; i++)
- if (eos->kids[i]->t == J_NUM) out[found++] = (int)eos->kids[i]->num;
- }
- free(arena);
- free(text);
- return found;
+ const char *source = "";
+ int n = coli_load_stop_ids(dir, out, max, &source);
+ static int noted = 0;
+ if (!noted) {
+ noted = 1;
+ if (n) fprintf(stderr, "[glm53] %d stop id(s) from %s\n", n, source);
+ else fprintf(stderr, "[glm53] no eos_token_id in generation_config.json or config.json: "
+ "generation stops only at the token limit\n");
+ }
+ return n;
}
/* ================= protocollo serve =================
diff --git a/c/stop_ids.h b/c/stop_ids.h
new file mode 100644
index 00000000..7046f4e9
--- /dev/null
+++ b/c/stop_ids.h
@@ -0,0 +1,68 @@
+/* stop_ids.h — the end-of-generation token ids of a checkpoint.
+ *
+ * HF checkpoints declare them in two places and agree on neither: the
+ * standalone text models put `eos_token_id` at the top of config.json, the
+ * multimodal wrappers put it under `text_config`, and generation_config.json
+ * repeats it (as an int or a list) when the repo ships one. An engine that
+ * reads only generation_config.json never stops on a converted or hand-copied
+ * checkpoint that lacks the file, and produces text until --ngen runs out
+ * (#1478). So: generation_config.json first, then config.json at the top
+ * level, then config.json's text_config; the caller learns which one answered
+ * so it can say so on stderr. Returns the number of ids written to out[]. */
+#ifndef COLI_STOP_IDS_H
+#define COLI_STOP_IDS_H
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "json.h"
+
+static int coli_stop_ids_from(jval *obj, int *out, int max) {
+ if (!obj || obj->t != J_OBJ) return 0;
+ jval *eos = json_get(obj, "eos_token_id");
+ int found = 0;
+ if (eos && eos->t == J_NUM && found < max) out[found++] = (int)eos->num;
+ else if (eos && eos->t == J_ARR)
+ for (int i = 0; i < eos->len && found < max; i++)
+ if (eos->kids[i]->t == J_NUM) out[found++] = (int)eos->kids[i]->num;
+ return found;
+}
+
+static jval *coli_stop_ids_parse(const char *dir, const char *file, char **arena) {
+ char path[4096]; snprintf(path, sizeof(path), "%s/%s", dir, file);
+ FILE *f = fopen(path, "rb");
+ if (!f) return NULL;
+ fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET);
+ if (size <= 0 || size > (64l << 20)) { fclose(f); return NULL; }
+ char *text = malloc((size_t)size + 1);
+ if (!text || fread(text, 1, (size_t)size, f) != (size_t)size) { free(text); fclose(f); return NULL; }
+ text[size] = 0; fclose(f);
+ jval *root = json_parse(text, arena);
+ free(text);
+ return root;
+}
+
+/* source_out (may be NULL) names where the ids came from: "generation_config.json",
+ * "config.json", "config.json (text_config)", or "" when none declared any. */
+static int coli_load_stop_ids(const char *dir, int *out, int max, const char **source_out) {
+ static const char *files[2] = { "generation_config.json", "config.json" };
+ const char *source = "";
+ int found = 0;
+ for (int fi = 0; fi < 2 && found == 0; fi++) {
+ char *arena = NULL;
+ jval *root = coli_stop_ids_parse(dir, files[fi], &arena);
+ if (root) {
+ found = coli_stop_ids_from(root, out, max);
+ if (found) source = files[fi];
+ else if (fi == 1) {
+ found = coli_stop_ids_from(json_get(root, "text_config"), out, max);
+ if (found) source = "config.json (text_config)";
+ }
+ }
+ json_free(root); free(arena);
+ }
+ if (source_out) *source_out = source;
+ return found;
+}
+
+#endif /* COLI_STOP_IDS_H */
diff --git a/c/tests/test_convert_glm53_meta.py b/c/tests/test_convert_glm53_meta.py
new file mode 100644
index 00000000..a607d5d7
--- /dev/null
+++ b/c/tests/test_convert_glm53_meta.py
@@ -0,0 +1,75 @@
+"""#1478: the converter must leave a generation_config.json in the container
+whenever the source declares eos ids, also when the shards come from --indir
+(which used to copy no metadata at all)."""
+import importlib.util
+import json
+import os
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent.parent
+SRC = HERE / "tools" / "convert_glm53.py"
+
+try:
+ import numpy # noqa: F401 (the converter imports it at module level)
+ HAVE_NUMPY = True
+except ImportError:
+ HAVE_NUMPY = False
+
+
+def load_converter():
+ spec = importlib.util.spec_from_file_location("convert_glm53_t", SRC)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
[email protected](HAVE_NUMPY, "numpy is not installed; the converter imports it")
+class ConverterMetaTest(unittest.TestCase):
+ def setUp(self):
+ self.m = load_converter()
+ self.tmp = tempfile.TemporaryDirectory()
+ self.out = os.path.join(self.tmp.name, "out"); os.makedirs(self.out)
+ self.src = os.path.join(self.tmp.name, "src"); os.makedirs(self.src)
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def test_eos_from_text_config_and_top_level(self):
+ self.assertEqual(self.m.eos_ids_from_config({"text_config": {"eos_token_id": [1, 2]}}), [1, 2])
+ self.assertEqual(self.m.eos_ids_from_config({"eos_token_id": 7}), [7])
+ self.assertEqual(self.m.eos_ids_from_config({"eos_token_id": 7, "text_config": {"eos_token_id": [1]}}), [7])
+ self.assertEqual(self.m.eos_ids_from_config({"text_config": {}}), [])
+ self.assertEqual(self.m.eos_ids_from_config({"eos_token_id": "x"}), [])
+
+ def test_generation_config_written_from_config(self):
+ with open(os.path.join(self.out, "config.json"), "w") as f:
+ json.dump({"model_type": "glm5_next", "text_config": {"eos_token_id": [154820, 154827, 154829]}}, f)
+ self.assertEqual(self.m.ensure_generation_config(self.out), [154820, 154827, 154829])
+ with open(os.path.join(self.out, "generation_config.json")) as f:
+ self.assertEqual(json.load(f)["eos_token_id"], [154820, 154827, 154829])
+ # already there: left alone
+ self.assertIsNone(self.m.ensure_generation_config(self.out))
+
+ def test_nothing_known_writes_nothing(self):
+ with open(os.path.join(self.out, "config.json"), "w") as f:
+ json.dump({"model_type": "glm5_next"}, f)
+ self.assertIsNone(self.m.ensure_generation_config(self.out))
+ self.assertFalse(os.path.exists(os.path.join(self.out, "generation_config.json")))
+
+ def test_indir_metadata_is_carried(self):
+ for name, body in (("config.json", {"eos_token_id": 3}), ("generation_config.json", {"eos_token_id": [3, 4]}),
+ ("tokenizer.json", {})):
+ with open(os.path.join(self.src, name), "w") as f:
+ json.dump(body, f)
+ copied, missing = self.m.copy_meta_from_dir(self.src, self.out)
+ self.assertEqual(copied, ["config.json", "generation_config.json", "tokenizer.json"])
+ self.assertIn("chat_template.jinja", missing)
+ with open(os.path.join(self.out, "generation_config.json")) as f:
+ self.assertEqual(json.load(f)["eos_token_id"], [3, 4])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/c/tests/test_stop_ids.c b/c/tests/test_stop_ids.c
new file mode 100644
index 00000000..cc27cbd4
--- /dev/null
+++ b/c/tests/test_stop_ids.c
@@ -0,0 +1,68 @@
+/* stop_ids.h (#1478): eos ids come from generation_config.json, else from
+ * config.json at the top level, else from config.json's text_config, and the
+ * caller learns which; a checkpoint declaring none yields 0 and "". */
+#include <stdio.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 <unistd.h>
+#define MKDIR(p) mkdir(p, 0755)
+#define RMDIR(p) rmdir(p)
+#endif
+#include "../stop_ids.h"
+
+#define CHECK(c) do { if (!(c)) { fprintf(stderr, "%s:%d: check failed: %s\n", __FILE__, __LINE__, #c); return 1; } } while (0)
+static int put(const char *dir, const char *file, const char *text) {
+ char p[512]; snprintf(p, sizeof p, "%s/%s", dir, file);
+ FILE *f = fopen(p, "wb"); if (!f) return -1; fputs(text, f); fclose(f); return 0;
+}
+static void wipe(const char *dir) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/generation_config.json", dir); remove(p);
+ snprintf(p, sizeof p, "%s/config.json", dir); remove(p);
+ RMDIR(dir);
+}
+int main(void) {
+ const char *D = "tmp_stop_ids"; int ids[8]; const char *src = NULL;
+ wipe(D); CHECK(MKDIR(D) == 0);
+
+ /* generation_config.json wins, list form, and config.json is not consulted */
+ CHECK(put(D, "generation_config.json", "{\"eos_token_id\": [154820, 154827, 154829], \"pad_token_id\": 154820}") == 0);
+ CHECK(put(D, "config.json", "{\"eos_token_id\": 7}") == 0);
+ CHECK(coli_load_stop_ids(D, ids, 8, &src) == 3);
+ CHECK(ids[0] == 154820 && ids[1] == 154827 && ids[2] == 154829 && !strcmp(src, "generation_config.json"));
+
+ /* int form, and `max` caps a list */
+ CHECK(put(D, "generation_config.json", "{\"eos_token_id\": 42}") == 0);
+ CHECK(coli_load_stop_ids(D, ids, 8, &src) == 1 && ids[0] == 42);
+ CHECK(put(D, "generation_config.json", "{\"eos_token_id\": [1,2,3,4]}") == 0);
+ CHECK(coli_load_stop_ids(D, ids, 2, &src) == 2 && ids[1] == 2);
+
+ /* no generation_config.json: config.json top level */
+ { char p[512]; snprintf(p, sizeof p, "%s/generation_config.json", D); remove(p); }
+ CHECK(coli_load_stop_ids(D, ids, 8, &src) == 1 && ids[0] == 7 && !strcmp(src, "config.json"));
+
+ /* multimodal wrapper: only text_config declares it (the GLM-5.3-Flash layout) */
+ CHECK(put(D, "config.json", "{\"model_type\": \"glm5_next\", \"text_config\": {\"eos_token_id\": [154820, 154827]}}") == 0);
+ CHECK(coli_load_stop_ids(D, ids, 8, &src) == 2 && ids[1] == 154827 && !strcmp(src, "config.json (text_config)"));
+
+ /* a generation_config.json without eos does not shadow config.json */
+ CHECK(put(D, "generation_config.json", "{\"do_sample\": true}") == 0);
+ CHECK(coli_load_stop_ids(D, ids, 8, &src) == 2 && !strcmp(src, "config.json (text_config)"));
+
+ /* nothing anywhere */
+ CHECK(put(D, "generation_config.json", "{}") == 0);
+ CHECK(put(D, "config.json", "{\"text_config\": {}}") == 0);
+ CHECK(coli_load_stop_ids(D, ids, 8, &src) == 0 && !strcmp(src, ""));
+ /* and a missing directory is just zero, never a crash */
+ CHECK(coli_load_stop_ids("tmp_stop_ids_missing", ids, 8, NULL) == 0);
+
+ wipe(D);
+ puts("stop_ids tests: ok");
+ return 0;
+}
diff --git a/c/tools/convert_glm53.py b/c/tools/convert_glm53.py
index f0241dc9..07dd6185 100644
--- a/c/tools/convert_glm53.py
+++ b/c/tools/convert_glm53.py
@@ -44,6 +44,60 @@ META_FILES = ("config.json", "generation_config.json", "tokenizer.json",
"chat_template.jinja")
+def copy_meta_from_dir(indir, outdir):
+ """--indir: the metadata files sit next to the local shards; carry the ones
+ that exist into the container, and say which did not. Before this, --indir
+ copied none of them: a container without generation_config.json never
+ stops generating (#1478)."""
+ copied, missing = [], []
+ for meta in META_FILES:
+ src = os.path.join(indir, meta)
+ if os.path.isfile(src):
+ if not os.path.exists(os.path.join(outdir, meta)):
+ shutil.copy(src, os.path.join(outdir, meta))
+ copied.append(meta)
+ else:
+ missing.append(meta)
+ return copied, missing
+
+
+def eos_ids_from_config(config):
+ """eos_token_id as HF writes it: at the top level (text checkpoints) or under
+ text_config (multimodal wrappers such as GLM-5.3-Flash); int or list."""
+ for section in (config, config.get("text_config") if isinstance(config, dict) else None):
+ if not isinstance(section, dict):
+ continue
+ eos = section.get("eos_token_id")
+ if isinstance(eos, int):
+ return [eos]
+ if isinstance(eos, list) and eos and all(isinstance(x, int) for x in eos):
+ return list(eos)
+ return []
+
+
+def ensure_generation_config(outdir):
+ """The engine reads its stop ids from generation_config.json first and
+ config.json second; a container that has neither file carrying eos ids runs
+ to the token limit. When generation_config.json is absent and config.json
+ declares the ids, write the minimal file so every reader agrees. Returns
+ the ids written, or None when nothing was needed or nothing was known."""
+ gen = os.path.join(outdir, "generation_config.json")
+ cfg = os.path.join(outdir, "config.json")
+ if os.path.exists(gen) or not os.path.isfile(cfg):
+ return None
+ try:
+ with open(cfg, encoding="utf-8") as f:
+ ids = eos_ids_from_config(json.load(f))
+ except (OSError, ValueError):
+ return None
+ if not ids:
+ return None
+ with open(gen, "w", encoding="utf-8") as f:
+ json.dump({"eos_token_id": ids}, f, indent=2)
+ f.write("\n")
+ return ids
+
+
# ---------------------------------------------------------------- quantizzatore
def quant_int4_grouped(w, gs=64):
"""int4 group-scaled: una scala ogni `gs` elementi lungo l'asse di input.
@@ -345,6 +399,9 @@ def main():
if a.indir:
shards = sorted(x for x in os.listdir(a.indir) if x.endswith(".safetensors"))
fetch = lambda fn: os.path.join(a.indir, fn)
+ copied, missing = copy_meta_from_dir(a.indir, a.outdir)
+ print(f"[meta] copied from {a.indir}: {', '.join(copied) or 'nothing'}"
+ + (f" | not there: {', '.join(missing)}" if missing else ""), flush=True)
else:
from huggingface_hub import hf_hub_download
# Il token salvato in ~/.cache/huggingface puo' essere un OAuth scaduto
@@ -398,6 +455,14 @@ def main():
except Exception as exc: # noqa: BLE001
print(f"[meta] {meta}: {exc}", flush=True)
+ written = ensure_generation_config(a.outdir)
+ if written:
+ print(f"[meta] generation_config.json was missing: written from config.json "
+ f"(eos_token_id {written})", flush=True)
+ elif not os.path.exists(os.path.join(a.outdir, "generation_config.json")):
+ print("[meta] WARNING: no generation_config.json and no eos_token_id in config.json: "
+ "the engine will not know where the model stops", flush=True)
+
if a.limit_shards:
shards = shards[:a.limit_shards]
todo = [s for s in shards if s not in done]