File size: 11,187 Bytes
4ffdd01 | 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 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | # SPDX-License-Identifier: Apache-2.0
"""Clean-room fp32 CPU reference of the Raon-Speech-9B decoders (ARCH sections 5, 6): thinker (36 x Qwen3 D4096),
text head, thinker->talker MLP, talker (4 x Qwen3 D2048), audio head, ``proj_code``, code predictor (5 x Qwen3
D1024, greedy), output adaptor (RVQ tables + MLP + RMSNorm), input adaptor, speaker projection.
Numerics follow transformers 4.57.3 in fp32: RMSNorm ``w * (x * rsqrt(mean(x^2) + eps))``; q/k per-head RMSNorm
before RoPE (``rotate_half``, inv_freq in fp32, ``cos/sin`` of ``pos * inv_freq``); GQA; softmax attention with
scale 128^-0.5, causal; SwiGLU; residual adds. Weights are read from the bf16 checkpoint and upcast (exact).
Memory: the thinker keeps its weights as stored (bf16, memory-mapped) and upcasts one layer at a time
(``Thinker(resident=False)``, about 0.8 GB transient), the small stages are resident in fp32.
ck = Checkpoint(); th = Thinker(ck); tk = Talker(ck); cp = CodePredictor(ck); oad = OutputAdaptor(ck)
h, l35 = th.forward(rows [T, 4096], positions) # KV cache appended; final-norm hidden + layer-35 rows
logits = th.text_logits(h[-1])
t = tk.forward(l35_rows, positions) # talker final-norm hidden
code0_logits = tk.audio_logits(t[-1]); row0 = tk.proj_code(t[-1])
codes, logits15 = cp.predict(row0, code0) # greedy codes 1..15
next_row = oad(codes) # [4096]
"""
from __future__ import annotations
from typing import Dict, List, Optional, Sequence, Tuple
import torch
import torch.nn.functional as F
from ..config import CODE_PREDICTOR, CODEBOOK_SIZE, NUM_CODEBOOKS, TALKER, THINKER, Qwen3Dims
from ..weights import stages as ST
from ..weights.source import Checkpoint
F32 = torch.float32
def rms_norm(x: torch.Tensor, w: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
xf = x.float()
var = xf.pow(2).mean(-1, keepdim=True)
return w.float() * (xf * torch.rsqrt(var + eps))
def rotate_half(x: torch.Tensor) -> torch.Tensor:
h = x.shape[-1] // 2
return torch.cat((-x[..., h:], x[..., :h]), dim=-1)
def rope_cos_sin(positions: torch.Tensor, head_dim: int, theta: float) -> Tuple[torch.Tensor, torch.Tensor]:
"""transformers default RoPE in fp32: [T, head_dim] cos / sin."""
inv = 1.0 / (theta ** (torch.arange(0, head_dim, 2, dtype=torch.int64).to(F32) / head_dim))
freqs = (inv[:, None] @ positions.to(F32)[None, :]).transpose(0, 1)
emb = torch.cat((freqs, freqs), dim=-1)
return emb.cos(), emb.sin()
class KVCache:
"""Per-layer K (post norm + RoPE) / V, fp32 [kv_heads, T, head_dim]."""
def __init__(self, n_layers: int):
self.k: List[Optional[torch.Tensor]] = [None] * n_layers
self.v: List[Optional[torch.Tensor]] = [None] * n_layers
@property
def length(self) -> int:
return 0 if self.k[0] is None else int(self.k[0].shape[1])
def append(self, l: int, k: torch.Tensor, v: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
self.k[l] = k if self.k[l] is None else torch.cat([self.k[l], k], 1)
self.v[l] = v if self.v[l] is None else torch.cat([self.v[l], v], 1)
return self.k[l], self.v[l]
def truncate(self, n: int) -> None:
for l in range(len(self.k)):
if self.k[l] is not None:
self.k[l], self.v[l] = self.k[l][:, :n], self.v[l][:, :n]
class Qwen3Stack:
"""A Qwen3 decoder stack over externally given input rows (no embedding), with a KV cache."""
def __init__(self, layers: Sequence[Dict[str, torch.Tensor]], norm: torch.Tensor, dims: Qwen3Dims,
resident: bool = True):
self.dims = dims
self.resident = resident
self.layers = [{k: (v.float() if resident else v) for k, v in L.items()} for L in layers]
self.norm = norm.float()
self.cache = KVCache(dims.layers)
def reset(self) -> None:
self.cache = KVCache(self.dims.layers)
def _w(self, L: Dict[str, torch.Tensor], n: str) -> torch.Tensor:
return L[n] if self.resident else L[n].float()
def layer(self, l: int, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, start: int) -> torch.Tensor:
d = self.dims
L = self.layers[l]
w = lambda n: self._w(L, n) # noqa: E731
T = x.shape[0]
h = rms_norm(x, w("in_norm"), d.eps)
q = (h @ w("wq").T).view(T, d.heads, d.head_dim)
k = (h @ w("wk").T).view(T, d.kv_heads, d.head_dim)
v = (h @ w("wv").T).view(T, d.kv_heads, d.head_dim)
q = rms_norm(q, w("q_norm"), d.eps).transpose(0, 1)
k = rms_norm(k, w("k_norm"), d.eps).transpose(0, 1)
v = v.transpose(0, 1)
q = q * cos[None] + rotate_half(q) * sin[None]
k = k * cos[None] + rotate_half(k) * sin[None]
K, V = self.cache.append(l, k, v)
rep = d.heads // d.kv_heads
K, V = K.repeat_interleave(rep, 0), V.repeat_interleave(rep, 0)
S = K.shape[1]
sc = (q @ K.transpose(1, 2)) * (d.head_dim ** -0.5)
qpos = torch.arange(start, start + T)[:, None]
kpos = torch.arange(S)[None, :]
sc = sc.masked_fill((kpos > qpos)[None], float("-inf"))
o = torch.softmax(sc, -1) @ V # [H, T, hd]
o = o.transpose(0, 1).reshape(T, d.heads * d.head_dim)
x = x + o @ w("wo").T
h = rms_norm(x, w("post_norm"), d.eps)
x = x + (F.silu(h @ w("gate").T) * (h @ w("up").T)) @ w("down").T
return x
@torch.inference_mode()
def forward(self, x: torch.Tensor, positions: Optional[torch.Tensor] = None, taps: Optional[dict] = None):
"""x [T, D] input rows at positions ``cache.length ..`` (or ``positions``) -> (final-norm hidden [T, D],
pre-norm output of the last layer [T, D])."""
x = x.float()
start = self.cache.length
if positions is None:
positions = torch.arange(start, start + x.shape[0])
cos, sin = rope_cos_sin(positions, self.dims.head_dim, self.dims.theta)
for l in range(self.dims.layers):
x = self.layer(l, x, cos, sin, start)
if taps is not None:
taps.setdefault(f"layer{l}", []).append(x.clone())
return rms_norm(x, self.norm, self.dims.eps), x
class Thinker(Qwen3Stack):
def __init__(self, ck: Checkpoint, resident: bool = False):
layers = [ST.thinker_layer(ck, l) for l in range(THINKER.layers)]
head = ST.thinker_head(ck)
super().__init__(layers, head["norm"], THINKER, resident=resident)
self.lm_head = head["lm_head"] # bf16 [V, D], upcast per use
self.ck = ck
def embed(self, ids: Sequence[int]) -> torch.Tensor:
return self.ck.rows("text_model.embed_tokens.weight", list(ids), F32)
def text_logits(self, h: torch.Tensor) -> torch.Tensor:
"""final-norm hidden [.., 4096] -> [.., 153723] fp32 (lm_head upcast in row blocks)."""
h = h.float().reshape(-1, THINKER.d)
out = torch.empty(h.shape[0], self.lm_head.shape[0])
for s in range(0, self.lm_head.shape[0], 16384):
out[:, s:s + 16384] = h @ self.lm_head[s:s + 16384].float().T
return out
class Talker(Qwen3Stack):
def __init__(self, ck: Checkpoint):
w = ST.talker(ck, F32)
super().__init__(w["layers"], w["norm"], TALKER, resident=True)
self.w = w
def t2t(self, h35: torch.Tensor) -> torch.Tensor:
w = self.w
return F.silu(h35.float() @ w["t2t_w1"].T + w["t2t_b1"]) @ w["t2t_w2"].T + w["t2t_b2"]
def forward_l35(self, h35: torch.Tensor, positions: Optional[torch.Tensor] = None) -> torch.Tensor:
"""layer-35 rows [T, 4096] -> talker final-norm hidden [T, 2048] (KV appended)."""
return self.forward(self.t2t(h35), positions)[0]
def audio_logits(self, t: torch.Tensor) -> torch.Tensor:
return t.float() @ self.w["audio_head"].T
def proj_code(self, t: torch.Tensor) -> torch.Tensor:
return t.float() @ self.w["proj_code_w"].T + self.w["proj_code_b"]
class CodePredictor:
"""Greedy code predictor: positions 0..15 per frame, fresh cache per frame (``predict_codes``)."""
def __init__(self, ck: Checkpoint):
w = ST.code_predictor(ck, F32)
self.stack = Qwen3Stack(w["layers"], w["norm"], CODE_PREDICTOR, resident=True)
self.embed = w["embed"] # [16 * 2048, 1024]
self.heads = w["heads"] # [15, 2048, 1024]
@torch.inference_mode()
def predict(self, row0: torch.Tensor, code0: int) -> Tuple[List[int], torch.Tensor]:
"""(codes 1..15, logits [15, 2048]); code0 2048 (audio end) is looked up as 2047 (``safe_first_code``)."""
self.stack.reset()
c0 = min(int(code0), CODEBOOK_SIZE - 1)
x = torch.stack([row0.float().reshape(-1), self.embed[c0]])
codes, logits = [], []
for g in range(NUM_CODEBOOKS - 1):
h, _ = self.stack.forward(x)
lg = h[-1] @ self.heads[g].T
c = int(torch.argmax(lg))
codes.append(c)
logits.append(lg)
x = self.embed[(g + 1) * CODEBOOK_SIZE + c][None]
return codes, torch.stack(logits)
@torch.inference_mode()
def parallel_logits(self, row0: torch.Tensor, codes: Sequence[int]) -> torch.Tensor:
"""Teacher-forced logits [15, 2048] for a frame's codes (official ``parallel_forward``)."""
self.stack.reset()
c = torch.as_tensor(list(codes)[:NUM_CODEBOOKS - 1]).long()
c[0] = c[0].clamp(max=CODEBOOK_SIZE - 1)
emb = self.embed[c + torch.arange(NUM_CODEBOOKS - 1) * CODEBOOK_SIZE]
h, _ = self.stack.forward(torch.cat([row0.float().reshape(1, -1), emb]))
return torch.einsum("sh,sch->sc", h[1:], self.heads)
class Adaptor:
"""EmbeddingAdaptor (MLP mode, 2 layers): ``RMSNorm(W2 GELU(W1 x))``."""
def __init__(self, w1: torch.Tensor, w2: torch.Tensor, norm: torch.Tensor, eps: float = 1e-6):
self.w1, self.w2, self.norm, self.eps = w1.float(), w2.float(), norm.float(), eps
def __call__(self, x: torch.Tensor) -> torch.Tensor:
return rms_norm(F.gelu(x.float() @ self.w1.T) @ self.w2.T, self.norm, self.eps)
class OutputAdaptor(Adaptor):
"""Frame codes -> thinker row: RVQ latent (sum of 16 projected table rows) then the adaptor MLP."""
def __init__(self, ck: Checkpoint):
w = ST.oad(ck, F32)
super().__init__(w["w1"], w["w2"], w["norm"])
self.tables = w["tables"] # [16, 2048, 512]
def latent(self, codes: torch.Tensor) -> torch.Tensor:
c = torch.as_tensor(codes).long().reshape(-1, NUM_CODEBOOKS)
return sum(self.tables[g][c[:, g]] for g in range(NUM_CODEBOOKS))
def rows(self, codes: torch.Tensor) -> torch.Tensor:
return self(self.latent(codes))
class InputAdaptor(Adaptor):
def __init__(self, ck: Checkpoint):
w = ST.input_adaptor(ck, F32)
super().__init__(w["w1"], w["w2"], w["norm"])
class SpeakerProjection:
def __init__(self, ck: Checkpoint):
self.w = ST.speaker_projection(ck, F32)
def __call__(self, e: torch.Tensor) -> torch.Tensor:
return e.float().reshape(-1) @ self.w.T
|