Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
fix(convert): refuse a checkpoint this converter cannot serve (#1305)
Vincenzo Fornaroa642a8b61f89
diff --git a/c/tests/test_convert_guard.py b/c/tests/test_convert_guard.pynew file mode 100644index 00000000..8e84861f--- /dev/null+++ b/c/tests/test_convert_guard.py@@ -0,0 +1,85 @@+"""La guardia di famiglia del convertitore GLM-5.2 (#1304).++`coli convert` accetta qualunque --repo ma il convertitore serve una famiglia+sola. Su Qwen3.8 (BF16) i tensori non riconosciuti passavano upcastati a f32:+ogni shard raddoppiava, e il reporter di #1304 si e' fermato a 424 GB scritti.++Le due meta' del test:+- comportamento: GLM-5.2 passa, ogni altra famiglia viene rifiutata con+ l'indicazione giusta, l'ignoto viene rifiutato senza indovinare;+- contratto: gli insiemi della guardia sono copie di family_registry.py, e una+ copia che diverge e' il difetto che la guardia esiste per curare. Chi+ aggiunge o rinomina una famiglia fallisce qui, non su un disco pieno.+"""+import os+import sys+import unittest++try:+ import numpy # noqa: F401 -- il modulo del convertitore lo importa in testa+except ImportError:+ raise unittest.SkipTest("numpy not installed")++sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "tools"))+sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))+from convert_fp8_to_int4 import ( # noqa: E402+ GLM52_MODEL_TYPES,+ OTHER_FAMILY_PATHS,+ check_model_family,+)+from family_registry import FAMILIES # noqa: E402+++class ConvertGuardTest(unittest.TestCase):+ def test_glm52_passes(self):+ for model_type in sorted(GLM52_MODEL_TYPES):+ check_model_family({"model_type": model_type}, "x") # nessuna eccezione++ def test_every_other_family_is_refused_with_its_own_pointer(self):+ for family in FAMILIES:+ if family.id == "glm":+ continue+ for model_type in family.model_types:+ with self.assertRaises(SystemExit) as caught:+ check_model_family({"model_type": model_type}, "some/repo")+ message = str(caught.exception)+ self.assertIn(model_type, message)+ # il rifiuto deve dire DOVE andare, non solo no: e' la+ # differenza fra una guardia e un muro+ self.assertTrue("tools/" in message or "docs/" in message or+ "FP8" in message,+ f"{model_type}: refusal has no pointer:\n{message}")++ def test_qwen38_refusal_says_no_conversion_exists(self):+ with self.assertRaises(SystemExit) as caught:+ check_model_family({"model_type": "qwen4_exp"}, "Qwen/Qwen3.8-Flash-Next")+ self.assertIn("NOT converted", str(caught.exception))+ self.assertIn("FP8", str(caught.exception))++ def test_unknown_and_missing_types_are_refused_not_guessed(self):+ for config in ({"model_type": "llama"}, {"model_type": ""}, {}):+ with self.assertRaises(SystemExit):+ check_model_family(config, "x")++ def test_guard_sets_match_the_registry(self):+ """Il contratto anti-divergenza: la guardia deve conoscere ESATTAMENTE+ le famiglie del registry. Se una famiglia nuova arriva senza una voce+ qui, il suo checkpoint passerebbe alla via 'ignoto' con un messaggio+ generico invece del puntatore giusto -- non un disastro, ma il test lo+ segnala subito; se GLM-5.2 rinomina un model_type, la guardia+ rifiuterebbe il modello che esiste per servire, e questo E' un+ disastro."""+ glm = next(f for f in FAMILIES if f.id == "glm")+ self.assertEqual(GLM52_MODEL_TYPES, set(glm.model_types),+ "la guardia e family_registry non concordano su cosa "+ "sia GLM-5.2: il convertitore rifiuterebbe il suo "+ "stesso modello")+ others = {mt for f in FAMILIES if f.id != "glm" for mt in f.model_types}+ self.assertEqual(others, set(OTHER_FAMILY_PATHS),+ "una famiglia del registry non ha la sua voce nella "+ "guardia (o la guardia ne elenca una rimossa): il "+ "puntatore per-famiglia non verrebbe mostrato")+++if __name__ == "__main__":+ unittest.main()diff --git a/c/tools/convert_fp8_to_int4.py b/c/tools/convert_fp8_to_int4.pyindex 6b9c9a1d..d1cf02d2 100644--- a/c/tools/convert_fp8_to_int4.py+++ b/c/tools/convert_fp8_to_int4.py@@ -32,6 +32,63 @@ import numpy as np_positioned_write_lock = threading.Lock()+# ---------- guardia di famiglia (#1304) ----------+# Questo convertitore serve UNA famiglia: GLM-5.2. Ma `coli convert` accetta+# qualunque --repo, e in una settimana due utenti gli hanno dato Qwen3.8:+# i tensori BF16 che non riconosce come esperti GLM passano upcastati a f32,+# ogni shard raddoppia, e #1304 si e' fermato a 424 GB scritti su 360 di+# sorgente. Il controllo del model_type costa 5 KB di config.json e va fatto+# PRIMA del primo shard, non dopo il disco pieno.+#+# I due insiemi qui sotto sono copie di family_registry.py, e una copia che+# diverge e' esattamente il difetto che questa guardia cura: il test+# tests/test_convert_guard.py li confronta col registry e fallisce alla prima+# famiglia aggiunta o rinominata.+GLM52_MODEL_TYPES = {"glm_moe_dsa", "glm5_moe", "glm"}+OTHER_FAMILY_PATHS = {+ "glm5_next": "GLM-5.3-Flash: use tools/convert_glm53.py",+ "glm5_next_text": "GLM-5.3-Flash: use tools/convert_glm53.py",+ "qwen4_exp": "Qwen3.8-Flash-Next is NOT converted: download the official "+ "FP8 checkpoint (Qwen/Qwen3.8-Flash-Next-FP8) and run it "+ "directly; see docs/qwen38.md and issue #1304",+ "qwen4_exp_text": "Qwen3.8-Flash-Next is NOT converted: download the official "+ "FP8 checkpoint (Qwen/Qwen3.8-Flash-Next-FP8) and run it "+ "directly; see docs/qwen38.md and issue #1304",+ "qwen3_5_moe": "Qwen3.6: use tools/convert_qwen36.py",+ "qwen3_5_moe_text":"Qwen3.6: use tools/convert_qwen36.py",+ "inkling_mm_model":"Inkling: use tools/convert_inkling_int4.py",+ "inkling": "Inkling: use tools/convert_inkling_int4.py",+ "olmoe": "OLMoE: use tools/convert_olmoe.py",+ "kimi_k3": "Kimi K3: see docs/kimi_k3.md for its container pipeline",+ "kimi_linear": "Kimi K3: see docs/kimi_k3.md for its container pipeline",+ "deepseek_v4": "DeepSeek V4: see docs/deepseek-v4.md, section Download",+}+++def check_model_family(config, where):+ """Ferma il convertitore su un checkpoint che non e' GLM-5.2.++ `config` e' il config.json del checkpoint gia' parsato; `where` dice al+ messaggio da dove viene (un path o un repo id). Ritorna in silenzio per+ GLM-5.2; esce con indicazione per-famiglia per tutto il resto.+ """+ model_type = config.get("model_type")+ if not isinstance(model_type, str) or not model_type:+ raise SystemExit(f"ERROR: {where}: config.json has no usable model_type; "+ "refusing to guess. This converter is for GLM-5.2 only.")+ if model_type in GLM52_MODEL_TYPES:+ return+ hint = OTHER_FAMILY_PATHS.get(model_type)+ if hint:+ raise SystemExit(f"ERROR: {where} is '{model_type}', not GLM-5.2.\n"+ f" This converter would silently upcast most of its "+ f"tensors and roughly double the size (#1304).\n {hint}")+ raise SystemExit(f"ERROR: {where} is '{model_type}', which this converter does "+ f"not know. It converts GLM-5.2 only; other families have "+ f"their own tools under c/tools/, and Qwen3.8 needs none.")+++def _save_file_atomic(save_file, tensors, destination, **kwargs):destination = os.fspath(destination)temporary = destination + ".tmp"@@ -636,6 +693,11 @@ def main():os.makedirs(a.outdir, exist_ok=True)if a.indir: # conversione locale (test)+ cfg_path = os.path.join(a.indir, "config.json")+ if os.path.exists(cfg_path):+ with open(cfg_path) as fh:+ check_model_family(json.load(fh), a.indir)+ # niente config.json: fixture sintetiche (glm_tiny) -- si procede come sempreshards = sorted(glob.glob(os.path.join(a.indir, "*.safetensors")))from safetensors.numpy import save_file# #383: se l'indice c'e', i passaggi --mtp/--indexer convertono SOLO gli shard@@ -785,6 +847,19 @@ def main():os.environ.setdefault("HF_HUB_DISABLE_XET", "1") # =0 per riabilitare xet / to re-enable xetfrom huggingface_hub import HfApi, hf_hub_download+ # La guardia va qui: config.json pesa 5 KB e decide se i prossimi 300 GB+ # hanno senso. Se il repo non ha config.json si procede con un avviso, per+ # non rompere mirror atipici: il fallimento utile e' sul model_type+ # sbagliato, non sulla rete.+ try:+ with open(hf_hub_download(a.repo, "config.json")) as fh:+ check_model_family(json.load(fh), a.repo)+ except SystemExit:+ raise+ except Exception as problem:+ print(f"WARNING: could not read {a.repo}/config.json ({problem}); "+ "proceeding without the family check.")+# lock anti-doppione: DUE convertitori sulla stessa outdir si corrompono a vicenda.# EN: anti-duplicate lock: TWO converters on the same outdir corrupt each other.# fcntl is Unix-only; on Windows use msvcrt or skip locking.