MCPcopy Create free account
hub / github.com/FunAudioLLM/FunMusic / forward

Method forward

inspiremusic/transformer/convolution.py:90–145  ·  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

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

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected