| 14 | |
| 15 | |
| 16 | class LinearDecoder(AbsDecoder): |
| 17 | |
| 18 | @typechecked |
| 19 | def __init__( |
| 20 | self, |
| 21 | vocab_size: int, |
| 22 | encoder_output_size: int, |
| 23 | pooling: str = "mean", |
| 24 | dropout: float = 0.0, |
| 25 | ): |
| 26 | """Initialize the module.""" |
| 27 | super().__init__() |
| 28 | logging.warning( |
| 29 | "Using Linear Decoder which is meant to be used for " |
| 30 | "classification tasks only." |
| 31 | ) |
| 32 | |
| 33 | self.input_dim = encoder_output_size |
| 34 | assert vocab_size > 3, "Invalid vocab size, must be > 3." |
| 35 | self.output_dim = vocab_size - 3 |
| 36 | self.dropout = None |
| 37 | if dropout != 0.0: |
| 38 | self.dropout = torch.nn.Dropout(p=dropout) |
| 39 | self.linear_out = torch.nn.Linear(self.input_dim, self.output_dim) |
| 40 | assert pooling in [ |
| 41 | "mean", |
| 42 | "max", |
| 43 | "CLS", |
| 44 | ], f"Invalid pooling: {pooling}. Should be 'mean', 'max' or 'CLS'." |
| 45 | self.pooling = pooling |
| 46 | |
| 47 | def forward( |
| 48 | self, |
| 49 | hs_pad: torch.Tensor, |
| 50 | hlens: torch.Tensor, |
| 51 | ys_in_pad: torch.Tensor = None, |
| 52 | ys_in_lens: torch.Tensor = None, |
| 53 | ) -> Tuple[torch.Tensor, torch.Tensor]: |
| 54 | """Forward method. |
| 55 | |
| 56 | Args: |
| 57 | hs_pad: (B, Tmax, D) |
| 58 | hlens: (B,) |
| 59 | Returns: |
| 60 | output: (B, n_classes) |
| 61 | """ |
| 62 | |
| 63 | mask = make_pad_mask(lengths=hlens, xs=hs_pad, length_dim=1).to(hs_pad.device) |
| 64 | if self.dropout is not None: |
| 65 | hs_pad = self.dropout(hs_pad) |
| 66 | if self.pooling == "mean": |
| 67 | unmasked_entries = (~mask).to(dtype=hs_pad.dtype) |
| 68 | input_feature = (hs_pad * unmasked_entries).sum(dim=1) |
| 69 | input_feature = input_feature / unmasked_entries.sum(dim=1) |
| 70 | elif self.pooling == "max": |
| 71 | input_feature = hs_pad.masked_fill(mask, float("-inf")) |
| 72 | input_feature, _ = torch.max(input_feature, dim=1) |
| 73 | elif self.pooling == "CLS": |
no outgoing calls
searching dependent graphs…