PowerMachine commited on
Commit
5914924
·
verified ·
1 Parent(s): a6c45ef

Upload cnn_bigru/models/cooperative_bigru.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. cnn_bigru/models/cooperative_bigru.py +379 -0
cnn_bigru/models/cooperative_bigru.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """cooperative_bigru.py — Núcleo cooperativo CNN-BiGRU do projeto.
2
+
3
+ Implementa os 3 níveis de cooperação descritos em dados.txt:
4
+
5
+ NÍVEL 1 — Cooperação Global (Cross-Attention pós-CNN):
6
+ PonteGlobalCrossAttention com máscaras de padding.
7
+
8
+ NÍVEL 2 — Cooperação Passo a Passo (GRUCell com Porta Gated):
9
+ CellStepCooperativaComAtenuacao: calcula alfa (Sigmoid) que regula
10
+ o quanto uma rede aceita da outra, com máscara de padding.
11
+
12
+ NÍVEL 3 — Ponte de Fusão Final:
13
+ Concatena os estados forward+backward de cada rede (128 por rede = 256)
14
+ e projeta para a camada de classificação/decodificação.
15
+
16
+ Inclui:
17
+ - Inicialização ortogonal das matrizes recorrentes
18
+ - Normalização espectral opcional nos pesos lineares
19
+ - Self-attention no final de cada bloco (requisito do dados.txt)
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import logging
24
+ import math
25
+ from typing import Optional, Tuple
26
+
27
+ import torch
28
+ import torch.nn as nn
29
+ import torch.nn.functional as F
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+
34
+ def _orthogonal_init(layer: nn.Module) -> None:
35
+ """Aplica inicialização ortogonal nos pesos de uma camada Linear/GRUCell."""
36
+ for name, p in layer.named_parameters():
37
+ if "weight" in name and p.dim() >= 2:
38
+ try:
39
+ nn.init.orthogonal_(p)
40
+ except Exception:
41
+ nn.init.xavier_uniform_(p)
42
+ elif "bias" in name:
43
+ nn.init.zeros_(p)
44
+
45
+
46
+ # ============================================================================
47
+ # NÍVEL 1 — Cross-Attention Global com máscaras
48
+ # ============================================================================
49
+
50
+ class PonteGlobalCrossAttention(nn.Module):
51
+ """Atenção cruzada pós-CNN com máscara de padding.
52
+
53
+ A Rede A usa seus dados como Query para encontrar informações relevantes
54
+ nas Keys da Rede B, agregando os Values mais importantes.
55
+ """
56
+
57
+ def __init__(self, channels: int, n_heads: int = 4, dropout: float = 0.1):
58
+ super().__init__()
59
+ assert channels % n_heads == 0, f"channels ({channels}) deve ser divisível por n_heads ({n_heads})"
60
+ self.channels = channels
61
+ self.n_heads = n_heads
62
+ self.head_dim = channels // n_heads
63
+
64
+ self.query = nn.Linear(channels, channels)
65
+ self.key = nn.Linear(channels, channels)
66
+ self.value = nn.Linear(channels, channels)
67
+ self.out = nn.Linear(channels, channels)
68
+ self.dropout = nn.Dropout(dropout)
69
+
70
+ def forward(
71
+ self,
72
+ x_a: torch.Tensor,
73
+ x_b: torch.Tensor,
74
+ mask_b: Optional[torch.Tensor] = None,
75
+ ) -> torch.Tensor:
76
+ # x_a: [B, T_a, C], x_b: [B, T_b, C]
77
+ B, Ta, C = x_a.shape
78
+ Tb = x_b.size(1)
79
+
80
+ q = self.query(x_a).view(B, Ta, self.n_heads, self.head_dim).transpose(1, 2)
81
+ k = self.key(x_b).view(B, Tb, self.n_heads, self.head_dim).transpose(1, 2)
82
+ v = self.value(x_b).view(B, Tb, self.n_heads, self.head_dim).transpose(1, 2)
83
+
84
+ scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
85
+
86
+ if mask_b is not None:
87
+ # mask_b: [B, T_b] -> [B, 1, 1, T_b]
88
+ scores = scores.masked_fill(mask_b.unsqueeze(1).unsqueeze(1) == 0, -1e9)
89
+
90
+ attn = F.softmax(scores, dim=-1)
91
+ attn = self.dropout(attn)
92
+ ctx = torch.matmul(attn, v) # [B, n_heads, Ta, head_dim]
93
+ ctx = ctx.transpose(1, 2).contiguous().view(B, Ta, C)
94
+ return x_a + self.out(ctx)
95
+
96
+
97
+ # ============================================================================
98
+ # NÍVEL 2 — Célula Cooperativa Passo-a-Passo com Atenuação Gated
99
+ # ============================================================================
100
+
101
+ class CellStepCooperativaComAtenuacao(nn.Module):
102
+ """Célula GRU cooperativa com porta de atenuação (gated bridge).
103
+
104
+ Calcula alfa = Sigmoid(linear(concat(x_t, h_partner))) em [0, 1]:
105
+ - Se alfa -> 0, a ponte desativa (isolamento dos fluxos)
106
+ - Se alfa -> 1, a ponte transfere totalmente o contexto
107
+
108
+ Tratamento de padding: se mask_t == 0, mantém o h anterior intacto.
109
+ """
110
+
111
+ def __init__(self, input_size: int, hidden_size: int):
112
+ super().__init__()
113
+ self.cell_A = nn.GRUCell(input_size, hidden_size)
114
+ self.cell_B = nn.GRUCell(input_size, hidden_size)
115
+ _orthogonal_init(self.cell_A)
116
+ _orthogonal_init(self.cell_B)
117
+
118
+ # Pontes lineares
119
+ self.ponte_B_para_A = nn.Linear(hidden_size, input_size)
120
+ self.ponte_A_para_B = nn.Linear(hidden_size, input_size)
121
+
122
+ # Porta de atenuação (gated)
123
+ self.porta_atenuacao_A = nn.Linear(input_size + hidden_size, 1)
124
+ self.porta_atenuacao_B = nn.Linear(input_size + hidden_size, 1)
125
+
126
+ def forward(
127
+ self,
128
+ x_t_A: torch.Tensor,
129
+ x_t_B: torch.Tensor,
130
+ h_prev_A: torch.Tensor,
131
+ h_prev_B: torch.Tensor,
132
+ mask_t_A: torch.Tensor,
133
+ mask_t_B: torch.Tensor,
134
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
135
+ # mask_t: [B, 1]
136
+
137
+ # 1. Fator de atenuação (Sigmoid -> [0, 1])
138
+ alfa_A = torch.sigmoid(self.porta_atenuacao_A(torch.cat((x_t_A, h_prev_B), dim=-1)))
139
+ alfa_B = torch.sigmoid(self.porta_atenuacao_B(torch.cat((x_t_B, h_prev_A), dim=-1)))
140
+
141
+ # 2. Injeção de contexto com atenuação + máscara
142
+ influencia_B = torch.tanh(self.ponte_B_para_A(h_prev_B)) * alfa_A * mask_t_B
143
+ influencia_A = torch.tanh(self.ponte_A_para_B(h_prev_A)) * alfa_B * mask_t_A
144
+
145
+ x_t_A_coop = x_t_A + influencia_B
146
+ x_t_B_coop = x_t_B + influencia_A
147
+
148
+ # 3. Atualização GRU
149
+ h_next_A_bruto = self.cell_A(x_t_A_coop, h_prev_A)
150
+ h_next_B_bruto = self.cell_B(x_t_B_coop, h_prev_B)
151
+
152
+ # 4. Preserva h anterior onde a sequência acabou (mask=0)
153
+ h_next_A = torch.where(mask_t_A == 1, h_next_A_bruto, h_prev_A)
154
+ h_next_B = torch.where(mask_t_B == 1, h_next_B_bruto, h_prev_B)
155
+
156
+ return h_next_A, h_next_B
157
+
158
+
159
+ # ============================================================================
160
+ # Self-Attention (requisito do dados.txt: sumariza passos temporais)
161
+ # ============================================================================
162
+
163
+ class SelfAttentionSummary(nn.Module):
164
+ """Self-attention que resume os passos temporais antes da classificação.
165
+
166
+ Recebe a sequência de outputs da BiGRU [B, T, H] e produz um único vetor
167
+ [B, H] ponderado por atenção aprendida.
168
+ """
169
+
170
+ def __init__(self, hidden_dim: int, dropout: float = 0.1):
171
+ super().__init__()
172
+ self.query = nn.Linear(hidden_dim, hidden_dim)
173
+ self.key = nn.Linear(hidden_dim, hidden_dim)
174
+ self.value = nn.Linear(hidden_dim, hidden_dim)
175
+ self.dropout = nn.Dropout(dropout)
176
+
177
+ def forward(
178
+ self,
179
+ x: torch.Tensor,
180
+ mask: Optional[torch.Tensor] = None,
181
+ ) -> torch.Tensor:
182
+ # x: [B, T, H]
183
+ # Usa o primeiro token como query (ou um pooling da sequência)
184
+ q = self.query(x.mean(dim=1, keepdim=True)) # [B, 1, H]
185
+ k = self.key(x) # [B, T, H]
186
+ v = self.value(x)
187
+
188
+ scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(x.size(-1)) # [B, 1, T]
189
+ if mask is not None:
190
+ scores = scores.masked_fill(mask.unsqueeze(1) == 0, -1e9)
191
+ attn = F.softmax(scores, dim=-1)
192
+ attn = self.dropout(attn)
193
+ ctx = torch.matmul(attn, v) # [B, 1, H]
194
+ return ctx.squeeze(1) # [B, H]
195
+
196
+
197
+ # ============================================================================
198
+ # Núcleo Cooperativo CNN-BiGRU
199
+ # ============================================================================
200
+
201
+ class CooperativeCNNBiGRU(nn.Module):
202
+ """Núcleo cooperativo CNN-BiGRU (dual-stream) com 3 níveis de ponte.
203
+
204
+ Args:
205
+ vocab_size: tamanho do vocabulário.
206
+ embedding_dim: dimensão do embedding de tokens.
207
+ cnn_filters: número de filtros da Conv1d.
208
+ gru_hidden: dimensão oculta de cada direção da GRU.
209
+ n_heads: número de cabeças para cross-attention.
210
+ dropout: probabilidade de dropout.
211
+ pad_idx: índice do token de padding.
212
+ use_spectral_norm: se True, aplica normalização espectral nas lineares.
213
+ """
214
+
215
+ def __init__(
216
+ self,
217
+ vocab_size: int,
218
+ embedding_dim: int = 64,
219
+ cnn_filters: int = 64,
220
+ gru_hidden: int = 64,
221
+ n_heads: int = 4,
222
+ dropout: float = 0.1,
223
+ pad_idx: int = 1,
224
+ use_spectral_norm: bool = False,
225
+ ):
226
+ super().__init__()
227
+ self.pad_idx = pad_idx
228
+ self.cnn_filters = cnn_filters
229
+ self.gru_hidden = gru_hidden
230
+
231
+ self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=pad_idx)
232
+ nn.init.orthogonal_(self.embedding.weight)
233
+
234
+ # CNN extractors (cada stream tem o seu)
235
+ self.conv_A = nn.Conv1d(embedding_dim, cnn_filters, kernel_size=3, padding=1)
236
+ self.conv_B = nn.Conv1d(embedding_dim, cnn_filters, kernel_size=3, padding=1)
237
+
238
+ # Nível 1: Pontes globais (cross-attention)
239
+ self.ponte_global_A = PonteGlobalCrossAttention(cnn_filters, n_heads=n_heads, dropout=dropout)
240
+ self.ponte_global_B = PonteGlobalCrossAttention(cnn_filters, n_heads=n_heads, dropout=dropout)
241
+
242
+ # Nível 2: Células cooperativas passo-a-passo
243
+ self.gru_coop_direto = CellStepCooperativaComAtenuacao(cnn_filters, gru_hidden)
244
+ self.gru_coop_inverso = CellStepCooperativaComAtenuacao(cnn_filters, gru_hidden)
245
+
246
+ # Self-attention para sumarização temporal (requisito do dados.txt)
247
+ self.self_attn_A = SelfAttentionSummary(gru_hidden * 2, dropout=dropout)
248
+ self.self_attn_B = SelfAttentionSummary(gru_hidden * 2, dropout=dropout)
249
+
250
+ # Camadas de saída (sem classificador aqui — o classificador fica no modelo multimodal)
251
+ self.dropout = nn.Dropout(dropout)
252
+ self.feat_dim = gru_hidden * 2 # 128 por stream (forward + backward concat)
253
+
254
+ # Spectral norm opcional
255
+ if use_spectral_norm:
256
+ self.conv_A = nn.utils.spectral_norm(self.conv_A)
257
+ self.conv_B = nn.utils.spectral_norm(self.conv_B)
258
+ self.ponte_global_A.query = nn.utils.spectral_norm(self.ponte_global_A.query)
259
+ self.ponte_global_A.key = nn.utils.spectral_norm(self.ponte_global_A.key)
260
+ self.ponte_global_A.value = nn.utils.spectral_norm(self.ponte_global_A.value)
261
+ self.ponte_global_B.query = nn.utils.spectral_norm(self.ponte_global_B.query)
262
+ self.ponte_global_B.key = nn.utils.spectral_norm(self.ponte_global_B.key)
263
+ self.ponte_global_B.value = nn.utils.spectral_norm(self.ponte_global_B.value)
264
+
265
+ def forward(
266
+ self,
267
+ input_A: torch.Tensor,
268
+ input_B: torch.Tensor,
269
+ return_sequences: bool = False,
270
+ ) -> dict:
271
+ """
272
+ Args:
273
+ input_A: [B, T_a] tokens do stream A
274
+ input_B: [B, T_b] tokens do stream B
275
+ return_sequences: se True, retorna também as saídas temporais das BiGRUs
276
+
277
+ Returns:
278
+ dict com:
279
+ out_A: [B, 128] representação final do stream A
280
+ out_B: [B, 128] representação final do stream B
281
+ fused: [B, 256] concatenação (out_A || out_B)
282
+ (opcional) seq_A: [B, T, 128] saídas temporais do stream A
283
+ (opcional) seq_B: [B, T, 128] saídas temporais do stream B
284
+ """
285
+ batch_size = input_A.size(0)
286
+ seq_len_A = input_A.size(1)
287
+ seq_len_B = input_B.size(1)
288
+ device = input_A.device
289
+
290
+ # Máscaras de padding
291
+ mask_A = (input_A != self.pad_idx).float()
292
+ mask_B = (input_B != self.pad_idx).float()
293
+
294
+ # 1. Embeddings + CNN
295
+ emb_A = self.embedding(input_A).permute(0, 2, 1) # [B, D, T_a]
296
+ emb_B = self.embedding(input_B).permute(0, 2, 1) # [B, D, T_b]
297
+
298
+ feat_A = F.relu(self.conv_A(emb_A)).permute(0, 2, 1) * mask_A.unsqueeze(-1)
299
+ feat_B = F.relu(self.conv_B(emb_B)).permute(0, 2, 1) * mask_B.unsqueeze(-1)
300
+
301
+ # 2. NÍVEL 1: Pontes globais (cross-attention)
302
+ feat_A_coop = self.ponte_global_A(feat_A, feat_B, mask_B) * mask_A.unsqueeze(-1)
303
+ feat_B_coop = self.ponte_global_B(feat_B, feat_A, mask_A) * mask_B.unsqueeze(-1)
304
+
305
+ # 3. Estados ocultos iniciais
306
+ h_dir_A = torch.zeros(batch_size, self.gru_hidden, device=device)
307
+ h_dir_B = torch.zeros(batch_size, self.gru_hidden, device=device)
308
+ h_inv_A = torch.zeros(batch_size, self.gru_hidden, device=device)
309
+ h_inv_B = torch.zeros(batch_size, self.gru_hidden, device=device)
310
+
311
+ max_steps = max(seq_len_A, seq_len_B)
312
+ seq_dir_A, seq_dir_B = [], []
313
+ seq_inv_A, seq_inv_B = [], []
314
+
315
+ # 4. NÍVEL 2: Laço direto
316
+ for t in range(max_steps):
317
+ x_t_A = feat_A_coop[:, t, :] if t < seq_len_A else torch.zeros(batch_size, self.cnn_filters, device=device)
318
+ x_t_B = feat_B_coop[:, t, :] if t < seq_len_B else torch.zeros(batch_size, self.cnn_filters, device=device)
319
+
320
+ m_t_A = mask_A[:, t].unsqueeze(-1) if t < seq_len_A else torch.zeros(batch_size, 1, device=device)
321
+ m_t_B = mask_B[:, t].unsqueeze(-1) if t < seq_len_B else torch.zeros(batch_size, 1, device=device)
322
+
323
+ h_dir_A, h_dir_B = self.gru_coop_direto(x_t_A, x_t_B, h_dir_A, h_dir_B, m_t_A, m_t_B)
324
+ if return_sequences:
325
+ seq_dir_A.append(h_dir_A)
326
+ seq_dir_B.append(h_dir_B)
327
+
328
+ # 5. Laço inverso
329
+ for t in reversed(range(max_steps)):
330
+ x_t_A = feat_A_coop[:, t, :] if t < seq_len_A else torch.zeros(batch_size, self.cnn_filters, device=device)
331
+ x_t_B = feat_B_coop[:, t, :] if t < seq_len_B else torch.zeros(batch_size, self.cnn_filters, device=device)
332
+
333
+ m_t_A = mask_A[:, t].unsqueeze(-1) if t < seq_len_A else torch.zeros(batch_size, 1, device=device)
334
+ m_t_B = mask_B[:, t].unsqueeze(-1) if t < seq_len_B else torch.zeros(batch_size, 1, device=device)
335
+
336
+ h_inv_A, h_inv_B = self.gru_coop_inverso(x_t_A, x_t_B, h_inv_A, h_inv_B, m_t_A, m_t_B)
337
+ if return_sequences:
338
+ seq_inv_A.append(h_inv_A)
339
+ seq_inv_B.append(h_inv_B)
340
+
341
+ # 6. Concatenação forward+backward (128 por stream)
342
+ out_A = torch.cat((h_dir_A, h_inv_A), dim=1) # [B, 128]
343
+ out_B = torch.cat((h_dir_B, h_inv_B), dim=1) # [B, 128]
344
+
345
+ # 7. NÍVEL 3: Fusão final
346
+ fused = torch.cat((out_A, out_B), dim=1) # [B, 256]
347
+
348
+ result = {
349
+ "out_A": out_A,
350
+ "out_B": out_B,
351
+ "fused": fused,
352
+ "mask_A": mask_A,
353
+ "mask_B": mask_B,
354
+ }
355
+
356
+ if return_sequences:
357
+ # Reconstrói sequência temporal [B, T, 128] somando direto + inverso
358
+ # Para cada t, h_dir e h_inv são estados — aqui retornamos a concatenação
359
+ seq_A = []
360
+ seq_B = []
361
+ for i in range(max_steps):
362
+ a_dir = seq_dir_A[i]
363
+ a_inv = seq_inv_A[max_steps - 1 - i]
364
+ seq_A.append(torch.cat((a_dir, a_inv), dim=1))
365
+ b_dir = seq_dir_B[i]
366
+ b_inv = seq_inv_B[max_steps - 1 - i]
367
+ seq_B.append(torch.cat((b_dir, b_inv), dim=1))
368
+ result["seq_A"] = torch.stack(seq_A, dim=1)
369
+ result["seq_B"] = torch.stack(seq_B, dim=1)
370
+
371
+ return result
372
+
373
+
374
+ __all__ = [
375
+ "PonteGlobalCrossAttention",
376
+ "CellStepCooperativaComAtenuacao",
377
+ "SelfAttentionSummary",
378
+ "CooperativeCNNBiGRU",
379
+ ]