디코더 레이어
인코더 트랜스포머와 마찬가지로, 디코더 트랜스포머도 멀티헤드 어텐션과 feed-forward 서브레이어로 이루어진 여러 레이어를 쌓아 만듭니다. 이 컴포넌트들을 조합해서 DecoderLayer 클래스를 만들어 보세요.
MultiHeadAttention과 FeedForwardSubLayer 클래스가 제공되어 있으며, 이전에 만든 tgt_mask도 사용할 수 있어요.
이 연습은 강의의 일부입니다
PyTorch로 배우는 Transformer 모델
연습 안내
__init__ 메서드에서 정의한 레이어들을 거치도록 입력 임베딩을 전달하기 위해 forward() 메서드를 완성하세요:
- 제공된
tgt_mask를 사용하고, 입력 임베딩x를 query, key, value 행렬로 사용해 어텐션을 계산하세요. dropout과 첫 번째 레이어 정규화인norm1을 적용하세요.- feed-forward 서브레이어인
ff_sublayer를 통과시키세요. dropout과 두 번째 레이어 정규화인norm2를 적용하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
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