File size: 2,879 Bytes
2d4936d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
69
70
71
72
73
74
75
"""The reference: gepard in PyTorch (fp32, CPU), as GepardRunner.generate does it, with one seeded generator."""
import math
import sys
from pathlib import Path

import numpy as np
import torch
from tokenizers import Tokenizer

sys.path.insert(0, str(Path(__file__).parent))
import gepard_model as gm  # noqa: E402

ROOT = Path(__file__).resolve().parents[1]
TOK = Tokenizer.from_file(str(ROOT / "data" / "gepard" / "tokenizer.json"))


def text_ids(text: str) -> list[int]:
    """Tokens of the text, repeated until short ones reach 16 text tokens, as TextRepeater.expand does."""
    ids = TOK.encode(text, add_special_tokens=False).ids
    n = len(ids)
    r = 1 if n <= 0 or n >= 13 else max(1, min(math.ceil(16 / n), 8))
    block = [gm.SOT] + ids + [gm.EOT]
    return block * (r - 1) + block + [gm.SOS]


class Reference:
    def __init__(self):
        self.g, self.comp, self.emb = gm.load()

    @torch.no_grad()
    def prefill(self, ids, prefix=None):
        x = torch.nn.functional.embedding(torch.tensor([ids]), self.emb)
        if prefix is not None:
            x = torch.cat((prefix, x), 1)
        s = x.shape[1]
        mask = torch.zeros(s, s).masked_fill(torch.triu(torch.ones(s, s), 1).bool(), float("-inf"))
        e = torch.zeros(gm.L, gm.KV, 0, gm.HD)
        h, k, v = self.g.decoder(x, e, e, *gm.rope(0, s), mask)
        return h[0, -1], k, v

    @torch.no_grad()
    def step(self, codes, k, v):
        n = k.shape[2]
        h, k1, v1 = self.g.decoder(self.g.embed_frame(torch.as_tensor(codes)[None]), k, v, *gm.rope(n, 1), torch.zeros(1, n + 1))
        return h[0, 0], torch.cat((k, k1), 2), torch.cat((v, v1), 2)

    @torch.no_grad()
    def generate(self, text, seed, temperature=0.3, max_frames=2000, prefix=None, trace=None):
        rng = np.random.default_rng(seed)
        h, k, v = self.prefill(text_ids(text), prefix)
        frames = []
        for i in range(max_frames):
            logits, stop = self.g.outputs(h[None])
            logits, stop = logits[0].numpy(), float(stop[0])
            if i > 0 and 1 / (1 + math.exp(-stop)) > 0.5:
                break
            if trace is not None:
                trace.append((logits.copy(), stop))
            codes = sample(logits, rng, temperature)
            frames.append(codes)
            h, k, v = self.step(codes, k, v)
        return np.stack(frames)                                             # [T, 32]


def sample(logits, rng, temperature):
    """One code per head, all 32, from softmax(logits / temperature); numpy so every runtime draws the same numbers."""
    out, at = np.empty(32, np.int64), 0
    for i, n in enumerate(gm.LEVELS):
        z = logits[at:at + n].astype(np.float64) / temperature
        p = np.exp(z - z.max())
        p /= p.sum()
        out[i] = min(int(np.searchsorted(np.cumsum(p), rng.random())), n - 1)
        at += n
    return out