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)
相关推荐
+wacyltd大模型备案算法备案1 天前
大模型备案怎么做?2025年企业大模型备案全流程与材料清单详解
人工智能·大模型备案·算法备案·大模型上线登记
吾在学习路1 天前
故事型总结:Swin Transformer 是如何打破 Vision Transformer 壁垒的?
人工智能·深度学习·transformer
sandwu1 天前
AI自动化测试(一)
人工智能·agent·playwright·ai自动化测试·midscene
问道飞鱼1 天前
【人工智能】AI Agent 详解:定义、分类与典型案例
人工智能·ai agent
编码小哥1 天前
OpenCV形态学操作:腐蚀与膨胀原理解析
人工智能·opencv·计算机视觉
lbb 小魔仙1 天前
AI + 云原生实战:K8s 部署分布式训练集群,效率翻倍
人工智能·云原生·kubernetes
顽强卖力1 天前
第二章:什么是数据分析师?
笔记·python·职场和发展·学习方法
啊巴矲1 天前
小白从零开始勇闯人工智能:机器学习初级篇(随机森林)
人工智能·机器学习
技术小甜甜1 天前
[AI Agent] 如何在本地部署 Aider 并接入局域网 Ollama 模型,实现本地智能助手操作系统资源
人工智能·ai·自动化·agent
江湖独行侠1 天前
基于光学定位系统实现手术器械和CT模型的追踪
人工智能·信息可视化·健康医疗