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 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
| import torch import torch.nn as nn import torch.nn.functional as F
class RAFMSerPlusPlus(nn.Module): """ RAFM_SER++: 轻量多模态语音情绪识别 架构: 1. 语音分支: HuBERT-Base (冻结) + 适配层 2. 文本分支: BERT (冻结) + 适配层 3. RAFM: 非对称残差注意力融合 (语音 → 文本 单向注入) 4. BYOL 对齐: 跨模态表示对齐 5. 注意力引导池化 6. 分类头 """ def __init__(self, speech_dim=768, text_dim=768, hidden_dim=256, num_classes=4): super().__init__() self.speech_adapter = nn.Sequential( nn.Linear(speech_dim, hidden_dim), nn.LayerNorm(hidden_dim), nn.GELU() ) self.text_adapter = nn.Sequential( nn.Linear(text_dim, hidden_dim), nn.LayerNorm(hidden_dim), nn.GELU() ) self.rafm = AsymmetricResidualAttentionFusion( dim=hidden_dim, num_heads=4 ) self.attn_pool = AttentionPooling(hidden_dim) self.classifier = nn.Sequential( nn.Dropout(0.2), nn.Linear(hidden_dim, num_classes) ) def forward(self, speech_feat, text_feat): """ Args: speech_feat: (B, L_s, 768) HuBERT 输出 text_feat: (B, L_t, 768) BERT 输出 Returns: logits: (B, num_classes) """ speech = self.speech_adapter(speech_feat) text = self.text_adapter(text_feat) fused = self.rafm(speech, text) pooled = self.attn_pool(fused) logits = self.classifier(pooled) return logits
class AsymmetricResidualAttentionFusion(nn.Module): """ RAFM: 非对称残差注意力融合 核心思想: 语音情感线索单向注入文本语义表示 - 不用双向交互 (太贵) - 语音特征做 Query, 文本特征做 K/V - 残差连接保持文本表示 """ def __init__(self, dim=256, num_heads=4): super().__init__() self.cross_attn = nn.MultiheadAttention( dim, num_heads, batch_first=True, dropout=0.1 ) self.norm1 = nn.LayerNorm(dim) self.norm2 = nn.LayerNorm(dim) self.ffn = nn.Sequential( nn.Linear(dim, dim * 2), nn.GELU(), nn.Dropout(0.1), nn.Linear(dim * 2, dim) ) def forward(self, speech, text): """ Args: speech: (B, L_s, D) 语音特征 text: (B, L_t, D) 文本特征 Returns: fused: (B, L_t, D) 语音增强的文本特征 """ normed_q = self.norm1(speech) normed_kv = self.norm1(text) attn_out, _ = self.cross_attn( normed_q, normed_kv, normed_kv ) fused = text + attn_out[:, :text.shape[1], :] fused = fused + self.ffn(self.norm2(fused)) return fused
class AttentionPooling(nn.Module): """注意力引导池化""" def __init__(self, dim=256): super().__init__() self.attn = nn.Linear(dim, 1) def forward(self, x): """ Args: x: (B, L, D) Returns: pooled: (B, D) """ weights = F.softmax(self.attn(x), dim=1) pooled = (x * weights).sum(dim=1) return pooled
class BYOLAlignment(nn.Module): """ BYOL 跨模态对齐 将语音和文本表示拉到同一空间 无需负样本 (vs SimCLR) """ def __init__(self, dim=256, projection_dim=128): super().__init__() self.speech_proj = nn.Sequential( nn.Linear(dim, dim), nn.GELU(), nn.Linear(dim, projection_dim) ) self.text_proj = nn.Sequential( nn.Linear(dim, dim), nn.GELU(), nn.Linear(dim, projection_dim) ) def forward(self, speech_repr, text_repr): s = self.speech_proj(speech_repr) t = self.text_proj(text_repr) loss = 2 - 2 * F.cosine_similarity( s, t.detach(), dim=-1 ).mean() return loss
if __name__ == "__main__": model = RAFMSerPlusPlus(num_classes=4) speech = torch.randn(2, 100, 768) text = torch.randn(2, 32, 768) logits = model(speech, text) print(f"Speech: {speech.shape}") print(f"Text: {text.shape}") print(f"Logits: {logits.shape}") print(f"Params: {sum(p.numel() for p in model.parameters()):,}") import time model.eval() with torch.no_grad(): start = time.time() for _ in range(100): _ = model(speech, text) elapsed = time.time() - start print(f"Speed: {100/elapsed:.1f} it/s")
|