For the complete documentation index, see llms.txt. This page is also available as Markdown.

ONNX Import

Importing ONNX models into SameDiff

ONNX Import

The nd4j-samediff-import-onnx module imports ONNX (Open Neural Network Exchange) models into SameDiff. After import, the model is a native SameDiff graph.

For pure inference without graph conversion, consider ONNX Runtime instead.


Maven Dependency

<dependency>
    <groupId>org.nd4j</groupId>
    <artifactId>nd4j-samediff-import-onnx</artifactId>
    <version>${dl4j.version}</version>
</dependency>

Exporting an ONNX Model

Most frameworks can export to ONNX. Common export patterns:

From PyTorch:

import torch
import torch.onnx

model = MyModel()
model.eval()
dummy_input = torch.randn(1, 3, 224, 224)

torch.onnx.export(
    model,
    dummy_input,
    "model.onnx",
    opset_version=11,
    input_names=["input"],
    output_names=["output"]
)

From Keras/TensorFlow:

From scikit-learn via sklearn-onnx:


Importing an ONNX Model

Use OnnxGraphMapper to import an ONNX file:

From an InputStream:


Running Inference

After import, provide values for each ONNX input by name:


Inspecting the Graph

To find input and output names in an ONNX model before or after import:

In Java, after import:


Supported ONNX Ops

The following ONNX operators are mapped to SameDiff:

Arithmetic:

  • Add, Sub, Mul, Div, Pow, Mod, Abs, Neg, Exp, Log, Sqrt, Ceil, Floor, Round

Linear algebra:

  • Gemm, MatMul, BatchMatMul

Activation functions:

  • Relu, Sigmoid, Tanh, Softmax, LogSoftmax, Elu, Selu, LeakyRelu, PRelu, HardSigmoid, HardSwish, Mish, Swish

Convolution:

  • Conv, ConvTranspose, DepthwiseConv

Pooling:

  • MaxPool, AveragePool, GlobalMaxPool, GlobalAveragePool, LpPool

Normalization:

  • BatchNormalization, InstanceNormalization, LayerNormalization, GroupNormalization

Recurrent:

  • LSTM, GRU, RNN

Shape manipulation:

  • Reshape, Transpose, Concat, Flatten, Squeeze, Unsqueeze, Expand, Tile, Pad

Indexing and slicing:

  • Gather, GatherElements, GatherND, Slice, ScatterElements, ScatterND, NonZero

Reduction:

  • ReduceSum, ReduceMean, ReduceMax, ReduceMin, ReduceProd, ReduceL1, ReduceL2

Type:

  • Cast, Identity, Constant, ConstantOfShape

Comparison:

  • Equal, Greater, GreaterOrEqual, Less, LessOrEqual, Not, And, Or, Where

Other:

  • Dropout (inference mode — passthrough), Shape, Size, Range, OneHot, EyeLike


Supported ONNX Opsets

The op mapper is tested against ONNX opsets 9 through 13. Most ops in these opsets are covered. Newer opset versions may introduce ops not yet mapped; use onnx.version_converter.convert_version() in Python to downgrade to opset 11 if needed.


Complete Example: ResNet-50 Inference


Troubleshooting

Op not supported: the ONNX model contains an operator with no registered mapper. Note the op name from the error and check whether it appears in the supported list above. File a GitHub issue for coverage gaps.

Input name not found: use the Python ONNX inspection snippet to find the exact input names. Names are case-sensitive.

Shape mismatch: ONNX models (especially those exported from PyTorch) typically use NCHW format [batch, channels, height, width]. Ensure your input INDArray is constructed in this layout.

Dynamic shapes: ONNX models with dim_value=0 (fully dynamic dimensions) may need concrete shapes provided at inference time. The importer handles most common patterns, but unusual dynamic shape expressions may require manual intervention.

Opset too new: if the model uses an opset version higher than 13, convert it to opset 11 in Python using onnx.version_converter.convert_version(model, 11) before importing.

Last updated

Was this helpful?