Pytorch在多GPU下选择特定序号的GPU运行程序

部署运行你感兴趣的模型镜像

原先的代码可能如下:

device = torch.device("cuda:0" if torch.cuda.is_available() and not args.no_cuda else "cpu")
model = model.to(device)
if args.n_gpu > 1:
    model = torch.nn.DataParallel(model)

上面这段代码会指定序号为0的GPU作为初始加载的GPU,同时如果有多GPU的情况下,会使用该服务器上所有的GPU运行程序。假定服务器有8块GPU,序号就是0-7,该代码就会全部使用0-7的GPU。但是如果服务器上假设序号为0-3的GPU被人占用了,那怎么办?直接使用上述代码就会OOM,所以对上述代码修改,就是下面的代码:

device = torch.device("cuda:{}".format(4) if torch.cuda.is_available() and not args.no_cuda else "cpu")
model = model.to(device)
if args.n_gpu > 1:
    model = torch.nn.DataParallel(model, device_ids=[4,5,6,7])

这段代码将初始加载的GPU改为序号为4的GPU,并且在多GPU的情况下,选取了序号为4-7的GPU来运行代码,这样子在序号为0-3的GPU被占用时就不会和别人冲突了。

您可能感兴趣的与本文相关的镜像

PyTorch 2.5

PyTorch 2.5

PyTorch
Cuda

PyTorch 是一个开源的 Python 机器学习库,基于 Torch 库,底层由 C++ 实现,应用于人工智能领域,如计算机视觉和自然语言处理

### 如何在 PyTorch 中使用 GPU 进行计算 #### 检查 GPU 可用性 为了确保能够利用GPU进行加速,在程序开始部分应该先检测是否有可用的GPU。这可以通过调用`torch.cuda.is_available()`函数完成,如果返回值为True,则表示至少有一块支持CUDA技术的NVIDIA显卡可供使用[^1]。 ```python import torch if torch.cuda.is_available(): print("CUDA is available.") else: print("No CUDA device found.") ``` #### 获取 GPU 设备详情 当确认存在可用的GPU之后,还可以进一步获取更关于这些设备的信息: - `torch.cuda.device_count()`用于查询系统中有少张GPU; - `torch.cuda.current_device()`可以获得当前正在使用的GPU编号,默认是从0开始计数的第一张卡; - 对于特定编号的GPU,可通过`torch.cuda.get_device_name(device)`获得其名称字符串。 ```python print(f"Number of GPUs: {torch.cuda.device_count()}") current_gpu_index = torch.cuda.current_device() print(f"Current GPU index: {current_gpu_index}") gpu_name = torch.cuda.get_device_name(current_gpu_index) print(f"Name of the current GPU: {gpu_name}") ``` #### 将 Tensor 移动到 GPU 上 对于想要放到GPU上处理的数据结构(比如Tensor),只需要简单地调用`.to('cuda')`方法即可实现迁移操作。同样地,也可以通过指定确切的device参数来选择具体哪一块GPU作为目标位置[^3]。 ```python tensor_on_cpu = torch.randn((2, 3)) tensor_on_gpu = tensor_on_cpu.to('cuda') print(tensor_on_gpu.device) # 应该显示 cuda:X (X代表具体的GPU序号) ``` #### 在 Module 中启用 GPU 加速 为了让整个神经网络模型能够在GPU环境中运行,除了要将输入数据转移到相应的硬件外,还需要把定义好的Module实例也迁移到那里去。这一步骤同样是借助`.to('cuda')`接口轻松达成目的。 ```python model = MyModel().to('cuda') input_data = torch.randn(batch_size, input_channels).to('cuda') output = model(input_data) loss_function = nn.CrossEntropyLoss() target_labels = ... loss_value = loss_function(output, target_labels.to('cuda')) ```
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值