File size: 8,803 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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 | """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"]
|