graykode / graykode/nlp-tutorial

Faster attention calculation in 4-2.Seq2Seq?

Đang mở
#75 1 bình luận 0 reaction 0 người được giao Xem trên GitHub
Ngôn ngữ chính
Jupyter Notebook
Star
14.9k
Fork
3.9k
Chỉ số merge pull request
Không có pull request nào được merge trong 30 ngày

Mô tả

Thanks for sharing! Just found out `Attention.get_att_weight` is calculating attention in a for-loop? this looks rather slow isn't it?

`4-2.Seq2Seq(Attention)/Seq2Seq(Attention).ipynb`

```python
def get_att_weight(self, dec_output, enc_outputs): # get attention weight one 'dec_output' with 'enc_outputs'
n_step = len(enc_outputs)
attn_scores = torch.zeros(n_step) # attn_scores : [n_step]

for i in range(n_step):
attn_scores[i] = self.get_att_score(dec_output, enc_outputs[i])

# Normalize scores to weights in range 0 to 1
return F.softmax(attn_scores).view(1, 1, -1)

def get_att_score(self, dec_output, enc_output): # enc_outputs [batch_size, num_directions(=1) * n_hidden]
score = self.attn(enc_output) # score : [batch_size, n_hidden]
return torch.dot(dec_output.view(-1), score.view(-1)) # inner product make scalar value
```

Suggested parallel version

```python
def get_att_weight(self, dec_output, enc_outputs): # get attention weight one 'dec_output' with 'enc_outputs'
n_step = len(enc_outputs)
attn_scores = torch.zeros(n_step,device=self.device) # attn_scores : [n_step]

enc_t = self.attn(enc_outputs)
score = dec_output.transpose(1,0).bmm(enc_t.transpose(1,0).transpose(2,1))
out1 = score.softmax(-1)
return out1

```

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Hướng nghiên cứu

Start in 4-2.Seq2Seq(Attention)/Seq2Seq(Attention).ipynb and inspect get_att_weight alongside get_att_score. Compare the loop-based and suggested batched attention calculations for equivalent weights and measure whether the revised calculation is faster. Done means the notebook preserves the intended attention output without the per-step loop.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
python, pytorch
Lĩnh vực
machine-learning, performance
Loại issue
Tái cấu trúc
Độ khó
3/5
Thời gian dự kiến
1-2 ngày
Mức độ hoạt động
Đình trệ
Độ rõ ràng
Khá rõ ràng
Mức phù hợp với người mới
42/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.