You are encountering this error because the onnx Python package is required by torch.onnx.export, but it's not included in your initial !pip install command.
The line ModuleNotFoundError: No module named 'onnx' confirms this.
To fix this, you need to install the onnx package.
Here's the corrected code:
!pip install transformers torch onnx # Add onnx to the installation command
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import torch
import torch.onnx as onnx
import onnx # Import the onnx package as well (though not strictly necessary for *this* fix, good practice if you plan to load/check the ONNX model)
# Model and tokenizer loading
model_name = "prdev/mini-gte"
model = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
# Set the model to evaluation mode
model.eval()
# Create dummy input tensors
batch_size = 1
seq_length = 128
input_ids = torch.ones(batch_size, seq_length, dtype=torch.long)
attention_mask = torch.ones(batch_size, seq_length, dtype=torch.long)
# Define the output filename
output_filename = f"{model_name.split('/')[-1]}.onnx"
# Export the model to ONNX with opset_version=14
try:
torch.onnx.export(
model,
(input_ids, attention_mask),
output_filename,
export_params=True,
opset_version=14,
do_constant_folding=True,
input_names=['input_ids', 'attention_mask'],
output_names=['output'],
dynamic_axes={
'input_ids': {0: 'batch_size', 1: 'sequence_length'},
'attention_mask': {0: 'batch_size', 1: 'sequence_length'},
'output': {0: 'batch_size'}
}
)
print(f"Model has been converted to ONNX and saved as {output_filename}")
except Exception as e:
print(f"An error occurred during ONNX export: {e}")
# Optional: Verify the ONNX model
try:
onnx_model = onnx.load(output_filename)
onnx.checker.check_model(onnx_model)
print("ONNX model checked successfully!")
except Exception as e:
print(f"Error checking ONNX model: {e}")
Explanation of the Fix:
!pip install transformers torch onnx: Added onnx to the installation command. This ensures that the necessary onnx library is available before torch.onnx.export tries to use it.
import onnx: Added import onnx. While torch.onnx.export handles the internal usage, explicitly importing onnx is good practice and required if you later want to load or check the generated .onnx file (as shown in the optional verification block).