Download code/vitakws/features.py from thucdangvan020999/aurora-wake-model: direct link, hf CLI and curl.
- Browser
- Download file 5.17 kB
-
https://huggingface.co/thucdangvan020999/aurora-wake-model/resolve/main/code/vitakws/features.py
- Command line
-
hf download hf://thucdangvan020999/aurora-wake-model/code/vitakws/features.py
-
curl -L -o features.py https://huggingface.co/thucdangvan020999/aurora-wake-model/resolve/main/code/vitakws/features.py
5.17 kB
| """Log-mel front end. | |
| The same maths is implemented twice on purpose: | |
| * ``LogMel`` torch module used for training (runs on the GPU). | |
| * ``logmel_numpy`` dependency-free reference for porting to the device | |
| (Kotlin/C++) and for the ONNX runtime path. | |
| ``tests/test_features.py`` checks that the two agree. | |
| Framing uses no centre padding, so frame ``i`` covers samples | |
| ``[i*hop, i*hop + n_fft)``. Features of a sliding window can therefore be | |
| computed incrementally on the device and stay identical to training. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import asdict, dataclass | |
| import numpy as np | |
| import torch | |
| from torch import nn | |
| class FeatureConfig: | |
| sample_rate: int = 16000 | |
| n_fft: int = 512 | |
| win_length: int = 480 | |
| hop_length: int = 160 | |
| n_mels: int = 40 | |
| f_min: float = 20.0 | |
| f_max: float = 7600.0 | |
| log_eps: float = 1e-6 | |
| def num_frames(self, num_samples: int) -> int: | |
| if num_samples < self.n_fft: | |
| return 0 | |
| return 1 + (num_samples - self.n_fft) // self.hop_length | |
| def to_dict(self) -> dict: | |
| return asdict(self) | |
| def hz_to_mel(hz: np.ndarray | float) -> np.ndarray: | |
| return 2595.0 * np.log10(1.0 + np.asarray(hz, dtype=np.float64) / 700.0) | |
| def mel_to_hz(mel: np.ndarray | float) -> np.ndarray: | |
| return 700.0 * (10.0 ** (np.asarray(mel, dtype=np.float64) / 2595.0) - 1.0) | |
| def mel_filterbank(cfg: FeatureConfig) -> np.ndarray: | |
| """Triangular HTK-scale mel filters, shape [n_mels, n_fft // 2 + 1].""" | |
| n_freqs = cfg.n_fft // 2 + 1 | |
| freqs = np.linspace(0.0, cfg.sample_rate / 2.0, n_freqs) | |
| edges = mel_to_hz(np.linspace(hz_to_mel(cfg.f_min), hz_to_mel(cfg.f_max), cfg.n_mels + 2)) | |
| lower = (freqs[None, :] - edges[:-2, None]) / (edges[1:-1, None] - edges[:-2, None]) | |
| upper = (edges[2:, None] - freqs[None, :]) / (edges[2:, None] - edges[1:-1, None]) | |
| return np.maximum(0.0, np.minimum(lower, upper)).astype(np.float32) | |
| def analysis_window(cfg: FeatureConfig) -> np.ndarray: | |
| """Periodic Hann of ``win_length`` centred inside ``n_fft`` samples.""" | |
| n = np.arange(cfg.win_length, dtype=np.float64) | |
| hann = 0.5 - 0.5 * np.cos(2.0 * np.pi * n / cfg.win_length) | |
| left = (cfg.n_fft - cfg.win_length) // 2 | |
| window = np.zeros(cfg.n_fft, dtype=np.float64) | |
| window[left : left + cfg.win_length] = hann | |
| return window.astype(np.float32) | |
| def logmel_numpy(wave: np.ndarray, cfg: FeatureConfig) -> np.ndarray: | |
| """Mono float waveform [T] -> log-mel [n_mels, frames].""" | |
| wave = np.asarray(wave, dtype=np.float32) | |
| n_frames = cfg.num_frames(len(wave)) | |
| if n_frames == 0: | |
| return np.zeros((cfg.n_mels, 0), dtype=np.float32) | |
| idx = np.arange(cfg.n_fft)[None, :] + cfg.hop_length * np.arange(n_frames)[:, None] | |
| frames = wave[idx] * analysis_window(cfg)[None, :] | |
| power = np.abs(np.fft.rfft(frames, n=cfg.n_fft, axis=1)) ** 2 | |
| mel = power @ mel_filterbank(cfg).T.astype(np.float64) | |
| return np.log(mel + cfg.log_eps).T.astype(np.float32) | |
| class LogMel(nn.Module): | |
| """Waveform [B, T] -> log-mel [B, 1, n_mels, frames].""" | |
| def __init__(self, cfg: FeatureConfig | None = None): | |
| super().__init__() | |
| self.cfg = cfg or FeatureConfig() | |
| self.register_buffer("window", torch.from_numpy(analysis_window(self.cfg))) | |
| self.register_buffer("fbank", torch.from_numpy(mel_filterbank(self.cfg))) | |
| def forward(self, wave: torch.Tensor) -> torch.Tensor: | |
| spec = torch.stft( | |
| wave, | |
| n_fft=self.cfg.n_fft, | |
| hop_length=self.cfg.hop_length, | |
| win_length=self.cfg.n_fft, | |
| window=self.window, | |
| center=False, | |
| return_complex=True, | |
| ) | |
| power = spec.real**2 + spec.imag**2 | |
| mel = torch.matmul(self.fbank, power) | |
| return torch.log(mel + self.cfg.log_eps).unsqueeze(1) | |
| def spec_augment( | |
| feats: torch.Tensor, | |
| *, | |
| freq_masks: int, | |
| freq_width: int, | |
| time_masks: int, | |
| time_width: int, | |
| generator: torch.Generator | None = None, | |
| ) -> torch.Tensor: | |
| """SpecAugment masking (Park et al., 2019) on [B, 1, F, T]; masked cells get the batch mean.""" | |
| if (freq_masks == 0 or freq_width == 0) and (time_masks == 0 or time_width == 0): | |
| return feats | |
| b, _, f, t = feats.shape | |
| out = feats.clone() | |
| fill = feats.mean() | |
| def rand(high: int, n: int) -> torch.Tensor: | |
| return torch.randint(0, high + 1, (n,), generator=generator) | |
| for _ in range(freq_masks if freq_width > 0 else 0): | |
| widths = rand(min(freq_width, f), b) | |
| for i in range(b): | |
| w = int(widths[i]) | |
| if w: | |
| start = int(torch.randint(0, f - w + 1, (1,), generator=generator)) | |
| out[i, :, start : start + w, :] = fill | |
| for _ in range(time_masks if time_width > 0 else 0): | |
| widths = rand(min(time_width, t), b) | |
| for i in range(b): | |
| w = int(widths[i]) | |
| if w: | |
| start = int(torch.randint(0, t - w + 1, (1,), generator=generator)) | |
| out[i, :, :, start : start + w] = fill | |
| return out | |