我正在尝试运行 ONNX 模型
import onnxruntime as ort
import onnxruntime.backend
model_path = "model.onnx"
#https://microsoft.github.io/onnxruntime/
ort_sess = ort.InferenceSession(model_path)
print( ort.get_device() )
Run Code Online (Sandbox Code Playgroud)
这打印出来
cpu
Run Code Online (Sandbox Code Playgroud)
我怎样才能让它在我的 GPU 上运行?我如何确认它正在工作?
我已通过以下方式将模型导出到 ONNX:
# Export the model
torch_out = torch.onnx._export(learn.model, # model being run
x, # model input (or a tuple for multiple inputs)
EXPORT_PATH + "mnist.onnx", # where to save the model (can be a file or file-like object)
export_params=True) # store the trained parameter weights inside the model file
Run Code Online (Sandbox Code Playgroud)
现在我正在尝试将模型转换为 Tensorflow Lite 文件,以便我可以在 Android 上进行推理。不幸的是,PyTorch/Caffe2 对 Android 的支持相当缺乏或过于复杂,但 Tensorflow 看起来要简单得多。
ONNX 到 Tflite 的文档对此非常清楚。
我尝试通过以下方式导出到 Tensorflow GraphDef proto:
tf_rep.export_graph(EXPORT_PATH + 'mnist-test/mnist-tf-export.pb')
然后运行toco
:
toco \
--graph_def_file=mnist-tf-export.pb \
--input_format=TENSORFLOW_GRAPHDEF …
Run Code Online (Sandbox Code Playgroud) 我在 Matlab 2019b 中训练了一个 CNN,它将图像分为三个类别。当这个 CNN 在 Matlab 中进行测试时,它运行良好,只需要 10-15 秒就可以对图像进行分类。我在 Maltab 中使用了 exportONNXNetwork 函数,以便我可以在 Tensorflow 中实现我的 CNN。这是我用来在 python 中使用 ONNX 文件的代码:
import onnx
from onnx_tf.backend import prepare
import numpy as np
from PIL import Image
onnx_model = onnx.load('trainednet.onnx')
tf_rep = prepare(onnx_model)
filepath = 'filepath.png'
img = Image.open(filepath).resize((224,224)).convert("RGB")
img = array(img).transpose((2,0,1))
img = np.expand_dims(img, 0)
img = img.astype(np.uint8)
probabilities = tf_rep.run(img)
print(probabilities)
Run Code Online (Sandbox Code Playgroud)
当尝试使用此代码对同一测试集进行分类时,它似乎对图像进行了正确分类,但速度非常慢,并且在某些点达到高达 95+% 的高内存使用率时会冻结我的计算机。
我还在命令提示符下对它进行分类时注意到它打印:
2020-04-18 18:26:39.214286: W tensorflow/core/grappler/optimizers/meta_optimizer.cc:530] constant_folding failed: Deadline exceeded: constant_folding exceeded deadline., time = 486776.938ms. …
Run Code Online (Sandbox Code Playgroud) 我正在学习这个新的 ONNX 框架,它允许我们将深度学习(和其他)模型部署到生产中。
然而,我缺少一件事。我认为拥有这样一个框架的主要原因是为了推理目的,例如当我们有一个经过训练的模型并希望在不同的 venv 中使用它时(例如我们不能拥有 PyTorch),该模型仍然可以使用。
我在这里准备了一个“从头开始”的例子:
# Modules
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader, TensorDataset
import torchvision
import onnx
import onnxruntime
import matplotlib.pyplot as plt
import numpy as np
# %config Completer.use_jedi = False
# MNIST Example dataset
train_loader = torch.utils.data.DataLoader(
torchvision.datasets.MNIST(
'data', train=True, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
])),
batch_size=800)
# Take data and labels "by hand"
inputs_batch, labels_batch = next(iter(train_loader))
# Simple Model
class CNN(nn.Module):
def …
Run Code Online (Sandbox Code Playgroud) 最近更新到 tensorflow 2.0 并且无法将我的 .h5 模型转换为 .onnx 。曾经是一个非常简单的程序,但现在我遇到了问题。当我运行以下代码时:
# onnx testing
import onnx
import keras2onnx
import os
import tensorflow as tf
from tensorflow.keras.models import load_model
folder = r'\\rdnas'
os.chdir(folder)
#os.environ["TF_KERAS"]='1'
model_loc = folder+'\\model.h5'
model = tf.keras.models.load_model(model_loc)
model.summary()
# Onnx covnersion
onnx_model = keras2onnx.convert_keras(model)
temp_model_file = 'model.onnx'
onnx.save_model(onnx_model, temp_model_file)
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,出现以下错误
Using TensorFlow backend.
Can't import tf2onnx module, so the conversion on a model with any custom/lambda layer will fail!
Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
DVA_input (Dense) …
Run Code Online (Sandbox Code Playgroud) 我已经训练了检测算法并保存了我最好的模型。现在我想将我的模型(预训练)转换为 C++ 并在我的应用程序中使用它。我想知道将 pyTorch 模型转换为 C++ 的可能方法是什么?
谢谢!
我正在尝试将 HuggingFace 变压器模型中的 Pegasus 新闻编辑室转换为 ONNX 格式。我遵循了Huggingface 发布的指南。安装先决条件后,我运行了以下代码:
!rm -rf onnx/
from pathlib import Path
from transformers.convert_graph_to_onnx import convert
convert(framework="pt", model="google/pegasus-newsroom", output=Path("onnx/google/pegasus-newsroom.onnx"), opset=11)
Run Code Online (Sandbox Code Playgroud)
并得到这些错误:
ValueError Traceback (most recent call last)
<ipython-input-9-3b37ed1ceda5> in <module>()
3 from transformers.convert_graph_to_onnx import convert
4
----> 5 convert(framework="pt", model="google/pegasus-newsroom", output=Path("onnx/google/pegasus-newsroom.onnx"), opset=11)
6
7
6 frames
/usr/local/lib/python3.6/dist-packages/transformers/models/pegasus/modeling_pegasus.py in forward(self, input_ids, attention_mask, encoder_hidden_states, encoder_attention_mask, head_mask, encoder_head_mask, past_key_values, inputs_embeds, use_cache, output_attentions, output_hidden_states, return_dict)
938 input_shape = inputs_embeds.size()[:-1]
939 else:
--> 940 raise ValueError("You have to specify either …
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 onnx 将detr 模型转换为张量流。torch.onnx.export
我使用opset_version=12转换了模型。(它生成一个detr.onnx
文件)
然后我尝试使用此示例将 onnx 文件转换为张量流模型。我添加了onnx.check_model
一行以确保模型正确加载。
import math
from PIL import Image
import requests
import matplotlib.pyplot as plt
import torch
from torch import nn
from torchvision.models import resnet50
import onnx
from onnx_tf.backend import prepare
import torchvision.transforms as T
torch.set_grad_enabled(False)
model = torch.hub.load('facebookresearch/detr', 'detr_resnet50', pretrained=True)
url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
im = Image.open(requests.get(url, stream=True).raw)
transform = T.Compose([
T.Resize(800),
T.ToTensor(),
T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
img = transform(im).unsqueeze(0)
torch.onnx.export(model, img, 'detr.onnx', opset_version = 12) …
Run Code Online (Sandbox Code Playgroud) C = torch.cat((A,B),1)
Run Code Online (Sandbox Code Playgroud)
张量的形状:
A is (1, 128, 128, 256)
B is (1, 1, 128, 256)
Run Code Online (Sandbox Code Playgroud)
预期C
值为(1, 129, 128, 256)
这段代码可以在pytorch上运行,但是在转换为core-ml时会出现以下错误:
"Error while converting op of type: {}. Error message: {}\n".format(node.op_type, err_message, )
TypeError: Error while converting op of type: Concat. Error message: unable to translate constant array shape to CoreML shape"
Run Code Online (Sandbox Code Playgroud) 我正在边缘设备(使用 NVIDIA GTX 1080)上运行 Mask R-CNN 模型。我目前正在使用 Detectron2 Mask R-CNN 实现,并且我的推理速度约为 5 FPS。
为了加快速度,我查看了其他推理引擎和模型实现。例如 ONNX,但我无法获得更快的推理速度。
TensorRT 对我来说看起来很有希望,但我没有找到一个现成的“开箱即用”的实现。
是否有其他成熟且快速的推理引擎或其他技术来加速推理?
onnx ×10
pytorch ×6
tensorflow ×5
python ×4
keras ×2
onnx-coreml ×2
c++ ×1
cnn ×1
matlab ×1
numpy ×1
onnxruntime ×1
python-3.x ×1
spyder ×1