pytorch 指定GPU设备

使用os.environ["CUDA_VISIBLE_DEVICES"]

这种方法是通过环境变量限制可见的CUDA设备,从而在多个GPU的机器上只让PyTorch看到并使用指定的GPU。这种方式的好处是所有后续的CUDA调用都会使用这个GPU,并且代码中不需要显式地指定设备索引。

python 复制代码
import os

# 设置只使用2号GPU
os.environ["CUDA_VISIBLE_DEVICES"] = '2'

import torch
import torch.nn as nn

# 检查PyTorch是否检测到GPU
if torch.cuda.is_available():
    print(f"Using GPU: {torch.cuda.get_device_name(0)}")  # 注意这里是0,因为只有一个可见的GPU
else:
    print("No GPU available, using CPU instead.")

# 定义模型
class YourModel(nn.Module):
    def __init__(self):
        super(YourModel, self).__init__()
        self.layer = nn.Linear(10, 1)
    
    def forward(self, x):
        return self.layer(x)

# 创建模型并移动到GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = YourModel().to(device)

# 示例数据和前向传播
input_data = torch.randn(5, 10).to(device)
output = model(input_data)
print(output)

直接指定设备索引

这种方法是在代码中直接指定要使用的设备索引,无需修改环境变量。这种方式更加显式,并且可以在同一脚本中使用多个不同的GPU。

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

# 检查设备是否可用并打印设备名称
if torch.cuda.is_available():
    device = torch.device("cuda:2")  # 直接指定设备索引
    print(f"Using GPU: {torch.cuda.get_device_name(2)}")
else:
    device = torch.device("cpu")
    print("No GPU available, using CPU instead.")

# 定义模型
class YourModel(nn.Module):
    def __init__(self):
        super(YourModel, self).__init__()
        self.layer = nn.Linear(10, 1)
    
    def forward(self, x):
        return self.layer(x)

# 创建模型并移动到指定的GPU
model = YourModel().to(device)

# 示例数据和前向传播
input_data = torch.randn(5, 10).to(device)
output = model(input_data)
print(output)
相关推荐
喝拿铁写前端1 小时前
Dify 构建 FE 工作流:前端团队可复用 AI 工作流实战
前端·人工智能
阿里云大数据AI技术2 小时前
阿里云 EMR Serverless Spark + DataWorks 技术实践:引领企业 Data+AI 一体化转型
人工智能
billhan20162 小时前
MCP 深入理解:协议原理与自定义开发
人工智能
用户8356290780512 小时前
无需 Office:Python 批量转换 PPT 为图片
后端·python
Jahzo2 小时前
openclaw桌面端体验--ClawX
人工智能·github
billhan20162 小时前
Agent 开发全流程:从概念到生产
人工智能
threerocks2 小时前
过了个年,AI 圈变天了?但没人告诉你为什么
人工智能
threerocks3 小时前
Anthropic CEO Dario Amodei:海啸已在地平线上,但没人在看
人工智能
用户5191495848453 小时前
Adrenaline GPU 漏洞利用框架:突破 Android 内核内存读写限制
人工智能·aigc
hulkie3 小时前
从 AI 对话应用理解 SSE 流式传输:一项 "老技术" 的新生
前端·人工智能