Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use PyTorch device and cuda.device

Shulou Source: shulou.com Published: 2022-06-01 01:13:47 10月01日 Update

This article mainly explains "how to use PyTorch device and cuda.device". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use PyTorch device and cuda.device.

1 View current device input: import torchprint ("Default Device: {}" .format (torch.Tensor ([4,5,6]) .device))

Output:

Default Device: cpu

2 cpu devices can be specified using "cpu:0"

Input situation

Device= torch.Tensor ([1,2,3], device= "cpu:0") .deviceprint ("Device Type: {}" .format (device))

Output situation

Device Type: cpu

3 gpu devices can be specified using "cuda:0"

Input situation

Gpu = torch.device ("cuda:0") print ("GPU Device: [{}: {}]" .format (gpu.type, gpu.index))

Output situation

GPU Device: [cuda:0]

4 query the number of CPU and GPU devices

Input situation

Print ("Total GPU Count: {}" .format (torch.cuda.device_count () print ("Total CPU Count: {}" .format (torch.cuda.os.cpu_count ()

Output situation

Total GPU Count: 1

Total CPU Count: 8

5 convert from CPU device to GPU device 5.1 torch.Tensor method uses CPU device by default

Input situation

Data = torch.Tensor ([[1,4,7], [3,6,9], [2,5,8]) print (data.shape)

Output situation

Torch.Size ([3,3])

5.2 use the to method to convert the Tensor of cpu to the GPU device

Input situation:

Data_gpu = data.to (torch.device ("cuda:0")) print (data_gpu.device)

Output:

Cuda:0

5.3 use the .cuda method to convert the Tensor of cpu to the GPU device

Input situation:

Data_gpu2 = data.cuda (torch.device ("cuda:0")) # if there is only one piece of gpu, write it directly like this: data_gpu2 = data.cuda () print (data_gpu2.device)

Output:

Cuda:0

Thank you for your reading, the above is the content of "how to use PyTorch device and cuda.device". After the study of this article, I believe you have a deeper understanding of how to use PyTorch device and cuda.device, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Situation equipment input output method learning content only that is ideas quantity articles more knowledge knowledge points articles follow questions practice push Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Docker Shulou Technology NVidia vpn