| 466 | self.get_modules(self, mdl, input) |
| 467 | |
| 468 | def forward(self, hidden_states, attention_mask, output_all_encoded_layers=True, checkpoint_activations=False): |
| 469 | all_encoder_layers = [] |
| 470 | |
| 471 | def custom(start, end): |
| 472 | |
| 473 | def custom_forward(*inputs): |
| 474 | layers = self.layer[start:end] |
| 475 | x_ = inputs[0] |
| 476 | for layer in layers: |
| 477 | x_ = layer(x_, inputs[1]) |
| 478 | return x_ |
| 479 | |
| 480 | return custom_forward |
| 481 | |
| 482 | if checkpoint_activations: |
| 483 | l = 0 |
| 484 | num_layers = len(self.layer) |
| 485 | chunk_length = math.ceil(math.sqrt(num_layers)) |
| 486 | while l < num_layers: |
| 487 | hidden_states = checkpoint.checkpoint(custom(l, l + chunk_length), hidden_states, attention_mask * 1) |
| 488 | l += chunk_length |
| 489 | # decoder layers |
| 490 | else: |
| 491 | for i, layer_module in enumerate(self.layer): |
| 492 | hidden_states = layer_module(hidden_states, attention_mask, self.grads, collect_all_grads=True) |
| 493 | hidden_states.register_hook(lambda x, i=i, self=self: self.grads.append([x, "hidden_state"])) |
| 494 | |
| 495 | if output_all_encoded_layers: |
| 496 | all_encoder_layers.append((hidden_states)) |
| 497 | |
| 498 | if not output_all_encoded_layers or checkpoint_activations: |
| 499 | hidden_states = self.FinalLayerNorm(hidden_states) |
| 500 | all_encoder_layers.append((hidden_states)) |
| 501 | return all_encoder_layers |