(start, end, kw_args_index, cross_layer_index)
| 616 | if self.checkpoint_activations: |
| 617 | # define custom_forward for checkpointing |
| 618 | def custom(start, end, kw_args_index, cross_layer_index): |
| 619 | def custom_forward(*inputs): |
| 620 | layers_ = self.layers[start:end] |
| 621 | x_, mask = inputs[0], inputs[1] |
| 622 | |
| 623 | # recover kw_args and output_cross_layer |
| 624 | flat_inputs = inputs[2:] |
| 625 | kw_args, output_cross_layer = {}, {} |
| 626 | for k, idx in kw_args_index.items(): |
| 627 | kw_args[k] = flat_inputs[idx] |
| 628 | for k, idx in cross_layer_index.items(): |
| 629 | output_cross_layer[k] = flat_inputs[idx] |
| 630 | # ----------------- |
| 631 | |
| 632 | output_per_layers_part = [] |
| 633 | for i, layer in enumerate(layers_): |
| 634 | output_this_layer_obj, output_cross_layer_obj = {}, {} |
| 635 | if 'layer_forward' in self.hooks: |
| 636 | layer_ret = self.hooks['layer_forward']( |
| 637 | x_, mask, layer_id=layer.layer_id, |
| 638 | **kw_args, position_ids=position_ids, **output_cross_layer, |
| 639 | output_this_layer=output_this_layer_obj, |
| 640 | output_cross_layer=output_cross_layer_obj |
| 641 | ) |
| 642 | else: |
| 643 | layer_ret = layer( |
| 644 | x_, mask, layer_id=layer.layer_id, |
| 645 | **kw_args, position_ids=position_ids, **output_cross_layer, |
| 646 | output_this_layer=output_this_layer_obj, |
| 647 | output_cross_layer=output_cross_layer_obj |
| 648 | ) |
| 649 | if isinstance(layer_ret, tuple): |
| 650 | layer_ret = layer_ret[0] # for legacy API |
| 651 | x_, output_this_layer, output_cross_layer = layer_ret, output_this_layer_obj, output_cross_layer_obj |
| 652 | if output_hidden_states: |
| 653 | output_this_layer['hidden_states'] = x_ |
| 654 | output_per_layers_part.append(output_this_layer) |
| 655 | |
| 656 | # flatten for re-aggregate keywords outputs |
| 657 | flat_outputs = [] |
| 658 | for output_this_layer in output_per_layers_part: |
| 659 | for k in output_this_layer: |
| 660 | # TODO add warning for depth>=2 grad tensors |
| 661 | flat_outputs.append(output_this_layer[k]) |
| 662 | output_this_layer[k] = len(flat_outputs) - 1 |
| 663 | for k in output_cross_layer: |
| 664 | flat_outputs.append(output_cross_layer[k]) |
| 665 | output_cross_layer[k] = len(flat_outputs) - 1 |
| 666 | # -------------------- |
| 667 | |
| 668 | return (x_, output_per_layers_part, output_cross_layer, *flat_outputs) |
| 669 | return custom_forward |
| 670 | |
| 671 | # prevent to lose requires_grad in checkpointing. |
| 672 | # To save memory when only finetuning the final layers, don't use checkpointing. |
nothing calls this directly
no outgoing calls
no test coverage detected