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

convert: make multistream shard writes portable on Windows

Blaked19b16102b21
diff --git a/c/tests/test_convert_positioned_write.py b/c/tests/test_convert_positioned_write.py
new file mode 100644
index 00000000..15c3f1cf
--- /dev/null
+++ b/c/tests/test_convert_positioned_write.py
@@ -0,0 +1,89 @@
+import ast
+import os
+import tempfile
+import threading
+import types
+import unittest
+from pathlib import Path
+
+
+CONVERTER = Path(__file__).resolve().parent.parent / "tools" / "convert_fp8_to_int4.py"
+
+
+def load_positioned_write(os_module):
+ tree = ast.parse(CONVERTER.read_text(encoding="utf-8"), filename=str(CONVERTER))
+ helper = next(node for node in tree.body
+ if isinstance(node, ast.FunctionDef) and node.name == "_positioned_write")
+ namespace = {"os": os_module, "_positioned_write_lock": threading.Lock()}
+ exec(compile(ast.Module(body=[helper], type_ignores=[]), str(CONVERTER), "exec"), namespace)
+ return namespace["_positioned_write"]
+
+
+class ShortWriteFallback:
+ SEEK_SET = os.SEEK_SET
+ pwrite = None
+
+ @staticmethod
+ def lseek(fd, offset, whence):
+ return os.lseek(fd, offset, whence)
+
+ @staticmethod
+ def write(fd, data):
+ return os.write(fd, data[:2])
+
+
+class PositionedWriteTest(unittest.TestCase):
+ def setUp(self):
+ self.directory = tempfile.TemporaryDirectory()
+ self.addCleanup(self.directory.cleanup)
+ self.path = Path(self.directory.name) / "part"
+
+ def open_part(self, size):
+ self.path.write_bytes(b"\x00" * size)
+ flags = os.O_WRONLY | getattr(os, "O_BINARY", 0)
+ fd = os.open(self.path, flags)
+ self.addCleanup(os.close, fd)
+ return fd
+
+ def test_fallback_writes_disjoint_binary_chunks_exactly(self):
+ first = b"A\nB\x1aC"
+ second = b"D\x1aE\nF"
+ fd = self.open_part(len(first) + len(second))
+ positioned_write = load_positioned_write(ShortWriteFallback)
+
+ positioned_write(fd, second, len(first))
+ positioned_write(fd, first, 0)
+
+ self.assertEqual(self.path.read_bytes(), first + second)
+
+ @unittest.skipUnless(hasattr(os, "pwrite"), "os.pwrite is unavailable")
+ def test_pwrite_path_retries_short_writes(self):
+ payload = b"A\nB\x1aC"
+ fd = self.open_part(len(payload))
+
+ def short_pwrite(descriptor, data, offset):
+ return os.pwrite(descriptor, data[:2], offset)
+
+ positioned_write = load_positioned_write(
+ types.SimpleNamespace(pwrite=short_pwrite))
+ positioned_write(fd, payload, 0)
+
+ self.assertEqual(self.path.read_bytes(), payload)
+
+ def test_zero_length_write_is_an_error(self):
+ fd = self.open_part(1)
+ cases = (
+ (types.SimpleNamespace(pwrite=lambda descriptor, data, offset: 0),
+ "pwrite returned zero bytes"),
+ (types.SimpleNamespace(
+ pwrite=None, SEEK_SET=os.SEEK_SET, lseek=os.lseek,
+ write=lambda descriptor, data: 0),
+ "write returned zero bytes"),
+ )
+ for os_module, message in cases:
+ with self.subTest(message=message), self.assertRaisesRegex(OSError, message):
+ load_positioned_write(os_module)(fd, b"x", 0)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/c/tools/convert_fp8_to_int4.py b/c/tools/convert_fp8_to_int4.py
index 597642ef..ab55403b 100644
--- a/c/tools/convert_fp8_to_int4.py
+++ b/c/tools/convert_fp8_to_int4.py
@@ -25,9 +25,34 @@ USO:
# reale: scarica+converte+cancella shard per shard
python3 tools/convert_fp8_to_int4.py --repo zai-org/GLM-5.2-FP8 --outdir /path/to/glm52_i4
"""
-import os, sys, glob, json, shutil, argparse
+import os, sys, glob, json, shutil, argparse, threading
import numpy as np
+
+_positioned_write_lock = threading.Lock()
+
+
+def _positioned_write(fd, data, offset):
+ remaining = memoryview(data)
+ pwrite = getattr(os, "pwrite", None)
+ if pwrite is not None:
+ while remaining:
+ written = pwrite(fd, remaining, offset)
+ if written == 0:
+ raise OSError("pwrite returned zero bytes")
+ remaining = remaining[written:]
+ offset += written
+ return
+
+ with _positioned_write_lock:
+ os.lseek(fd, offset, os.SEEK_SET)
+ while remaining:
+ written = os.write(fd, remaining)
+ if written == 0:
+ raise OSError("write returned zero bytes")
+ remaining = remaining[written:]
+
+
# ---------- quantizzazione: identica al C (glm.c) ----------
def quant_int8(w, bits): # w: [O,I] f32 -> (qbytes U8 [O*I], scale f32 [O])
qmax = (1 << (bits - 1)) - 1
@@ -805,7 +830,8 @@ def main():
except Exception: pass
if not os.path.exists(part):
with open(part, "wb") as f: f.truncate(expected) # file sparse / sparse file
- fd = os.open(part, os.O_WRONLY)
+ flags = os.O_WRONLY | getattr(os, "O_BINARY", 0)
+ fd = os.open(part, flags)
t0 = _t.time(); nres = [0]; log_lock = threading.Lock(); stopfail = []
def worker(t):
s0, s1 = segs[t]
@@ -823,7 +849,7 @@ def main():
if not chunk: break
rem = (s1 - s0) - done[t] # mai oltre il segmento / never past the segment
if len(chunk) > rem: chunk = chunk[:rem]
- os.pwrite(fd, chunk, s0 + done[t])
+ _positioned_write(fd, chunk, s0 + done[t])
done[t] += len(chunk)
except KeyboardInterrupt: raise
except Exception as ex: