"""Codec-based token filtering (visidx) for the released CoVisco encoder. The encoder natively supports sparse patch selection: ``model(px, visible_indices=visidx)`` computes only the selected patches and derives 4D-RoPE from them (``covisco_vit.get_segments``). This module generates the ``visidx`` indices from video codec signals, mirroring the training-time ``precompute_codec_visidx`` pipeline. Signal backends (tried in order): 1. **cv_reader** (exact, identical to training): the Compressed-Video-Reader C++ extension + patched FFmpeg reads H.264/H.265 macroblock motion vectors and DCT residuals. The scoring functions are embedded below verbatim from ``Compressed_Video_Reader/tool/offline_precompute_llava_codec_assets.py`` (MIT, AcherStyx/Compressed-Video-Reader). Install it from https://github.com/AcherStyx/Compressed-Video-Reader to enable. 2. **PyAV** (fallback): FFmpeg ``AV_FRAME_DATA_MOTION_VECTORS`` side data for motion; luminance frame differences approximate the residual. Two usage modes: 1. End-to-end (scoring runs inline, right before the forward pass):: from codec_visidx import compute_codec_visidx visidx, meta = compute_codec_visidx("video.mp4", num_frames=64, segment_t_size=16, keep_ratio=0.57) out = model(px, modality="video", run_decoder=False, visible_indices=torch.from_numpy(visidx).unsqueeze(0)) 2. Pre-extracted (batch/off output matches the SFT pipeline):: python codec_visidx.py --jsonl videos.jsonl --out_root cache/ # writes cache//visidx.npy + frame_ids.npy + meta.json visidx convention (see ``covisco_vit.get_segments``): - Grid: ``num_frames`` frames, ``(image_size/patch_size)^2`` patches per frame. - Global index ``idx = t * (h*w) + row * w + col``. - Tokens per segment (``segment_t_size`` frames) must be equal, and the whole array sorted ascending (``get_segments`` reshapes to ``(num_seg, L//num_seg)``). """ import argparse import json import os from typing import Any, Dict, List, Optional, Tuple import numpy as np try: import av _HAS_AV = True except ImportError: # pragma: no cover av = None _HAS_AV = False try: from cv_reader import api as cv_api _HAS_CV_READER = True except ImportError: # pragma: no cover cv_api = None _HAS_CV_READER = False # --------------------------------------------------------------------------- # Frame sampling (must stay consistent with the reader used at forward time) # --------------------------------------------------------------------------- def sample_frame_ids(total_frames: int, num_frames: int) -> List[int]: """Uniform sampling via np.linspace(0, total-1, num_frames). Use the *same* rule when building the (B, C, T, H, W) tensor, so the t-th frame at forward time matches the t-th scored frame here. """ if total_frames <= 0: return [0] * int(num_frames) ids = np.linspace(0, total_frames - 1, int(num_frames)).astype(int) return [int(x) for x in ids.tolist()] # --------------------------------------------------------------------------- # Scoring functions — verbatim from Compressed_Video_Reader/tool/ # offline_precompute_llava_codec_assets.py (MIT), so the cv_reader path is # numerically identical to the training-time precompute pipeline. # --------------------------------------------------------------------------- def _residual_y_generic(residual: np.ndarray) -> np.ndarray: if residual.ndim == 2: return residual if residual.ndim == 3 and residual.shape[2] >= 1: if residual.shape[2] == 3: try: import cv2 return cv2.cvtColor(residual, cv2.COLOR_BGR2YUV)[:, :, 0] except Exception: return residual[:, :, 0] return residual[:, :, 0] raise ValueError(f"Unexpected residual shape: {residual.shape}") def _residual_energy_norm(res_y: np.ndarray, pct: float = 95.0, use_grad: bool = False) -> np.ndarray: if not use_grad: x = np.abs(res_y.astype(np.float32) - 128.0) else: r = res_y.astype(np.float32) gx = np.abs(np.roll(r, -1, axis=1) - np.roll(r, 1, axis=1)) gy = np.abs(np.roll(r, -1, axis=0) - np.roll(r, 1, axis=0)) x = 0.5 * (gx + gy) a = float(np.percentile(x, pct)) a = max(a, 1.0) return np.clip(x / a, 0.0, 1.0).astype(np.float32) def _mv_energy_norm(mv: np.ndarray, H: int, W: int, mv_unit_div: float = 4.0, pct: float = 95.0, compensate: str = "median") -> np.ndarray: if mv.ndim == 3 and mv.shape[2] >= 2: mvx_q = mv[:, :, 0] mvy_q = mv[:, :, 1] else: raise ValueError(f"Unexpected motion_vector shape: {mv.shape}") vx = mvx_q.astype(np.float32) / float(mv_unit_div) vy = mvy_q.astype(np.float32) / float(mv_unit_div) c = (compensate or "median").lower() if c == "median": vx = vx - np.median(vx) vy = vy - np.median(vy) elif c == "mean": vx = vx - float(np.mean(vx)) vy = vy - float(np.mean(vy)) elif c == "none": pass else: raise ValueError(f"Unknown mv compensate: {compensate}") mag = np.sqrt(vx * vx + vy * vy).astype(np.float32) a = float(np.percentile(mag, pct)) a = max(a, 1e-6) norm = np.clip(mag / a, 0.0, 1.0) try: import cv2 norm_u = cv2.resize(norm, (int(W), int(H)), interpolation=cv2.INTER_NEAREST) except ImportError: # cv2-free fallback: nearest "resize" via index rounding (slower, same semantics) hh, ww = norm.shape yi = (np.arange(int(H)) * hh // int(H)).clip(0, hh - 1) xi = (np.arange(int(W)) * ww // int(W)).clip(0, ww - 1) norm_u = norm[np.ix_(yi, xi)] return norm_u.astype(np.float32) def _cv_reader_fetch_mvres_by_frame_ids( video_path: str, frame_ids: List[int], with_residual: bool = True, seek_to_frame: Optional[int] = None, decode_len: Optional[int] = None, ) -> List[Dict[str, Any]]: """Fetch motion vectors + residuals for the requested frame ids via cv_reader. Verbatim port of offline_precompute_llava_codec_assets.py (MIT). """ if not _HAS_CV_READER: raise RuntimeError("cv_reader not available") frame_ids = [int(x) for x in list(frame_ids)] if frame_ids is not None else [] if len(frame_ids) == 0: return [] pos_map: Dict[int, List[int]] = {} for i, fid in enumerate(frame_ids): pos_map.setdefault(int(fid), []).append(i) out: List[Any] = [None] * len(frame_ids) max_fid = max(frame_ids) def _all_done() -> bool: for q in pos_map.values(): if q: return False return True def _cb(d: Dict[str, Any]): idx = int(d.get("frame_idx", -1)) if idx in pos_map and pos_map[idx]: j = pos_map[idx].pop(0) mv = np.asarray(d["motion_vector"]) if with_residual: if "residual_y" in d: ry = np.asarray(d["residual_y"]) else: ry = _residual_y_generic(np.asarray(d["residual"])) out[j] = {"frame_idx": idx, "motion_vector": mv, "residual_y": ry} else: out[j] = {"frame_idx": idx, "motion_vector": mv} return (not _all_done()) if hasattr(cv_api, "read_video_cb"): without_residual = 0 if with_residual else 1 use_seek = (seek_to_frame is not None) and (int(seek_to_frame) >= 0) if use_seek: st = int(seek_to_frame) if decode_len is None: max_frames = int(max(0, max_fid - st) + 1) else: max_frames = int(max(1, int(decode_len))) try: cv_api.read_video_cb( str(video_path), _cb, int(without_residual), int(max_frames), frame_ids, int(st), int(max_frames), ) except TypeError: legacy_max_frames = int(max_fid) + 1 cv_api.read_video_cb(str(video_path), _cb, int(without_residual), int(legacy_max_frames), frame_ids) else: max_frames = int(max_fid) + 1 cv_api.read_video_cb(str(video_path), _cb, int(without_residual), int(max_frames), frame_ids) else: frames = cv_api.read_video(str(video_path), 0, -1) if not isinstance(frames, (list, tuple)): frames = list(frames) for i, fid in enumerate(frame_ids): fid2 = max(0, min(int(fid), len(frames) - 1)) fr = frames[fid2] mv = np.asarray(fr["motion_vector"]) if with_residual: if "residual_y" in fr: ry = np.asarray(fr["residual_y"]) else: ry = _residual_y_generic(np.asarray(fr["residual"])) out[i] = {"frame_idx": fid2, "motion_vector": mv, "residual_y": ry} else: out[i] = {"frame_idx": fid2, "motion_vector": mv} last = None for i in range(len(out)): if out[i] is None: if last is not None: out[i] = last else: last = out[i] if last is not None: for i in range(len(out)): if out[i] is None: out[i] = last return out # type: ignore # --------------------------------------------------------------------------- # Energy-map post-processing (identical to the training-time pipeline) # --------------------------------------------------------------------------- def _resize_shorter_centercrop_map(arr2d: np.ndarray, out_size: int) -> np.ndarray: """Map a (H,W) energy map to (out_size,out_size). Resize shorter side to ``out_size`` then center-crop — spatially consistent with ``build_preprocess`` (Resize + CenterCrop), so the scoring grid aligns with the patch grid the ViT actually sees. """ H, W = arr2d.shape[:2] out_size = int(out_size) if H <= 0 or W <= 0: return np.zeros((out_size, out_size), dtype=np.float32) scale = float(out_size) / float(min(H, W)) Hn = max(out_size, int(round(H * scale))) Wn = max(out_size, int(round(W * scale))) from PIL import Image img = Image.fromarray(arr2d.astype(np.float32)) img = img.resize((Wn, Hn), Image.BILINEAR) resized = np.asarray(img, dtype=np.float32) top = (Hn - out_size) // 2 left = (Wn - out_size) // 2 return resized[top:top + out_size, left:left + out_size].copy() def frame_scores(fused_hw: np.ndarray, image_size: int, patch_size: int) -> np.ndarray: """Pool a frame's fused energy map (H,W) into (h*w,) patch scores, row-major.""" sq = _resize_shorter_centercrop_map(fused_hw, out_size=int(image_size)) # (S,S) p = int(patch_size) hb = int(image_size) // p wb = int(image_size) // p s = sq[: hb * p, : wb * p].reshape(hb, p, wb, p).sum(axis=(1, 3)) # (hb, wb) return s.reshape(-1).astype(np.float32) # (hb*wb,) # --------------------------------------------------------------------------- # PyAV fallback signal extraction # --------------------------------------------------------------------------- def _decode_frames(path: str, frame_ids: List[int]): """Decode the requested frames via PyAV. Returns (grays, rgbs, H, W, mv_maps): per-frame grayscale/RGB images and (H,W) motion-energy maps from macroblock motion-vector side data (None per frame when the codec does not expose them). """ container = av.open(path) stream = container.streams.video[0] stream.thread_type = "AUTO" wanted = sorted(set(int(i) for i in frame_ids)) out_gray: List[np.ndarray] = [] out_rgb: List[Any] = [] motion_maps: List[Optional[np.ndarray]] = [] H = W = 0 idx = -1 wanted_set = set(wanted) for frame in container.decode(stream): idx += 1 if idx not in wanted_set: continue rgb = frame.to_image() # PIL gray = np.asarray(rgb.convert("L"), dtype=np.float32) H, W = gray.shape[:2] # Motion vectors from side data (FFmpeg AVMotionVector): # 10 int32 per vector: source, w, h, src_x, src_y, dst_x, dst_y, # flags, motion_x, motion_y mv_map = np.zeros((H, W), dtype=np.float32) got_mv = False try: for sd in frame.side_data: if sd.type.name == "MOTION_VECTORS": arr = np.frombuffer(bytes(sd.data), dtype=np.int32) n = arr.size // 10 arr = arr[:n * 10].reshape(n, 10) for row in arr: _, bw, bh, sx, sy, _, _, _, mx, my = row magnitude = float(mx * mx + my * my) ** 0.5 x0 = max(0, min(W - 1, int(sx))) y0 = max(0, min(H - 1, int(sy))) x1 = max(0, min(W - 1, int(sx) + max(1, int(bw)))) y1 = max(0, min(H - 1, int(sy) + max(1, int(bh)))) mv_map[y0:y1, x0:x1] += magnitude got_mv = True except Exception: pass out_gray.append(gray) out_rgb.append(rgb) motion_maps.append(mv_map if got_mv else None) if idx >= max(wanted_set): break container.close() gray_by_id = dict(zip(wanted, out_gray)) rgb_by_id = dict(zip(wanted, out_rgb)) mv_by_id = dict(zip(wanted, motion_maps)) grays = [gray_by_id.get(i, out_gray[-1] if out_gray else np.zeros((H, W), np.float32)) for i in frame_ids] rgbs = [rgb_by_id.get(i, out_rgb[-1] if out_rgb else None) for i in frame_ids] mvs = [mv_by_id.get(i) for i in frame_ids] return grays, rgbs, H, W, mvs def _frame_diff_energy(gray_a: np.ndarray, gray_b: np.ndarray) -> np.ndarray: """|a - b| energy map between two grayscale frames (residual proxy).""" d = np.abs(gray_a - gray_b) m = float(d.max()) return d / m if m > 0 else d def _pct_norm(x: np.ndarray, pct: float) -> np.ndarray: """Percentile normalization (same clipping rule as *_energy_norm).""" a = float(np.percentile(x, pct)) if x.size else 0.0 a = max(a, 1.0) return np.clip(x / a, 0.0, 1.0) # --------------------------------------------------------------------------- # visidx computation # --------------------------------------------------------------------------- def _probe_total_frames(video_path: str) -> int: with av.open(video_path) as container: stream = container.streams.video[0] total_frames = int(stream.frames or 0) if total_frames <= 0: if stream.average_rate and container.duration is not None: total_frames = int(float(container.duration) * float(stream.average_rate)) return total_frames def compute_codec_visidx( video_path: str, num_frames: int, segment_t_size: int, image_size: int = 224, patch_size: int = 14, keep_ratio: float = 0.57, mv_unit_div: float = 4.0, mv_pct: float = 95.0, res_pct: float = 95.0, w_mv: float = 1.0, w_res: float = 1.0, mv_compensate: str = "median", res_use_grad: bool = False, keep_first_per_segment: bool = True, verbose: bool = False, ) -> Tuple[np.ndarray, Dict]: """Compute codec-filtered patch indices (visidx) for one video. Signal backend priority: ``cv_reader`` (exact MV + DCT residual, identical to the training-time pipeline) -> PyAV motion-vector side data + frame-diff residual proxy. Returns ``(visidx, meta)``; ``visidx`` is int64, ascending, shape ``(num_seg * k_seg,)``. Use it as:: model(px, modality="video", run_decoder=False, visible_indices=torch.from_numpy(visidx).unsqueeze(0)) with ``px`` built from the same ``num_frames``-linspace sampling and the same square ``image_size`` preprocessing. ``keep_ratio`` default 0.57 matches the benchmark evaluation config (0.5 is the SFT training default). """ assert image_size % patch_size == 0, ( f"image_size({image_size}) must be divisible by patch_size({patch_size})") per_frame = (image_size // patch_size) ** 2 assert num_frames % segment_t_size == 0, ( f"num_frames({num_frames}) must be divisible by segment_t_size({segment_t_size})") num_seg = num_frames // segment_t_size total_frames = _probe_total_frames(video_path) frame_ids = sample_frame_ids(total_frames, num_frames) # ---- per-frame scoring ---- scores = np.zeros((int(num_frames), int(per_frame)), dtype=np.float32) H0 = W0 = 0 if _HAS_CV_READER: signal = "cv_reader(mv+residual)" items = _cv_reader_fetch_mvres_by_frame_ids(video_path, frame_ids, with_residual=True) if not isinstance(items, (list, tuple)) or len(items) == 0: raise RuntimeError(f"cv_reader returned empty: {video_path}") ry0 = np.asarray(items[0].get("residual_y", np.zeros((0, 0)))) if ry0.ndim >= 2 and ry0.size: H0, W0 = int(ry0.shape[0]), int(ry0.shape[1]) if H0 <= 0 or W0 <= 0: grays, _rgbs, H0, W0, _m = _decode_frames(video_path, frame_ids) for t in range(int(num_frames)): it = items[int(t)] res_norm = _residual_energy_norm(np.asarray(it["residual_y"]), pct=float(res_pct), use_grad=bool(res_use_grad)) mv_norm = _mv_energy_norm(np.asarray(it["motion_vector"]), H=int(H0), W=int(W0), mv_unit_div=float(mv_unit_div), pct=float(mv_pct), compensate=str(mv_compensate)) denom = float(w_mv + w_res) if (w_mv + w_res) != 0 else 1.0 fused = np.clip((float(w_mv) * mv_norm + float(w_res) * res_norm) / denom, 0.0, 1.0) scores[t] = frame_scores(fused, image_size=int(image_size), patch_size=int(patch_size)) else: grays, _rgbs, H0, W0, mv_maps = _decode_frames(video_path, frame_ids) any_mv = any(m is not None for m in mv_maps) signal = "pyav_mv+frame_diff" if any_mv else "frame_diff" for t in range(int(num_frames)): prev = grays[t - 1] if t > 0 else grays[t] res_norm = _pct_norm(_frame_diff_energy(grays[t], prev), pct=95.0) if mv_maps[t] is not None: mv_norm = _pct_norm(mv_maps[t], pct=95.0) else: mv_norm = res_norm denom = float(w_mv + w_res) if (w_mv + w_res) != 0 else 1.0 fused = np.clip((float(w_mv) * mv_norm + float(w_res) * res_norm) / denom, 0.0, 1.0) scores[t] = frame_scores(fused, image_size=int(image_size), patch_size=int(patch_size)) # ---- equal top-K per segment ---- k_seg = max(1, int(round(float(keep_ratio) * segment_t_size * per_frame))) k_seg = min(k_seg, segment_t_size * per_frame) k_floored_to_first = False if keep_first_per_segment and k_seg < per_frame: k_seg = per_frame k_floored_to_first = True selected: List[np.ndarray] = [] for s in range(int(num_seg)): f0 = s * segment_t_size seg = scores[f0:f0 + segment_t_size].reshape(-1) if keep_first_per_segment: first = np.arange(per_frame, dtype=np.int64) rest_budget = k_seg - per_frame if rest_budget > 0: seg_rest = seg.copy() seg_rest[:per_frame] = -np.inf top_rest = np.argpartition(seg_rest, -rest_budget)[-rest_budget:] local = np.concatenate([first, top_rest.astype(np.int64)]) else: local = first else: k = min(k_seg, seg.size) local = np.argpartition(seg, -k)[-k:].astype(np.int64) local_t = local // per_frame hw = local % per_frame gidx = (f0 + local_t) * per_frame + hw selected.append(gidx.astype(np.int64)) visidx = np.sort(np.concatenate(selected)).astype(np.int64) meta = { "num_frames": int(num_frames), "segment_t_size": int(segment_t_size), "num_seg": int(num_seg), "image_size": int(image_size), "patch_size": int(patch_size), "per_frame_patches": int(per_frame), "total_patches": int(num_frames * per_frame), "keep_ratio": float(keep_ratio), "k_per_segment": int(k_seg), "keep_first_per_segment": bool(keep_first_per_segment), "k_floored_to_first": bool(k_floored_to_first), "visidx_len": int(visidx.size), "total_frames": int(total_frames), "orig_hw": [int(H0), int(W0)], "signal": signal, "video": os.path.abspath(str(video_path)), "w_mv": float(w_mv), "w_res": float(w_res), "mv_compensate": str(mv_compensate), "res_use_grad": bool(res_use_grad), } if verbose: print(f"[codec_visidx] {video_path}: {signal}, keep " f"{visidx.size}/{num_frames * per_frame} patches " f"({visidx.size / (num_frames * per_frame):.1%})") return visidx, meta def load_visidx(cache_dir: str) -> np.ndarray: """Load a pre-extracted visidx.npy from a cache directory.""" return np.load(os.path.join(cache_dir, "visidx.npy")) # --------------------------------------------------------------------------- # Pre-extraction CLI (output layout matches the SFT precompute pipeline) # --------------------------------------------------------------------------- def _read_jsonl(path: str) -> List[Dict]: out = [] with open(path) as f: for line in f: line = line.strip() if line: out.append(json.loads(line)) return out def main(): ap = argparse.ArgumentParser( description="Precompute codec-filtered visidx for CoVisco-L-14 " "(cv_reader exact if installed; PyAV motion vectors + " "frame-diff residual proxy otherwise).") ap.add_argument("--jsonl", required=True, help='JSONL with {"video": path, "key": unique_id} per line') ap.add_argument("--out_root", required=True, help="Output root; writes //{visidx,frame_ids}.npy + meta.json") ap.add_argument("--num_frames", type=int, default=64) ap.add_argument("--segment_t_size", type=int, default=16) ap.add_argument("--image_size", type=int, default=224) ap.add_argument("--patch_size", type=int, default=14) ap.add_argument("--keep_ratio", type=float, default=0.57) ap.add_argument("--w_mv", type=float, default=1.0) ap.add_argument("--w_res", type=float, default=1.0) ap.add_argument("--mv_compensate", type=str, default="median", choices=["median", "mean", "none"]) ap.add_argument("--res_use_grad", action="store_true") args = ap.parse_args() jobs = _read_jsonl(args.jsonl) ok = fail = 0 for i, job in enumerate(jobs, 1): video = job["video"] key = job.get("key", os.path.splitext(os.path.basename(job["video"]))[0]) out_dir = os.path.join(args.out_root, key) try: os.makedirs(out_dir, exist_ok=True) visidx, meta = compute_codec_visidx( video, num_frames=args.num_frames, segment_t_size=args.segment_t_size, image_size=args.image_size, patch_size=args.patch_size, keep_ratio=args.keep_ratio, w_mv=args.w_mv, w_res=args.w_res, mv_compensate=args.mv_compensate, res_use_grad=args.res_use_grad, ) np.save(os.path.join(out_dir, "visidx.npy"), visidx) np.save(os.path.join(out_dir, "frame_ids.npy"), np.asarray(sample_frame_ids(meta["total_frames"], meta["num_frames"]), dtype=np.int32)) with open(os.path.join(out_dir, "meta.json"), "w") as f: json.dump(meta, f, indent=2) ok += 1 print(f"[{i}/{len(jobs)}] OK {key}: {visidx.size} indices " f"({meta['signal']})", flush=True) except Exception as e: # noqa: BLE001 fail += 1 print(f"[{i}/{len(jobs)}] FAIL {key}: {e}", flush=True) print(f"done: {ok} ok, {fail} failed") if __name__ == "__main__": main()