"""VLM2Vec-V2.0 编码封装(Q3 决策:帧级 image emb + clip 级 video emb 两级)。 复用 MAGIC-video 的 VLM2VecV2EmbeddingModel wrapper(权重已在本地 HF 缓存): - encode_frames: 关键帧 JPEG 批量图像编码(wrapper.encode_image 内部真批量) - encode_clip: 一个 clip 的关键帧序列当作视频编码 → 1 个 clip 级向量 (复用已保存的关键帧 JPEG,不重复解码视频;帧数补齐为偶数 以满足 Qwen2-VL temporal patch=2) - encode_texts: 检索 query 文本编码(推理阶段 memory_store 调用) """ import logging import sys import numpy as np import torch from config import MAGIC_SRC, setup_hf_env logger = logging.getLogger(__name__) setup_hf_env() if MAGIC_SRC not in sys.path: sys.path.insert(0, MAGIC_SRC) class MemoryEncoder: def __init__(self, model_name: str = "VLM2Vec/VLM2Vec-V2.0", device: str = "cuda", clip_max_pixels: int = 360 * 420): from worldmm.embedding.vlm2vecv2 import VLM2VecV2EmbeddingModel self.model = VLM2VecV2EmbeddingModel(model_name=model_name, device=device) self.device = device self.clip_max_pixels = clip_max_pixels # 视频/图像的 instruction 常量(与 MMEB 协议一致) from worldmm.embedding.VLM2Vec.src.model.processor import ( QWEN2_VL, VLM_IMAGE_TOKENS, VLM_VIDEO_TOKENS, ) self._img_token = VLM_IMAGE_TOKENS[QWEN2_VL] self._vid_token = VLM_VIDEO_TOKENS[QWEN2_VL] # ---------------------------------------------------------- 帧级编码 def encode_frames(self, image_paths: list, batch_size: int = 16) -> np.ndarray: """关键帧 JPEG → (n, D) 归一化向量。""" embs = [] for i in range(0, len(image_paths), batch_size): batch = image_paths[i:i + batch_size] out = self.model.encode_image( batch, query_text=f"{self._img_token} Represent the given video frame.", ) embs.append(out) return np.concatenate(embs, axis=0) if embs else np.zeros((0, 1536), np.float32) # --------------------------------------------------------- clip 级编码 def encode_clip(self, frames: list, clip_seconds: float) -> np.ndarray: """一个 clip 的帧序列 → (1, D) 视频级向量。 frames: 图片路径列表 或 PIL.Image 列表 或 JPEG bytes 列表 (v2 用 clip 内均匀 8 帧的内存 JPEG,qwen_vl_utils.fetch_image 原生支持 PIL)。 """ import io from PIL import Image from worldmm.embedding.VLM2Vec.src.model.vlm_backbone.qwen2_vl.qwen_vl_utils import ( process_vision_info, ) items = [] for f in frames: if isinstance(f, bytes): items.append(Image.open(io.BytesIO(f)).convert("RGB")) elif isinstance(f, str): items.append(f"file://{f}") else: items.append(f) # PIL.Image if len(items) == 1: items = items * 2 # temporal patch=2 需要至少 2 帧 if len(items) % 2 == 1: items.append(items[-1]) messages = [{ "role": "user", "content": [ { "type": "video", "video": items, "max_pixels": self.clip_max_pixels, "fps": max(len(items) / max(clip_seconds, 1.0), 0.1), }, {"type": "text", "text": "Describe this video."}, ], }] _, video_inputs = process_vision_info(messages) inputs = self.model.processor( text=f"{self._vid_token} Represent the given video.", videos=video_inputs, return_tensors="pt", ) inputs = {k: v.to(self.device) for k, v in inputs.items()} if "pixel_values_videos" in inputs: inputs["pixel_values_videos"] = inputs["pixel_values_videos"].unsqueeze(0) if "video_grid_thw" in inputs: inputs["video_grid_thw"] = inputs["video_grid_thw"].unsqueeze(0) with torch.no_grad(): with torch.autocast(device_type=self.device.split(":")[0], dtype=torch.bfloat16): out = self.model.model(qry=inputs)["qry_reps"] return out.float().cpu().numpy() # ------------------------------------------------------------ 文本编码 def encode_texts(self, texts: list) -> np.ndarray: """检索 query → (n, D)。推理阶段 search_vis 用。""" return self.model.encode_text(texts)