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)
相关推荐
开开心心就好32 分钟前
图片格式转换工具,右键菜单一键转换简化
linux·运维·服务器·python·django·pdf·1024程序员节
骥龙33 分钟前
1.2下、工欲善其事:物联网安全研究环境搭建指南
python·物联网·安全
GISer_Jing41 分钟前
AI开发实战:从零搭建智能应用
人工智能·prompt·aigc
WZGL123041 分钟前
智慧养老方兴未艾,“AI+养老”让银龄老人晚年更美好
大数据·人工智能·物联网·生活·智能家居
狼爷1 小时前
一文看懂 AI 世界里的新黑话Skills、MCP、Projects、Prompts
人工智能·openai·ai编程
疾风sxp1 小时前
nl2sql技术实现自动sql生成之langchain4j SqlDatabaseContentRetriever
java·人工智能·langchain4j
DisonTangor1 小时前
阿里Qwen开源Qwen3-VL-Embedding 和 Qwen3-VL-Reranker
人工智能·搜索引擎·开源·aigc·embedding
其美杰布-富贵-李1 小时前
深度学习中的 tmux
服务器·人工智能·深度学习·tmux
<-->1 小时前
deepspeed vs vllm
人工智能
Lxinccode1 小时前
BUG(20) : response.text耗时很久, linux耗时十几秒, Windows耗时零点几秒
python·bug·requests·response.text·response.text慢