PowerMachine commited on
Commit
89fb828
·
verified ·
1 Parent(s): ee2e50a

Upload cnn_bigru/models/multimodal_encoders.py with huggingface_hub

Browse files
cnn_bigru/models/multimodal_encoders.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """multimodal_encoders.py — Encoders para imagem e áudio.
2
+
3
+ Para o projeto CNN-BiGRU multimodal, precisamos de encoders que produzam
4
+ sequências de features compatíveis com o núcleo cooperativo CNN-BiGRU.
5
+
6
+ - ImageEncoder: CNN 2D -> flatten espacial -> projeção linear -> [B, T_img, C]
7
+ - AudioEncoder: CNN 1D sobre espectrograma -> [B, T_aud, C]
8
+
9
+ A fusão multimodal acontece trocando o stream B do núcleo cooperativo pela
10
+ saída do encoder visual/áudio, ou adicionando-os como streams extras numa
11
+ versão estendida. Aqui usamos uma fusão por concatenação + projeção.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+ from typing import Optional
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ class ImageEncoder(nn.Module):
26
+ """CNN 2D simples que codifica imagem em sequência de features.
27
+
28
+ Input: [B, C, H, W]
29
+ Output: [B, T_img, out_dim] onde T_img = (H/4) * (W/4)
30
+
31
+ Usa 2 blocos Conv2d+ReLU+MaxPool para reduzir dimensão espacial por 4.
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ in_channels: int = 1,
37
+ out_dim: int = 64,
38
+ hidden_dim: int = 32,
39
+ ):
40
+ super().__init__()
41
+ self.conv1 = nn.Conv2d(in_channels, hidden_dim, kernel_size=3, padding=1)
42
+ self.conv2 = nn.Conv2d(hidden_dim, hidden_dim * 2, kernel_size=3, padding=1)
43
+ self.pool = nn.MaxPool2d(2)
44
+ self.proj = nn.Linear(hidden_dim * 2, out_dim)
45
+ self.out_dim = out_dim
46
+
47
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
48
+ # x: [B, C, H, W]
49
+ x = F.relu(self.conv1(x))
50
+ x = self.pool(x) # [B, C', H/2, W/2]
51
+ x = F.relu(self.conv2(x))
52
+ x = self.pool(x) # [B, C'', H/4, W/4]
53
+ B, C, H, W = x.shape
54
+ x = x.permute(0, 2, 3, 1).contiguous().view(B, H * W, C) # [B, T, C]
55
+ x = self.proj(x) # [B, T, out_dim]
56
+ return x
57
+
58
+
59
+ class AudioEncoder(nn.Module):
60
+ """Encoder de áudio: CNN 1D sobre espectrograma (T freq bins como canais).
61
+
62
+ Input: [B, 1, T_time, F_freq]
63
+ Output: [B, T_time, out_dim]
64
+
65
+ Trata a dimensão de frequência como canais e processa a dimensão temporal
66
+ com Conv1d, produzindo uma sequência compatível com BiGRU.
67
+ """
68
+
69
+ def __init__(
70
+ self,
71
+ n_freq: int = 40,
72
+ out_dim: int = 64,
73
+ hidden_dim: int = 32,
74
+ ):
75
+ super().__init__()
76
+ self.conv1 = nn.Conv1d(n_freq, hidden_dim, kernel_size=3, padding=1)
77
+ self.conv2 = nn.Conv1d(hidden_dim, hidden_dim * 2, kernel_size=3, padding=1)
78
+ self.proj = nn.Linear(hidden_dim * 2, out_dim)
79
+ self.out_dim = out_dim
80
+
81
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
82
+ # x: [B, 1, T, F] -> queremos [B, F, T] para Conv1d
83
+ B, _, T, F_ = x.shape
84
+ x = x.view(B, F_, T) # [B, F, T]
85
+ x = F.relu(self.conv1(x)) # [B, hidden, T]
86
+ x = F.relu(self.conv2(x)) # [B, hidden*2, T]
87
+ x = x.permute(0, 2, 1) # [B, T, hidden*2]
88
+ x = self.proj(x) # [B, T, out_dim]
89
+ return x
90
+
91
+
92
+ class MultimodalFusion(nn.Module):
93
+ """Fusão de features de texto, imagem e áudio.
94
+
95
+ Recebe três tensores [B, D_text], [B, D_img], [B, D_aud] e produz
96
+ um único tensor [B, out_dim] usando concatenação + projeção +
97
+ uma porta de fusão (gated) que aprende a importância de cada modalidade.
98
+ """
99
+
100
+ def __init__(
101
+ self,
102
+ d_text: int,
103
+ d_img: int,
104
+ d_aud: int,
105
+ out_dim: int = 128,
106
+ dropout: float = 0.1,
107
+ ):
108
+ super().__init__()
109
+ d_concat = d_text + d_img + d_aud
110
+ self.proj = nn.Linear(d_concat, out_dim)
111
+ # Porta de fusão: aprende pesos por modalidade
112
+ self.gate_text = nn.Linear(d_text, 1)
113
+ self.gate_img = nn.Linear(d_img, 1)
114
+ self.gate_aud = nn.Linear(d_aud, 1)
115
+ self.dropout = nn.Dropout(dropout)
116
+ self.out_dim = out_dim
117
+
118
+ def forward(
119
+ self,
120
+ text_feat: torch.Tensor,
121
+ img_feat: torch.Tensor,
122
+ aud_feat: torch.Tensor,
123
+ ) -> torch.Tensor:
124
+ # Gates (Sigmoid -> [0, 1])
125
+ g_t = torch.sigmoid(self.gate_text(text_feat)) # [B, 1]
126
+ g_i = torch.sigmoid(self.gate_img(img_feat))
127
+ g_a = torch.sigmoid(self.gate_aud(aud_feat))
128
+
129
+ # Aplica gates como máscara suave
130
+ text_g = text_feat * g_t
131
+ img_g = img_feat * g_i
132
+ aud_g = aud_feat * g_a
133
+
134
+ # Concatena e projeta
135
+ concat = torch.cat((text_g, img_g, aud_g), dim=-1)
136
+ out = self.proj(concat)
137
+ out = self.dropout(out)
138
+ return out
139
+
140
+
141
+ __all__ = ["ImageEncoder", "AudioEncoder", "MultimodalFusion"]