"""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")