Download ecodec_fast/istft_head.py from ESpeech/ECodec-FAST: direct link, hf CLI and curl.
- Browser
- Download file 2.47 kB
-
https://huggingface.co/ESpeech/ECodec-FAST/resolve/main/ecodec_fast/istft_head.py
- Command line
-
hf download hf://ESpeech/ECodec-FAST/ecodec_fast/istft_head.py
-
curl -L -o istft_head.py https://huggingface.co/ESpeech/ECodec-FAST/resolve/main/ecodec_fast/istft_head.py
2.47 kB
| """ISTFTHead vendored from vocos 0.1.0 (MIT, https://github.com/gemelo-ai/vocos) to avoid the | |
| vocos -> encodec dependency chain. Unchanged except for imports.""" | |
| import torch | |
| from torch import nn | |
| class ISTFT(nn.Module): | |
| """iSTFT with "same" padding (torch.istft only supports center=True with windowing).""" | |
| def __init__(self, n_fft: int, hop_length: int, win_length: int, padding: str = "same"): | |
| super().__init__() | |
| if padding not in ["center", "same"]: | |
| raise ValueError("Padding must be 'center' or 'same'.") | |
| self.padding = padding | |
| self.n_fft = n_fft | |
| self.hop_length = hop_length | |
| self.win_length = win_length | |
| self.register_buffer("window", torch.hann_window(win_length)) | |
| def forward(self, spec: torch.Tensor) -> torch.Tensor: | |
| if self.padding == "center": | |
| return torch.istft(spec, self.n_fft, self.hop_length, self.win_length, self.window, center=True) | |
| pad = (self.win_length - self.hop_length) // 2 | |
| assert spec.dim() == 3, "Expected a 3D tensor as input" | |
| B, N, T = spec.shape | |
| ifft = torch.fft.irfft(spec, self.n_fft, dim=1, norm="backward") | |
| ifft = ifft * self.window[None, :, None] | |
| output_size = (T - 1) * self.hop_length + self.win_length | |
| y = torch.nn.functional.fold( | |
| ifft, output_size=(1, output_size), kernel_size=(1, self.win_length), stride=(1, self.hop_length), | |
| )[:, 0, 0, pad:-pad] | |
| window_sq = self.window.square().expand(1, T, -1).transpose(1, 2) | |
| window_envelope = torch.nn.functional.fold( | |
| window_sq, output_size=(1, output_size), kernel_size=(1, self.win_length), stride=(1, self.hop_length), | |
| ).squeeze()[pad:-pad] | |
| assert (window_envelope > 1e-11).all() | |
| return y / window_envelope | |
| class ISTFTHead(nn.Module): | |
| """Predicts STFT magnitude/phase from features [B, L, H] and returns audio [B, T].""" | |
| def __init__(self, dim: int, n_fft: int, hop_length: int, padding: str = "same"): | |
| super().__init__() | |
| self.out = torch.nn.Linear(dim, n_fft + 2) | |
| self.istft = ISTFT(n_fft=n_fft, hop_length=hop_length, win_length=n_fft, padding=padding) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| x = self.out(x).transpose(1, 2) | |
| mag, p = x.chunk(2, dim=1) | |
| mag = torch.clip(torch.exp(mag), max=1e2) | |
| S = mag * (torch.cos(p) + 1j * torch.sin(p)) | |
| return self.istft(S) | |