PowerMachine commited on
Commit
ae39b5f
·
verified ·
1 Parent(s): 268754b

Delete models/cooperative_bigru.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. models/cooperative_bigru.py +0 -519
models/cooperative_bigru.py DELETED
@@ -1,519 +0,0 @@
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
-
37
- Em caso de falha (e.g., matriz não-quadrada com fan_in < fan_out), registra
38
- warning e faz fallback para xavier_uniform_ (não silencioso).
39
- """
40
- for name, p in layer.named_parameters():
41
- if "weight" in name and p.dim() >= 2:
42
- try:
43
- nn.init.orthogonal_(p)
44
- except Exception as e:
45
- logger.warning(
46
- f"_orthogonal_init: falhou em {name} (shape={tuple(p.shape)}): {e}. "
47
- f"Usando xavier_uniform_ como fallback."
48
- )
49
- nn.init.xavier_uniform_(p)
50
- elif "bias" in name:
51
- nn.init.zeros_(p)
52
-
53
-
54
- # ============================================================================
55
- # NÍVEL 1 — Cross-Attention Global com máscaras
56
- # ============================================================================
57
-
58
- class PonteGlobalCrossAttention(nn.Module):
59
- """Atenção cruzada pós-CNN com máscara de padding.
60
-
61
- A Rede A usa seus dados como Query para encontrar informações relevantes
62
- nas Keys da Rede B, agregando os Values mais importantes.
63
- """
64
-
65
- def __init__(self, channels: int, n_heads: int = 4, dropout: float = 0.1):
66
- super().__init__()
67
- assert channels % n_heads == 0, f"channels ({channels}) deve ser divisível por n_heads ({n_heads})"
68
- self.channels = channels
69
- self.n_heads = n_heads
70
- self.head_dim = channels // n_heads
71
-
72
- self.query = nn.Linear(channels, channels)
73
- self.key = nn.Linear(channels, channels)
74
- self.value = nn.Linear(channels, channels)
75
- self.out = nn.Linear(channels, channels)
76
- self.dropout = nn.Dropout(dropout)
77
-
78
- def forward(
79
- self,
80
- x_a: torch.Tensor,
81
- x_b: torch.Tensor,
82
- mask_b: Optional[torch.Tensor] = None,
83
- ) -> torch.Tensor:
84
- # x_a: [B, T_a, C], x_b: [B, T_b, C]
85
- B, Ta, C = x_a.shape
86
- Tb = x_b.size(1)
87
-
88
- q = self.query(x_a).view(B, Ta, self.n_heads, self.head_dim).transpose(1, 2)
89
- k = self.key(x_b).view(B, Tb, self.n_heads, self.head_dim).transpose(1, 2)
90
- v = self.value(x_b).view(B, Tb, self.n_heads, self.head_dim).transpose(1, 2)
91
-
92
- scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
93
-
94
- if mask_b is not None:
95
- # mask_b: [B, T_b] -> [B, 1, 1, T_b]
96
- scores = scores.masked_fill(mask_b.unsqueeze(1).unsqueeze(1) == 0, -1e9)
97
-
98
- attn = F.softmax(scores, dim=-1)
99
- attn = self.dropout(attn)
100
- ctx = torch.matmul(attn, v) # [B, n_heads, Ta, head_dim]
101
- ctx = ctx.transpose(1, 2).contiguous().view(B, Ta, C)
102
- return x_a + self.out(ctx)
103
-
104
-
105
- # ============================================================================
106
- # NÍVEL 2 — Célula Cooperativa Passo-a-Passo com Atenuação Gated
107
- # ============================================================================
108
-
109
- class CellStepCooperativaComAtenuacao(nn.Module):
110
- """Célula GRU cooperativa com porta de atenuação (gated bridge).
111
-
112
- Calcula alfa = Sigmoid(linear(concat(x_t, h_partner))) em [0, 1]:
113
- - Se alfa -> 0, a ponte desativa (isolamento dos fluxos)
114
- - Se alfa -> 1, a ponte transfere totalmente o contexto
115
-
116
- Tratamento de padding: se mask_t == 0, mantém o h anterior intacto.
117
- """
118
-
119
- def __init__(self, input_size: int, hidden_size: int):
120
- super().__init__()
121
- self.cell_A = nn.GRUCell(input_size, hidden_size)
122
- self.cell_B = nn.GRUCell(input_size, hidden_size)
123
- _orthogonal_init(self.cell_A)
124
- _orthogonal_init(self.cell_B)
125
-
126
- # Pontes lineares
127
- self.ponte_B_para_A = nn.Linear(hidden_size, input_size)
128
- self.ponte_A_para_B = nn.Linear(hidden_size, input_size)
129
-
130
- # Porta de atenuação (gated)
131
- self.porta_atenuacao_A = nn.Linear(input_size + hidden_size, 1)
132
- self.porta_atenuacao_B = nn.Linear(input_size + hidden_size, 1)
133
-
134
- def forward(
135
- self,
136
- x_t_A: torch.Tensor,
137
- x_t_B: torch.Tensor,
138
- h_prev_A: torch.Tensor,
139
- h_prev_B: torch.Tensor,
140
- mask_t_A: torch.Tensor,
141
- mask_t_B: torch.Tensor,
142
- ) -> Tuple[torch.Tensor, torch.Tensor]:
143
- # mask_t: [B, 1]
144
-
145
- # 1. Fator de atenuação (Sigmoid -> [0, 1])
146
- alfa_A = torch.sigmoid(self.porta_atenuacao_A(torch.cat((x_t_A, h_prev_B), dim=-1)))
147
- alfa_B = torch.sigmoid(self.porta_atenuacao_B(torch.cat((x_t_B, h_prev_A), dim=-1)))
148
-
149
- # 2. Injeção de contexto com atenuação + máscara
150
- influencia_B = torch.tanh(self.ponte_B_para_A(h_prev_B)) * alfa_A * mask_t_B
151
- influencia_A = torch.tanh(self.ponte_A_para_B(h_prev_A)) * alfa_B * mask_t_A
152
-
153
- x_t_A_coop = x_t_A + influencia_B
154
- x_t_B_coop = x_t_B + influencia_A
155
-
156
- # 3. Atualização GRU
157
- h_next_A_bruto = self.cell_A(x_t_A_coop, h_prev_A)
158
- h_next_B_bruto = self.cell_B(x_t_B_coop, h_prev_B)
159
-
160
- # 4. Preserva h anterior onde a sequência acabou (mask=0)
161
- h_next_A = torch.where(mask_t_A == 1, h_next_A_bruto, h_prev_A)
162
- h_next_B = torch.where(mask_t_B == 1, h_next_B_bruto, h_prev_B)
163
-
164
- return h_next_A, h_next_B
165
-
166
-
167
- # ============================================================================
168
- # Self-Attention Final Layer (requisito do dados.txt linha 470)
169
- # ============================================================================
170
-
171
- class SelfAttentionSummary(nn.Module):
172
- """Self-attention final layer que resume os passos temporais antes da classificação.
173
-
174
- Implementa uma self-attention TRUE (não usa mean como query, conforme
175
- requisito do dados.txt linha 470 "Self-Attention no final de cada bloco"):
176
- - Query, Key, Value são todas projeções lineares aprendidas de x
177
- - Multi-head com n_heads cabeças
178
- - Máscara de padding (ignora tokens [PAD])
179
- - Causal opcional (não usado em sumarização, mas disponível)
180
- - Residual + LayerNorm para estabilidade
181
-
182
- Saída: [B, hidden_dim] — vetor agregado que resume toda a sequência.
183
-
184
- Args:
185
- hidden_dim: dimensão de entrada/saída
186
- n_heads: número de cabeças (deve dividir hidden_dim)
187
- dropout: probabilidade de dropout
188
- use_residual: se True, soma residual com entrada (via LayerNorm)
189
- aggregation: "mean" (média dos heads após attn) ou "first" (primeiro token)
190
- """
191
-
192
- def __init__(
193
- self,
194
- hidden_dim: int,
195
- n_heads: int = 4,
196
- dropout: float = 0.1,
197
- use_residual: bool = True,
198
- aggregation: str = "mean",
199
- ):
200
- super().__init__()
201
- if hidden_dim % n_heads != 0:
202
- raise ValueError(
203
- f"hidden_dim ({hidden_dim}) deve ser divisível por n_heads ({n_heads})"
204
- )
205
- self.hidden_dim = hidden_dim
206
- self.n_heads = n_heads
207
- self.head_dim = hidden_dim // n_heads
208
- self.use_residual = use_residual
209
- self.aggregation = aggregation
210
-
211
- # Projeções lineares aprendidas (TRUE self-attention, não mean-pool)
212
- self.q_proj = nn.Linear(hidden_dim, hidden_dim)
213
- self.k_proj = nn.Linear(hidden_dim, hidden_dim)
214
- self.v_proj = nn.Linear(hidden_dim, hidden_dim)
215
- self.out_proj = nn.Linear(hidden_dim, hidden_dim)
216
- self.dropout = nn.Dropout(dropout)
217
-
218
- if use_residual:
219
- self.ln = nn.LayerNorm(hidden_dim)
220
-
221
- # Token especial de "sumarização" aprendido (CLS-like)
222
- # Adicionado no início da sequência para servir como query global
223
- self.cls_token = nn.Parameter(torch.zeros(1, 1, hidden_dim))
224
- nn.init.normal_(self.cls_token, std=0.02)
225
-
226
- def forward(
227
- self,
228
- x: torch.Tensor,
229
- mask: Optional[torch.Tensor] = None,
230
- ) -> torch.Tensor:
231
- """
232
- Args:
233
- x: [B, T, H] — sequência de saídas da BiGRU
234
- mask: [B, T] — 1 para token real, 0 para PAD (None = todos válidos)
235
-
236
- Returns:
237
- summary: [B, H] — vetor sumarizado
238
- """
239
- B, T, H = x.shape
240
-
241
- # Prepend CLS token: [B, 1, H] + [B, T, H] -> [B, T+1, H]
242
- cls = self.cls_token.expand(B, -1, -1)
243
- x_ext = torch.cat([cls, x], dim=1)
244
- T_ext = T + 1
245
-
246
- # Estender máscara para o CLS (sempre ativo)
247
- if mask is not None:
248
- cls_mask = torch.ones(B, 1, device=x.device, dtype=mask.dtype)
249
- mask_ext = torch.cat([cls_mask, mask], dim=1) # [B, T+1]
250
- else:
251
- mask_ext = None
252
-
253
- # Projeções Q, K, V (todas aprendidas — true self-attention)
254
- q = self.q_proj(x_ext) # [B, T+1, H]
255
- k = self.k_proj(x_ext)
256
- v = self.v_proj(x_ext)
257
-
258
- # Reshape para multi-head: [B, n_heads, T+1, head_dim]
259
- q = q.view(B, T_ext, self.n_heads, self.head_dim).transpose(1, 2)
260
- k = k.view(B, T_ext, self.n_heads, self.head_dim).transpose(1, 2)
261
- v = v.view(B, T_ext, self.n_heads, self.head_dim).transpose(1, 2)
262
-
263
- # Scaled dot-product attention (sem máscara causal — é encoder-style)
264
- scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
265
- # scores: [B, n_heads, T+1, T+1]
266
-
267
- if mask_ext is not None:
268
- # Aplicar máscara nas chaves: tokens PAD devem receber atenção zero
269
- # mask_ext: [B, T+1] -> [B, 1, 1, T+1]
270
- scores = scores.masked_fill(
271
- mask_ext.unsqueeze(1).unsqueeze(1) == 0, -1e9
272
- )
273
-
274
- # Lidar com linhas totalmente mascaradas (evitar NaN)
275
- all_neg = (scores <= -1e9).all(dim=-1, keepdim=True)
276
- scores = torch.where(all_neg, torch.zeros_like(scores), scores)
277
-
278
- attn = F.softmax(scores, dim=-1)
279
- attn = self.dropout(attn)
280
-
281
- # Contexto: [B, n_heads, T+1, head_dim]
282
- ctx = torch.matmul(attn, v)
283
- ctx = ctx.transpose(1, 2).contiguous().view(B, T_ext, H)
284
- ctx = self.out_proj(ctx)
285
-
286
- # Residual + LayerNorm (estabilidade)
287
- if self.use_residual:
288
- ctx = self.ln(ctx + x_ext)
289
-
290
- # Sumarização: usar o CLS token (posição 0) como saída
291
- if self.aggregation == "first":
292
- summary = ctx[:, 0, :] # [B, H]
293
- else:
294
- # Média sobre todas as posições válidas (com mask)
295
- if mask_ext is not None:
296
- # Ponderar pela máscara
297
- weights = mask_ext.unsqueeze(-1).float() # [B, T+1, 1]
298
- sum_ctx = (ctx * weights).sum(dim=1) # [B, H]
299
- count = weights.sum(dim=1).clamp(min=1.0)
300
- summary = sum_ctx / count
301
- else:
302
- summary = ctx.mean(dim=1)
303
-
304
- return summary
305
-
306
-
307
- # ============================================================================
308
- # Núcleo Cooperativo CNN-BiGRU
309
- # ============================================================================
310
-
311
- class CooperativeCNNBiGRU(nn.Module):
312
- """Núcleo cooperativo CNN-BiGRU (dual-stream) com 3 níveis de ponte.
313
-
314
- Args:
315
- vocab_size: tamanho do vocabulário.
316
- embedding_dim: dimensão do embedding de tokens.
317
- cnn_filters: número de filtros da Conv1d.
318
- gru_hidden: dimensão oculta de cada direção da GRU.
319
- n_heads: número de cabeças para cross-attention.
320
- dropout: probabilidade de dropout.
321
- pad_idx: índice do token de padding.
322
- use_spectral_norm: se True, aplica normalização espectral nas lineares.
323
- """
324
-
325
- def __init__(
326
- self,
327
- vocab_size: int,
328
- embedding_dim: int = 64,
329
- cnn_filters: int = 64,
330
- gru_hidden: int = 64,
331
- n_heads: int = 4,
332
- dropout: float = 0.1,
333
- pad_idx: int = 1,
334
- use_spectral_norm: bool = False,
335
- ):
336
- super().__init__()
337
- self.pad_idx = pad_idx
338
- self.cnn_filters = cnn_filters
339
- self.gru_hidden = gru_hidden
340
-
341
- self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=pad_idx)
342
- nn.init.orthogonal_(self.embedding.weight)
343
-
344
- # CNN extractors (cada stream tem o seu)
345
- self.conv_A = nn.Conv1d(embedding_dim, cnn_filters, kernel_size=3, padding=1)
346
- self.conv_B = nn.Conv1d(embedding_dim, cnn_filters, kernel_size=3, padding=1)
347
-
348
- # Nível 1: Pontes globais (cross-attention)
349
- self.ponte_global_A = PonteGlobalCrossAttention(cnn_filters, n_heads=n_heads, dropout=dropout)
350
- self.ponte_global_B = PonteGlobalCrossAttention(cnn_filters, n_heads=n_heads, dropout=dropout)
351
-
352
- # Nível 2: Células cooperativas passo-a-passo
353
- self.gru_coop_direto = CellStepCooperativaComAtenuacao(cnn_filters, gru_hidden)
354
- self.gru_coop_inverso = CellStepCooperativaComAtenuacao(cnn_filters, gru_hidden)
355
-
356
- # Self-attention para sumarização temporal (requisito do dados.txt)
357
- self.self_attn_A = SelfAttentionSummary(gru_hidden * 2, dropout=dropout)
358
- self.self_attn_B = SelfAttentionSummary(gru_hidden * 2, dropout=dropout)
359
-
360
- # Camadas de saída (sem classificador aqui — o classificador fica no modelo multimodal)
361
- self.dropout = nn.Dropout(dropout)
362
- self.feat_dim = gru_hidden * 2 # 128 por stream (forward + backward concat)
363
-
364
- # Spectral norm opcional
365
- if use_spectral_norm:
366
- self.conv_A = nn.utils.spectral_norm(self.conv_A)
367
- self.conv_B = nn.utils.spectral_norm(self.conv_B)
368
- self.ponte_global_A.query = nn.utils.spectral_norm(self.ponte_global_A.query)
369
- self.ponte_global_A.key = nn.utils.spectral_norm(self.ponte_global_A.key)
370
- self.ponte_global_A.value = nn.utils.spectral_norm(self.ponte_global_A.value)
371
- self.ponte_global_B.query = nn.utils.spectral_norm(self.ponte_global_B.query)
372
- self.ponte_global_B.key = nn.utils.spectral_norm(self.ponte_global_B.key)
373
- self.ponte_global_B.value = nn.utils.spectral_norm(self.ponte_global_B.value)
374
-
375
- def forward(
376
- self,
377
- input_A: torch.Tensor,
378
- input_B: torch.Tensor,
379
- return_sequences: bool = False,
380
- ) -> dict:
381
- """
382
- Args:
383
- input_A: [B, T_a] tokens do stream A
384
- input_B: [B, T_b] tokens do stream B
385
- return_sequences: se True, retorna também as saídas temporais das BiGRUs
386
-
387
- Returns:
388
- dict com:
389
- out_A: [B, 128] representação final do stream A
390
- out_B: [B, 128] representação final do stream B
391
- fused: [B, 256] concatenação (out_A || out_B)
392
- (opcional) seq_A: [B, T, 128] saídas temporais do stream A
393
- (opcional) seq_B: [B, T, 128] saídas temporais do stream B
394
- """
395
- batch_size = input_A.size(0)
396
- seq_len_A = input_A.size(1)
397
- seq_len_B = input_B.size(1)
398
- device = input_A.device
399
-
400
- # Máscaras de padding
401
- mask_A = (input_A != self.pad_idx).float()
402
- mask_B = (input_B != self.pad_idx).float()
403
-
404
- # 1. Embeddings + CNN
405
- emb_A = self.embedding(input_A).permute(0, 2, 1) # [B, D, T_a]
406
- emb_B = self.embedding(input_B).permute(0, 2, 1) # [B, D, T_b]
407
-
408
- feat_A = F.relu(self.conv_A(emb_A)).permute(0, 2, 1) * mask_A.unsqueeze(-1)
409
- feat_B = F.relu(self.conv_B(emb_B)).permute(0, 2, 1) * mask_B.unsqueeze(-1)
410
-
411
- # 2. NÍVEL 1: Pontes globais (cross-attention)
412
- feat_A_coop = self.ponte_global_A(feat_A, feat_B, mask_B) * mask_A.unsqueeze(-1)
413
- feat_B_coop = self.ponte_global_B(feat_B, feat_A, mask_A) * mask_B.unsqueeze(-1)
414
-
415
- # 3. Estados ocultos iniciais
416
- h_dir_A = torch.zeros(batch_size, self.gru_hidden, device=device)
417
- h_dir_B = torch.zeros(batch_size, self.gru_hidden, device=device)
418
- h_inv_A = torch.zeros(batch_size, self.gru_hidden, device=device)
419
- h_inv_B = torch.zeros(batch_size, self.gru_hidden, device=device)
420
-
421
- max_steps = max(seq_len_A, seq_len_B)
422
- seq_dir_A, seq_dir_B = [], []
423
- seq_inv_A, seq_inv_B = [], []
424
-
425
- # 4. NÍVEL 2: Laço direto
426
- # Sempre coletamos as sequências temporais (necessário para self-attention final)
427
- for t in range(max_steps):
428
- x_t_A = feat_A_coop[:, t, :] if t < seq_len_A else torch.zeros(batch_size, self.cnn_filters, device=device)
429
- x_t_B = feat_B_coop[:, t, :] if t < seq_len_B else torch.zeros(batch_size, self.cnn_filters, device=device)
430
-
431
- m_t_A = mask_A[:, t].unsqueeze(-1) if t < seq_len_A else torch.zeros(batch_size, 1, device=device)
432
- m_t_B = mask_B[:, t].unsqueeze(-1) if t < seq_len_B else torch.zeros(batch_size, 1, device=device)
433
-
434
- 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)
435
- seq_dir_A.append(h_dir_A)
436
- seq_dir_B.append(h_dir_B)
437
-
438
- # 5. Laço inverso
439
- for t in reversed(range(max_steps)):
440
- x_t_A = feat_A_coop[:, t, :] if t < seq_len_A else torch.zeros(batch_size, self.cnn_filters, device=device)
441
- x_t_B = feat_B_coop[:, t, :] if t < seq_len_B else torch.zeros(batch_size, self.cnn_filters, device=device)
442
-
443
- m_t_A = mask_A[:, t].unsqueeze(-1) if t < seq_len_A else torch.zeros(batch_size, 1, device=device)
444
- m_t_B = mask_B[:, t].unsqueeze(-1) if t < seq_len_B else torch.zeros(batch_size, 1, device=device)
445
-
446
- 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)
447
- seq_inv_A.append(h_inv_A)
448
- seq_inv_B.append(h_inv_B)
449
-
450
- # 6. Concatenação forward+backward (128 por stream)
451
- final_A = torch.cat((h_dir_A, h_inv_A), dim=1) # [B, 128]
452
- final_B = torch.cat((h_dir_B, h_inv_B), dim=1) # [B, 128]
453
-
454
- # 6.5 SELF-ATTENTION FINAL LAYER (requisito do dados.txt linha 470)
455
- # Constrói sequência temporal [B, T, 2H] para aplicar self-attention
456
- out_A = final_A
457
- out_B = final_B
458
- seq_A_full = None
459
- seq_B_full = None
460
-
461
- # Aplicar self-attention TRUE (não mean-pool) sobre a sequência temporal
462
- if getattr(self, "self_attn_A", None) is not None:
463
- # Construir sequência temporal concatenando dir + inv em cada posição t
464
- try:
465
- seq_A_list = []
466
- seq_B_list = []
467
- for i in range(max_steps):
468
- if i < len(seq_dir_A) and (max_steps - 1 - i) < len(seq_inv_A):
469
- a_dir = seq_dir_A[i]
470
- a_inv = seq_inv_A[max_steps - 1 - i]
471
- seq_A_list.append(torch.cat((a_dir, a_inv), dim=1))
472
- if i < len(seq_dir_B) and (max_steps - 1 - i) < len(seq_inv_B):
473
- b_dir = seq_dir_B[i]
474
- b_inv = seq_inv_B[max_steps - 1 - i]
475
- seq_B_list.append(torch.cat((b_dir, b_inv), dim=1))
476
- if seq_A_list:
477
- seq_A_full = torch.stack(seq_A_list, dim=1) # [B, T, 2H]
478
- if seq_B_list:
479
- seq_B_full = torch.stack(seq_B_list, dim=1)
480
- except Exception as e:
481
- logger.warning(f"SelfAttention: falha ao construir sequência temporal: {e}")
482
- seq_A_full = None
483
- seq_B_full = None
484
-
485
- # Aplicar self-attention TRUE (não mean-pool)
486
- if seq_A_full is not None:
487
- out_A = self.self_attn_A(seq_A_full, mask=mask_A)
488
- if seq_B_full is not None:
489
- out_B = self.self_attn_B(seq_B_full, mask=mask_B)
490
-
491
- # 7. NÍVEL 3: Fusão final
492
- fused = torch.cat((out_A, out_B), dim=1) # [B, 256]
493
-
494
- result = {
495
- "out_A": out_A,
496
- "out_B": out_B,
497
- "fused": fused,
498
- "final_A": final_A, # estados finais raw (sem self-attention)
499
- "final_B": final_B,
500
- "mask_A": mask_A,
501
- "mask_B": mask_B,
502
- }
503
-
504
- if return_sequences:
505
- # Sequências temporais [B, T, 2H]
506
- if seq_A_full is not None:
507
- result["seq_A"] = seq_A_full
508
- if seq_B_full is not None:
509
- result["seq_B"] = seq_B_full
510
-
511
- return result
512
-
513
-
514
- __all__ = [
515
- "PonteGlobalCrossAttention",
516
- "CellStepCooperativaComAtenuacao",
517
- "SelfAttentionSummary",
518
- "CooperativeCNNBiGRU",
519
- ]