To upload your ONNX model and related files to Hugging Face using your write token, and to ensure it's ready for client-side use (e.g., with JavaScript or ONNX.js), follow this structured approach.
✅ Prerequisites
Before proceeding, ensure you have the following installed in your environment:
pip install huggingface_hub transformers torch onnx
You’ll also need your Hugging Face write token. Never hardcode it in scripts. Instead, use the Hugging Face CLI to authenticate:
huggingface-cli login
This will prompt you to enter your token and store it securely.
📁 File Structure
To make your model fully usable, ensure the following files are included:
model.onnx (your exported ONNX model)
config.json (model configuration)
tokenizer_config.json (tokenizer configuration)
special_tokens_map.json (special tokens)
vocab.txt or tokenizer.json (tokenizer vocabulary)
README.md (optional, but recommended)
These files are typically generated when you save the model and tokenizer using save_pretrained().
🧠 Step-by-Step Code
Here's a complete script that:
- Saves the tokenizer and configuration.
- Uploads the model and files to Hugging Face.
- Uses the Hugging Face Hub API with your token.
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import torch
import onnx
from huggingface_hub import HfApi, HfFolder
# 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
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)
torch.onnx.export(
model,
(input_ids, attention_mask),
"./model/model.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("Model and files saved locally.")
# 4. Upload to Hugging Face
api = HfApi()
repo_id = "your-username/your-model-name" # Replace with your repo name
# Upload files
api.upload_folder(
repo_id=repo_id,
folder_path="./model",
commit_message="Upload ONNX model and assets"
)
print(f"Model uploaded to https://huggingface.co/{repo_id}")
🧪 Client-Side Usage (JavaScript)
If you're using this on a client-side website, you can load the model via ONNX.js or Hugging Face's Transformers.js (if the model is in the correct format). Here's a quick example using ONNX.js:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/onnxjs@1.0.0/dist/onnx.min.js"></script>
</head>
<body>
<script>
async function loadModel() {
const model = await ort.InferenceSession.create("https://huggingface.co/your-username/your-model-name/resolve/main/model.onnx");
const input = new Float32Array([...]); // Your input tensor
const output = await model.run({ input_ids: input, attention_mask: input });
console.log(output);
}
loadModel();
</script>
</body>
</html>
🔒 Security Tip
Never hardcode your Hugging Face token in scripts. Use the huggingface-cli login command to store it securely.
📝 Final Notes
- Ensure your model is compatible with the intended client-side framework (ONNX.js, Transformers.js, etc.).
- If you're using the Hugging Face Transformers.js library, you may need to retrain or convert the model to the
.bin format instead of ONNX.
- Always test your model locally before uploading.
Let me know if you need help with the JavaScript side or converting the model to a different format!