laich f7b6b6eff6 | 5 days ago | |
---|---|---|
doc | 3 months ago | |
mindtorch | 5 days ago | |
testing | 2 months ago | |
third_party/einops | 10 months ago | |
.drone.yml | 5 months ago | |
.gitignore | 6 months ago | |
.readthedocs.yaml | 6 months ago | |
LICENSE | 2 years ago | |
README.md | 4 months ago | |
README.rst | 5 months ago | |
README_en.md | 4 months ago | |
pylint_check.sh | 10 months ago | |
pylintrc | 1 year ago | |
requirements.txt | 5 months ago | |
run.sh | 10 months ago | |
setup.py | 1 week ago |
简体中文 | English
MSAdapter是一款MindSpore生态适配工具,在不改变用户原有使用习惯下,将PyTorch/JAX等三方框架代码快速迁移到MindSpore生态上,帮助用户高效使用中国算力网——智算网络的昇腾算力。
MindTorch是将PyTorch训练脚本高效迁移至MindSpore框架执行的工具,其目的是在不改变原有PyTorch用户的使用习惯情况下,使得PyTorch代码能在昇腾上获得高效性能。
有关安装指南、教程和API的更多详细信息,请参阅教程文档。
首先查看版本说明选择所需的MindTorch和MindSpore版本。
请根据MindSpore官网安装指南进行安装。
pip install mindtorch (MindSpore版本 >= 2.2.1)
或
pip install msadapter (MindSpore版本 == 2.0.0)
git clone https://git.openi.org.cn/OpenI/MSAdapter.git
cd MSAdapter
python setup.py install
如果出现权限不足的提示,请按照如下方式安装:
python setup.py install --user || exit 1
安装好MindTorch后, 你可以按照以下方式使用它:
from mindtorch.tools import mstorch_enable # 需要在主入口文件导入torch相关模块的前面使用
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor
# 1.Working with data
# Download training data from open datasets.
training_data = datasets.FashionMNIST(root="data", train=True, download=True, transform=ToTensor())
# Download test data from open datasets.
test_data = datasets.FashionMNIST(root="data", train=False, download=True, transform=ToTensor())
# 2.Creating Models
class NeuralNetwork(nn.Module):
def __init__(self):
super().__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28*28, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 10)
)
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
def train(dataloader, model, loss_fn, optimizer, device):
size = len(dataloader.dataset)
model.train()
for batch, (X, y) in enumerate(dataloader):
X, y = X.to(device), y.to(device)
# Compute prediction error
pred = model(X)
loss = loss_fn(pred, y)
# Backpropagation
loss.backward()
optimizer.step()
optimizer.zero_grad()
if batch % 100 == 0:
loss, current = loss.item(), (batch + 1) * len(X)
print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
def test(dataloader, model, loss_fn, device):
size = len(dataloader.dataset)
num_batches = len(dataloader)
model.eval()
test_loss, correct = 0, 0
with torch.no_grad():
for X, y in dataloader:
X, y = X.to(device), y.to(device)
pred = model(X)
test_loss += loss_fn(pred, y).item()
correct += (pred.argmax(1) == y).type(torch.float).sum().item()
test_loss /= num_batches
correct /= size
print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
if __name__ == '__main__':
train_dataloader = DataLoader(training_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)
# Get cpu, gpu or mps device for training.
device = (
"cuda"
if torch.cuda.is_available()
else "mps"
if torch.backends.mps.is_available()
else "cpu"
)
model = NeuralNetwork().to(device)
# 3.Optimizing the Model Parameters
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
epochs = 5
for t in range(epochs):
print(f"Epoch {t+1}\n-------------------------------")
train(train_dataloader, model, loss_fn, optimizer, device)
test(test_dataloader, model, loss_fn, device)
print("Done!")
# 4.Saving Models
torch.save(model.state_dict(), "model.pth")
print("Saved PyTorch Model State to model.pth")
# 5.Loading Models
model = NeuralNetwork().to(device)
model.load_state_dict(torch.load("model.pth"))
classes = [
"T-shirt/top",
"Trouser",
"Pullover",
"Dress",
"Coat",
"Sandal",
"Shirt",
"Sneaker",
"Bag",
"Ankle boot",
]
# 6.Predicted
model.eval()
x, y = test_data[0][0], test_data[0][1]
with torch.no_grad():
x = x.to(device)
pred = model(x)
predicted, actual = classes[pred[0].argmax(0)], classes[y]
print(f'Predicted: "{predicted}", Actual: "{actual}"')
导入mstorch_enable后,代码执行时torch同名的导入模块会自动被转换为mindtorch相应的模块(目前支持torch、torchvision、torchaudio相关模块的自动转换),接下来执行主入口的.py文件即可。更多的使用方式可以参考使用指南
分支名 | 发布版本 | 发布时间 | 配套MindSpore版本 | 启智算力资源 |
---|---|---|---|---|
master | - | - | MindSpore 2.3.0 | - |
release_0.3 | 0.3 | 2024-04-29 | MindSpore 2.3.0-rc1 | 智算网络集群 - 镜像:mindtorch0.3_mindspore2.3.0_torchnpu2.2.0_cann8.0 |
release_0.2 | 0.2.1 | 2024-02-01 | MindSpore 2.2.1 / MindSpore 2.2.10 | - |
release_0.1 | 0.1 | 2023-06-15 | MindSpore 2.0.0 | - |
中间版本:
pip install git+https://openi.pcl.ac.cn/OpenI/MSAdapter.git@da13b6719c
pip install git+https://openi.pcl.ac.cn/OpenI/MSAdapter.git@59f62a1858
欢迎开发者参与贡献。更多详情,请参阅我们的贡献指南.
如果您在使用时有任何问题或建议,欢迎加入MSAdapter SIG参与讨论。
MindSpore对PyTorch接口的支持工具
Python Markdown
Dear OpenI User
Thank you for your continuous support to the Openl Qizhi Community AI Collaboration Platform. In order to protect your usage rights and ensure network security, we updated the Openl Qizhi Community AI Collaboration Platform Usage Agreement in January 2024. The updated agreement specifies that users are prohibited from using intranet penetration tools. After you click "Agree and continue", you can continue to use our services. Thank you for your cooperation and understanding.
For more agreement content, please refer to the《Openl Qizhi Community AI Collaboration Platform Usage Agreement》