텍스트 생성용 어텐션 메커니즘

PyTorch로 배우는 텍스트 딥러닝

Shubham Jain

Instructor

텍스트 처리의 모호성

  • "The monkey ate that banana because it was too hungry"

  • 단어 "it"은 무엇을 가리키나요?

HumanVsMachine

PyTorch로 배우는 텍스트 딥러닝

어텐션 메커니즘

  • 단어 중요도 부여
  • 기계 해석이 인간 이해와 일치하도록 함

어텐션 차트

1 Xie, Huiqiang & Qin, Zhijin & Li, Geoffrey & Juang, Biing-Hwang. (2020). Deep Learning Enabled Semantic Communication Systems
PyTorch로 배우는 텍스트 딥러닝

자기어텐션과 멀티헤드 어텐션

  • 자기어텐션: 문장 내 단어의 중요도 산정

    • "지붕 위에 있던 고양이"가 "무서워했다"
    • "무서워했다"를 "고양이"와 연결
  • 멀티헤드 어텐션: 여러 스포트라이트로 다양한 측면 포착

    • "무서워했다"의 의미는 다음과 연관 가능
    • "고양이", "지붕", 또는 "위에 있었다"
PyTorch로 배우는 텍스트 딥러닝

어텐션 메커니즘 - 어휘와 데이터 설정

data = ["the cat sat on the mat", ...]

vocab = set(' '.join(data).split())
word_to_ix = {word: i for i, word in enumerate(vocab)} ix_to_word = {i: word for word, i in word_to_ix.items()}
pairs = [sentence.split() for sentence in data] input_data = [[word_to_ix[word] for word in sentence[:-1]] for sentence in pairs] target_data = [word_to_ix[sentence[-1]] for sentence in pairs] inputs = [torch.tensor(seq, dtype=torch.long) for seq in input_data] targets = torch.tensor(target_data, dtype=torch.long)
PyTorch로 배우는 텍스트 딥러닝

모델 정의

embedding_dim = 10
hidden_dim = 16

class RNNWithAttentionModel(nn.Module): def __init__(self): super(RNNWithAttentionModel, self).__init__()
self.embeddings = nn.Embedding(vocab_size, embedding_dim) self.rnn = nn.RNN(embedding_dim, hidden_dim, batch_first=True)
self.attention = nn.Linear(hidden_dim, 1)
self.fc = nn.Linear(hidden_dim, vocab_size)
PyTorch로 배우는 텍스트 딥러닝

어텐션을 포함한 순전파

def forward(self, x):
    x = self.embeddings(x)
    out, _ = self.rnn(x)

attn_weights = torch.nn.functional.softmax(self.attention(out).squeeze(2), dim=1)
context = torch.sum(attn_weights.unsqueeze(2) * out, dim=1) out = self.fc(context) return out
def pad_sequences(batch): max_len = max([len(seq) for seq in batch]) return torch.stack([torch.cat([seq, torch.zeros(max_len-len(seq)).long()]) for seq in batch])
PyTorch로 배우는 텍스트 딥러닝

훈련 준비

criterion = nn.CrossEntropyLoss()

attention_model = RNNWithAttentionModel() optimizer = torch.optim.Adam(attention_model.parameters(), lr=0.01)
for epoch in range(300): attention_model.train() optimizer.zero_grad()
padded_inputs = pad_sequences(inputs) outputs = attention_model(padded_inputs)
loss = criterion(outputs, targets) loss.backward() optimizer.step()
PyTorch로 배우는 텍스트 딥러닝

모델 평가

for input_seq, target in zip(input_data, target_data):
    input_test = torch.tensor(input_seq, dtype=torch.long).unsqueeze(0)

attention_model.eval() attention_output = attention_model(input_test)
attention_prediction = ix_to_word[torch.argmax(attention_output).item()]
print(f"\nInput: {' '.join([ix_to_word[ix] for ix in input_seq])}") print(f"Target: {ix_to_word[target]}") print(f"RNN with Attention prediction: {attention_prediction}")
Input: the cat sat on the
Target: mat
RNN with Attention prediction: mat
PyTorch로 배우는 텍스트 딥러닝

Ayo berlatih!

PyTorch로 배우는 텍스트 딥러닝

Preparing Video For Download...