"""Host operations for the fp32 LiteRT graphs. The Kaldi feature extraction and resampling algorithms follow the model's upstream implementation. See the model NOTICE for attribution. This module provides graph inputs and NumPy audio processing for synthesis. """ import math import numpy as np import torch import torch.nn.functional as F NEG = -30000.0 def layer_kinds(c): gdn = [l for l in range(c["n_layers"]) if (l + 1) % c["gdn_period"] != 0] attn = [l for l in range(c["n_layers"]) if (l + 1) % c["gdn_period"] == 0] return gdn, attn def empty_state(c, past): """Zero cache for a new sequence: (kv [1, kv, 2A P, hd], gdn_state, conv_state), numpy float32.""" import numpy as np gdn, attn = layer_kinds(c) inner = c["gdn_heads"] * c["gdn_head_dim"] return (np.zeros((1, c["n_kv_heads"], 2 * len(attn) * past, c["head_dim"]), np.float32), np.zeros((len(gdn), c["gdn_heads"], c["gdn_head_dim"], c["gdn_head_dim"]), np.float32), np.zeros((len(gdn), c["gdn_kernel"] - 1, 3 * inner), np.float32)) class LMHost: def __init__(self, model, past): lm = model.lm.inner if hasattr(model.lm, "inner") else model.lm self.c = lm.c self.past = past self.n_attn = len(layer_kinds(self.c)[1]) self.emb = [e.weight.detach().float().numpy() for e in lm.multi_embedder.embedders] self.spk = lm.speaker_projection self.cond = [e.weight.detach().float().numpy() for e in lm.condition_embeddings] hd = self.c["head_dim"] self.freq = self.c["rope_theta"] ** (-torch.arange(0, hd, 2, dtype=torch.float32) / hd) def row(self, ids, pos, speaker_rows=None, condition_rows=None): """ids [11] int -> the LM input row [1, 1, 1024] float32 (before the graph's RMS norm).""" x = self.emb[0][int(ids[0])].copy() for cb in range(1, len(self.emb)): x = x + self.emb[cb][int(ids[cb])] if speaker_rows and pos in speaker_rows: w = self.spk vec = torch.as_tensor(speaker_rows[pos], dtype=torch.float32).reshape(-1) x = F.linear(vec, w.weight.float(), w.bias.float()).detach().numpy() if condition_rows and pos in condition_rows: table = sorted(condition_rows).index(pos) x = self.cond[table][int(condition_rows[pos])].copy() return x.reshape(1, 1, -1).astype(np.float32) def rope(self, pos): ang = torch.tensor([float(pos)], dtype=torch.float32)[:, None] * self.freq[None, :] return (ang.cos().numpy().reshape(1, 1, 1, -1).astype(np.float32), ang.sin().numpy().reshape(1, 1, 1, -1).astype(np.float32)) def mask(self, pos): m = np.full((1, 1, 1, self.past + 1), NEG, np.float32) m[..., :pos] = 0.0 m[..., self.past] = 0.0 return m def fresh(self): """A new sequence's state: {"pos", "kv" [1, kv, 2A P, hd], "gdn", "conv"}.""" kv, gdn, conv = empty_state(self.c, self.past) return {"pos": 0, "kv": kv, "gdn": gdn, "conv": conv} @staticmethod def copy_state(st): return {"pos": st["pos"], "kv": st["kv"].copy(), "gdn": st["gdn"].copy(), "conv": st["conv"].copy()} def inputs(self, st, x): cos, sin = self.rope(st["pos"]) return [x, cos, sin, self.mask(st["pos"]), st["kv"], st["gdn"], st["conv"]] def step(self, run, st, x): """run(inputs list) -> outputs list; one row. Returns logits [n_cb, vocab], updates st in place.""" pos = st["pos"] assert pos < self.past, (pos, self.past) logits, kv_new, gdn, conv = run(self.inputs(st, x)) for j in range(kv_new.shape[2]): # kv_new [1, kv, 2A, hd]: k, v of each attention layer along dim 2 st["kv"][:, :, j * self.past + pos] = kv_new[:, :, j] st["gdn"] = np.array(gdn, np.float32, copy=True) st["conv"] = np.array(conv, np.float32, copy=True) st["pos"] = pos + 1 return np.asarray(logits).reshape(self.c["n_codebooks"], -1) # ===================================================================================================== codec def codec_tables(cfg, frames, hd=64): """The decoder graph's static inputs: RoPE cos / sin of positions 0 .. 16 T - 1 [1, 1, 16 T, hd / 2] (the reference's formula, float32) and the causal sliding-window masks [1, 1, T_s, T_s] of the stages.""" freq = torch.exp(torch.arange(hd // 2, dtype=torch.float32) * (-math.log(10000.0) * 2 / hd)) n = frames * 2 ** (len(cfg["stages"]) - 1) ph = torch.arange(n, dtype=torch.float32)[:, None] * freq[None, :] cos = ph.cos().numpy().reshape(1, 1, n, hd // 2).astype(np.float32) sin = ph.sin().numpy().reshape(1, 1, n, hd // 2).astype(np.float32) wins = [] for si, s in enumerate(cfg["stages"]): t = frames * 2 ** si d = np.arange(t)[:, None] - np.arange(t)[None, :] wins.append(np.where((d >= 0) & (d < s["context_frames"]), 0.0, NEG).astype(np.float32).reshape(1, 1, t, t)) return cos, sin, wins def codec_frame_masks(frames, f, n_stages=5): out = [] for si in range(n_stages): r = 2 ** si m = np.zeros((1, frames * r, 1), np.float32) m[:, : f * r] = 1.0 out.append(m) return out class CodecHost: def __init__(self, model, frames): codec = model.codec self.c = codec.c self.frames = frames assert self.c["head_hop"] == 184 and self.c["fir_kernel"] == 127 and self.c["hop"] == 2940 assert (self.c["resample_orig"], self.c["resample_new"], self.c["resample_width"]) == (736, 735, 17) self.books = [q.codebook.detach().float().numpy() for q in codec.quantizers] self.mixer = codec.head.mixer.weight.detach().float().numpy() # [1, 2, 127] self.kernel = codec.to_external_kernel.detach().float().numpy() # [735, 1, 770] self.windows = {n: torch.hann_window(n, periodic=True).float().numpy() for n in self.c["n_ffts"]} assert len(self.c["stages"]) == 5 self.cos, self.sin, self.wins = codec_tables(self.c, frames) def inputs(self, codes): """codes [F, n_cb] int (F <= bucket) -> graph inputs (cv, cos, sin, 5 windows, 5 frame masks).""" f = codes.shape[0] assert f <= self.frames, (f, self.frames) dim = self.books[0].shape[1] cv = np.zeros((1, self.frames, dim * len(self.books)), np.float32) for i, book in enumerate(self.books): cv[0, :f, dim * i:dim * (i + 1)] = book[np.asarray(codes)[:, i]] return [cv, self.cos, self.sin] + self.wins + codec_frame_masks(self.frames, f) def split(self, head, f): """The graph's packed head output [1, 16 T, 738 + 2210] -> (out736, out2208) of the F valid frames.""" h = np.asarray(head, np.float32).reshape(16 * self.frames, -1)[: 16 * f] n0 = self.c["n_ffts"][0] + 2 return h[:, :n0], h[:, n0:] # ---- head outputs -> audio def _spec(self, out, n): logmag, phase = np.split(out.astype(np.float32), 2, axis=-1) # [frames, n/2 + 1] each mag = np.exp(np.minimum(logmag, np.float32(math.log(100.0)))) return mag, phase def istft_np(self, mag, phase, n, length): """NumPy iSTFT, center=True, periodic Hann, hop 184 (fp32 FFT path: norm="forward" then 1/n in float32).""" hop = 184 spec = np.empty(mag.shape, np.complex64) # [T, bins] spec.real = mag * np.cos(phase) spec.imag = mag * np.sin(phase) fr = np.fft.irfft(spec, n=n, axis=-1, norm="forward") assert fr.dtype == np.float32, fr.dtype fr = fr * np.float32(1.0 / n) w = self.windows[n] fr = fr * w[None, :] t = fr.shape[0] k = n // hop seg = np.zeros((t + k - 1, hop), np.float32) env = np.zeros((t + k - 1, hop), np.float32) w2 = (w * w).reshape(k, hop) frs = fr.reshape(t, k, hop) for j in range(k): seg[j:j + t] += frs[:, j] env[j:j + t] += w2[j][None, :] y = seg.reshape(-1) e = env.reshape(-1) y = y / np.where(e > 1e-11, e, np.float32(1.0)) return y[n // 2: n // 2 + length] def audio_np(self, o736, o2208): frames = o736.shape[0] length = frames * 184 br = [] for out, n in ((o736, 736), (o2208, 2208)): mag, ph = self._spec(out, n) br.append(self.istft_np(mag, ph, n, length)) xs = np.stack(br) # [2, length] xp = np.pad(xs, ((0, 0), (63, 63))) w = self.mixer[0] # [2, 127] mix = np.zeros(length, np.float32) for c in range(2): win = np.lib.stride_tricks.sliding_window_view(xp[c], 127) # [length, 127] mix = mix + (win @ w[c]).astype(np.float32) xp2 = np.pad(mix, (17, 17 + 736)) fr = np.lib.stride_tricks.sliding_window_view(xp2, 770)[::736] # [J, 770] y = (fr @ self.kernel[:, 0, :].T).astype(np.float32).reshape(-1) y = y[: math.ceil(735 * length / 736)] return y[: (frames // 16) * 2940] class SpeakerHost: def __init__(self, model, mm, frames=998): enc = model.speaker_encoder self.c = enc.c self.mm = mm self.frames = frames # the reference's own fbank tables (hamming window, mel banks), computed once with its code path sr = float(self.c["sample_rate"]) self.size = int(sr * self.c["frame_length_ms"] * 0.001) self.shift = int(sr * self.c["frame_shift_ms"] * 0.001) self.padded = 2 ** (self.size - 1).bit_length() self.window = torch.hamming_window(self.size, periodic=False, alpha=0.54, beta=0.46, dtype=torch.float32).numpy() self.banks = self._banks() def _banks(self): nb = int(self.c["num_mel_bins"]) sr = float(self.c["sample_rate"]) dtype = torch.float32 padded = self.padded fft_bin_width = sr / padded mel_low, mel_high = 1127.0 * math.log(1.0 + 20.0 / 700.0), 1127.0 * math.log(1.0 + 0.5 * sr / 700.0) delta = (mel_high - mel_low) / (nb + 1) bins = torch.arange(nb, dtype=dtype).unsqueeze(1) left, center, right = mel_low + bins * delta, mel_low + (bins + 1.0) * delta, mel_low + (bins + 2.0) * delta mel = (1127.0 * (1.0 + fft_bin_width * torch.arange(padded / 2, dtype=dtype) / 700.0).log()).unsqueeze(0) banks = torch.max(torch.zeros(1, dtype=dtype), torch.min((mel - left) / (center - left), (right - mel) / (right - center))) return F.pad(banks, (0, 1), mode="constant", value=0).numpy() # [80, 257] def wav16k(self, wav, sr): enc_in = torch.as_tensor(wav, dtype=torch.float32) if enc_in.ndim == 1: enc_in = enc_in[None] if enc_in.shape[0] > 1: enc_in = enc_in.mean(dim=0, keepdim=True) y = self.mm.sinc_resample(enc_in, int(sr), int(self.c["sample_rate"])) return y[..., : int(float(self.c["max_seconds"]) * int(self.c["sample_rate"]))][0].numpy() def fbank_np(self, x16k): x = (x16k.astype(np.float32) * np.float32(self.c["waveform_scale"])) n = 1 + (len(x) - self.size) // self.shift fr = np.lib.stride_tricks.as_strided(x, (n, self.size), (self.shift * 4, 4)).copy() fr = fr - fr.mean(axis=1, keepdims=True, dtype=np.float32) prev = np.concatenate([fr[:, :1], fr[:, :-1]], axis=1) fr = fr - np.float32(0.97) * prev fr = fr * self.window[None, :] fr = np.pad(fr, ((0, 0), (0, self.padded - self.size))) spec = np.fft.rfft(fr, axis=-1, norm="forward") * np.float32(self.padded) power = (np.abs(spec).astype(np.float32)) ** 2 mel = power @ self.banks.T return np.log(np.maximum(mel, np.float32(np.finfo(np.float32).eps))).astype(np.float32) # [frames, 80] def inputs(self, fb): """fbank [frames, 80] -> graph inputs (feats [1, 80, T], m1, m2, k1, k2).""" f = fb.shape[0] assert f <= self.frames, (f, self.frames) feats = fb.T - fb.T.mean(axis=-1, keepdims=True, dtype=np.float32) x = np.zeros((1, fb.shape[1], self.frames), np.float32) x[0, :, :f] = feats t2 = (self.frames + 1) // 2 f2 = (f + 1) // 2 m1 = np.zeros((1, 1, 1, self.frames), np.float32) m1[..., :f] = 1.0 m2 = np.zeros((1, 1, 1, t2), np.float32) m2[..., :f2] = 1.0 k1 = np.where(m1 > 0, 0.0, NEG).astype(np.float32) k2 = np.where(m2 > 0, 0.0, NEG).astype(np.float32) return [x, m1, m2, k1, k2]