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

fix: harden deep doctor input validation

billb6478e9ad57e
diff --git a/c/doctor.py b/c/doctor.py
index b87db002..fa4d63c2 100644
--- a/c/doctor.py
+++ b/c/doctor.py
@@ -11,6 +11,8 @@ from pathlib import Path
from resource_plan import GB, build_plan, discover_gpus, format_plan, memory_available
SAFETENSORS_MAX_HEADER = 512 << 20
+MODEL_INDEX_MAX_BYTES = SAFETENSORS_MAX_HEADER
+MAX_SAFETENSORS_SHARDS = 512
SAFETENSORS_DTYPES = {
"BF16": 2,
"F16": 2,
@@ -44,8 +46,8 @@ def _json_object(pairs):
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:
+ file_size = os.fstat(stream.fileno()).st_size
raw_length = stream.read(8)
if len(raw_length) != 8:
raise ValueError("short safetensors header")
@@ -103,23 +105,35 @@ def _shard_sequence_report(shards):
hf_shards.append(tuple(map(int, hf_match.groups())))
elif out_match:
out_shards.append(int(out_match.group(1)))
+ if hf_shards and out_shards:
+ return {
+ "status": "fail",
+ "summary": "model mixes filename-declared shard schemes",
+ "details": {
+ "huggingface_shards": len(hf_shards),
+ "converter_shards": len(out_shards),
+ },
+ }
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):
+ in_range = {index for index in found if 1 <= index <= total}
+ missing = max(total - len(in_range), 0)
+ unexpected = len(found - in_range)
+ duplicates = len(hf_shards) - len(found)
+ if missing or unexpected or duplicates:
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),
+ "missing_shards": missing,
+ "unexpected_shards": unexpected,
+ "duplicate_shards": duplicates,
},
}
return {
@@ -129,17 +143,20 @@ def _shard_sequence_report(shards):
}
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):
+ first = min(found)
+ last = max(found)
+ missing = last + 1 - len(found)
+ duplicates = len(out_shards) - len(found)
+ if missing or duplicates:
return {
"status": "fail",
"summary": "converter shard numbering contains gaps or duplicates",
"details": {
- "first_shard": min(found),
- "last_shard": max(found),
+ "first_shard": first,
+ "last_shard": last,
"found_shards": len(found),
- "missing_shards": len(missing),
+ "missing_shards": missing,
+ "duplicate_shards": duplicates,
"tail_completeness_declared": False,
},
}
@@ -162,8 +179,11 @@ def deep_container_report(model, mirror_dir=None):
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")
+ if len(shards) > MAX_SAFETENSORS_SHARDS:
+ raise ValueError(
+ f"more than {MAX_SAFETENSORS_SHARDS} safetensors shards "
+ "are not supported by the runtime"
+ )
tensor_sources = {}
shard_headers = {}
@@ -208,8 +228,18 @@ def deep_container_report(model, mirror_dir=None):
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)
+ with index_path.open("rb") as stream:
+ index_size = os.fstat(stream.fileno()).st_size
+ if index_size > MODEL_INDEX_MAX_BYTES:
+ raise ValueError(
+ f"model index exceeds {MODEL_INDEX_MAX_BYTES} bytes"
+ )
+ raw_index = stream.read(index_size + 1)
+ if len(raw_index) != index_size:
+ raise ValueError("model index changed while reading")
+ document = json.loads(raw_index, object_pairs_hook=_json_object)
+ if not isinstance(document, dict):
+ raise ValueError("model index is not a JSON object")
weight_map = document.get("weight_map")
if not isinstance(weight_map, dict):
raise ValueError("weight_map is not an object")
diff --git a/c/tests/test_doctor.py b/c/tests/test_doctor.py
index aeec755d..958e949f 100644
--- a/c/tests/test_doctor.py
+++ b/c/tests/test_doctor.py
@@ -5,6 +5,7 @@ import sys
import tempfile
import unittest
from pathlib import Path
+from unittest import mock
from doctor import exit_code, format_doctor, run_doctor
from resource_plan import GB
@@ -220,6 +221,41 @@ class DoctorTest(unittest.TestCase):
self.assertEqual(checks["model.shard_sequence"]["status"], "fail")
self.assertEqual(checks["model.shard_sequence"]["details"]["missing_shards"], 1)
+ def test_deep_check_rejects_converter_sequence_not_starting_at_zero(self):
+ write_shard(self.model / "out-00005.safetensors", [("five.weight", 1)])
+ write_shard(self.model / "out-00006.safetensors", [("six.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"]["first_shard"], 5)
+ self.assertEqual(checks["model.shard_sequence"]["details"]["missing_shards"], 5)
+
+ def test_deep_check_handles_sparse_large_converter_index(self):
+ write_shard(self.model / "out-1000000000000.safetensors", [
+ ("sparse.weight", 1),
+ ])
+
+ checks = self.checks_by_id(self.report(deep=True))
+ sequence = checks["model.shard_sequence"]
+
+ self.assertEqual(sequence["status"], "fail")
+ self.assertEqual(sequence["details"]["last_shard"], 1_000_000_000_000)
+ self.assertEqual(sequence["details"]["missing_shards"], 1_000_000_000_000)
+
+ def test_deep_check_rejects_mixed_shard_filename_schemes(self):
+ write_shard(self.model / "model-00001-of-00001.safetensors", [
+ ("hf.weight", 1),
+ ])
+ write_shard(self.model / "out-00000.safetensors", [("out.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.assertIn("mixes", checks["model.shard_sequence"]["summary"])
+
def test_deep_check_rejects_missing_core_tensor(self):
write_shard(self.model / "model.safetensors", [
("model.embed_tokens.weight", 1),
@@ -280,6 +316,25 @@ class DoctorTest(unittest.TestCase):
self.assertEqual(checks["model.index"]["status"], "pass")
self.assertEqual(checks["model.index"]["details"]["indexed_tensors"], len(tensors))
+ def test_deep_check_reports_non_object_model_index(self):
+ (self.model / "model.safetensors.index.json").write_text("[]")
+
+ checks = self.checks_by_id(self.report(deep=True))
+
+ self.assertEqual(checks["model.container"]["status"], "pass")
+ self.assertEqual(checks["model.index"]["status"], "fail")
+ self.assertIn("not a JSON object", checks["model.index"]["summary"])
+
+ def test_deep_check_bounds_model_index_read(self):
+ (self.model / "model.safetensors.index.json").write_text("{}")
+
+ with mock.patch("doctor.MODEL_INDEX_MAX_BYTES", 1):
+ checks = self.checks_by_id(self.report(deep=True))
+
+ self.assertEqual(checks["model.container"]["status"], "pass")
+ self.assertEqual(checks["model.index"]["status"], "fail")
+ self.assertIn("exceeds 1 bytes", checks["model.index"]["summary"])
+
def test_cli_deep_json_is_machine_readable(self):
cli = Path(__file__).parents[1] / "coli"
run = subprocess.run([