Slayer1B-Poetry / tutorials /slayer_training.py
kacperwikiel's picture
Add five native Slayer notebooks: generation, CPT, SFT, RL and measured checkpoint averaging
05c768b verified
Raw History Blame Contribute Delete
9.03 kB
"""Small, inspectable native Slayer LoRA teaching loops; not a production trainer."""
from pathlib import Path
from contextlib import contextmanager
import hashlib, json, random
import torch
import torch.nn.functional as F
from pydantic import BaseModel, ConfigDict, Field
from tokenizers import Tokenizer
from common import load_base, attach
from lora import adapter_state, LoRALinear
class Config(BaseModel):
model_config = ConfigDict(extra='forbid', frozen=True, strict=True)
context: int = Field(default=128, ge=8, le=1024)
learning_rate: float = Field(default=1e-4, gt=0, le=0.01)
seed: int = 42
class Example(BaseModel):
model_config = ConfigDict(extra='forbid', frozen=True, strict=True)
prompt: str = Field(min_length=1)
response: str = Field(min_length=1)
class Workshop:
def __init__(self, root, config=Config()):
self.root=Path(root); self.config=config
random.seed(config.seed); torch.manual_seed(config.seed)
self.recipe=json.loads((self.root/'recipe.json').read_text())
self.recipe['training'].update(activation_checkpointing=True, loss_chunk=0)
self.device='cuda' if torch.cuda.is_available() else 'cpu'
self.model,self.provenance=load_base(self.recipe,self.device)
attach(self.model,self.recipe)
assert hashlib.sha256((self.root/'tokenizer.json').read_bytes()).hexdigest() == '0640d3bd3674d7a6e59c540d945a2ad275a12e1bcaeb6007c37a90751f9815dd'
self.tokenizer=Tokenizer.from_file(str(self.root/'tokenizer.json'))
self.params=[p for p in self.model.parameters() if p.requires_grad]
self.optimizer=torch.optim.AdamW(self.params,lr=config.learning_rate)
self.steps=0
print(f'{self.device}: {sum(p.numel() for p in self.params):,} trainable parameters')
def amp(self): return torch.autocast(self.device,dtype=torch.bfloat16)
def ids(self,text): return self.tokenizer.encode(text,add_special_tokens=False).ids
@contextmanager
def parent(self):
"""Disable native adapters without copying the 1B reference model."""
modules=[m for m in self.model.modules() if isinstance(m,LoRALinear)]
scales=[m.scaling for m in modules]
try:
for m in modules:m.scaling=0.
yield
finally:
for m,s in zip(modules,scales):m.scaling=s
def reset(self):
"""Independent lesson: zero B restores parent; reset optimizer as well."""
with torch.no_grad():
for m in self.model.modules():
if isinstance(m,LoRALinear):m.B.zero_()
self.optimizer=torch.optim.AdamW(self.params,lr=self.config.learning_rate)
self.steps=0
def update(self,loss):
if not torch.isfinite(loss):raise ValueError('Nonfinite loss')
self.optimizer.zero_grad(set_to_none=True);loss.backward()
torch.nn.utils.clip_grad_norm_(self.params,1.,error_if_nonfinite=True)
self.optimizer.step();self.steps+=1
return float(loss.detach())
def cpt(self,texts,steps=10):
"""All next tokens supervised, EOS boundaries; incomplete tail omitted."""
stream=[]
for text in texts:stream += [0]+self.ids(text)+[0]
n=self.config.context
windows=[stream[i:i+n+1] for i in range(0,len(stream)-n,n)]
if not windows:raise ValueError('Need at least context+1 tokens')
self.model.train();history=[]
for step in range(steps):
z=torch.tensor([random.choice(windows)],device=self.device)
with self.amp():
logits,_=self.model(z[:,:-1]);loss=F.cross_entropy(logits.float().reshape(-1,logits.size(-1)),z[:,1:].reshape(-1))
history.append(self.update(loss));print({'step':step+1,'cpt_ce':history[-1]})
return history
def encode_sft(self,example):
"""Separate encoding defines a stable boundary; no silent truncation."""
e=Example.model_validate(example)
prompt=[0]+self.ids(e.prompt);response=self.ids(e.response)+[0]
tokens=prompt+response
if len(tokens)-1>self.config.context:raise ValueError('Example too long: shorten it or increase context')
x=torch.tensor([tokens[:-1]],device=self.device)
y=torch.tensor([tokens[1:]],device=self.device)
# y[j] predicts tokens[j+1]; first response is tokens[len(prompt)].
y[:,:len(prompt)-1]=-100
return x,y
def sft(self,examples,steps=10):
batches=[self.encode_sft(e) for e in examples]
if not batches:raise ValueError('No SFT examples')
self.model.train();history=[]
for step in range(steps):
x,y=random.choice(batches)
with self.amp():
logits,_=self.model(x);loss=F.cross_entropy(logits.float().reshape(-1,logits.size(-1)),y.reshape(-1),ignore_index=-100)
history.append(self.update(loss));print({'step':step+1,'response_ce':history[-1]})
return history
@torch.no_grad()
def sample(self,prompt,max_new_tokens=48,seed=1234):
"""Unfiltered categorical sampling at temperature 1: on-policy for RL."""
self.model.eval();torch.manual_seed(seed)
ids=[0]+self.ids(prompt);completion=[]
if len(ids)+max_new_tokens>self.config.context:raise ValueError('Prompt + rollout exceeds context')
for _ in range(max_new_tokens):
with self.amp():logits,_=self.model(torch.tensor([ids],device=self.device))
t=int(torch.multinomial(logits[0,-1].float().softmax(-1),1))
ids.append(t);completion.append(t)
if t==0:break
return completion,self.tokenizer.decode(completion)
def rl(self,prompts,reward,updates=3,group_size=4,max_new_tokens=24,kl_beta=.02):
"""On-policy REINFORCE + leave-one-out baseline + full categorical KL.
One optimizer step per freshly sampled group. No PPO/GRPO clipping,
replay, reward model, filtering or temperature/logprob mismatch.
Reference is always the frozen parent (adapters disabled).
"""
if group_size<2:raise ValueError('group_size must be >=2')
history=[]
for u in range(updates):
prompt=prompts[u%len(prompts)]
rolls=[self.sample(prompt,max_new_tokens,self.config.seed+u*group_size+i) for i in range(group_size)]
scores=torch.tensor([float(reward(text)) for _,text in rolls],device=self.device)
if not torch.isfinite(scores).all():raise ValueError('Nonfinite reward')
advantages=(scores-(scores.sum()-scores)/(group_size-1)).detach()
self.optimizer.zero_grad(set_to_none=True)
# Eval mode keeps rollout and scoring distributions identical.
self.model.eval();pg_total=kl_total=0.
for (completion,_),advantage in zip(rolls,advantages):
prefix=[0]+self.ids(prompt);seq=prefix+completion
x=torch.tensor([seq[:-1]],device=self.device)
targets=torch.tensor(completion,device=self.device)
start=len(prefix)-1
with torch.no_grad(),self.parent(),self.amp():ref,_=self.model(x)
ref_logp=ref[0,start:].float().log_softmax(-1).detach();del ref
with self.amp():logits,_=self.model(x)
logp=logits[0,start:].float().log_softmax(-1)
chosen=logp.gather(-1,targets[:,None]).squeeze(-1)
# Sequence log probability (sum) is the REINFORCE estimator.
pg=-advantage*chosen.sum()
kl=(logp.exp()*(logp-ref_logp)).sum(-1).mean()
loss=(pg+kl_beta*kl)/group_size
if not torch.isfinite(loss):raise ValueError('Nonfinite RL loss')
loss.backward();pg_total+=float(pg.detach())/group_size;kl_total+=float(kl.detach())/group_size
torch.nn.utils.clip_grad_norm_(self.params,1.,error_if_nonfinite=True)
self.optimizer.step();self.steps+=1
row={'update':u+1,'mean_reward':float(scores.mean()),'reward_std':float(scores.std(unbiased=False)),
'policy_loss':pg_total,'reference_kl':kl_total,'samples':[{'text':t,'reward':float(r)} for (_,t),r in zip(rolls,scores)]}
history.append(row);print(json.dumps(row))
return history
def save(self,path):
path=Path(path);path.parent.mkdir(parents=True,exist_ok=True)
torch.save({'adapters':adapter_state(self.model),'recipe':self.recipe,'step':self.steps,
'provenance':self.provenance,'tokenizer_sha256':hashlib.sha256((self.root/'tokenizer.json').read_bytes()).hexdigest()},path)
print('Saved',path)
def form_reward(text):
"""Toy observable form proxy, explicitly not literary quality."""
lines=[s.strip() for s in text.splitlines() if s.strip()]
if not lines:return 0.
four_lines=max(0.,1.-abs(len(lines)-4)/4)
distinct=len(set(lines))/len(lines)
length=min(len(text.split())/24,1.)
return .5*four_lines+.25*distinct+.25*length