Download scripts/l15.py from matthiastl/tyger-coreml: direct link, hf CLI and curl.
- Browser
- Download file 8.44 kB
-
https://huggingface.co/matthiastl/tyger-coreml/resolve/main/scripts/l15.py
- Command line
-
hf download hf://matthiastl/tyger-coreml/scripts/l15.py
-
curl -L -o l15.py https://huggingface.co/matthiastl/tyger-coreml/resolve/main/scripts/l15.py
8.44 kB
| """Nemotron 3.5 ASR streaming's encoder up to layer 15, in plain PyTorch, for export. | |
| The same computation as transformers' `NemotronAsrStreamingEncoder` with `num_lookahead_tokens=0` on one unpadded | |
| window (the only way tyger uses it): causal Conv2d subsampling by 8, then conformer blocks whose attention sees the | |
| current frame and the 56 before it (relative positions, Transformer-XL style), and whose depthwise convolution is | |
| causal. Weights are taken from the HF module by name. Also the log-mel front end in numpy, so the port needs neither | |
| transformers nor torch at run time. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| import numpy as np | |
| import torch | |
| from torch import nn | |
| LEFT = 56 # config.sliding_window - 1 | |
| LAYERS = 15 | |
| LOG_GUARD = 2.0 ** -24 | |
| class FFN(nn.Module): | |
| def __init__(self, d, f): | |
| super().__init__() | |
| self.linear1, self.linear2 = nn.Linear(d, f, bias=False), nn.Linear(f, d, bias=False) | |
| def forward(self, x): | |
| return self.linear2(nn.functional.silu(self.linear1(x))) | |
| class Attention(nn.Module): | |
| def __init__(self, d, h): | |
| super().__init__() | |
| self.h, self.dk = h, d // h | |
| self.q_proj, self.k_proj, self.v_proj, self.o_proj = (nn.Linear(d, d, bias=False) for _ in range(4)) | |
| self.relative_k_proj = nn.Linear(d, d, bias=False) | |
| self.bias_u = nn.Parameter(torch.zeros(h, self.dk)) | |
| self.bias_v = nn.Parameter(torch.zeros(h, self.dk)) | |
| def forward(self, x, pos, mask): | |
| """x (1, T, d); pos (1, 2T-1, d) for offsets T-1 .. -(T-1); mask (T, T) bool, True = may attend.""" | |
| t = x.shape[1] | |
| q = self.q_proj(x).view(1, t, self.h, self.dk).transpose(1, 2) | |
| k = self.k_proj(x).view(1, t, self.h, self.dk).transpose(1, 2) | |
| v = self.v_proj(x).view(1, t, self.h, self.dk).transpose(1, 2) | |
| scale = self.dk ** -0.5 | |
| p = self.relative_k_proj(pos).view(1, -1, self.h, self.dk).permute(0, 2, 3, 1) | |
| bd = (q + self.bias_v.view(1, self.h, 1, self.dk)) @ p # (1, h, T, 2T-1) | |
| bd = nn.functional.pad(bd, (1, 0)).reshape(1, self.h, -1, t)[:, :, 1:].reshape(1, self.h, t, -1)[..., :t] | |
| bd = (bd * scale).masked_fill(~mask, float("-inf")) | |
| ac = ((q + self.bias_u.view(1, self.h, 1, self.dk)) @ k.transpose(2, 3)) * scale | |
| w = torch.softmax(ac + bd, dim=-1) | |
| return self.o_proj((w @ v).transpose(1, 2).reshape(1, t, -1)) | |
| class ConvModule(nn.Module): | |
| def __init__(self, d, kernel): | |
| super().__init__() | |
| self.kernel = kernel | |
| # The 1x1 convolutions are linear layers over channels: written as such, they export as MatMul (and get | |
| # 8-bit weights with the other linear layers). | |
| self.pointwise_conv1 = nn.Linear(d, 2 * d, bias=False) | |
| self.depthwise_conv = nn.Conv1d(d, d, kernel, groups=d, bias=False) | |
| self.norm = nn.LayerNorm(d) | |
| self.pointwise_conv2 = nn.Linear(d, d, bias=False) | |
| def forward(self, x): | |
| x = nn.functional.glu(self.pointwise_conv1(x), dim=-1).transpose(1, 2) | |
| x = self.depthwise_conv(nn.functional.pad(x, (self.kernel - 1, 0))).transpose(1, 2) | |
| return self.pointwise_conv2(nn.functional.silu(self.norm(x))) | |
| class Block(nn.Module): | |
| def __init__(self, d, h, f, kernel): | |
| super().__init__() | |
| self.feed_forward1, self.feed_forward2 = FFN(d, f), FFN(d, f) | |
| self.self_attn = Attention(d, h) | |
| self.conv = ConvModule(d, kernel) | |
| for name in ("norm_feed_forward1", "norm_self_att", "norm_conv", "norm_feed_forward2", "norm_out"): | |
| setattr(self, name, nn.LayerNorm(d)) | |
| def forward(self, x, pos, mask): | |
| x = x + 0.5 * self.feed_forward1(self.norm_feed_forward1(x)) | |
| x = x + self.self_attn(self.norm_self_att(x), pos, mask) | |
| x = x + self.conv(self.norm_conv(x)) | |
| x = x + 0.5 * self.feed_forward2(self.norm_feed_forward2(x)) | |
| return self.norm_out(x) | |
| class Subsampling(nn.Module): | |
| """Three causal stride-2 Conv2d stages over (time, mel): time padded (2, 1), frequency padded (2, 1).""" | |
| def __init__(self, channels=256, d=1024, mels=128): | |
| super().__init__() | |
| self.conv_in = nn.Conv2d(1, channels, 3, stride=2) | |
| self.dw = nn.ModuleList(nn.Conv2d(channels, channels, 3, stride=2, groups=channels) for _ in range(2)) | |
| self.pw = nn.ModuleList(nn.Conv2d(channels, channels, 1) for _ in range(2)) | |
| freq = mels | |
| for _ in range(3): | |
| freq = freq // 2 + 1 # 128 -> 65 -> 33 -> 17 | |
| self.linear = nn.Linear(channels * freq, d) | |
| def forward(self, mel): | |
| x = torch.relu(self.conv_in(nn.functional.pad(mel.unsqueeze(1), (2, 1, 2, 1)))) | |
| for dw, pw in zip(self.dw, self.pw): | |
| x = torch.relu(pw(dw(nn.functional.pad(x, (2, 1, 2, 1))))) | |
| return self.linear(x.transpose(1, 2).reshape(1, x.shape[2], -1)) | |
| def positions(t: int, d: int) -> torch.Tensor: | |
| """(1, 2t-1, d): interleaved sin/cos of relative offsets t-1 .. -(t-1).""" | |
| inv = 1.0 / (10000.0 ** (torch.arange(0, d, 2, dtype=torch.float32) / d)) | |
| f = torch.arange(t - 1, -t, -1, dtype=torch.float32)[:, None] * inv | |
| return torch.stack([f.sin(), f.cos()], -1).reshape(1, 2 * t - 1, d) | |
| class L15(nn.Module): | |
| """log-mel (1, T, 128) -> layer-15 output (1, T', 1024), T' = (T - 1) // 8 + 1.""" | |
| def __init__(self, d=1024, h=8, f=4096, kernel=9, layers=LAYERS): | |
| super().__init__() | |
| self.d = d | |
| self.subsampling = Subsampling(d=d) | |
| self.layers = nn.ModuleList(Block(d, h, f, kernel) for _ in range(layers)) | |
| def forward(self, mel): | |
| x = self.subsampling(mel) | |
| t = x.shape[1] | |
| idx = torch.arange(t) | |
| diff = idx[:, None] - idx[None, :] | |
| mask = (diff >= 0) & (diff <= LEFT) | |
| pos = positions(t, self.d) | |
| for layer in self.layers: | |
| x = layer(x, pos, mask) | |
| return x | |
| def from_hf(cls, encoder) -> "L15": | |
| """Copy the weights of transformers' NemotronAsrStreamingEncoder (its first 15 layers).""" | |
| model = cls() | |
| src = encoder.state_dict() | |
| mapping = { | |
| "subsampling.conv_in.weight": "subsampling.conv_in.weight", | |
| "subsampling.conv_in.bias": "subsampling.conv_in.bias", | |
| "subsampling.linear.weight": "subsampling.linear.weight", | |
| "subsampling.linear.bias": "subsampling.linear.bias", | |
| } | |
| for i in range(2): | |
| for kind, ours in (("depthwise_conv", "dw"), ("pointwise_conv", "pw")): | |
| for p in ("weight", "bias"): | |
| mapping[f"subsampling.{ours}.{i}.{p}"] = f"subsampling.layers.{i}.{kind}.{p}" | |
| for name in model.state_dict(): | |
| if name.startswith("layers."): | |
| mapping[name] = name | |
| missing = [ours for ours, theirs in mapping.items() if theirs not in src] | |
| if missing or set(mapping) != set(model.state_dict()): | |
| raise KeyError(f"weights not found: {missing[:5]}") | |
| weights = {} | |
| for ours, theirs in mapping.items(): | |
| w = src[theirs] | |
| weights[ours] = w[..., 0] if ".pointwise_conv" in ours and w.dim() == 3 else w | |
| model.load_state_dict(weights, strict=True) | |
| return model.eval() | |
| class LogMel: | |
| """The processor's features in numpy: pre-emphasis, centred 512-point STFT of a 400-sample symmetric Hann window | |
| every 160 samples, power, 128 Slaney mels, log(x + 2^-24); the last frame (past the audio) is zeroed.""" | |
| def __init__(self, mel_filters: np.ndarray): | |
| self.filters = mel_filters.astype(np.float32) # (128, 257) | |
| n = np.arange(400) | |
| hann = (0.5 - 0.5 * np.cos(2 * math.pi * n / 399)).astype(np.float32) | |
| self.window = np.zeros(512, np.float32) | |
| self.window[56:456] = hann | |
| def __call__(self, wav: np.ndarray) -> np.ndarray: | |
| x = np.concatenate([wav[:1], wav[1:] - 0.97 * wav[:-1]]).astype(np.float32) | |
| x = np.pad(x, (256, 256)) | |
| frames = 1 + (len(x) - 512) // 160 | |
| idx = np.arange(512)[None, :] + 160 * np.arange(frames)[:, None] | |
| spec = np.fft.rfft(x[idx] * self.window, axis=1) | |
| power = (spec.real ** 2 + spec.imag ** 2).astype(np.float32) | |
| mel = np.log(power @ self.filters.T + LOG_GUARD).astype(np.float32) | |
| mel[len(wav) // 160:] = 0.0 | |
| return mel | |