Open-Sora: Democratizing Efficient Video Production for All
Python
[feat] llava support image and text (#13)
Zheng Zangwei (Alex Zheng)f1ee27ba2f23
diff --git a/configs/opensora-v1-1/train/Vx360p.py b/configs/opensora-v1-1/train/Vx360p.pyindex f896231..edf022b 100644--- a/configs/opensora-v1-1/train/Vx360p.py+++ b/configs/opensora-v1-1/train/Vx360p.py@@ -37,7 +37,7 @@ vae = dict(text_encoder = dict(type="t5",from_pretrained="DeepFloyd/t5-v1_1-xxl",- model_max_length=120,+ model_max_length=300,shardformer=True,)scheduler = dict(diff --git a/tools/aesthetic/inference.py b/tools/aesthetic/inference.pyindex 76aec8a..3d0b73b 100644--- a/tools/aesthetic/inference.py+++ b/tools/aesthetic/inference.py@@ -10,7 +10,7 @@ import torchimport torch.nn as nnimport torch.nn.functional as Ffrom einops import rearrange-from PIL import Image+from torchvision.datasets.folder import pil_loaderfrom tqdm import tqdmIMG_EXTENSIONS = (".jpg", ".jpeg", ".png", ".ppm", ".bmp", ".pgm", ".tif", ".tiff", ".webp")@@ -35,10 +35,6 @@ def extract_frames(video_path, points=(0.1, 0.5, 0.9)):return frames-def get_image(image_path):- return Image.open(image_path).convert("RGB")--class VideoTextDataset(torch.utils.data.Dataset):def __init__(self, csv_path, transform=None, points=(0.1, 0.5, 0.9)):self.csv_path = csv_path@@ -50,7 +46,7 @@ class VideoTextDataset(torch.utils.data.Dataset):sample = self.data.iloc[index]path = sample["path"]if not is_video(path):- images = [get_image(path)]+ images = [pil_loader(path)]else:images = extract_frames(sample["path"], points=self.points)images = [self.transform(img) for img in images]@@ -122,7 +118,7 @@ def main(args):)# compute aesthetic scores- dataset.data["aesthetic"] = np.nan+ dataset.data["aesthetic_score"] = np.nanindex = 0for batch in tqdm(dataloader):images = batch["image"].to(device)@@ -133,7 +129,7 @@ def main(args):scores = rearrange(scores, "(b p) 1 -> b p", b=B)scores = scores.mean(dim=1)scores_np = scores.cpu().numpy()- dataset.data.loc[index : index + len(scores_np) - 1, "aesthetic"] = scores_np+ dataset.data.loc[index : index + len(scores_np) - 1, "aesthetic_score"] = scores_npindex += len(images)dataset.data.to_csv(output_file, index=False)print(f"Saved aesthetic scores to {output_file}.")diff --git a/tools/caption/README.md b/tools/caption/README.mdindex ec35acb..8af5920 100644--- a/tools/caption/README.md+++ b/tools/caption/README.md@@ -4,10 +4,9 @@ Human labeling of videos is expensive and time-consuming. We adopt powerful imag-## LLaVA Captioning-We extract three frames from the video for captioning. With batch inference, we can achieve 10 times speedup, with 2.4 videos/s on 8 GPUs.+We extract three frames from the video for captioning. With batch inference, we can achieve 10 times speedup. With approximatly 720p resolution and 3 frames, the speed is 2~3 videos/s on 8 GPUs. If we resize the smaller side to 336, the speed can be 8 videos/s.### Requirement@@ -33,8 +32,8 @@ pip install -e .# install flash attentionpip install flash-attn --no-build-isolation-# install colossalai-pip install colossalai+# install colossalai and pyav+pip install colossalai pyav```Since only the 34B model's performance is comparable to GPT-4V, we only provide the usage of the 34B model. The 34B model is available [here](https://huggingface.co/liuhaotian/llava-v1.6-vicuna-7b), or run our script and it will be downloaded automatically.@@ -45,9 +44,34 @@ Prepare a csv file for processing. The csv file can be generated by `convert_dat```bash# we run this on 8xH800 GPUs-torchrun --nproc_per_node 8 --standalone -m tools.caption.caption_llava samples output.csv --tp-size 2 --dp-size 4 --bs 16+torchrun --nproc_per_node 8 --standalone -m tools.caption.caption_llava DATA.csv --tp-size 2 --dp-size 4 --bs 16+# at least two 80G GPUs are required+torchrun --nproc_per_node 2 --standalone -m tools.caption.caption_llava DATA.csv --tp-size 2 --dp-size 1 --bs 16+# can also caption images+torchrun --nproc_per_node 2 --standalone -m tools.caption.caption_llava DATA.csv --tp-size 2 --dp-size 1 --bs 16 --prompt image+```++After running the script, with `dp-size=N`, you will get `N` parts of csv files. Run the following command to merge them:++```bash+python -m tools.datasets.csvutil DATA_caption_part0.csv DATA_caption_part1.csv DATA_caption_part2.csv DATA_caption_part3.csv --output DATA_caption.csv```+### Resume++Sometimes the process may be interrupted. We can resume the process by running the following command:++```bash+# merge generated results+# output: DATA_caption_part0+DATA_caption_part1+DATA_caption_part2+DATA_caption_part3.csv+python -m tools.datasets.csvutil DATA_caption_part0.csv DATA_caption_part1.csv DATA_caption_part2.csv DATA_caption_part3.csv+# get the remaining videos+# output: DATA-DATA_caption_part0+DATA_caption_part1+DATA_caption_part2+DATA_caption_part3.csv+python -m tools.datasets.csvutil DATA.csv --difference DATA_caption_part0+DATA_caption_part1+DATA_caption_part2+DATA_caption_part3.csv+```++Then use the output csv file to resume the process.+## GPT-4V CaptioningRun the following command to generate captions for videos with GPT-4V:diff --git a/tools/caption/caption_gpt4.py b/tools/caption/caption_gpt4.pyindex b2c7590..8618651 100644--- a/tools/caption/caption_gpt4.py+++ b/tools/caption/caption_gpt4.py@@ -1,11 +1,19 @@import argparse+import base64import csvimport os+from io import BytesIOimport requestsimport tqdm-from .utils import extract_frames, prompts, read_video_list+from .utils import PROMPTS, VideoTextDataset+++def to_base64(image):+ buffer = BytesIO()+ image.save(buffer, format="JPEG")+ return base64.b64encode(buffer.getvalue()).decode("utf-8")def get_caption(frame, prompt, api_key):@@ -38,31 +46,31 @@ def main(args):# ======================================================# 1. read video list# ======================================================- videos = read_video_list(args.video_folder, args.output_file)- f = open(args.output_file, "a")+ dataset = VideoTextDataset(args.input)+ output_file = os.path.splitext(args.input)[0] + "_caption.csv"+ f = open(output_file, "w")writer = csv.writer(f)+ writer.writerow(["video", "caption"])# ======================================================# 2. generate captions# ======================================================- for video in tqdm.tqdm(videos):- video_path = os.path.join(args.video_folder, video)- frame, length = extract_frames(video_path, base_64=True)- if len(frame) < 3:- continue-- prompt = prompts[args.prompt]- caption = get_caption(frame, prompt, args.key)+ for sample in tqdm.tqdm(dataset):+ prompt = PROMPTS[args.prompt]+ if "text" in args.prompt:+ prompt = prompt.format(sample["text"])+ frames = sample["image"]+ frames = [to_base64(frame) for frame in frames]+ caption = get_caption(frames, prompt, args.key)- writer.writerow((video, caption, length))+ writer.writerow((sample["path"], caption))f.close()if __name__ == "__main__":parser = argparse.ArgumentParser()- parser.add_argument("video_folder", type=str)- parser.add_argument("output_file", type=str)- parser.add_argument("--prompt", type=str, default="three_frames")+ parser.add_argument("input", type=str, help="Path to the input CSV file")+ parser.add_argument("--prompt", type=str, default="video-f3-detail-3ex")parser.add_argument("--key", type=str)args = parser.parse_args()diff --git a/tools/caption/caption_llava.py b/tools/caption/caption_llava.pyindex 58cdd03..3a673aa 100644--- a/tools/caption/caption_llava.py+++ b/tools/caption/caption_llava.py@@ -1,303 +1,26 @@import argparseimport csv-import osimport timeimport warningsfrom datetime import timedelta-import pandas as pdimport torchimport torch.distributed as distfrom colossalai.cluster import DistCoordinator, ProcessGroupMeshfrom colossalai.shardformer import ShardConfig, ShardFormerfrom colossalai.utils import get_current_device, set_seed-from llava.constants import DEFAULT_IMAGE_TOKEN, IGNORE_INDEX, IMAGE_TOKEN_INDEX+from llava.constants import DEFAULT_IMAGE_TOKEN, IMAGE_TOKEN_INDEXfrom llava.conversation import conv_templates-from llava.mm_utils import get_anyres_image_grid_shape, get_model_name_from_path, process_images, tokenizer_image_token+from llava.mm_utils import get_model_name_from_path, process_images, tokenizer_image_tokenfrom llava.model.builder import load_pretrained_model-from llava.model.llava_arch import unpad_imagefrom llava.utils import disable_torch_init-from PIL import Imagefrom tqdm import tqdmfrom .acceleration.llava.policy import LlavaForCausalLMPolicy-from .utils import Timer, extract_frames, prompts+from .utils import PROMPTS, Timer, VideoTextDataset, collate_fndisable_torch_init()-IMG_EXTENSIONS = (".jpg", ".jpeg", ".png", ".ppm", ".bmp", ".pgm", ".tif", ".tiff", ".webp")-VID_EXTENSIONS = (".mp4", ".avi", ".mov", ".mkv")---def is_video(filename):- ext = os.path.splitext(filename)[-1].lower()- return ext in VID_EXTENSIONS---def get_image(image_path):- return Image.open(image_path).convert("RGB")---def prepare_inputs_labels_for_multimodal(- self, input_ids, position_ids, attention_mask, past_key_values, labels, images, image_sizes=None-):- # llava_arch.py- vision_tower = self.get_vision_tower()- if vision_tower is None or images is None or input_ids.shape[1] == 1:- return input_ids, position_ids, attention_mask, past_key_values, None, labels-- if type(images) is list or images.ndim == 5:- if type(images) is list:- images = [x.unsqueeze(0) if x.ndim == 3 else x for x in images]- concat_images = torch.cat([image for image in images], dim=0)- image_features = self.encode_images(concat_images)- split_sizes = [image.shape[0] for image in images]- image_features = torch.split(image_features, split_sizes, dim=0)- mm_patch_merge_type = getattr(self.config, "mm_patch_merge_type", "flat")- image_aspect_ratio = getattr(self.config, "image_aspect_ratio", "square")- if mm_patch_merge_type == "flat":- image_features = [x.flatten(0, 1) for x in image_features]- elif mm_patch_merge_type.startswith("spatial"):- new_image_features = []- for image_idx, image_feature in enumerate(image_features):- if image_feature.shape[0] > 1:- base_image_feature = image_feature[0]- image_feature = image_feature[1:]- height = width = self.get_vision_tower().num_patches_per_side- assert height * width == base_image_feature.shape[0]- if image_aspect_ratio == "anyres":- num_patch_width, num_patch_height = get_anyres_image_grid_shape(- image_sizes[image_idx],- self.config.image_grid_pinpoints,- self.get_vision_tower().config.image_size,- )- image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)- else:- raise NotImplementedError- if "unpad" in mm_patch_merge_type:- image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()- image_feature = image_feature.flatten(1, 2).flatten(2, 3)- image_feature = unpad_image(image_feature, image_sizes[image_idx])- image_feature = torch.cat(- (- image_feature,- self.model.image_newline[:, None, None]- .expand(*image_feature.shape[:-1], 1)- .to(image_feature.device),- ),- dim=-1,- )- image_feature = image_feature.flatten(1, 2).transpose(0, 1)- else:- image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous()- image_feature = image_feature.flatten(0, 3)- image_feature = torch.cat((base_image_feature, image_feature), dim=0)- else:- image_feature = image_feature[0]- if "unpad" in mm_patch_merge_type:- image_feature = torch.cat(- (image_feature, self.model.image_newline[None].to(image_feature.device)), dim=0- )- new_image_features.append(image_feature)- image_features = new_image_features- else:- raise ValueError(f"Unexpected mm_patch_merge_type: {self.config.mm_patch_merge_type}")- else:- image_features = self.encode_images(images)-- # TODO: image start / end is not implemented here to support pretraining.- if getattr(self.config, "tune_mm_mlp_adapter", False) and getattr(self.config, "mm_use_im_start_end", False):- raise NotImplementedError-- # Let's just add dummy tensors if they do not exist,- # it is a headache to deal with None all the time.- # But it is not ideal, and if you have a better idea,- # please open an issue / submit a PR, thanks.- _labels = labels- _position_ids = position_ids- _attention_mask = attention_mask- if attention_mask is None:- attention_mask = torch.ones_like(input_ids, dtype=torch.bool)- else:- attention_mask = attention_mask.bool()- if position_ids is None:- position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)- if labels is None:- labels = torch.full_like(input_ids, IGNORE_INDEX)-- # remove the padding using attention_mask -- FIXME- input_ids = [- cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)- ]- labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]-- new_input_embeds = []- new_labels = []- cur_image_idx = 0- for batch_idx, cur_input_ids in enumerate(input_ids):- num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()- if num_images == 0:- cur_image_features = image_features[cur_image_idx]- cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)- cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)- new_input_embeds.append(cur_input_embeds)- new_labels.append(labels[batch_idx])- cur_image_idx += 1- continue-- image_token_indices = (- [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]- )- cur_input_ids_noim = []- cur_labels = labels[batch_idx]- cur_labels_noim = []- for i in range(len(image_token_indices) - 1):- cur_input_ids_noim.append(cur_input_ids[image_token_indices[i] + 1 : image_token_indices[i + 1]])- cur_labels_noim.append(cur_labels[image_token_indices[i] + 1 : image_token_indices[i + 1]])- split_sizes = [x.shape[0] for x in cur_labels_noim]- cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))- cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)- cur_new_input_embeds = []- cur_new_labels = []-- for i in range(num_images + 1):- cur_new_input_embeds.append(cur_input_embeds_no_im[i])- cur_new_labels.append(cur_labels_noim[i])- if i < num_images:- cur_image_features = image_features[cur_image_idx]- cur_image_idx += 1- cur_new_input_embeds.append(cur_image_features)- cur_new_labels.append(- torch.full(- (cur_image_features.shape[0],),- IGNORE_INDEX,- device=cur_labels.device,- dtype=cur_labels.dtype,- )- )-- cur_new_input_embeds = [x.to(self.device) for x in cur_new_input_embeds]-- cur_new_input_embeds = torch.cat(cur_new_input_embeds)- cur_new_labels = torch.cat(cur_new_labels)-- new_input_embeds.append(cur_new_input_embeds)- new_labels.append(cur_new_labels)-- # Truncate sequences to max length as image embeddings can make the sequence longer- tokenizer_model_max_length = getattr(self.config, "tokenizer_model_max_length", None)- if tokenizer_model_max_length is not None:- new_input_embeds = [x[:tokenizer_model_max_length] for x in new_input_embeds]- new_labels = [x[:tokenizer_model_max_length] for x in new_labels]-- # Combine them- max_len = max(x.shape[0] for x in new_input_embeds)- batch_size = len(new_input_embeds)-- new_input_embeds_padded = []- new_labels_padded = torch.full(- (batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device- )- attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device)- position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)-- for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):- cur_len = cur_new_embed.shape[0]- if getattr(self.config, "tokenizer_padding_side", "right") == "left":- new_input_embeds_padded.append(- torch.cat(- (- torch.zeros(- (max_len - cur_len, cur_new_embed.shape[1]),- dtype=cur_new_embed.dtype,- device=cur_new_embed.device,- ),- cur_new_embed,- ),- dim=0,- )- )- if cur_len > 0:- new_labels_padded[i, -cur_len:] = cur_new_labels- attention_mask[i, -cur_len:] = True- position_ids[i, -cur_len:] = torch.arange(- 0, cur_len, dtype=position_ids.dtype, device=position_ids.device- )- else:- new_input_embeds_padded.append(- torch.cat(- (- cur_new_embed,- torch.zeros(- (max_len - cur_len, cur_new_embed.shape[1]),- dtype=cur_new_embed.dtype,- device=cur_new_embed.device,- ),- ),- dim=0,- )- )- if cur_len > 0:- new_labels_padded[i, :cur_len] = cur_new_labels- attention_mask[i, :cur_len] = True- position_ids[i, :cur_len] = torch.arange(- 0, cur_len, dtype=position_ids.dtype, device=position_ids.device- )-- new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)-- if _labels is None:- new_labels = None- else:- new_labels = new_labels_padded-- if _attention_mask is None:- attention_mask = None- else:- attention_mask = attention_mask.to(dtype=_attention_mask.dtype)-- if _position_ids is None:- position_ids = None-- return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels---class VideoTextDataset(torch.utils.data.Dataset):- def __init__(self, csv_path, transform=None, points=(0.1, 0.5, 0.9)):- self.csv_path = csv_path- self.transform = transform- self.data = pd.read_csv(csv_path)- self.points = points-- def getitem(self, index):- sample = self.data.iloc[index]- path = sample["path"]- if not is_video(path):- images = [get_image(path)]- length = 1- else:- images, length = extract_frames(sample["path"], points=self.points)- imgs_size = [img.size for img in images]- images = self.transform(images)-- # we put images into a list as pytorch dataloader does not accept Pill- out = dict(path=path, image=images, length=length, img_size=imgs_size)- return out-- def __len__(self):- return len(self.data)-- def __getitem__(self, index):- return self.getitem(index)---def collate_fn(batch):- paths = [item["path"] for item in batch]- images = [item["image"] for item in batch]- lengths = [item["length"] for item in batch]- img_sizes = [item["img_size"] for item in batch]- return paths, images, lengths, img_sizes-@torch.inference_mode()def main(args):@@ -319,15 +42,9 @@ def main(args):tp_group = mesh.get_group_along_axis(1)# ======================================================- # 3. load model and prepare prompts+ # 2. load model# ======================================================model_path = "liuhaotian/llava-v1.6-34b"- query = prompts[args.prompt]- print(f"Prompt: {query}")- conv = conv_templates["chatml_direct"].copy()- conv.append_message(conv.roles[0], DEFAULT_IMAGE_TOKEN + "\n" + query)- prompt = conv.get_prompt()-with warnings.catch_warnings():warnings.simplefilter("ignore") # Pytorch non-meta copying warning fills out the consoletokenizer, model, image_processor, context_len = load_pretrained_model(@@ -339,11 +56,9 @@ def main(args):attn_implementation="flash_attention_2",)dist.barrier()- input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt")- input_ids = input_ids.unsqueeze(0).cuda()# ======================================================- # 4. Apply system optimization+ # 3. Apply system optimization# ======================================================# create huggingface model as normaltp_size = dist.get_world_size(tp_group)@@ -356,15 +71,47 @@ def main(args):torch.cuda.empty_cache()# ======================================================- # 5. Prepare dataloader+ # 4. Prepare dataloader# ======================================================+ # prepare prompt+ query = PROMPTS[args.prompt]+ if dist.get_rank() == 0:+ print(f"Prompt: {query}")++ if "text" in args.prompt:++ def get_text_input_ids(text):+ conv = conv_templates["chatml_direct"].copy()+ query_text = query.format(text)+ conv.append_message(conv.roles[0], DEFAULT_IMAGE_TOKEN + "\n" + query_text)+ prompt = conv.get_prompt()+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt")+ input_ids = input_ids.unsqueeze(0)+ return input_ids++ else:+ conv = conv_templates["chatml_direct"].copy()+ conv.append_message(conv.roles[0], DEFAULT_IMAGE_TOKEN + "\n" + query)+ prompt = conv.get_prompt()+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt")+ input_ids = input_ids.unsqueeze(0)++ def get_text_input_ids(*args):+ return input_ids+# build datasetdef transform(imgs):imgs = process_images(imgs, image_processor, model.config)imgs = imgs.to(dtype=torch.float16)return imgs- dataset = VideoTextDataset(args.input, points=(0.2, 0.5, 0.8), transform=transform)+ dataset = VideoTextDataset(+ args.input,+ transform=transform,+ num_frames=args.num_frames,+ get_text_input_ids=get_text_input_ids,+ resize=args.resize,+ )total_num_videos = len(dataset)# build sampler@@ -375,7 +122,6 @@ def main(args):)# build dataloader-dataloader = torch.utils.data.DataLoader(dataset,batch_size=args.bs,@@ -391,27 +137,19 @@ def main(args):output_file = args.input.replace(".csv", "_caption.csv")# create csv writer- has_main_writer = dist.get_rank() == 0has_dp_writter = dist.get_rank(tp_group) == 0- if has_main_writer:- # we keep track of the processed videos in main file- # so we use append mode- main_file = open(output_file, "a")- main_writer = csv.writer(main_file)-if has_dp_writter:# the dp writer takes care of the files processed on the current dp rank# so we use write mode- output_file_split = f"{output_file}.part{dp_rank}"+ output_file_split = output_file.replace(".csv", f"_part{dp_rank}.csv")dp_file = open(output_file_split, "w")dp_writer = csv.writer(dp_file)+ dp_writer.writerow(["path", "caption", "num_frames"])# ======================================================# 5. generate captions# ======================================================- args.bs-if dist.get_rank(tp_group) == 0:pbar = tqdm(dataloader, position=dp_rank, desc=f"Data Parallel Rank {dist.get_rank(dp_group)}")else:@@ -423,21 +161,22 @@ def main(args):generate_time = []total_time = []- for batch in pbar:+ for i, batch in enumerate(pbar):# measure timeif args.profile:torch.cuda.synchronize()start_time = time.time()- video_files, frames, video_lengths, img_size_list = batch+ video_files, frames, video_lengths, img_size_list, texts = batch# encode the batch of inputswith Timer() as encode_timer:samples = []- for imgs, imgs_size in zip(frames, img_size_list):+ for imgs, imgs_size, input_ids in zip(frames, img_size_list, texts):imgs = imgs.cuda()- _, _, _, _, inputs_embeds, _ = prepare_inputs_labels_for_multimodal(- model, input_ids, None, None, None, None, images=imgs, image_sizes=imgs_size+ input_ids = input_ids.cuda()+ _, _, _, _, inputs_embeds, _ = model.prepare_inputs_labels_for_multimodal(+ input_ids, None, None, None, None, images=imgs, image_sizes=imgs_size)samples.append(inputs_embeds)@@ -467,9 +206,8 @@ def main(args):output_ids = super(type(model), model).generate(inputs_embeds=inputs_embeds,attention_mask=attention_mask,- do_sample=args.tp_size == 1, # sampling is not deterministic and may cause TP to hang- temperature=0.2,- max_new_tokens=512,+ do_sample=False, # sampling is not deterministic and may cause TP to hang+ max_new_tokens=args.max_tokens,use_cache=True,)outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)@@ -509,17 +247,6 @@ def main(args):dp_file.close()dist.barrier()- # merge files- if has_main_writer:- for i in range(dp_size):- output_file_split = f"{output_file}.part{i}"- with open(output_file_split, "r") as f:- reader = csv.reader(f)- for row in reader:- main_writer.writerow(row)- os.remove(output_file_split)- main_file.close()-# terminate distributed envdist.destroy_process_group()@@ -527,14 +254,19 @@ def main(args):if __name__ == "__main__":parser = argparse.ArgumentParser()parser.add_argument("input", type=str, help="Path to the input CSV file")-- parser.add_argument("--bs", type=int, default=32)- parser.add_argument("--prompt", type=str, default="three_frames")- parser.add_argument("--tp-size", type=int, default=1)- parser.add_argument("--dp-size", type=int, default=1)+ parser.add_argument("--prompt", type=str, default="video-f3-detail-3ex")+ parser.add_argument("--resize", type=int, default=336)+ parser.add_argument("--num-frames", type=int, default=3)+ parser.add_argument("--max-tokens", type=int, default=300)+ # speed related+ parser.add_argument("--bs", type=int, default=16)+ parser.add_argument("--tp-size", type=int, default=2)+ parser.add_argument("--dp-size", type=int, default=4)parser.add_argument("--num-workers", type=int, default=8)+ parser.add_argument("--prefetch-factor", type=int, default=8, help="Prefetch factor")+ # debug relatedparser.add_argument("--profile", action="store_true")parser.add_argument("--profile-warmup", type=int, default=1)- parser.add_argument("--prefetch-factor", type=int, default=8, help="Prefetch factor")+args = parser.parse_args()main(args)diff --git a/tools/caption/utils.py b/tools/caption/utils.pyindex fb6085e..44226d5 100644--- a/tools/caption/utils.py+++ b/tools/caption/utils.py@@ -1,71 +1,108 @@-import base64-import csvimport osimport time-import cv2-from PIL import Image--prompts = {- "naive": "Describe the video",- "three_frames": "A video is given by providing three frames in chronological order. Describe this video and its style to generate a description. Pay attention to all objects in the video. Do not describe each frame individually. Do not reply with words like 'first frame'. The description should be useful for AI to re-generate the video. The description should be less than six sentences. Here are some examples of good descriptions: 1. A stylish woman walks down a Tokyo street filled with warm glowing neon and animated city signage. She wears a black leather jacket, a long red dress, and black boots, and carries a black purse. She wears sunglasses and red lipstick. She walks confidently and casually. The street is damp and reflective, creating a mirror effect of the colorful lights. Many pedestrians walk about. 2. Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field. 3. Drone view of waves crashing against the rugged cliffs along Big Sur's garay point beach. The crashing blue waters create white-tipped waves, while the golden light of the setting sun illuminates the rocky shore. A small island with a lighthouse sits in the distance, and green shrubbery covers the cliff's edge. The steep drop from the road down to the beach is a dramatic feat, with the cliff’s edges jutting out over the sea. This is a view that captures the raw beauty of the coast and the rugged landscape of the Pacific Coast Highway.",+import av+import pandas as pd+import torch+import torchvision.transforms as transforms+from torchvision.datasets.folder import pil_loader++PROMPTS = {+ "image": "Describe this image and its style in a very detailed manner. Pay attention to all objects in the image. The description should be useful for AI to re-generate the image. The description should be no more than six sentences.",+ "image-text": "Describe this image and its style in a very detailed manner. Pay attention to all objects in the image. The description should be useful for AI to re-generate the image. The description should be no more than six sentences. Some information about the image is '{}'.",+ "video": "Describe this video and its style in a very detailed manner. Pay attention to all objects in the video. The description should be useful for AI to re-generate the video. The description should be no more than six sentences.",+ "video-f1-detail-3ex": "A video is given by providing the middle frame. Describe this video and its style to generate a description. Pay attention to all objects in the video. The description should be useful for AI to re-generate the video. The description should be no more than six sentences. Here are some examples of good descriptions: 1. A stylish woman walks down a Tokyo street filled with warm glowing neon and animated city signage. She wears a black leather jacket, a long red dress, and black boots, and carries a black purse. She wears sunglasses and red lipstick. She walks confidently and casually. The street is damp and reflective, creating a mirror effect of the colorful lights. Many pedestrians walk about. 2. Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field. 3. Drone view of waves crashing against the rugged cliffs along Big Sur's garay point beach. The crashing blue waters create white-tipped waves, while the golden light of the setting sun illuminates the rocky shore. A small island with a lighthouse sits in the distance, and green shrubbery covers the cliff's edge. The steep drop from the road down to the beach is a dramatic feat, with the cliff’s edges jutting out over the sea. This is a view that captures the raw beauty of the coast and the rugged landscape of the Pacific Coast Highway.",+ "video-f3-detail-3ex": "A video is given by providing three frames in chronological order. Describe this video and its style to generate a description. Pay attention to all objects in the video. Do not describe each frame individually. Do not reply with words like 'first frame'. The description should be useful for AI to re-generate the video. The description should be no more than six sentences. Here are some examples of good descriptions: 1. A stylish woman walks down a Tokyo street filled with warm glowing neon and animated city signage. She wears a black leather jacket, a long red dress, and black boots, and carries a black purse. She wears sunglasses and red lipstick. She walks confidently and casually. The street is damp and reflective, creating a mirror effect of the colorful lights. Many pedestrians walk about. 2. Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field. 3. Drone view of waves crashing against the rugged cliffs along Big Sur's garay point beach. The crashing blue waters create white-tipped waves, while the golden light of the setting sun illuminates the rocky shore. A small island with a lighthouse sits in the distance, and green shrubbery covers the cliff's edge. The steep drop from the road down to the beach is a dramatic feat, with the cliff’s edges jutting out over the sea. This is a view that captures the raw beauty of the coast and the rugged landscape of the Pacific Coast Highway.",+ "video-f3-detail-2ex-text": "A video is given by providing three frames in chronological order. Some information about the image is '{}'. Describe this video and its style to generate a description. Pay attention to all objects in the video. Do not describe each frame individually. Do not reply with words like 'first frame'. The description should be useful for AI to re-generate the video. The description should be no more than six sentences. Here are some examples of good descriptions: 1. A stylish woman walks down a Tokyo street filled with warm glowing neon and animated city signage. She wears a black leather jacket, a long red dress, and black boots, and carries a black purse. She wears sunglasses and red lipstick. She walks confidently and casually. The street is damp and reflective, creating a mirror effect of the colorful lights. Many pedestrians walk about. 2. Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field.",}--def get_filelist(file_path):- Filelist = []- VID_EXTENSIONS = ("mp4", "avi", "mov", "mkv")- for home, dirs, files in os.walk(file_path):- for filename in files:- ext = filename.split(".")[-1]- if ext in VID_EXTENSIONS:- Filelist.append(os.path.join(home, filename))- return Filelist---def get_video_length(cap):- return int(cap.get(cv2.CAP_PROP_FRAME_COUNT))+IMG_EXTENSIONS = (".jpg", ".jpeg", ".png", ".ppm", ".bmp", ".pgm", ".tif", ".tiff", ".webp")+VID_EXTENSIONS = (".mp4", ".avi", ".mov", ".mkv")+NUM_FRAMES_POINTS = {+ 1: (0.5,),+ 2: (0.25, 0.75),+ 3: (0.1, 0.5, 0.9),+}-def encode_image(image_path):- with open(image_path, "rb") as image_file:- return base64.b64encode(image_file.read()).decode("utf-8")+def is_video(filename):+ ext = os.path.splitext(filename)[-1].lower()+ return ext in VID_EXTENSIONS-def extract_frames(video_path, points=(0.2, 0.5, 0.8), base_64=False):- cap = cv2.VideoCapture(video_path)- length = get_video_length(cap)- points = [int(length * point) for point in points]+def extract_frames(video_path, points=(0.1, 0.5, 0.9)):+ container = av.open(video_path)+ total_frames = container.streams.video[0].framesframes = []- if length < 3:- return frames, lengthfor point in points:- cap.set(cv2.CAP_PROP_POS_FRAMES, point)- ret, frame = cap.read()- if not base_64:- frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)- frame = Image.fromarray(frame)- else:- _, buffer = cv2.imencode(".jpg", frame)- frame = base64.b64encode(buffer).decode("utf-8")+ target_frame = total_frames * point+ target_timestamp = int((target_frame * av.time_base) / container.streams.video[0].average_rate)+ container.seek(target_timestamp)+ frame = next(container.decode(video=0)).to_image()frames.append(frame)- return frames, length---def read_video_list(video_folder, output_file):- processed_videos = []- if os.path.exists(output_file):- with open(output_file, "r") as f:- reader = csv.reader(f)- samples = list(reader)- processed_videos = [sample[0] for sample in samples]-- # read video list- videos = get_filelist(video_folder)- print(f"Dataset contains {len(videos)} videos.")- videos = [video for video in videos if video not in processed_videos]- print(f"Processing {len(videos)} new videos.")- return videos+ return frames, total_frames+++class VideoTextDataset(torch.utils.data.Dataset):+ def __init__(self, csv_path, transform=None, num_frames=3, get_text_input_ids=None, resize=None):+ self.csv_path = csv_path+ self.transform = transform+ self.data = pd.read_csv(csv_path)+ self.points = NUM_FRAMES_POINTS[num_frames]+ self.get_text_input_ids = get_text_input_ids+ self.use_text = False+ self.resize_size = resize+ self.resize = transforms.Resize(resize, transforms.InterpolationMode.BICUBIC) if resize is not None else None+ if "text" in self.data.columns:+ self.use_text = True++ def getitem(self, index):+ sample = self.data.iloc[index]+ path = sample["path"]+ if not is_video(path):+ images = [pil_loader(path)]+ length = 1+ else:+ images, length = extract_frames(sample["path"], points=self.points)+ if self.resize_size is not None:+ images_r = []+ for img in images:+ if img.size[0] > self.resize_size or img.size[1] > self.resize_size:+ img = self.resize(img)+ images_r.append(img)+ images = images_r+ imgs_size = [img.size for img in images]+ if self.transform is not None:+ images = self.transform(images)++ # we put images into a list as pytorch dataloader does not accept Pill+ out = dict(path=path, image=images, length=length, img_size=imgs_size)+ if self.get_text_input_ids is not None:+ if self.use_text:+ out["text"] = self.get_text_input_ids(sample["text"])+ else:+ out["text"] = self.get_text_input_ids()+ else:+ if self.use_text:+ out["text"] = sample["text"]+ else:+ out["text"] = ""+ return out++ def __len__(self):+ return len(self.data)++ def __getitem__(self, index):+ return self.getitem(index)+++def collate_fn(batch):+ paths = [item["path"] for item in batch]+ images = [item["image"] for item in batch]+ lengths = [item["length"] for item in batch]+ img_sizes = [item["img_size"] for item in batch]+ texts = [item["text"] for item in batch]+ return paths, images, lengths, img_sizes, textsclass Timer:diff --git a/tools/datasets/README.md b/tools/datasets/README.mdindex 3ec7a81..e0fc1dc 100644--- a/tools/datasets/README.md+++ b/tools/datasets/README.md@@ -7,7 +7,7 @@ After preparing the raw dataset according to the [instructions](/docs/datasets.mAll dataset should be provided in a CSV file, which is used both for training and data preprocessing.. The CSV file should only contain the following columns (can be optional).```csv-path, text, num_frames, fps, width, height, aspect_ratio, aesthetic_score, clip_score+path, text, num_frames, fps, width, height, aspect_ratio, aesthetic_score, clip_score, .../absolute/path/to/image1.jpg, caption1, num_of_frames/absolute/path/to/video2.mp4, caption2, num_of_frames```diff --git a/tools/datasets/csvutil.py b/tools/datasets/csvutil.pyindex 110be8c..d83892e 100644--- a/tools/datasets/csvutil.py+++ b/tools/datasets/csvutil.py@@ -57,6 +57,15 @@ LLAVA_PREFIX = ["The video features","The video is ","In the video,",+ "The image shows",+ "The image captures",+ "The image features",+ "The image depicts",+ "The image presents",+ "The image features",+ "The image is ",+ "The image portrays",+ "In the image,",]@@ -96,6 +105,7 @@ def parse_args():parser.add_argument("--shard", type=int, default=None)parser.add_argument("--sort-descending", type=str, default=None)parser.add_argument("--sort-ascending", type=str, default=None)+ parser.add_argument("--difference", type=str, default=None)# path processingparser.add_argument("--abspath", type=str, default=None)@@ -182,6 +192,14 @@ def main(args):data = pd.concat(data, ignore_index=True, sort=False)print(f"Total number of samples: {len(data)}.")+ # make difference+ if args.difference is not None:+ data_diff = pd.read_csv(args.difference)+ print(f"Difference csv contains {len(data_diff)} samples.")+ data = data[~data["path"].isin(data_diff["path"])]+ input_name += f"-{os.path.basename(args.difference).split('.')[0]}"+ print(f"Filtered number of samples: {len(data)}.")+# get output pathoutput_path = get_output_path(args, input_name)