Il layer del decoder
Come i transformer encoder, anche i transformer decoder sono composti da più layer che usano multi-head attention e sotto-livelli feed-forward. Prova a combinare questi componenti per costruire una classe DecoderLayer.
Le classi MultiHeadAttention e FeedForwardSubLayer sono a tua disposizione, insieme al tgt_mask che hai creato.
Questo esercizio fa parte del corso
Modelli Transformer con PyTorch
Istruzioni dell'esercizio
Completa il metodo forward() per far passare le embedding di input attraverso i layer definiti nel metodo __init__:
- Esegui il calcolo dell'attenzione usando il
tgt_maskfornito e le embedding di input,x, per le matrici query, key e value. - Applica il
dropoute la prima normalizzazione di layer,norm1. - Esegui il passaggio attraverso il sotto-livello feed-forward,
ff_sublayer. - Applica il
dropoute la seconda normalizzazione di layer,norm2.
Esercizio pratico interattivo
Prova a risolvere questo esercizio completando il codice di esempio.
class DecoderLayer(nn.Module):
def __init__(self, d_model, num_heads, d_ff, dropout):
super().__init__()
self.self_attn = MultiHeadAttention(d_model, num_heads)
self.ff_sublayer = FeedForwardSubLayer(d_model, d_ff)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.dropout = nn.Dropout(dropout)
def forward(self, x, tgt_mask):
# Perform the attention calculation
attn_output = self.____
# Apply dropout and the first layer normalization
x = self.____(x + self.____(attn_output))
# Pass through the feed-forward sublayer
ff_output = self.____(x)
# Apply dropout and the second layer normalization
x = self.____(x + self.____(ff_output))
return x