#!/usr/bin/env python3 """Load CoVisco-L-14 and extract image embeddings. This is a self-contained loader for the open-sourced CoVisco vision encoder. It does NOT depend on the open_clip package - only on torch / transformers / torchvision / safetensors (see requirements.txt). Example: python load_covisco.py --weights model.safetensors --image path/to/img.jpg """ import argparse import json import os import torch from PIL import Image from covisco_vit import CoViscoEncoderConfig # noqa: F401 (kept for back-compat) try: # package / trust_remote_code context from .covisco_model import (CoViscoModel, make_image_preprocess, make_native_preprocess, read_video_frames) except ImportError: # flat script context from covisco_model import (CoViscoModel, make_image_preprocess, make_native_preprocess, read_video_frames) # `read_video_frames` is re-exported from covisco_model (single source of truth) # so `from load_covisco import read_video_frames` keeps working. __all__ = ["build_model", "build_preprocess", "build_native_preprocess", "encode_image", "encode_video", "embed_images", "embed_videos", "read_video_frames"] def build_model(config_path: str, weights_path: str, device: str = "cpu", image_size: int = None, segment_t_size: int = None): """Load CoViscoModel via ``from_pretrained`` and apply runtime overrides. Weights are loaded with ``CoViscoModel.from_pretrained`` from the directory that holds ``config.json`` (it reads ``model.safetensors`` there), so ``config_path`` determines the model directory and ``weights_path`` is only used to warn if it points elsewhere. ``image_size`` and ``segment_t_size`` optionally override the values stored in config.json. Both are runtime-only (they do not change any weight shape: patch embedding is a conv, positions are RoPE, the abstract query tokens depend on ``num_query_per_seg``, and the RoPE module does not depend on ``segment_t_size``), so they are applied *after* loading by setting encoder attributes. ``image_size`` is informational only — the encoder derives its patch grid from the runtime input shape. For video, the frame count T must be a positive multiple of the effective segment_t_size (asserted inside the encoder's get_segments). """ with open(config_path) as f: cfg = json.load(f) if image_size is not None and image_size < 1: raise ValueError(f"image_size must be >= 1, got {image_size}") if segment_t_size is not None and segment_t_size < 1: raise ValueError(f"segment_t_size must be >= 1, got {segment_t_size}") model_dir = os.path.dirname(os.path.abspath(config_path)) if os.path.dirname(os.path.abspath(weights_path)) != model_dir: print(f"[WARN] from_pretrained loads model.safetensors from {model_dir}; " f"the --weights path {weights_path} is ignored.") # from_pretrained reports missing/unexpected keys itself. The release stores # the encoder twice (under ``encoder.*`` and its alias ``visual.*``); both # resolve to the same module, so a clean load reports none. model = CoViscoModel.from_pretrained(model_dir) # Apply runtime-only overrides on the live encoder (no weight depends on them). if image_size is not None: model.encoder.image_size = image_size model.encoder.config.image_size = image_size if segment_t_size is not None: model.set_segment_t_size(segment_t_size) effective_seg_t = model.encoder.segment_t_size print(f"[INFO] effective segment_t_size = {effective_seg_t} " f"(video frame count T must be a multiple of it)") return model.eval().to(device), cfg def build_preprocess(cfg: dict, size: int = None): """Square validation transform (shortest-edge resize + center crop). Thin wrapper over :func:`covisco_model.make_image_preprocess`; equivalent to ``model.build_preprocess(size)`` on a ``from_pretrained`` model. ``size`` overrides ``preprocess_cfg['size']`` (config.json default: 224). """ return make_image_preprocess(cfg["preprocess_cfg"], size) def build_native_preprocess(cfg: dict, max_side: int = 1400): """Aspect-ratio-preserving transform at (near-)native resolution. Thin wrapper over :func:`covisco_model.make_native_preprocess`; equivalent to ``model.build_native_preprocess(max_side)`` on a ``from_pretrained`` model. Keeps the aspect ratio, caps the long side at ``max_side``, and rounds each side to a multiple of ``patch_size``. """ return make_native_preprocess(cfg["preprocess_cfg"], cfg["covisco_encoder_cfg"]["patch_size"], max_side) def encode_image(model, preprocess=None, image: Image.Image = None, device: str = "cpu", branch: str = "to_image_caption", return_intermediates: bool = False, return_attentions: bool = False): """Thin wrapper over ``model.encode_image`` (kept for back-compat). Prefer ``model.encode_image(image, preprocess, branch)`` directly. The ``device`` argument is ignored — the embedding is computed on the model's own device (``build_model`` already placed it there). With ``return_intermediates`` / ``return_attentions`` the full forward dict is returned instead of a single tensor. """ if image is None: raise ValueError("encode_image requires an image") return model.encode_image(image, preprocess=preprocess, branch=branch, return_intermediates=return_intermediates, return_attentions=return_attentions) def encode_video(model, preprocess, frames, device: str = "cpu", branch: str = "to_video_caption", visible_indices=None, return_intermediates: bool = False, return_attentions: bool = False): """Thin wrapper over ``model.encode_video`` (kept for back-compat). Prefer ``model.encode_video(frames, preprocess, branch, visible_indices)`` directly. The ``device`` argument is ignored — the embedding is computed on the model's own device. With ``return_intermediates`` / ``return_attentions`` the full forward dict is returned instead of a single tensor. """ return model.encode_video(frames, preprocess=preprocess, branch=branch, visible_indices=visible_indices, return_intermediates=return_intermediates, return_attentions=return_attentions) def embed_images(model, inputs, preprocess=None, branch: str = "to_image_caption", return_intermediates: bool = False, return_attentions: bool = False): """Thin wrapper over ``model.embed_images`` (batched image embedding).""" return model.embed_images(inputs, preprocess=preprocess, branch=branch, return_intermediates=return_intermediates, return_attentions=return_attentions) def embed_videos(model, inputs, preprocess=None, branch: str = "to_video_caption", visible_indices=None, return_intermediates: bool = False, return_attentions: bool = False): """Thin wrapper over ``model.embed_videos`` (batched video embedding).""" return model.embed_videos(inputs, preprocess=preprocess, branch=branch, visible_indices=visible_indices, return_intermediates=return_intermediates, return_attentions=return_attentions) def main(): here = os.path.dirname(os.path.abspath(__file__)) ap = argparse.ArgumentParser() ap.add_argument("--config", default=os.path.join(here, "config.json")) ap.add_argument("--weights", default=os.path.join(here, "model.safetensors")) ap.add_argument("--image", default=None, help="Optional image path; smoke test if omitted") ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu") ap.add_argument("--native_resolution", action="store_true", help="Keep the original aspect ratio at (near-)native " "resolution instead of the square 224 transform") ap.add_argument("--max_side", type=int, default=1400, help="Long-side cap (pixels) under --native_resolution") ap.add_argument("--image_size", type=int, default=None, help="Override the square input resolution (config.json " "default: 224). Informational only; the encoder " "accepts any resolution.") ap.add_argument("--segment_t_size", type=int, default=None, help="Override the video temporal segment size " "(config.json default: 32). Runtime-only; video frame " "count T must be a positive multiple of it.") args = ap.parse_args() model, cfg = build_model(args.config, args.weights, args.device, image_size=args.image_size, segment_t_size=args.segment_t_size) if args.native_resolution: preprocess = build_native_preprocess(cfg, max_side=args.max_side) else: preprocess = build_preprocess(cfg) if args.image: img = Image.open(args.image) else: print("[smoke test] no --image given, using a blank 224x224 image") img = Image.new("RGB", (cfg["preprocess_cfg"]["size"],) * 2, color=(127, 127, 127)) emb = encode_image(model, preprocess, img, args.device) print(f"to_image_caption embedding: shape={tuple(emb.shape)} " f"| L2 norm={emb.norm(dim=-1).item():.4f} (expected ~1.0)") if __name__ == "__main__": main()