Slayer1B-Poetry / tutorials /inspect_checkpoint.py
kacperwikiel's picture
Add five native Slayer notebooks: generation, CPT, SFT, RL and measured checkpoint averaging
05c768b verified
Raw History Blame Contribute Delete
3.01 kB
"""Load a native full checkpoint for fixed-setting generation and text CE."""
from pathlib import Path
from types import SimpleNamespace
import hashlib,importlib.util,math
import torch
import torch.nn.functional as F
from huggingface_hub import hf_hub_download
from tokenizers import Tokenizer
class NativeCheckpoint:
def __init__(self,path,tokenizer_path,device='cpu'):
source=hf_hub_download('SlayerLab/Slayer1B-1.09','train_gpt_ref_r24_2.py',revision='58d8f359c1fdd887f1b7344ec52c5511c111f790')
assert hashlib.sha256(Path(source).read_bytes()).hexdigest()=='46f83b51fcec18ffc3273d80fb9eab29e182c52d8667800dab27b80f7ff18afc'
spec=importlib.util.spec_from_file_location('slayer_merge_arch',source);module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
checkpoint=torch.load(path,map_location='cpu',weights_only=True,mmap=True)
config=SimpleNamespace(**checkpoint['config']);config.act_ckpt=False;config.loss_chunk=0;config.z_loss=0.
with torch.device('meta'):model=module.GPT(config.vocab,config.n_layer,config.n_embd,config.n_head,config.block,config)
model.load_state_dict(checkpoint['model'],strict=True,assign=True);model.head.weight=model.tok.weight
self.model=model.to(device=device,dtype=torch.bfloat16).eval();self.device=device
assert hashlib.sha256(Path(tokenizer_path).read_bytes()).hexdigest()=='0640d3bd3674d7a6e59c540d945a2ad275a12e1bcaeb6007c37a90751f9815dd'
self.tokenizer=Tokenizer.from_file(str(tokenizer_path))
@torch.no_grad()
def generate(self,prompt,tokens=32,seed=1234):
torch.manual_seed(seed);seq=[0]+self.tokenizer.encode(prompt,add_special_tokens=False).ids;out=[]
for i in range(tokens):
with torch.autocast(self.device,dtype=torch.bfloat16):z,_=self.model(torch.tensor([seq[-1024:]],device=self.device))
logits=z[0,-1].float()
# Fixed top-k 50, temperature 1; no forced minimum length.
logits[logits<logits.topk(50).values[-1]]=-float('inf')
token=int(torch.multinomial(logits.softmax(-1),1))
if token==0:break
seq.append(token);out.append(token)
return prompt+self.tokenizer.decode(out)
@torch.no_grad()
def evaluate(self,texts,context=128):
total=0.;count=0
for text in texts:
ids=[0]+self.tokenizer.encode(text,add_special_tokens=False).ids+[0]
for start in range(0,len(ids)-1,context):
chunk=ids[start:start+context+1]
if len(chunk)<2:continue
x=torch.tensor([chunk[:-1]],device=self.device);y=torch.tensor(chunk[1:],device=self.device)
with torch.autocast(self.device,dtype=torch.bfloat16):z,_=self.model(x)
total+=float(F.cross_entropy(z[0].float(),y,reduction='sum'));count+=len(y)
if not count:raise ValueError('Empty evaluation')
ce=total/count;return {'ce':ce,'perplexity':math.exp(ce),'tokens':count}