Download scripts/reference.py from matthiastl/gepard-onnx: direct link, hf CLI and curl.
- Browser
- Download file 2.88 kB
-
https://huggingface.co/matthiastl/gepard-onnx/resolve/main/scripts/reference.py
- Command line
-
hf download hf://matthiastl/gepard-onnx/scripts/reference.py
-
curl -L -o reference.py https://huggingface.co/matthiastl/gepard-onnx/resolve/main/scripts/reference.py
2.88 kB
| """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() | |
| 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 | |
| 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) | |
| 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 | |