Feature Extraction
Transformers
Safetensors
sentence-transformers
mistral_contrastive
brevitech
mirror
video-text-retrieval
text-to-video-retrieval
image-text-retrieval
zero-shot-classification
contrastive
embeddings
multilingual
custom_code
Instructions to use brevitech/Mistral-Multimodal-Embed-1B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use brevitech/Mistral-Multimodal-Embed-1B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="brevitech/Mistral-Multimodal-Embed-1B", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("brevitech/Mistral-Multimodal-Embed-1B", trust_remote_code=True, device_map="auto") - sentence-transformers
How to use brevitech/Mistral-Multimodal-Embed-1B with sentence-transformers:
from sentence_transformers import SentenceTransformer model = SentenceTransformer("brevitech/Mistral-Multimodal-Embed-1B", trust_remote_code=True) sentences = [ "The weather is lovely today.", "It's so sunny outside!", "He drove to the stadium." ] embeddings = model.encode(sentences) similarities = model.similarity(embeddings, embeddings) print(similarities.shape) # [3, 3] - Notebooks
- Google Colab
- Kaggle
File size: 7,138 Bytes
08d2a21 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | """Image preprocessing for the Mistral two-encoder contrastive model.
The model is variable-resolution (2D RoPE, no learned position embeddings), so it
accepts square *or* rectangular inputs as long as height and width are multiples of
``patch_size * spatial_merge_size`` (= 14 * 2 = 28).
Three transforms, matching the training/eval pipeline. Pick one via ``build_transform``:
- ``squash`` — resize directly to ``size x size`` (aspect ratio distorted, no crop). Good for
low / fixed resolution (e.g. 224, 336). Fixed-size output -> dense batching.
- ``center_crop`` — resize the shortest edge to ``size`` keeping aspect ratio, then
center-crop ``size x size``. Fixed-size output -> dense batching.
- ``keep_ratio`` — resize the longest side to ``size`` keeping aspect ratio, rounding both sides
**up** to a multiple of 28 so the ViT tiles exactly. Output is rectangular and variable-size, so
pass the images as a list to ``get_image_features([...])``.
NOTE on keep_ratio rounding: sides are rounded **up** to a multiple of 28, as in training
(e.g. 200x900 at 672 px -> 168x672, not 140x672 as rounding down would give).
Normalization uses the per-channel mean and standard deviation in ``IMAGE_MEAN`` and ``IMAGE_STD``.
Training used cv2 ``INTER_AREA`` resize; set ``use_cv2_resize=True`` to match it exactly,
otherwise torchvision bicubic is used (a close approximation).
"""
from collections.abc import Callable
from enum import StrEnum
import torch
import torchvision.transforms.functional as TF
from PIL import Image
from torchvision import transforms
from torchvision.transforms import InterpolationMode
IMAGE_MEAN = (0.48145466, 0.4578275, 0.40821073)
IMAGE_STD = (0.26862954, 0.26130258, 0.27577711)
PATCH_SIZE = 14
SPATIAL_MERGE_SIZE = 2
GRID_UNIT = PATCH_SIZE * SPATIAL_MERGE_SIZE # 28: H and W must be multiples of this
class TransformKind(StrEnum):
squash = "squash"
center_crop = "center_crop"
keep_ratio = "keep_ratio"
def _cv2_resize(img: torch.Tensor, new_h: int, new_w: int) -> torch.Tensor:
import cv2 # local import so cv2 is only required when use_cv2_resize=True
np_img = img.permute(1, 2, 0).numpy()
np_img = cv2.resize(np_img, (new_w, new_h), interpolation=cv2.INTER_AREA)
return torch.from_numpy(np_img).permute(2, 0, 1).contiguous()
def _resize(img: torch.Tensor, new_h: int, new_w: int, use_cv2_resize: bool) -> torch.Tensor:
if use_cv2_resize:
return _cv2_resize(img, new_h, new_w)
return TF.resize(img, [new_h, new_w], interpolation=InterpolationMode.BICUBIC, antialias=True)
class _SquashResize(torch.nn.Module):
def __init__(self, size: int, use_cv2_resize: bool) -> None:
super().__init__()
self.size = size
self.use_cv2_resize = use_cv2_resize
def forward(self, img: torch.Tensor) -> torch.Tensor:
return _resize(img, self.size, self.size, self.use_cv2_resize)
class _KeepRatioResize(torch.nn.Module):
def __init__(self, max_size: int, use_cv2_resize: bool) -> None:
super().__init__()
self.max_size = max_size
self.use_cv2_resize = use_cv2_resize
def forward(self, img: torch.Tensor) -> torch.Tensor:
_, h, w = img.shape
# Match the training transform: scale the longest side to max_size, then round each
# side UP to a multiple of GRID_UNIT so the ViT tiles exactly (rounding up, not down,
# is what the model was trained on; e.g. 200x900 at 672 px -> 168x672, not 140x672).
scale = self.max_size / max(h, w)
new_h = max(round(h * scale), 1)
new_w = max(round(w * scale), 1)
new_h = ((new_h - 1) // GRID_UNIT + 1) * GRID_UNIT
new_w = ((new_w - 1) // GRID_UNIT + 1) * GRID_UNIT
return _resize(img, new_h, new_w, self.use_cv2_resize)
class _CenterCropResize(torch.nn.Module):
"""Resize shortest edge to ``size`` (keep aspect), then center-crop ``size x size``."""
def __init__(self, size: int, use_cv2_resize: bool) -> None:
super().__init__()
self.size = size
self.use_cv2_resize = use_cv2_resize
def forward(self, img: torch.Tensor) -> torch.Tensor:
_, h, w = img.shape
scale = self.size / min(h, w)
img = _resize(img, round(h * scale), round(w * scale), self.use_cv2_resize)
return TF.center_crop(img, [self.size, self.size])
def _to_float_tensor(image: Image.Image | torch.Tensor) -> torch.Tensor:
"""PIL image or uint8 ``(3, H, W)`` RGB tensor (e.g. a decoded video frame) -> float
``(3, H, W)`` in [0, 1]. Both paths are pixel-identical: ``to_tensor`` on an RGB image is
exactly ``uint8 / 255``."""
if isinstance(image, torch.Tensor):
assert image.dtype == torch.uint8 and image.ndim == 3 and image.shape[0] == 3, (
f"Expected a uint8 (3, H, W) RGB tensor, got dtype={image.dtype}, "
f"shape={tuple(image.shape)}"
)
return image.float().div(255)
return TF.to_tensor(image.convert("RGB"))
def _compose(resize_op: torch.nn.Module) -> Callable[[Image.Image | torch.Tensor], torch.Tensor]:
return transforms.Compose(
[
transforms.Lambda(_to_float_tensor),
resize_op,
transforms.Normalize(mean=IMAGE_MEAN, std=IMAGE_STD),
]
)
def build_squash_transform(size: int = 448, use_cv2_resize: bool = False) -> Callable[[Image.Image | torch.Tensor], torch.Tensor]:
"""Resize to ``size x size`` (aspect distorted) then normalize. Returns (3, size, size)."""
return _compose(_SquashResize(size, use_cv2_resize))
def build_center_crop_transform(size: int = 448, use_cv2_resize: bool = False) -> Callable[[Image.Image | torch.Tensor], torch.Tensor]:
"""Resize shortest edge to ``size`` then center-crop ``size x size`` and normalize."""
return _compose(_CenterCropResize(size, use_cv2_resize))
def build_keep_ratio_transform(size: int = 448, use_cv2_resize: bool = False) -> Callable[[Image.Image | torch.Tensor], torch.Tensor]:
"""Resize longest side to ``size`` (rounded to multiples of 28) then normalize.
Output is rectangular and varies per image, so pass the images as a list to ``get_image_features``.
"""
return _compose(_KeepRatioResize(size, use_cv2_resize))
def build_transform(
kind: TransformKind = "keep_ratio", size: int = 448, use_cv2_resize: bool = False
) -> Callable[[Image.Image | torch.Tensor], torch.Tensor]:
"""Single entry point: select the image transform by name.
Defaults to ``keep_ratio`` at 448 px, as in ``preprocessor_config.json``. ``use_cv2_resize``
defaults to ``False`` here so this function never requires cv2; ``MistralContrastiveImageProcessor``
defaults to ``True`` to match the training resize.
"""
if kind == "squash":
return build_squash_transform(size, use_cv2_resize)
if kind == "center_crop":
return build_center_crop_transform(size, use_cv2_resize)
if kind == "keep_ratio":
return build_keep_ratio_transform(size, use_cv2_resize)
raise ValueError(f"Unknown transform kind {kind!r}; expected squash | center_crop | keep_ratio")
|