File size: 2,214 Bytes
480f8c6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import argparse,json,pathlib,torch
from model import Embedding,Block
from torch import nn
from tokenizer import MultiResolutionTokenizer
from utf8_constraint import UTF8Constraint
class MultiResolutionLM(nn.Module):
def __init__(self,entries,d=128,layers=4,heads=4,context=256,composite=True,mode='softmax'):
super().__init__();self.context=context;self.emb=Embedding(entries,d,composite);self.pos=nn.Embedding(context+1,d);self.blocks=nn.ModuleList([Block(d,heads,mode) for _ in range(layers)]);self.norm=nn.LayerNorm(d)
def forward(self,ids,pos):
e=self.emb();x=e[ids]+self.pos(pos)
for block in self.blocks:x=block(x)
return self.norm(x)@e.T
def main():
ap=argparse.ArgumentParser();ap.add_argument('prompt');ap.add_argument('--mode',choices=['assistant','informal','completion'],default='assistant');ap.add_argument('--tokens',type=int,default=64);ap.add_argument('--device',default='cpu');a=ap.parse_args()
torch.set_num_threads(2);root=pathlib.Path(__file__).parent;cfg=json.loads((root/'config.json').read_text());tok=MultiResolutionTokenizer.load(root/'tokenizer.json')
m=MultiResolutionLM(tok.entries,**cfg['architecture']);m.load_state_dict(torch.load(root/'weights.pt',map_location='cpu',weights_only=True));m.to(a.device).eval()
prefix=a.prompt if a.mode=='completion' else 'Mode: '+a.mode+'\nUser: '+a.prompt+'\nAssistant: '
ids=tok.encode(prefix);lens=list(map(len,tok.raw));pos=[0]
for j in ids:pos.append(pos[-1]+lens[j])
if pos[-1]+4>m.context:raise ValueError('Prompt exceeds context capacity')
c=UTF8Constraint(tok.raw);pending=b'';out=[]
with torch.inference_mode():
for i in range(a.tokens):
z=m(torch.tensor([[256]+ids],device=a.device),torch.tensor([pos],device=a.device))[0,-1]*cfg['output_logit_scale']
allowed=[j for j in c.allowed(pending,min(3,a.tokens-1-i)) if pos[-1]+lens[j]+len(pending)<=m.context-4]
if not allowed:break
j=allowed[int(z[allowed].argmax())]
if j==257:break
pending=c.advance(pending,tok.raw[j]);ids.append(j);pos.append(pos[-1]+lens[j]);out.append(j)
print(tok.decode(out))
if __name__=='__main__':main()
|