Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
feat: add deep doctor preflight
bill9b2b7d15945a
diff --git a/README.md b/README.mdindex 86aad79c..4b6d6922 100644--- a/README.md+++ b/README.md@@ -259,6 +259,7 @@ the full 756 GB on disk at once:COLI_MODEL=/nvme/glm52_i4 ./coli chat # RAM budget, cache and MTP auto-detectedCOLI_MODEL=/nvme/glm52_i4 ./coli plan # inspect the planned VRAM/RAM/disk placementCOLI_MODEL=/nvme/glm52_i4 ./coli doctor # read-only readiness check+COLI_MODEL=/nvme/glm52_i4 ./coli doctor --deep # strict tensors/shards/index/mirror preflight./coli web --model /nvme/glm52_i4 # API + web dashboard on one port./coli serve --model /nvme/glm52_i4 # OpenAI-compatible API only```diff --git a/c/coli b/c/coliindex c6afcfe3..d9b13e6b 100755--- a/c/coli+++ b/c/coli@@ -551,11 +551,15 @@ def cmd_doctor(a):if vram<0: raise ValueError("--vram cannot be negative")except ValueError as error:report={"schema_version":1,"status":"error","model":os.path.abspath(a.model),+ "mode":"deep" if a.deep else "standard","checks":[{"id":"config.arguments","status":"fail","summary":str(error)}],"plan":None}print(json.dumps(report,indent=2) if a.json else format_doctor(report))return 2- report=run_doctor(a.model,ram,ctx,devices,vram,engine_path=GLM)+ report=run_doctor(+ a.model, ram, ctx, devices, vram, engine_path=GLM, deep=a.deep,+ mirror_dir=os.environ.get("COLI_MODEL_MIRROR"),+ )print(json.dumps(report,indent=2) if a.json else format_doctor(report))return exit_code(report)@@ -984,6 +988,8 @@ def main():pp.add_argument("--json",action="store_true")pd=sub.add_parser("doctor",parents=[common])pd.add_argument("--json",action="store_true",help="emit a versioned JSON report")+ pd.add_argument("--deep",action="store_true",+ help="strictly check every tensor layout, model index, and configured mirror")pr=sub.add_parser("run", parents=[common]); pr.add_argument("prompt", nargs="*")pc=sub.add_parser("chat", parents=[common])pc.add_argument("--attach", nargs="?", const="http://127.0.0.1:8000", default=None,diff --git a/c/doctor.py b/c/doctor.pyindex cbe9c870..b87db002 100644--- a/c/doctor.py+++ b/c/doctor.py@@ -4,11 +4,26 @@import osimport sysimport json+import reimport subprocessfrom pathlib import Pathfrom resource_plan import GB, build_plan, discover_gpus, format_plan, memory_available+SAFETENSORS_MAX_HEADER = 512 << 20+SAFETENSORS_DTYPES = {+ "BF16": 2,+ "F16": 2,+ "F32": 4,+ "U8": 1,+ "I8": 1,+}+REQUIRED_CORE_TENSORS = (+ "model.embed_tokens.weight",+ "model.norm.weight",+ "lm_head.weight",+)+def _check(identifier, status, summary, **details):item = {"id": identifier, "status": status, "summary": summary}@@ -17,6 +32,289 @@ def _check(identifier, status, summary, **details):return item+def _json_object(pairs):+ result = {}+ for key, value in pairs:+ if key in result:+ raise ValueError(f"duplicate JSON key: {key}")+ result[key] = value+ return result+++def _safetensors_header(path):+ """Read one bounded safetensors header without touching tensor payloads."""+ path = Path(path)+ file_size = path.stat().st_size+ with path.open("rb") as stream:+ raw_length = stream.read(8)+ if len(raw_length) != 8:+ raise ValueError("short safetensors header")+ header_length = int.from_bytes(raw_length, "little")+ if (header_length < 2 or header_length > SAFETENSORS_MAX_HEADER or+ header_length > file_size - 8):+ raise ValueError(f"invalid safetensors header length: {header_length}")+ raw_header = stream.read(header_length)+ if len(raw_header) != header_length:+ raise ValueError("short safetensors header body")+ try:+ header = json.loads(raw_header, object_pairs_hook=_json_object)+ except (UnicodeDecodeError, json.JSONDecodeError) as error:+ raise ValueError(f"invalid safetensors JSON: {error}") from error+ if not isinstance(header, dict):+ raise ValueError("safetensors header is not a JSON object")+ return file_size, raw_header, header+++def _tensor_layout(meta, payload_size):+ if not isinstance(meta, dict):+ raise ValueError("tensor metadata is not an object")+ dtype = meta.get("dtype")+ offsets = meta.get("data_offsets")+ shape = meta.get("shape")+ if dtype not in SAFETENSORS_DTYPES:+ raise ValueError(f"unsupported dtype: {dtype!r}")+ if (not isinstance(offsets, list) or len(offsets) != 2 or+ any(isinstance(value, bool) or not isinstance(value, int) for value in offsets)):+ raise ValueError("data_offsets must contain exactly two integers")+ start, end = offsets+ if start < 0 or end < start or end > payload_size:+ raise ValueError(f"data_offsets [{start}, {end}] exceed payload size {payload_size}")+ if (not isinstance(shape, list) or+ any(isinstance(value, bool) or not isinstance(value, int) or value < 0+ for value in shape)):+ raise ValueError("shape must contain only non-negative integers")+ elements = 1+ for dimension in shape:+ elements *= dimension+ if elements > (1 << 63) - 1:+ raise ValueError("shape element count exceeds int64")+ if dtype not in ("U8", "I8") and end - start != elements * SAFETENSORS_DTYPES[dtype]:+ raise ValueError("shape and dtype disagree with the tensor byte span")+ return start, end+++def _shard_sequence_report(shards):+ hf_shards = []+ out_shards = []+ for shard in shards:+ hf_match = re.fullmatch(r"model-(\d+)-of-(\d+)\.safetensors", shard.name)+ out_match = re.fullmatch(r"out-(\d+)\.safetensors", shard.name)+ if hf_match:+ hf_shards.append(tuple(map(int, hf_match.groups())))+ elif out_match:+ out_shards.append(int(out_match.group(1)))+ if hf_shards:+ declared = {total for _, total in hf_shards}+ if len(declared) != 1:+ return {"status": "fail", "summary": "shard filenames declare different totals"}+ total = declared.pop()+ found = {index for index, _ in hf_shards}+ missing = sorted(set(range(1, total + 1)) - found)+ unexpected = sorted(found - set(range(1, total + 1)))+ if missing or unexpected or len(found) != len(hf_shards):+ return {+ "status": "fail",+ "summary": "declared shard sequence is incomplete or inconsistent",+ "details": {+ "declared_shards": total,+ "found_shards": len(found),+ "missing_shards": len(missing),+ "unexpected_shards": len(unexpected),+ },+ }+ return {+ "status": "pass",+ "summary": "all filename-declared shards are present",+ "details": {"declared_shards": total, "found_shards": len(found)},+ }+ if out_shards:+ found = set(out_shards)+ expected = set(range(min(found), max(found) + 1))+ missing = sorted(expected - found)+ if missing or len(found) != len(out_shards):+ return {+ "status": "fail",+ "summary": "converter shard numbering contains gaps or duplicates",+ "details": {+ "first_shard": min(found),+ "last_shard": max(found),+ "found_shards": len(found),+ "missing_shards": len(missing),+ "tail_completeness_declared": False,+ },+ }+ return {+ "status": "pass",+ "summary": "converter shard numbering is contiguous",+ "details": {+ "first_shard": min(found),+ "last_shard": max(found),+ "found_shards": len(found),+ "tail_completeness_declared": False,+ },+ }+ return {"status": "skip", "summary": "shard filenames do not declare a sequence"}+++def deep_container_report(model, mirror_dir=None):+ """Validate all tensor headers/layouts and runtime-equivalent mirror admission."""+ model = Path(model).expanduser().resolve()+ shards = sorted(model.glob("*.safetensors"))+ if not shards:+ raise ValueError("no safetensors shards found")+ if len(shards) > 512:+ raise ValueError("more than 512 safetensors shards are not supported by the runtime")++ tensor_sources = {}+ shard_headers = {}+ tensor_count = 0+ header_bytes = 0+ payload_bytes = 0+ for shard in shards:+ try:+ file_size, raw_header, header = _safetensors_header(shard)+ except (OSError, ValueError) as error:+ raise ValueError(f"{shard.name}: {error}") from error+ payload_size = file_size - 8 - len(raw_header)+ ranges = []+ for name, meta in header.items():+ if name == "__metadata__":+ if not isinstance(meta, dict):+ raise ValueError(f"{shard.name}: __metadata__ is not an object")+ continue+ if name in tensor_sources:+ raise ValueError(+ f"duplicate tensor {name!r} in {tensor_sources[name]} and {shard.name}"+ )+ try:+ start, end = _tensor_layout(meta, payload_size)+ except ValueError as error:+ raise ValueError(f"{shard.name}: tensor {name!r}: {error}") from error+ tensor_sources[name] = shard.name+ tensor_count += 1+ ranges.append((start, end, name))+ ranges = [item for item in ranges if item[0] != item[1]]+ ranges.sort()+ for previous, current in zip(ranges, ranges[1:]):+ if current[0] < previous[1]:+ raise ValueError(+ f"{shard.name}: tensors {previous[2]!r} and {current[2]!r} overlap"+ )+ shard_headers[shard.name] = (file_size, raw_header)+ header_bytes += len(raw_header)+ payload_bytes += payload_size++ index_path = model / "model.safetensors.index.json"+ index = {"status": "skip", "summary": "model index is not present"}+ if index_path.is_file():+ try:+ document = json.loads(index_path.read_text(encoding="utf-8"),+ object_pairs_hook=_json_object)+ weight_map = document.get("weight_map")+ if not isinstance(weight_map, dict):+ raise ValueError("weight_map is not an object")+ if any(not isinstance(name, str) or not isinstance(shard, str)+ for name, shard in weight_map.items()):+ raise ValueError("weight_map keys and values must be strings")+ missing_tensors = sorted(set(weight_map) - set(tensor_sources))+ unindexed_tensors = sorted(set(tensor_sources) - set(weight_map))+ misplaced_tensors = sorted(+ name for name in set(weight_map) & set(tensor_sources)+ if weight_map[name] != tensor_sources[name]+ )+ unknown_shards = sorted(+ {name for name in weight_map.values() if name not in shard_headers}+ )+ if missing_tensors or unindexed_tensors or misplaced_tensors or unknown_shards:+ raise ValueError(+ "index disagrees with scanned tensors "+ f"(missing={len(missing_tensors)}, unindexed={len(unindexed_tensors)}, "+ f"misplaced={len(misplaced_tensors)}, unknown_shards={len(unknown_shards)})"+ )+ index = {+ "status": "pass",+ "summary": "model index matches every scanned tensor",+ "details": {"indexed_tensors": len(weight_map)},+ }+ except (OSError, UnicodeDecodeError, json.JSONDecodeError, ValueError) as error:+ index = {"status": "fail", "summary": f"model index is invalid: {error}"}++ missing_core = [name for name in REQUIRED_CORE_TENSORS if name not in tensor_sources]+ required = {+ "status": "fail" if missing_core else "pass",+ "summary": (+ f"{len(missing_core)} required core tensor(s) are missing"+ if missing_core else "required core tensors are present"+ ),+ "details": {+ "required_tensors": len(REQUIRED_CORE_TENSORS),+ "missing_tensors": missing_core,+ },+ }++ mirror = {"status": "skip", "summary": "no mirror directory is configured"}+ if mirror_dir:+ mirror_path = Path(mirror_dir).expanduser().resolve()+ accepted = 0+ missing = 0+ divergent = 0+ if not mirror_path.is_dir():+ mirror = {+ "status": "warn",+ "summary": "configured mirror directory is unavailable",+ "details": {"path": str(mirror_path), "accepted_shards": 0},+ }+ else:+ for name, (primary_size, primary_header) in shard_headers.items():+ candidate = mirror_path / name+ if not candidate.is_file():+ missing += 1+ continue+ try:+ mirror_size, mirror_header, _ = _safetensors_header(candidate)+ except (OSError, ValueError):+ divergent += 1+ continue+ if mirror_size == primary_size and mirror_header == primary_header:+ accepted += 1+ else:+ divergent += 1+ if divergent:+ status = "warn"+ summary = "one or more mirror shards would be rejected by the runtime"+ elif accepted:+ status = "pass"+ summary = "mirror shards satisfy runtime size and header admission"+ else:+ status = "warn"+ summary = "configured mirror contains no admissible primary shards"+ mirror = {+ "status": status,+ "summary": summary,+ "details": {+ "path": str(mirror_path),+ "accepted_shards": accepted,+ "missing_shards": missing,+ "divergent_shards": divergent,+ "partial_mirror_allowed": True,+ },+ }++ return {+ "container": {+ "shards": len(shards),+ "tensors": tensor_count,+ "header_bytes": header_bytes,+ "payload_bytes": payload_bytes,+ "payload_hashing": False,+ },+ "sequence": _shard_sequence_report(shards),+ "required": required,+ "index": index,+ "mirror": mirror,+ }++def cuda_linkage(engine_path):"""Return CUDA linkage state without loading the executable or CUDA runtime."""engine = Path(engine_path)@@ -50,7 +348,7 @@ def cuda_linkage(engine_path):def run_doctor(model, ram_gb=0, context=4096, gpu_indices=None, vram_gb=0, *,engine_path, available_memory=None, available_disk=None, gpus=None,- linkage=None):+ linkage=None, deep=False, mirror_dir=None):"""Collect a complete report. No model payload, engine, or CUDA context is loaded."""model = Path(model).expanduser().resolve()checks = []@@ -150,16 +448,54 @@ def run_doctor(model, ram_gb=0, context=4096, gpu_indices=None, vram_gb=0, *,checks.append(_check("placement.plan", "warn", "; ".join(plan["warnings"])))else:checks.append(_check("placement.plan", "pass", "tier placement has no warnings"))- except (OSError, ValueError, KeyError) as error:+ except (OSError, ValueError, KeyError, TypeError) as error:checks.append(_check("model.shards", "fail", str(error)))checks.append(_check("storage.disk", "skip", "storage check requires a valid model"))checks.append(_check("memory.ram", "skip", "RAM projection requires a valid model"))checks.append(_check("placement.plan", "skip", "placement requires a valid model"))+ if deep:+ try:+ deep_report = deep_container_report(model, mirror_dir=mirror_dir)+ details = deep_report["container"]+ checks.append(_check(+ "model.container", "pass",+ "all tensor headers and layouts are internally consistent",+ **details,+ ))+ sequence = deep_report["sequence"]+ checks.append(_check(+ "model.shard_sequence", sequence["status"], sequence["summary"],+ **sequence.get("details", {}),+ ))+ required = deep_report["required"]+ checks.append(_check(+ "model.required", required["status"], required["summary"],+ **required.get("details", {}),+ ))+ index = deep_report["index"]+ checks.append(_check("model.index", index["status"], index["summary"],+ **index.get("details", {})))+ mirror = deep_report["mirror"]+ checks.append(_check("storage.mirror", mirror["status"], mirror["summary"],+ **mirror.get("details", {})))+ except (OSError, ValueError) as error:+ checks.append(_check("model.container", "fail", str(error)))+ checks.append(_check(+ "model.shard_sequence", "skip",+ "shard sequence check requires a valid container",+ ))+ checks.append(_check(+ "model.required", "skip",+ "required-tensor check requires a valid container",+ ))+ checks.append(_check("model.index", "skip", "index check requires a valid container"))+ checks.append(_check("storage.mirror", "skip", "mirror check requires a valid container"))+statuses = {item["status"] for item in checks}status = "error" if "fail" in statuses else "warning" if "warn" in statuses else "ok"return {"schema_version": 1, "status": status, "model": str(model),- "checks": checks, "plan": plan}+ "mode": "deep" if deep else "standard", "checks": checks, "plan": plan}def format_doctor(report):diff --git a/c/tests/test_doctor.py b/c/tests/test_doctor.pyindex 89501471..aeec755d 100644--- a/c/tests/test_doctor.py+++ b/c/tests/test_doctor.py@@ -41,6 +41,8 @@ class DoctorTest(unittest.TestCase):(self.model / "tokenizer.json").write_text("{}")write_shard(self.model / "model.safetensors", [("model.embed_tokens.weight", 100),+ ("model.norm.weight", 8),+ ("lm_head.weight", 100),("model.layers.0.self_attn.q_a_proj.weight", 200),("model.layers.1.mlp.experts.0.gate_proj.weight", 30),("model.layers.1.mlp.experts.0.up_proj.weight", 30),@@ -79,6 +81,7 @@ class DoctorTest(unittest.TestCase):checks = self.checks_by_id(report)self.assertEqual(report["schema_version"], 1)+ self.assertEqual(report["mode"], "standard")self.assertEqual(report["status"], "ok")self.assertIsNotNone(report["plan"])self.assertEqual(checks["accelerator.cuda"]["status"], "skip")@@ -169,6 +172,126 @@ class DoctorTest(unittest.TestCase):self.assertTrue(run.stdout.lstrip().startswith("{"))self.assertTrue(run.stdout.rstrip().endswith("}"))+ def test_deep_check_validates_every_tensor_layout(self):+ report = self.report(deep=True)+ checks = self.checks_by_id(report)++ self.assertEqual(report["mode"], "deep")+ self.assertEqual(checks["model.container"]["status"], "pass")+ self.assertEqual(checks["model.container"]["details"]["shards"], 1)+ self.assertEqual(checks["model.container"]["details"]["tensors"], 8)+ self.assertFalse(checks["model.container"]["details"]["payload_hashing"])+ self.assertEqual(checks["model.shard_sequence"]["status"], "skip")+ self.assertEqual(checks["model.required"]["status"], "pass")+ self.assertEqual(checks["model.index"]["status"], "skip")+ self.assertEqual(checks["storage.mirror"]["status"], "skip")++ def test_deep_check_rejects_overlapping_tensor_ranges(self):+ header = {+ "first": {"dtype": "U8", "shape": [4], "data_offsets": [0, 4]},+ "second": {"dtype": "U8", "shape": [4], "data_offsets": [2, 6]},+ }+ raw = json.dumps(header).encode()+ shard = self.model / "model.safetensors"+ shard.write_bytes(struct.pack("<Q", len(raw)) + raw + b"\0" * 6)++ checks = self.checks_by_id(self.report(deep=True))++ self.assertEqual(checks["model.container"]["status"], "fail")+ self.assertIn("overlap", checks["model.container"]["summary"])++ def test_deep_check_rejects_duplicate_tensor_names_across_shards(self):+ write_shard(self.model / "second.safetensors", [+ ("model.embed_tokens.weight", 1),+ ])++ checks = self.checks_by_id(self.report(deep=True))++ self.assertEqual(checks["model.container"]["status"], "fail")+ self.assertIn("duplicate tensor", checks["model.container"]["summary"])++ def test_deep_check_rejects_gap_in_converter_shard_sequence(self):+ write_shard(self.model / "out-00000.safetensors", [("zero.weight", 1)])+ write_shard(self.model / "out-00002.safetensors", [("two.weight", 1)])++ checks = self.checks_by_id(self.report(deep=True))++ self.assertEqual(checks["model.container"]["status"], "pass")+ self.assertEqual(checks["model.shard_sequence"]["status"], "fail")+ self.assertEqual(checks["model.shard_sequence"]["details"]["missing_shards"], 1)++ def test_deep_check_rejects_missing_core_tensor(self):+ write_shard(self.model / "model.safetensors", [+ ("model.embed_tokens.weight", 1),+ ])++ checks = self.checks_by_id(self.report(deep=True))++ self.assertEqual(checks["model.container"]["status"], "pass")+ self.assertEqual(checks["model.required"]["status"], "fail")+ self.assertEqual(checks["model.required"]["details"]["missing_tensors"], [+ "model.norm.weight",+ "lm_head.weight",+ ])++ def test_deep_check_reports_runtime_equivalent_partial_mirror(self):+ mirror = self.root / "mirror"+ mirror.mkdir()+ primary = self.model / "model.safetensors"+ (mirror / primary.name).write_bytes(primary.read_bytes())++ checks = self.checks_by_id(self.report(deep=True, mirror_dir=mirror))+ mirror_check = checks["storage.mirror"]++ self.assertEqual(mirror_check["status"], "pass")+ self.assertEqual(mirror_check["details"]["accepted_shards"], 1)+ self.assertEqual(mirror_check["details"]["divergent_shards"], 0)+ self.assertTrue(mirror_check["details"]["partial_mirror_allowed"])++ def test_deep_check_warns_when_mirror_header_diverges(self):+ mirror = self.root / "mirror"+ mirror.mkdir()+ write_shard(mirror / "model.safetensors", [("different.weight", 620)])++ checks = self.checks_by_id(self.report(deep=True, mirror_dir=mirror))+ mirror_check = checks["storage.mirror"]++ self.assertEqual(mirror_check["status"], "warn")+ self.assertEqual(mirror_check["details"]["accepted_shards"], 0)+ self.assertEqual(mirror_check["details"]["divergent_shards"], 1)++ def test_deep_check_validates_model_index(self):+ tensors = [+ "model.embed_tokens.weight",+ "model.norm.weight",+ "lm_head.weight",+ "model.layers.0.self_attn.q_a_proj.weight",+ "model.layers.1.mlp.experts.0.gate_proj.weight",+ "model.layers.1.mlp.experts.0.up_proj.weight",+ "model.layers.1.mlp.experts.1.gate_proj.weight",+ "model.layers.1.mlp.experts.1.up_proj.weight",+ ]+ (self.model / "model.safetensors.index.json").write_text(json.dumps({+ "weight_map": {name: "model.safetensors" for name in tensors},+ }))++ checks = self.checks_by_id(self.report(deep=True))++ self.assertEqual(checks["model.index"]["status"], "pass")+ self.assertEqual(checks["model.index"]["details"]["indexed_tensors"], len(tensors))++ def test_cli_deep_json_is_machine_readable(self):+ cli = Path(__file__).parents[1] / "coli"+ run = subprocess.run([+ sys.executable, str(cli), "doctor", "--model", str(self.model),+ "--gpu", "none", "--ram", "16", "--ctx", "32", "--deep", "--json",+ ], text=True, capture_output=True, check=False)++ report = json.loads(run.stdout)+ checks = self.checks_by_id(report)+ self.assertEqual(report["mode"], "deep")+ self.assertIn("model.container", checks)+if __name__ == "__main__":unittest.main()diff --git a/docs/SETTINGS.md b/docs/SETTINGS.mdindex ef6566e4..131fafc6 100644--- a/docs/SETTINGS.md+++ b/docs/SETTINGS.md@@ -2,7 +2,7 @@Command-line settings for the two user-facing programs: the **`coli`** CLI and the **`openai_server.py`** server. The underlying `glm` engine is driven by environment variables — see [ENVIRONMENT.md](ENVIRONMENT.md).-**Generated from `upstream/dev @ 6d3ed7e`** (argparse definitions in `c/coli` and `c/openai_server.py`). See [MAINTAINING-DOCS.md](MAINTAINING-DOCS.md) to regenerate.+**Updated for the contribution based on `upstream/dev @ 21e7a35`** (argparse definitions in `c/coli` and `c/openai_server.py`). See [MAINTAINING-DOCS.md](MAINTAINING-DOCS.md) to regenerate.---@@ -21,7 +21,7 @@ Flags may also be given **after** the subcommand. Most flags map onto an engine| `build` | Build/prepare the engine. || `info` | Print model / build info. || `plan` | Show the computed RAM/VRAM placement plan (`--json` for machine-readable). |-| `doctor` | Environment/health check (`--json` for a versioned report). |+| `doctor` | Environment/health check (`--json` report, `--deep` strict preflight). || `run "<prompt>"` | One-shot generation for the given prompt (positional, may be multi-word). || `chat` | Interactive REPL chat. || `serve` | Start the OpenAI-compatible HTTP server. |@@ -74,6 +74,11 @@ Flags may also be given **after** the subcommand. Most flags map onto an engine**`bench`**: `[tasks...]` (positional), `--limit 40`, `--data <bench dir>`.**`plan` / `doctor`**: `--json`.+**`doctor`**: `--deep` strictly checks every safetensors header and tensor+layout, filename-declared shard completeness, required core tensors, an+optional model index, and runtime-equivalent size/header admission for+`COLI_MODEL_MIRROR`. It does not hash tensor payloads or load the engine.+---## `openai_server.py` — the HTTP server