Skip to content
This repository has been archived by the owner on Aug 1, 2023. It is now read-only.

Remove pad tokens from attention during decoding #226

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions pytorch_translate/beam_decode.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,8 @@ def _generate(self, encoder_input, beam_size=None, maxlen=None, prefix_tokens=No

attn = scores.new(bsz * beam_size, src_encoding_len, maxlen + 2)
attn_buf = attn.clone()

nonpad_idxs = src_tokens.ne(self.pad)

# list of completed sentences
finalized = [[] for i in range(bsz)]
Expand Down Expand Up @@ -258,11 +260,13 @@ def finalize_hypos(step, bbsz_idx, eos_scores, unfinalized_scores=None):
sents_seen.add(sent)

def get_hypo():
_, alignment = attn_clone[i].max(dim=0)
# remove padding tokens from attn scores
hypo_attn = attn_clone[i][nonpad_idxs[sent]]
_, alignment = hypo_attn.max(dim=0)
return {
"tokens": tokens_clone[i],
"score": score,
"attention": attn_clone[i], # src_len x tgt_len
"attention": hypo_attn, # src_len x tgt_len
"alignment": alignment,
"positional_scores": pos_scores[i],
}
Expand Down