"""gepard-1.0 in plain PyTorch: the decoder with a key/value memory (the part that runs once per audio frame), the audio interface, the heads and the voice compressor. Written from nineninesix-ai/gepard-inference's modeling.py and ref_compressor.py (Apache-2.0) and transformers' Qwen 3.5; every piece is checked against those in check_parity.py.""" import json import math from pathlib import Path import torch from safetensors.torch import load_file from torch import nn from torch.nn import functional as F ROOT = Path(__file__).resolve().parents[1] WEIGHTS = ROOT / "data" / "gepard" / "model.safetensors" L, D, H, HD, KV, FF, THETA, EPS = 14, 1024, 8, 256, 2, 3584, 1e7, 1e-6 LEVELS = [8, 7, 6, 6] * 8 SOT, EOT, SOS, EOS = 248073, 248074, 248070, 248071 class RMS(nn.Module): def __init__(self, d, eps=EPS): super().__init__() self.weight, self.eps = nn.Parameter(torch.ones(d)), eps def forward(self, x): return self.weight * (x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)) def rope(n_start, n, device=None): """cos, sin [n, 256] for positions n_start .. n_start + n - 1 (rotate_half layout, head_dim 256).""" inv = 1.0 / (THETA ** (torch.arange(0, HD, 2, dtype=torch.float32) / HD)) ang = torch.outer(torch.arange(n_start, n_start + n, dtype=torch.float32), inv) ang = torch.cat((ang, ang), -1) return ang.cos(), ang.sin() def rotate(x, cos, sin): a, b = x[..., :HD // 2], x[..., HD // 2:] return x * cos + torch.cat((-b, a), -1) * sin class Layer(nn.Module): def __init__(self): super().__init__() self.q_proj, self.o_proj = nn.Linear(D, 2 * H * HD, bias=False), nn.Linear(H * HD, D, bias=False) self.k_proj, self.v_proj = nn.Linear(D, KV * HD, bias=False), nn.Linear(D, KV * HD, bias=False) self.q_norm, self.k_norm, self.input_layernorm, self.post_attention_layernorm = RMS(HD), RMS(HD), RMS(D), RMS(D) self.gate_proj, self.up_proj, self.down_proj = nn.Linear(D, FF, bias=False), nn.Linear(D, FF, bias=False), nn.Linear(FF, D, bias=False) def forward(self, x, pk, pv, cos, sin, mask): """x [1, S, D]; pk, pv [2, P, 256]; cos, sin [S, 256]; mask [S, P + S] added to the scores -> x, new k, new v.""" s = x.shape[1] h = self.input_layernorm(x) qg = self.q_proj(h).view(1, s, H, 2 * HD) q, gate = self.q_norm(qg[..., :HD]).transpose(1, 2), qg[..., HD:].reshape(1, s, H * HD) k = self.k_norm(self.k_proj(h).view(1, s, KV, HD)).transpose(1, 2) v = self.v_proj(h).view(1, s, KV, HD).transpose(1, 2) q, k = rotate(q, cos, sin), rotate(k, cos, sin) kk, vv = torch.cat((pk[None], k), 2), torch.cat((pv[None], v), 2) kr, vr = kk.repeat_interleave(H // KV, 1), vv.repeat_interleave(H // KV, 1) o = torch.softmax(torch.matmul(q, kr.transpose(2, 3)) * HD ** -0.5 + mask, -1) o = torch.matmul(o, vr).transpose(1, 2).reshape(1, s, H * HD) * torch.sigmoid(gate) x = x + self.o_proj(o) f = self.post_attention_layernorm(x) return x + self.down_proj(F.silu(self.gate_proj(f)) * self.up_proj(f)), k[0], v[0] class Decoder(nn.Module): def __init__(self): super().__init__() self.layers, self.norm = nn.ModuleList(Layer() for _ in range(L)), RMS(D) def forward(self, x, pk, pv, cos, sin, mask): """x [1, S, D], pk, pv [L, 2, P, 256] -> hidden [1, S, D], k, v [L, 2, S, 256] of the new positions.""" ks, vs = [], [] for i, l in enumerate(self.layers): x, k, v = l(x, pk[i], pv[i], cos, sin, mask) ks.append(k), vs.append(v) return self.norm(x), torch.stack(ks), torch.stack(vs) class Gepard(nn.Module): """Decoder plus the parts around it. Text embedding kept apart (it is only needed once per sentence).""" def __init__(self): super().__init__() self.decoder = Decoder() self.audio_embeddings = nn.ModuleList(nn.Embedding(n, 32) for n in LEVELS) self.proj1, self.proj2 = nn.Linear(32 * 32, D), nn.Linear(D, D) self.register_buffer("scale", torch.ones(1)) self.heads = nn.ModuleList(nn.Linear(D, n) for n in LEVELS) self.stop = nn.Linear(D, 1) def embed_frame(self, codes): """codes [S, 32] long -> [1, S, D].""" x = torch.cat([e(codes[:, i]) for i, e in enumerate(self.audio_embeddings)], -1) x = self.proj2(F.gelu(self.proj1(x))) return (F.layer_norm(x, (D,)) * self.scale)[None] def outputs(self, hidden): """hidden [S, D] -> 216 logits (the 32 heads, in order), stop logit.""" return torch.cat([h(hidden) for h in self.heads], -1), self.stop(hidden)[..., 0] class Compressor(nn.Module): """Reference codes [1, T, 32] (unfolded) -> prefix [1, 8, 1024].""" class Attn(nn.Module): def __init__(self): super().__init__() self.q_proj, self.k_proj, self.v_proj, self.out_proj = (nn.Linear(D, D, bias=False) for _ in range(4)) def forward(self, q, kv): b, n, m = q.shape[0], q.shape[1], kv.shape[1] sp = lambda t, l: l(t).view(b, -1, 8, D // 8).transpose(1, 2) a = torch.matmul(sp(q, self.q_proj), sp(kv, self.k_proj).transpose(2, 3)) * (D // 8) ** -0.5 return self.out_proj(torch.matmul(torch.softmax(a, -1), sp(kv, self.v_proj)).transpose(1, 2).reshape(b, n, D)) class Block(nn.Module): def __init__(self): super().__init__() self.norm_self, self.norm_cross, self.norm_ffn = RMS(D), RMS(D), RMS(D) self.self_attn, self.cross_attn = Compressor.Attn(), Compressor.Attn() self.gate_proj, self.up_proj, self.down_proj = nn.Linear(D, 4 * D, bias=False), nn.Linear(D, 4 * D, bias=False), nn.Linear(4 * D, D, bias=False) def forward(self, q, ref): h = self.norm_self(q) q = q + self.self_attn(h, h) q = q + self.cross_attn(self.norm_cross(q), ref) h = self.norm_ffn(q) return q + self.down_proj(F.silu(self.gate_proj(h)) * self.up_proj(h)) def __init__(self): super().__init__() self.input_proj = nn.Linear(32, D) self.queries = nn.Parameter(torch.zeros(8, D)) self.blocks = nn.ModuleList(Compressor.Block() for _ in range(2)) self.final_norm, self.output_scale = RMS(D), nn.Parameter(torch.ones(1)) pe = torch.zeros(2048, D) pos, div = torch.arange(2048, dtype=torch.float32)[:, None], torch.exp(torch.arange(0, D, 2).float() * (-math.log(10000.0) / D)) pe[:, 0::2], pe[:, 1::2] = torch.sin(pos * div), torch.cos(pos * div) self.register_buffer("pe", pe, persistent=False) self.register_buffer("half_levels", torch.tensor([max(n // 2, 1) for n in LEVELS], dtype=torch.float32), persistent=False) def forward(self, codes): x = (codes.float() - self.half_levels) / self.half_levels x = self.input_proj(x) + self.pe[:x.shape[1]] q = self.queries[None].expand(x.shape[0], -1, -1) for b in self.blocks: q = b(q, x) return self.output_scale * self.final_norm(q) def load(weights=WEIGHTS): """-> (Gepard, Compressor, text embedding [248320, 1024]) in fp32.""" sd = {k: v.float() for k, v in load_file(str(weights)).items()} g, c = Gepard(), Compressor() gs = {} for k, v in sd.items(): if k.startswith("model.layers."): k2 = k[len("model.layers."):].replace("self_attn.", "").replace("mlp.", "") gs["decoder.layers." + k2] = v + 1.0 if "norm" in k2 else v # the backbone's norms keep weight - 1 elif k == "model.norm.weight": gs["decoder.norm.weight"] = v + 1.0 elif k.startswith("audio_embeddings."): gs[k] = v elif k.startswith("audio_embed_proj.0."): gs["proj1." + k.split(".")[-1]] = v elif k.startswith("audio_embed_proj.2."): gs["proj2." + k.split(".")[-1]] = v elif k == "audio_embed_scale": gs["scale"] = v.reshape(1) elif k.startswith("codebook_heads."): gs["heads." + k[len("codebook_heads."):]] = v elif k.startswith("stop_head."): gs["stop." + k[len("stop_head."):]] = v missing, unexpected = g.load_state_dict(gs, strict=False) cs = {} for k, v in sd.items(): if k.startswith("ref_compressor."): k = k[len("ref_compressor."):].replace(".ffn.", ".") cs[k] = v.reshape(1) if k == "output_scale" else v cm, cu = c.load_state_dict(cs, strict=False) print("gepard: missing", missing[:4], "unexpected", unexpected[:4], "| compressor: missing", cm[:4], "unexpected", cu[:4]) return g.eval(), c.eval(), sd["model.embed_tokens.weight"]