r""" The forward process of the block.
(
self,
x,
query_vector,
input_mask,
init_reset=True,
batch_valid_length=None,
)
| 142 | ) |
| 143 | |
| 144 | def construct( |
| 145 | self, |
| 146 | x, |
| 147 | query_vector, |
| 148 | input_mask, |
| 149 | init_reset=True, |
| 150 | batch_valid_length=None, |
| 151 | ): |
| 152 | r""" |
| 153 | The forward process of the block. |
| 154 | """ |
| 155 | # [bs * seq_length, embedding_size] |
| 156 | input_x = self.layernorm1(x) |
| 157 | input_x = F.cast(input_x, self.dtype) |
| 158 | |
| 159 | # indicate whether reset saved states |
| 160 | key_reset = None |
| 161 | value_reset = None |
| 162 | |
| 163 | if self.use_past: |
| 164 | # reset states, init_reset True for reuse and False for reset |
| 165 | key_reset = self.assign( |
| 166 | self.key_past, |
| 167 | self.mul(self.key_past, F.cast(init_reset, self.dtype)), |
| 168 | ) |
| 169 | value_reset = self.assign( |
| 170 | self.value_past, |
| 171 | self.mul(self.value_past, F.cast(init_reset, self.dtype)), |
| 172 | ) |
| 173 | # add dependency for desired execution order |
| 174 | input_x = F.depend(input_x, key_reset) |
| 175 | input_x = F.depend(input_x, value_reset) |
| 176 | |
| 177 | attention, layer_present = self.attention( |
| 178 | query_vector, |
| 179 | input_x, |
| 180 | input_x, |
| 181 | input_mask, |
| 182 | self.key_past, |
| 183 | self.value_past, |
| 184 | batch_valid_length, |
| 185 | ) |
| 186 | # For post-layernorm the inputs for residual path are output of self-attention and output of layernorm |
| 187 | if self.post_layernorm_residual: |
| 188 | x = self.add(input_x, attention) |
| 189 | # For pre-layernorm the inputs for residual path are output of self-attention and input of this layer |
| 190 | else: |
| 191 | x = self.add(x, attention) |
| 192 | |
| 193 | output_x = self.layernorm2(x) |
| 194 | output_x = F.cast(output_x, self.dtype) |
| 195 | mlp_logit = self.output(output_x) |
| 196 | |
| 197 | value_update = None |
| 198 | key_update = None |
| 199 | if self.use_past: |
| 200 | # current key and value |
| 201 | key_present, value_present = layer_present |