Exporting HybridBlock using ONNX format


#1

Hello,

Can you please explain how to export a network using onnx_mxnet.export_model without first writing symbolic graph and parameters to file system.
Right now I’m doing it with the following code

import mxnet as mx
from mxnet import nd, gluon
from mxnet.contrib import onnx as onnx_mxnet

net = gluon.nn.Dense(1, in_units=2)
net.collect_params().initialize()
net.hybridize()
net(nd.array([[4,7]]))
net.export('model', epoch=1)
onnx_mxnet.export_model('model-symbol.json', 'model-0001.params', [(1,2)])

In the MXNet ONNX documentation for onnx_mxnet.export_model it is stated that

Parameters:

  • sym ( str or symbol object ) – Path to the json file or Symbol object
  • params ( str or symbol object ) – Path to the params file or params dictionary. (Including both arg_params and aux_params)

What are Symbol object and params dictionary and how can I extract them conveniently from net ?


#2

Change last line to:

onnx_mxnet.export_model(
    sym=net(sym.var('data')),
    params={k: v._reduce() for k, v in net.collect_params().items()},
    input_shape=[(1, 2)])

#3

Maybe better to replace v._reduce() with v.data(ctx=mx.cpu())


#4

Parameter._reduce() is different than Parameter.data(ctx), with former properly reducing the NDArrays across all contexts into a single NDArray on CPU, and the latter returning an existing NDArray on the requested context. So, for example, if parameter is only initialized on GPU, calling data(mx.cpu()) should return an error.