crow-ko / crow.py
Asuwa's picture
Initial release
6da28ad verified
Raw History Blame Contribute Delete
7.23 kB
"""
Talk to the crow: a ~17M-parameter model that answers only with actions and crow sounds.
pip install torch sentencepiece safetensors
python crow.py # greedy, like the evaluated replies
python crow.py --temp 0.8 # sampled, livelier
Type to the crow. Empty line = quit. /new = start over as a stranger.
The crow sees the whole conversation every turn (up to ~2,000 tokens), so it remembers how you treated it.
Adapted from tallow.py in digi-the-robot/Tallow (Apache-2.0). Same architecture; the text format differs:
speaker labels are "you:" / "crow:", and each [mood level] tag is a single tokenizer symbol ("[caution_min]").
"""
import argparse
import json
import os
from dataclasses import dataclass
import sentencepiece as spm
import torch
import torch.nn as nn
import torch.nn.functional as F
from safetensors.torch import load_file
HERE = os.path.dirname(os.path.abspath(__file__))
DEV = "cuda" if torch.cuda.is_available() else "cpu"
# ---------------------------------------------------------------- the model (Llama-style, as in upstream Tallow)
@dataclass
class Config:
vocab: int = 8192
ctx: int = 2048
d: int = 384
layers: int = 8
heads: int = 6
hidden: int = 1024
class RMSNorm(nn.Module):
def __init__(self, d, eps=1e-5):
super().__init__()
self.weight = nn.Parameter(torch.ones(d))
self.eps = eps
def forward(self, x):
xf = x.float()
return (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight).type_as(x)
def rope_tables(head_dim, ctx, base=10000.0):
inv = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim))
ang = torch.outer(torch.arange(ctx).float(), inv)
ang = torch.cat([ang, ang], dim=-1)
return ang.cos(), ang.sin()
def rotate(x, cos, sin):
x1, x2 = x.chunk(2, dim=-1)
return x * cos + torch.cat([-x2, x1], dim=-1) * sin
class Attention(nn.Module):
def __init__(self, c):
super().__init__()
self.heads, self.hd = c.heads, c.d // c.heads
self.qkv = nn.Linear(c.d, 3 * c.d, bias=False)
self.out = nn.Linear(c.d, c.d, bias=False)
def forward(self, x, cos, sin):
B, T, D = x.shape
q, k, v = self.qkv(x).split(D, dim=2)
q, k, v = (t.view(B, T, self.heads, self.hd).transpose(1, 2) for t in (q, k, v))
q, k = rotate(q, cos, sin), rotate(k, cos, sin)
a = F.scaled_dot_product_attention(q, k, v, is_causal=True)
return self.out(a.transpose(1, 2).reshape(B, T, D))
class SwiGLU(nn.Module):
def __init__(self, c):
super().__init__()
self.gate = nn.Linear(c.d, c.hidden, bias=False)
self.up = nn.Linear(c.d, c.hidden, bias=False)
self.down = nn.Linear(c.hidden, c.d, bias=False)
def forward(self, x):
return self.down(F.silu(self.gate(x)) * self.up(x))
class Block(nn.Module):
def __init__(self, c):
super().__init__()
self.norm1, self.attn = RMSNorm(c.d), Attention(c)
self.norm2, self.mlp = RMSNorm(c.d), SwiGLU(c)
def forward(self, x, cos, sin):
x = x + self.attn(self.norm1(x), cos, sin)
return x + self.mlp(self.norm2(x))
class Crow(nn.Module):
def __init__(self, c):
super().__init__()
self.c = c
self.embed = nn.Embedding(c.vocab, c.d)
self.blocks = nn.ModuleList(Block(c) for _ in range(c.layers))
self.norm = RMSNorm(c.d)
cos, sin = rope_tables(c.d // c.heads, c.ctx)
self.register_buffer("cos", cos, persistent=False)
self.register_buffer("sin", sin, persistent=False)
def forward(self, idx):
T = idx.shape[1]
x = self.embed(idx)
cos, sin = self.cos[:T].to(x.dtype), self.sin[:T].to(x.dtype)
for b in self.blocks:
x = b(x, cos, sin)
return self.norm(x) @ self.embed.weight.T # tied embeddings
# ---------------------------------------------------------------- the text format
NL = "<nl>"
def to_sp(text):
"""Line breaks -> <nl>; a space after every OPENING '*' (1st, 3rd, ... on a line)."""
lines = []
for line in text.split("\n"):
out, stars = [], 0
for i, ch in enumerate(line):
out.append(ch)
if ch == "*":
stars += 1
if stars % 2 == 1 and i + 1 < len(line) and not line[i + 1].isspace():
out.append(" ")
lines.append("".join(out))
return (NL + " ").join(lines)
def from_sp(text):
text = text.replace(NL + " ", "\n").replace(NL, "\n")
lines = []
for line in text.split("\n"):
out, stars, i = [], 0, 0
while i < len(line):
ch = line[i]
out.append(ch)
if ch == "*":
stars += 1
if stars % 2 == 1 and line[i + 1:i + 2] == " " and i + 2 < len(line) and not line[i + 2].isspace():
i += 1
i += 1
lines.append("".join(out))
return "\n".join(lines)
@torch.no_grad()
def reply(model, sp, ids, text, temp=0.0, top_k=50, max_new=80):
"""Append the user's line and the crow's reply to `ids` (the token history). Returns the reply text."""
nl = sp.piece_to_id(NL)
ids += sp.encode(to_sp(f"you: {text}")) + [nl] + sp.encode(to_sp("crow:"))
while len(ids) > model.c.ctx - max_new: # forget the oldest lines if the history is too long
cut = ids.index(nl) + 1
del ids[:cut]
out = []
for _ in range(max_new):
logits = model(torch.tensor([ids + out], device=DEV))[0, -1].float()
if temp > 0:
logits = logits / temp
logits[logits < torch.topk(logits, top_k).values[-1]] = -float("inf")
nxt = int(torch.multinomial(F.softmax(logits, -1), 1))
else:
nxt = int(logits.argmax())
if nxt in (nl, sp.eos_id()):
break
out.append(nxt)
ids += out + [nl]
line = from_sp(sp.decode(out)).strip()
if line.startswith("[") and "]" in line: # "[caution_min] ..." -> "[caution min] ..."
tag, rest = line[1:].split("]", 1)
line = f"[{tag.replace('_', ' ')}]{rest}"
return line
def load(folder=HERE):
with open(os.path.join(folder, "config.json"), encoding="utf-8") as f:
model = Crow(Config(**json.load(f)))
state = load_file(os.path.join(folder, "model.safetensors")) # stored as fp16
model.load_state_dict({k: v.float() for k, v in state.items()})
model.to(DEV).eval()
return model, spm.SentencePieceProcessor(model_file=os.path.join(folder, "tokenizer.model"))
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--temp", type=float, default=0.0, help="0 = greedy (default); try 0.8 for variety")
a = ap.parse_args()
model, sp = load()
ids = []
print("The crow is on the power line. (empty line = quit, /new = start over)\n")
while True:
you = input("you: ").strip()
if not you:
break
if you == "/new":
ids = []
print("(it doesn't know you anymore)\n")
continue
print(f"crow: {reply(model, sp, ids, you, a.temp)}\n")