File size: 22,790 Bytes
ce7ee55 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 | ## This file is modified from https://github.com/kq-chen/qwen-vl-utils/blob/main/src/qwen_vl_utils/vision_process.py
from __future__ import annotations
import base64
import logging
import math
import os
import sys
import time
import warnings
from functools import lru_cache
from io import BytesIO
from typing import Dict, Union
import random
import requests
import torch
import torchvision
from packaging import version
from PIL import Image
from torchvision import io, transforms
from torchvision.transforms import InterpolationMode
logger = logging.getLogger(__name__)
IMAGE_FACTOR = 28
MIN_PIXELS = 4 * 28 * 28
MAX_PIXELS = 16384 * 28 * 28
MAX_RATIO = 200
VIDEO_MIN_PIXELS = 128 * 28 * 28
VIDEO_MAX_PIXELS = 768 * 28 * 28
VIDEO_TOTAL_PIXELS = 24576 * 28 * 28
FRAME_FACTOR = 2
FPS = 2.0
FPS_MIN_FRAMES = 4
FPS_MAX_FRAMES = 768
def round_by_factor(number: int, factor: int) -> int:
"""Returns the closest integer to 'number' that is divisible by 'factor'."""
return round(number / factor) * factor
def ceil_by_factor(number: int, factor: int) -> int:
"""Returns the smallest integer greater than or equal to 'number' that is divisible by 'factor'."""
return math.ceil(number / factor) * factor
def floor_by_factor(number: int, factor: int) -> int:
"""Returns the largest integer less than or equal to 'number' that is divisible by 'factor'."""
return math.floor(number / factor) * factor
def smart_resize(
height: int, width: int, factor: int = IMAGE_FACTOR, min_pixels: int = MIN_PIXELS, max_pixels: int = MAX_PIXELS
) -> tuple[int, int]:
"""
Rescales the image so that the following conditions are met:
1. Both dimensions (height and width) are divisible by 'factor'.
2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
3. The aspect ratio of the image is maintained as closely as possible.
"""
if max(height, width) / min(height, width) > MAX_RATIO:
raise ValueError(
f"absolute aspect ratio must be smaller than {MAX_RATIO}, got {max(height, width) / min(height, width)}"
)
h_bar = max(factor, round_by_factor(height, factor))
w_bar = max(factor, round_by_factor(width, factor))
if h_bar * w_bar > max_pixels:
beta = math.sqrt((height * width) / max_pixels)
h_bar = floor_by_factor(height / beta, factor)
w_bar = floor_by_factor(width / beta, factor)
elif h_bar * w_bar < min_pixels:
beta = math.sqrt(min_pixels / (height * width))
h_bar = ceil_by_factor(height * beta, factor)
w_bar = ceil_by_factor(width * beta, factor)
return h_bar, w_bar
def fetch_image(ele: dict[str, str | Image.Image], size_factor: int = IMAGE_FACTOR) -> Image.Image:
if "image" in ele:
image = ele["image"]
else:
image = ele["image_url"]
image_obj = None
if isinstance(image, Image.Image):
image_obj = image
elif image.startswith("http://") or image.startswith("https://"):
image_obj = Image.open(requests.get(image, stream=True).raw)
elif image.startswith("file://"):
image_obj = Image.open(image[7:])
elif image.startswith("data:image"):
if "base64," in image:
_, base64_data = image.split("base64,", 1)
data = base64.b64decode(base64_data)
image_obj = Image.open(BytesIO(data))
else:
image_obj = Image.open(image)
if image_obj is None:
raise ValueError(f"Unrecognized image input, support local path, http url, base64 and PIL.Image, got {image}")
image = image_obj.convert("RGB")
## resize
if "resized_height" in ele and "resized_width" in ele:
resized_height, resized_width = smart_resize(
ele["resized_height"],
ele["resized_width"],
factor=size_factor,
)
else:
width, height = image.size
min_pixels = ele.get("min_pixels", MIN_PIXELS)
max_pixels = ele.get("max_pixels", MAX_PIXELS)
resized_height, resized_width = smart_resize(
height,
width,
factor=size_factor,
min_pixels=min_pixels,
max_pixels=max_pixels,
)
image = image.resize((resized_width, resized_height))
return image
def smart_nframes(
ele: dict,
total_frames: int,
video_fps: int | float,
) -> int:
"""calculate the number of frames for video used for model inputs.
Args:
ele (dict): a dict contains the configuration of video.
support either `fps` or `nframes`:
- nframes: the number of frames to extract for model inputs.
- fps: the fps to extract frames for model inputs.
- min_frames: the minimum number of frames of the video, only used when fps is provided.
- max_frames: the maximum number of frames of the video, only used when fps is provided.
total_frames (int): the original total number of frames of the video.
video_fps (int | float): the original fps of the video.
Raises:
ValueError: nframes should in interval [FRAME_FACTOR, total_frames].
Returns:
int: the number of frames for video used for model inputs.
"""
assert not ("fps" in ele and "nframes" in ele), "Only accept either `fps` or `nframes`"
if "nframes" in ele:
nframes = round_by_factor(ele["nframes"], FRAME_FACTOR)
else:
fps = ele.get("fps", FPS)
min_frames = ceil_by_factor(ele.get("min_frames", FPS_MIN_FRAMES), FRAME_FACTOR)
max_frames = floor_by_factor(ele.get("max_frames", min(FPS_MAX_FRAMES, total_frames)), FRAME_FACTOR)
nframes = total_frames / video_fps * fps
nframes = min(max(nframes, min_frames), max_frames)
nframes = round_by_factor(nframes, FRAME_FACTOR)
if nframes > total_frames:
nframes = total_frames
if not (FRAME_FACTOR <= nframes and nframes <= total_frames):
raise ValueError(f"nframes should in interval [{FRAME_FACTOR}, {total_frames}], but got {nframes}.")
return nframes
def _read_video_torchvision(
ele: dict,
) -> torch.Tensor:
"""read video using torchvision.io.read_video
Args:
ele (dict): a dict contains the configuration of video.
support keys:
- video: the path of video. support "file://", "http://", "https://" and local path.
- video_start: the start time of video.
- video_end: the end time of video.
Returns:
torch.Tensor: the video tensor with shape (T, C, H, W).
"""
video_path = ele["video"]
if version.parse(torchvision.__version__) < version.parse("0.19.0"):
if "http://" in video_path or "https://" in video_path:
warnings.warn("torchvision < 0.19.0 does not support http/https video path, please upgrade to 0.19.0.")
if "file://" in video_path:
video_path = video_path[7:]
st = time.time()
video, audio, info = io.read_video(
video_path,
start_pts=ele.get("video_start", 0.0),
end_pts=ele.get("video_end", None),
pts_unit="sec",
output_format="TCHW",
)
total_frames, video_fps = video.size(0), info["video_fps"]
# logger.info(f"torchvision: {video_path=}, {total_frames=}, {video_fps=}, time={time.time() - st:.3f}s")
if ele['sample_type'] == 'uniform':
nframes = smart_nframes(ele, total_frames=total_frames, video_fps=video_fps)
idx = torch.linspace(0, total_frames - 1, nframes).round().long().tolist()
elif ele['sample_type'] == 'multi_pts':
frames_each_pts = 6
num_pts = 4
fps = 8
nframes = int(total_frames * fps // video_fps)
frames_idx = torch.linspace(0, total_frames - 1, nframes).round().long().tolist()
start_pt = int(frames_each_pts // 2)
end_pt = int(nframes - frames_each_pts // 2 - 1)
pts = torch.linspace(start_pt, end_pt, num_pts).round().long().tolist()
idx = []
for pt in pts:
idx.extend(frames_idx[pt - frames_each_pts // 2 : pt + frames_each_pts // 2])
video = video[idx]
return video
def is_decord_available() -> bool:
import importlib.util
return importlib.util.find_spec("decord") is not None
def _read_video_decord(
ele: dict,
) -> torch.Tensor:
"""read video using decord.VideoReader
Args:
ele (dict): a dict contains the configuration of video.
support keys:
- video: the path of video. support "file://", "http://", "https://" and local path.
- video_start: the start time of video.
- video_end: the end time of video.
Returns:
torch.Tensor: the video tensor with shape (T, C, H, W).
"""
import decord
video_path = ele["video"]
st = time.time()
vr = decord.VideoReader(video_path)
# TODO: support start_pts and end_pts
if 'video_start' in ele or 'video_end' in ele:
raise NotImplementedError("not support start_pts and end_pts in decord for now.")
total_frames, video_fps = len(vr), vr.get_avg_fps()
# logger.info(f"decord: {video_path=}, {total_frames=}, {video_fps=}, time={time.time() - st:.3f}s")
if ele['sample_type'] == 'uniform':
nframes = smart_nframes(ele, total_frames=total_frames, video_fps=video_fps)
# nframes = max(nframes, 8)
# import pdb; pdb.set_trace()
idx = torch.linspace(0, total_frames - 1, nframes).round().long().tolist()
elif ele['sample_type'] == 'multi_pts':
frames_each_pts = 6
num_pts = 4
fps = 8
nframes = int(total_frames * fps // video_fps)
frames_idx = torch.linspace(0, total_frames - 1, nframes).round().long().tolist()
start_pt = int(frames_each_pts // 2)
end_pt = int(nframes - frames_each_pts // 2 - 1)
pts = torch.linspace(start_pt, end_pt, num_pts).round().long().tolist()
idx = []
for pt in pts:
idx.extend(frames_idx[pt - frames_each_pts // 2 : pt + frames_each_pts // 2])
video = vr.get_batch(idx).asnumpy()
video = torch.tensor(video).permute(0, 3, 1, 2) # Convert to TCHW format
return video
VIDEO_READER_BACKENDS = {
"decord": _read_video_decord,
"torchvision": _read_video_torchvision,
}
FORCE_QWENVL_VIDEO_READER = os.getenv("FORCE_QWENVL_VIDEO_READER", None)
@lru_cache(maxsize=1)
def get_video_reader_backend() -> str:
if FORCE_QWENVL_VIDEO_READER is not None:
video_reader_backend = FORCE_QWENVL_VIDEO_READER
elif is_decord_available():
video_reader_backend = "decord"
else:
video_reader_backend = "torchvision"
print(f"qwen-vl-utils using {video_reader_backend} to read video.", file=sys.stderr)
return video_reader_backend
def fetch_video(ele: dict, image_factor: int = IMAGE_FACTOR) -> torch.Tensor | list[Image.Image]:
if isinstance(ele["video"], str):
video_reader_backend = get_video_reader_backend()
video = VIDEO_READER_BACKENDS[video_reader_backend](ele)
# import pdb; pdb.set_trace()
nframes, _, height, width = video.shape
min_pixels = ele.get("min_pixels", VIDEO_MIN_PIXELS)
total_pixels = ele.get("total_pixels", VIDEO_TOTAL_PIXELS)
max_pixels = max(min(VIDEO_MAX_PIXELS, total_pixels / nframes * FRAME_FACTOR), int(min_pixels * 1.05))
max_pixels = ele.get("max_pixels", max_pixels)
if "resized_height" in ele and "resized_width" in ele:
resized_height, resized_width = smart_resize(
ele["resized_height"],
ele["resized_width"],
factor=image_factor,
)
else:
resized_height, resized_width = smart_resize(
height,
width,
factor=image_factor,
min_pixels=min_pixels,
max_pixels=max_pixels,
)
video = transforms.functional.resize(
video,
[resized_height, resized_width],
interpolation=InterpolationMode.BICUBIC,
antialias=True,
).float()
return video
else:
assert isinstance(ele["video"], (list, tuple))
process_info = ele.copy()
process_info.pop("type", None)
process_info.pop("video", None)
images = [
fetch_image({"image": video_element, **process_info}, size_factor=image_factor)
for video_element in ele["video"]
]
nframes = ceil_by_factor(len(images), FRAME_FACTOR)
if len(images) < nframes:
images.extend([images[-1]] * (nframes - len(images)))
return images
def extract_vision_info(conversations: list[dict] | list[list[dict]]) -> list[dict]:
vision_infos = []
if isinstance(conversations[0], dict):
conversations = [conversations]
for conversation in conversations:
for message in conversation:
if isinstance(message["content"], list):
for ele in message["content"]:
if (
"image" in ele
or "image_url" in ele
or "video" in ele
or ele["type"] in ("image", "image_url", "video")
):
vision_infos.append(ele)
return vision_infos
def process_vision_info(
conversations: list[dict] | list[list[dict]],
) -> tuple[list[Image.Image] | None, list[torch.Tensor | list[Image.Image]] | None]:
vision_infos = extract_vision_info(conversations)
## Read images or videos
image_inputs = []
video_inputs = []
for vision_info in vision_infos:
if "image" in vision_info or "image_url" in vision_info:
image_inputs.append(fetch_image(vision_info))
elif "video" in vision_info:
video_inputs.append(fetch_video(vision_info))
else:
raise ValueError("image, image_url or video should in content.")
if len(image_inputs) == 0:
image_inputs = None
if len(video_inputs) == 0:
video_inputs = None
return image_inputs, video_inputs
Number = Union[int, float]
def _round_by_factor(x: Number, factor: int) -> int:
return int(round(x / factor) * factor)
def _ceil_by_factor(x: Number, factor: int) -> int:
return int(math.ceil(x / factor) * factor)
def _floor_by_factor(x: Number, factor: int) -> int:
return int(math.floor(x / factor) * factor)
def smart_nlatents(
ele: Dict,
total_latents: int,
*,
t_factor: int = 1, # 时间对齐因子(如 2/4)
default_ratio: float = 0.25, # 没提供任何策略时,默认取 25%
default_min_latents: int = 4, # 默认最小 latent 数
default_max_latents: int | None = None, # 默认最大 latent 数(None 表示不额外限制)
t_compress: int | None = None, # 仅当用到 'nframes'->'nlatents' 映射时需要
) -> int:
"""
返回用于解码/计算的 latent 步数 n_latents(不依赖 fps)。
允许的配置键(任选其一优先生效):
- 'nlatents' : 直接给 latent 个数
- 'ratio' : 按比例(0~1)取 total_latents * ratio
- 'every'/'stride' : 每隔 k 取一个 → 取 ceil(total_latents / k)
- 'nframes' : 若提供并想从帧域映射,需要传入 t_compress(=每 latent 对应的原始帧数)
另外支持:
- 'min_latents' / 'max_latents':latent 级上下限
- t_factor:对齐因子(结果会对齐到 t_factor 的倍数)
"""
if total_latents < 1:
raise ValueError("total_latents must be >= 1")
# 上下限(latent 级)
min_latents = ele.get("min_latents", default_min_latents)
max_latents = ele.get("max_latents", default_max_latents if default_max_latents is not None else total_latents)
# 规范化与对齐
min_latents = max(1, _ceil_by_factor(min_latents, t_factor))
max_latents = _floor_by_factor(min(max_latents, total_latents), t_factor)
if min_latents > max_latents:
# 当对齐与限制冲突时,退一步:把 min 压到 max
min_latents = max_latents
# 决策优先级:nlatents > ratio > (every/stride) > nframes > 默认
if "nlatents" in ele:
n = ele["nlatents"]
elif "ratio" in ele:
ratio = float(ele["ratio"])
ratio = min(max(ratio, 0.0), 1.0)
n = int(round(total_latents * ratio))
elif ("every" in ele) or ("stride" in ele):
k = int(ele.get("every", ele.get("stride")))
if k <= 0:
raise ValueError("`every/stride` must be a positive integer")
n = int(math.ceil(total_latents / k))
elif "nframes" in ele:
if t_compress is None or t_compress <= 0:
raise ValueError("To use `nframes`, please provide a positive `t_compress`.")
n = int(round(ele["nframes"] / t_compress))
else:
# 默认:按比例取
n = int(round(total_latents * default_ratio))
# 对齐 + 限制 + 边界修正
n = max(min(n, max_latents), min_latents)
n = max(_round_by_factor(max(n, 1), t_factor), t_factor)
n = min(n, total_latents)
if not (t_factor <= n <= total_latents):
raise ValueError(f"n_latents should be in [{t_factor}, {total_latents}], got {n}")
return int(n)
def _aligned_positions(total_latents: int, t_factor: int) -> List[int]:
"""
返回允许的对齐位置集合(升序)。若 t_factor=1,则返回 0..T-1。
若 t_factor>1,则返回 0, t_factor, 2*t_factor, ... <= T-1 的最大倍数。
"""
if t_factor < 1:
raise ValueError("t_factor must be >= 1")
if t_factor == 1:
return list(range(total_latents))
last = (total_latents - 1) // t_factor * t_factor
return list(range(0, last + 1, t_factor))
def sample_latent_indices(
total_latents: int,
n_latents: int,
*,
mode: Mode = "uniform",
t_factor: int = 1,
include_endpoints: bool = True,
seed: Optional[int] = None,
) -> List[int]:
"""
从 [0, total_latents-1] 采样 n_latents 个“时间步索引”,可选对齐到 t_factor。
- mode="uniform": 在“允许位置集合”上等距采样(常用于覆盖全局)。
- mode="random" : 在“允许位置集合”上不放回随机采样(常用于数据增广)。
- mode="window" : 在“允许位置集合”上取长度为 n_latents 的连续窗口(居中或随机)。
- include_endpoints: 等距模式下尽可能包含首尾(在对齐限制内)。
"""
if not (1 <= n_latents <= total_latents):
raise ValueError(f"n_latents must be in [1, {total_latents}], got {n_latents}")
allowed = _aligned_positions(total_latents, t_factor)
if len(allowed) < n_latents:
# 对齐过强,导致可选位置少于需求数量
raise ValueError(
f"Not enough aligned positions: len(allowed)={len(allowed)} < n_latents={n_latents}. "
f"Try reducing t_factor or n_latents."
)
if seed is not None:
random.seed(seed)
if mode == "uniform":
if n_latents == 1:
# 居中取一个(在对齐集合上)
return [allowed[len(allowed) // 2]]
if include_endpoints:
# 在“允许位置集合”的索引空间做 linspace
# i 从 0..(n_latents-1),映射到 [0..len(allowed)-1]
out = []
L = len(allowed)
for i in range(n_latents):
pos = round(i * (L - 1) / (n_latents - 1))
out.append(allowed[pos])
# 去重(极端情况下 rounding 可能重复),若重复则从邻近补齐
out = _dedup_and_fill(out, allowed, prefer_endpoints=True)
return out
else:
# 不强求两端,用中心化等距
out = []
step = (len(allowed)) / n_latents
for i in range(n_latents):
pos = math.floor((i + 0.5) * step)
pos = min(pos, len(allowed) - 1)
out.append(allowed[pos])
out = _dedup_and_fill(out, allowed, prefer_endpoints=False)
return out
elif mode == "random":
if include_endpoints and n_latents >= 2:
first, last = allowed[0], allowed[-1]
interior = allowed[1:-1]
need = n_latents - 2
choice = random.sample(interior, need) if need > 0 else []
out = [first] + sorted(choice) + [last]
return out
else:
return sorted(random.sample(allowed, n_latents))
elif mode == "window":
# 从 allowed 上取连续 n_latents 个
L = len(allowed)
if L == n_latents:
return allowed
# 居中起始(若想随机窗口,把 start 改成 random.randint(0, L-n_latents))
start = (L - n_latents) // 2
return allowed[start : start + n_latents]
else:
raise ValueError(f"Unknown mode: {mode}")
def _dedup_and_fill(chosen: List[int], allowed: List[int], prefer_endpoints: bool) -> List[int]:
"""去重并在 allowed 中补齐缺少的个数,尽量保持有序与均匀。"""
seen = set()
out = []
for x in chosen:
if x not in seen:
out.append(x); seen.add(x)
need = len(chosen) - len(out)
if need <= 0:
return out
# 从 allowed 中补,优先靠近原始列表的空位
# 简单策略:扫描 allowed,按顺序补足未出现的
if prefer_endpoints:
# 优先保留端点,先头尾,再中间
candidates = []
if allowed[0] not in seen:
candidates.append(allowed[0])
if allowed[-1] not in seen:
candidates.append(allowed[-1])
for a in allowed:
if a not in seen and a not in candidates:
candidates.append(a)
else:
candidates = [a for a in allowed if a not in seen]
out_set = set(out)
for a in candidates:
if len(out) >= len(chosen):
break
if a not in out_set:
out.append(a); out_set.add(a)
out.sort()
return out
# -------- 与 torch 张量对接的安全选择函数 --------
def select_latents_by_indices(latents, indices):
"""
给定 latents: [B, C, T, H, W] 与 indices(list/1D tensor, 升序唯一),
返回选取后的子序列: [B, C, T', H, W];该操作对 latents 可反传。
"""
import torch
if not torch.is_tensor(indices):
indices = torch.tensor(indices, dtype=torch.long, device=latents.device)
else:
indices = indices.to(device=latents.device, dtype=torch.long)
return latents.index_select(dim=2, index=indices) |