graykode / graykode/nlp-tutorial

Faster attention calculation in 4-2.Seq2Seq?

未关闭
#75 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看
主要语言
Jupyter Notebook
星标
14.9k
派生
3.9k
PR 合并指标
30 天内没有已合并 PR

描述

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

```

贡献指南

打开贡献指南

调研方向

从 4-2.Seq2Seq(Attention)/Seq2Seq(Attention).ipynb 开始,检查 get_att_weight 和 get_att_score。比较基于循环的 attention 计算与建议的批量计算,确认它们产生等价的权重,并测量修改后的计算是否更快。当 notebook 在没有逐步循环的情况下仍保留预期的 attention 输出时,即表示完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
python, pytorch
领域
machine-learning, performance
Issue 类型
重构
难度
3/5
预计耗时
1-2 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
42/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。