MCPcopy Create free account
hub / github.com/ASLP-lab/OSUM / forward

Method forward

OSUM/wenet/efficient_conformer/convolution.py:93–154  ·  view source on GitHub ↗

Compute convolution module. Args: x (torch.Tensor): Input tensor (#batch, time, channels). mask_pad (torch.Tensor): used for batch padding (#batch, 1, time), (0, 0, 0) means fake mask. cache (torch.Tensor): left context cache, it is only

(
        self,
        x: torch.Tensor,
        mask_pad: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool),
        cache: torch.Tensor = torch.zeros((0, 0, 0)),
    )

Source from the content-addressed store, hash-verified

91 self.stride = stride
92
93 def forward(
94 self,
95 x: torch.Tensor,
96 mask_pad: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool),
97 cache: torch.Tensor = torch.zeros((0, 0, 0)),
98 ) -> Tuple[torch.Tensor, torch.Tensor]:
99 """Compute convolution module.
100 Args:
101 x (torch.Tensor): Input tensor (#batch, time, channels).
102 mask_pad (torch.Tensor): used for batch padding (#batch, 1, time),
103 (0, 0, 0) means fake mask.
104 cache (torch.Tensor): left context cache, it is only
105 used in causal convolution (#batch, channels, cache_t),
106 (0, 0, 0) meas fake cache.
107 Returns:
108 torch.Tensor: Output tensor (#batch, time, channels).
109 """
110 # exchange the temporal dimension and the feature dimension
111 x = x.transpose(1, 2) # (#batch, channels, time)
112
113 # mask batch padding
114 if mask_pad.size(2) > 0: # time > 0
115 x.masked_fill_(~mask_pad, 0.0)
116
117 if self.lorder > 0:
118 if cache.size(2) == 0: # cache_t == 0
119 x = nn.functional.pad(x, (self.lorder, 0), 'constant', 0.0)
120 else:
121 # When export ONNX,the first cache is not None but all-zero,
122 # cause shape error in residual block,
123 # eg. cache14 + x9 = 23, 23-7+1=17 != 9
124 cache = cache[:, :, -self.lorder:]
125 assert cache.size(0) == x.size(0) # equal batch
126 assert cache.size(1) == x.size(1) # equal channel
127 x = torch.cat((cache, x), dim=2)
128 assert (x.size(2) > self.lorder)
129 new_cache = x[:, :, -self.lorder:]
130 else:
131 # It's better we just return None if no cache is requried,
132 # However, for JIT export, here we just fake one tensor instead of
133 # None.
134 new_cache = torch.zeros((0, 0, 0), dtype=x.dtype, device=x.device)
135
136 # GLU mechanism
137 x = self.pointwise_conv1(x) # (batch, 2*channel, dim)
138 x = nn.functional.glu(x, dim=1) # (batch, channel, dim)
139
140 # 1D Depthwise Conv
141 x = self.depthwise_conv(x)
142 if self.use_layer_norm:
143 x = x.transpose(1, 2)
144 x = self.activation(self.norm(x))
145 if self.use_layer_norm:
146 x = x.transpose(1, 2)
147 x = self.pointwise_conv2(x)
148 # mask batch padding
149 if mask_pad.size(2) > 0: # time > 0
150 if mask_pad.size(2) != x.size(2):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected