Downloads · 30 days
0
jinaai/xlm-roberta-flash-implementation-onnx
xlm-roberta-flash-implementation-onnx is a machine learning model from jinaai. Use it for the machine learning task on the model card, and read the license before you ship it in a product. It is set up for transformers. The card lists the license as cc-by-nc-4.0.
Modified version of xlm-roberta-flash-implementation for the onnx conversion
Downloads · 30 days
0
Access
Public
Updated Sep 16, 2024
Repo size
—
Likes
0
Public
Click a slice to open those files.
.py176 KB · 97%
From the Hugging Face model README
Modified version of xlm-roberta-flash-implementation for the onnx conversion
The original RoPE implementation did not compute the entire rotation matrix at the start. Instead, it calculated the matrix only for the required sequence length, cached it, and recalculated if a longer sequence came as input. This approach isn't compatible with ONNX, which requires a fixed graph during inference. To solve this, I now calculate the entire rotation matrix in advance.
We have custom forward and backward functions for RoPE. ONNX does not support custom backward functions, but since we only need forward passes for inference with ONNX, I removed the backward function completely.
ONNX stores the model in a protobuf format, which has a maximum size limit of 2GB. Our model was too large to fit this limit, so I had to store the model's parameters as external data files.
unique() FunctionWe used the unique() function to identify unique task types in a batch, which is important when there are multiple task types. However, ONNX does not support the unique() function. For inference, having multiple task types in a batch is not important. Therefore, I modified the code to use the task_id argument—an integer that works for every text in a batch—instead of the adapter_mask, which was a tensor specifying an independent task ID for each text in the batch.
import torch
from transformers import AutoModel, AutoTokenizer
import torch.onnx
model = AutoModel.from_pretrained('/home/admin/saba/jina-embeddings-v3', trust_remote_code=True, use_flash_attn=False)
model.eval()
onnx_path = "/home/admin/saba/jina-embeddings-v3/onnx/model.onnx"
tokenizer = AutoTokenizer.from_pretrained('/home/admin/saba/jina-embeddings-v3')
inputs = tokenizer(["jina", 'ai'], return_tensors="pt", padding='longest')
inps = inputs['input_ids']
mask = inputs['attention_mask']
task_id = 2
torch.onnx.export(
model,
(inps, mask, task_id),
onnx_path,
export_params=True,
do_constant_folding=True,
input_names = ['input_ids', 'attention_mask', 'task_id'],
output_names = ['text_embeds'],
opset_version=16,
dynamic_axes={
'input_ids' : {0 : 'batch_size', 1: 'sequence_length'},
'attention_mask' : {0 : 'batch_size', 1: 'sequence_length'},
'text_embeds' : {0 : 'batch_size'}
},
)