Integrate with Sentence Transformers

#2
by tomaarsen HF Staff - opened

Hello @umberto-tomasini , @juliendenize and team!

Congratulations on your release! Outperforming EG2 so quickly after it released is quite impressive. I think it would be valuable for the community if this model was also supported by Sentence Transformers, like those models this is now beating (Qwen3-VL, EG2, etc.), so I had my agent add support for it through the standard Sentence Transformers interface. It works rather well, much like standard CLIP (except with video of course).

There's really only ~2 changes:

  • in modeling, we now ensure the inputs are cast correctly. This is an oversight in ST as it doesn't nicely cast lists of Tensors.
  • add a processing file for the video processing (based on your README) and the AutoProcessor.

Plus some ST-specific configuration to tell it which modules to load & how to forward inputs.

Also, my README and this PR description currently use Wikipedia images directly as your GitHub currently still 404s and I want to have working examples for anyone trying out the model. I can write a follow-up to this once the GitHub is also live, by then you should be able to pass the image URLs directly to model.encode, it'll automatically detect the modality and forward accordingly :)

Anyways, here's the agent's PR. Happy to adjust this as you see fit, or answer any questions!

Pull Request overview

  • Add text, image, and video encoding through Sentence Transformers 5.4.0 and newer.

Details

A single Transformer module dispatches to get_text_features, get_image_features, or get_video_features according to the input modality. Each method already returns a normalized embedding. The processor routes inputs to the tokenizer, image processor, or video processor. The video processor uses the existing frame transform and samples 16 evenly spaced frames, including both endpoints, as in the Transformers quick start.

Across three captions, two images of different sizes, and a video, the largest fp32 cosine difference from the native Transformers 5.8.0 baseline was 1.5e-7. The two retrieval photos and the video in the new example are public alternatives to the original GitHub assets, whose URLs returned 404 during verification.

Added files

  • modules.json and sentence_bert_config.json select the feature method for each modality.
  • config_sentence_transformers.json configures cosine similarity.
  • processing_mistral_contrastive.py and processor_config.json expose the tokenizer, image processor, and video preprocessing through AutoProcessor.

Modified files

  • modeling_mistral_contrastive.py moves visual inputs to the patch convolution's device and dtype.
  • README.md adds the Sentence Transformers tag and an example for all three modalities.

The example uses Python 3.11 or newer. TorchCodec needs a compatible PyTorch build and FFmpeg for video files.

pip install "sentence-transformers[image,video]>=5.4.0" "transformers>=5.2.0" opencv-python-headless torchcodec
from io import BytesIO

import httpx
from PIL import Image
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("mistralai/mistral-multimodal-embed-1B", trust_remote_code=True, revision="refs/pr/2")

texts = ["iconic windmill", "a gothic cathedral", "a statue in a sunny square"]
photo_urls = [
    "https://upload.wikimedia.org/wikipedia/commons/2/25/De_Adriaan_windmill_in_Haarlem.jpg",
    "https://upload.wikimedia.org/wikipedia/commons/f/fe/Cologne_Cathedral.jpg",
]
# NOTE: Only needed for Wikipedia, you should be able to pass only the URLs once the GitHub images/videos are live
headers = {"User-Agent": "Clipstral example (https://huggingface.co/mistralai/mistral-multimodal-embed-1B)"}
with httpx.Client(headers=headers) as client:
    photos = [Image.open(BytesIO(client.get(url).raise_for_status().content)) for url in photo_urls]

text_embeddings = model.encode(texts)
image_embeddings = model.encode(photos)
print(model.similarity(image_embeddings, text_embeddings))
# tensor([[0.2280, 0.0980, 0.0888],
#         [0.1074, 0.2267, 0.0905]])

video = "https://raw.githubusercontent.com/opencv/opencv/4.12.0/samples/data/vtest.avi"
print(model.encode(video).shape)
# (1024,)

The existing AutoModel, AutoTokenizer, and AutoImageProcessor quick start continues to use the same weights and feature methods. Note also the revision="refs/pr/2", which means that you can run this snippet outright without installing the branch. Should make it easier to compare against the main branch.

  • Tom Aarsen
tomaarsen changed pull request status to open
Ready to merge
This branch is ready to get merged automatically.

Sign up or log in to comment