File size: 6,981 Bytes
7e7a152 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | """Spatial-AST 音频前端的共享组件(torchlibrosa shim + conv/patch 工具)。
Vendored from SLAM-LLM's `src/slam_llm/models/SpatialAST/SpatialAST.py`.
原 `BinauralEncoder`(双声道编码器)与 `load_spatial_ast` 已随 ST-Audio Encoder
改造移除——本模块现在只保留被 `foa_features` / `st_audio_encoder` 复用的部件:
`_STFTBuffer` / `_LogmelFilterBankBuffer`(STFT/logmel shim)、`conv3x3`、
`PatchEmbed_new`。
torchlibrosa's `STFT` / `LogmelFilterBank` use `nn.Parameter.data = torch.Tensor(...)`
assignment in __init__, which crashes inside HF's `init_empty_weights()` and
DeepSpeed's `zero.Init()` contexts (the parameter has been moved to meta
device or partitioned, and in-place .data assignment from a real cpu tensor
mismatches). We provide drop-in replacements `_STFTBuffer` and
`_LogmelFilterBankBuffer` that use `register_buffer` for the (frozen) FFT
basis and mel filter — the math is byte-identical to torchlibrosa, only the
storage type differs, and buffers are not subject to accelerate's parameter
materialisation hook (when `include_buffers=False`, the default).
"""
import librosa
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.models.layers import to_2tuple
# ---------------------------- torchlibrosa-compatible shims ----------------------------
def _dft_matrix(n: int) -> np.ndarray:
"""Same as torchlibrosa.stft.DFTBase.dft_matrix — returns (n, n) complex."""
x, y = np.meshgrid(np.arange(n), np.arange(n))
omega = np.exp(-2 * np.pi * 1j / n)
return np.power(omega, x * y)
class _STFTBuffer(nn.Module):
"""Drop-in replacement for torchlibrosa.stft.STFT using register_buffer.
Same fourier-basis math, same windowing, same conv1d compute, same output
shape `(batch, 1, time_steps, n_fft//2+1)` — bit-exact with torchlibrosa.
"""
def __init__(self, n_fft=2048, hop_length=None, win_length=None,
window='hann', center=True, pad_mode='reflect',
freeze_parameters=True):
super().__init__()
self.n_fft = n_fft
self.center = center
self.pad_mode = pad_mode
self.win_length = win_length if win_length is not None else n_fft
self.hop_length = hop_length if hop_length is not None else int(self.win_length // 4)
fft_window = librosa.filters.get_window(window, self.win_length, fftbins=True)
fft_window = librosa.util.pad_center(fft_window, size=n_fft)
W = _dft_matrix(n_fft)
out_channels = n_fft // 2 + 1
real_w = np.real(W[:, :out_channels] * fft_window[:, None]).T[:, None, :] # (n_freq, 1, n_fft)
imag_w = np.imag(W[:, :out_channels] * fft_window[:, None]).T[:, None, :]
self.register_buffer("conv_real_weight", torch.tensor(real_w, dtype=torch.float32))
self.register_buffer("conv_imag_weight", torch.tensor(imag_w, dtype=torch.float32))
def forward(self, input):
# input: (B, T)
x = input.unsqueeze(1) # (B, 1, T)
if self.center:
x = F.pad(x, (self.n_fft // 2, self.n_fft // 2), mode=self.pad_mode)
# Buffers stay fp32 by design (numerical stability of FFT basis); cast to
# input dtype on the fly so bf16 / fp16 audio flows work without `model.to`
# having converted them.
w_real = self.conv_real_weight.to(x.dtype)
w_imag = self.conv_imag_weight.to(x.dtype)
real = F.conv1d(x, w_real, stride=self.hop_length) # (B, n_freq, T')
imag = F.conv1d(x, w_imag, stride=self.hop_length)
real = real[:, None, :, :].transpose(2, 3) # (B, 1, T', n_freq)
imag = imag[:, None, :, :].transpose(2, 3)
return real, imag
class _LogmelFilterBankBuffer(nn.Module):
"""Drop-in replacement for torchlibrosa.stft.LogmelFilterBank using
register_buffer. Same mel matrix (librosa.filters.mel), same matmul, same
power_to_db. `self.melW` attribute exposed for code that reaches into it
(e.g. FOAFeatureExtractor uses it to apply mel to intensity features).
"""
def __init__(self, sr=22050, n_fft=2048, n_mels=64, fmin=0.0, fmax=None,
is_log=True, ref=1.0, amin=1e-10, top_db=80.0,
freeze_parameters=True):
super().__init__()
self.is_log = is_log
self.ref = ref
self.amin = amin
self.top_db = top_db
if fmax is None:
fmax = sr // 2
mel_np = librosa.filters.mel(
sr=sr, n_fft=n_fft, n_mels=n_mels, fmin=fmin, fmax=fmax,
).T # (n_freq, n_mels)
self.register_buffer("melW", torch.tensor(mel_np, dtype=torch.float32))
def forward(self, input):
# input: (..., n_freq) → output: (..., n_mels)
# Cast melW to input dtype on the fly (same rationale as _STFTBuffer).
mel = torch.matmul(input, self.melW.to(input.dtype))
if not self.is_log:
return mel
log_spec = 10.0 * torch.log10(torch.clamp(mel, min=self.amin))
log_spec = log_spec - 10.0 * float(np.log10(max(self.amin, self.ref)))
if self.top_db is not None:
log_spec = torch.clamp(log_spec, min=log_spec.max().item() - self.top_db)
return log_spec
# ---------------------------- shared conv / patch-embed helpers ----------------------------
def conv3x3(in_channels, out_channels, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
class PatchEmbed_new(nn.Module):
"""Flexible image-to-patch embedding (overlapping patches supported)."""
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, stride=10):
super().__init__()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
stride = to_2tuple(stride)
self.img_size = img_size
self.patch_size = patch_size
self.in_chans = in_chans
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
# Conv2d output shape (padding=0, dilation=1, groups=1):
# out = floor((in - kernel) / stride) + 1
# We compute it analytically rather than running a dummy forward in
# __init__ — under DeepSpeed zero.Init the Conv2d weight has shape [0]
# (partitioned) and forward crashes with "weight should have at least
# three dimensions".
h = (img_size[0] - patch_size[0]) // stride[0] + 1
w = (img_size[1] - patch_size[1]) // stride[1] + 1
self.patch_hw = (h, w)
self.num_patches = h * w
def get_output_shape(self, img_size):
# Kept for backward-compat with any external caller; not used in __init__.
return self.proj(torch.randn(1, self.in_chans, img_size[0], img_size[1])).shape
def forward(self, x):
x = self.proj(x)
x = x.flatten(2)
x = x.transpose(1, 2)
return x
|