Delon Swartz commited on
Commit
6b02537
·
verified ·
1 Parent(s): 7109237

add sample_native.py

Browse files
Files changed (1) hide show
  1. sample_native.py +42 -0
sample_native.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Generate side-by-side samples from the trained native twins."""
3
+ import argparse
4
+ import torch
5
+ import torch.nn.functional as F
6
+ from tokenizers import Tokenizer
7
+ from native_kolm import TinyLM, DEV, TOK_JSON
8
+
9
+
10
+ @torch.no_grad()
11
+ def generate(model, tok, prompt, max_new=120, temperature=0.8, top_k=40, seed=0):
12
+ g = torch.Generator(device="cpu").manual_seed(seed)
13
+ ids = tok.encode(prompt).ids
14
+ x = torch.tensor([ids], device=DEV)
15
+ for _ in range(max_new):
16
+ logits, _ = model(x[:, -model.ctx:])
17
+ lg = logits[0, -1] / temperature
18
+ if top_k:
19
+ v, _ = torch.topk(lg, top_k)
20
+ lg[lg < v[-1]] = float("-inf")
21
+ p = F.softmax(lg, dim=-1).cpu()
22
+ nxt = torch.multinomial(p, 1, generator=g).item()
23
+ x = torch.cat([x, torch.tensor([[nxt]], device=DEV)], dim=1)
24
+ return tok.decode(x[0].tolist())
25
+
26
+
27
+ def main():
28
+ ap = argparse.ArgumentParser()
29
+ ap.add_argument("--prompt", default="Once upon a time")
30
+ ap.add_argument("--seed", type=int, default=0)
31
+ args = ap.parse_args()
32
+ tok = Tokenizer.from_file(TOK_JSON)
33
+ for arch in ["kolm", "transformer"]:
34
+ m = TinyLM(tok.get_vocab_size(), ctx=256, arch=arch).to(DEV)
35
+ m.load_state_dict(torch.load(f"native_{arch}.pt", map_location=DEV))
36
+ m.eval()
37
+ print(f"\n=== {arch} ===")
38
+ print(generate(m, tok, args.prompt, seed=args.seed))
39
+
40
+
41
+ if __name__ == "__main__":
42
+ main()