| 1 |
# Copyright 2025 The HuggingFace Inc. team. All rights reserved. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
import json |
| 16 |
import os |
| 17 |
import pathlib |
| 18 |
import queue |
| 19 |
import time |
| 20 |
from concurrent.futures import ThreadPoolExecutor |
| 21 |
|
| 22 |
import av |
| 23 |
import fire |
| 24 |
import numpy as np |
| 25 |
import torch |
| 26 |
from huggingface_hub import snapshot_download |
| 27 |
from tqdm import tqdm |
| 28 |
from transformers import LlavaNextVideoForConditionalGeneration, LlavaNextVideoProcessor |
| 29 |
|
| 30 |
from accelerate import PartialState |
| 31 |
|
| 32 |
|
| 33 |
START_TIME = time.strftime("%Y%m%d_%H%M%S") |
| 34 |
DTYPE_MAP = {"fp32": torch.float32, "fp16": torch.float16, "bf16": torch.bfloat16} |
| 35 |
|
| 36 |
|
| 37 |
""" |
| 38 |
Example: |
| 39 |
|
| 40 |
accelerate launch llava_next_video.py |
| 41 |
""" |
| 42 |
|
| 43 |
|
| 44 |
def save_results(output_queue: queue.Queue, output_dir: pathlib.Path): |
| 45 |
count = 0 |
| 46 |
while True: |
| 47 |
try: |
| 48 |
item = output_queue.get(timeout=5) |
| 49 |
if item is None: |
| 50 |
break |
| 51 |
prompt, video, generated_text = item |
| 52 |
example_file = f"example_{count}" |
| 53 |
temp_dir = os.path.join(output_dir, example_file) |
| 54 |
|
| 55 |
metadata = {"prompt": prompt, "video": video, "generated_text": generated_text} |
| 56 |
with open(temp_dir, "w") as f: |
| 57 |
json.dump(metadata, f, indent=4) |
| 58 |
count += 1 |
| 59 |
|
| 60 |
except queue.Empty: |
| 61 |
continue |
| 62 |
|
| 63 |
|
| 64 |
def get_batches(processed_videos, batch_size): |
| 65 |
num_batches = (len(processed_videos) + batch_size - 1) // batch_size |
| 66 |
batches = [] |
| 67 |
|
| 68 |
for i in range(num_batches): |
| 69 |
start_index = i * batch_size |
| 70 |
end_index = min((i + 1) * batch_size, len(processed_videos)) |
| 71 |
batch = processed_videos[start_index:end_index] |
| 72 |
batches.append(batch) |
| 73 |
|
| 74 |
return batches |
| 75 |
|
| 76 |
|
| 77 |
def read_video_pyav(container, indices): |
| 78 |
""" |
| 79 |
Decode the video with PyAV decoder. |
| 80 |
Args: |
| 81 |
container (`av.container.input.InputContainer`): PyAV container. |
| 82 |
indices (`List[int]`): List of frame indices to decode. |
| 83 |
Returns: |
| 84 |
result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3). |
| 85 |
""" |
| 86 |
frames = [] |
| 87 |
container.seek(0) |
| 88 |
start_index = indices[0] |
| 89 |
end_index = indices[-1] |
| 90 |
for i, frame in enumerate(container.decode(video=0)): |
| 91 |
if i > end_index: |
| 92 |
break |
| 93 |
if i >= start_index and i in indices: |
| 94 |
frames.append(frame) |
| 95 |
return np.stack([x.to_ndarray(format="rgb24") for x in frames]) |
| 96 |
|
| 97 |
|
| 98 |
def get_video_paths(video_dir): |
| 99 |
"""Get paths to all video files in the directory and its subdirectories.""" |
| 100 |
video_extensions = (".mp4", ".avi", ".mov", ".mkv") # Add more extensions if needed |
| 101 |
video_paths = [] |
| 102 |
|
| 103 |
for root, _, files in os.walk(video_dir): |
| 104 |
for file in files: |
| 105 |
if file.lower().endswith(video_extensions): |
| 106 |
video_paths.append(os.path.join(root, file)) |
| 107 |
|
| 108 |
return video_paths |
| 109 |
|
| 110 |
|
| 111 |
def process_videos(video_paths, processor, prompt, frames_per_video): |
| 112 |
"""Process a batch of videos and prepare them for the model.""" |
| 113 |
batch_inputs = [] |
| 114 |
|
| 115 |
for video_path in video_paths: |
| 116 |
try: |
| 117 |
with av.open(video_path) as container: |
| 118 |
total_frames = container.streams.video[0].frames |
| 119 |
indices = np.arange(0, total_frames, total_frames / frames_per_video).astype(int) |
| 120 |
clip = read_video_pyav(container, indices) |
| 121 |
|
| 122 |
processed = processor(text=prompt, videos=clip, return_tensors="pt") |
| 123 |
batch_inputs.append( |
| 124 |
{ |
| 125 |
"input_ids": processed["input_ids"], |
| 126 |
"pixel_values_videos": processed["pixel_values_videos"], |
| 127 |
"video": video_path, |
| 128 |
} |
| 129 |
) |
| 130 |
|
| 131 |
except Exception as e: |
| 132 |
print(f"Error processing video {video_path}: {str(e)}") |
| 133 |
continue |
| 134 |
|
| 135 |
return batch_inputs |
| 136 |
|
| 137 |
|
| 138 |
def main( |
| 139 |
model_name: str = "llava-hf/LLaVA-NeXT-Video-7B-hf", |
| 140 |
save_dir: str = "./evaluation/examples", |
| 141 |
prompt: str = "USER: <video>\nGenerate caption ASSISTANT:", |
| 142 |
frames_per_video: int = 8, |
| 143 |
max_new_tokens: int = 100, |
| 144 |
batch_size: int = 4, |
| 145 |
dtype: str = "fp16", |
| 146 |
num_workers: int = 1, |
| 147 |
low_mem: bool = True, |
| 148 |
): |
| 149 |
# Start up the distributed environment without needing the Accelerator. |
| 150 |
distributed_state = PartialState() |
| 151 |
|
| 152 |
processor = LlavaNextVideoProcessor.from_pretrained(model_name) |
| 153 |
model = LlavaNextVideoForConditionalGeneration.from_pretrained( |
| 154 |
model_name, torch_dtype=DTYPE_MAP[dtype], low_cpu_mem_usage=low_mem, device_map=distributed_state.device |
| 155 |
) |
| 156 |
|
| 157 |
if distributed_state.is_main_process: |
| 158 |
if not os.path.exists(save_dir): |
| 159 |
os.makedirs(save_dir) |
| 160 |
print(f"Directory '{save_dir}' created successfully.") |
| 161 |
else: |
| 162 |
print(f"Directory '{save_dir}' already exists.") |
| 163 |
|
| 164 |
videos_dir = snapshot_download(repo_id="malterei/LLaVA-Video-small-swift", repo_type="dataset") |
| 165 |
video_paths = get_video_paths(videos_dir) |
| 166 |
processed_videos = process_videos(video_paths, processor, prompt, frames_per_video) |
| 167 |
batches = get_batches(processed_videos, batch_size) |
| 168 |
|
| 169 |
output_queue = queue.Queue() |
| 170 |
save_thread = ThreadPoolExecutor(max_workers=num_workers) |
| 171 |
save_future = save_thread.submit(save_results, output_queue, save_dir) |
| 172 |
for _, batch_raw in tqdm(enumerate(batches), total=len(batches)): |
| 173 |
try: |
| 174 |
with distributed_state.split_between_processes(batch_raw) as batched_inputs: |
| 175 |
for batch in batched_inputs: |
| 176 |
output = model.generate( |
| 177 |
input_ids=batch["input_ids"].to(distributed_state.device), |
| 178 |
pixel_values_videos=batch["pixel_values_videos"].to(distributed_state.device, model.dtype), |
| 179 |
max_new_tokens=max_new_tokens, |
| 180 |
) |
| 181 |
generated_text = processor.batch_decode(output, skip_special_tokens=True) |
| 182 |
output_queue.put((prompt, batch["video"], generated_text)) |
| 183 |
finally: |
| 184 |
output_queue.put(None) |
| 185 |
save_thread.shutdown(wait=True) |
| 186 |
|
| 187 |
save_future.result() |
| 188 |
distributed_state.destroy_process_group() |
| 189 |
|
| 190 |
|
| 191 |
if __name__ == "__main__": |
| 192 |
fire.Fire(main) |