"""gepard-1.0 on a CPU with ONNX Runtime and numpy, no PyTorch (RULE.md). Sampling is seeded numpy, as reference.py's.""" from __future__ import annotations import math from pathlib import Path import numpy as np import onnxruntime as ort ROOT = Path(__file__).resolve().parents[1] LEVELS = [8, 7, 6, 6] * 8 HALF = np.array([4, 3, 3, 3] * 8, np.float32) L, KV, HD, THETA = 14, 2, 256, 1e7 SOS = 248070 def session(path, threads): o = ort.SessionOptions() o.intra_op_num_threads, o.inter_op_num_threads = threads, 1 o.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL return ort.InferenceSession(str(path), o, providers=["CPUExecutionProvider"]) def rope(start, n): inv = 1.0 / (THETA ** (np.arange(0, HD, 2, dtype=np.float32) / HD)) a = np.outer(np.arange(start, start + n, dtype=np.float32), inv) a = np.concatenate((a, a), -1) return np.cos(a).astype(np.float32), np.sin(a).astype(np.float32) def sample(logits, rng, temperature): out, at = np.empty(32, np.int64), 0 for i, n in enumerate(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 class Port: def __init__(self, folder=ROOT / "export", decoder="decoder.onnx", threads=4, codec_threads=None): f = Path(folder) self.dec, self.frame, self.heads = session(f / decoder, threads), session(f / "frame.onnx", 1), session(f / "heads.onnx", 1) self.codec = session(f / "codec_decoder.onnx", codec_threads or threads) self.emb = np.load(f / "text_embedding.f16.npy", mmap_mode="r") self._comp_path, self._comp = f / "compressor.onnx", None self.threads = threads def prefix(self, ref_codes): self._comp = self._comp or session(self._comp_path, self.threads) return self._comp.run(None, {"codes": ref_codes[None].astype(np.int64)})[0] def _run(self, x, k, v): s, p = x.shape[1], k.shape[2] cos, sin = rope(p, s) mask = np.zeros((s, p + s), np.float32) if s > 1: mask[:, p:] = np.where(np.triu(np.ones((s, s), bool), 1), -np.inf, 0).astype(np.float32) h, nk, nv = self.dec.run(None, {"x": x, "past_k": k, "past_v": v, "cos": cos, "sin": sin, "mask": mask}) return h[0], np.concatenate((k, nk), 2), np.concatenate((v, nv), 2) def prefill(self, ids, prefix=None): x = self.emb[ids].astype(np.float32)[None] if prefix is not None: x = np.concatenate((prefix, x), 1) e = np.zeros((L, KV, 0, HD), np.float32) h, k, v = self._run(x, e, e) return h[-1], k, v def out(self, h): logits, stop = self.heads.run(None, {"hidden": h[None]}) return logits[0], float(stop[0]) def step(self, codes, k, v): x = self.frame.run(None, {"codes": codes[None].astype(np.int64)})[0][None] h, k, v = self._run(x, k, v) return h[0], k, v def generate(self, ids, seed, temperature=0.3, max_frames=2000, prefix=None): rng = np.random.default_rng(seed) h, k, v = self.prefill(ids, prefix) frames = [] for i in range(max_frames): logits, stop = self.out(h) if i > 0 and 1 / (1 + math.exp(-stop)) > 0.5: break codes = sample(logits, rng, temperature) frames.append(codes) h, k, v = self.step(codes, k, v) return np.stack(frames) def decode(self, codes): z = ((codes.astype(np.float32) - HALF) / HALF).T[None] return self.codec.run(None, {"z": z})[0].reshape(-1)