upload the chat thing
Browse files
chat.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Interactive prompt loop for micro500. Loads the model once; exit with Ctrl+C."""
|
| 2 |
+
import json
|
| 3 |
+
import sys
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from safetensors.torch import load_file
|
| 9 |
+
|
| 10 |
+
from model import MicroLM
|
| 11 |
+
|
| 12 |
+
WEIGHTS = "micro500.safetensors"
|
| 13 |
+
CONFIG = "micro500_config.json"
|
| 14 |
+
CONTEXT = 64 # characters of history fed to the model
|
| 15 |
+
N_CHARS = 300 # characters generated per prompt
|
| 16 |
+
TEMP = 0.8
|
| 17 |
+
TOP_K = 0 # 0 = disabled
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def load():
|
| 21 |
+
cfg = json.load(open(CONFIG))
|
| 22 |
+
chars = cfg["chars"]
|
| 23 |
+
net = MicroLM(len(chars), cfg["d"], cfg["h"], cfg["pad"])
|
| 24 |
+
net.load_state_dict(load_file(WEIGHTS))
|
| 25 |
+
net.eval()
|
| 26 |
+
stoi = {c: i for i, c in enumerate(chars)}
|
| 27 |
+
itos = {i: c for c, i in stoi.items()}
|
| 28 |
+
return net, stoi, itos
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@torch.no_grad()
|
| 32 |
+
def generate(net, stoi, itos, prompt, n=N_CHARS, temp=TEMP, top_k=TOP_K):
|
| 33 |
+
ids = [stoi.get(c, 0) for c in prompt.lower()] or [0]
|
| 34 |
+
start = time.perf_counter()
|
| 35 |
+
for _ in range(n):
|
| 36 |
+
x = torch.tensor([ids[-CONTEXT:]])
|
| 37 |
+
logits = net(x)[0, -1] / temp
|
| 38 |
+
if top_k:
|
| 39 |
+
v, _ = torch.topk(logits, top_k)
|
| 40 |
+
logits[logits < v[-1]] = float("-inf")
|
| 41 |
+
ids.append(torch.multinomial(F.softmax(logits, -1), 1).item())
|
| 42 |
+
elapsed = time.perf_counter() - start
|
| 43 |
+
text = "".join(itos[i] for i in ids)
|
| 44 |
+
return text, n / elapsed
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def main():
|
| 48 |
+
net, stoi, itos = load()
|
| 49 |
+
n_params = sum(p.numel() for p in net.parameters())
|
| 50 |
+
print(f"micro500 loaded ({n_params} parameters). Press Ctrl+C to quit.\n")
|
| 51 |
+
try:
|
| 52 |
+
while True:
|
| 53 |
+
prompt = input("prompt> ")
|
| 54 |
+
text, tps = generate(net, stoi, itos, prompt)
|
| 55 |
+
print(f"\n{text}\n")
|
| 56 |
+
print(f"[{tps:,.0f} tokens/sec]\n")
|
| 57 |
+
except (KeyboardInterrupt, EOFError):
|
| 58 |
+
print("\nbye")
|
| 59 |
+
sys.exit(0)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
if __name__ == "__main__":
|
| 63 |
+
main()
|