"""Codec (compressed-video) preprocessing backend for LlavaOnevision2_5. This module supplies the six symbols that ``processing_llava_onevision2_5.LlavaOnevision2_5Processor.__call__`` imports when it is called with ``video_backend="codec"``: CodecConfig process_codec_video drop_padding_canvases codec_positions_for_processor rewrite_text_with_codec_positions codec_image_processor_outputs Unlike the frame-sampling backend, the codec backend turns a video into a small set of *canvases*. A canvas is a mosaic: its patches are taken from several different source frames, chosen by bitcost energy. Each patch therefore carries its own ``(t, h, w)`` source position, and the model consumes those positions through ``forward(..., patch_positions=...)`` to build 3-D RoPE. Feeding the canvases as if they were ordinary video frames would discard the temporal information entirely. Requires the ``codec-video-prep`` package (>= 0.3.0) for the native decoding and canvas construction; it is imported lazily so that importing this module never fails on installations that only use the frame-sampling path. """ from __future__ import annotations import hashlib import json import os import shutil from dataclasses import dataclass, field, asdict from pathlib import Path from typing import Any, Dict, List, Optional, Tuple import numpy as np import torch from PIL import Image VISION_START = "<|vision_start|>" VISION_END = "<|vision_end|>" IMAGE_PAD = "<|image_pad|>" # This checkpoint's vision tower: patch 16, 3x3 spatial merge. DEFAULT_PATCH_SIZE = 16 DEFAULT_SPATIAL_MERGE_SIZE = 3 try: # optional: only needed for POSIX advisory locking of the cache import fcntl except ImportError: # pragma: no cover - non-POSIX fcntl = None # type: ignore[assignment] # The canvas timestamp format lives in its own module, copied verbatim from the # training encoder so inference and training cannot drift apart. Keep this # import at module level: when the repo is loaded as remote code, transformers # scans the source for relative imports and copies those siblings into its # module cache, and an import hidden inside a function is not copied. try: from .canvas_timestamp_schema import ( SCHEMA as CANVAS_TIMESTAMP_SCHEMA, rewrite_existing_canvas_wrappers, summarize_canvases, ) except ImportError: # plain directory on sys.path, not loaded as remote code from canvas_timestamp_schema import ( # type: ignore[no-redef] SCHEMA as CANVAS_TIMESTAMP_SCHEMA, rewrite_existing_canvas_wrappers, summarize_canvases, ) # ============================================================================= # CodecConfig # ============================================================================= @dataclass class CodecConfig: """Codec preprocessing settings. Defaults reproduce the released inference recipe: 512 candidate frames, 64 canvases, patch 16, 3x3 blocks, 313600-pixel canvas budget. ``max_pixels`` is overwritten by the processor from its own pixel knob so the canvas budget and the image-processor budget cannot drift apart. ``options`` passes advanced ``BitcostReadinessConfig`` fields straight to ``codec_video_prep.prepare_video``; unknown names raise there, by design. """ strategy: str = "adaptive_pwindow" target_canvas: int = 64 num_sampled_frames: int = 512 patch: int = DEFAULT_PATCH_SIZE block_size: int = 3 max_pixels: int = 313600 canvas_format: str = "png" cache_root: Optional[str] = None options: Dict[str, Any] = field(default_factory=dict) def __post_init__(self) -> None: if int(self.target_canvas) <= 0: raise ValueError("target_canvas must be > 0") if int(self.num_sampled_frames) <= 0: raise ValueError("num_sampled_frames must be > 0") if int(self.patch) <= 0: raise ValueError("patch must be > 0") if int(self.max_pixels) <= 0: raise ValueError("max_pixels must be > 0") if self.canvas_format not in ("png", "jpg", "npy"): raise ValueError( f"canvas_format must be one of png/jpg/npy, got {self.canvas_format!r}" ) def resolved_cache_root(self) -> Path: if self.cache_root: return Path(self.cache_root) env = os.environ.get("CVP_CODEC_CACHE_ROOT") if env: return Path(env) return Path.home() / ".cache" / "codec_video_prep" / "canvases" def cache_key(self, video: str) -> str: payload = dict(asdict(self)) payload.pop("cache_root", None) payload["video"] = str(video) try: payload["mtime"] = os.path.getmtime(video) payload["size"] = os.path.getsize(video) except OSError: pass raw = json.dumps(payload, sort_keys=True, default=str) return hashlib.md5(raw.encode()).hexdigest() # ============================================================================= # process_codec_video # ============================================================================= def _require_codec_video_prep(): try: import codec_video_prep # noqa: F401 except ImportError as exc: # pragma: no cover raise ImportError( "video_backend='codec' needs the `codec-video-prep` package (>=0.3.0), " "which provides the patched FFmpeg/dav1d bitcost decoder. Install the " "release wheel for your Python ABI, then re-run. " "Use video_backend='frames' for plain frame sampling." ) from exc import codec_video_prep as cvp if not hasattr(cvp, "prepare_video"): raise ImportError( "The installed codec-video-prep is too old: it has no `prepare_video` " "(needs >= 0.3.0). Upgrade to the released wheel." ) return cvp def process_codec_video(video: str, cfg: CodecConfig) -> Dict[str, Any]: """Run codec preprocessing for one video and return its canvases. Returns a dict with ``images`` (list of RGB ``PIL.Image``), ``src_positions`` (``int`` array ``[total_patches, 3]`` of ``(src_frame, patch_row, patch_col)``), ``fps``, ``out_dir`` and ``meta``. Results are cached per (video, config) under ``cfg.resolved_cache_root()`` so repeated evaluation of the same video does not re-decode it. """ cvp = _require_codec_video_prep() video = str(video) if not os.path.exists(video): raise FileNotFoundError(f"codec backend: video not found: {video}") root = cfg.resolved_cache_root() out_dir = root / f"{Path(video).stem}_{cfg.cache_key(video)}" done_marker = out_dir / "src_patch_position.npy" if done_marker.exists(): return _load_codec_dir(cvp, out_dir) root.mkdir(parents=True, exist_ok=True) lock_path = root / f".{out_dir.name}.lock" lock_fd = os.open(str(lock_path), os.O_CREAT | os.O_RDWR, 0o644) try: if fcntl is not None: fcntl.flock(lock_fd, fcntl.LOCK_EX) # Another process may have finished while we waited for the lock. if done_marker.exists(): return _load_codec_dir(cvp, out_dir) # prepare_video requires a non-existent or empty out_dir; a partial # directory from an earlier failure must go. if out_dir.exists(): shutil.rmtree(out_dir) cvp.prepare_video( video=video, out_dir=str(out_dir), strategy=cfg.strategy, target_canvas=int(cfg.target_canvas), num_sampled_frames=int(cfg.num_sampled_frames), patch=int(cfg.patch), block_size=int(cfg.block_size), max_pixels=int(cfg.max_pixels), canvas_format=cfg.canvas_format, **dict(cfg.options), ) return _load_codec_dir(cvp, out_dir) finally: try: if fcntl is not None: fcntl.flock(lock_fd, fcntl.LOCK_UN) finally: os.close(lock_fd) def _load_codec_dir(cvp, out_dir: Path) -> Dict[str, Any]: result = cvp.load_inference_result(str(out_dir)) return { "images": list(result.images), "src_positions": np.asarray(result.src_positions), "fps": float(result.fps), "out_dir": str(out_dir), "meta": getattr(result, "meta", {}), } # ============================================================================= # drop_padding_canvases # ============================================================================= def drop_padding_canvases( images: List[Image.Image], src_positions: np.ndarray, ) -> Tuple[List[Image.Image], np.ndarray, int]: """Remove canvases that hold no real patches, and fill stray invalid slots. Short videos (or strategies whose budget exceeds the available content) can emit canvases whose source positions are all ``-1``. Those carry no signal, so they are dropped rather than padded into the prompt. Within a kept canvas, any remaining invalid slot inherits the first valid position so the position array stays dense and aligned with the patch grid. Returns ``(images, src_positions, num_dropped)``. """ src_positions = np.asarray(src_positions) n_canvas = len(images) if n_canvas == 0: return images, src_positions, 0 total_patches = int(src_positions.shape[0]) if total_patches % n_canvas != 0: raise ValueError( f"src_positions length {total_patches} is not divisible by the canvas " f"count {n_canvas}; the preprocessing output is inconsistent." ) ppc = total_patches // n_canvas positions = src_positions.reshape(n_canvas, ppc, 3).copy() keep_mask = (positions[..., 0] >= 0).any(axis=1) dropped = int(n_canvas - int(keep_mask.sum())) if dropped: images = [im for im, keep in zip(images, keep_mask.tolist()) if keep] positions = positions[keep_mask] for canvas_pos in positions: valid = canvas_pos[:, 0] >= 0 if bool(valid.all()): continue canvas_pos[~valid] = canvas_pos[valid][0] return images, positions.reshape(-1, 3), dropped # ============================================================================= # patch-position layout # ============================================================================= def convert_positions_to_block_layout( positions: torch.Tensor, t: int, h: int, w: int, spatial_merge_size: int = DEFAULT_SPATIAL_MERGE_SIZE, ) -> torch.Tensor: """Reorder row-major ``[t*h*w, 3]`` positions into the merger's block layout. The patch merger consumes patches in ``spatial_merge_size`` x ``spatial_merge_size`` blocks, so the positions must be permuted the same way the image processor permutes the pixel rows. """ sms = int(spatial_merge_size) if sms == 1: return positions if h % sms or w % sms: raise ValueError( f"canvas patch grid {h}x{w} is not divisible by spatial_merge_size={sms}. " "Set the codec `block_size` equal to the vision tower's spatial_merge_size " "so every canvas grid aligns with the merger." ) total = int(t) * int(h) * int(w) indices = torch.arange(total, device=positions.device).view(t, h, w) indices = ( indices.view(t, h // sms, sms, w // sms, sms) .permute(0, 1, 3, 2, 4) .contiguous() .view(total) ) return positions[indices] def codec_positions_for_processor( src_positions: np.ndarray, image_grid_thw: torch.Tensor, device: Any = None, spatial_merge_size: int = DEFAULT_SPATIAL_MERGE_SIZE, ) -> torch.Tensor: """Turn codec source positions into block-layout ``patch_positions``. ``image_grid_thw`` has one row per canvas; the positions are split to match and each chunk is permuted into block layout. A length mismatch is an error rather than something to truncate: it means the canvas geometry and the position array disagree, and silently trimming would misalign every patch. """ if device is None: device = getattr(image_grid_thw, "device", "cpu") positions = torch.as_tensor(np.asarray(src_positions)).long().to(device) chunks: List[torch.Tensor] = [] offset = 0 for row in image_grid_thw: t, h, w = (int(row[0]), int(row[1]), int(row[2])) n = t * h * w chunk = positions[offset : offset + n] if chunk.shape[0] != n: raise ValueError( f"codec patch positions exhausted: canvas grid needs {n} rows but only " f"{chunk.shape[0]} remain (total available {positions.shape[0]})." ) chunks.append( convert_positions_to_block_layout(chunk, t, h, w, spatial_merge_size) ) offset += n if offset != int(positions.shape[0]): raise ValueError( "codec patch position length mismatch: image_grid_thw consumes " f"{offset} positions but {positions.shape[0]} were produced. Check that " "the image processor did not rescale the canvases." ) return torch.cat(chunks, dim=0) # ============================================================================= # text rewriting # ============================================================================= # The per-source-frame "timestamp runs" serializer that used to live here is # gone on purpose. It split one canvas into one block per contributing source # frame, which is not the protocol: a P-window canvas carries patches from many # frames and takes a single time range, not one point timestamp per frame. # Formatting now comes from canvas_timestamp_schema, the training module. def rewrite_text_with_codec_positions( text: str, patch_positions: torch.Tensor, fps: float, decimals: int = 1, spatial_merge_size: int = DEFAULT_SPATIAL_MERGE_SIZE, image_grid_thw: Any = None, ) -> str: """Give every canvas one timestamp: a point if it holds a single source frame, a time range if its patches span several. This is the training-side schema ``canvas_patch_span_point_range_v1``. The formatting is not reimplemented here: ``canvas_timestamp_schema`` is a verbatim copy of the module the training encoder uses, so inference and training cannot drift apart. One canvas is one image: the vision tower runs over it once, and its patches may come from many source frames. Splitting that canvas into one block per source frame — the behaviour this function used to have — tells the language model that several separate images start and end inside what was a single image, and inflates the vision region several-fold. The canvas keeps one wrapper and gets one marker in front of it. """ if image_grid_thw is None: raise ValueError( "canvas timestamps need image_grid_thw to know where each canvas ends; " "pass the grid returned by the image processor." ) summaries = summarize_canvases( patch_positions, image_grid_thw, fps=fps, spatial_merge_size=spatial_merge_size, ) # The chat template emits one <|vision_start|><|video_pad|><|vision_end|> # span for the whole video. Expand it into one wrapper per canvas, then let # the authoritative module prefix each wrapper with its own marker. # Separator between canvas wrappers. Training's mm_plugin emits a newline # between blocks; the frozen eval adapter joins them with nothing. Keep the # training form by default and let a run select the other for comparison. _sep = os.environ.get("CVP_CANVAS_WRAPPER_SEP") _sep = "\n" if _sep is None else _sep body = _sep.join( VISION_START + IMAGE_PAD * s.merged_token_count + VISION_END for s in summaries ) + _sep first_vs = text.find(VISION_START) last_ve = text.rfind(VISION_END) if first_vs == -1 or last_ve == -1: raise ValueError( "codec backend: the prompt has no <|vision_start|>...<|vision_end|> span to " "replace. Build the text with the chat template and a video placeholder." ) tail_start = last_ve + len(VISION_END) if tail_start < len(text) and text[tail_start] == "\n": tail_start += 1 expanded = text[:first_vs] + body + text[tail_start:] rewritten, _info = rewrite_existing_canvas_wrappers( expanded, summaries, decimals=decimals ) return rewritten # ============================================================================= # image-processor bridge # ============================================================================= def codec_image_processor_outputs( image_processor: Any, images: List[Image.Image], max_pixels: Optional[int] = None, patch_size: int = DEFAULT_PATCH_SIZE, ) -> Dict[str, Any]: """Patchify the canvases without letting the image processor rescale them. A canvas's pixels and its source positions are bound together by the patch grid. If ``smart_resize`` shrinks a canvas, every position silently points at the wrong patch, so the budget is raised to at least the largest canvas and the resulting grid is checked against the canvases' true geometry. """ if not images: raise ValueError("codec backend: no canvases to process.") largest = max(im.width * im.height for im in images) budget = max(int(max_pixels or 0), int(largest)) try: out = image_processor(images=images, max_pixels=budget, return_tensors="pt") except TypeError: # Older/newer image processors may not accept max_pixels as a call kwarg. out = image_processor(images=images, return_tensors="pt") grid = out["image_grid_thw"] if int(grid.shape[0]) != len(images): raise ValueError( f"image processor returned {int(grid.shape[0])} grid rows for {len(images)} " "canvases; cannot align patch positions." ) for i, (im, row) in enumerate(zip(images, grid)): exp_h, exp_w = im.height // patch_size, im.width // patch_size got_h, got_w = int(row[1]), int(row[2]) if (got_h, got_w) != (exp_h, exp_w): raise ValueError( f"canvas {i} is {im.width}x{im.height} (expected patch grid " f"{exp_h}x{exp_w} at patch={patch_size}) but the image processor " f"produced {got_h}x{got_w}. The canvas was rescaled, which invalidates " "the source positions. Raise the processor's pixel budget, or lower the " "codec `max_pixels` so canvases stay within it." ) return out __all__ = [ "CodecConfig", "process_codec_video", "drop_padding_canvases", "codec_positions_for_processor", "rewrite_text_with_codec_positions", "codec_image_processor_outputs", "convert_positions_to_block_layout", "CANVAS_TIMESTAMP_SCHEMA", ]