Download student.py from TigreGotico/wakehubert-tiny: direct link, hf CLI and curl.
- Browser
- Download file 4.15 kB
-
https://huggingface.co/TigreGotico/wakehubert-tiny/resolve/main/student.py
- Command line
-
hf download hf://TigreGotico/wakehubert-tiny/student.py
-
curl -L -o student.py https://huggingface.co/TigreGotico/wakehubert-tiny/resolve/main/student.py
4.15 kB
| """WakeHuBERT tiny: causal log-mel + dilated depthwise-separable conv student (torch only). | |
| model = load_wakehubert_tiny("model.safetensors") | |
| features = model(waveform) # waveform [batch, samples] float32 at 16 kHz -> [batch, frames, 128] | |
| One feature frame every 320 samples (50 per second); frame t depends only on samples before 320 * (t + 1). | |
| """ | |
| import json | |
| import math | |
| from pathlib import Path | |
| import torch | |
| import torch.nn.functional as F | |
| from torch import nn | |
| SR = 16000 | |
| def mel_filterbank(n_freqs, f_min, f_max, n_mels, sample_rate): | |
| """HTK-scale triangular filters, unnormalised; returns [n_freqs, n_mels].""" | |
| def to_mel(f): | |
| return 2595.0 * math.log10(1.0 + f / 700.0) | |
| all_freqs = torch.linspace(0, sample_rate // 2, n_freqs) | |
| pts = torch.linspace(to_mel(f_min), to_mel(f_max), n_mels + 2) | |
| f_pts = 700.0 * (10.0 ** (pts / 2595.0) - 1.0) | |
| f_diff = f_pts[1:] - f_pts[:-1] | |
| slopes = f_pts.unsqueeze(0) - all_freqs.unsqueeze(1) | |
| down = -slopes[:, :-2] / f_diff[:-1] | |
| up = slopes[:, 2:] / f_diff[1:] | |
| return torch.clamp(torch.min(down, up), min=0.0) | |
| class CausalLogMel(nn.Module): | |
| """Log-mel at 100 frames per second; the DFT is a fixed convolution with a left-padded Hann window.""" | |
| def __init__(self, n_mels=64, n_fft=400, hop=160): | |
| super().__init__() | |
| k, f = torch.arange(n_fft), torch.arange(n_fft // 2 + 1) | |
| ang = 2 * math.pi * f[:, None] * k[None, :] / n_fft | |
| win = torch.hann_window(n_fft, periodic=True) | |
| self.register_buffer("basis", (torch.cat([torch.cos(ang), -torch.sin(ang)]) * win).unsqueeze(1)) | |
| self.register_buffer("mel", mel_filterbank(n_fft // 2 + 1, 0.0, SR / 2, n_mels, SR).T.contiguous()) | |
| self.pad, self.hop, self.n_freq = n_fft - hop, hop, n_fft // 2 + 1 | |
| def forward(self, wav): | |
| spec = F.conv1d(F.pad(wav.unsqueeze(1), (self.pad, 0)), self.basis, stride=self.hop) | |
| power = spec[:, :self.n_freq].pow(2) + spec[:, self.n_freq:].pow(2) | |
| return torch.log(torch.matmul(self.mel, power) + 1e-6) | |
| class CausalConv1d(nn.Module): | |
| def __init__(self, in_ch, out_ch, kernel, stride=1, bias=False): | |
| super().__init__() | |
| self.pad = kernel - stride | |
| self.conv = nn.Conv1d(in_ch, out_ch, kernel, stride, bias=bias) | |
| def forward(self, x): | |
| return self.conv(F.pad(x, (self.pad, 0))) | |
| class DSBlock(nn.Module): | |
| """Causal dilated depthwise conv, BN, ReLU, 1x1 conv, BN, plus skip, ReLU.""" | |
| def __init__(self, ch, kernel, dilation): | |
| super().__init__() | |
| self.pad = (kernel - 1) * dilation | |
| self.dw = nn.Conv1d(ch, ch, kernel, dilation=dilation, groups=ch, bias=False) | |
| self.bn1 = nn.BatchNorm1d(ch) | |
| self.pw = nn.Conv1d(ch, ch, 1, bias=False) | |
| self.bn2 = nn.BatchNorm1d(ch) | |
| def forward(self, x): | |
| y = F.relu(self.bn1(self.dw(F.pad(x, (self.pad, 0))))) | |
| return F.relu(self.bn2(self.pw(y)) + x) | |
| class WakeHuBERTTiny(nn.Module): | |
| def __init__(self, channels=256, blocks=8, feature_dim=128, n_mels=64, kernel=5): | |
| super().__init__() | |
| self.mel = CausalLogMel(n_mels) | |
| self.norm = nn.BatchNorm1d(n_mels) | |
| self.stem = CausalConv1d(n_mels, channels, 4, 2) | |
| self.stem_bn = nn.BatchNorm1d(channels) | |
| self.blocks = nn.Sequential(*(DSBlock(channels, kernel, 2 ** (i % 4)) for i in range(blocks))) | |
| self.out = nn.Conv1d(channels, feature_dim, 1) | |
| self.feature_dim = feature_dim | |
| def forward(self, wav): | |
| x = F.relu(self.stem_bn(self.stem(self.norm(self.mel(wav))))) | |
| return self.out(self.blocks(x)).transpose(1, 2) | |
| def load_wakehubert_tiny(path="model.safetensors", config=None): | |
| """Build the model from ``config.json`` (looked up beside the weights unless given) and load the weights.""" | |
| from safetensors.torch import load_file | |
| path = Path(path) | |
| config = Path(config) if config else path.with_name("config.json") | |
| args = json.loads(config.read_text())["pytorch"]["init_args"] | |
| model = WakeHuBERTTiny(**args) | |
| model.load_state_dict(load_file(str(path)), strict=True) | |
| return model.eval() | |