Integrate with Sentence Transformers

#2
by tomaarsen HF Staff - opened
README.md CHANGED
@@ -11,6 +11,7 @@ tags:
11
  - embeddings
12
  - multilingual
13
  - custom_code
 
14
  ---
15
 
16
  # Mistral Multimodal Embed - Clipstral
@@ -113,6 +114,44 @@ For other accelerators, follow the [uv PyTorch guide](https://docs.astral.sh/uv/
113
 
114
  ## Quick start
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  The model code ships with the weights and loads with `trust_remote_code=True`. The snippets below run in order
117
  as one script, from any folder: the three example files (under 1 MB) are downloaded from the
118
  [GitHub repository](https://github.com/mistralai/mistral-multimodal-embed). Replace them with your own files to embed your data.
@@ -156,7 +195,7 @@ and the processor returns a list of tensors (with `squash` or `center_crop`, it
156
  All returned features are L2-normalized 1,024-dimensional float32 tensors, so a dot product is a cosine
157
  similarity.
158
 
159
- ### Videos
160
 
161
  A video is embedded from 16 evenly spaced frames, here decoded with OpenCV and encoded at 224 px:
162
 
 
11
  - embeddings
12
  - multilingual
13
  - custom_code
14
+ - sentence-transformers
15
  ---
16
 
17
  # Mistral Multimodal Embed - Clipstral
 
114
 
115
  ## Quick start
116
 
117
+ ### Using Sentence Transformers
118
+
119
+ You can load the model using Sentence Transformers by passing `trust_remote_code=True`.
120
+
121
+ ```python
122
+ # pip install sentence-transformers[image,video] opencv-python-headless torchcodec
123
+ from sentence_transformers import SentenceTransformer
124
+
125
+ model = SentenceTransformer("mistralai/mistral-multimodal-embed-1B", trust_remote_code=True)
126
+
127
+ texts = ["iconic windmill", "a gothic cathedral", "a statue in a sunny square"]
128
+ images = [
129
+ "https://raw.githubusercontent.com/mistralai/mistral-multimodal-embed/main/assets/images/image_00.jpg",
130
+ "https://raw.githubusercontent.com/mistralai/mistral-multimodal-embed/main/assets/images/image_01.jpg",
131
+ ]
132
+ video = "https://raw.githubusercontent.com/mistralai/mistral-multimodal-embed/main/assets/videos/video_02.mp4"
133
+
134
+ # encode() detects the input modality automatically
135
+ text_embeddings = model.encode(texts)
136
+ image_embeddings = model.encode(images)
137
+ video_embedding = model.encode(video)
138
+ print(text_embeddings.shape, image_embeddings.shape, video_embedding.shape)
139
+ # (3, 1024) (2, 1024) (1024,)
140
+
141
+ # Compute cosine similarity
142
+ image_text_similarity = model.similarity(image_embeddings, text_embeddings)
143
+ video_text_similarity = model.similarity(video_embedding, text_embeddings)
144
+ print(image_text_similarity)
145
+ # tensor([[0.1953, 0.1275, 0.1447],
146
+ # [0.1071, 0.2144, 0.1063]])
147
+ print(video_text_similarity)
148
+ # tensor([[0.1495, 0.1446, 0.3000]])
149
+ ```
150
+
151
+ For other ways to pass images and videos to `encode()`, see the [Sentence Transformers input formats guide](https://sbert.net/docs/input_formats.html).
152
+
153
+ ### Using Transformers
154
+
155
  The model code ships with the weights and loads with `trust_remote_code=True`. The snippets below run in order
156
  as one script, from any folder: the three example files (under 1 MB) are downloaded from the
157
  [GitHub repository](https://github.com/mistralai/mistral-multimodal-embed). Replace them with your own files to embed your data.
 
195
  All returned features are L2-normalized 1,024-dimensional float32 tensors, so a dot product is a cosine
196
  similarity.
197
 
198
+ #### Videos
199
 
200
  A video is embedded from 16 evenly spaced frames, here decoded with OpenCV and encoded at 224 px:
201
 
config_sentence_transformers.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "__version__": {
3
+ "pytorch": "2.10.0+cu128",
4
+ "sentence_transformers": "5.4.0",
5
+ "transformers": "5.2.0"
6
+ },
7
+ "default_prompt_name": null,
8
+ "model_type": "SentenceTransformer",
9
+ "prompts": {},
10
+ "similarity_fn_name": "cosine"
11
+ }
modeling_mistral_contrastive.py CHANGED
@@ -425,7 +425,8 @@ class MistralContrastiveVisionModel(nn.Module):
425
  self.visual_projection = nn.Linear(config.vision_dim, config.projection_dim, bias=False)
426
 
427
  def encode_patches(self, pixel_values: torch.Tensor) -> tuple[torch.Tensor, int, int]:
428
- x = self.patch_conv(pixel_values) # (B, dim, gh, gw)
 
429
  grid_h, grid_w = x.shape[-2], x.shape[-1]
430
  x = x.flatten(2).transpose(1, 2) # (B, gh * gw, dim)
431
  x = self.ln_pre(x)
 
425
  self.visual_projection = nn.Linear(config.vision_dim, config.projection_dim, bias=False)
426
 
427
  def encode_patches(self, pixel_values: torch.Tensor) -> tuple[torch.Tensor, int, int]:
428
+ weight = self.patch_conv.weight
429
+ x = self.patch_conv(pixel_values.to(weight.dtype if weight.is_meta else weight)) # (B, dim, gh, gw)
430
  grid_h, grid_w = x.shape[-2], x.shape[-1]
431
  x = x.flatten(2).transpose(1, 2) # (B, gh * gw, dim)
432
  x = self.ln_pre(x)
modules.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "idx": 0,
4
+ "name": "0",
5
+ "path": "",
6
+ "type": "sentence_transformers.base.modules.transformer.Transformer"
7
+ }
8
+ ]
processing_mistral_contrastive.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Text, image, and video preprocessing for Mistral Multimodal Embed."""
2
+
3
+ import numpy as np
4
+ import torch
5
+ from transformers.feature_extraction_utils import BatchFeature
6
+ from transformers.image_transforms import to_pil_image
7
+ from transformers.image_utils import make_flat_list_of_images
8
+ from transformers.processing_utils import ProcessorMixin, VideosKwargs
9
+ from transformers.video_processing_utils import BaseVideoProcessor
10
+
11
+ from .image_transforms import TransformKind, build_transform
12
+
13
+
14
+ class MistralContrastiveVideoProcessorKwargs(VideosKwargs, total=False):
15
+ transform: str
16
+ use_cv2_resize: bool
17
+
18
+
19
+ class MistralContrastiveVideoProcessor(BaseVideoProcessor):
20
+ model_input_names = ["videos"]
21
+ valid_kwargs = MistralContrastiveVideoProcessorKwargs
22
+ size = {"longest_edge": 224}
23
+ transform = "keep_ratio"
24
+ use_cv2_resize = True
25
+ do_sample_frames = True
26
+ num_frames = 16
27
+
28
+ def sample_frames(self, metadata, num_frames=None, fps=None, **kwargs):
29
+ if fps is not None:
30
+ return super().sample_frames(metadata, num_frames=num_frames, fps=fps, **kwargs)
31
+ count = self.num_frames if num_frames is None else num_frames
32
+ if count < 1 or metadata.total_num_frames < 1:
33
+ raise ValueError("Video sampling requires at least one frame.")
34
+ return np.linspace(0, metadata.total_num_frames - 1, count).round().astype(int)
35
+
36
+ def _preprocess(self, videos, size, transform, use_cv2_resize, **kwargs):
37
+ process_frame = build_transform(TransformKind(transform), size.longest_edge or size.height, use_cv2_resize)
38
+ clips = [torch.stack([process_frame(frame) for frame in video]) for video in videos]
39
+ return BatchFeature({"videos": clips})
40
+
41
+
42
+ class MistralContrastiveProcessor(ProcessorMixin):
43
+ def __init__(self, image_processor, tokenizer, video_processor):
44
+ super().__init__(image_processor, tokenizer, video_processor)
45
+
46
+ def __call__(self, text=None, images=None, videos=None, **kwargs):
47
+ if text is None and images is None and videos is None:
48
+ raise ValueError("Provide text, images, or videos to encode.")
49
+ kwargs = self._merge_kwargs(
50
+ self.valid_processor_kwargs, tokenizer_init_kwargs=self.tokenizer.init_kwargs, **kwargs
51
+ )
52
+ inputs = BatchFeature()
53
+ if text is not None:
54
+ inputs.update(self.tokenizer(text, **kwargs["text_kwargs"]))
55
+ if images is not None:
56
+ images = make_flat_list_of_images(self.image_processor.fetch_images(images))
57
+ images = [to_pil_image(image) for image in images]
58
+ inputs.update(self.image_processor(images, **kwargs["images_kwargs"]))
59
+ if videos is not None:
60
+ inputs.update(self.video_processor(videos, **kwargs["videos_kwargs"]))
61
+ if text is not None:
62
+ # The joint forward names this argument differently from get_video_features.
63
+ inputs["video_pixel_values"] = inputs.pop("videos")
64
+ return inputs
65
+
66
+
67
+ MistralContrastiveVideoProcessor.register_for_auto_class()
68
+ MistralContrastiveProcessor.register_for_auto_class()
processor_config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "processor_class": "MistralContrastiveProcessor",
3
+ "auto_map": {
4
+ "AutoProcessor": "processing_mistral_contrastive.MistralContrastiveProcessor"
5
+ },
6
+ "video_processor": {
7
+ "auto_map": {
8
+ "AutoVideoProcessor": "processing_mistral_contrastive.MistralContrastiveVideoProcessor"
9
+ },
10
+ "video_processor_type": "MistralContrastiveVideoProcessor",
11
+ "do_sample_frames": true,
12
+ "num_frames": 16,
13
+ "size": {"longest_edge": 224}
14
+ }
15
+ }
sentence_bert_config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "transformer_task": "feature-extraction",
3
+ "modality_config": {
4
+ "text": {
5
+ "method": "get_text_features",
6
+ "method_output_name": null
7
+ },
8
+ "image": {
9
+ "method": "get_image_features",
10
+ "method_output_name": null
11
+ },
12
+ "video": {
13
+ "method": "get_video_features",
14
+ "method_output_name": null
15
+ }
16
+ },
17
+ "module_output_name": "sentence_embedding",
18
+ "processing_kwargs": {
19
+ "text": {
20
+ "truncation": false
21
+ }
22
+ }
23
+ }