SoFunction
Updated on 2024-11-17

Introduction to PyTorch device and usage

1 View the current device

Input Situation:

import torch
print("Default Device : {}".format(([4, 5, 6]).device))

Output:

Default Device : cpu

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

Inputs

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

Output

Device Type: cpu

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

Inputs

gpu = ("cuda:0")
print("GPU Device:【{}:{}】".format(, ))

Output

GPU Device:【cuda:0】

4 Querying the number of CPU and GPU devices

Inputs

print("Total GPU Count :{}".format(.device_count()))
print("Total CPU Count :{}".format(.cpu_count()))

Output

Total GPU Count :1
Total CPU Count :8

5 Switching from a CPU device to a GPU device

5.1 Methods use CPU devices by default

Inputs

data = ([[1, 4, 7], [3, 6, 9], [2, 5, 8]])
print()

Output

([3, 3])

5.2 Converting a cpu's Tensor to a GPU device using the to method

Input Situation:

data_gpu = (("cuda:0"))
print(data_gpu.device)

Output:

cuda:0

5.3 Converting a cpu's Tensor to a GPU device using the .cuda method

Input Situation:

data_gpu2 = (("cuda:0"))
# If there is only one gpu write it directly like this: data_gpu2 = ()
print(data_gpu2.device)

Output:

cuda:0

This article on PyTorch device and the use of this article is introduced to this, more related to the use of PyTorch device content please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!