File size: 1,931 Bytes
998397a | 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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | """Load the model and generate. Run from the folder this file is in."""
import pathlib
import sys
import torch
from safetensors.torch import load_file
from tokenizers import Tokenizer
HERE = pathlib.Path(__file__).parent
sys.path.insert(0, str(HERE))
from m2r.config import load
from m2r.model.torch_model import Model, swa_mask
cfg = load(HERE / "training_config.yaml")
model = Model(cfg.model).to(torch.bfloat16)
model.load_state_dict(load_file(str(HERE / "model.safetensors")))
model.eval()
tok = Tokenizer.from_file(str(HERE / "tokenizer.json"))
mask = swa_mask(cfg.model, dtype=torch.bfloat16)
# BOS (id 1) starts a document. The model was trained with attention confined
# to document boundaries, keyed on this token, so a prompt without it is
# unlike anything it saw in training.
ids = [1] + tok.encode("The capital of France is").ids
# The training forward wants a whole number of blocks: sliding-window
# attention chunks by `window`, linear attention by its own chunk, and a MoE
# layer by `route_block`. A prompt is whatever length it is, so pad up to a
# common multiple and read the LAST REAL position. Right-padding cannot reach
# a real token -- attention is causal and the MLP is position-wise.
PAD_TO = max(cfg.model.window, cfg.model.route_block or 1, 256)
# SAMPLED, not greedy. A 7.5 M-parameter model decoded greedily falls into a
# repetition loop within a few tokens -- "vibrant vibrant vibrant" -- which
# says more about argmax than about the model.
TEMPERATURE, TOP_K = 0.8, 40
torch.manual_seed(0)
def next_token(ids):
n = len(ids)
x = torch.tensor([ids + [0] * ((-n) % PAD_TO)])
with torch.no_grad():
h = model.body(x, mask)[:, n - 1]
logits = (h @ model.emb.t().to(h.dtype)).float()[0] / TEMPERATURE
v, i = logits.topk(TOP_K)
return int(i[torch.multinomial(v.softmax(-1), 1)])
for _ in range(60):
ids.append(next_token(ids))
print(tok.decode(ids[1:]))
|