PyTorch 2.0 以下版本中设置默认使用 GPU 的方法

PyTorch 2.0 以下版本中设置默认使用 GPU 的方法

在 PyTorch 2.0以下版本中,默认情况下仍然是使用 CPU 进行计算,除非明确指定使用 GPU。在 PyTorch 2.0 以下版本中,虽然没有 torch.set_default_device 的便捷方法,但可以通过显式地将张量、模型和操作分配到 GPU 来使用 GPU。

1. 检查 GPU 可用性

在使用 GPU 之前,首先检查系统中是否有可用的 GPU。

python 复制代码
import torch

# 检查是否有可用的 GPU
print(torch.cuda.is_available())  # 返回 True 或 False

# 检查可用 GPU 的数量
print(torch.cuda.device_count())

# 当前 GPU 名称
if torch.cuda.is_available():
    print(torch.cuda.get_device_name(0))

2. 将张量移动到 GPU

张量可以通过 .to('cuda').cuda() 方法显式地移动到 GPU。

python 复制代码
# 创建一个张量并将其移动到 GPU
x = torch.tensor([1.0, 2.0, 3.0])
x_gpu = x.to('cuda')  # 或 x.cuda()
print(x_gpu.device)  # 输出:cuda:0

# 在 GPU 上进行计算
y = x_gpu * 2
print(y)  # 输出在 GPU 上的结果
3. 将模型移动到 GPU

PyTorch 模型及其参数需要显式地移动到 GPU。

python 复制代码
# 定义一个简单的模型
model = torch.nn.Linear(10, 1)

# 将模型移动到 GPU
model = model.to('cuda')  # 或 model.cuda()

# 检查模型参数所在的设备
print(next(model.parameters()).device)  # 输出:cuda:0
4. 确保输入数据和模型在同一设备上

模型和输入数据需要在同一个设备上,否则会报错。

python 复制代码
# 创建一个张量并移动到 GPU
input_data = torch.randn(5, 10).to('cuda')

# 定义并移动模型到 GPU
model = torch.nn.Linear(10, 1).to('cuda')

# 前向传播
output = model(input_data)
print(output)

5. 使用 torch.device 动态管理设备

可以使用 torch.device 动态管理设备。

python 复制代码
# 定义设备
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# 将张量移动到设备
x = torch.tensor([1.0, 2.0, 3.0]).to(device)

# 将模型移动到设备
model = torch.nn.Linear(10, 1).to(device)

6. 优化器和损失函数的设备兼容性

当使用 GPU 时,模型的输出和目标(target)都需要在同一设备上。

python 复制代码
# 创建数据和目标,并移动到 GPU
data = torch.randn(5, 10).to('cuda')
target = torch.randn(5, 1).to('cuda')

# 定义模型并移动到 GPU
model = torch.nn.Linear(10, 1).to('cuda')

# 定义损失函数
criterion = torch.nn.MSELoss()

# 定义优化器
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

# 前向传播
output = model(data)
loss = criterion(output, target)

# 反向传播
loss.backward()
optimizer.step()

7. 混合设备计算(可选)

在多 GPU 或混合 CPU/GPU 环境中,可以手动管理每个张量或模型的设备。

python 复制代码
# 在 CPU 上创建张量
x_cpu = torch.tensor([1.0, 2.0, 3.0])

# 在 GPU 上创建张量
x_gpu = x_cpu.to('cuda')

# 将结果移动回 CPU
result = x_gpu * 2
result_cpu = result.to('cpu')
print(result_cpu)

总结

在 PyTorch 2.0 以下版本中,使用 GPU 的核心是 显式地将张量和模型移动到 GPU,并确保所有相关操作在同一设备上完成。以下是核心方法的汇总:

  • 检查 GPU 可用性: torch.cuda.is_available()

  • 移动张量到 GPU: .to('cuda').cuda()

  • 移动模型到 GPU: .to('cuda').cuda()

  • 动态设备管理: torch.device

相关推荐
码界筑梦坊10 分钟前
353-基于Python的大湾区气候数据可视化分析系统
开发语言·python·信息可视化·数据分析·django·vue·毕业设计
nancy_princess11 分钟前
attention基础概念1
人工智能
做个文艺程序员13 分钟前
华为昇腾NPU部署开源大模型全攻略(以Qwen3-8B为例)
人工智能·深度学习·华为
weiwei2284427 分钟前
torch.nn神经网络详解
pytorch·mnist·手写识别
如何原谅奋力过但无声31 分钟前
【chap11-动态规划(上 - 基础题目&背包问题)】用Python3刷《代码随想录》
数据结构·python·算法·动态规划
智算菩萨36 分钟前
【论文精读】Automated machine learning for positive-unlabelled learning
论文阅读·人工智能·机器学习·论文笔记·贝叶斯优化·自动机器学习·无标签学习
小程故事多_8043 分钟前
破解Agent“半途摆烂”困局,OpenDev凭Harness架构,撕开Code Agents的工程化真相
人工智能·架构·aigc·harness
吴佳浩1 小时前
Vibe Coding 时代:Vue 消失了还是 React 太强?
人工智能
Elastic 中国社区官方博客1 小时前
Elasticsearch:如何在 Elastic AI Builder 里使用 DSL 来查询 Elasticsearch
大数据·人工智能·elasticsearch·搜索引擎·ai·全文检索
云姜.1 小时前
JSON Schema使用
python·json