Pytorch 在M1 Mac上使用PyTorch: RuntimeError: Placeholder storage has not been allocated on MPS device

Pytorch 在M1 Mac上使用PyTorch: RuntimeError: Placeholder storage has not been allocated on MPS device

在本文中,我们将介绍如何在M1 Mac上使用PyTorch,并解决可能遇到的RuntimeError: Placeholder storage has not been allocated on MPS device错误。

阅读更多:Pytorch 教程

什么是PyTorch?

PyTorch是一个基于Python的开源机器学习库,主要用于深度学习任务。它提供了丰富的工具和函数,以便开发人员可以更轻松地构建和训练神经网络模型。PyTorch具有动态计算图的特点,这使得它在许多应用中比其他库更加灵活和强大。

在M1 Mac 上安装 PyTorch

对于M1芯片的Mac用户,PyTorch的安装稍微有些不同。由于M1芯片的体系结构不同于传统的Intel芯片,因此需要额外的步骤来确保PyTorch正确安装和运行。

首先,我们需要使用conda创建一个虚拟环境,并安装Miniforge,一个面向科学计算的Anaconda发行版。可以通过以下命令安装Miniforge:

wget https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-MacOSX-arm64.sh -O Miniforge.sh
/bin/bash Miniforge.sh
Python

安装完成后,我们需要激活虚拟环境并安装PyTorch

conda create --name pytorch_env
conda activate pytorch_env
conda install pytorch torchvision torchaudio -c pytorch -c conda-forge
Python

完成这些步骤后,PyTorch将成功安装在您的M1 Mac上。

RuntimeError: Placeholder storage has not been allocated on MPS device错误解决方法

在使用PyTorch时,可能会遇到一个常见的错误:“RuntimeError: Placeholder storage has not been allocated on MPS device”。这个错误通常是由于在图形处理器上使用多进程时导致的。

要解决这个问题,我们需要在代码中添加一行设置环境变量的代码:

import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "True"
Python

将这行代码添加到您的PyTorch代码的开头,重新运行程序,这个错误就应该会被解决了。

下面是一个使用PyTorch进行图像分类的示例代码,在M1 Mac上运行时可能会遇到“RuntimeError: Placeholder storage has not been allocated on MPS device”错误:

import torch
import torchvision
from torchvision import transforms

# 设置环境变量
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "True"

# 定义预处理的transforms
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5,), (0.5,))
])

# 加载MNIST数据集
trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)

# 定义神经网络模型
class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = torch.nn.Conv2d(1, 20, 5)
        self.relu1 = torch.nn.ReLU()
        self.conv2 = torch.nn.Conv2d(20, 50, 5)
        self.relu2 = torch.nn.ReLU()
        self.fc1 = torch.nn.Linear(4*4*50, 500)
        self.relu3 = torch.nn.ReLU()
        self.fc2 = torch.nn.Linear(500, 10)

    def forward(self, x):
        x = self.conv1(x)
        x = self.relu1(x)
        x = torch.nn.functional.max_pool2d(x, 2, 2)
        x = self.conv2(x)
        x = self.relu2(x)
        x = torch.nn.functional.max_pool2d(x, 2, 2)
        x = x.view(-1, 4*4*50)
        x = self.fc1(x)
        x = self.relu3(x)
        x = self.fc2(x)
        return x

# 初始化模型
net = Net()

# 定义损失函数和优化器
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

# 训练模型
for epoch in range(5):
    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        inputs, labels = data
        optimizer.zero_grad()
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        if i % 100 == 99:
            print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 100))
            running_loss = 0.0

print('Finished Training')
Python

通过在代码中添加os.environ["KMP_DUPLICATE_LIB_OK"] = "True"这行代码,我们解决了“RuntimeError: Placeholder storage has not been allocated on MPS device”错误。现在您可以在M1 Mac上顺利运行PyTorch代码了。

总结

本文介绍了如何在M1 Mac上安装和使用PyTorch,并解决可能遇到的“RuntimeError: Placeholder storage has not been allocated on MPS device”错误。通过按照提供的安装步骤来安装PyTorch,并在代码中添加环境变量设置,您可以在M1 Mac上成功运行PyTorch代码。PyTorch的强大功能和易用性使得它成为深度学习任务的理想选择,并且在M1 Mac上的支持使得开发人员可以更好地利用新一代的硬件平台。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册