Download code/tests/check_export.py from Redhanuman/pocket-storyteller: direct link, hf CLI and curl.
- Browser
- Download file 3.25 kB
-
https://huggingface.co/Redhanuman/pocket-storyteller/resolve/main/code/tests/check_export.py
- Command line
-
hf download hf://Redhanuman/pocket-storyteller/code/tests/check_export.py
-
curl -L -o check_export.py https://huggingface.co/Redhanuman/pocket-storyteller/resolve/main/code/tests/check_export.py
3.25 kB
| """Read a packed model file back in Python and write reference answers for the browser engine. | |
| python tests/check_export.py web/storyteller.bin [ckpt.pt] | |
| Writes tests/expected.json (token ids and next-piece scores for some test sentences). | |
| If a checkpoint is given, also compares validation loss: float32 checkpoint vs the packed file. | |
| """ | |
| import sys, json, struct, numpy as np, torch | |
| sys.path.insert(0, ".") | |
| from model import Config, Storyteller | |
| from tokenizer import Tokenizer, split_stories | |
| def load_packed(path): | |
| buf = open(path, "rb").read() | |
| assert buf[:4] == b"STRY" | |
| hlen = struct.unpack("<I", buf[4:8])[0] | |
| h = json.loads(buf[8:8 + hlen]); base = 8 + hlen | |
| sd = {} | |
| for t in h["tensors"]: | |
| n = int(np.prod(t["shape"])); o = base + t["offset"] | |
| if t["kind"] == "f32": | |
| sd[t["name"]] = torch.from_numpy(np.frombuffer(buf, np.float32, n, o).copy()); continue | |
| rows, bits = t["shape"][0], t["bits"] | |
| scale = np.frombuffer(buf, np.float32, rows, o).reshape(rows, 1) | |
| raw = np.frombuffer(buf, np.uint8, -(-n * bits // 8), o + 4 * rows) | |
| if bits == 8: | |
| ints = raw.view(np.int8).astype(np.float32) | |
| else: | |
| b = np.unpackbits(raw, bitorder="little")[:n * bits].reshape(n, bits) | |
| ints = (b * (1 << np.arange(bits))).sum(1).astype(np.float32) - (2 ** (bits - 1) - 1) | |
| sd[t["name"]] = torch.from_numpy((ints.reshape(t["shape"]) * scale).astype(np.float32)) | |
| return h, sd | |
| h, sd = load_packed(sys.argv[1]) | |
| cfg = Config(**h["config"]) | |
| m = Storyteller(cfg); m.load_state_dict(sd); m.eval() | |
| tok = Tokenizer(h["merges"]) | |
| texts = ["Once upon a time, there was a little fox named Pip", | |
| "Lily didn't want to go. \"I'm scared,\" she said.", | |
| "One day, Tom's mom said, \"It’s 3 o'clock!\"\n\nThey ran home—fast.", | |
| "The big red ball rolled down the hill and"] | |
| stories = list(split_stories(open("data/valid.txt", encoding="utf-8", errors="ignore").read(400_000)))[:40] | |
| out = {"cases": [], "tok": [{"text": s, "ids": tok.encode(s)} for s in texts + stories]} | |
| with torch.no_grad(): | |
| for s in texts + stories[:2]: | |
| ids = [0] + tok.encode(s)[:cfg.ctx - 1] | |
| out["cases"].append({"ids": ids[1:], "logits": [round(float(v), 5) for v in m(torch.tensor([ids]))[0, -1]]}) | |
| json.dump(out, open("tests/expected.json", "w")) | |
| print(f"wrote tests/expected.json ({len(out['cases'])} score cases, {len(out['tok'])} tokenizer cases)") | |
| if len(sys.argv) > 2: | |
| ck = torch.load(sys.argv[2], map_location="cpu") | |
| ref = Storyteller(cfg); ref.load_state_dict(ck["model"]); ref.eval() | |
| val = np.memmap("data/val.bin", dtype=np.uint16, mode="r") | |
| rng = np.random.default_rng(7); tot = [0.0, 0.0]; NB = 12 | |
| with torch.no_grad(): | |
| for _ in range(NB): | |
| ix = rng.integers(0, len(val) - cfg.ctx - 1, 32) | |
| x = torch.from_numpy(np.stack([val[i:i + cfg.ctx].astype(np.int64) for i in ix])) | |
| y = torch.from_numpy(np.stack([val[i + 1:i + 1 + cfg.ctx].astype(np.int64) for i in ix])) | |
| tot[0] += ref(x, y).item() / NB; tot[1] += m(x, y).item() / NB | |
| print(f"validation loss: float32 checkpoint {tot[0]:.4f}, packed file {tot[1]:.4f} ({tot[1]-tot[0]:+.4f})") | |