Pytorch2.0中compiled_model=torch.compile(model) 的正确添加位置

PyTorch官网推出了2.0稳定版,新特性torch.compile允许用户只需添加model=torch.compile(model)即可实现模型训练加速。无论是CPU训练、单卡训练还是多卡训练(DistributedDataParallel),只需关注这行代码的位置,无需大量修改原有代码,即可享受性能提升。

今天pytorch官网更新了pytorch2.0稳定版,迫不及待的我直接更新了,确实像官方所说,只需加入model=torch.compile(model)一行代码即可加速,加入的位置如下。

cpu训练:

 model=UNet(deep_supervision=True)
 model=torch.compile(model)

单卡训练:

 model=UNet(deep_supervision=True)
 model.to(Device)
 model=torch.compile(model)

多卡训练:

 model=UNet(deep_supervision=True)
 model.to(Device)
 model=nn.parallel.DistributedDataParallel(
         model,
         device_ids=[lo
import torch import torch.nn as nn import torch.optim as optim import time # 定义一个简单的模型 class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__() self.fc = nn.Linear(10, 1) def forward(self, x): return self.fc(x) # 模拟一些数据 inputs = torch.randn(32, 10) labels = torch.randn(32, 1) # eager 模式训练 model_eager = SimpleModel() criterion = nn.MSELoss() optimizer_eager = optim.SGD(model_eager.parameters(), lr=0.01) start_time_eager = time.time() for epoch in range(100): outputs = model_eager(inputs) loss = criterion(outputs, labels) optimizer_eager.zero_grad() loss.backward() optimizer_eager.step() end_time_eager = time.time() time_eager = end_time_eager - start_time_eager # torch.compile 模式训练 model_compiled = SimpleModel() compiled_model = torch.compile(model_compiled) optimizer_compiled = optim.SGD(model_compiled.parameters(), lr=0.01) start_time_compiled = time.time() for epoch in range(100): outputs = compiled_model(inputs) loss = criterion(outputs, labels) optimizer_compiled.zero_grad() loss.backward() optimizer_compiled.step() end_time_compiled = time.time() time_compiled = end_time_compiled - start_time_compiled # 计算速度提升比例 speedup_ratio = time_eager / time_compiled print(f"Eager 模式训练时间: {time_eager} 秒") print(f"torch.compile 模式训练时间: {time_compiled} 秒") print(f"速度提升比例: {speedup_ratio} 倍") 就这个示例代码,为什么compile模式比eager模式慢了100多倍?
09-03
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄渡猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值