amx-moe-e256-4day / example.py
gdiamos's picture
m2-reasoning export from moe-grow-e256-4day-sft-window-20260907T054932
998397a verified
Raw History Blame Contribute Delete
1.93 kB
"""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:]))