Run frontier MoE models on hardware you already own β pure C, zero deps, experts streamed from disk. Tiny engine, immense model. π¦
C
test: token-exact parity gate β local vs cluster-delegated sharding (#7)
eli4982f660b38a
diff --git a/c/tests/test_cluster_sharding.py b/c/tests/test_cluster_sharding.pynew file mode 100644index 00000000..2b111850--- /dev/null+++ b/c/tests/test_cluster_sharding.py@@ -0,0 +1,212 @@+"""Token-exact parity gate: local vs cluster-delegated expert sharding (#7).++Mirrors test_dense_sharding.py (#550) but STRONGER. #550 asserted only that the+baseline and delegated runs produce *equal* teacher-forcing signatures. This gate+asserts BOTH (a) identical token signatures AND (b) ZERO `[ORACLE] mismatch`+lines in BOTH runs β i.e. the local CPU run must already reproduce the+transformers oracle token-exactly, and delegating the routed-expert shard to a+cluster worker must not perturb a single position.++The engine routes ONLY routed experts to the worker: `cluster_moe_batch` shards+`uniq[]`, which `moe()` builds exclusively from the per-position routed expert+ids (`idxs[]`); the shared expert is computed locally on the coordinator in both+the baseline and delegated runs, so it is not part of the shard under test.++Fixtures (ticket #3, generated by tools/make_glm_oracle.py β regenerated, not+committed):+ glm_tiny_fmt6/ fmt=6 (E8/IQ3) routed experts β the ONLY format that carries+ the activation rotation, hence the only one that exercises the+ worker's `e8_rot_rows` pre-rotation (the fmt=6 bug under test).+ glm_tiny_fmt4/ fmt=4 (grouped int4) routed experts β the no-rotation control.++Regeneration (run from c/):+ python3 tools/make_glm_oracle.py --fmt6+ python3 tools/make_glm_oracle.py --fmt4++Determinism: both the worker and the coordinator run the SAME c/colibri binary+(same ARCH) with the SAME numeric-path env block, so the comparison is+meaningful rather than accidental.+"""++import os+import re+import socket+import subprocess+import time+import unittest+from pathlib import Path+++HERE = Path(__file__).resolve().parent+C_DIR = HERE.parent+ENGINE = C_DIR / "colibri"+FMT6 = C_DIR / "glm_tiny_fmt6"+FMT4 = C_DIR / "glm_tiny_fmt4"++# cap, ebits, dbits β same order the engine parses argv (c/colibri.c main()).+ENGINE_ARGS = ["64", "16", "16"]++# Numeric-path determinism pinning, applied to BOTH the worker and the+# coordinator. The worker is always CPU (it returns from main() before GPU+# init), and both coordinator runs use the same binary, so ARCH matches.+_NUMERIC_ENV = {+ "IDOT": "0",+ "I4S": "1",+ "COLI_NO_FUSED_PAIR": "1",+ "SPEC_PIN": "0",+ "XEXP": "0",+ "I4_ACC512": "0",+ "I3_AVX512": "0",+ "DRAFT": "0",+ "COLI_CUDA": "0",+ "COLI_METAL": "0",+ "COLI_VULKAN": "0",+ "COLI_NO_OMP_TUNE": "1",+}+++def _fixture_ok(d: Path) -> bool:+ return (+ (d / "config.json").exists()+ and (d / "model.safetensors").exists()+ and (d / "ref_glm.json").exists()+ )+++def _available() -> bool:+ return ENGINE.exists() and _fixture_ok(FMT6)+++def _skip_reason() -> str:+ if not ENGINE.exists():+ return "colibri is not built (run: make colibri)"+ return "glm_tiny_fmt6 fixture absent (run: python3 tools/make_glm_oracle.py --fmt6)"+++def _free_port() -> int:+ with socket.socket() as sock:+ sock.bind(("127.0.0.1", 0))+ return sock.getsockname()[1]+++def _tf_signature(result: subprocess.CompletedProcess[str]):+ match = re.search(+ r"PREFILL \(teacher-forcing\).*:\s+(\d+)/(\d+) positions",+ result.stdout,+ )+ mismatches = tuple(+ line for line in result.stderr.splitlines() if line.startswith("[ORACLE] mismatch")+ )+ return (match.groups() if match else None, mismatches)++[email protected](_available(), _skip_reason())+class ClusterShardingParityTest(unittest.TestCase):+ """Local CPU must equal cluster-delegated expert sharding, token-exact."""++ def _run_parity(self, fixture_dir: Path):+ port = _free_port()+ worker_env = {+ **os.environ,+ "SNAP": str(fixture_dir),+ "EXPERT_WORKER": "1",+ "CLUSTER_WORKER_PORT": str(port),+ **_NUMERIC_ENV,+ }+ worker = subprocess.Popen(+ [str(ENGINE), *ENGINE_ARGS],+ cwd=C_DIR,+ env=worker_env,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ )+ try:+ deadline = time.monotonic() + 10+ while time.monotonic() < deadline:+ if worker.poll() is not None:+ stderr = worker.stderr.read() if worker.stderr else ""+ self.fail(f"cluster worker exited early: {stderr}")+ try:+ with socket.create_connection(("127.0.0.1", port), timeout=0.1):+ break+ except OSError:+ time.sleep(0.05)+ else:+ self.fail("cluster worker did not start listening")++ common_env = {+ **os.environ,+ "SNAP": str(fixture_dir),+ "REF": str(fixture_dir / "ref_glm.json"),+ "TF": "1",+ "TEMP": "0",+ **_NUMERIC_ENV,+ }+ baseline = subprocess.run(+ [str(ENGINE), *ENGINE_ARGS],+ cwd=C_DIR,+ env=common_env,+ capture_output=True,+ text=True,+ check=False,+ )+ delegated = subprocess.run(+ [str(ENGINE), *ENGINE_ARGS],+ cwd=C_DIR,+ env={**common_env, "CLUSTER_WORKERS": f"127.0.0.1:{port}"},+ capture_output=True,+ text=True,+ check=False,+ )+ self.assertEqual(baseline.returncode, 0, baseline.stderr)+ self.assertEqual(delegated.returncode, 0, delegated.stderr)++ base_sig = _tf_signature(baseline)+ del_sig = _tf_signature(delegated)+ self.assertIsNotNone(+ base_sig[0],+ f"baseline produced no teacher-forcing signature:\n"+ f"stdout={baseline.stdout}\nstderr={baseline.stderr}",+ )+ self.assertEqual(+ base_sig[1],+ (),+ f"baseline mismatched the oracle ({base_sig[0]}): {base_sig[1]}",+ )+ self.assertEqual(+ del_sig[1],+ (),+ f"delegated mismatched the oracle ({del_sig[0]}): {del_sig[1]}",+ )+ self.assertEqual(+ base_sig,+ del_sig,+ "cluster delegation changed teacher-forced token predictions",+ )+ finally:+ worker.terminate()+ try:+ worker.wait(timeout=2)+ except subprocess.TimeoutExpired:+ worker.kill()+ worker.wait()+ for stream in (worker.stdout, worker.stderr):+ if stream is not None:+ stream.close()++ def test_fmt6_parity(self):+ """fmt=6 (rotation-bearing) routed experts: worker must rotate the input."""+ self._run_parity(FMT6)++ @unittest.skipUnless(+ _fixture_ok(FMT4),+ "glm_tiny_fmt4 fixture absent (run: python3 tools/make_glm_oracle.py --fmt4)",+ )+ def test_fmt4_parity(self):+ """fmt=4 (no-rotation control) routed experts."""+ self._run_parity(FMT4)+++if __name__ == "__main__":+ unittest.main()