Upload 7 files
Browse files
Makefile
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
PYTHON = python3
|
| 2 |
+
SP_PREFIX = amaia
|
| 3 |
+
VOCAB_SIZE = 32768
|
| 4 |
+
CKPT = amaia.pt
|
| 5 |
+
SP_MODEL = amaia.model
|
| 6 |
+
|
| 7 |
+
GUTENBERG_IDS = 84 1342 11 98 2701 1661 345 844 1952 174 5200 76 1400 2600 4300
|
| 8 |
+
|
| 9 |
+
.PHONY: all vocab train stream run clean help
|
| 10 |
+
|
| 11 |
+
all: vocab
|
| 12 |
+
|
| 13 |
+
vocab: train.txt
|
| 14 |
+
$(PYTHON) vocab.py train.txt --prefix $(SP_PREFIX) --vocab-size $(VOCAB_SIZE)
|
| 15 |
+
|
| 16 |
+
train: $(SP_MODEL)
|
| 17 |
+
$(PYTHON) train.py train.txt --sp-model $(SP_MODEL) --ckpt $(CKPT)
|
| 18 |
+
|
| 19 |
+
stream: $(SP_MODEL)
|
| 20 |
+
@echo "Streaming $(words $(GUTENBERG_IDS)) books from Project Gutenberg..."
|
| 21 |
+
@for id in $(GUTENBERG_IDS); do \
|
| 22 |
+
echo " book $$id" >&2; \
|
| 23 |
+
curl -s --max-time 30 \
|
| 24 |
+
"https://www.gutenberg.org/cache/epub/$$id/pg$$id.txt" \
|
| 25 |
+
|| curl -s --max-time 30 \
|
| 26 |
+
"https://gutenberg.org/files/$$id/$$id-0.txt"; \
|
| 27 |
+
done > /tmp/amaia_stream.txt && \
|
| 28 |
+
$(PYTHON) train.py /tmp/amaia_stream.txt --sp-model $(SP_MODEL) --ckpt $(CKPT)
|
| 29 |
+
|
| 30 |
+
run: $(CKPT)
|
| 31 |
+
@read -p "Prompt: " p && $(PYTHON) generate.py "$$p" --sp-model $(SP_MODEL) --ckpt $(CKPT)
|
| 32 |
+
|
| 33 |
+
clean:
|
| 34 |
+
rm -f $(SP_PREFIX).model $(SP_PREFIX).vocab $(CKPT) /tmp/amaia_stream.txt
|
| 35 |
+
|
| 36 |
+
help:
|
| 37 |
+
@echo ""
|
| 38 |
+
@echo " make vocab train tokenizer from train.txt"
|
| 39 |
+
@echo " make train train on local train.txt"
|
| 40 |
+
@echo " make stream download Gutenberg books and train"
|
| 41 |
+
@echo " make run interactive prompt"
|
| 42 |
+
@echo " make clean remove model files"
|
| 43 |
+
@echo ""
|
config.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass, field
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
@dataclass
|
| 6 |
+
class AmaiaConfig:
|
| 7 |
+
vocab_size: int = 32768
|
| 8 |
+
d_model: int = 128
|
| 9 |
+
n_heads: int = 4
|
| 10 |
+
n_layers: int = 4
|
| 11 |
+
max_seq: int = 256
|
| 12 |
+
dropout: float = 0.1
|
| 13 |
+
|
| 14 |
+
lr: float = 3e-4
|
| 15 |
+
lr_min: float = 1e-5
|
| 16 |
+
warmup_steps: int = 500
|
| 17 |
+
decay_steps: int = 50000
|
| 18 |
+
beta1: float = 0.9
|
| 19 |
+
beta2: float = 0.999
|
| 20 |
+
weight_decay: float = 0.1
|
| 21 |
+
grad_clip: float = 1.0
|
| 22 |
+
|
| 23 |
+
batch_size: int = 32
|
| 24 |
+
chunk_size: int = 128
|
| 25 |
+
num_workers: int = 2
|
| 26 |
+
|
| 27 |
+
ckpt_file: str = "amaia.pt"
|
| 28 |
+
sp_model: str = "amaia.model"
|
| 29 |
+
log_every: int = 100
|
| 30 |
+
ckpt_every: int = 1000
|
| 31 |
+
sample_every: int = 500
|
| 32 |
+
sample_prompt: str = "The"
|
| 33 |
+
max_new_tokens: int = 80
|
data.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import random
|
| 3 |
+
import torch
|
| 4 |
+
from torch.utils.data import IterableDataset
|
| 5 |
+
import sentencepiece as spm
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class StreamDataset(IterableDataset):
|
| 9 |
+
def __init__(self, text, sp_model_path, chunk_size, stride=None):
|
| 10 |
+
self.sp = spm.SentencePieceProcessor()
|
| 11 |
+
self.sp.Load(sp_model_path)
|
| 12 |
+
self.chunk_size = chunk_size
|
| 13 |
+
self.stride = stride or chunk_size // 2
|
| 14 |
+
ids = self.sp.Encode(text)
|
| 15 |
+
self.ids = torch.tensor(ids, dtype=torch.long)
|
| 16 |
+
|
| 17 |
+
def __iter__(self):
|
| 18 |
+
data = self.ids
|
| 19 |
+
n = len(data) - self.chunk_size - 1
|
| 20 |
+
indices = list(range(0, n, self.stride))
|
| 21 |
+
random.shuffle(indices)
|
| 22 |
+
for i in indices:
|
| 23 |
+
x = data[i : i + self.chunk_size]
|
| 24 |
+
y = data[i + 1 : i + self.chunk_size + 1]
|
| 25 |
+
yield x, y
|
| 26 |
+
|
| 27 |
+
def vocab_size(self):
|
| 28 |
+
return self.sp.GetPieceSize()
|
| 29 |
+
|
| 30 |
+
def decode(self, ids):
|
| 31 |
+
return self.sp.Decode(ids)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def load_text(path_or_stdin):
|
| 35 |
+
if path_or_stdin == "-":
|
| 36 |
+
return sys.stdin.read()
|
| 37 |
+
with open(path_or_stdin, "r", encoding="utf-8", errors="ignore") as f:
|
| 38 |
+
return f.read()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def build_vocab(text_path, sp_model_prefix, vocab_size, input_sentence_size=2000000):
|
| 42 |
+
spm.SentencePieceTrainer.Train(
|
| 43 |
+
input=text_path,
|
| 44 |
+
model_prefix=sp_model_prefix,
|
| 45 |
+
vocab_size=vocab_size,
|
| 46 |
+
model_type="bpe",
|
| 47 |
+
character_coverage=1.0,
|
| 48 |
+
input_sentence_size=input_sentence_size,
|
| 49 |
+
shuffle_input_sentence=True,
|
| 50 |
+
pad_id=3,
|
| 51 |
+
)
|
generate.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import argparse
|
| 3 |
+
import torch
|
| 4 |
+
import sentencepiece as spm
|
| 5 |
+
|
| 6 |
+
from model import Amaia
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def main():
|
| 10 |
+
parser = argparse.ArgumentParser(description="Generate text with Amaia")
|
| 11 |
+
parser.add_argument("prompt", nargs="?", default="The")
|
| 12 |
+
parser.add_argument("--ckpt", default="amaia.pt")
|
| 13 |
+
parser.add_argument("--sp-model", default="amaia.model")
|
| 14 |
+
parser.add_argument("--max-tokens", type=int, default=200)
|
| 15 |
+
parser.add_argument("--temperature",type=float, default=0.8)
|
| 16 |
+
parser.add_argument("--top-p", type=float, default=0.92)
|
| 17 |
+
args = parser.parse_args()
|
| 18 |
+
|
| 19 |
+
ckpt = torch.load(args.ckpt, map_location="cpu")
|
| 20 |
+
cfg = ckpt["cfg"]
|
| 21 |
+
model = Amaia(cfg)
|
| 22 |
+
model.load_state_dict(ckpt["model"])
|
| 23 |
+
model.eval()
|
| 24 |
+
|
| 25 |
+
sp = spm.SentencePieceProcessor()
|
| 26 |
+
sp.Load(args.sp_model)
|
| 27 |
+
|
| 28 |
+
ids = sp.Encode(args.prompt)
|
| 29 |
+
idx = torch.tensor([ids], dtype=torch.long)
|
| 30 |
+
|
| 31 |
+
with torch.no_grad():
|
| 32 |
+
out = model.generate(idx, args.max_tokens,
|
| 33 |
+
temperature=args.temperature,
|
| 34 |
+
top_p=args.top_p)
|
| 35 |
+
|
| 36 |
+
print(sp.Decode(out[0].tolist()))
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if __name__ == "__main__":
|
| 40 |
+
main()
|
model.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class CausalSelfAttention(nn.Module):
|
| 8 |
+
def __init__(self, cfg):
|
| 9 |
+
super().__init__()
|
| 10 |
+
self.n_heads = cfg.n_heads
|
| 11 |
+
self.d_head = cfg.d_model // cfg.n_heads
|
| 12 |
+
self.qkv = nn.Linear(cfg.d_model, 3 * cfg.d_model, bias=False)
|
| 13 |
+
self.proj = nn.Linear(cfg.d_model, cfg.d_model, bias=False)
|
| 14 |
+
self.dropout = nn.Dropout(cfg.dropout)
|
| 15 |
+
|
| 16 |
+
def forward(self, x):
|
| 17 |
+
B, T, C = x.shape
|
| 18 |
+
q, k, v = self.qkv(x).split(C, dim=2)
|
| 19 |
+
q = q.view(B, T, self.n_heads, self.d_head).transpose(1, 2)
|
| 20 |
+
k = k.view(B, T, self.n_heads, self.d_head).transpose(1, 2)
|
| 21 |
+
v = v.view(B, T, self.n_heads, self.d_head).transpose(1, 2)
|
| 22 |
+
y = F.scaled_dot_product_attention(q, k, v, is_causal=True,
|
| 23 |
+
dropout_p=self.dropout.p if self.training else 0.0)
|
| 24 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C)
|
| 25 |
+
return self.dropout(self.proj(y))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class FFN(nn.Module):
|
| 29 |
+
def __init__(self, cfg):
|
| 30 |
+
super().__init__()
|
| 31 |
+
self.fc1 = nn.Linear(cfg.d_model, 4 * cfg.d_model)
|
| 32 |
+
self.fc2 = nn.Linear(4 * cfg.d_model, cfg.d_model)
|
| 33 |
+
self.dropout = nn.Dropout(cfg.dropout)
|
| 34 |
+
|
| 35 |
+
def forward(self, x):
|
| 36 |
+
return self.dropout(self.fc2(F.gelu(self.fc1(x))))
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class Block(nn.Module):
|
| 40 |
+
def __init__(self, cfg):
|
| 41 |
+
super().__init__()
|
| 42 |
+
self.ln1 = nn.LayerNorm(cfg.d_model)
|
| 43 |
+
self.attn = CausalSelfAttention(cfg)
|
| 44 |
+
self.ln2 = nn.LayerNorm(cfg.d_model)
|
| 45 |
+
self.ffn = FFN(cfg)
|
| 46 |
+
|
| 47 |
+
def forward(self, x):
|
| 48 |
+
x = x + self.attn(self.ln1(x))
|
| 49 |
+
x = x + self.ffn(self.ln2(x))
|
| 50 |
+
return x
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class Amaia(nn.Module):
|
| 54 |
+
def __init__(self, cfg):
|
| 55 |
+
super().__init__()
|
| 56 |
+
self.cfg = cfg
|
| 57 |
+
self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.d_model)
|
| 58 |
+
self.pos_emb = nn.Embedding(cfg.max_seq, cfg.d_model)
|
| 59 |
+
self.drop = nn.Dropout(cfg.dropout)
|
| 60 |
+
self.blocks = nn.Sequential(*[Block(cfg) for _ in range(cfg.n_layers)])
|
| 61 |
+
self.ln_f = nn.LayerNorm(cfg.d_model)
|
| 62 |
+
self.head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
|
| 63 |
+
self.tok_emb.weight = self.head.weight
|
| 64 |
+
self.apply(self._init_weights)
|
| 65 |
+
|
| 66 |
+
def _init_weights(self, m):
|
| 67 |
+
if isinstance(m, nn.Linear):
|
| 68 |
+
nn.init.normal_(m.weight, std=0.02)
|
| 69 |
+
if m.bias is not None:
|
| 70 |
+
nn.init.zeros_(m.bias)
|
| 71 |
+
elif isinstance(m, nn.Embedding):
|
| 72 |
+
nn.init.normal_(m.weight, std=0.02)
|
| 73 |
+
|
| 74 |
+
def forward(self, idx, targets=None):
|
| 75 |
+
B, T = idx.shape
|
| 76 |
+
pos = torch.arange(T, device=idx.device)
|
| 77 |
+
x = self.drop(self.tok_emb(idx) + self.pos_emb(pos))
|
| 78 |
+
x = self.blocks(x)
|
| 79 |
+
x = self.ln_f(x)
|
| 80 |
+
logits = self.head(x)
|
| 81 |
+
loss = None
|
| 82 |
+
if targets is not None:
|
| 83 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
|
| 84 |
+
return logits, loss
|
| 85 |
+
|
| 86 |
+
def n_params(self):
|
| 87 |
+
return sum(p.numel() for p in self.parameters())
|
| 88 |
+
|
| 89 |
+
@torch.no_grad()
|
| 90 |
+
def generate(self, idx, max_new_tokens, temperature=0.8, top_p=0.92):
|
| 91 |
+
for _ in range(max_new_tokens):
|
| 92 |
+
idx_cond = idx[:, -self.cfg.max_seq:]
|
| 93 |
+
logits, _ = self(idx_cond)
|
| 94 |
+
logits = logits[:, -1, :] / temperature
|
| 95 |
+
probs = F.softmax(logits, dim=-1)
|
| 96 |
+
sorted_probs, sorted_idx = torch.sort(probs, descending=True)
|
| 97 |
+
cumsum = torch.cumsum(sorted_probs, dim=-1)
|
| 98 |
+
mask = cumsum - sorted_probs > top_p
|
| 99 |
+
sorted_probs[mask] = 0.0
|
| 100 |
+
sorted_probs /= sorted_probs.sum()
|
| 101 |
+
next_token = sorted_idx.gather(-1, torch.multinomial(sorted_probs, 1))
|
| 102 |
+
idx = torch.cat([idx, next_token], dim=1)
|
| 103 |
+
return idx
|
train.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import math
|
| 4 |
+
import time
|
| 5 |
+
import argparse
|
| 6 |
+
import torch
|
| 7 |
+
from torch.utils.data import DataLoader
|
| 8 |
+
|
| 9 |
+
from config import AmaiaConfig
|
| 10 |
+
from model import Amaia
|
| 11 |
+
from data import StreamDataset, load_text
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def lr_schedule(step, cfg):
|
| 15 |
+
if step < cfg.warmup_steps:
|
| 16 |
+
return cfg.lr * step / cfg.warmup_steps
|
| 17 |
+
t = min(1.0, (step - cfg.warmup_steps) / (cfg.decay_steps - cfg.warmup_steps))
|
| 18 |
+
return cfg.lr_min + 0.5 * (cfg.lr - cfg.lr_min) * (1.0 + math.cos(math.pi * t))
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def save_checkpoint(model, optimizer, step, cfg, path):
|
| 22 |
+
torch.save({
|
| 23 |
+
"model": model.state_dict(),
|
| 24 |
+
"optimizer": optimizer.state_dict(),
|
| 25 |
+
"step": step,
|
| 26 |
+
"cfg": cfg,
|
| 27 |
+
}, path)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def load_checkpoint(model, optimizer, path):
|
| 31 |
+
ckpt = torch.load(path, map_location="cpu")
|
| 32 |
+
model.load_state_dict(ckpt["model"])
|
| 33 |
+
optimizer.load_state_dict(ckpt["optimizer"])
|
| 34 |
+
return ckpt["step"]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def sample(model, dataset, prompt, cfg, device):
|
| 38 |
+
model.eval()
|
| 39 |
+
sp_ids = dataset.sp.Encode(prompt)
|
| 40 |
+
idx = torch.tensor([sp_ids], dtype=torch.long, device=device)
|
| 41 |
+
with torch.no_grad():
|
| 42 |
+
out = model.generate(idx, cfg.max_new_tokens)
|
| 43 |
+
tokens = out[0].tolist()
|
| 44 |
+
text = dataset.decode(tokens)
|
| 45 |
+
model.train()
|
| 46 |
+
return text
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def train(args):
|
| 50 |
+
cfg = AmaiaConfig()
|
| 51 |
+
|
| 52 |
+
if args.d_model: cfg.d_model = args.d_model
|
| 53 |
+
if args.n_layers: cfg.n_layers = args.n_layers
|
| 54 |
+
if args.n_heads: cfg.n_heads = args.n_heads
|
| 55 |
+
if args.max_seq: cfg.max_seq = args.max_seq
|
| 56 |
+
if args.batch: cfg.batch_size = args.batch
|
| 57 |
+
if args.lr: cfg.lr = args.lr
|
| 58 |
+
if args.sp_model: cfg.sp_model = args.sp_model
|
| 59 |
+
if args.ckpt: cfg.ckpt_file = args.ckpt
|
| 60 |
+
|
| 61 |
+
device = torch.device("cpu")
|
| 62 |
+
torch.set_num_threads(os.cpu_count())
|
| 63 |
+
|
| 64 |
+
print(f"Reading input...")
|
| 65 |
+
text = load_text(args.input)
|
| 66 |
+
print(f" {len(text):,} characters")
|
| 67 |
+
|
| 68 |
+
print(f"Building dataset...")
|
| 69 |
+
dataset = StreamDataset(text, cfg.sp_model, cfg.chunk_size)
|
| 70 |
+
cfg.vocab_size = dataset.vocab_size()
|
| 71 |
+
print(f" vocab={cfg.vocab_size} tokens={len(dataset.ids):,} chunks≈{len(dataset.ids)//cfg.chunk_size:,}")
|
| 72 |
+
|
| 73 |
+
loader = DataLoader(
|
| 74 |
+
dataset,
|
| 75 |
+
batch_size=cfg.batch_size,
|
| 76 |
+
num_workers=cfg.num_workers,
|
| 77 |
+
pin_memory=False,
|
| 78 |
+
persistent_workers=cfg.num_workers > 0,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
model = Amaia(cfg).to(device)
|
| 82 |
+
print(f"\nAmaia params={model.n_params()/1e6:.2f}M d_model={cfg.d_model} layers={cfg.n_layers} heads={cfg.n_heads}")
|
| 83 |
+
|
| 84 |
+
optimizer = torch.optim.AdamW(
|
| 85 |
+
model.parameters(),
|
| 86 |
+
lr=cfg.lr,
|
| 87 |
+
betas=(cfg.beta1, cfg.beta2),
|
| 88 |
+
weight_decay=cfg.weight_decay,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
step = 0
|
| 92 |
+
if os.path.exists(cfg.ckpt_file):
|
| 93 |
+
step = load_checkpoint(model, optimizer, cfg.ckpt_file)
|
| 94 |
+
print(f"Resumed from {cfg.ckpt_file} at step {step}")
|
| 95 |
+
else:
|
| 96 |
+
print(f"Starting fresh")
|
| 97 |
+
|
| 98 |
+
try:
|
| 99 |
+
model = torch.compile(model)
|
| 100 |
+
print("torch.compile() enabled")
|
| 101 |
+
except Exception:
|
| 102 |
+
print("torch.compile() not available, running eager")
|
| 103 |
+
|
| 104 |
+
smooth_loss = None
|
| 105 |
+
t0 = time.time()
|
| 106 |
+
tokens_seen = 0
|
| 107 |
+
|
| 108 |
+
print(f"\nbatch={cfg.batch_size} chunk={cfg.chunk_size} lr={cfg.lr:.2e}\n")
|
| 109 |
+
|
| 110 |
+
model.train()
|
| 111 |
+
while True:
|
| 112 |
+
for x, y in loader:
|
| 113 |
+
x, y = x.to(device), y.to(device)
|
| 114 |
+
|
| 115 |
+
for pg in optimizer.param_groups:
|
| 116 |
+
pg["lr"] = lr_schedule(step + 1, cfg)
|
| 117 |
+
|
| 118 |
+
optimizer.zero_grad(set_to_none=True)
|
| 119 |
+
_, loss = model(x, y)
|
| 120 |
+
loss.backward()
|
| 121 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip)
|
| 122 |
+
optimizer.step()
|
| 123 |
+
|
| 124 |
+
step += 1
|
| 125 |
+
tokens_seen += x.numel()
|
| 126 |
+
lv = loss.item()
|
| 127 |
+
smooth_loss = lv if smooth_loss is None else 0.98 * smooth_loss + 0.02 * lv
|
| 128 |
+
|
| 129 |
+
if step % cfg.log_every == 0:
|
| 130 |
+
elapsed = time.time() - t0
|
| 131 |
+
tps = tokens_seen / elapsed if elapsed > 0 else 0
|
| 132 |
+
lr_now = optimizer.param_groups[0]["lr"]
|
| 133 |
+
print(f"step {step:7d} loss {smooth_loss:.4f} lr {lr_now:.2e} {tps/1000:.1f}k tok/s")
|
| 134 |
+
|
| 135 |
+
if step % cfg.sample_every == 0:
|
| 136 |
+
text_out = sample(model, dataset, cfg.sample_prompt, cfg, device)
|
| 137 |
+
print(f"\n--- sample ---\n{text_out}\n---\n")
|
| 138 |
+
|
| 139 |
+
if step % cfg.ckpt_every == 0:
|
| 140 |
+
save_checkpoint(model, optimizer, step, cfg, cfg.ckpt_file)
|
| 141 |
+
print(f"Checkpoint saved → {cfg.ckpt_file}")
|
| 142 |
+
|
| 143 |
+
save_checkpoint(model, optimizer, step, cfg, cfg.ckpt_file)
|
| 144 |
+
print(f"\nDone. steps={step} loss={smooth_loss:.4f}")
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def main():
|
| 148 |
+
parser = argparse.ArgumentParser(description="Train Amaia")
|
| 149 |
+
parser.add_argument("input", nargs="?", default="-",
|
| 150 |
+
help="text file to train on, or - for stdin (default: -)")
|
| 151 |
+
parser.add_argument("--sp-model", default="amaia.model")
|
| 152 |
+
parser.add_argument("--ckpt", default="amaia.pt")
|
| 153 |
+
parser.add_argument("--d-model", type=int)
|
| 154 |
+
parser.add_argument("--n-layers", type=int)
|
| 155 |
+
parser.add_argument("--n-heads", type=int)
|
| 156 |
+
parser.add_argument("--max-seq", type=int)
|
| 157 |
+
parser.add_argument("--batch", type=int)
|
| 158 |
+
parser.add_argument("--lr", type=float)
|
| 159 |
+
args = parser.parse_args()
|
| 160 |
+
train(args)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
if __name__ == "__main__":
|
| 164 |
+
main()
|
vocab.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import sys
|
| 3 |
+
from data import build_vocab, load_text
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def main():
|
| 7 |
+
parser = argparse.ArgumentParser(description="Train a SentencePiece BPE tokenizer")
|
| 8 |
+
parser.add_argument("input", help="text file to train on")
|
| 9 |
+
parser.add_argument("--prefix", default="amaia", help="output model prefix")
|
| 10 |
+
parser.add_argument("--vocab-size", type=int, default=10970)
|
| 11 |
+
args = parser.parse_args()
|
| 12 |
+
|
| 13 |
+
print(f"Training vocab on {args.input} size={args.vocab_size} ...")
|
| 14 |
+
build_vocab(args.input, args.prefix, args.vocab_size)
|
| 15 |
+
print(f"Saved {args.prefix}.model {args.prefix}.vocab")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
if __name__ == "__main__":
|
| 19 |
+
main()
|