EchoScout-FourTask / code /omini /models /foa_features.py
zhizeng115's picture
Complete four-task dataset and portable code release
7e7a152 verified
Raw History Blame Contribute Delete
3.58 kB
"""FOA 7 通道时频前端:4 路 ambisonic logmel + 3 路 active intensity(mel 域)。
active intensity 矢量是 FOA SELD 的标准空间特征(Politis 2020):
I_a = Re( conj(S_W) * S_a ), a ∈ {X, Y, Z}
归一化分母用全通道能量 E = |S_W|^2 + |S_X|^2 + |S_Y|^2 + |S_Z|^2,
再用与 logmel 同一张 mel 滤波器把线性频率压到 mel 频带(保留符号,不取 log)。
所有谱计算走 fp32(FFT/mel 数值稳定性,与 spatial_ast 同样的考量)。
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from .spatial_ast import _LogmelFilterBankBuffer, _STFTBuffer
class FOAFeatureExtractor(nn.Module):
def __init__(self, sr=32000, n_fft=1024, hop_length=320, n_mels=128,
fmin=50, fmax=14000, target_frame=1024, eps=1e-8):
super().__init__()
self.target_frame = target_frame
self.n_mels = n_mels
self.eps = eps
self.spectrogram_extractor = _STFTBuffer(
n_fft=n_fft, hop_length=hop_length, win_length=n_fft, window="hann",
center=True, pad_mode="reflect", freeze_parameters=True,
)
self.logmel_extractor = _LogmelFilterBankBuffer(
sr=sr, n_fft=n_fft, n_mels=n_mels, fmin=fmin, fmax=fmax,
ref=1.0, amin=1e-10, top_db=None, freeze_parameters=True,
)
# 只对 4 路 logmel 做无仿射归一化(镜像原 BinauralEncoder 的 bn)
self.bn = nn.BatchNorm2d(4, affine=False)
def forward(self, waveforms):
if waveforms.dim() != 3 or waveforms.shape[1] != 4:
raise ValueError(
f"FOAFeatureExtractor 需要 [B,4,T] 的 FOA 波形,收到 {tuple(waveforms.shape)}"
)
B, C, T = waveforms.shape
# 谱计算全程 fp32:bf16 下 log10(clamp(mel, 1e-10)) 会因 1e-10 下溢导致
# clamp 失效、出 -inf(违反「STFT/intensity 在 fp32 域做」的全局约束)。
x = waveforms.reshape(B * C, T).float() # fp32 谱计算
real, imag = self.spectrogram_extractor(x) # 各 [B*4, 1, T', n_freq](fp32)
real = real.reshape(B, C, real.shape[2], real.shape[3])
imag = imag.reshape(B, C, imag.shape[2], imag.shape[3])
mag = torch.sqrt(real ** 2 + imag ** 2) # [B,4,T',n_freq](fp32)
log_mel = self.logmel_extractor(mag) # [B,4,T',n_mels](fp32)
log_mel = self.bn(log_mel.type_as(waveforms)) # cast 回输入 dtype 再 BN
# active intensity(real/imag 已是 fp32)
rw, iw = real[:, 0:1], imag[:, 0:1] # W
ra, ia = real[:, 1:4], imag[:, 1:4] # X,Y,Z
iv = rw * ra + iw * ia # Re(conj(W)*a): [B,3,T',n_freq]
energy = (real ** 2 + imag ** 2).sum(dim=1, keepdim=True) # [B,1,T',n_freq]
iv = iv / (energy + self.eps)
melW = self.logmel_extractor.melW.float() # [n_freq, n_mels]
iv_mel = torch.matmul(iv, melW) # [B,3,T',n_mels]
iv_mel = iv_mel.type_as(log_mel)
feats = torch.cat([log_mel, iv_mel], dim=1) # [B,7,T',n_mels]
if feats.shape[2] < self.target_frame:
feats = F.interpolate(
feats, (self.target_frame, feats.shape[3]),
mode="bicubic", align_corners=True,
)
elif feats.shape[2] > self.target_frame:
feats = feats[:, :, : self.target_frame, :]
return feats