""" CoVisco SigLIP Model This module implements a CoVisco model with multiple projection heads for SigLIP training using pre-extracted embeddings as supervision signals. The model includes: 1. CoVisco encoder (trainable) 2. Multiple projection heads (to_image, to_image_caption, to_video_caption) 3. Independent logit_scale and logit_bias for each contrast pair 4. Optional reconstruction decoder """ from typing import Dict, Optional, Tuple import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from transformers.configuration_utils import PretrainedConfig from transformers.modeling_utils import PreTrainedModel # Dual import so this file works both as a plain script (absolute import) and # as a HuggingFace dynamic module loaded via trust_remote_code (relative import, # which is what the auto_map in config.json resolves to). try: # package / trust_remote_code context from .covisco_vit import CoViscoEncoderModel, CoViscoEncoderConfig from .reconstruction_decoder import ReconstructionDecoder except ImportError: # flat script context from covisco_vit import CoViscoEncoderModel, CoViscoEncoderConfig from reconstruction_decoder import ReconstructionDecoder class CoViscoConfig(PretrainedConfig): """Config for :class:`CoViscoModel`. Keeps the released ``config.json`` layout unchanged: three nested dicts (``covisco_encoder_cfg``, ``covisco_cfg``, ``preprocess_cfg``). The model rebuilds an ``CoViscoEncoderConfig`` from ``covisco_encoder_cfg`` and reads head dims / logit inits from ``covisco_cfg``. """ model_type = "covisco" def __init__( self, covisco_encoder_cfg=None, covisco_cfg=None, preprocess_cfg=None, **kwargs, ): super().__init__(**kwargs) self.covisco_encoder_cfg = covisco_encoder_cfg or {} self.covisco_cfg = covisco_cfg or {} self.preprocess_cfg = preprocess_cfg or {} # --------------------------------------------------------------------------- # Preprocessing / frame-sampling helpers. # # These are plain functions (no model needed) so they can be shared by the # CoViscoModel convenience methods below and by load_covisco.py. torchvision / # PIL / PyAV are imported lazily so a pure forward-pass user does not pay for # them, and PyAV stays an optional dependency (video decoding only). # --------------------------------------------------------------------------- def make_image_preprocess(preprocess_cfg: Dict, size: Optional[int] = None): """Square validation transform: shortest-edge resize + center crop + normalize. ``size`` overrides ``preprocess_cfg['size']`` (runtime-only; the encoder accepts any resolution). Reads mean/std/interpolation from ``preprocess_cfg``. """ from torchvision import transforms from torchvision.transforms import InterpolationMode interp = { "bicubic": InterpolationMode.BICUBIC, "bilinear": InterpolationMode.BILINEAR, "nearest": InterpolationMode.NEAREST, }[preprocess_cfg.get("interpolation", "bicubic")] size = size or preprocess_cfg["size"] mode = preprocess_cfg.get("mode", "RGB") return transforms.Compose([ # Enforce the configured colour mode so the transform is correct even # when applied directly to a non-RGB (grayscale / RGBA / palette) image. transforms.Lambda(lambda im: im.convert(mode)), transforms.Resize(size, interpolation=interp), transforms.CenterCrop(size), transforms.ToTensor(), transforms.Normalize(mean=preprocess_cfg["mean"], std=preprocess_cfg["std"]), ]) def make_native_preprocess(preprocess_cfg: Dict, patch_size: int, max_side: int = 1400): """Aspect-ratio-preserving transform at (near-)native resolution. Keeps the original aspect ratio, scales so the long side <= ``max_side``, and rounds each side to a multiple of ``patch_size`` (the encoder derives its patch grid as H//patch_size x W//patch_size at runtime). Recommended for text-heavy document pages where a square center-crop destroys detail; encode one image at a time (a batch is a single dense tensor). """ from torchvision import transforms from PIL import Image to_tensor = transforms.ToTensor() normalize = transforms.Normalize(mean=preprocess_cfg["mean"], std=preprocess_cfg["std"]) mode = preprocess_cfg.get("mode", "RGB") def _round(x): return max(patch_size, int(round(x / patch_size)) * patch_size) def preprocess(img): img = img.convert(mode) # enforce configured colour mode w, h = img.size scale = min(1.0, max_side / max(w, h)) nw, nh = _round(w * scale), _round(h * scale) img = img.resize((nw, nh), Image.BICUBIC) return normalize(to_tensor(img)) return preprocess def read_video_frames(path: str, num_frames: int): """Uniformly sample ``num_frames`` RGB frames (list of PIL images) from a video. Requires PyAV (``pip install av``), an *optional* dependency used only for video decoding. The ``int()`` truncation mirrors ``np.linspace(0, n-1, k).astype(int)`` — the exact rule ``codec_visidx.sample_frame_ids`` uses — so a clip built here stays frame-aligned with a codec visidx computed over the same decoded frames. """ try: import av except ImportError as e: # keep video decoding optional raise ImportError( "read_video_frames needs PyAV for video decoding: pip install av" ) from e if num_frames < 1: raise ValueError(f"num_frames must be >= 1, got {num_frames}") container = av.open(path) stream = container.streams.video[0] stream.thread_type = "AUTO" frames = [f.to_image() for f in container.decode(stream)] container.close() if not frames: raise ValueError(f"no frames decoded from {path!r}") if num_frames == 1: idx = [0] else: n = len(frames) idx = [int(i * (n - 1) / (num_frames - 1)) for i in range(num_frames)] return [frames[i] for i in idx] class ContrastiveHead(torch.nn.Module): def __init__( self, in_dim: int, out_dim: int, ) -> None: super().__init__() self.layer_norm = torch.nn.LayerNorm(normalized_shape=in_dim, eps=1e-6) self.proj = torch.nn.Linear(in_dim, out_dim, bias=False) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.proj(self.layer_norm(x)) class CoViscoModel(PreTrainedModel): """ CoVisco model with multiple projection heads for SigLIP training. Each contrast pair (image-caption, image-image, video-caption) uses independent logit_scale and logit_bias parameters, allowing different modalities to have different temperature and bias values. This is a :class:`~transformers.PreTrainedModel`, so it supports ``CoViscoModel.from_pretrained(dir)`` and, with ``auto_map`` in config.json, ``AutoModel.from_pretrained(dir, trust_remote_code=True)``. All architecture args come from a :class:`CoViscoConfig`: * ``config.covisco_encoder_cfg`` -> CoViscoEncoderConfig for the encoder * ``config.covisco_cfg`` -> head dims, reconstruction flag, logit inits """ config_class = CoViscoConfig base_model_prefix = "covisco" main_input_name = "pixel_values" supports_gradient_checkpointing = True _no_split_modules = ["CoViscoEncoderEncoderLayer"] def __init__(self, config: CoViscoConfig): super().__init__(config) covisco_config = CoViscoEncoderConfig(**config.covisco_encoder_cfg) ccfg = config.covisco_cfg self.hidden_size = covisco_config.hidden_size self.num_query_per_seg = covisco_config.num_query_per_seg # 1. CoVisco Encoder (trainable) self.encoder = CoViscoEncoderModel(covisco_config) # Create a visual attribute for compatibility with factory code self.visual = self.encoder # 2. Multiple projection heads self.proj_to_image = ContrastiveHead( covisco_config.hidden_size, ccfg.get("image_embed_dim", 1024) ) self.proj_to_image_caption = ContrastiveHead( covisco_config.hidden_size, ccfg.get("image_caption_embed_dim", 1024) ) self.proj_to_video_caption = ContrastiveHead( covisco_config.hidden_size, ccfg.get("video_caption_embed_dim", 1024) ) # 3. Independent logit_scale for each contrast pair # Note: SigLIP uses logit_scale directly as temperature (not log of temperature like CLIP) self.logit_scale_image_caption = nn.Parameter( torch.ones(1) * ccfg.get("init_logit_scale_image_caption", 10.0) ) self.logit_scale_image_image = nn.Parameter( torch.ones(1) * ccfg.get("init_logit_scale_image_image", 10.0) ) self.logit_scale_video_caption = nn.Parameter( torch.ones(1) * ccfg.get("init_logit_scale_video_caption", 10.0) ) # 4. Independent logit_bias for each contrast pair self.logit_bias_image_caption = nn.Parameter( torch.ones(1) * ccfg.get("init_logit_bias_image_caption", -10.0) ) self.logit_bias_image_image = nn.Parameter( torch.ones(1) * ccfg.get("init_logit_bias_image_image", -10.0) ) self.logit_bias_video_caption = nn.Parameter( torch.ones(1) * ccfg.get("init_logit_bias_video_caption", -10.0) ) # 5. Optional reconstruction decoder self.use_reconstruction = ccfg.get("use_reconstruction", False) if self.use_reconstruction: self.reconstruction_decoder = ReconstructionDecoder( hidden_size=covisco_config.hidden_size, num_image_query_tokens=ccfg.get("decoder_num_image_queries", 256), num_video_query_tokens=ccfg.get("decoder_num_video_queries", 256), num_layers=ccfg.get("decoder_layers", 6), num_heads=ccfg.get("decoder_num_heads", 8), ) self.post_init() def _init_weights(self, module): """Random init for from-scratch construction; overwritten by loaded weights.""" std = getattr(self.config, "initializer_range", 0.02) if isinstance(module, (nn.Linear, nn.Conv2d)): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() elif isinstance(module, (nn.LayerNorm, nn.RMSNorm)): # RMSNorm has no bias, so guard with hasattr before zeroing it. module.weight.data.fill_(1.0) if hasattr(module, "bias") and module.bias is not None: module.bias.data.zero_() def forward( self, pixel_values: torch.Tensor, visible_indices: Optional[torch.Tensor] = None, return_intermediates: bool = False, return_attentions: bool = False, run_decoder: bool = True, modality: Optional[str] = None, segment_offset: Optional[int] = 0, ) -> Dict[str, torch.Tensor]: """ Forward pass of the CoVisco SigLIP model. Args: pixel_values: Input images/videos of shape (B, C, H, W) or (B, T, C, H, W) return_intermediates: Whether to return intermediate outputs (query_tokens, vit_tokens) return_attentions: Whether to return attention weights run_decoder: Whether to run the reconstruction decoder. Set to False during gradient accumulation cache phase to save computation. modality: Controls which projection heads to compute. "image" -> to_image, to_image_caption, to_image_video_caption "video" -> to_video_caption only None -> all projections (backward compatible) Returns: Dictionary containing model outputs. """ # Get encoder outputs with return_dict=True to access all outputs encoder_outputs = self.encoder( pixel_values, visible_indices=visible_indices, output_attentions=return_attentions, output_hidden_states=return_intermediates, return_dict=True, segment_offset=segment_offset, ) # Extract pooled output and sequence output pooled_output = encoder_outputs.pooler_output # (B, D) or (B, S*Q, D) -> pooled to (B, D) sequence_output = encoder_outputs.last_hidden_state # (B, S, N, D) # Reshape sequence_output for easier processing batch_size, num_segments, num_tokens, hidden_size = sequence_output.shape # Extract query tokens (first num_query_per_seg tokens in each segment) query_tokens = sequence_output[:, :, :self.num_query_per_seg, :] # (B, S, Q, D) # query_tokens_flat = query_tokens.reshape(batch_size, -1, hidden_size) # (B, S*Q, D) # Extract ViT patch tokens (remaining tokens) vit_tokens = sequence_output[:, :, self.num_query_per_seg:, :] # (B, S, N-Q, D) # vit_tokens_flat = vit_tokens.reshape(batch_size, -1, hidden_size) # (B, S*(N-Q), D) # Ensure pooled_output is (B, D) - handle case where it might be (B, S*Q, D) # if pooled_output.dim() == 3: # Global average pooling if we have segment-level outputs # pooled_output = pooled_output.mean(dim=1) # Apply projections selectively based on modality outputs = {'pooled_output': pooled_output} if modality is None or modality == "image": outputs['to_image'] = F.normalize(self.proj_to_image(pooled_output), dim=-1) outputs['to_image_caption'] = F.normalize(self.proj_to_image_caption(pooled_output), dim=-1) # Images whose captions were encoded by the *video* text encoder share the # video-caption head: same projection weights, separate output key so the # loss can report it independently from real video batches. outputs['to_image_video_caption'] = F.normalize(self.proj_to_video_caption(pooled_output), dim=-1) if modality is None or modality == "video": outputs['to_video_caption'] = F.normalize(self.proj_to_video_caption(pooled_output), dim=-1) # Optionally return intermediate outputs for reconstruction loss if return_intermediates: outputs['query_tokens'] = query_tokens outputs['vit_tokens'] = vit_tokens.detach() # Optionally run reconstruction decoder if self.use_reconstruction and run_decoder: reconstructed = self.reconstruction_decoder( query_tokens, return_attentions=False, ) outputs['reconstructed'] = reconstructed # if return_attentions and isinstance(reconstructed, tuple): # outputs['reconstruction_attentions'] = reconstructed[1] if return_attentions: outputs['attentions'] = encoder_outputs.attentions return outputs def get_logit_scales_and_biases(self, modality: str = "image") -> Dict[str, torch.Tensor]: """ Get logit_scale and logit_bias for the specified modality. Args: modality: Current modality ("image" or "video") Returns: Dictionary with logit_scales and logit_biases for this modality """ logit_scales = {} logit_biases = {} if modality == "image": logit_scales['image_caption'] = self.logit_scale_image_caption logit_scales['image_image'] = self.logit_scale_image_image logit_biases['image_caption'] = self.logit_bias_image_caption logit_biases['image_image'] = self.logit_bias_image_image # Shared with real video batches: the image-with-video-caption pair lives in # the same embedding space, so it reuses the video-caption temperature/bias. logit_scales['video_caption'] = self.logit_scale_video_caption logit_biases['video_caption'] = self.logit_bias_video_caption elif modality == "video": logit_scales['video_caption'] = self.logit_scale_video_caption logit_biases['video_caption'] = self.logit_bias_video_caption return logit_scales, logit_biases # ----------------------------------------------------------------------- # Convenience preprocessing / encoding API. # # Available on any `from_pretrained(..., trust_remote_code=True)` model # (this file is downloaded via auto_map), so Hub users get the full # image/video pipeline without needing load_covisco.py. All read config # from `self.config.preprocess_cfg` / `self.config.covisco_encoder_cfg`. # ----------------------------------------------------------------------- def build_preprocess(self, size: Optional[int] = None): """Square per-frame transform (shortest-edge resize + center crop).""" return make_image_preprocess(self.config.preprocess_cfg, size) def build_native_preprocess(self, max_side: int = 1400): """Aspect-preserving per-frame transform at (near-)native resolution.""" patch_size = self.config.covisco_encoder_cfg.get("patch_size", 14) return make_native_preprocess(self.config.preprocess_cfg, patch_size, max_side) read_video_frames = staticmethod(read_video_frames) def set_segment_t_size(self, segment_t_size: int): """Override the (runtime-only) video temporal segment size. No weight shape depends on it, so it is applied to the live encoder. Video frame count T must be a positive multiple of it. Returns ``self``. """ if segment_t_size < 1: raise ValueError(f"segment_t_size must be >= 1, got {segment_t_size}") self.encoder.segment_t_size = segment_t_size self.encoder.config.segment_t_size = segment_t_size return self # ---- shared helpers for the encode_* / embed_* API ------------------- @staticmethod def _select_branch(out, branch, modality): if branch in out: return out[branch] extra = (" Use 'to_image_video_caption' for the 4096-d embedding." if modality == "image" else "") raise KeyError( f"branch={branch!r} not produced under modality={modality!r}; " f"available: {sorted(k for k in out if k.startswith('to_'))}.{extra}") @staticmethod def _frame_to_tensor(item, preprocess): """One frame/image -> (C, H, W) tensor. Accepts path / PIL / 3-D tensor.""" if isinstance(item, torch.Tensor): if item.ndim != 3: raise ValueError(f"an image/frame tensor must be (C,H,W), got {tuple(item.shape)}") return item if isinstance(item, str): from PIL import Image item = Image.open(item) return preprocess(item.convert("RGB")) def _clip_to_cthw(self, clip, preprocess): """One clip -> (C, T, H, W) tensor. Accepts a frame sequence or (T,C,H,W).""" if isinstance(clip, torch.Tensor): if clip.ndim != 4: raise ValueError(f"a clip tensor must be (T,C,H,W), got {tuple(clip.shape)}") return clip.permute(1, 0, 2, 3) if isinstance(clip, str) or hasattr(clip, "convert"): raise ValueError( "embed_videos expects a sequence of CLIPS, but got a single " "frame/path. Wrap one clip as [clip], or use encode_video.") frames = [self._frame_to_tensor(f, preprocess) for f in clip] if not frames: raise ValueError("a clip is empty") return torch.stack(frames).permute(1, 0, 2, 3) # (T,C,H,W) -> (C,T,H,W) # ---- batched API ----------------------------------------------------- @torch.inference_mode() def embed_images(self, inputs, preprocess=None, branch: str = "to_image_caption", return_intermediates: bool = False, return_attentions: bool = False): """Batched image embedding -> ``(B, D)`` (or the full forward dict). ``inputs`` is either: * a 4-D tensor ``(B, C, H, W)`` — already preprocessed, used as-is; or * a sequence whose items are each a path (str), a PIL image, or a 3-D ``(C, H, W)`` tensor. Non-tensor items go through ``preprocess`` (default ``build_preprocess()``, square); tensors are used as-is. All items must share ``(C, H, W)`` so they stack into one dense batch — use the square ``build_preprocess``. Native/variable resolution cannot be densely batched; embed those one at a time (``encode_image``). """ device = next(self.parameters()).device if isinstance(inputs, torch.Tensor): if inputs.ndim != 4: raise ValueError(f"image batch tensor must be (B,C,H,W), got {tuple(inputs.shape)}") px = inputs else: if isinstance(inputs, (str, bytes)) or hasattr(inputs, "convert"): raise ValueError( "embed_images expects a batch (list of path/PIL/tensor, or a " "(B,C,H,W) tensor); for one image use encode_image or pass [image].") inputs = list(inputs) if not inputs: raise ValueError("inputs is empty") if preprocess is None: preprocess = self.build_preprocess() frames = [self._frame_to_tensor(it, preprocess) for it in inputs] try: px = torch.stack(frames) except RuntimeError as e: raise ValueError( "could not batch images of different sizes; use square " "build_preprocess, or embed variable-resolution images one at a time" ) from e out = self(px.to(device), modality="image", run_decoder=False, return_intermediates=return_intermediates, return_attentions=return_attentions) if return_intermediates or return_attentions: return out return self._select_branch(out, branch, "image") @torch.inference_mode() def embed_videos(self, inputs, preprocess=None, branch: str = "to_video_caption", visible_indices=None, return_intermediates: bool = False, return_attentions: bool = False): """Batched video embedding -> ``(B, D)`` (or the full forward dict). ``inputs`` is either: * a 5-D tensor ``(B, C, T, H, W)`` — used as-is; or * a sequence of **clips**, where each clip is a frame sequence (path / PIL / 3-D tensor items) or a ``(T, C, H, W)`` tensor. A flat frame list is rejected (ambiguous: one clip vs many 1-frame clips) — wrap a single clip as ``[clip]`` or use ``encode_video``. All clips must share ``(C, T, H, W)``. ``visible_indices`` (codec mode) may be ``(L,)`` (shared across the batch) or ``(B, L)``. """ device = next(self.parameters()).device if isinstance(inputs, torch.Tensor): if inputs.ndim != 5: raise ValueError(f"video batch tensor must be (B,C,T,H,W), got {tuple(inputs.shape)}") px = inputs else: if isinstance(inputs, (str, bytes)) or hasattr(inputs, "convert"): raise ValueError( "embed_videos expects a batch of clips (list of clips, or a " "(B,C,T,H,W) tensor); for one clip use encode_video or pass [clip].") inputs = list(inputs) if not inputs: raise ValueError("inputs is empty") if preprocess is None: preprocess = self.build_preprocess() clips = [self._clip_to_cthw(c, preprocess) for c in inputs] # each (C,T,H,W) try: px = torch.stack(clips) # (B,C,T,H,W) except RuntimeError as e: raise ValueError("could not batch clips of different (C,T,H,W) shapes") from e px = px.to(device) kwargs = {} if visible_indices is not None: vi = visible_indices if not isinstance(vi, torch.Tensor): vi = torch.as_tensor(vi) vi = vi.long() if vi.ndim == 1: vi = vi.unsqueeze(0).expand(px.shape[0], -1) # (L,) shared across batch elif vi.ndim == 2: if vi.shape[0] != px.shape[0]: raise ValueError( f"visible_indices batch {vi.shape[0]} != number of clips {px.shape[0]}") else: raise ValueError(f"visible_indices must be 1-D or 2-D, got shape {tuple(vi.shape)}") kwargs["visible_indices"] = vi.to(device) out = self(px, modality="video", run_decoder=False, return_intermediates=return_intermediates, return_attentions=return_attentions, **kwargs) if return_intermediates or return_attentions: return out return self._select_branch(out, branch, "video") # ---- single-sample convenience (thin wrappers over the batched API) -- def encode_image(self, image, preprocess=None, branch: str = "to_image_caption", return_intermediates: bool = False, return_attentions: bool = False): """L2-normalized embedding for a **single** image (path / PIL / tensor). Returns ``(1, D)``. Branches: ``to_image_caption`` / ``to_image`` (1536-d, SigLIP2) or ``to_image_video_caption`` (4096-d, Qwen3-VL-Embedding). For many images use :meth:`embed_images`. ``return_intermediates`` / ``return_attentions`` return the full dict. """ return self.embed_images([image], preprocess=preprocess, branch=branch, return_intermediates=return_intermediates, return_attentions=return_attentions) def encode_video(self, frames, preprocess=None, branch: str = "to_video_caption", visible_indices=None, return_intermediates: bool = False, return_attentions: bool = False): """L2-normalized embedding for a **single** clip. ``frames`` is a frame sequence (path / PIL / 3-D tensor items) or a ``(T, C, H, W)`` tensor. Returns ``(1, D)``. ``visible_indices`` enables codec sparse-patch mode. For many clips use :meth:`embed_videos`. """ return self.embed_videos([frames], preprocess=preprocess, branch=branch, visible_indices=visible_indices, return_intermediates=return_intermediates, return_attentions=return_attentions)