PyTorch内存与参数管理笔记

获取PyTorch模型的总参数量:

import torch
import torch.nn as nn

model = nn.Sequential(
    nn.Linear(784, 128),
    nn.ReLU(),
    nn.Linear(128, 10)
)

total_params = sum(p.numel() for p in model.parameters())
print(f"Total number of parameters: {total_params}")

查看每层的参数

获取每个层的参数量:

for name, parameter in model.named_parameters():
    print(f"{name}: {parameter.numel()}")

查看当前GPU内存使用

# 当前分配的总内存
current_memory = torch.cuda.memory_allocated()
print(f"Current memory allocated: {current_memory} bytes")

# 峰值内存
peak_memory = torch.cuda.max_memory_allocated()
print(f"Peak memory allocated: {peak_memory} bytes")

优化和释放内存

删除不再需要的变量

x = torch.randn(1000, 1000, device="cuda")
y = torch.randn(1000, 1000, device="cuda")
z = x + y

del x, y
torch.cuda.empty_cache()  # 清空未使用的缓存

使用torch.no_grad()

在进行推理或任何不需要计算梯度的前向传播时,使用torch.no_grad()来减少内存使用:

with torch.no_grad():
    output = model(input)

原地操作

尽可能使用原地操作,减少内存分配:

x = torch.randn(1000, 1000, device="cuda")
x.add_(1)  # 原地加1

清空CUDA缓存

在确定某些内存不再被需要后,可以清空CUDA缓存:

torch.cuda.empty_cache()
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值