Here's the updated code with quantization added to reduce the model size significantly:
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import torch
import onnx
from huggingface_hub import HfApi, HfFolder
import os
# Install required packages for quantization
os.system("pip install onnxruntime onnx-simplifier")
from onnxruntime.quantization import quantize_dynamic, QuantType
# 1. Load model and tokenizer
model_name = "prdev/mini-gte"
model = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
# 2. Save tokenizer and config
os.makedirs("./model", exist_ok=True)
model.save_pretrained("./model")
tokenizer.save_pretrained("./model")
# 3. Export to ONNX
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 to temporary file first
torch.onnx.export(
model,
(input_ids, attention_mask),
"./model/model_fp32.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("Original model exported to ONNX format.")
# 4. Optimize with ONNX Simplifier
os.system("python -m onnxsim ./model/model_fp32.onnx ./model/model_optimized.onnx")
print("Model optimized with ONNX Simplifier.")
# 5. Quantize the model to INT8
quantize_dynamic(
model_input="./model/model_optimized.onnx",
model_output="./model/model.onnx",
weight_type=QuantType.QInt8,
optimize_model=True
)
print("Model quantized to INT8 precision.")
# 6. Clean up temporary files
os.remove("./model/model_fp32.onnx")
os.remove("./model/model_optimized.onnx")
# 7. Create a README.md file with model card
readme_content = """---
tags:
- onnx
- transformers
- sentence-embedding
- mini-gte
license: apache-2.0
language:
- en
library_name: transformers
pipeline_tag: sentence-similarity
---
# mini-gte (ONNX Quantized)
A lightweight, optimized version of the `mini-gte` model for **client-side inference** (browser/edge). Exported to ONNX and quantized to INT8 for compatibility with ONNX.js, Transformers.js, and other edge-friendly runtimes.
## 🚀 Features
- **ONNX Format**: Ready for browser/edge deployment.
- **INT8 Quantized**: Significantly reduced size with minimal accuracy loss.
- **Sentence Embeddings**: Generate embeddings for semantic search, clustering, etc.
## 📦 Files
```plaintext
model/
├── config.json
├── model.onnx (INT8 quantized)
├── tokenizer_config.json
├── special_tokens_map.json
└── vocab.txt
💻 Usage (Client-Side)
ONNX.js (Browser)
<script src="https://cdn.jsdelivr.net/npm/onnxjs@latest/dist/onnx.min.js"></script>
<script>
async function loadModel() {
const sess = await ort.InferenceSession.create(
"https://huggingface.co/RainbowPiBubbles/mini-gte-onnx/resolve/main/model.onnx"
);
const inputIds = new ort.Tensor("int64", new BigInt64Array([...]), [1, 128]); // Your input
const attentionMask = new ort.Tensor("int64", new BigInt64Array([...]), [1, 128]); // Your mask
const output = await sess.run({
input_ids: inputIds,
attention_mask: attentionMask
});
console.log(output); // Embeddings tensor
}
loadModel();
</script>