gradient_checkpointing以计算时间换取内存

gradient_checkpointing的方法能够以计算时间去换取内存,这里我阅读longformer的源代码的时候,读取到了以下的内容,可以作为以计算时间换取内存的经典代码方式

if self.gradient_checkpointing and self.training:
    #gradient_checkpoint:以计算时间换内存的方式,显著减小模型训练对gpu的占用
    def create_custom_forward(module):
        def custom_forward(*inputs):
            return module(*inputs, is_global_attn, output_attentions)

        return custom_forward

    layer_outputs = torch.utils.checkpoint.checkpoint(
        create_custom_forward(layer_module),
        hidden_states,
        attention_mask,
        head_mask[idx] if head_mask is not None else None,
        is_index_masked,
        is_index_global_attn,
    )
else:
    layer_outputs = layer_module(
        hidden_states,
        attention_mask=attention_mask,
        layer_head_mask=head_mask[idx] if head_mask is not None else None,
        is_index_masked=is_index_masked,
        is_index_global_attn=is_index_global_attn,
        is_global_attn=is_global_attn,
        output_attentions=output_attentions,
    )

两者调用的方式本质上是一样的,只不过使用self.gradient_checkpointing的时候,调用了torch.utils.checkpoint模块,能够用时间换取显存的调用

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值