File size: 7,829 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 156 157 158 159 160 161 162 163 164 165 166 | """ST-Audio Encoder:时间分辨空间音频编码器(对齐 Oh et al. 2026)。
前端可配置(`audio_frontend`):
- "binaural"(默认):BinauralFeatureExtractor(2ch→logmel×2+IPD×2=4ch) →
conv_downsample(4→1)。conv_downsample/backbone/head(355)/fc_norm/pos_embed/cls_tokens
全继承 BAT `finetuned.pth`(双声道域,零迁移)——即论文 stage1+2 已由 BAT 训好,只需训 stage3。
**不建静态 DoA/dist 头**(stage1/2 跳过;静态定位 token 本就不进 LLM)。
- "foa":FOAFeatureExtractor(4ch→7ch) → foa_conv(7→1)(随机初始化,需 FOA 域 stage1+2)。
建 doa_head/dist_head(论文 stage2 的静态全局定位头)。
公共结构:12 层 backbone → 3 全局 token(semantic[/DoA/dist]) + 512 patch;patch reshape
[T'=64,F'=8] → 频率维平均 → 插值 40 bin → 2 层时序 self-attn → 逐 bin 动态头
(activity/direction/log-distance)。送 LLM = [semantic_token] ++ [40 temporal] = 41 token。
命名约定(ckpt 继承):binaural 前端 conv 用 `conv_downsample`(4→1) 以继承 finetuned.pth;
foa 前端 conv 用 `foa_conv`(7→1) 避开同名不同 shape 冲突(strict=False 仍会 raise size mismatch)。
"""
from dataclasses import dataclass
from functools import partial
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from .binaural_features import BinauralFeatureExtractor
from .foa_features import FOAFeatureExtractor
from .spatial_ast import PatchEmbed_new, conv3x3
from .vision_transformer import Block, VisionTransformer
@dataclass
class STEncoderOutput:
audio_tokens: torch.Tensor # [B,41,768]
semantic_logits: torch.Tensor # [B,355]
class75_logits: torch.Tensor # [B,75]
activity: torch.Tensor # [B,40] logit
direction: torch.Tensor # [B,40,3] 单位向量
log_distance: torch.Tensor # [B,40]
doa_vec: Optional[torch.Tensor] = None # [B,3] 单位向量;仅 foa 前端(静态定位头)有
dist: Optional[torch.Tensor] = None # [B,1] log 距离;仅 foa 前端有
class STAudioEncoder(VisionTransformer):
def __init__(self, audio_frontend="binaural", num_classes=355, embed_dim=768,
depth=12, num_heads=12, audio_bins=40, temporal_layers=2,
mlp_ratio=4, qkv_bias=True, drop_path_rate=0.1, patch_size=16,
norm_layer=partial(nn.LayerNorm, eps=1e-6)):
super().__init__(
num_classes=num_classes, drop_path_rate=drop_path_rate,
patch_size=patch_size, embed_dim=embed_dim, depth=depth,
num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias,
norm_layer=norm_layer,
)
if audio_frontend not in ("binaural", "foa"):
raise ValueError(f"audio_frontend must be 'binaural' or 'foa', got {audio_frontend!r}")
self.audio_frontend = audio_frontend
img_size = (1024, 128)
self.audio_bins = audio_bins
# 3 个静态全局 token:semantic / DoA / distance(继承 finetuned.pth cls_tokens(1,3,768))
del self.cls_token
self.num_cls_tokens = 3
self.cls_tokens = nn.Parameter(torch.zeros(1, 3, embed_dim))
self.patch_embed = PatchEmbed_new(
img_size=img_size, patch_size=(16, 16), in_chans=1,
embed_dim=embed_dim, stride=16,
)
num_patches = self.patch_embed.num_patches # 64*8 = 512
self.patch_hw = self.patch_embed.patch_hw # (64, 8)
self.pos_embed = nn.Parameter(
torch.zeros(1, num_patches + 1, embed_dim), requires_grad=False
)
# 前端 + 通道下采样 conv(命名决定能否继承 finetuned.pth)
if audio_frontend == "binaural":
self.in_chans = 2
self.binaural = BinauralFeatureExtractor()
self.conv_downsample = nn.Sequential(conv3x3(4, 1), nn.BatchNorm2d(1), nn.GELU())
self.doa_head = None # stage1/2 跳过:无静态定位头
self.dist_head = None
else: # foa
self.in_chans = 4
self.foa = FOAFeatureExtractor()
self.foa_conv = nn.Sequential(conv3x3(7, 1), nn.BatchNorm2d(1), nn.GELU())
self.doa_head = nn.Linear(embed_dim, 3)
self.dist_head = nn.Linear(embed_dim, 1)
# 语义头 self.head(355) 与 fc_norm 继承自基类/ckpt
self.fc_norm = norm_layer(embed_dim)
self.class75_head = nn.Linear(embed_dim, 75)
# 时序分支(stage3 新增,随机初始化)
dpr = [0.0] * temporal_layers
self.temporal_blocks = nn.ModuleList([
Block(dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio,
qkv_bias=qkv_bias, drop_path=dpr[i], norm_layer=norm_layer)
for i in range(temporal_layers)
])
self.act_head = nn.Linear(embed_dim, 1)
self.dir_head = nn.Linear(embed_dim, 3)
self.logdist_head = nn.Linear(embed_dim, 1)
del self.norm # 与原 Spatial-AST 一致:不在 backbone 末尾再 norm
def _frontend(self, waveforms):
if self.audio_frontend == "binaural":
return self.conv_downsample(self.binaural(waveforms)) # [B,1,1024,128]
return self.foa_conv(self.foa(waveforms)) # [B,1,1024,128]
def forward_backbone(self, waveforms):
if waveforms.dim() != 3 or waveforms.shape[1] != self.in_chans:
raise ValueError(
f"audio_frontend={self.audio_frontend!r} 需要 [B,{self.in_chans},T] 波形,"
f"收到 {tuple(waveforms.shape)}"
)
x = self._frontend(waveforms) # [B,1,1024,128]
x = self.patch_embed(x) # [B,512,768]
x = x + self.pos_embed[:, 1:, :]
cls = self.cls_tokens.expand(x.shape[0], -1, -1)
x = torch.cat([cls, x], dim=1) # [B,515,768]
x = self.pos_drop(x)
for blk in self.blocks:
x = blk(x)
return x # [B,515,768]
def forward(self, waveforms):
x = self.forward_backbone(waveforms)
B = x.shape[0]
sem_t, doa_t, dist_t = x[:, 0], x[:, 1], x[:, 2]
patches = x[:, 3:] # [B,512,768]
norm_sem = self.fc_norm(sem_t)
semantic_logits = self.head(norm_sem)
class75_logits = self.class75_head(norm_sem)
doa_vec = dist = None
if self.doa_head is not None: # 仅 foa 前端
doa_vec = F.normalize(self.doa_head(self.fc_norm(doa_t)), dim=-1)
dist = self.dist_head(self.fc_norm(dist_t))
# patch → [T'=64, F'=8] → 频率平均 → 插值 40 → 时序 self-attn
Tp, Fp = self.patch_hw
grid = patches.reshape(B, Tp, Fp, -1).mean(dim=2) # [B,64,768]
temporal = F.interpolate(
grid.transpose(1, 2), size=self.audio_bins,
mode="linear", align_corners=False,
).transpose(1, 2) # [B,40,768]
for blk in self.temporal_blocks:
temporal = blk(temporal)
activity = self.act_head(temporal).squeeze(-1) # [B,40]
direction = F.normalize(self.dir_head(temporal), dim=-1) # [B,40,3]
log_distance = self.logdist_head(temporal).squeeze(-1) # [B,40]
audio_tokens = torch.cat([sem_t.unsqueeze(1), temporal], dim=1) # [B,41,768]
return STEncoderOutput(
audio_tokens=audio_tokens,
semantic_logits=semantic_logits,
class75_logits=class75_logits,
activity=activity, direction=direction, log_distance=log_distance,
doa_vec=doa_vec, dist=dist,
)
|