Skip to content

Qwen3-0.6B inference (12 KB), bare-metal bootable OS (22 KB), and from-scratch Mini-GPT trainer with live Braille TUI (32 KB) in 100% pure x86-64 NASM assembly. Zero C, zero libc, zero dependencies.

3.3 KB
Raw Blame
#!/usr/bin/env python3
"""Exercise byte vocabulary handling through the Mini-GPT CLI."""

from pathlib import Path
import struct
import subprocess
import sys
import tempfile
import unittest


BINARY = Path(__file__).resolve().parents[1] / "build/asm-gpt-train"


class TrainingDataTests(unittest.TestCase):
    def setUp(self):
        directory = tempfile.TemporaryDirectory()
        self.addCleanup(directory.cleanup)
        self.root = Path(directory.name)
        self.data = self.root / "corpus"
        self.dump = self.root / "debug"
        self.checkpoint = self.root / "model.ckpt"

    def train(self, *args):
        return subprocess.run(
            [BINARY, "--data", self.data, "--layers", "1", "--dim", "16",
             "--heads", "1", "--hidden", "16", "--steps", "1", "--batch", "1",
             "-t", "1", "--sample-every", "0", "--plain", *args],
            capture_output=True, timeout=10,
        )

    def batch(self, name):
        data = (self.dump / name).read_bytes()
        return [value for value, in struct.iter_unpack("<I", data)]

    def test_full_vocabulary(self):
        self.data.write_bytes(bytes(range(256)) * 2)
        for model in ([], ["--load", self.checkpoint]):
            with self.subTest(resumed=bool(model)):
                result = self.train("--seq", "256", "--dump-debug", self.dump,
                                    "--save", self.checkpoint, *model)
                self.assertEqual(result.returncode, 0, result.stderr)
                self.assertEqual(sorted(self.batch("batch_x.bin")), list(range(256)))
                self.assertEqual(sorted(self.batch("batch_y.bin")), list(range(256)))

    def test_checkpoint_prompt_byte_255(self):
        self.data.write_bytes(bytes(range(256)) * 2)
        self.train("--seq", "4", "--save", self.checkpoint).check_returncode()

        # Give token 255 a known greedy continuation. The residual carries its
        # first embedding component through the zeroed transformer block.
        checkpoint = self.checkpoint.read_bytes()
        header_size = 64 + 512
        weights = bytearray(len(checkpoint) - header_size)
        dim = 16
        lm_head = len(weights) - 256 * dim * 4
        struct.pack_into("<f", weights, 255 * dim * 4, 1.0)
        struct.pack_into("<f", weights, lm_head - dim * 4, 1.0)  # final RMSNorm
        struct.pack_into("<f", weights, lm_head + ord("A") * dim * 4, 1.0)
        self.checkpoint.write_bytes(checkpoint[:header_size] + weights)
        result = subprocess.run(
            [BINARY, "--load", self.checkpoint, "--sample-only", "--prompt", b"\xff",
             "--sample-tokens", "1", "--temp", "0", "-t", "1"],
            check=True, capture_output=True, timeout=10,
        )
        self.assertEqual(result.stdout, b"\xffA\n")

    def test_unknown_bytes_keep_token_zero(self):
        self.data.write_bytes(b"abc" * 32)
        self.train("--seq", "4", "--save", self.checkpoint).check_returncode()
        self.data.write_bytes(b"?" * 96)
        self.train("--load", self.checkpoint, "--dump-debug", self.dump).check_returncode()
        self.assertEqual(self.batch("batch_x.bin"), [0] * 4)
        self.assertEqual(self.batch("batch_y.bin"), [0] * 4)


if __name__ == "__main__":
    if len(sys.argv) > 1 and not sys.argv[1].startswith("-"):
        BINARY = Path(sys.argv.pop(1)).resolve()
    unittest.main()