| 424 | self.get_modules(self, mdl, input) |
| 425 | |
| 426 | def forward(self, hidden_states, attention_mask, output_all_encoded_layers=True, checkpoint_activations=False): |
| 427 | all_encoder_layers = [] |
| 428 | |
| 429 | def custom(start, end): |
| 430 | |
| 431 | def custom_forward(*inputs): |
| 432 | layers = self.layer[start:end] |
| 433 | x_ = inputs[0] |
| 434 | for layer in layers: |
| 435 | x_ = layer(x_, inputs[1]) |
| 436 | return x_ |
| 437 | |
| 438 | return custom_forward |
| 439 | |
| 440 | if checkpoint_activations: |
| 441 | l = 0 |
| 442 | num_layers = len(self.layer) |
| 443 | chunk_length = math.ceil(math.sqrt(num_layers)) |
| 444 | while l < num_layers: |
| 445 | hidden_states = checkpoint.checkpoint(custom(l, l + chunk_length), hidden_states, attention_mask * 1) |
| 446 | l += chunk_length |
| 447 | # decoder layers |
| 448 | else: |
| 449 | for i, layer_module in enumerate(self.layer): |
| 450 | hidden_states = layer_module(hidden_states, attention_mask, self.grads, collect_all_grads=True) |
| 451 | hidden_states.register_hook(lambda x, i=i, self=self: self.grads.append([x, "hidden_state"])) |
| 452 | |
| 453 | if output_all_encoded_layers: |
| 454 | all_encoder_layers.append((hidden_states)) |
| 455 | |
| 456 | if not output_all_encoded_layers or checkpoint_activations: |
| 457 | all_encoder_layers.append((hidden_states)) |
| 458 | return all_encoder_layers |