python - model.to(device) 和 model=model.to(device) 有什么区别?
问题描述
假设模型本来是存储在CPU上的,然后我想把它移到GPU0上,那么我可以这样做:
device = torch.device('cuda:0')
model = model.to(device)
# or
model.to(device)
这两条线有什么区别?
解决方案
没有语义差异。nn.Module.to
函数将模型移动到设备。
但要小心。
对于张量(文档):
# tensor a is in CPU
device = torch.device('cuda:0')
b = a.to(device)
# a is still in CPU!
# b is in GPU!
# a and b are different
对于模型(文档):
# model a is in CPU
device = torch.device('cuda:0')
b = a.to(device)
# a and b are in GPU
# a and b point to the same model
推荐阅读
- javascript - JSON Stringify 每行一个对象
- postgresql - 如何使 PostgreSQL 约束仅适用于新值
- php - ngrok 在 laravel 6 中返回 419 并禁用 CSRF 令牌
- r - 在 R 中导入多张工作簿的几张
- python - 是什么导致熊猫和 geopandas 出现此列表索引超出范围错误?
- tensorflow - 特征嵌入应该在神经网络中的 dropout 层之前还是之后进行?
- angular - 用户类型 3-4 字符的 Mat-Select Angular 选项过滤器
- sql - 创建临时表,它复制一列的值但更改另一列的值
- regex - 即使之前有空格,如何匹配数字?
- microsoft-teams - 共享屏幕菜单中的按钮未显示在 Microsoft 团队中