| 79 | |
| 80 | |
| 81 | class DecoderLayer(nn.Module): |
| 82 | def __init__(self, self_attention, cross_attention, d_model, d_ff=None, |
| 83 | dropout=0.1, activation="relu"): |
| 84 | super(DecoderLayer, self).__init__() |
| 85 | d_ff = d_ff or 4 * d_model |
| 86 | self.self_attention = self_attention |
| 87 | self.cross_attention = cross_attention |
| 88 | self.conv1 = nn.Conv1d(in_channels=d_model, out_channels=d_ff, kernel_size=1) |
| 89 | self.conv2 = nn.Conv1d(in_channels=d_ff, out_channels=d_model, kernel_size=1) |
| 90 | self.norm1 = nn.LayerNorm(d_model) |
| 91 | self.norm2 = nn.LayerNorm(d_model) |
| 92 | self.norm3 = nn.LayerNorm(d_model) |
| 93 | self.dropout = nn.Dropout(dropout) |
| 94 | self.activation = F.relu if activation == "relu" else F.gelu |
| 95 | |
| 96 | def forward(self, x, cross, x_mask=None, cross_mask=None): |
| 97 | x = x + self.dropout(self.self_attention( |
| 98 | x, x, x, |
| 99 | attn_mask=x_mask |
| 100 | )[0]) |
| 101 | x = self.norm1(x) |
| 102 | |
| 103 | x = x + self.dropout(self.cross_attention( |
| 104 | x, cross, cross, |
| 105 | attn_mask=cross_mask |
| 106 | )[0]) |
| 107 | |
| 108 | y = x = self.norm2(x) |
| 109 | y = self.dropout(self.activation(self.conv1(y.transpose(-1, 1)))) |
| 110 | y = self.dropout(self.conv2(y).transpose(-1, 1)) |
| 111 | |
| 112 | return self.norm3(x + y) |
| 113 | |
| 114 | |
| 115 | class Decoder(nn.Module): |