pytorch CUDA版本和CUDA实际如何工作?

问题描述 投票:0回答:1

这是我的 conda 环境的软件包列表:

MY PACKAGE LIST

如你所见,我还没有安装cudatoolkit并且nvcc命令无法使用。但我确实安装了 CUDA 版本的 pytorch。

但是,当我在Python中导入torch并检查

torch.cuda.is_available()
时,它返回Ture。

我什至运行这个测试脚本:

import torch
from torch import nn
from torch.nn import Module
from torch.optim.lr_scheduler import LambdaLR


class TestNet(Module):
    def __init__(self) -> None:
        super().__init__()
        self.linear = nn.Linear(10,10)

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

if __name__=="__main__":
    if torch.cuda.is_available():
        device = "cuda"
    else:
        device = "cpu"
    print(f"Using device {device}")
    test_samples = torch.rand([32,10]).to(device)
    gt_matrix = torch.eye(10).to(device)
    target = torch.matmul(test_samples, gt_matrix)

    model = TestNet().to(device)

    optimizer = torch.optim.SGD(model.parameters(), lr=1)
    criterion = nn.MSELoss()
    scheduler = LambdaLR(optimizer, lr_lambda=lambda x: min(x, 24)/24)

    for epoch in range(128):
        logits = model(test_samples)
        loss = criterion(logits, target)
        learning_rate = optimizer.param_groups[0]["lr"]

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

        print(f"Epoch {epoch+1}/{24}, loss {loss.item()}, lr {learning_rate}")
    
    print("Learned matrix:")
    print(model.state_dict()["linear.weight"])

并且运行成功。

所以我很好奇 pytorch CUDA 版本实际上是如何工作的?是否需要预装CUDA工具包?另外,通过

conda install cudatoolkit
conda install cuda
安装 CUDA 和通过图形安装程序安装有什么区别?

python machine-learning deep-learning pytorch
1个回答
0
投票

根据此 SO 线程 和此 论坛线程,您不需要在本地计算机上安装

nvcc
,因为 PyTorch 附带了自己的 CUDA 库。唯一的要求是您的设备上安装了 CUDA 驱动程序,并且它支持您通过 Pytorch 安装的 CUDA 版本。

我假设

conda install cudatoolkit
安装独立的 CUDA 工具包,但独立于 PyTorch。在安装页面之后,您应该使用
conda install pytorch::pytorch-cuda
。这样您就可以安装支持 CUDA 的 PyTorch。

© www.soinside.com 2019 - 2024. All rights reserved.