pytoch M2芯片测试

2023-10-12 08:28
文章标签 芯片 测试 m2 pytoch

本文主要是介绍pytoch M2芯片测试,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

今天才发现我的新片是M2芯片,而不是M1芯片,有点尴尬
在这里插入图片描述
参考网址
https://www.oldcai.com/ai/pytorch-train-MNIST-with-gpu-on-mac/

测试结果如下

M2_cpu.py

# https://www.oldcai.com/ai/pytorch-train-MNIST-with-gpu-on-mac/
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision.datasets import MNIST
from torchvision.transforms import ToTensorprint(f"PyTorch version: {torch.__version__}")# Check PyTorch has access to MPS (Metal Performance Shader, Apple's GPU architecture)
print(f"Is MPS (Metal Performance Shader) built? {torch.backends.mps.is_built()}")
print(f"Is MPS available? {torch.backends.mps.is_available()}")# Set the device
device = "cpu"
device = torch.device(device)
print(f"Using device: {device}")# Define the CNN model
class HandwritingRecognitionModel(nn.Module):def __init__(self):super().__init__()# Define the convolutional layersself.conv1 = nn.Conv2d(1, 16, kernel_size=3, padding=1)self.conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1)# Define the pooling and dropout layersself.pool = nn.MaxPool2d(2, 2)self.dropout1 = nn.Dropout(0.25)self.dropout2 = nn.Dropout(0.5)# Define the fully connected layersself.fc1 = nn.Linear(32 * 7 * 7, 128)self.fc2 = nn.Linear(128, 10)def forward(self, x):# Pass the input through the convolutional layersx = self.conv1(x)x = self.pool(x)x = self.dropout1(x)x = self.conv2(x)x = self.pool(x)x = self.dropout2(x)# Reshape the output for the fully connected layersx = x.view(-1, 32 * 7 * 7)# Pass the output through the fully connected layersx = self.fc1(x)x = self.fc2(x)# Return the final outputreturn x# Load the MNIST dataset
train_dataset = MNIST("./data", train=True, download=True, transform=ToTensor())
test_dataset = MNIST("./data", train=False, download=True, transform=ToTensor())# Define the data loaders
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)# Define the model
model = HandwritingRecognitionModel().to(device)# Define the loss function and optimizer
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)from time import time 
t0 = time()
# Train the model for 10 epochs
for epoch in range(10):# Set the model to training modemodel.train()# Iterate over the training datafor images, labels in train_loader:images, labels = images.to(device), labels.to(device)# Pass the input through the modeloutputs = model(images)# Compute the lossloss = loss_fn(outputs, labels)# Backpropagate the errorloss.backward()# Update the model parametersoptimizer.step()# Set the model to evaluation modemodel.eval()# Evaluate the model on the validation setwith torch.no_grad():correct = 0total = 0for images, labels in test_loader:images, labels = images.to(device), labels.to(device)# Pass the input through the modeloutputs = model(images)# Get the predicted labels_, predicted = torch.max(outputs.data, 1)# Update the total and correct countstotal += labels.size(0)correct += (predicted == labels).sum()# Print the accuracyprint(f"Epoch {epoch + 1}: Accuracy = {100 * correct / total:.2f}%")t1 =time()
print("10 epoch cost {}s".format(t1-t0))

结果如下
在这里插入图片描述

M2_MPS.py

import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision.datasets import MNIST
from torchvision.transforms import ToTensorprint(f"PyTorch version: {torch.__version__}")# Check PyTorch has access to MPS (Metal Performance Shader, Apple's GPU architecture)
print(f"Is MPS (Metal Performance Shader) built? {torch.backends.mps.is_built()}")
print(f"Is MPS available? {torch.backends.mps.is_available()}")# Set the device
device = "mps" if torch.backends.mps.is_available() else "cpu"
device = torch.device(device)
print(f"Using device: {device}")# Define the CNN model
class HandwritingRecognitionModel(nn.Module):def __init__(self):super().__init__()# Define the convolutional layersself.conv1 = nn.Conv2d(1, 16, kernel_size=3, padding=1)self.conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1)# Define the pooling and dropout layersself.pool = nn.MaxPool2d(2, 2)self.dropout1 = nn.Dropout(0.25)self.dropout2 = nn.Dropout(0.5)# Define the fully connected layersself.fc1 = nn.Linear(32 * 7 * 7, 128)self.fc2 = nn.Linear(128, 10)def forward(self, x):# Pass the input through the convolutional layersx = self.conv1(x)x = self.pool(x)x = self.dropout1(x)x = self.conv2(x)x = self.pool(x)x = self.dropout2(x)# Reshape the output for the fully connected layersx = x.view(-1, 32 * 7 * 7)# Pass the output through the fully connected layersx = self.fc1(x)x = self.fc2(x)# Return the final outputreturn x# Load the MNIST dataset
train_dataset = MNIST("./data", train=True, download=True, transform=ToTensor())
test_dataset = MNIST("./data", train=False, download=True, transform=ToTensor())# Define the data loaders
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)# Define the model
model = HandwritingRecognitionModel().to(device)# Define the loss function and optimizer
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)from time import time 
t0 = time()
# Train the model for 10 epochs
for epoch in range(10):# Set the model to training modemodel.train()# Iterate over the training datafor images, labels in train_loader:images, labels = images.to(device), labels.to(device)# Pass the input through the modeloutputs = model(images)# Compute the lossloss = loss_fn(outputs, labels)# Backpropagate the errorloss.backward()# Update the model parametersoptimizer.step()# Set the model to evaluation modemodel.eval()# Evaluate the model on the validation setwith torch.no_grad():correct = 0total = 0for images, labels in test_loader:images, labels = images.to(device), labels.to(device)# Pass the input through the modeloutputs = model(images)# Get the predicted labels_, predicted = torch.max(outputs.data, 1)# Update the total and correct countstotal += labels.size(0)correct += (predicted == labels).sum()# Print the accuracyprint(f"Epoch {epoch + 1}: Accuracy = {100 * correct / total:.2f}%")t1 =time()
print("10 epoch cost {}s".format(t1-t0))

