PyTorch框架-Python GPU编程

第一部分:环境配置

1.1 安装必要工具

  • 确保您的计算机有NVIDIA显卡并安装好了显卡驱动
  • 安装CUDA Toolkit(版本根据显卡选择,推荐11.x以上)
  • 安装PyTorch(会自动安装CUDA支持)
bash 复制代码
# 使用pip安装PyTorch(访问官网https://pytorch.org/获取最新安装命令)
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118

1.2 验证GPU是否可用

python 复制代码
import torch

# 检查CUDA是否可用
print("CUDA available:", torch.cuda.is_available())

# 查看GPU数量
print("GPU count:", torch.cuda.device_count())

# 查看当前GPU名称
if torch.cuda.is_available():
    print("Current GPU:", torch.cuda.get_device_name(0))

第二部分:基础GPU操作

2.1 将数据转移到GPU

python 复制代码
# 创建一个CPU上的Tensor
cpu_tensor = torch.tensor([1.0, 2.0, 3.0])

# 将Tensor转移到GPU
gpu_tensor = cpu_tensor.cuda()  # 或者使用 .to('cuda:0')

# 将数据移回CPU
gpu_tensor.cpu()

2.2 直接在GPU上创建数据

python 复制代码
# 在GPU上直接创建Tensor
gpu_tensor = torch.tensor([4.0, 5.0, 6.0], device='cuda:0')

# 使用更简洁的写法
gpu_tensor = torch.cuda.FloatTensor([7.0, 8.0, 9.0])

2.3 执行GPU计算

python 复制代码
a = torch.randn(10000, 10000, device='cuda')  # 创建随机矩阵
b = torch.randn(10000, 10000, device='cuda')

# GPU矩阵乘法(比CPU快数十倍)
c = torch.matmul(a, b)

第三部分:实际应用示例

示例1:GPU加速的矩阵运算

python 复制代码
import time

# CPU版本
start = time.time()
cpu_a = torch.randn(10000, 10000)
cpu_b = torch.randn(10000, 10000)
cpu_c = torch.matmul(cpu_a, cpu_b)
print("CPU time:", time.time() - start)

# GPU版本
start = time.time()
gpu_a = cpu_a.cuda()
gpu_b = cpu_b.cuda()
gpu_c = torch.matmul(gpu_a, gpu_b)
print("GPU time:", time.time() - start)

示例2:训练一个简单的神经网络

python 复制代码
import torch.nn as nn
import torch.optim as optim

# 定义网络
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc = nn.Linear(784, 10)

    def forward(self, x):
        return self.fc(x)

# 创建网络并转移到GPU
net = Net().cuda()

# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.01)

# 生成随机数据(注意将数据也转移到GPU)
inputs = torch.randn(32, 784).cuda()  # batch_size=32
labels = torch.randint(0, 10, (32,)).cuda()

# 训练步骤
outputs = net(inputs)
loss = criterion(outputs, labels)

optimizer.zero_grad()
loss.backward()
optimizer.step()

print("Loss:", loss.item())

第四部分:高级技巧

4.1 多GPU并行

python 复制代码
# 使用DataParallel进行数据并行
if torch.cuda.device_count() > 1:
    print("Using", torch.cuda.device_count(), "GPUs!")
    net = nn.DataParallel(net)

4.2 内存管理

python 复制代码
# 清空GPU缓存
torch.cuda.empty_cache()

# 监控显存使用
print("Memory allocated:", torch.cuda.memory_allocated()/1024**3, "GB")
print("Memory cached:   ", torch.cuda.memory_reserved()/1024**3, "GB")

第五部分:常见问题解决

  1. CUDA out of memory:

    • 减小batch size
    • 使用torch.cuda.empty_cache()
    • 检查是否有不需要的Tensor保留引用
  2. 设备不匹配错误:

    • 确保所有参与计算的Tensor都在同一设备上
    • 使用.to(device)统一设备
  3. 性能优化:

    • 使用torch.backends.cudnn.benchmark = True启用cuDNN自动优化
    • 使用pin_memory=True加速数据加载

第六部分:学习资源推荐

  1. PyTorch官方文档:pytorch.org/docs/stable...
  2. CUDA编程指南:docs.nvidia.com/cuda/
  3. 深度学习框架对比:PyTorch vs TensorFlow

通过这个教程,您应该能够:

✅ 配置Python GPU开发环境

✅ 进行基础的GPU张量操作

✅ 实现GPU加速的神经网络训练

✅ 处理常见的GPU使用问题

相关推荐
小帅热爱难回头14 分钟前
编写Skill生成AI落地项目系统架构
python
diving deep1 小时前
脚本速览-python
开发语言·python
2601_951643772 小时前
Python第一,Java跌出前三,C语言杀回来了
java·c语言·python·编程语言排行·技术趋势
AC赳赳老秦4 小时前
OpenClaw+Power Apps 实战:自动生成 Power Apps 应用、连接 Excel 数据源
大数据·开发语言·python·serverless·excel·deepseek·openclaw
茉莉玫瑰花茶6 小时前
综合案例 - AI 智能租房助手 [ 5 ]
服务器·数据库·人工智能·python·ai
文艺倾年6 小时前
【强化学习】强化学习基本概念,20W字总结(一)
人工智能·python·语言模型·自然语言处理·面试·职场和发展·大模型
宸丶一6 小时前
Day 13:持久化记忆 - 让 Agent 拥有长期记忆
jvm·python·ai
码云骑士6 小时前
13-列表append的底层真相(上)-listobject源码中的预分配策略
开发语言·python
浦信仿真大讲堂7 小时前
达索系统SIMULIA Abaqus 2026接触和约束的增强新功能介绍
人工智能·python·算法·仿真软件·达索软件
xufengzhu7 小时前
第三方 Python 库 Loguru 的进阶实战
python·loguru