Skip to content

Commit

Permalink
Avoid padding indices in MeanEncoder (OpenNMT#1398)
Browse files Browse the repository at this point in the history
* We avoid padding while mean pooling
* placed batch dimension first for bmm
* replaced accidentally deleted line
  • Loading branch information
KaijuML authored and vince62s committed Apr 15, 2019
1 parent d3d280e commit db4d2fb
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion onmt/encoders/mean_encoder.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Define a minimal encoder."""
from onmt.encoders.encoder import EncoderBase
from onmt.utils.misc import sequence_mask
import torch


class MeanEncoder(EncoderBase):
Expand Down Expand Up @@ -28,7 +30,16 @@ def forward(self, src, lengths=None):

emb = self.embeddings(src)
_, batch, emb_dim = emb.size()
mean = emb.mean(0).expand(self.num_layers, batch, emb_dim)

if lengths is not None:
# we avoid padding while mean pooling
mask = sequence_mask(lengths).float()
mask = mask / lengths.unsqueeze(1).float()
mean = torch.bmm(mask.unsqueeze(1), emb.transpose(0, 1)).squeeze(1)
else:
mean = emb.mean(0)

mean = mean.expand(self.num_layers, batch, emb_dim)
memory_bank = emb
encoder_final = (mean, mean)
return encoder_final, memory_bank, lengths

0 comments on commit db4d2fb

Please sign in to comment.