"""CNN (dilated) + GRU 2 tầng hai chiều + skip head 1×1. Chuyển nguyên trạng từ `test 2/train_open_patch_v2.py` (lớp CNNGRU); không đổi kiến trúc. """ from __future__ import annotations import torch import torch.nn as nn class CNNGRU(nn.Module): def __init__(self, in_ch: int, d: int = 64, pdrop: float = 0.05): super().__init__() self.cnn = nn.Sequential( nn.Conv1d(in_ch, d, kernel_size=5, padding=2, dilation=1), nn.ReLU(), nn.Dropout(pdrop), nn.Conv1d(d, d, kernel_size=5, padding=4, dilation=2), nn.ReLU(), nn.Dropout(pdrop), nn.Conv1d(d, d, kernel_size=5, padding=8, dilation=4), nn.ReLU(), ) self.gru = nn.GRU( input_size=d, hidden_size=d, num_layers=2, batch_first=True, bidirectional=True, dropout=0.0, ) self.head = nn.Conv1d(2 * d, 1, kernel_size=1) self.head_skip = nn.Conv1d(in_ch, 1, kernel_size=1) self.bias = nn.Parameter(torch.zeros(1)) def forward(self, x: torch.Tensor) -> torch.Tensor: # x: (B, C, L) -> (B, 1, L) h = self.cnn(x) h2, _ = self.gru(h.transpose(1, 2)) y_main = self.head(h2.transpose(1, 2)) y_skip = self.head_skip(x) return y_main + y_skip + self.bias.view(1, 1, 1)