Download code/tests/name_probe.py from Redhanuman/pocket-storyteller: direct link, hf CLI and curl.
- Browser
- Download file 3.59 kB
-
https://huggingface.co/Redhanuman/pocket-storyteller/resolve/main/code/tests/name_probe.py
- Command line
-
hf download hf://Redhanuman/pocket-storyteller/code/tests/name_probe.py
-
curl -L -o name_probe.py https://huggingface.co/Redhanuman/pocket-storyteller/resolve/main/code/tests/name_probe.py
3.59 kB
| """Does the model keep track of who is who? | |
| python tests/name_probe.py first.bin final.bin (packed files or .pt checkpoints) | |
| Uses stories the model never saw. Whenever a story already has two or more named characters and | |
| the next word is one of their names, it asks: does the model prefer the right name over the other | |
| names in the story? Also reports how often its first guess for the next piece is right. | |
| """ | |
| import sys, numpy as np, torch | |
| sys.path.insert(0, ".") | |
| from model import Config, Storyteller | |
| from tokenizer import Tokenizer | |
| src = open("tests/check_export.py").read().split("h, sd = load_packed")[0] # reuse its reader | |
| ns = {}; exec(src, ns) | |
| tok = Tokenizer.load("data/tok4096.json") | |
| train = np.memmap("data/train.bin", dtype=np.uint16, mode="r")[:100_000_000] | |
| val = np.memmap("data/val.bin", dtype=np.uint16, mode="r") | |
| # names = capitalised single pieces that often come right after " named" in the training stories | |
| named = tok.ids[" named"] | |
| after = np.bincount(np.asarray(train[1:])[np.asarray(train[:-1]) == named], minlength=len(tok.vocab)) | |
| names = [i for i in np.argsort(-after)[:200] if after[i] >= 200 and tok.vocab[i][0] == " " and tok.vocab[i][1:].isalpha() | |
| and tok.vocab[i][1].isupper() and len(tok.vocab[i]) >= 4] | |
| is_name = np.zeros(len(tok.vocab), bool); is_name[names] = True | |
| print(f"{len(names)} names, for example:", " ".join(tok.vocab[i].strip() for i in names[:14])) | |
| # the first N stories of the validation file, each as one window of up to 256 pieces | |
| N, C = 6000, 256 | |
| starts = np.flatnonzero(np.asarray(val[:3_000_000]) == 0)[:N + 1] | |
| X = np.zeros((N, C), np.int64); L = np.zeros(N, np.int64) | |
| for k in range(N): | |
| s = np.asarray(val[starts[k]:min(starts[k + 1], starts[k] + C)]).astype(np.int64) # starts with the 0 marker | |
| X[k, :len(s)] = s; L[k] = len(s) | |
| # the spots to test: position t holds a name that is already in the story, and the story has 2+ names so far | |
| spots = [] | |
| for k in range(N): | |
| seen = [] | |
| for t in range(1, L[k]): | |
| y = X[k, t] | |
| if is_name[y]: | |
| if y in seen and len(seen) >= 2: | |
| spots.append((k, t, tuple(seen))) | |
| if y not in seen: | |
| seen.append(y) | |
| print(f"{len(spots)} spots in {N} stories where the next word is one of 2 or more characters already in the story") | |
| for path in sys.argv[1:]: | |
| if path.endswith(".pt"): | |
| ck = torch.load(path, map_location="cpu"); cfg = Config(**ck["config"]); sd = ck["model"] | |
| else: | |
| h, sd = ns["load_packed"](path); cfg = Config(**h["config"]) | |
| m = Storyteller(cfg); m.load_state_dict(sd); m.eval() | |
| right = total = 0; top1 = pieces = 0; chance = 0.0 | |
| by_row = {} | |
| for k, t, seen in spots: | |
| by_row.setdefault(k, []).append((t, seen)) | |
| with torch.no_grad(): | |
| for b in range(0, N, 100): | |
| x = torch.from_numpy(X[b:b + 100]) | |
| logits = m(x) # [100, C, vocab] | |
| pred = logits.argmax(-1).numpy() | |
| for j in range(x.shape[0]): | |
| n = L[b + j] | |
| top1 += int((pred[j, :n - 1] == X[b + j, 1:n]).sum()); pieces += n - 1 | |
| for t, seen in by_row.get(b + j, []): | |
| sc = logits[j, t - 1, list(seen)] | |
| right += int(seen[int(sc.argmax())] == X[b + j, t]); total += 1; chance += 1 / len(seen) | |
| print(f"{path}: right character {100 * right / total:.1f}% of {total} (guessing would give {100 * chance / total:.0f}%) | " | |
| f"first guess for the next piece is right {100 * top1 / pieces:.1f}% of {pieces:,}") | |