Error Explanation
The error message indicates that the onnx module is not installed, which is required by PyTorch for exporting models to the ONNX format. Although you've installed transformers and torch, onnx is a separate package that needs to be installed explicitly.
Solution
You need to install the onnx package. Run the following command in your environment:
!pip install onnx
Updated Installation Block
To avoid similar issues in the future, install all required packages at once:
!pip install transformers torch onnx
Full Corrected Code
Here's your updated code block with all necessary installations:
# Install necessary packages
!pip install transformers torch onnx
# Import necessary libraries
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import torch
import torch.onnx as onnx
# 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)
# Export the model to ONNX with opset_version=14
torch.onnx.export(
model,
(input_ids, attention_mask),
f"{model_name.split('/')[-1]}.onnx",
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 {model_name.split('/')[-1]}.onnx")
Additional Tips
- Virtual Environments: Consider using virtual environments (e.g.,
venv, conda) to manage your packages. This helps avoid version conflicts and keeps your global Python environment clean.
- Requirements Files: For projects, create a
requirements.txt file listing all dependencies (e.g., transformers, , ). Then, install them all at once with .