0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

torch.Tensor.to() でGPUに変数が転送できない?model.to(device)とは返り値が違う

Posted at

はじめに

NNモデルをGPUに転送する際には model.to(device) で転送することができます.
一方,単なる配列を転送する際にはこれではうまくいかなかったので,備忘録として記録します.

環境

  • Python 3.11
  • torch 2.3.0+cu118

方法

これだとうまくいかない.

tensor = torch.rand([2,3])
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

print(tensor.device)
# cpu

tensor.to(device)
print(tensor.device)
# cpu

model.to(divece) と違い,配列をGPUに転送する際には返り値をもらってくる必要がある.

tensor_gpu = tensor.to(device)
print(tensor_gpu.device)
# cuda:0

torch.Tensor.to の返り値は Tensor であるのに対し,torch.nn.module.to の返り値は Self であることが原因である.

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?