结果如下
在这里插入图片描述

这篇关于pytoch M2芯片测试的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/194569

相关文章

SpringBoot中整合RabbitMQ(测试+部署上线最新完整)的过程

《SpringBoot中整合RabbitMQ(测试+部署上线最新完整)的过程》本文详细介绍了如何在虚拟机和宝塔面板中安装RabbitMQ,并使用Java代码实现消息的发送和接收,通过异步通讯,可以优化... 目录一、RabbitMQ安装二、启动RabbitMQ三、javascript编写Java代码1、引入

Nginx设置连接超时并进行测试的方法步骤

《Nginx设置连接超时并进行测试的方法步骤》在高并发场景下,如果客户端与服务器的连接长时间未响应,会占用大量的系统资源,影响其他正常请求的处理效率,为了解决这个问题,可以通过设置Nginx的连接... 目录设置连接超时目的操作步骤测试连接超时测试方法:总结:设置连接超时目的设置客户端与服务器之间的连接

如何测试计算机的内存是否存在问题? 判断电脑内存故障的多种方法

《如何测试计算机的内存是否存在问题?判断电脑内存故障的多种方法》内存是电脑中非常重要的组件之一,如果内存出现故障,可能会导致电脑出现各种问题,如蓝屏、死机、程序崩溃等,如何判断内存是否出现故障呢?下... 如果你的电脑是崩溃、冻结还是不稳定,那么它的内存可能有问题。要进行检查,你可以使用Windows 11

性能测试介绍

性能测试是一种测试方法,旨在评估系统、应用程序或组件在现实场景中的性能表现和可靠性。它通常用于衡量系统在不同负载条件下的响应时间、吞吐量、资源利用率、稳定性和可扩展性等关键指标。 为什么要进行性能测试 通过性能测试,可以确定系统是否能够满足预期的性能要求,找出性能瓶颈和潜在的问题,并进行优化和调整。 发现性能瓶颈:性能测试可以帮助发现系统的性能瓶颈,即系统在高负载或高并发情况下可能出现的问题

字节面试 | 如何测试RocketMQ、RocketMQ?

字节面试:RocketMQ是怎么测试的呢? 答: 首先保证消息的消费正确、设计逆向用例,在验证消息内容为空等情况时的消费正确性; 推送大批量MQ,通过Admin控制台查看MQ消费的情况,是否出现消费假死、TPS是否正常等等问题。(上述都是临场发挥,但是RocketMQ真正的测试点,还真的需要探讨) 01 先了解RocketMQ 作为测试也是要简单了解RocketMQ。简单来说,就是一个分

【测试】输入正确用户名和密码,点击登录没有响应的可能性原因

目录 一、前端问题 1. 界面交互问题 2. 输入数据校验问题 二、网络问题 1. 网络连接中断 2. 代理设置问题 三、后端问题 1. 服务器故障 2. 数据库问题 3. 权限问题: 四、其他问题 1. 缓存问题 2. 第三方服务问题 3. 配置问题 一、前端问题 1. 界面交互问题 登录按钮的点击事件未正确绑定,导致点击后无法触发登录操作。 页面可能存在

业务中14个需要进行A/B测试的时刻[信息图]

在本指南中,我们将全面了解有关 A/B测试 的所有内容。 我们将介绍不同类型的A/B测试,如何有效地规划和启动测试,如何评估测试是否成功,您应该关注哪些指标,多年来我们发现的常见错误等等。 什么是A/B测试? A/B测试(有时称为“分割测试”)是一种实验类型,其中您创建两种或多种内容变体——如登录页面、电子邮件或广告——并将它们显示给不同的受众群体,以查看哪一种效果最好。 本质上,A/B测

Verybot之OpenCV应用一:安装与图像采集测试

在Verybot上安装OpenCV是很简单的,只需要执行:         sudo apt-get update         sudo apt-get install libopencv-dev         sudo apt-get install python-opencv         下面就对安装好的OpenCV进行一下测试,编写一个通过USB摄像头采

BIRT 报表的自动化测试

来源:http://www.ibm.com/developerworks/cn/opensource/os-cn-ecl-birttest/如何为 BIRT 报表编写自动化测试用例 BIRT 是一项很受欢迎的报表制作工具,但目前对其的测试还是以人工测试为主。本文介绍了如何对 BIRT 报表进行自动化测试,以及在实际项目中的一些测试实践,从而提高了测试的效率和准确性 -------

可测试,可维护,可移植:上位机软件分层设计的重要性

互联网中,软件工程师岗位会分前端工程师,后端工程师。这是由于互联网软件规模庞大,从业人员众多。前后端分别根据各自需求发展不一样的技术栈。那么上位机软件呢?它规模小,通常一个人就能开发一个项目。它还有必要分前后端吗? 有必要。本文从三个方面论述。分别是可测试,可维护,可移植。 可测试 软件黑盒测试更普遍,但很难覆盖所有应用场景。于是有了接口测试、模块化测试以及单元测试。都是通过降低测试对象