File size: 2,552 Bytes
bd05a8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
57
58
59
60
61
62
63
64
65
66
67
68
"""Answer a question about a passage. Run from the folder this file is in."""
import json
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.data.templates import EOT, render_prompt
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)
gen = json.loads((HERE / "generation.json").read_text())

# THE BAN IS REQUIRED, not a tuning knob. These vocabulary rows never occur in
# the training corpus, so the sampled softmax never drew them as negatives and
# never pushed their logits down. They sit near 0 while every trained token
# that is wrong here sits near -7.9, and they win the argmax whenever the model
# is unsure -- which meant answering " ballo" to 21% of DROP questions before
# they were masked. Deleting this line reintroduces that.
BAN = torch.tensor(gen["banned_token_ids"], dtype=torch.long)

PAD_TO = max(cfg.model.window, cfg.model.route_block or 1, 256)
eot_id = tok.encode(EOT, add_special_tokens=False).ids[0]

QUESTION = "In what year was the Royal Dutch Petroleum Company founded?"
CONTEXT = ("In February 1907, the Royal Dutch Shell Group was created through "
           "the amalgamation of two rival companies: the Royal Dutch "
           "Petroleum Company, founded in 1890, and the Shell Transport and "
           "Trading Company of the United Kingdom.")

# render_prompt IS the format this model was tuned on, imported rather than
# copied so it cannot drift. It already emits BOS, so do not prepend one.
prompt = render_prompt([f"{QUESTION}\n\n{CONTEXT}"], thinking=False)
ids = tok.encode(prompt, add_special_tokens=False).ids


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]
    logits[BAN] = -1e30                       # see above
    return int(logits.argmax())               # greedy: answers are 1-2 words


out = []
for _ in range(32):
    t = next_token(ids)
    if t == eot_id:
        break
    out.append(t)
    ids.append(t)

print(tok.decode(out).replace("<think></think>", "").strip())
# expected: 1890