To convert a given PyTorch model to the ExecuTorch format, we first need to compile the model using torch.export. The API expects the first argument mod to be a torch.nn.Module. The API will call the forward method of the module to trace the computation graph.

When we load a sentence-transformer model, we notice that model indeed has a type of torch.nn.Module:

from sentence_transformers import SentenceTransformer
 
model = SentenceTransformer("models/all-minilm-l6-v2")
print(type(model))

We use torch.export on model:

sample_inputs = (  
    torch.zeros(1, 512, dtype=torch.int),  
    torch.zeros(1, 512, dtype=torch.int),  
    torch.zeros(1, 512, dtype=torch.int),  
)  
dynamic_shapes = {  
    "input_ids": {  
        1: Dim("seq_len", min=1, max=512)  
    },  
    "attention_mask": {  
        1: Dim("seq_len", min=1, max=512)  
    },  
    "token_type_ids": {  
        1: Dim("seq_len", min=1, max=512)  
    }  
}  
  
exported_program = export(model, sample_inputs, dynamic_shapes=dynamic_shapes)

the program crashes with the following error:

modality_name: Modality = features.get("modality", "text")
                              ^^^^^^^^^^^^
AttributeError: 'FakeTensor' object has no attribute 'get'
pip3 install sentence-transformers torch tokenizers executorch
import torch
from executorch.backends.xnnpack.partition.xnnpack_partitioner import XnnpackPartitioner
from executorch.exir import to_edge_transform_and_lower
from torch.export import Dim, export
from transformers.models import BertModel
 
# The following directory contains
# - pytorch_model.bin
# - config.json
# from https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2/tree/main
model = BertModel.from_pretrained("models/all-minilm-l6-v2")
 
sample_inputs = (
    torch.zeros(1, 512, dtype=torch.int),
    torch.zeros(1, 512, dtype=torch.int),
    torch.zeros(1, 512, dtype=torch.int),
)
dynamic_shapes = {
    "input_ids": {
        1: Dim("seq_len", min=1, max=512)
    },
    "attention_mask": {
        1: Dim("seq_len", min=1, max=512)
    },
    "token_type_ids": {
        1: Dim("seq_len", min=1, max=512)
    }
}
 
exported_program = export(model, sample_inputs, dynamic_shapes=dynamic_shapes)
executorch_program = to_edge_transform_and_lower(
    exported_program,
    partitioner = [XnnpackPartitioner()],
).to_executorch()
 
with open("model.pte", "wb") as file:
    file.write(executorch_program.buffer)