MCPcopy Create free account
hub / github.com/espnet/espnet / LinearDecoder

Class LinearDecoder

espnet2/asr/decoder/linear_decoder.py:16–106  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

14
15
16class 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":

Callers 12

test_forward_backwardFunction · 0.90
test_scoreFunction · 0.90
test_fwd_bkwdFunction · 0.90
test_scoreFunction · 0.90
test_metrics_multiclassFunction · 0.90
test_metrics_multilabelFunction · 0.90
test_forward_backwardFunction · 0.90
test_scoreFunction · 0.90
test_output_sizeFunction · 0.90
test_linear_decoderFunction · 0.90

Calls

no outgoing calls

Tested by 10

test_forward_backwardFunction · 0.72
test_scoreFunction · 0.72
test_fwd_bkwdFunction · 0.72
test_scoreFunction · 0.72
test_metrics_multiclassFunction · 0.72
test_metrics_multilabelFunction · 0.72
test_forward_backwardFunction · 0.72
test_scoreFunction · 0.72
test_output_sizeFunction · 0.72
test_linear_decoderFunction · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…