Check if ONNX Model is Valid using Python

Check if ONNX Model is Valid using Python

When working with ONNX models, it's important to ensure their validity before deployment to avoid potential errors or inconsistencies. By catching validation errors early on, we can save time and effort in debugging and troubleshooting during the deployment phase. Also, validating the model helps ensure the integrity and correctness of the model's structure. This tutorial explains how to check if ONNX model is valid using Python.

Prepare environment

  • Install the following package using pip:
pip install onnx

Code

In the following code, we define a function which takes a single argument, representing the file path to the ONNX model. In the function, we load the ONNX model from the specified file path. Inside a try block, the check_model function is called to validate the loaded ONNX model. If the model is invalid, an exception is raised. If no validation errors occur during the try block, the True value is returned, otherwise False.

import onnx


def is_onnx_model_valid(path):
    model = onnx.load(path)
    try:
        onnx.checker.check_model(model)
    except onnx.checker.ValidationError:
        return False
    return True


print(is_onnx_model_valid('model.onnx'))

When running the provided code, in the console you might see either True or False depending on the validity of the ONNX model.

Leave a Comment

Cancel reply

Your email address will not be published.