diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/AIP_dataset.py b/dataset_code/sft_sftnews/offload/dataset_tool/AIP_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..d272aaacfa2504db1a2c78e327760d55b393c593 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/dataset_tool/AIP_dataset.py @@ -0,0 +1,309 @@ +import torch +from torch.utils.data.dataset import Dataset +from torchvision.transforms.functional import to_tensor +from nebudata import refds +from .parquet_dataset.utils import hdfs_utils +from .parquet_dataset.parquet_utils import get_random_for_rank_and_worker, get_portion_for_rank_and_worker, get_worker_id, get_worker_count +from .parquet_dataset.utils.distributed_utils import get_data_parallel_rank, get_data_parallel_world_size +import random +from PIL import Image +import copy +import numpy as np +import json +from multiprocessing import Pool +import traceback + + +try: + import av + import io + pyav_enabled = True +except: + pyav_enabled = False + +try: + import imageio.v3 as iio + imageio_enabled = True +except: + imageio_enabled = False + + +def get_length(path, ignore_prefixes): + dataset = refds.RefDataset( + path, ignore_prefixes=ignore_prefixes) + return dataset.rank_total + + +def get_length_subprocess(path, ignore_prefixes): + with Pool(1) as pool: + counts = pool.apply( + get_length, args=(path, ignore_prefixes, )) + return counts + + +def sampling(video_length, sample_n_frames, sample_stride, skip_start_end=10): + # Jacob Sep 17th: If sample frames > video frames, we drop this video + if (sample_n_frames - 1) * sample_stride + 1 > (video_length - skip_start_end * 2): + return None + clip_length = min( + video_length, (sample_n_frames - 1) * sample_stride + 1) + start_idx = random.randint( + skip_start_end, video_length - clip_length - skip_start_end) + batch_index = np.linspace( + start_idx, start_idx + clip_length - 1, sample_n_frames, dtype=int) + return batch_index + + +class AIPVideoDataset(Dataset): + def __init__(self, + path, + sample_size=256, + sample_stride=4, + sample_n_frames=16, + caption_key='caption', + caption_path="", + fps=24, + shuffle=True, + infinite=True, + parquet_batch=128, + video_toskey='clip_toskey', + bytes_key='bytes', + ignore_prefixes=None, + decode_backend='pyav', + force_partition=False, + data_world_size=10000, # TODO: can be dynamic + local_cache_prefix='', + ): + self.sample_size = sample_size + assert self.sample_size == -1, \ + "only support original size, consider using sample_size==-1 for bucketing" + self.sample_stride = sample_stride + self.sample_n_frames = sample_n_frames + self.shuffle = shuffle + self.infinite = infinite # this doesn't work, the dataset is always infinite + self.fps = fps + self.force_partition = force_partition + self.data_world_size = data_world_size + self.state_dict = {'data_world_size': self.data_world_size, 'seen_times': [0 for _ in range(self.data_world_size)]} + self.remaining_ranks = [] + self.local_cache_prefix = local_cache_prefix + + self.path = path + self.parquet_batch = parquet_batch + self.video_toskey = video_toskey + self.caption_key = caption_key # the key used to store caption + self.bytes_key = bytes_key # the key used to store real bytes + self.ignore_prefixes = ignore_prefixes + self.decode_backend = decode_backend + + self.total_length = None + # read caption json file from caption_path seperately, for Seed V2 dataset + self.caption_data = None + if caption_path != "": + # with open(caption_path, 'r') as f: + if caption_path.startswith("hdfs"): + caption_path = hdfs_utils.download(caption_path, './') + with open(caption_path, 'r') as f: + caption_data = json.load(f) + caption_data = json.loads(hdfs_utils.read(caption_path)) + self.total_length = len(caption_data) + self.caption_data = {item['uttid']: item[self.caption_key] + for item in caption_data} + + if self.decode_backend == 'imageio': + assert imageio_enabled, 'failed to install imageio' + elif self.decode_backend == 'pyav': + assert pyav_enabled, 'failed to install pyav' + + def __iter__(self): + rank = get_data_parallel_rank() + world_size = get_data_parallel_world_size() + worker_id = get_worker_id() + worker_count = get_worker_count() + overall_workers = world_size * worker_count + + self.local_cache_path = f'{self.local_cache_prefix}_{rank}_{worker_id}.txt' + refs = [(self.video_toskey, self.bytes_key) + ] if self.video_toskey != '' else [] + + worker_ranks = get_portion_for_rank_and_worker(self.remaining_ranks, allow_empty=True) + + while True: + if self.shuffle: + get_random_for_rank_and_worker(None).shuffle(worker_ranks) + + for rank in worker_ranks: + with open(self.local_cache_path, 'a') as f: + f.write(f'{rank}\n') + filereader = refds.RefDataset(self.path, ignore_prefixes=self.ignore_prefixes, world_size=self.data_world_size, rank=rank) + for batch in filereader.iter_batches(batch_size=self.parquet_batch, refs=refs): + actual_size = len(batch[self.bytes_key]) + columns = [col for col in batch.column_names] + for i in range(actual_size): + params_dict = {col: batch[col] + [i].as_py() for col in columns} + if self.caption_data is not None: + # if we have caption_data, use it to replace caption + uttid = params_dict['uttid'] + if uttid not in self.caption_data: + continue + params_dict[self.caption_key] = self.caption_data[uttid] + frames, metadata = self._data_process(params_dict) + if frames is None: + continue + yield self._pack_frames(frames, metadata) + + overall_ranks = [] + while len(overall_ranks) < overall_workers: + overall_ranks += list(range(self.data_world_size)) + worker_ranks = get_portion_for_rank_and_worker(overall_ranks, force=True) + + def _pack_frames(self, frames, metadata): + tensor_frames = [] + for frame in frames: + frame = to_tensor(frame) + tensor_frames.append(frame) + tensor_frames = torch.stack(tensor_frames) + # make value from -1.0 to 1.0 + pixel_values = tensor_frames * 2.0 - 1.0 + item = dict( + mp4=pixel_values, + txt=metadata[self.caption_key], + num_frames=self.sample_n_frames, + fps=metadata.get('fps', self.fps), + ) + return item + + def _data_process(self, params): + tosbytes = params[self.bytes_key] + del params[self.bytes_key] # remove the bytes key + metadata = copy.deepcopy(params) + try: + frames = self._bytes_to_PILs(tosbytes) + except: + print("data error: ", metadata) + traceback.print_exc() + return None, None + if frames is None: + return None, None + return frames, metadata + + def _bytes_to_PILs(self, video_bytes): + if self.decode_backend == 'imageio': + raw_frames = iio.imread( + video_bytes, index=None, format_hint=".mp4") + video_length = raw_frames.shape[0] + video_idxs = sampling( + video_length, self.sample_n_frames, self.sample_stride) + if video_idxs is None: + return None + frames = [] + for i in video_idxs: + frames.append(Image.fromarray(raw_frames[i], 'RGB')) + + elif self.decode_backend[:4] == 'pyav': + file_io = io.BytesIO(video_bytes) + container = av.open(file_io) + stream = container.streams.video[0] + video_length = container.streams.video[0].frames + video_idxs = sampling( + video_length, self.sample_n_frames, self.sample_stride) + if video_idxs is None: + return None + frames_sorted = [] + key_frame_idxs = [] + + # Get keyframe without decoding + stream.codec_context.skip_frame = "NONKEY" + for packet in container.demux(stream): + if packet.is_keyframe: + frame_idx = int( + packet.pts * stream.time_base * stream.average_rate + 1e-6) + key_frame_idxs.append(frame_idx) + + # Reset for decode any frames + stream.codec_context.skip_frame = "DEFAULT" + + # Sort the frames under the cases that frames are unsorted + video_idxs_sort_idx = np.argsort(np.array(video_idxs)) + video_idxs_sorted = np.array(video_idxs)[video_idxs_sort_idx] + + # The keyframe assignment for each frame + keyframe_assignment = np.clip(((np.array(video_idxs_sorted)[ + None] - np.array(key_frame_idxs)[:, None]) > 0).sum(0) - 1, 0, None) + + time_base = container.streams.video[0].time_base + framerate = container.streams.video[0].average_rate + + previous_keyframe_assigment = -1 + for ii, frame_num in enumerate(video_idxs_sorted): + this_assignment = keyframe_assignment[ii] + + # Reseek only if when the keyframe are changed, avoid redecode frames + if this_assignment != previous_keyframe_assigment: + # Calculate the timestamp for the desired frame + frame_container_pts = int( + ((key_frame_idxs[this_assignment] + 1) / framerate) / time_base) + + # Seek to the closest keyframe before the desired timestamp + container.seek(frame_container_pts, backward=True, + stream=container.streams.video[0]) + previous_keyframe_assigment = this_assignment + + # Record where we start, for debug only + # start_idx = key_frame_idxs[this_assignment] + + previous_frame_idx = -1 + while previous_frame_idx < frame_num: + frame = next(container.decode(video=0)) + previous_frame_idx = int( + frame.pts * stream.time_base * stream.average_rate + 1e-6) + # Debug code to check if always get the desired frame + # print(f"start={start_idx}, source={previous_frame_idx}, target={frame_num}, ") + frames_sorted.append(frame.to_image()) + + # Recollect to the original sorts => inverse sort + frames = [None for _ in range(len(video_idxs))] + for i, idx in enumerate(video_idxs_sort_idx): + frames[idx] = frames_sorted[i] + elif self.decode_backend == 'image_bytes': + video_length = len(video_bytes) + video_idxs = sampling( + video_length, self.sample_n_frames, self.sample_stride) + if video_idxs is None: + return None + frames = [] + for idx in video_idxs: + frame_byte = video_bytes[idx] + with Image.open(io.BytesIO(frame_byte)) as frame: + frame = frame.convert("RGB") + frames.append(frame) + + return frames + + def load_state_dict(self, state_dict): + # get remaining ranks + if 'data_world_size' not in self.state_dict: + print('[AIP_dataset] no state_dict; init data loading') + elif self.data_world_size != self.state_dict['data_world_size']: + print('[AIP_dataset] inconsistent data_world_size, init data loading') + elif self.state_dict['data_world_size'] != len(self.state_dict.get('seen_times', [])): + print('[AIP_dataset] corrupted state_dict; init data loading') + else: + #this has to be the same across all workers + self.state_dict = state_dict + print('[AIP_dataset] resume data loading from state_dict') + max_times = max(self.state_dict['seen_times']) + for rank, times in enumerate(self.state_dict['seen_times']): + for _ in range(max_times-times): + self.remaining_ranks.append(rank) + + def __len__(self): + if self.total_length is None: + counts = get_length_subprocess(self.path, self.ignore_prefixes) + self.total_length = counts + return self.total_length + + @ classmethod + def create_dataset_function(cls, data_path, args, **kwargs): + return cls(path=data_path, **kwargs) diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/__init__.py b/dataset_code/sft_sftnews/offload/dataset_tool/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8e0b76067dfdb443049ab1c639d2706fa667b333 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/dataset_tool/__init__.py @@ -0,0 +1,5 @@ +from .dataset_hdfs import * +from .image_dataset import T2IHDFSDataset, T2IHDFSDataset_dump +from .parquet_dataset.video_parquet import SeedV1Dataset, SeedV1Dataset_dump +from .AIP_dataset import AIPVideoDataset +from .collection_dataset import CollectionDataset, CollectionDataset_dump, collate_fn_map diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/AIP_dataset.cpython-310.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/AIP_dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c1eecaad3b75e59aeafe417bd8ac649b56e3d2b Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/AIP_dataset.cpython-310.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/AIP_dataset.cpython-311.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/AIP_dataset.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26d010ca3d7dbc1b68d1ba4d6112fa08cad72a11 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/AIP_dataset.cpython-311.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/__init__.cpython-310.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b91ecadfbe26acba715d7a065a361524c8611a65 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/__init__.cpython-310.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/__init__.cpython-311.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03c257fa6b3b8217c50d1bf04d636519bbc633be Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/__init__.cpython-311.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/__init__.cpython-313.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6001fec9dff23714b8a10052a1f39477d47622cc Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/__init__.cpython-313.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/collection_dataset.cpython-310.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/collection_dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d500def6bedb34cc6702351b79dedd7493310a90 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/collection_dataset.cpython-310.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/collection_dataset.cpython-311.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/collection_dataset.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3e3376e742fc84ae8e6301f41296986baed87d0 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/collection_dataset.cpython-311.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/dataset_hdfs.cpython-310.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/dataset_hdfs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae5622f63c830063b80f28d29bb90725f9d2bffe Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/dataset_hdfs.cpython-310.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/dataset_hdfs.cpython-311.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/dataset_hdfs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbad1dc193ebb0a3f6186c72a46e6d67ad11fcab Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/dataset_hdfs.cpython-311.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/dataset_hdfs.cpython-313.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/dataset_hdfs.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a85e4a7a828c7feff25c0061c0012a7ea6866fc7 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/dataset_hdfs.cpython-313.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/image_dataset.cpython-310.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/image_dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee7c3511c8282be58027eca98ce790e7bfc47a2e Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/image_dataset.cpython-310.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/image_dataset.cpython-311.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/image_dataset.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21af4f41755b8c4c9b81a7809347bb87d95872d4 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/__pycache__/image_dataset.cpython-311.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/collection_dataset.py b/dataset_code/sft_sftnews/offload/dataset_tool/collection_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..f8b31601c9537abbeb08189b35c98bf7359a5178 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/dataset_tool/collection_dataset.py @@ -0,0 +1,672 @@ +import io +import os +import json +import glob +import torch +from copy import deepcopy +from typing import Dict, List +import importlib +import random +from torch.utils.data import ChainDataset, IterableDataset, Dataset +import torchvision.transforms as transforms +from torch.utils.data._utils.collate import default_collate +from torchvision.transforms import functional as F +import concurrent.futures + +from dataset_tool.AIP_dataset import AIPVideoDataset + +from PIL import Image +from diffusers.utils import export_to_video +from diffusers.training_utils import free_memory + +def collate_fn_map(samples): + """ + Custom collate function that processes a list of samples into a batch. + """ + if type(samples) is list and type(samples[0]) is list: + samples = samples[0] # remove the first batch, as it is always 1 + if isinstance(samples[0], dict): + none_keys = [] + for key in samples[0]: + values = [sample[key] for sample in samples] + if any(value is None for value in values): + none_keys.append(key) + + if none_keys: + print(f"Warning: Found None values in keys: {none_keys}") + + return {key: default_collate([sample[key] for sample in samples]) for key in samples[0]} + raise NotImplementedError + else: + return default_collate(samples) + + +class CollectionDataset_dump(IterableDataset): + def __init__( + self, + train_data: list[str], + train_data_weights: list[int | float], + dataset_collections: Dict[str, Dict], + batch_size=1, + image_batch_size=48, + enable_bucket=False, + infinite=True, + shuffle=True, + local_cache='', # this should be a ByteNAS path + data_cache_prefix={'AIPVideoDataset': 'aip_dataset_cache'}, + ): + # prepare for bucketings + self.enable_bucket = enable_bucket + self.batch_size = batch_size + self.image_batch_size = image_batch_size + + self.buckets = {} + self.buckets_transform = {} + self.resolutions = set() + if not self.enable_bucket: + assert batch_size == 1, "if not enable_bucket, batch_size must be 1" + + self.train_data_weights = train_data_weights + + self.dataset_list = [] + self.dataset_names = [] + self.image_dataset_names = [] + self.dataset_collections = dataset_collections + self.dataset_to_aspect_ratios = {} + self.init_state_dict = {} + self.local_cache_prefix_list = [] + for data_name in train_data: + if data_name not in dataset_collections: + print(f'{data_name} not in dataset collections') + return + self.dataset_config = dataset_collections[data_name] + aspect_ratios = self.dataset_config['aspect_ratios'] + self.dataset_to_aspect_ratios[data_name] = aspect_ratios + self.add_aspect_ratios(aspect_ratios) + + module, cls = self.dataset_config['target'].rsplit(".", 1) + data_class = getattr( + importlib.import_module(module, package=None), cls) + if cls == 'T2IHDFSDataset' or cls == 'T2IHDFSDataset_dump': + self.image_dataset_names.append(data_name) + + if cls in data_cache_prefix: + data_cache = os.path.join(local_cache, data_cache_prefix[cls]) + os.makedirs(data_cache, exist_ok=True) + local_cache_prefix = os.path.join(data_cache, data_name) + self.clean_cache(local_cache_prefix) + self.dataset_config['params']['local_cache_prefix'] = local_cache_prefix + self.local_cache_prefix_list.append(local_cache_prefix) + else: + self.local_cache_prefix_list.append('') + dataset = data_class.create_dataset_function( + self.dataset_config['path'], None, **self.dataset_config['params']) + if cls == 'AIPVideoDataset': + self.init_state_dict[data_name] = dataset.state_dict + self.dataset_list.append(dataset) + self.dataset_names.append(data_name) + self.length = sum([len(dataset) for dataset in self.dataset_list]) + self.dataset_iter_list = [iter(dataset) for dataset in self.dataset_list] + + def add_aspect_ratios(self, aspect_ratios): + for key in aspect_ratios.keys(): + self.buckets[key] = [] + + for key, sample_size in aspect_ratios.items(): + sample_size = tuple(sample_size) + self.buckets_transform[key] = transforms.Compose([ + transforms.Resize(min(sample_size[0], sample_size[1])), # fix when height > width + transforms.CenterCrop(sample_size), + ]) + for h, w in aspect_ratios.values(): + self.resolutions.add((49, h, w)) + + def get_bucket_id(self, item, dataset_name): + """ + for large resolution data, we may have multiple bucket ids + """ + _,_,_,H,W = item['mp4']['latent_256_size'] + H = H * 64 + W = W* 64 + ratio = float(H) / float(W) + + ratio_strategy = self.dataset_collections[dataset_name]['ratio_strategy'] + ratios = self.dataset_to_aspect_ratios[dataset_name] + if ratio_strategy == 'random': + bucket_id = random.choice(list(ratios.keys())) + elif ratio_strategy == 'closest': + bucket_id = min(ratios.items(), + key=lambda r: abs(float(r[1][0]) / float(r[1][1]) - ratio))[0] + else: + raise f"ratio_strategy {ratio_strategy} not support ..." + + return bucket_id + + def __len__(self): + return self.length + + def crop_and_resize(self, image, h_prime, w_prime): + """ + Crop and resize a 4D tensor image. + + Args: + image: The input 4D tensor image of shape (frame, channel, h, w). + h_prime: Desired height of the cropped image. + w_prime: Desired width of the cropped image. + + Returns: + The cropped and resized 4D tensor image. + """ + frames, channels, h, w = image.shape + aspect_ratio_original = h / w + aspect_ratio_target = h_prime / w_prime + + if aspect_ratio_original >= aspect_ratio_target: + new_h = int(w * aspect_ratio_target) + top = (h - new_h) // 2 + bottom = top + new_h + left = 0 + right = w + else: + new_w = int(h / aspect_ratio_target) + left = (w - new_w) // 2 + right = left + new_w + top = 0 + bottom = h + # print(f"left {left}, right {right}, top {top}, bottom {bottom}") + # Crop the image + cropped_image = image[:, :, top:bottom, left:right] + # Resize the cropped image + resized_image = F.resize(cropped_image, (h_prime, w_prime)) + return resized_image + + def put_to_bucket(self, item, dataset_name): + if len(item['latent'].shape) == 5: + _,_,_,H,W = item['latent'].shape + else: + _,_,H,W = item['latent'].shape + bucket_id = [] + for key, value in self.dataset_to_aspect_ratios[dataset_name].items(): + if value == [H * 64, W* 64]: + bucket_id = key + ori_frams, ori_c, ori_H, ori_W = item['mp4'].shape + ori_ratio = ori_H / ori_W + bucket_h, bucket_w = self.dataset_to_aspect_ratios[dataset_name][bucket_id][0], self.dataset_to_aspect_ratios[dataset_name][bucket_id][1] + bucket_ratio = bucket_h / bucket_w + # print(f"ori_H {ori_H}, ori_W {ori_W}, ori_ratio {ori_ratio}. bucket_h {bucket_h}, bucket_w {bucket_w}, bucket_ratio {bucket_ratio}") + item['mp4'] = self.crop_and_resize(item['mp4'], bucket_h, bucket_w) + + # ori_frams, ori_c, ori_H, ori_W = item['mp4'].shape + # ori_ratio = ori_H / ori_W + # bucket_h, bucket_w = self.dataset_to_aspect_ratios[dataset_name][bucket_id][0], self.dataset_to_aspect_ratios[dataset_name][bucket_id][1] + # bucket_ratio = bucket_h / bucket_w + # # print(f"ori_H {ori_H}, ori_W {ori_W}, ori_ratio {ori_ratio}. bucket_h {bucket_h}, bucket_w {bucket_w}, bucket_ratio {bucket_ratio}") + # item['mp4'] = self.crop_and_resize(item['mp4'], bucket_h, bucket_w) + + # frames, c, H, W = item['mp4'].shape + # # rewrite item to the same format as the original dataset + new_item = {} + new_item['videos'] = item['mp4'] + if len(item['latent'].shape) == 5: + new_item['latent'] = item['latent'][0] + else: + new_item['latent'] = item['latent'] + new_item['prompts'] = item['txt'] if item['txt'] is not None else "" # check text + latent_tail = item.get('latent_tail') + if latent_tail is not None: + new_item['latent_tail'] = item['latent_tail'] + latent_flow = item.get('latent_flow') + if latent_flow is not None: + new_item['latent_flow'] = item['latent_flow'] + # else: + # new_item['latent_tail'] = None + # new_item['video_metadata'] = { + # 'num_frames': frames, + # 'height': H, + # 'width': W, + # } + self.buckets[bucket_id].append(new_item) + + batch = None + cur_batch_size = self.image_batch_size if bucket_id.startswith("i-") else self.batch_size + if len(self.buckets[bucket_id]) >= cur_batch_size: + batch = self.buckets[bucket_id] + self.buckets[bucket_id] = [] + return batch + + def __iter__(self): + def __native__iter(): + while True: + dataset_idx = random.choices( + list(range(len(self.dataset_list))), weights=self.dataset_weights)[0] + dataset = self.dataset_iter_list[dataset_idx] + yield next(dataset) + + def __bucket__iter(): + def get_next_item(dataset): + return next(dataset) + while True: + dataset_idx = random.choices( + list(range(len(self.dataset_list))), weights=self.train_data_weights)[0] + dataset = self.dataset_iter_list[dataset_idx] + dataset_name = self.dataset_names[dataset_idx] + if dataset_name in self.image_dataset_names: + replicate_times = max(int(self.image_batch_size / self.batch_size), 1) + batch_data_list = [] + while replicate_times > 0: + item = next(dataset) + batch_data = self.put_to_bucket(item, dataset_name) + if batch_data is not None: + batch_data_list.append(batch_data) + replicate_times -= 1 + for batch_data in batch_data_list: + yield batch_data + # else: + # item = next(dataset) + # if item == "wtf_is_abnormal": + # print(f"too much abnormal from {dataset_name}, continue") + # continue + # if item == "max_bad_file_count_reached": + # print(f"{dataset_name} for this worker is corrupted, continue") + # continue + # batch_data = self.put_to_bucket(item, dataset_name) + # if batch_data is not None: + # yield batch_data + else: + with concurrent.futures.ThreadPoolExecutor() as executor: + future = executor.submit(get_next_item, dataset) + try: + item = future.result(timeout=10) + except concurrent.futures.TimeoutError: + print(f"timeout for get data from {dataset_name}") + continue + if item == "wtf_is_abnormal": + print(f"too much abnormal from {dataset_name}, continue") + continue + if item == "max_bad_file_count_reached": + print(f"{dataset_name} for this worker is corrupted, continue") + continue + batch_data = self.put_to_bucket( item, dataset_name) + if batch_data is not None: + yield batch_data + + if self.enable_bucket: + return __bucket__iter() + else: + return __native__iter() + + def state_dict(self): + output_state_dict = deepcopy(self.init_state_dict) + for dataset_name, local_cache_prefix in zip(self.dataset_names, self.local_cache_prefix_list): + if dataset_name not in self.init_state_dict: + continue + cache_list = glob.glob(f'{local_cache_prefix}*') + for cache_path in cache_list: + with open(cache_path, 'r') as f: + for l in f.readlines(): + r = int(l.strip()) + output_state_dict[dataset_name]['seen_times'][r] += 1 + return output_state_dict + + def load_state_dict(self, state_dict): + for dataset_name, local_cache_prefix, dataset in zip(self.dataset_names, self.local_cache_prefix_list, self.dataset_list): + if dataset_name not in state_dict: + continue + if dataset_name not in self.init_state_dict: + continue + self.clean_cache(local_cache_prefix) + dataset.load_state_dict(state_dict[dataset_name]) + self.init_state_dict[dataset_name] = dataset.state_dict + + def clean_cache(self, local_cache_prefix): + for fname in glob.glob(f'{local_cache_prefix}*'): + try: + os.remove(fname) + except OSError: + pass + + @classmethod + def create_dataset_function(cls, data, data_weights, **kwargs): + return cls(data, data_weights, **kwargs) + + + +class CollectionDataset(IterableDataset): + def __init__( + self, + train_data: list[str], + train_data_weights: list[int | float], + dataset_collections: Dict[str, Dict], + batch_size=1, + image_batch_size=48, + enable_bucket=False, + infinite=True, + shuffle=True, + local_cache='', # this should be a ByteNAS path + data_cache_prefix={'AIPVideoDataset': 'aip_dataset_cache'}, + ): + # prepare for bucketings + self.enable_bucket = enable_bucket + self.batch_size = batch_size + self.image_batch_size = image_batch_size + + self.buckets = {} + self.buckets_transform = {} + self.resolutions = set() + if not self.enable_bucket: + assert batch_size == 1, "if not enable_bucket, batch_size must be 1" + + self.train_data_weights = train_data_weights + + self.dataset_list = [] + self.dataset_names = [] + self.image_dataset_names = [] + self.dataset_collections = dataset_collections + self.dataset_to_aspect_ratios = {} + self.init_state_dict = {} + self.local_cache_prefix_list = [] + for data_name in train_data: + if data_name not in dataset_collections: + print(f'{data_name} not in dataset collections') + return + self.dataset_config = dataset_collections[data_name] + aspect_ratios = self.dataset_config['aspect_ratios'] + self.dataset_to_aspect_ratios[data_name] = aspect_ratios + self.add_aspect_ratios(aspect_ratios) + + module, cls = self.dataset_config['target'].rsplit(".", 1) + data_class = getattr( + importlib.import_module(module, package=None), cls) + if cls == 'T2IHDFSDataset': + self.image_dataset_names.append(data_name) + + if cls in data_cache_prefix: + data_cache = os.path.join(local_cache, data_cache_prefix[cls]) + os.makedirs(data_cache, exist_ok=True) + local_cache_prefix = os.path.join(data_cache, data_name) + self.clean_cache(local_cache_prefix) + self.dataset_config['params']['local_cache_prefix'] = local_cache_prefix + self.local_cache_prefix_list.append(local_cache_prefix) + else: + self.local_cache_prefix_list.append('') + dataset = data_class.create_dataset_function( + self.dataset_config['path'], None, **self.dataset_config['params']) + if cls == 'AIPVideoDataset': + self.init_state_dict[data_name] = dataset.state_dict + self.dataset_list.append(dataset) + self.dataset_names.append(data_name) + + self.length = sum([len(dataset) for dataset in self.dataset_list]) + self.dataset_iter_list = [iter(dataset) for dataset in self.dataset_list] + + def add_aspect_ratios(self, aspect_ratios): + for key in aspect_ratios.keys(): + self.buckets[key] = [] + + for key, sample_size in aspect_ratios.items(): + sample_size = tuple(sample_size) + self.buckets_transform[key] = transforms.Compose([ + transforms.Resize(min(sample_size[0], sample_size[1])), # fix when height > width + transforms.CenterCrop(sample_size), + ]) + for h, w in aspect_ratios.values(): + self.resolutions.add((49, h, w)) + + def get_bucket_id(self, item, dataset_name): + """ + for large resolution data, we may have multiple bucket ids + """ + frames, c, H, W = item['mp4'].shape + ratio = float(H) / float(W) + + ratio_strategy = self.dataset_collections[dataset_name]['ratio_strategy'] + ratios = self.dataset_to_aspect_ratios[dataset_name] + if ratio_strategy == 'random': + bucket_id = random.choice(list(ratios.keys())) + elif ratio_strategy == 'closest': + bucket_id = min(ratios.items(), + key=lambda r: abs(float(r[1][0]) / float(r[1][1]) - ratio))[0] + else: + raise f"ratio_strategy {ratio_strategy} not support ..." + + return bucket_id + + def __len__(self): + return self.length + + def crop_and_resize(self, image, h_prime, w_prime): + """ + Crop and resize a 4D tensor image. + + Args: + image: The input 4D tensor image of shape (frame, channel, h, w). + h_prime: Desired height of the cropped image. + w_prime: Desired width of the cropped image. + + Returns: + The cropped and resized 4D tensor image. + """ + frames, channels, h, w = image.shape + aspect_ratio_original = h / w + aspect_ratio_target = h_prime / w_prime + + if aspect_ratio_original >= aspect_ratio_target: + new_h = int(w * aspect_ratio_target) + top = (h - new_h) // 2 + bottom = top + new_h + left = 0 + right = w + else: + new_w = int(h / aspect_ratio_target) + left = (w - new_w) // 2 + right = left + new_w + top = 0 + bottom = h + # print(f"left {left}, right {right}, top {top}, bottom {bottom}") + # Crop the image + cropped_image = image[:, :, top:bottom, left:right] + # Resize the cropped image + resized_image = F.resize(cropped_image, (h_prime, w_prime)) + return resized_image + + def _save_frames(self, frame_raw, uid, fps, stride=None, base_path="/mnt/bn/yufan-dev-my/ysh/Datasets/sft_sftnews_videos"): + if stride: + output_path = f"{base_path}/processed/stride{stride}" + else: + output_path = f"{base_path}/processed" + os.makedirs(output_path, exist_ok=True) + + save_list = [] + frame_height, frame_width = None, None + for frame in frame_raw: + frame = (frame + 1) / 2 * 255 + frame = transforms.ToPILImage()(frame.to(torch.uint8)).convert("RGB") + if frame_height is None: + frame_height, frame_width = frame.height, frame.width + video_path = f"{output_path}/{uid}_{len(frame_raw)}_{frame_height}_{frame_width}.mp4" + if os.path.exists(video_path): + print(f"skip original video: {video_path}") + return + save_list.append(frame) + frame = None + del frame + + if not save_list: + return + + export_to_video(save_list, video_path, fps=fps) + print(f"save to {video_path}") + + save_list = None + del save_list + + free_memory() + + + def put_to_bucket(self, item, dataset_name): + bucket_id = self.get_bucket_id(item, dataset_name) + ori_frams, ori_c, ori_H, ori_W = item['mp4'].shape + ori_ratio = ori_H / ori_W + bucket_h, bucket_w = self.dataset_to_aspect_ratios[dataset_name][bucket_id][0], self.dataset_to_aspect_ratios[dataset_name][bucket_id][1] + bucket_ratio = bucket_h / bucket_w + # print(f"ori_H {ori_H}, ori_W {ori_W}, ori_ratio {ori_ratio}. bucket_h {bucket_h}, bucket_w {bucket_w}, bucket_ratio {bucket_ratio}") + item['mp4'] = self.crop_and_resize(item['mp4'], bucket_h, bucket_w) + + # ----- save video ----- + try: + if item["topk_avg_motion_scores_t"] >= 400: + base_path="/mnt/bn/yufan-dev-my/ysh/Datasets/sft_sftnews_videos/high_motion" + else: + base_path="/mnt/bn/yufan-dev-my/ysh/Datasets/sft_sftnews_videos/low_motion" + self._save_frames(item['mp4'], item["uttid"], item['fps'], base_path=base_path) + + item["stride_mp4"] = self.crop_and_resize(item["stride_mp4"], bucket_h, bucket_w) + self._save_frames(item["stride_mp4"], item["uttid"], item['fps'], stride=item['stride'], base_path=base_path) + except: + pass + # ----- save video ----- + + # ----- save meta ----- + if item["topk_avg_motion_scores_t"] >= 400: + base_path="/mnt/bn/yufan-dev-my/ysh/Datasets/sft_sftnews_videos/metadata/high_motion" + else: + base_path="/mnt/bn/yufan-dev-my/ysh/Datasets/sft_sftnews_videos/metadata/low_motion" + os.makedirs(base_path, exist_ok=True) + output_path = os.path.join(base_path, f"{item['uttid']}.json") + if not os.path.exists(output_path): + meta = { + "uttid": item["uttid"], + "text": item['txt'], + "ori_num_frames": item["ori_num_frames"], + "ori_height": item["ori_height"], + "ori_width": item["ori_width"], + "cur_num_frames": item["cur_num_frames"], + "cur_height": item['mp4'].shape[-2], + "cur_width": item['mp4'].shape[-1], + "topk_avg_motion_scores_t": item["topk_avg_motion_scores_t"], + } + with open(output_path, 'w',) as f: + json.dump(meta, f, indent=2) + print(f"save json to {output_path}") + # ----- save meta ----- + + first_frame = item['mp4'][0] + item["first_frames_images"] = (first_frame + 1) / 2 * 255 + + frames, c, H, W = item['mp4'].shape + # rewrite item to the same format as the original dataset + new_item = {} + new_item['videos'] = item['mp4'] + new_item['prompts'] = item['txt'] if item['txt'] is not None else "" # check text + new_item['video_metadata'] = { + 'num_frames': frames, + 'height': H, + 'width': W, + } + new_item["first_frames_images"] = item["first_frames_images"] + new_item["uttid"] = item["uttid"] + new_item['stride_videos'] = item["stride_mp4"] + new_item["topk_avg_motion_scores_t"] = item["topk_avg_motion_scores_t"] + self.buckets[bucket_id].append(new_item) + + batch = None + cur_batch_size = self.image_batch_size if bucket_id.startswith("i-") else self.batch_size + if len(self.buckets[bucket_id]) >= cur_batch_size: + batch = self.buckets[bucket_id] + self.buckets[bucket_id] = [] + + # item["uttid"] = None + # item['txt'] = None + # item["ori_num_frames"] = None + # item["ori_height"] = None + # item["ori_width"] = None + # item["cur_num_frames"] = None + # item['mp4'] = None + # item["topk_avg_motion_scores_t"] = None + # item["first_frames_images"] = None + # new_item['videos'] = None + # new_item['prompts'] = None + # new_item["first_frames_images"] = None + # new_item["uttid"] = None + # new_item['stride_videos'] = None + # new_item["topk_avg_motion_scores_t"] = None + + new_item = None + item = None + meta = None + del meta + del item + del new_item + free_memory() + + return batch + + def __iter__(self): + def __native__iter(): + while True: + dataset_idx = random.choices( + list(range(len(self.dataset_list))), weights=self.dataset_weights)[0] + dataset = self.dataset_iter_list[dataset_idx] + yield next(dataset) + + def __bucket__iter(): + while True: + dataset_idx = random.choices( + list(range(len(self.dataset_list))), weights=self.train_data_weights)[0] + dataset = self.dataset_iter_list[dataset_idx] + dataset_name = self.dataset_names[dataset_idx] + if dataset_name in self.image_dataset_names: + replicate_times = max(int(self.image_batch_size / self.batch_size), 1) + batch_data_list = [] + while replicate_times > 0: + item = next(dataset) + batch_data = self.put_to_bucket(item, dataset_name) + if batch_data is not None: + batch_data_list.append(batch_data) + replicate_times -= 1 + for batch_data in batch_data_list: + yield batch_data + else: + item = next(dataset) + batch_data = self.put_to_bucket(item, dataset_name) + if batch_data is not None: + yield batch_data + + if self.enable_bucket: + return __bucket__iter() + else: + return __native__iter() + + def state_dict(self): + output_state_dict = deepcopy(self.init_state_dict) + for dataset_name, local_cache_prefix in zip(self.dataset_names, self.local_cache_prefix_list): + if dataset_name not in self.init_state_dict: + continue + cache_list = glob.glob(f'{local_cache_prefix}*') + for cache_path in cache_list: + with open(cache_path, 'r') as f: + for l in f.readlines(): + r = int(l.strip()) + output_state_dict[dataset_name]['seen_times'][r] += 1 + return output_state_dict + + def load_state_dict(self, state_dict): + for dataset_name, local_cache_prefix, dataset in zip(self.dataset_names, self.local_cache_prefix_list, self.dataset_list): + if dataset_name not in state_dict: + continue + if dataset_name not in self.init_state_dict: + continue + self.clean_cache(local_cache_prefix) + dataset.load_state_dict(state_dict[dataset_name]) + self.init_state_dict[dataset_name] = dataset.state_dict + + def clean_cache(self, local_cache_prefix): + for fname in glob.glob(f'{local_cache_prefix}*'): + try: + os.remove(fname) + except OSError: + pass + + @classmethod + def create_dataset_function(cls, data, data_weights, **kwargs): + return cls(data, data_weights, **kwargs) diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/dataset_hdfs.py b/dataset_code/sft_sftnews/offload/dataset_tool/dataset_hdfs.py new file mode 100644 index 0000000000000000000000000000000000000000..e97cd27a0163f79ccc7c61f70f5d62bf87861694 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/dataset_tool/dataset_hdfs.py @@ -0,0 +1,198 @@ +# ------------------------------------- +# Modified by: Jacob Zhiyuan Fang +# Date: 2024/09/10 +# Email: jacob.fang@bytedance.com +# Author: Xun Guo +# Email: guoxun.99@bytedance.com +# Date: 2024/05/29 +# ------------------------------------- + +import os +import json +import time +import random +import subprocess + +import torch +import numpy as np +import tensorflow as tf +import multiprocessing as mp +import torchvision.transforms as transforms + +from .parquet_dataset.parquet_utils import get_random_for_rank_and_worker, get_portion_for_rank_and_worker +from typing import List, Tuple +from dataloader import KVReader +from torch.utils.data.dataset import Dataset +from torchvision.transforms.functional import to_pil_image + +from diffusers.training_utils import free_memory + +class T2VHDFSDataset(Dataset): + def __init__(self, + json_path, + sample_size=256, + sample_stride=4, + sample_n_frames=16, + is_image=False, + pick=False, + fps=24, + shuffle=True, + infinite=True, + ): + super().__init__() + + with open(json_path, 'r') as jsonfile: + self.dataset = json.load(jsonfile) + assert type( + self.dataset) == list, "The annotation file should contain a list !!!" + + # IMPORTANT: Prevent tf load tensor to GPU. + tf.config.set_visible_devices([], 'GPU') + self._context_features = { + 'title': tf.io.FixedLenFeature([], dtype=tf.string)} + self._sequence_features = { + 'data': tf.io.FixedLenSequenceFeature([], dtype=tf.string)} + + self.length = len(self.dataset) + self.sample_n_frames = sample_n_frames + self.sample_stride = sample_stride + self.is_image = is_image + self.pick = pick + self.num_parallel_reader = 32 + self.shuffle = shuffle + self.infinite = infinite + if sample_size == -1: # if sample_size is None, using Identity transformation + self.pixel_transforms = transforms.Compose([ + transforms.Lambda(lambda x: x) + ]) + else: + sample_size = tuple(sample_size) if not isinstance( + sample_size, int) else (sample_size, sample_size) + self.pixel_transforms = transforms.Compose([ + transforms.Resize(sample_size[0]), + transforms.CenterCrop(sample_size), + ]) + self.fps = fps + + def __iter__(self): + if self.shuffle: + get_random_for_rank_and_worker(None).shuffle(self.dataset) + part_dataset = get_portion_for_rank_and_worker(self.dataset) + while True: + if self.shuffle: + get_random_for_rank_and_worker(None).shuffle(part_dataset) + for idx in range(len(part_dataset)): + try: + to_return = self.__getitem_impl__(idx) + yield to_return + except (RuntimeError, ValueError): + print('Appearing HDFS iops error setting src img \n' * 5) + # idx = random.sample(range(self.length), 1)[0] + if not self.infinite: + break + + def __len__(self): + return len(self.dataset) + + def decode_image(self, raw_data): + return tf.image.decode_jpeg(raw_data, channels=3, dct_method='INTEGER_ACCURATE').numpy() + + def get_batch(self, idx): + video_dict = self.dataset[idx] + video_name, index_file, caption = video_dict[ + 'video_name'], video_dict['index_file'], video_dict['caption'] + reader = KVReader(index_file, self.num_parallel_reader) + keys = reader.list_keys() + assert video_name in keys, "video file not in this index file !!!" + values = reader.read_many([video_name])[0] + + # Decode record + contexts, sequences = tf.io.parse_single_sequence_example( + serialized=values, + context_features=self._context_features, + sequence_features=self._sequence_features) + + # Raw frames data + raw_frames = sequences['data'] + del reader + video_length = len(raw_frames) + + # Sample frames + if not self.is_image: + + # Jacob Sep 17th: If sample frames > video frames, we drop this video + if (self.sample_n_frames - 1) * self.sample_stride + 1 > video_length: + return None, None + clip_length = min( + video_length, (self.sample_n_frames - 1) * self.sample_stride + 1) + start_idx = random.randint(0, video_length - clip_length) + batch_index = np.linspace( + start_idx, start_idx + clip_length - 1, self.sample_n_frames, dtype=int) + else: + batch_index = [random.randint(0, video_length - 1)] + + # Decode frames + pixel_values = [] + for idx in batch_index: + frame = raw_frames[idx] + frame = self.decode_image(frame) + frame = torch.as_tensor(frame).float().permute(2, 0, 1) + frame = (frame - 127.5) / 127.5 + pixel_values.append(frame) + + if self.is_image: + pixel_values = pixel_values[0] + + pixel_values = torch.stack(pixel_values, dim=0) + return pixel_values, caption + + def __getitem_impl__(self, idx, candidate=None): + # To avoid bad videos, we retry if there is an Exception. + # By default the size of videos are all 512, 910 so no need filter. + if candidate is None: + candidate = list(range(self.length)) + while True: + try: + pixel_values, caption = self.get_batch(idx) + + if pixel_values is None: + # restart + idx = random.sample(candidate, 1)[0] + else: + # end the iteration + break + except Exception as e: + print(f"VideoTextPairDataset got unexpected exception: {e}") + idx = random.sample(candidate, 1)[0] + pixel_values = self.pixel_transforms(pixel_values) + + # pixel_values in shape of Frames x channel x H x W + sample = dict( + mp4=pixel_values, + txt=caption, + num_frames=self.sample_n_frames, + fps=self.fps, + ) + + return sample + + @classmethod + def create_dataset_function(cls, json_path, args, **kwargs): + return cls(json_path=json_path, **kwargs) + + +# Dataset unit test checking how many videos are not preferred +if __name__ == "__main__": + dataset = T2VHDFSDataset( + json_path="/mnt/bn/icvg/video_gen/captions/pond5_res/pond5_data_res_human.json", + sample_size=512, + sample_stride=4, + sample_n_frames=49, + is_image=False, + pick=False, + ) + dataloader = torch.utils.data.DataLoader( + dataset, batch_size=1, num_workers=1) + for idx, batch in enumerate(dataloader): + if idx % 100 == 0: + breakpoint() diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/image_dataset.py b/dataset_code/sft_sftnews/offload/dataset_tool/image_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..0fbee47bd8f5bb4878609fc6e7d91300f09f94f0 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/dataset_tool/image_dataset.py @@ -0,0 +1,929 @@ +import os +import sys +import time +import torch +import random +import bson, json +from dataloader import KVReader, FalconReader +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional, Tuple +from torch.utils.data.dataset import Dataset +from torchvision.transforms import functional as TVF +from torchvision.transforms.functional import InterpolationMode +from torchvision.transforms import Compose, ToTensor, Normalize, RandomResizedCrop +from pyarrow import fs, Field +import pyarrow.parquet as pq +import numpy as np + +########## Utils ########## +def hlist_files(folders, postfix=".index"): + """ + 罗列一些 hdfs 路径下的文件。 + """ + import subprocess + import os + if isinstance(folders, str): + folders = [folders] + files = [] + for folder in folders: + if folder.startswith('hdfs'): + pipe = subprocess.Popen("hdfs dfs -ls -R {}".format(folder), shell=True, + stdout=subprocess.PIPE) + # output, _ = pipe.communicate() + for line in pipe.stdout: # type: ignore + line = line.strip() + # drwxr-xr-x - user group 4 file + if len(line.split()) < 5: + continue + filepath = line.split()[-1].decode("utf8") + if filepath.endswith(postfix): + files.append(filepath) + pipe.stdout.close() # type: ignore + pipe.wait() + else: + return [] + files = sorted(files) + return files + + +def resize_crop(image, image_height, image_width, use_resize_random_crop=False): + aspect_ratio = image_width / image_height + if not use_resize_random_crop: + resize = RandomResizedCrop( + size=(image_height, image_width), # Crop to target width height + scale=(1, 1), # Do not scale. + ratio=(aspect_ratio, aspect_ratio), # Keep target aspect ratio. + interpolation=InterpolationMode.LANCZOS # Use LANCZO for downsample. + ) + crop_top_coord, crop_left_coord, _, _ = resize.get_params(image, scale=(1, 1), ratio=( + aspect_ratio, aspect_ratio)) + crop_coords_top_left = torch.tensor([crop_top_coord, crop_left_coord]) + image = resize(image) + else: + image_aspect_ratio = image.width / image.height + if image_aspect_ratio >= aspect_ratio: + image_resize_h = image_height + image_resize_w = int(round(image_height * (image.width / image.height))) + crop_top_coord = 0 + crop_left_coord = random.randint(0, image_resize_w - image_width) + else: + image_resize_w = image_width + image_resize_h = int(round(image_width * (image.height / image.width))) + crop_top_coord = random.randint(0, image_resize_h - image_height) + crop_left_coord = 0 + image = TVF.resize(image, size=[image_resize_h, image_resize_w], + interpolation=InterpolationMode.LANCZOS) + image = TVF.crop(image, crop_top_coord, crop_left_coord, image_height, + image_width) + crop_coords_top_left = torch.tensor([crop_top_coord, crop_left_coord]) + return image, crop_coords_top_left + + +def partition_by_size(data: List[Any], size: int) -> List[List[Any]]: + """ + Partition a list by size. + When indivisible, the last group contains fewer items than the target size. + + Examples: + - data: [1,2,3,4,5] + - size: 2 + - return: [[1,2], [3,4], [5]] + """ + return [data[i:i+size] for i in range(0, len(data), size)] + + +class timer: + def __init__(self, op, wait_seconds): + self.op = op + self.wait_seconds = wait_seconds + + def __enter__(self): + self.start_time = time.time() + + def __exit__(self, *exc_info): + self.stop_time = time.time() + self.elapsed_seconds = self.stop_time - self.start_time + if self.elapsed_seconds > self.wait_seconds: + print(f"Op: '{self.op}' took: {round(self.elapsed_seconds, 2)} seconds.", file=sys.stderr) + + +########## ImageDecoder ########## +import io +from PIL import Image +from base64 import b64decode +from abc import abstractmethod + +class ImageDecoder: + """ + Decode image from json dictionary. + Return None or raise exception if sample cannot be decoded to skip forward. + """ + @abstractmethod + def __call__(self, item: Dict[str, Any]) -> Optional[Image.Image]: + raise NotImplementedError() + + +class GeneralImageDecoder(ImageDecoder): + """ + Read image from hdfs data entry, usually is in bytes format + """ + def __init__(self): + # Avoid image too large warning messages. + Image.MAX_IMAGE_PIXELS = 1000000000 + + def __call__(self, item: Dict[str, Any]) -> Optional[Image.Image]: + image_data = item.get("image_org") or item.get("image") or item.get("binary") + if image_data is None: + return None + + if isinstance(image_data, bytes): + image_bytes = image_data + else: + image_bytes = b64decode(image_data) + + with Image.open(io.BytesIO(image_bytes)) as image: + if image.mode == "RGBA" or image.info.get("transparency", None) is not None: + image = image.convert("RGBA") + white = Image.new(mode="RGB", size=image.size, color=(255, 255, 255)) + white.paste(image, mask=image.split()[3]) + image = white + else: + image = image.convert("RGB") + return image + + +########## ImagePredicate ########## +class ImagePredicate: + """ + Check if image satifiy a certaion requirements. + Return False if not satisfied and True if pass the check. + + Be sure to pass key-value pair when using + """ + @abstractmethod + def __call__(self, image: Image.Image, **kwargs) -> bool: + raise NotImplementedError() + + +class ImageMultiPredicate(ImagePredicate): + def __init__(self, predicates: List[ImagePredicate]): + self.predicates = predicates + + def __call__(self, image: Image.Image, **kwargs) -> bool: + for predicate in self.predicates: + if not predicate(image, **kwargs): + return False + return True + + +class ImageBucketResolutionPredicate(ImagePredicate): + def __call__(self, image: Image.Image, bucket: Any, **kwargs) -> bool: + if image.size[0] < bucket.image_width or image.size[1] < bucket.image_height: + return False + return True + + +class ImageAestheticPredicate(ImagePredicate): + def __init__(self, aes_thed=0): + self.aes_thed = aes_thed + + def __call__(self, image: Image.Image, content: dict, **kwargs) -> bool: + return ("aesthetic" not in content) or (content["aesthetic"] >= self.aes_thed) + + +########## TextCleaner ########## +import re +import ftfy +import html +import urllib.parse as ul +from bs4 import BeautifulSoup + +class TextCleaner: + """ + Clear up a caption with strange/improper contents + """ + bad_punct_regex = re.compile( + r'[' + '#®•©™&@·º½¾¿¡§~' + '\)' + '\(' + '\]' + '\[' + '\}' + '\{' + '\|' + '\\' + '\/' + '\*' + r']{1,}') + + def __call__(self, text): + # The exact text cleaning as was in the training stage: + text = self.clean_caption(text) + text = self.clean_caption(text) + return text + + @staticmethod + def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + def clean_caption(self, caption): + caption = str(caption) + caption = ul.unquote_plus(caption) + caption = caption.strip().lower() + caption = re.sub('', 'person', caption) + caption = re.sub('
', ' ', caption) + # urls: + caption = re.sub( + r'\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))', + # noqa + '', caption) # regex for urls + caption = re.sub( + r'\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))', + # noqa + '', caption) # regex for urls + # html: + caption = BeautifulSoup(caption, features='html.parser').text + + # @ + caption = re.sub(r'@[\w\d]+\b', '', caption) + + # 31C0—31EF CJK Strokes + # 31F0—31FF Katakana Phonetic Extensions + # 3200—32FF Enclosed CJK Letters and Months + # 3300—33FF CJK Compatibility + # 3400—4DBF CJK Unified Ideographs Extension A + # 4DC0—4DFF Yijing Hexagram Symbols + # 4E00—9FFF CJK Unified Ideographs + caption = re.sub(r'[\u31c0-\u31ef]+', '', caption) + caption = re.sub(r'[\u31f0-\u31ff]+', '', caption) + caption = re.sub(r'[\u3200-\u32ff]+', '', caption) + caption = re.sub(r'[\u3300-\u33ff]+', '', caption) + caption = re.sub(r'[\u3400-\u4dbf]+', '', caption) + caption = re.sub(r'[\u4dc0-\u4dff]+', '', caption) + caption = re.sub(r'[\u4e00-\u9fff]+', '', caption) + ####################################################### + + # все виды тире / all types of dash --> "-" + caption = re.sub( + r'[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+', + # noqa + '-', caption) + + # кавычки к одному стандарту + caption = re.sub(r'[`´«»“”¨]', '"', caption) + caption = re.sub(r'[‘’]', "'", caption) + + # " + caption = re.sub(r'"?', '', caption) + # & + caption = re.sub(r'&', '', caption) + + # ip adresses: + caption = re.sub(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', ' ', caption) + + # article ids: + caption = re.sub(r'\d:\d\d\s+$', '', caption) + + # \n + caption = re.sub(r'\\n', ' ', caption) + + # "#123" + caption = re.sub(r'#\d{1,3}\b', '', caption) + # "#12345.." + caption = re.sub(r'#\d{5,}\b', '', caption) + # "123456.." + caption = re.sub(r'\b\d{6,}\b', '', caption) + # filenames: + caption = re.sub( + r'[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)', '', caption) + + # + caption = re.sub(r'[\"\']{2,}', r'"', caption) # """AUSVERKAUFT""" + caption = re.sub(r'[\.]{2,}', r' ', caption) # """AUSVERKAUFT""" + + # ***AUSVERKAUFT***, #AUSVERKAUFT + caption = re.sub(self.bad_punct_regex, r' ', caption) + caption = re.sub(r'\s+\.\s+', r' ', caption) # " . " + + # this-is-my-cute-cat / this_is_my_cute_cat + regex2 = re.compile(r'(?:\-|\_)') + if len(re.findall(regex2, caption)) > 3: + caption = re.sub(regex2, ' ', caption) + + caption = self.basic_clean(caption) + + caption = re.sub(r'\b[a-zA-Z]{1,3}\d{3,15}\b', '', caption) # jc6640 + caption = re.sub(r'\b[a-zA-Z]+\d+[a-zA-Z]+\b', '', caption) # jc6640vc + caption = re.sub(r'\b\d+[a-zA-Z]+\d+\b', '', caption) # 6640vc231 + + caption = re.sub(r'(worldwide\s+)?(free\s+)?shipping', '', caption) + caption = re.sub(r'(free\s)?download(\sfree)?', '', caption) + caption = re.sub(r'\bclick\b\s(?:for|on)\s\w+', '', caption) + caption = re.sub( + r'\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?', '', caption) + caption = re.sub(r'\bpage\s+\d+\b', '', caption) + + # j2d1a2a... + caption = re.sub( + r'\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\b', r' ', caption) + + caption = re.sub(r'\b\d+\.?\d*[xх×]\d+\.?\d*\b', '', caption) + + caption = re.sub(r'\b\s+\:\s+', r': ', caption) + caption = re.sub(r'(\D[,\./])\b', r'\1 ', caption) + caption = re.sub(r'\s+', ' ', caption) + + caption.strip() + + caption = re.sub(r'^[\"\']([\w\W]+)[\"\']$', r'\1', caption) + caption = re.sub(r'^[\'\_,\-\:;]', r'', caption) + caption = re.sub(r'[\'\_,\-\:\-\+]$', r'', caption) + caption = re.sub(r'^\.\S+$', '', caption) + + return caption.strip() + + +########## T2IHDFSDataset ########## +@dataclass +class Bucket: + index_files: List[str] = field(default_factory=list) # the .index filenames + image_count: int = field(default=0) # the total number of images + image_height: int = field(default=0) # the image height + image_width: int = field(default=0) # the image width + +class T2IHDFSDataset(Dataset): + def __init__(self, + hdfs_path, + resolution, + caption_key, + aspect_ratios, + debug=False, + use_resize_random_crop=False, + skip_caption_ratios=[0, 0.0655]): + super().__init__() + + self.resolution = resolution + self.image_decoder = GeneralImageDecoder() + self.image_predicate = ImageMultiPredicate([ + ImageAestheticPredicate(), + ImageBucketResolutionPredicate(), + ]) + self.image_transform = Compose([ + ToTensor(), + Normalize(mean=0.5, std=0.5), + ]) + self.text_transform = TextCleaner() + self.caption_keys = caption_key + self.debug = debug + self.rank = 0 # mock value + self.use_resize_random_crop = use_resize_random_crop + self.skip_caption_ratios = skip_caption_ratios + + self.buckets = dict() + self.bucket_override = list(map(lambda ratio: (ratio[0], ratio[1]), aspect_ratios.values())) # w, h + + if isinstance(hdfs_path, str): + hdfs_path = [hdfs_path] + filepath_list = hlist_files(hdfs_path, postfix=".index") + + for filepath in filepath_list: + # Parse name, example: + # filepath: "/laion5b_aesv2_512plus_buckets/2_19_256-896_00002_00196.index" + # filename: "/laion5b_aesv2_512plus_buckets/2_19_256-896_00002_00196" + # basename: "2_19_256-896_00002_00196" + # extension: ".index" + filename, extension = os.path.splitext(filepath) + basename = os.path.basename(filename) + + # Parse basename, example: + # {id}_{image_count}_{image_height}-{image_width}_{other_info} + if extension in [".index", ".snappy"] and "tempstate" not in filename and 'tmp' not in filename: + image_count, image_height, image_width = basename.replace("_", "-").split("-")[1:4] + # skip invalid file. + try: + image_count = int(image_count) + image_height = int(image_height) + image_width = int(image_width) + except: + continue + if image_width <=0 or image_height<=0: + continue + + image_ratio = image_width / image_height + override_image_width, override_image_height = self._override_resolution_if_needed_v1(image_width, + image_height) + override_image_ratio = override_image_width / override_image_height + # Omit buckets with unreasonable size ratio, such as (128, 1536) + if override_image_ratio / image_ratio > 1.5 or override_image_ratio / image_ratio < 0.7: + continue + + bucket_key = (override_image_width, override_image_height) + bucket_entry = self.buckets.get(bucket_key, Bucket()) + bucket_entry.index_files.append(filename) + bucket_entry.image_count += image_count + bucket_entry.image_height = override_image_height + bucket_entry.image_width = override_image_width + self.buckets[bucket_key] = bucket_entry + + for i, bucket_entry in enumerate(self.buckets.values()): + print( + f"Bucket {i}: {bucket_entry.image_width}x{bucket_entry.image_height} " + + f"contains {bucket_entry.image_count} images." + ) + print(f"Total samples: {sum([bucket_entry.image_count for bucket_entry in self.buckets.values()])}") + + def _override_resolution_if_needed_v1(self, width: int, height: int) -> Tuple[int, int]: + """ + Override the bucket resolution if configured: + Example: + - bucket override: [(1000, 200), (200, 1000)] + - current resolution: (300, 900) + - return (200, 1000) because it is the closest in aspect ratio. + """ + if self.bucket_override is not None: + # If bucket override is defined, find a new resolution from the override list that best matches the aspect ratio. + assert len(self.bucket_override) > 0, "bucket_override must not be an empty list." + target_aspect_ratio = width / height + bucket_resolutions = self.bucket_override + bucket_aspect_ratios = torch.tensor([w / h for w, h in bucket_resolutions], dtype=torch.float64) + bucket_idx = bucket_aspect_ratios.sub(target_aspect_ratio).abs().argmin().item() + width, height = bucket_resolutions[bucket_idx] + + if self.resolution != 512: + # The buckets are defined in 512 resolution. If target resolution is not 512, we need to scale it and make sure divisible by 64. + ratio = self.resolution / 512 + width = (width * ratio) // 64 * 64 + height = (height * ratio) // 64 * 64 + + return int(width), int(height) + + def __len__(self): + return sum(bucket.image_count for bucket in self.buckets.values()) + + def __iter__(self): + bucket_entries = list(self.buckets.values()) + bucket_weights = list(map(lambda bucket: bucket.image_count, bucket_entries)) + bucket_iterators = list(map(lambda bucket: self._iterate_bucket(bucket), bucket_entries)) + + while True: + try: + bucket_iterator = random.choices(bucket_iterators, bucket_weights)[0] + bucket, index_file, key, content, image, original_size_as_tuple = next(bucket_iterator) + # get caption + text = self.get_caption(content) + # Skip sample if text returned None. + if text is None: + if self.debug: print("text is None") + continue + + if self.debug: + print(f"Original_size_as_tuple {original_size_as_tuple}") + print(f"Image size: {image.size}") + print(f"Text length: {len(text)}") + + # Resize and crop image + with timer(op=f"[Rank:{self.rank}] Resize image from {index_file}, key: {key}", wait_seconds=2): + image, crop_coords_top_left = resize_crop(image, bucket.image_height, + bucket.image_width, self.use_resize_random_crop) + + # Transform image and text + with timer(op=f"[Rank:{self.rank}] Transform image and text from {index_file}, key: {key}", + wait_seconds=2): + if self.image_transform is not None: + image = self.image_transform(image) + image = image.unsqueeze(0) # Add temporal dim + + # filter pure black image + if isinstance(image, torch.Tensor) and image.std() < 0.02 and image.mean() < -0.9: + if self.debug: print("image is too dark") + continue + + if self.text_transform is not None: + text = self.text_transform(text) + if text == "": + if self.debug: print("text is empty") + continue + + if self.debug: + print(f"dataset loading current text: en is {text}") + + item = dict( + mp4=image, + txt=text, + num_frames=1 + ) + yield item + except Exception as ex: + raise ex + # Error should not happen here, but we add a guard anyway. + #print(f"Bucket dataset processing sample received unexpected exception at file: {index_file}", ex, + # file=sys.stderr) + continue + + def _iterate_bucket(self, bucket: Bucket): + # Copy the list. + index_files = list(bucket.index_files) + count_unsatisfy_image_predicor = 0 + while True: + # Shuffle files + random.shuffle(index_files) + # Loop through all the .index files + for index_file in index_files: + try: + with timer( + op=f"[Rank:{self.rank}] KVReader opens and lists keys from index file {index_file}", + wait_seconds=3 + ): + reader = FalconReader(index_file) + keys = reader.list_keys() + + # We devide keys to batches then shuffle the batch order. + # Note that keys within a batch are still contiguous for faster data loading. + keys_batches = partition_by_size(keys, 64) + random.shuffle(keys_batches) + + for key_batch in keys_batches: + with timer( + op=f"[Rank:{self.rank}] KVReader reads values from index file {index_file}, keys: {key_batch}", + wait_seconds=10, + ): + # Read values. The keys within this batch are contiguous for faster loading. + value_batch = reader.read_many(key_batch) + + # Shuffle samples within this batch. + key_value_batch = list(zip(key_batch, value_batch)) + random.shuffle(key_value_batch) + + for key, value in key_value_batch: + # Decode json + with timer(op=f"[Rank:{self.rank}] Decoding bson/json from {index_file}, key: {key}", + wait_seconds=2): + try: + content = bson.loads(value) + except: + content = json.loads(value) + + # Decode image + with timer(op=f"[Rank:{self.rank}] Decoding image from {index_file}, key: {key}", + wait_seconds=2): + image = self.image_decoder(content) + original_size_as_tuple = torch.tensor([image.height, image.width]) + # check if image meets requirements, skip if not + if image is None: + if self.debug: print("find empty image") + continue + if self.image_predicate is not None and \ + not self.image_predicate(image=image, content=content, bucket=bucket): + if self.debug: print("image does not satifiy image predicates", index_file) + count_unsatisfy_image_predicor += 1 + # Find the consecutive 500 samples that do not satisfy image_predicate. + # This kv file may cause the dataloader queue to be empty, + # leading to program interruption. Therefore, skip this kv file. + if count_unsatisfy_image_predicor > 500: + count_unsatisfy_image_predicor = 0 + raise RuntimeError("Find invalid kv file, skip!") + continue + else: + count_unsatisfy_image_predicor = 0 + yield bucket, index_file, key, content, image, original_size_as_tuple + + except Exception as ex: + # Error may happen due to network issue when reading from data from this file. + # Skip to the next index file regardless. + print(f"Bucket dataset reading data received unexpected exception at file: {index_file}", ex, file=sys.stderr) + continue + + def get_caption(self, content): + text_key = None + if len(self.caption_keys) == 1: # only one key + res = content.get(self.caption_keys[0], None) + else: # 2 or more keys + for caption_key, skip_ratio in zip(self.caption_keys, self.skip_caption_ratios): + r1 = random.random() + if r1 >= skip_ratio and content.get(caption_key, None) is not None: + text_key = caption_key + break + # if all previous captions are skipped, use the last one (original caption) + if text_key is None: + if self.debug: + print("v1 {} v2 {} use original caption".format(self.caption_keys[0] in content, self.caption_keys[1] in content)) + res = content.get(self.caption_keys[-1], None) + else: + if self.debug: + print("v1 {} v2 {} use {}".format(self.caption_keys[0] in content, self.caption_keys[1] in content, text_key)) + res = content[text_key] + if res is None: + return None + else: + return res["text"] + + @classmethod + def create_dataset_function(cls, hdfs_path, args, **kwargs): + return cls(hdfs_path=hdfs_path, **kwargs) + + +class T2IHDFSDataset_dump(Dataset): + def __init__(self, + hdfs_path, + resolution, + caption_key, + aspect_ratios, + debug=False, + use_resize_random_crop=False, + skip_caption_ratios=[0, 0.0655]): + super().__init__() + ###delete + self.resolution = resolution + self.image_decoder = GeneralImageDecoder() + self.image_predicate = ImageMultiPredicate([ + ImageAestheticPredicate(), + ImageBucketResolutionPredicate(), + ]) + self.image_transform = Compose([ + ToTensor(), + Normalize(mean=0.5, std=0.5), + ]) + self.text_transform = TextCleaner() + self.caption_keys = caption_key + self.debug = debug + self.rank = 0 # mock value + self.use_resize_random_crop = use_resize_random_crop + self.skip_caption_ratios = skip_caption_ratios + + self.buckets = dict() + self.bucket_override = list(map(lambda ratio: (ratio[0], ratio[1]), aspect_ratios.values())) # w, h + if isinstance(hdfs_path, str): + hdfs_path = [hdfs_path] + filepath_list = hlist_files(hdfs_path, postfix=".parquet") + + for filepath in filepath_list: + # Parse name, example: + # filepath: "/laion5b_aesv2_512plus_buckets/2_19_256-896_00002_00196.index" + # filename: "/laion5b_aesv2_512plus_buckets/2_19_256-896_00002_00196" + # basename: "2_19_256-896_00002_00196" + # extension: ".index" + filename, extension = os.path.splitext(filepath) + basename = os.path.basename(filename) + + # Parse basename, example: + # {id}_{image_count}_{image_height}-{image_width}_{other_info} + if 'good' in filename and extension in [".parquet"]: + image_count, image_height, image_width = basename.replace("_", "-").split("-")[2:5] + elif extension in [".parquet"]: + image_count, image_height, image_width = basename.replace("_", "-").split("-")[1:4] + # skip invalid file. + try: + image_count = int(image_count) + image_height = int(image_height) + image_width = int(image_width) + except: + continue + if image_width <=0 or image_height<=0: + continue + + image_ratio = image_width / image_height + override_image_width, override_image_height = self._override_resolution_if_needed_v1(image_width, + image_height) + override_image_ratio = override_image_width / override_image_height + # Omit buckets with unreasonable size ratio, such as (128, 1536) + if override_image_ratio / image_ratio > 1.5 or override_image_ratio / image_ratio < 0.7: + continue + + bucket_key = (override_image_width, override_image_height) + bucket_entry = self.buckets.get(bucket_key, Bucket()) + bucket_entry.index_files.append(filename) + bucket_entry.image_count += image_count + bucket_entry.image_height = override_image_height + bucket_entry.image_width = override_image_width + self.buckets[bucket_key] = bucket_entry + + for i, bucket_entry in enumerate(self.buckets.values()): + print( + f"Bucket {i}: {bucket_entry.image_width}x{bucket_entry.image_height} " + + f"contains {bucket_entry.image_count} images." + ) + print(f"Total samples: {sum([bucket_entry.image_count for bucket_entry in self.buckets.values()])}") + + def _override_resolution_if_needed_v1(self, width: int, height: int) -> Tuple[int, int]: + """ + Override the bucket resolution if configured: + Example: + - bucket override: [(1000, 200), (200, 1000)] + - current resolution: (300, 900) + - return (200, 1000) because it is the closest in aspect ratio. + """ + if self.bucket_override is not None: + # If bucket override is defined, find a new resolution from the override list that best matches the aspect ratio. + assert len(self.bucket_override) > 0, "bucket_override must not be an empty list." + target_aspect_ratio = width / height + bucket_resolutions = self.bucket_override + bucket_aspect_ratios = torch.tensor([w / h for w, h in bucket_resolutions], dtype=torch.float64) + bucket_idx = bucket_aspect_ratios.sub(target_aspect_ratio).abs().argmin().item() + width, height = bucket_resolutions[bucket_idx] + + if self.resolution != 512: + # The buckets are defined in 512 resolution. If target resolution is not 512, we need to scale it and make sure divisible by 64. + ratio = self.resolution / 512 + width = (width * ratio) // 64 * 64 + height = (height * ratio) // 64 * 64 + + return int(width), int(height) + + def __len__(self): + return sum(bucket.image_count for bucket in self.buckets.values()) + + def __iter__(self): + bucket_entries = list(self.buckets.values()) + bucket_weights = list(map(lambda bucket: bucket.image_count, bucket_entries)) + bucket_iterators = list(map(lambda bucket: self._iterate_bucket(bucket), bucket_entries)) + + while True: + try: + bucket_iterator = random.choices(bucket_iterators, bucket_weights)[0] + bucket, content, image, original_size_as_tuple = next(bucket_iterator) + + if self.resolution == 256: + latent = np.frombuffer(content['latent_256'], dtype=np.float32) + latent = latent.reshape(content['latent_256_size']) + latent = torch.from_numpy(latent).to(torch.bfloat16) + if self.resolution == 512: + latent = np.frombuffer(content['latent_512'], dtype=np.float32) + latent = latent.reshape(content['latent_512_size']) + latent = torch.from_numpy(latent).to(torch.bfloat16) + + image, crop_coords_top_left = resize_crop(image, bucket.image_height, + bucket.image_width, self.use_resize_random_crop) + if self.image_transform is not None: + image = self.image_transform(image) + image = image.unsqueeze(0) # Add temporal dim + + # get caption + image_crop_256 = content.get('image_crop_256') + if image_crop_256 is not None: + text = self.get_caption_new(content) + else: + text = self.get_caption(content) + # Skip sample if text returned None. + if text is None: + if self.debug: print("text is None") + continue + + # Transform image and text + if self.text_transform is not None: + text = self.text_transform(text) + if text == "" or text == 'none': + if self.debug: print("text is empty") + continue + + if self.debug: + print(f"dataset loading current text: en is {text}") + + item = dict( + mp4=image, + latent = latent, + txt=text, + num_frames=1 + ) + yield item + except Exception as ex: + raise ex + # Error should not happen here, but we add a guard anyway. + #print(f"Bucket dataset processing sample received unexpected exception at file: {index_file}", ex, + # file=sys.stderr) + continue + + def _iterate_bucket(self, bucket: Bucket): + # Copy the list. + index_files = list(bucket.index_files) + count_unsatisfy_image_predicor = 0 + while True: + # Shuffle files + random.shuffle(index_files) + # Loop through all the .index files + for index_file in index_files: + try: + ##read parquet file + filesystem = fs.HadoopFileSystem('hdfs://harunasg', 0) + index_file = index_file + '.parquet' + with pq.ParquetFile(index_file, filesystem=filesystem) as fr: + # print(f'--- total: {fr.metadata.num_rows} ---- {fr.num_row_groups}') + # keys = [] + # for i in range(fr.num_row_groups): + # # 读取当前的 Row Group + # row_group = fr.read_row_group(i).to_pylist() + # keys += row_group + random_index = random.randint(0, fr.num_row_groups - 1) + keys = fr.read_row_group(random_index).to_pylist() + + # We devide keys to batches then shuffle the batch order. + # Note that keys within a batch are still contiguous for faster data loading. + keys_batches = partition_by_size(keys, 64) + random.shuffle(keys_batches) + + for key_batch in keys_batches: + random.shuffle(key_batch) + + for content in key_batch: + if self.resolution == 256: + latent = content['latent_256'] + else: + latent = content['latent_512'] + if not latent: + count_unsatisfy_image_predicor += 1 + # Find the consecutive 500 samples that do not satisfy image_predicate. + # This kv file may cause the dataloader queue to be empty, + # leading to program interruption. Therefore, skip this kv file. + if count_unsatisfy_image_predicor > 500: + count_unsatisfy_image_predicor = 0 + raise RuntimeError("Find invalid kv file, skip!") + continue + else: + count_unsatisfy_image_predicor = 0 + image = self.image_decoder(content) + original_size_as_tuple = torch.tensor([image.height, image.width]) + + yield bucket, content, image, original_size_as_tuple + + except Exception as ex: + # Error may happen due to network issue when reading from data from this file. + # Skip to the next index file regardless. + print(f"Bucket dataset reading data received unexpected exception at file: {index_file}", ex, file=sys.stderr) + continue + + def get_caption(self, content): + text_key = None + if len(self.caption_keys) == 1: # only one key + res = content.get(self.caption_keys[0], None) + else: # 2 or more keys + for caption_key, skip_ratio in zip(self.caption_keys, self.skip_caption_ratios): + r1 = random.random() + if r1 >= skip_ratio and content.get(caption_key, None) is not None: + text_key = caption_key + break + # if all previous captions are skipped, use the last one (original caption) + if text_key is None: + if self.debug: + print("v1 {} v2 {} use original caption".format(self.caption_keys[0] in content, self.caption_keys[1] in content)) + res = content.get(self.caption_keys[-1], None) + else: + if self.debug: + print("v1 {} v2 {} use {}".format(self.caption_keys[0] in content, self.caption_keys[1] in content, text_key)) + res = content[text_key] + if res is None: + return None + else: + return res + def get_caption_new(self, content): + caption_dict = json.loads(content['caption_dict']) + caption_list = [] + for k, v in caption_dict.items(): + if '_en_' in k and '_text' in k: + caption_list.append(v) + if len(caption_list) == 0: + return None + res = random.choice(caption_list) + return res + + @classmethod + def create_dataset_function(cls, hdfs_path, args, **kwargs): + return cls(hdfs_path=hdfs_path, **kwargs) + + +if __name__ == "__main__": + from omegaconf import OmegaConf + from torch.utils.data import DataLoader + from torch.utils.data.distributed import DistributedSampler + from matplotlib import pyplot as plt + import numpy as np + from training.dataset_tool import CollectionDataset, collate_fn_map + + hdfs_path = "hdfs://harunasg/home/byte_icvg_aigc_cp/user/seed_t2i/kexuanyi/data/train_data/pretrained_data/kv/v2.0/pretrained_en/v2.0_data_512_src_data" + config = "/mnt/bn/icvg/users/minxuan.lin/Workspace/video-factory/config/dataset_config/test_collection_config_sg.yaml" + seed = 0 + + # set seed + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + + configs = OmegaConf.load(config) + train_dataset = CollectionDataset.create_dataset_function(configs['train_data'], + configs['train_data_weights'], + **configs['data']['params']) + # train_dataset = T2IHDFSDataset.create_dataset_function(hdfs_path=hdfs_path, args=None, **configs['data']['params']['dataset_collections']['seedv2-t2i']['params']) + + # sampler = DistributedSampler(train_dataset, rank=rank, num_replicas=world_size,) + train_dataloader = DataLoader( + train_dataset, + batch_size=1, + num_workers=1, + collate_fn=collate_fn_map, + pin_memory=False + ) + + output_dir = "outputs/test1" + os.makedirs(output_dir, exist_ok=True) + + for i, batch in enumerate(train_dataloader): + print(batch.keys()) + print(batch['prompts']) + print(batch['videos'].size()) + print(batch['video_metadata']) + print(torch.min(batch['videos']), torch.max(batch['videos'])) + for j in range(batch['videos'].size()[0]): + plt.imsave(f"{output_dir}/test_{i}_{j}.jpg", ((batch['videos'][j,0,...]+1)*127.5).permute(1,2,0).numpy().astype(np.uint8)) + if i > 20: + break \ No newline at end of file diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__init__.py b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/__init__.cpython-310.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d41cf4f30eb1cca6c01922ee8fa4fb4a58f7b917 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/__init__.cpython-310.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/__init__.cpython-311.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30708724d7a491a5db077f0bfff118c6ce8d1289 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/__init__.cpython-311.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/base_parquet.cpython-310.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/base_parquet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3061b5a8d71f74ce2b4b26337175451ca79a3575 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/base_parquet.cpython-310.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/base_parquet.cpython-311.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/base_parquet.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44d3224dba91aa8999b6786d6e35d3a7a9c3eda7 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/base_parquet.cpython-311.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/parquet_utils.cpython-310.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/parquet_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce7bb00a2d22e5991d7a784f5735aa757458b7d5 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/parquet_utils.cpython-310.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/parquet_utils.cpython-311.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/parquet_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f408de9bf6a918a8702fed622eb018961714b888 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/parquet_utils.cpython-311.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/tos_client.cpython-310.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/tos_client.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe3801649259dbc2071a9e655cc15e1ebb7ff7b7 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/tos_client.cpython-310.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/tos_client.cpython-311.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/tos_client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb2f8fe7834d9bb53fbcbb3f5f0b821dbccfab71 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/tos_client.cpython-311.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/video_parquet.cpython-310.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/video_parquet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7ab4bc5e4fe9c3925411f23cc63343515e4438d Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/video_parquet.cpython-310.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/video_parquet.cpython-311.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/video_parquet.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64f246208641ad5ef5a0b17781cda26b91718f3a Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/__pycache__/video_parquet.cpython-311.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/base_parquet.py b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/base_parquet.py new file mode 100644 index 0000000000000000000000000000000000000000..62508fa4f25b2dcb519c5f8cf1e7754928c6ead9 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/base_parquet.py @@ -0,0 +1,289 @@ +from itertools import chain +from multiprocessing import Pool +from pyarrow.parquet import ParquetFile +from torch.utils.data import IterableDataset +from typing import List, Literal, Optional, Union +from pyarrow.fs import HadoopFileSystem, LocalFileSystem + +from .utils.hdfs_utils import listdir_with_metafile, exists +from .parquet_utils import ( + get_portion_for_worker_only, + get_random_for_rank_and_worker, + get_portion_for_rank_and_worker, +) + +def hack_s_data(filepath): + if "vae-1011" in filepath: + return filepath.replace("byte_data_tt_m/VGFM/data/packed/vae-1011", "byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011") + elif "dit-1126" in filepath: + return filepath.replace("byte_data_tt_m/user/sheng.bi/vgfm/packed/dit-1126", "byte_icvg_aigc_cp/user/video/temp/19900101/dit-1126") + else: + return filepath + +def get_filesystem(path: str) -> Union[LocalFileSystem, HadoopFileSystem]: + """ + Get filesystem based on the path. + """ + if path.startswith("hdfs://"): + return HadoopFileSystem.from_uri(path) + else: + return LocalFileSystem() + + +def read_metadata( + path: str, +): + fs = get_filesystem(path) + with ParquetFile(path, filesystem=fs) as file: + metadata = file.metadata + return metadata + + +class ParquetDataset(IterableDataset): + """ + Parquet dataset. + + Arguments: + path: a directory path that contains *.parquet files. + seed: seed for deterministic sampling. If None, just random. + partition: partition strategy. Split by *.parquet file or by row groups in each file. + force_partition: if True, raise error if partition is indivisible. + num_parallel_files: number of parallel files to read. + infinite: If True, data will be returned infinitely. + """ + + def __init__( + self, + path: Union[str, List[str]], + seed: Optional[int], + partition: Literal["file", "group", "dump"] = "file", + force_partition: bool = False, + num_parallel_files: int = 8, + infinite: bool = True, + path_mode: Literal["dir", "file"] = "dir", + shuffle: bool = True, + columns: Optional[List[str]] = None, + plugin_caption_path="", + dump_path = "", + ): + assert partition in ["file", "group", "dump"] + assert path_mode in ["dir", "file"] + + # Save settings. + self.seed = seed + self.infinite = infinite + self.partition = partition + self.force_partition = force_partition + self.num_parallel_files = num_parallel_files + self.shuffle = shuffle + self.columns = columns + + # List file paths. + filepaths = path if isinstance(path, list) else [path] + if path_mode == "dir": + filepaths = map(listdir_with_metafile, filepaths) + filepaths = chain(*filepaths) + filepaths = filter(lambda path: path.endswith(".parquet"), filepaths) + filepaths = [hack_s_data(path) for path in filepaths] + filepaths = sorted(filepaths) + assert len(filepaths) > 0 + + # Create file readers. + self.filereaders = [ + ParquetFileReader( + path=path, + seed=seed, + partition=partition, + force_partition=force_partition, + shuffle=shuffle, + columns=columns, + plugin_caption_path=plugin_caption_path.rstrip( + '/')+"/"+path.split('/')[-1] if plugin_caption_path != "" else "", + dump_path = dump_path.rstrip( + '/')+"/"+path.split('/')[-1] if dump_path != "" else "", + ) + for path in filepaths + ] + + # Please don't use a fake __len__(self)! Try making other functions e.g. get_size() instead. + def __len__(self): + if not hasattr(self, "count"): + # Calculate an approximate dataset item count. + # We open 5 files and compute the average items per file. + # Then we use this to approximate total dataset item count. + + with Pool(1) as pool: + counts = pool.map(len, self.filereaders[:5]) + self.count = int(sum(counts) / len(counts) * len(self.filereaders)) + return self.count + + def __iter__(self): + epoch = 0 + filereaders = self.filereaders + random = get_random_for_rank_and_worker(self.seed) + + # Partition by files if needed. + if self.partition == "file": + filereaders = get_portion_for_rank_and_worker( + filereaders, self.force_partition) + + while True: + # Initialize filereaders iterators. + if len(filereaders) == 0: + filereaders = get_portion_for_rank_and_worker( + self.filereaders, self.force_partition, resample = True) + iterators = [reader.__iter__(epoch=epoch) + for reader in filereaders] + if self.shuffle: + random.shuffle(iterators) + + # Yield samples. + bad_file_count = 0 + max_bad_file_count = len(iterators) + while any(iterators): + if self.shuffle: + iterator = random.choice( + iterators[: self.num_parallel_files]) + else: + iterator = iterators[0] + try: + result = next(iterator) + if result == "invalid parquet file!": + print("encounter data-caption file problem, removing iterator") + iterators.remove(iterator) + bad_file_count += 1 + if bad_file_count >= max_bad_file_count: + bad_file_count = 0 + yield "max_bad_file_count_reached" + continue + else: + yield result + except StopIteration: + iterators.remove(iterator) + + # Break after the first epoch if not infinite. + if not self.infinite: + break + + # Increment epoch. + epoch += 1 + + +class ParquetFileReader: + """ + Read a single *.parquet file. + + Arguments: + path: a *.parquet file path. + seed: seed for deterministic sampling. If None, just random. + partition: partition strategy. + force_partition: if True, raise error if partition is indivisible. + """ + + def __init__( + self, + path: str, + seed: Optional[int], + partition: bool, + force_partition: bool, + shuffle: bool, + columns: Optional[List[str]], + plugin_caption_path: str, + dump_path: str, + ): + self.path = path + self.seed = seed + self.partition = partition + self.force_partition = force_partition + self.shuffle = shuffle + self.columns = columns + self.plugin_caption_path = plugin_caption_path + self.dump_path = dump_path + + def __len__(self): + fs = get_filesystem(self.path) + with ParquetFile(self.path, filesystem=fs) as file: + return file.metadata.num_rows + + def __iter_parallel(self, epoch): + fs = get_filesystem(self.path) + print(self.path) + if not exists(self.path) or not exists(self.plugin_caption_path) or not exists(self.dump_path): + # return and make the iter empty + print(f"parallel loading warning: {self.path} or {self.plugin_caption_path} not exists, return empty iter") + yield "invalid parquet file!" + with ParquetFile(self.path, filesystem=fs) as file, \ + ParquetFile(self.plugin_caption_path, filesystem=fs) as plugin_caption, \ + ParquetFile(self.dump_path, filesystem=fs) as dump_file: + # List all groups. + groups = list(range(file.num_row_groups)) + + # Partition groups if needed. + if self.partition == "group": + groups = get_portion_for_rank_and_worker( + groups, self.force_partition) + elif self.partition == "dump": + groups = get_portion_for_worker_only(groups) + + if self.shuffle: + # Shuffle groups + seed = (self.seed + epoch) if self.seed is not None else None + get_random_for_rank_and_worker(seed).shuffle(groups) + + # Iteration over all samples from all row groups. + for group in groups: + print(group) + iter_main = file.iter_batches( + batch_size=1, row_groups=[group], columns=self.columns, + use_threads=False,) + iter_plugin_caption = plugin_caption.iter_batches( + batch_size=1, row_groups=[group], columns=None, + use_threads=False,) + iter_dump = dump_file.iter_batches( + batch_size=1, row_groups=[group], columns=None, + use_threads=False,) + + # Zip the two iterators to read rows "in parallel" + for main_batch, caption_batch, dump_batch in zip(iter_main, iter_plugin_caption, iter_dump): + # Convert each single-row batch to a dict + main_batch_dict = main_batch.to_pandas().iloc[0].to_dict() + caption_batch_dict = caption_batch.to_pandas( + ).iloc[0].to_dict() + dump_batch_dict = dump_batch.to_pandas().iloc[0].to_dict() + assert caption_batch_dict['uttid'] == main_batch_dict[ + 'uttid'] and caption_batch_dict['uttid'] == dump_batch_dict['uttid'], f"uttid not match {caption_batch_dict['uttid']} vs {main_batch_dict['uttid']}" + main_batch_dict.update(caption_batch_dict) + main_batch_dict.update(dump_batch_dict) + yield main_batch_dict + + def __iter_normal(self, epoch): + fs = get_filesystem(self.path) + with ParquetFile(self.path, filesystem=fs) as file: + # List all groups. + groups = list(range(file.num_row_groups)) + + # Partition groups if needed. + if self.partition == "group": + groups = get_portion_for_rank_and_worker( + groups, self.force_partition) + elif self.partition == "dump": + groups = get_portion_for_worker_only(groups) + + if self.shuffle: + # Shuffle groups + seed = (self.seed + epoch) if self.seed is not None else None + get_random_for_rank_and_worker(seed).shuffle(groups) + + # Iteration over all samples from all row groups. + for group in groups: + for sample in file.iter_batches( + batch_size=1, row_groups=[group], columns=self.columns, + use_threads=False, + ): + yield sample.to_pandas().iloc[0].to_dict() + + def __iter__(self, epoch=0): + if self.plugin_caption_path != "": + return self.__iter_parallel(epoch) + else: + return self.__iter_normal(epoch) \ No newline at end of file diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/parquet_utils.py b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/parquet_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4d0d3f95647180e25d7101ac1bd41598728c23ce --- /dev/null +++ b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/parquet_utils.py @@ -0,0 +1,142 @@ +import torch +import random +import importlib +import contextlib +import numpy as np + +from typing import Any, Dict, List, Optional +from torch.utils.data import get_worker_info +from omegaconf import DictConfig, ListConfig + +from .utils.partition_utils import partition_by_groups +from .utils.distributed_utils import get_data_parallel_rank, get_data_parallel_world_size + + +def get_worker_id() -> int: + """ + Get the current dataloader worker id. + """ + return get_worker_info().id if get_worker_info() is not None else 0 + + +def get_worker_count() -> int: + """ + Get the total dataloader worker count. + """ + return get_worker_info().num_workers if get_worker_info() is not None else 1 + + +def get_seed_for_rank_and_worker(seed: Optional[int]) -> Optional[int]: + """ + Get seed for current rank and worker. + """ + if seed is None: + return None + return seed + get_data_parallel_rank() * get_worker_count() + get_worker_id() + + +def get_random_for_rank_and_worker(seed: Optional[int]) -> random.Random: + """ + Get random.Random for the current rank and worker. + """ + return random.Random(get_seed_for_rank_and_worker(seed)) + + +def get_random_for_all_ranks(seed: Optional[int]) -> random.Random: + """ + Get random.Random that is the same for all ranks. + """ + return random.Random(seed or 0) + + +def get_portion_for_rank_and_worker(items: List[Any], force: bool = False, allow_empty: bool = False, resample: bool = False) -> List[Any]: + """ + Get the portion of items for current rank and worker. + """ + rank = get_data_parallel_rank() + world_size = get_data_parallel_world_size() + worker_id = get_worker_id() + worker_count = get_worker_count() + if resample: + return random.sample(items, len(items)//(world_size*worker_count)) + + if world_size * worker_count <= len(items): + # If there are enough items to be divided, we divide the items + items = partition_by_groups(items, world_size)[rank] + items = partition_by_groups(items, worker_count)[worker_id] + elif allow_empty: + if rank * worker_count + worker_id < len(items): + items = [items[rank * worker_count + worker_id]] + else: + items = [] + elif not force: + # If not enough items to be divided, all ranks and workers shuffle it + # with different seed. + items = list(items) + get_random_for_rank_and_worker(0).shuffle(items) + else: + raise ValueError("Items not divisible by world_size * worker_count") + return items + + +def get_portion_for_worker_only(items: List[Any]) -> List[Any]: + """ + Get the portion of items for current worker. + """ + worker_id = get_worker_id() + worker_count = get_worker_count() + + items = partition_by_groups(items, worker_count)[worker_id] + return items + + +@contextlib.contextmanager +def local_seed(seed: Optional[int]): + """ + Create a local context with seed is set, but exit back to the original random state. + If seed is None, do nothing. + """ + if seed is not None: + random_state = random.getstate() + np_state = np.random.get_state() + torch_state = torch.get_rng_state() + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + try: + yield + finally: + random.setstate(random_state) + np.random.set_state(np_state) + torch.set_rng_state(torch_state) + else: + yield + + +def _as_list(datasets): + if isinstance(datasets, list): + return datasets + if isinstance(datasets, dict): + return [d for d in datasets.values() if d is not None] + raise ValueError + + +def import_item(path: str, name: str) -> Any: + """ + Import a python item. Example: import_item("path.to.file", "MyClass") -> MyClass + """ + return getattr(importlib.import_module(path), name) + + +def create_dataset(path: str, *args, **kwargs) -> Any: + """ + Create a dataset. Requires the file to contain a "create_dataset" function. + """ + return import_item(path, "create_dataset")(*args, **kwargs) + + +def shift_seed(seed: Optional[int], shift: int) -> Optional[int]: + """ + Shift the seed by a given amount. Or return None if seed is None. + """ + return (seed + shift) if seed is not None else None diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__init__.py b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/__init__.cpython-310.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4618f213f6e4de3d119b9eb574660370511a0c00 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/__init__.cpython-310.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/__init__.cpython-311.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8965922df2076494dd79020455df6b56a49fd899 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/__init__.cpython-311.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/frame_sampler.cpython-310.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/frame_sampler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe95cb4fdd60db37f227dc7ef77946a6902dfd9d Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/frame_sampler.cpython-310.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/frame_sampler.cpython-311.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/frame_sampler.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8375f140466255079323c573c87b0de2d45c91e2 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/frame_sampler.cpython-311.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/text_sampler.cpython-310.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/text_sampler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6949c46d89ec8f922a253e8e9265b3c19cb56412 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/text_sampler.cpython-310.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/text_sampler.cpython-311.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/text_sampler.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a6ce255b9c95e04d4691d580a4c9d18f2e78a59 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/text_sampler.cpython-311.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/utils.cpython-310.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d92d7010eb4fbff6568329e5b9a6d0e58b66b97 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/utils.cpython-310.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/utils.cpython-311.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d131433646fd10b667f4a589a938f9f58dcce06a Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/__pycache__/utils.cpython-311.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/frame_sampler.py b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/frame_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..8a785c269c1efe8b8f4e19fee863d68020851753 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/frame_sampler.py @@ -0,0 +1,375 @@ +""" +Frame samplers. +""" + +import numpy as np + +from dataclasses import dataclass +from abc import ABC, abstractmethod +from typing import Any, Dict, List, Literal, NamedTuple, Optional, Tuple, Union + + +class FrameSamplerOutput(NamedTuple): + """ + Return indices for frame decoding, + and optionally additional information to return to user. + """ + + indices: List[int] + additional_info: Dict[str, Any] = {} + + +class FrameSampler(ABC): + """ + Frame sampler base class. + + Child class must implement __call__ method to return the decoding indices. + Or raise if the video cannot be sampled (e.g. too short, etc.) + """ + + @abstractmethod + def __call__(self, num_frames: int) -> FrameSamplerOutput: + raise NotImplementedError + + +class AllFrameSampler(FrameSampler): + """ + All frame sampler. Returns all frames in a video. + """ + + def __call__(self, num_frames: int) -> FrameSamplerOutput: + return FrameSamplerOutput(list(range(num_frames))) + + +class AdaptiveFrameSampler(FrameSampler): + """ + Adaptive frame sampler. + + Arguments: + length: frame length to return. + For example, [5,10] denotes to always return 5 frames or 10 frames. + It will choose the longest length that fits the original video. + For example, if the video is 9 frames total, it will clip to 5 frames. + stride: frame skip. + For example, 1 denotes no skip. 2 denotes select every other frame. 3 + denotes select every third frame. When a list is given, stride is randomly + chosen with even probability. However, user may set it to [1,1,2] to + denote 1 with 66% probability and 2 with 33% proability. + clip: clip location. + "center": clip video at the center. + "uniform": clip video uniformly at random. + jitter: jitter to the location. + Only applicable when clip is "center". + The value is the stdev of the normal distribution to shift the index. + """ + + def __init__( + self, + lengths: Union[int, List[int]], + strides: Union[int, List[int]] = 1, + clip: Literal["center", "uniform"] = "uniform", + jitter: float = 0.0, + ): + lengths = [lengths] if isinstance(lengths, int) else lengths + strides = [strides] if isinstance(strides, int) else strides + assert len(lengths) > 0 + assert len(strides) > 0 + assert clip in ["center", "uniform"] + assert jitter >= 0 + self.lengths = np.array(lengths) + self.strides = np.array(strides) + self.clip = clip + self.jitter = jitter + + def __call__( + self, + num_frames: int, + ) -> FrameSamplerOutput: + # Choose stride. + # Drop strides that are too long for this video. + # Then randomly choose a valid stride. + valid_strides = np.any(num_frames // self.strides >= + self.lengths.reshape(-1, 1), axis=0) + valid_strides = self.strides[valid_strides] + if valid_strides.size <= 0: + raise ValueError(f"Video is too short ({num_frames} frames).") + stride = np.random.choice(valid_strides) + + # Choose length. + # Pick the max length that can fit the video under the current stride. + valid_lengths = self.lengths[num_frames // stride >= self.lengths] + length = np.max(valid_lengths) + + # Choose start index. + min_start_index = 0 + max_start_index = num_frames - 1 - stride * (length - 1) + mid_start_index = round((min_start_index + max_start_index) / 2) + jitter = round(np.random.normal(loc=0, scale=self.jitter)) + + if self.clip == "center": + start_index = mid_start_index + jitter + elif self.clip == "uniform": + start_index = np.random.randint( + min_start_index, max_start_index + 1) + else: + raise NotImplementedError + + start_index = np.clip(start_index, min_start_index, max_start_index) + + # Compute indices + indices = np.arange(start_index, start_index + length * stride, stride) + + # Return indices and additional information to return to user. + return FrameSamplerOutput( + indices=indices.tolist(), + additional_info={ + "stride": stride, + "start_frame": start_index, + "end_frame": start_index + length * stride, + "total_frames": num_frames, + }, + ) + + +@dataclass +class AdaptiveAdvancedFrameSamplerStrategy: + stride: int + stride_prob: float + frame_lengths: List[int] + frame_lengths_prob: Union[Literal["uniform", "harmonic"], List[float]] + + +class AdaptiveAdvancedFrameSampler(FrameSampler): + """ + Advanced adaptive frame sampler supports different frame lengths for different strides, + and supports probabilistic sampling of both the stride and the frame length. + + strategies: A list of strategies to sample from. + clip: clip location. + "center": clip video at the center. + "uniform": clip video uniformly at random. + jitter: jitter to the location. + Only applicable when clip is "center". + The value is the stdev of the normal distribution to shift the index. + """ + + def __init__( + self, + strategies: List[AdaptiveAdvancedFrameSamplerStrategy], + clip: Literal["center", "uniform","simple"] = "uniform", + jitter: float = 0.0, + aligned: bool = False, + ): + assert len(strategies) > 0, "Strategies must not be empty" + assert len({s.stride for s in strategies}) == len( + strategies), "Strides cannot duplicate." + assert clip in ["center", "uniform","simple"] + assert jitter >= 0 + self.aligned = aligned + self.clip = clip + self.jitter = jitter + self.strides = [] + self.strides_prob = [] + self.frame_lengths = [] + self.frame_lengths_prob = [] + + for strategy in sorted(strategies, key=lambda s: s.stride): + # Validate strides. + assert isinstance( + strategy.stride, int), "Stride must be an integer." + assert strategy.stride > 0, "Stride must be a positive integer." + self.strides.append(strategy.stride) + + # Assign strides_prob. + assert isinstance(strategy.stride_prob, (int, float) + ), "Stride prob is not int/float." + assert strategy.stride_prob >= 0, "Stride prob must be non-negative." + self.strides_prob.append(strategy.stride_prob) + + # Assign frame lengths, sort by value. + assert len( + strategy.frame_lengths) > 0, "Frame lengths must not be empty." + frame_lengths = np.array(strategy.frame_lengths) + assert frame_lengths.dtype == int, "Frame lengths must be integers." + assert np.all(frame_lengths > + 0), "Frame lengths must be positive integers." + frame_lengths_sorted_idx = np.argsort(frame_lengths) + frame_lengths = frame_lengths[frame_lengths_sorted_idx] + self.frame_lengths.append(frame_lengths) + + # Assign frame lengths prob, apply the sorting to prob as well. + if strategy.frame_lengths_prob == "uniform": + # e.g. [0.2, 0.2, 0.2, 0.2, 0.2] + frame_lengths_prob = np.full( + len(frame_lengths), 1.0 / len(frame_lengths)) + elif strategy.frame_lengths_prob == "harmonic": + # e.g. [0.2, 0.25, 0.33, 0.5, 1] + frame_lengths_prob = np.flip( + 1 / np.arange(1, len(frame_lengths) + 1)) + elif isinstance(strategy.frame_lengths_prob, list): + frame_lengths_prob = np.array(strategy.frame_lengths_prob) + frame_lengths_prob = frame_lengths_prob[frame_lengths_sorted_idx] + else: + raise NotImplementedError + assert len(frame_lengths_prob) == len( + frame_lengths), "Frame lengths prob mismatch." + assert np.all(frame_lengths_prob >= + 0), "Frame lengths prob must not be negative." + assert frame_lengths_prob.sum() > 0, "Frame lengths prob must not be all zeros." + frame_lengths_prob /= frame_lengths_prob.sum() + self.frame_lengths_prob.append(frame_lengths_prob) + + self.strides = np.array(self.strides) + self.strides_prob = np.array(self.strides_prob) + assert self.strides_prob.sum() > 0, "Strides prob must not be all zeros." + self.strides_prob /= self.strides_prob.sum() + + def __call__(self, num_frames: int, frames_meta=None): + global_start_idx, global_end_idx = 0, num_frames + if self.aligned: + assert frames_meta is not None + global_start_idx = frames_meta['start_idxs'] + global_end_idx = frames_meta['end_idxs'] + num_frames = global_end_idx - global_start_idx + + if self.clip != 'simple': + sample_result = adptive_sample_framelen_and_stride( + num_frames=num_frames, + strides=self.strides, + strides_prob=self.strides_prob, + frame_lengths=self.frame_lengths, + frame_lengths_prob=self.frame_lengths_prob, + ) + + stride = sample_result["stride"] + length = sample_result["frame_length"] + else: + stride = self.strides[0] + length = self.frame_lengths[0][0] + + # Choose start index. + min_start_index = 0 + max_start_index = num_frames - 1 - stride * (length - 1) + mid_start_index = round((min_start_index + max_start_index) / 2) + jitter = round(np.random.normal(loc=0, scale=self.jitter)) + + if self.clip == 'simple': + start_index = global_start_idx + ## can only load dump data, will fix further + # if self.clip == "center": + # start_index = mid_start_index + jitter + # elif self.clip == "uniform": + # start_index = np.random.randint( + # min_start_index, max_start_index + 1) + # else: + # raise NotImplementedError + # else: + # start_index += global_start_idx + # min_start_index += global_start_idx + # max_start_index += global_start_idx + # start_index = np.clip(start_index, min_start_index, max_start_index) + + # Compute indices + indices = np.arange(start_index, start_index + length * stride, stride) + + # Return indices and additional information to return to user. + return FrameSamplerOutput( + indices=indices.tolist(), + additional_info={ + "stride": stride, + "start_frame": start_index, + "end_frame": start_index + length * stride, + "total_frames": num_frames, + }, + ) + + +def normalize_probabilities( + items: np.ndarray, + probs: np.ndarray, + masks: np.ndarray, +) -> Tuple[np.ndarray, np.ndarray]: + assert len(items), "Items must not be empty." + assert len(items) == len(masks) == len(probs), "Lengths must match." + assert isinstance(items, np.ndarray), "Items must be an np.ndarray." + assert isinstance(probs, np.ndarray), "Probs must be an np.ndarray." + assert isinstance(masks, np.ndarray), "Masks must be an np.ndarray." + assert masks.dtype == bool, "Masks must be boolean." + assert np.any(masks), "Masks must not be all False." + assert np.all(np.diff(masks.astype("int")) <= + 0), "Masks must not break monotonicity." + + ret_items = items[masks] + ret_probs = probs[masks] + + # Accumulate the probabilities of infeasible items to the last feasible one. + ret_probs[-1] += probs[~masks].sum() + + return ret_items, ret_probs + + +def adptive_sample_framelen_and_stride( + num_frames: int, + strides: np.ndarray, + strides_prob: np.ndarray, + frame_lengths: List[np.ndarray], + frame_lengths_prob: List[Optional[np.ndarray]], +) -> Dict[str, Any]: + """Adaptively sample frame length and stride for a video. + + Args: + num_frames: Number of frames in the current video. + strides: A list of strides. + strides_prob: The probability for each stride. + frame_lengths: The number of frames (sorted) to sample from at the current stride. + For example, `frame_length=10` at `stride=2` means that we need to have 20 frames. + When the number of frames to sample is infeasible, it will select the feasible frame + lengths and re-normalize the probability according to the feasible frames at hand. + For example, if `num_frames=10`, `frame_lengths[stride2]=[4, 5]`, + `frame_lengths[stride3]=[1, 3, 5]`, we can sample frame lengths 1, 2, and 5 at + `stride=2` (2, 4, and 10 frames) but only frame lengths 1, 3 at `stride=3`. In this + case, we will add the probability of `frame_length=5` at `stride=3` to `frame_length=3` + at `stride=3`, making it more likely to be selected. + frame_lengths_prob: The frame probabilities to sample from the corresponding frame lengths. + Defaults to None for uniform sampling. + Returns: + dictionary: A dictionary containing the selected frames and strides. if none is feasible, + it will raise an exception. + """ + assert len(strides) == len(strides_prob) == len( + frame_lengths) == len(frame_lengths_prob) + + # Prepare frame_lengths_mask for each stride. + frame_lengths_mask = [num_frames // s >= + l for s, l in zip(strides, frame_lengths)] + + # Prepare stride mask and prob. + strides_idxs = np.arange(len(strides)) + strides_mask = np.array([np.any(mask) for mask in frame_lengths_mask]) + assert np.any(strides_mask), ( + f"Cannot sample frames={num_frames} " + + f"from strides={strides} and lengths={frame_lengths}" + ) + + # Drop infeasible strides and normalize probability. + strides_idxs, strides_prob = normalize_probabilities( + strides_idxs, strides_prob, strides_mask) + + # Choose stride. + stride_idx = np.random.choice(strides_idxs, p=strides_prob) + stride = strides[stride_idx] + + # Prepare frame_lengths mask and prob for the current stride. + lengths = frame_lengths[stride_idx] + lengths_mask = frame_lengths_mask[stride_idx] + lengths_prob = frame_lengths_prob[stride_idx] + if lengths_prob is None: + lengths_prob = np.full(len(lengths), 1.0 / len(lengths)) + + # Drop infeasible lengths and normalize probability. + lengths, lengths_prob = normalize_probabilities( + lengths, lengths_prob, lengths_mask) + + # Choose frame length. + length = np.random.choice(lengths, p=lengths_prob) + return dict(stride=stride, frame_length=length) diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/text_sampler.py b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/text_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..4c329ccf4ae40ee5178de910e916504bff464269 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/text_sampler.py @@ -0,0 +1,332 @@ +""" +Text samplers. +""" + +from bs4 import BeautifulSoup +import urllib.parse as ul +import html +import ftfy +import re +import numpy as np + +from abc import ABC, abstractmethod +from typing import Dict, List, NamedTuple, Union + + +class TextSamplerOutput(NamedTuple): + """ + Return keys for text embedding, + and optionally additional information to return to user. + """ + + keys: Union[str, List[str]] + + +class TextSampler(ABC): + """ + Text sampler base class. + + Child class must implement __call__ method to return the embedding keys. + Or raise if the text cannot be sampled (key does not exist.) + """ + + @abstractmethod + def __call__(self, text: Dict[str, str]) -> TextSamplerOutput: + raise NotImplementedError + + +class TextAllSampler(TextSampler): + """ + All text sampler. Returns all texts. + + e.g. + text_sampler: + type: all + """ + + def __init__( + self, + all: List[str] = None, + **kwargs, + ): + self.all = all + + def __call__(self, text: Dict[str, str]) -> TextSamplerOutput: + assert len(text) > 0, "The input text does not exist." + + # Get keys. + keys = list(text.keys()) + + if self.all is not None: + keys = [key for key in self.all if key in keys] + assert len( + keys) > 0, f"No valid text sample found under keys: {text.keys()}." + + return TextSamplerOutput(keys=keys) + + +class TextFrequencySampler(TextSampler): + """ + Sample text based on frequency. + + e.g. + text_sampler: + type: frequency + frequency: + no_title_qwen_caption_en_v2_text: 0.9 + no_title_qwen_caption_en_text: 0.9 + origin_caption: 0.1 + + # support regular expression + ----- + .+qwen_caption_en.+: 0.95 + origin_caption: 0.05 + ----- + .+caption_qwen_recaption_cn_long_2_82_text: 0.9 + .+caption_qwen_recaption_cn_2_95_text: 0.9 + origin_caption: 0.1 + ----- + """ + + def __init__( + self, + frequency: Dict[str, float] = {}, + ): + self.frequency = frequency + # Get regular expression. + self.patterns = ( + {k: re.compile(k) for k in frequency.keys() + } if frequency is not None else None + ) + + def __call__(self, text: Dict[str, str]) -> TextSamplerOutput: + + assert len(text) > 0, "The input text does not exist." + + # Get keys. + keys = list(text.keys()) + + # Get weights. + if self.frequency is None or len(self.frequency) == 0: + weights = np.array([1.0] * len(keys)) + else: + matchs = {k: (False, "") for k in text.keys()} + counter = {k: 0 for k in self.frequency.keys()} + for k in keys: + for pstr, pat in self.patterns.items(): + if pat.match(k) is not None: + matchs[k] = (True, pstr) + counter[pstr] += 1 + break + weights = np.array( + [ + self.frequency[matchs[k][1]] / + counter[matchs[k][1]] if matchs[k][0] else 0.0 + for k in keys + ] + ) + weights_sum = weights.sum() + assert weights_sum > 0, f"No valid text sample found under keys: {keys}." + weights /= weights_sum + + # Sample key. + keys = str(np.random.choice(keys, p=weights)) + return TextSamplerOutput(keys=keys) + + +class TextPrioritySampler(TextSampler): + """ + Sample text based on priority. + + e.g. + text_sampler: + type: priority + priority: + - no_title_qwen_caption_en_v2_text + - no_title_qwen_caption_en_text + - origin_caption + """ + + def __init__( + self, + priority: List[str] = [], + ): + self.priority = priority + + def __call__(self, text: Dict[str, str]) -> TextSamplerOutput: + + assert len(text) > 0, "The input text does not exist." + + # Get keys. + keys = list(text.keys()) + + # Get priorities. + priorities = [key for key in self.priority if key in keys] + + # Select key. + if priorities: + keys = priorities[0] + else: + keys = str(np.random.choice(keys)) + + return TextSamplerOutput(keys=keys) + + +""" +Text cleaner. Copied from DeepFloyd IF. +(https://github.com/deep-floyd/IF/blob/develop/deepfloyd_if/modules/t5.py#L125) +""" + + +class TextCleaner: + """ + Clear up a caption with strange/improper contents + """ + + bad_punct_regex = re.compile( + r"[" + + "#®•©™&@·º½¾¿¡§~" + + r"\)" + + r"\(" + + r"\]" + + r"\[" + + r"\}" + + r"\{" + + r"\|" + + "\\" + + r"\/" + + r"\*" + + r"]{1,}" + ) + + def __call__(self, text): + # The exact text cleaning as was in the training stage: + text = self.clean_caption(text) + text = self.clean_caption(text) + return text + + @staticmethod + def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + def clean_caption(self, caption): + caption = str(caption) + caption = ul.unquote_plus(caption) + caption = caption.strip().lower() + caption = re.sub("", "person", caption) + caption = re.sub("
", " ", caption) + # urls: + caption = re.sub( + r"\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa: E501 + "", + caption, + ) # regex for urls + caption = re.sub( + r"\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa: E501 + "", + caption, + ) # regex for urls + # html: + caption = BeautifulSoup(caption, features="html.parser").text + + # @ + caption = re.sub(r"@[\w\d]+\b", "", caption) + + # 31C0—31EF CJK Strokes + # 31F0—31FF Katakana Phonetic Extensions + # 3200—32FF Enclosed CJK Letters and Months + # 3300—33FF CJK Compatibility + # 3400—4DBF CJK Unified Ideographs Extension A + # 4DC0—4DFF Yijing Hexagram Symbols + # 4E00—9FFF CJK Unified Ideographs + caption = re.sub(r"[\u31c0-\u31ef]+", "", caption) + caption = re.sub(r"[\u31f0-\u31ff]+", "", caption) + caption = re.sub(r"[\u3200-\u32ff]+", "", caption) + caption = re.sub(r"[\u3300-\u33ff]+", "", caption) + caption = re.sub(r"[\u3400-\u4dbf]+", "", caption) + caption = re.sub(r"[\u4dc0-\u4dff]+", "", caption) + caption = re.sub(r"[\u4e00-\u9fff]+", "", caption) + ####################################################### + + # все виды тире / all types of dash --> "-" + caption = re.sub( + r"[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+", # noqa: E501 + # noqa + "-", + caption, + ) + + # кавычки к одному стандарту + caption = re.sub(r"[`´«»“”¨]", '"', caption) + caption = re.sub(r"[‘’]", "'", caption) + + # " + caption = re.sub(r""?", "", caption) + # & + caption = re.sub(r"&", "", caption) + + # ip adresses: + caption = re.sub(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", " ", caption) + + # article ids: + caption = re.sub(r"\d:\d\d\s+$", "", caption) + + # \n + caption = re.sub(r"\\n", " ", caption) + + # "#123" + caption = re.sub(r"#\d{1,3}\b", "", caption) + # "#12345.." + caption = re.sub(r"#\d{5,}\b", "", caption) + # "123456.." + caption = re.sub(r"\b\d{6,}\b", "", caption) + # filenames: + caption = re.sub( + r"[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)", "", caption) + + # + caption = re.sub(r"[\"\']{2,}", r'"', caption) # """AUSVERKAUFT""" + caption = re.sub(r"[\.]{2,}", r" ", caption) # """AUSVERKAUFT""" + + # ***AUSVERKAUFT***, #AUSVERKAUFT + caption = re.sub(self.bad_punct_regex, r" ", caption) + caption = re.sub(r"\s+\.\s+", r" ", caption) # " . " + + # this-is-my-cute-cat / this_is_my_cute_cat + regex2 = re.compile(r"(?:\-|\_)") + if len(re.findall(regex2, caption)) > 3: + caption = re.sub(regex2, " ", caption) + + caption = self.basic_clean(caption) + + caption = re.sub(r"\b[a-zA-Z]{1,3}\d{3,15}\b", "", caption) # jc6640 + caption = re.sub(r"\b[a-zA-Z]+\d+[a-zA-Z]+\b", "", caption) # jc6640vc + caption = re.sub(r"\b\d+[a-zA-Z]+\d+\b", "", caption) # 6640vc231 + + caption = re.sub(r"(worldwide\s+)?(free\s+)?shipping", "", caption) + caption = re.sub(r"(free\s)?download(\sfree)?", "", caption) + caption = re.sub(r"\bclick\b\s(?:for|on)\s\w+", "", caption) + caption = re.sub( + r"\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?", "", caption) + caption = re.sub(r"\bpage\s+\d+\b", "", caption) + + # j2d1a2a... + caption = re.sub( + r"\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\b", r" ", caption) + + caption = re.sub(r"\b\d+\.?\d*[xх×]\d+\.?\d*\b", "", caption) + + caption = re.sub(r"\b\s+\:\s+", r": ", caption) + caption = re.sub(r"(\D[,\./])\b", r"\1 ", caption) + caption = re.sub(r"\s+", " ", caption) + + caption.strip() + + caption = re.sub(r"^[\"\']([\w\W]+)[\"\']$", r"\1", caption) + caption = re.sub(r"^[\'\_,\-\:;]", r"", caption) + caption = re.sub(r"[\'\_,\-\:\-\+]$", r"", caption) + caption = re.sub(r"^\.\S+$", "", caption) + + return caption.strip() diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/utils.py b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ca63b1f10f30dba74fd7b7ab995016b4b22e6e35 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/samplers/utils.py @@ -0,0 +1,42 @@ +from omegaconf import DictConfig, OmegaConf + +from .text_sampler import (TextAllSampler, + TextFrequencySampler, + TextPrioritySampler, + TextSampler, + ) +from .frame_sampler import (AdaptiveAdvancedFrameSampler, + AdaptiveAdvancedFrameSamplerStrategy, + AdaptiveFrameSampler, + AllFrameSampler, + FrameSampler, + ) + +TEXT_SAMPLER_TYPES = { + "all": TextAllSampler, + "frequency": TextFrequencySampler, + "priority": TextPrioritySampler, +} + + +def create_text_sampler(config: dict) -> TextSampler: + config = OmegaConf.to_object(config) + sampler_type = config.pop("type") + return TEXT_SAMPLER_TYPES[sampler_type](**config) + + +FRAME_SAMPLER_TYPES = { + "all": AllFrameSampler, + "adaptive": AdaptiveFrameSampler, + "adaptive_advanced": AdaptiveAdvancedFrameSampler, +} + + +def create_frame_sampler(config: dict) -> FrameSampler: + config = OmegaConf.to_object(config) + sampler_type = config.pop("type") + if sampler_type == "adaptive_advanced": + config["strategies"] = [ + AdaptiveAdvancedFrameSamplerStrategy(**s) for s in config["strategies"] + ] + return FRAME_SAMPLER_TYPES[sampler_type](**config) diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/tos_client.py b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/tos_client.py new file mode 100644 index 0000000000000000000000000000000000000000..70532c1358ad1f42f70753e32e3c95c38d079605 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/tos_client.py @@ -0,0 +1,192 @@ +import logging +import os +import yaml +import hashlib +import traceback +from typing import Any, Union, List, Optional +import bytedtos +import io +import decord +import torch +from pyarrow import fs + +def hdfs_read(file_path) -> bytes: + fp = str(file_path) + filesystem = resolve_fs(fp) + + with filesystem.open_input_stream(fp) as f: + content = f.readall() + return content + +def sha256_hashs(b: bytes, nbytes=32, bit_len=128) -> bytes: + m = hashlib.sha256() + m.update(b) + mb = m.digest() + bb = mb[:nbytes] + truncated_hashs = bb[: bit_len // 8] + return truncated_hashs.hex().lower() + +def retry(func, retry=3): + if retry == 0: + return func + + def wrapper(*args, **kwargs): + for i in range(retry): + error = '' + try: + return func(*args, **kwargs) + except KeyboardInterrupt: + raise KeyboardInterrupt + except: + print(f"In {__file__}, retry {i + 1} times!") + error = traceback.format_exc() + raise Exception(f"Traceback: {error}") + + return wrapper + + +def resolve_fs(paths: Union[str, list[str]]) -> fs.FileSystem: + _p: str = paths # type: ignore + if isinstance(paths, list): + _p = paths[0] + _p = "/".join(_p.split("/")[:3]) + filesystem, _ = fs._resolve_filesystem_and_path(_p) + + return filesystem + + + +class BaseClient: + def __init__(self, retry=0, **kwargs): + self.retry = retry + + def __call__(self, keys: Union[str, List[str]], hashs: Optional[Union[str, List[str]]]=None) -> Union[bytes, List[bytes]]: + """ + Read bytes from remote data source. + Args: + keys (str or list[str]): tos keys or hdfs uri or etc. + hashs (str or list[str]): hashs of the data. + Returns: + bytes (or list[bytes]]): bytes read from remote data source. + """ + if isinstance(keys, str): + assert hashs is None or isinstance(hashs, str) + keys = [keys] + hashs = [hashs] if hashs is not None else None + return_list = False + else: + return_list = True + + if hashs is not None: + bytes_get = retry(self.get_bytes_and_check, retry=3)(keys, hashs) + else: + bytes_get = retry(self.get_bytes, retry=self.retry)(keys) + + if return_list: + return bytes_get + else: + return bytes_get[0] + + def get_bytes_and_check(self, keys: List[bytes], hashs: List[bytes]) -> List[bytes]: + bytes_get = self.get_bytes(keys) + for k, b, h in zip(keys, bytes_get, hashs): + if sha256_hashs(b) != h: + raise Exception(f"hashs check failed on keyss {k}, {sha256_hashs(b)} != {h}!") + return bytes_get + + def get_bytes(self, keys: List[bytes]) -> List[bytes]: + """ + Read bytes from remote data source. + Args: + keyss: tos keys or hdfs uri or etc. + Returns: + bytes: bytes read from remote data source. + """ + raise NotImplementedError + +class TosClient(BaseClient): + def __init__( + self, + ak, + bucket, + idc, + timeout=10, + **kwargs, + ): + super().__init__(**kwargs) + self.tos_client = bytedtos.Client(bucket, ak, timeout=timeout, idc=idc) + + # Input => toskeys + def get_bytes(self, keys: List[bytes]) -> List[bytes]: + """ + Read bytes from tos keys. + Args: + keys (str or list[str]): tos keys. + Returns: + bytes (or list[bytes]]): bytes read from tos. + """ + return [self.tos_client.get_object(keys).data for keys in keys] + +class NebuTosClient(TosClient): + default_config = { + "nebudata-us": "hdfs://harunava/home/byte_icaip_nebudata/proj/nebudata/conf/nebuconfig_va_20240925.yaml", + "nebudata-sg": "hdfs://harunasg/home/byte_icaip_nebudata_sg/proj/nebudata/conf/nebuconfig_sg_20240925.yaml", # Default + } + + def __init__( + self, + ref_tos_bucket: Union[str, None] = None, + idc: Union[str, None] = None, + **kwargs, + ): + logging.info(f"NebuTos config: {ref_tos_bucket=} {idc=}") + if idc is None: + idc = os.environ.get("RUNTIME_IDC_NAME", "my2") + + if ref_tos_bucket is not None: + assert ref_tos_bucket in self.default_config, f"Unknow tos_bucket {ref_tos_bucket}, please use one of {self.default_config.keyss()}." + nebuconfig_file = self.default_config.get(ref_tos_bucket) + else: + arnold_base_dir = os.environ.get("ARNOLD_BASE_DIR", "hdfs://harunasg") + for ref_tos_bucket, nebuconfig_file in self.default_config.items(): + if arnold_base_dir in nebuconfig_file: + break + + nebuconfig = yaml.safe_load(hdfs_read(nebuconfig_file).decode("utf-8")) + default_access_keys = nebuconfig['tos_user_access_key'] + tos_ak = os.environ.get("TOS_USER_ACCESS_key", default_access_keys) + + super().__init__(tos_ak, ref_tos_bucket, idc, **kwargs) + + +if __name__ == "__main__": + client = NebuTosClient(ref_tos_bucket="nebudata-sg", idc="my2") + # toskey = 'cas/596ccf6d8de5d16e0ca5a91c0610d9bd' + toskey = 'cas/0c862903f94897a08bde81ee10104c48' + results = [client(toskey, hashs=toskey.split('cas/')[-1])] + # with open('output_video.mp4', 'wb') as f: + # f.write(results[0]) + # np_array = np.frombuffer(results[0], dtype=np.uint8) + file_io = io.BytesIO(results[0]) + reader = decord.VideoReader(file_io, ctx=decord.cpu(0)) + video_length = len(reader) + # sampler = FrameSamplerCollection(data_configs['samplers']) + # video_idxs, structure = self.sampler(video_length, params) + # frames_idxs = copy.deepcopy(video_idxs) + # in_range_len = len(video_idxs) + # out_range_idxs = self.add_out_range_sample( + # video_idxs, video_length, params) + # video_idxs = video_idxs + out_range_idxs + # video_idxs_array = np.array(video_idxs) + # video_idxs_valid_mask = video_idxs_array >= 0 + # valid_indices = video_idxs_array[video_idxs_valid_mask] + valid_indices = list(range(121)) + frames_batch = reader.get_batch(valid_indices).asnumpy() + frames_tensor = torch.from_numpy(frames_batch).float() + frames_tensor = (frames_tensor / 127.5) - 1 + frames_tensor = frames_tensor.permute(0, 3, 1, 2) + del reader + +# 'clip_toskey': 'cas/596ccf6d8de5d16e0ca5a91c0610d9bd' +# 'clip_tosurl': 'https://tosv.byted.org/obj/nebudata-sg/cas/596ccf6d8de5d16e0ca5a91c0610d9bd' +# 'clip_url': 'https://tosv-sg.tiktok-row.org/obj/nebudata-sg/cas/596ccf6d8de5d16e0ca5a91c0610d9bd' \ No newline at end of file diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/__pycache__/distributed_utils.cpython-310.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/__pycache__/distributed_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a93babbc479fe52fb8b67dd5c88dd3eca10441f Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/__pycache__/distributed_utils.cpython-310.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/__pycache__/distributed_utils.cpython-311.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/__pycache__/distributed_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b70c0e65ae832fa1bbcd121e79910f6c59dda95 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/__pycache__/distributed_utils.cpython-311.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/__pycache__/hdfs_utils.cpython-310.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/__pycache__/hdfs_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9749fb4dba1dea48b82f79df1c4ab0bdd0688979 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/__pycache__/hdfs_utils.cpython-310.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/__pycache__/hdfs_utils.cpython-311.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/__pycache__/hdfs_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b247ce64b65104af7e97f67dc64fa7e40d13d051 Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/__pycache__/hdfs_utils.cpython-311.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/__pycache__/partition_utils.cpython-310.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/__pycache__/partition_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3c68e645998be83ff37007cea5e57df313d528e Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/__pycache__/partition_utils.cpython-310.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/__pycache__/partition_utils.cpython-311.pyc b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/__pycache__/partition_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efaeec94eca15d0f6a69d9dca39f7f2bbe02995b Binary files /dev/null and b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/__pycache__/partition_utils.cpython-311.pyc differ diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/distributed_utils.py b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/distributed_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f2f8d60e2b84aa832dbb4427bb169808f723a120 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/distributed_utils.py @@ -0,0 +1,149 @@ +""" +Distributed basic functions. +""" + +import os +import torch +import torch.distributed as dist + +from typing import Optional +from torch.nn.parallel import DistributedDataParallel + +_DATA_PARALLEL_GROUP = None +_SEQUENCE_PARALLEL_GROUP = None +_SEQUENCE_PARALLEL_CPU_GROUP = None + + +def get_global_rank() -> int: + """ + Get the global rank, the global index of the GPU. + """ + return int(os.environ.get("RANK", "0")) + + +def get_local_rank() -> int: + """ + Get the local rank, the local index of the GPU. + """ + return int(os.environ.get("LOCAL_RANK", "0")) + + +def get_world_size() -> int: + """ + Get the world size, the total amount of GPUs. + """ + return int(os.environ.get("WORLD_SIZE", "1")) + + +def get_device() -> torch.device: + """ + Get current rank device. + """ + return torch.device("cuda", get_local_rank()) + + +def barrier_if_distributed(*args, **kwargs): + """ + Synchronizes all processes if under distributed context. + """ + if dist.is_initialized(): + return dist.barrier(*args, **kwargs) + + +def init_torch(cudnn_benchmark=True): + """ + Common PyTorch initialization configuration. + """ + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + torch.backends.cudnn.benchmark = cudnn_benchmark + torch.cuda.set_device(get_local_rank()) + dist.init_process_group( + backend="nccl", + rank=get_global_rank(), + world_size=get_world_size(), + ) + + +def convert_to_ddp(module: torch.nn.Module, **kwargs) -> DistributedDataParallel: + return DistributedDataParallel( + module=module, + device_ids=[get_local_rank()], + output_device=get_local_rank(), + **kwargs, + ) + + +def get_data_parallel_group() -> Optional[dist.ProcessGroup]: + """ + Get data parallel process group. + """ + return _DATA_PARALLEL_GROUP + + +def get_sequence_parallel_group() -> Optional[dist.ProcessGroup]: + """ + Get sequence parallel process group. + """ + return _SEQUENCE_PARALLEL_GROUP + + +def get_sequence_parallel_cpu_group() -> Optional[dist.ProcessGroup]: + """ + Get sequence parallel CPU process group. + """ + return _SEQUENCE_PARALLEL_CPU_GROUP + + +def get_data_parallel_rank() -> int: + """ + Get data parallel rank. + """ + group = get_data_parallel_group() + return dist.get_rank(group) if group else get_global_rank() + + +def get_data_parallel_world_size() -> int: + """ + Get data parallel world size. + """ + group = get_data_parallel_group() + return dist.get_world_size(group) if group else get_world_size() + + +def get_sequence_parallel_rank() -> int: + """ + Get sequence parallel rank. + """ + group = get_sequence_parallel_group() + return dist.get_rank(group) if group else 0 + + +def get_sequence_parallel_world_size() -> int: + """ + Get sequence parallel world size. + """ + group = get_sequence_parallel_group() + return dist.get_world_size(group) if group else 1 + + +def init_sequence_parallel(sequence_parallel_size: int): + """ + Initialize sequence parallel. + """ + global _DATA_PARALLEL_GROUP + global _SEQUENCE_PARALLEL_GROUP + global _SEQUENCE_PARALLEL_CPU_GROUP + assert dist.is_initialized() + world_size = dist.get_world_size() + rank = dist.get_rank() + data_parallel_size = world_size // sequence_parallel_size + for i in range(data_parallel_size): + start_rank = i * sequence_parallel_size + end_rank = (i + 1) * sequence_parallel_size + ranks = range(start_rank, end_rank) + group = dist.new_group(ranks) + cpu_group = dist.new_group(ranks, backend="gloo") + if rank in ranks: + _SEQUENCE_PARALLEL_GROUP = group + _SEQUENCE_PARALLEL_CPU_GROUP = cpu_group diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/hdfs_utils.py b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/hdfs_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8977031b9844fe26f4979c28dda3a672fe5a2247 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/hdfs_utils.py @@ -0,0 +1,277 @@ +""" +File system operations. Currently supports local and hadoop file systems. +""" +import os +import pickle +import shutil +import hashlib +import tarfile +import tempfile +import subprocess +from typing import Union, List, Optional +from pyarrow import fs + +from .distributed_utils import barrier_if_distributed, get_global_rank, get_local_rank + + +def resolve_fs(paths: Union[str, list[str]]) -> fs.FileSystem: + _p: str = paths # type: ignore + if isinstance(paths, list): + _p = paths[0] + _p = "/".join(_p.split("/")[:3]) + filesystem, _ = fs._resolve_filesystem_and_path(_p) + + return filesystem + + +def read(file_path) -> bytes: + fp = str(file_path) + filesystem = resolve_fs(fp) + + with filesystem.open_input_stream(fp) as f: + content = f.readall() + + return content + + +def is_hdfs_path(path: str) -> bool: + """ + Detects whether a path is an hdfs path. + A hdfs path must startswith "hdfs://" protocol prefix. + """ + return path.lower().startswith("hdfs://") + + +def download( + path: str, + dirname: Optional[str] = None, + filename: Optional[str] = None, + add_hash_suffix: bool = True, + distributed: bool = True, + overwrite: bool = False, +) -> str: + """ + Download a file to a local location. Returns the local path. + This function avoids repeated download if it has already been downloaded before. + Under distributed context, only local rank zero will download and the rest will wait. + Args: + path: source file path. + dirname: destination directory, or None for auto. + filename: destination file name, or None for auto. + add_hash_suffix: whether to add a hash suffix to distinguish + between files with same name but different paths. + distributed: True if this method is called by all ranks. False if called by a single rank. + overwrite: whether to overwrite a downloaded file. + """ + # If local path and no destination specification, directly return. + if not is_hdfs_path(path) and dirname is None and filename is None: + return path + + # Compute a local filename. + if dirname is None: + dirname = "downloads" + if filename is None: + filename = os.path.split(path)[-1] + if add_hash_suffix: + hashname = hashlib.md5(path.encode("utf-8")).hexdigest() + filename += "." + hashname + + pathname = os.path.join(dirname, filename) + to_bytenas = os.path.abspath(dirname).startswith("/mnt/bn") + + # If distributed, only local rank zero performs download. + # If the destination is on bytenas, only global rank zero performs download. + if (not distributed) or (get_global_rank() == 0) or (get_local_rank() == 0 and not to_bytenas): + # Download if the file doesn't exist. + if overwrite and os.path.exists(pathname): + remove(pathname) + if not os.path.exists(pathname): + os.makedirs(dirname, exist_ok=True) + copy(path, pathname) + + # If distributed, all ranks must wait. + if distributed: + barrier_if_distributed() + return pathname + + +def download_and_extract(path: str) -> str: + """ + Download from hdfs if needed and extract tarball if needed. + Do nothing if the file has already been downloaded and extracted locally. + Returns the extracted local path. + Under distributed context, only local rank zero will do work and the rest will wait. + """ + # Download from hdfs if needed. + path = download(path) + # If the path is a file instead of directory, + # assume it is a tarball and try extract it. + if os.path.isfile(path): + with tarfile.open(path) as tar: + # Assume the tarball's first entry as the directory name. + folder_name = tar.next().name + # If distributed, only local rank zero performs the extraction. + if get_local_rank() == 0: + # Extract only if it hasn't been extracted before. + if not os.path.exists(folder_name): + tar.extractall(".") + # If distributed, all ranks must wait. + barrier_if_distributed() + path = folder_name + return path + + +def listdir(path: str) -> List[str]: + """ + List directory. Returns full path. + + Examples: + - listdir("hdfs://dir") -> ["hdfs://dir/file1", "hdfs://dir/file2"] + - listdir("/dir") -> ["/dir/file1", "/dir/file2"] + """ + files = [] + + if is_hdfs_path(path): + pipe = subprocess.Popen( + args=["hdfs", "dfs", "-ls", path], + shell=False, + stdout=subprocess.PIPE, + ) + + for line in pipe.stdout: + parts = line.strip().split() + + # drwxr-xr-x - user group 4 file + if len(parts) < 5: + continue + + # Filter out warning texts when listing files on uswest cluster. + if "Warn" in parts[0].decode("utf8"): + continue + + files.append(parts[-1].decode("utf8")) + + pipe.stdout.close() + pipe.wait() + + else: + files = [os.path.join(path, file) for file in os.listdir(path)] + + return files + + +def listdir_with_metafile(path: str) -> List[str]: + """ + Create a metafile caching the list directory result. + Read from metafile for all other ranks and all future list operations. + Same behavior as listdir(path). + """ + # Local directory should directly return. + if not is_hdfs_path(path): + return listdir(path) + + # Define metafile path. + metafile = os.path.join(path, "metafile.pkl") + + # Write metafile if not exists, only by global rank zero. + if get_global_rank() == 0 and not exists(metafile): + files = listdir(path) + with tempfile.NamedTemporaryFile("wb", delete=True) as f: + f.write(pickle.dumps(files)) + f.flush() + copy(f.name, metafile, blocking=True) + + # All other ranks wait. + barrier_if_distributed() + + # All ranks read from metafile. + with open(download(metafile), "rb") as f: + files = pickle.loads(f.read()) + + # # Assert to prevent directory move. + # assert all( + # file.startswith(path) for file in files + # ), f"metafile for path: {path} is outdated. The directory likely has been moved." + + # Return the list of files. + return files + + +def exists(path: str) -> bool: + """ + Check whether a path exists. + Returns True if exists, False otherwise. + """ + if is_hdfs_path(path): + process = subprocess.run( + ["hdfs", "dfs", "-test", "-e", path], capture_output=True) + return process.returncode == 0 + return os.path.exists(path) + + +def mkdir(path: str): + """ + Create a directory. + Create all parent directory if not present. No-op if directory already present. + """ + if is_hdfs_path(path): + subprocess.run(["hdfs", "dfs", "-mkdir", "-p", path]) + else: + os.makedirs(path, exist_ok=True) + + +def copy(src: str, tgt: str, blocking: bool = True): + """ + Copy a file. + """ + if src == tgt: + return + + src_hdfs = is_hdfs_path(src) + tgt_hdfs = is_hdfs_path(tgt) + + if not src_hdfs and not tgt_hdfs: + shutil.copy(src, tgt) + return + + if src_hdfs and tgt_hdfs: + process = subprocess.Popen(["hdfs", "dfs", "-cp", "-f", src, tgt]) + elif src_hdfs and not tgt_hdfs: + process = subprocess.Popen( + ["hdfs", "dfs", "-get", "-c", "64", src, tgt]) + elif not src_hdfs and tgt_hdfs: + process = subprocess.Popen(["hdfs", "dfs", "-put", "-f", src, tgt]) + + if blocking: + process.wait() + + +def move(src: str, tgt: str): + """ + Move a file. + """ + if src == tgt: + return + + src_hdfs = is_hdfs_path(src) + tgt_hdfs = is_hdfs_path(tgt) + + if src_hdfs and tgt_hdfs: + subprocess.run(["hdfs", "dfs", "-mv", src, tgt]) + elif not src_hdfs and not tgt_hdfs: + shutil.move(src, tgt) + else: + copy(src, tgt) + remove(src) + + +def remove(path: str): + """ + Remove a file or directory. + """ + if is_hdfs_path(path): + subprocess.run(["hdfs", "dfs", "-rm", "-r", path]) + elif os.path.isfile(path): + os.remove(path) + else: + shutil.rmtree(path) diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/partition_utils.py b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/partition_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c00d0874a5db4f7f23242be51ee12c9a5c9d9f09 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/utils/partition_utils.py @@ -0,0 +1,45 @@ +""" +Partition utility functions. +""" + +from typing import Any, List + + +def partition_by_size(data: List[Any], size: int) -> List[List[Any]]: + """ + Partition a list by size. + When indivisible, the last group contains fewer items than the target size. + + Examples: + - data: [1,2,3,4,5] + - size: 2 + - return: [[1,2], [3,4], [5]] + """ + assert size > 0 + return [data[i: (i + size)] for i in range(0, len(data), size)] + + +def partition_by_groups(data: List[Any], groups: int) -> List[List[Any]]: + """ + Partition a list by groups. + When indivisible, some groups may have more items than others. + + Examples: + - data: [1,2,3,4,5] + - groups: 2 + - return: [[1,3,5], [2,4]] + """ + assert groups > 0 + return [data[i::groups] for i in range(groups)] + + +def shift_list(data: List[Any], n: int) -> List[Any]: + """ + Rotate a list by n elements. + + Examples: + - data: [1,2,3,4,5] + - n: 3 + - return: [4,5,1,2,3] + """ + return data[(n % len(data)):] + data[: (n % len(data))] diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/video_parquet.py b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/video_parquet.py new file mode 100644 index 0000000000000000000000000000000000000000..0f0c2ddf2147f91269225dba4ab8a5d64615346c --- /dev/null +++ b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/video_parquet.py @@ -0,0 +1,1023 @@ +import io +import json +import torch +import pickle + + +from torch import nn +from PIL import Image +from einops import rearrange +import torchvision.transforms as transforms +from torchvision.transforms.functional import to_tensor +from typing import Any, Callable, List, Literal, Optional, Union + +from .base_parquet import ParquetDataset +from .parquet_utils import local_seed, get_seed_for_rank_and_worker +from .samplers.utils import create_text_sampler, create_frame_sampler +from .samplers.text_sampler import TextFrequencySampler, TextSampler, TextCleaner +from .samplers.frame_sampler import FrameSampler, AllFrameSampler, AdaptiveAdvancedFrameSampler +import numpy as np +from .tos_client import NebuTosClient +#import decord +import cv2 +from datetime import datetime +import ast +import random +from io import BytesIO + +import os +from diffusers.utils import export_to_video +from diffusers.training_utils import free_memory + +DATA_SOURCE_MAPPING = { + # average quality data + "panda70m": "panda_middle_quality", + "hdvg": "hdvg_middle_quality", +} + +def get_cv2_video_api(): + import cv2.videoio_registry as vr + + api_pref = None + for backend in vr.getStreamBufferedBackends(): + if not vr.hasBackend(backend): + continue + if not vr.isBackendBuiltIn(backend): + _, abi, api = vr.getStreamBufferedBackendPluginVersion(backend) + if (abi < 1 or (abi == 1 and api < 2)): + continue + api_pref = backend + break + return api_pref +def patch_seed_sample(sample, plugin_caption_key): + # add new caption to text + new_caption = sample[plugin_caption_key] + text = sample.get("text", json.dumps({})) + text = json.loads(sample["text"]) + text[plugin_caption_key] = new_caption + sample['text'] = json.dumps(text) + # construct frames_meta + sample['frames_meta'] = { + 'start_idxs': sample['start_idxs'], + 'end_idxs': sample['end_idxs'], + } + return sample + +class SeedV1Dataset(ParquetDataset): + """ + Video parquet dataset. + + Arguments: + path: a directory path that contains *.parquet files. + video_frame_sampler: a callable function to sample frames from video. + video_transform: a callable function to perform transformation on video. + text_transform: a callable function to perform transformation on text. + seed: seed for deterministic sampling. If None, just random. + partition: partition strategy. Split by *.parquet file or by row groups in each file. + force_partition: if True, raise error if partition is indivisible. + num_parallel_files: number of parallel files to read. + infinite: If True, data will be returned infinitely. + use_offline_emb: If True, load latent/text_emb from offline dataset. + """ + + def __init__( + self, + path: Union[str, List[str]], + *, + sample_size: int | List[int], + video_frame_sampler: FrameSampler = AllFrameSampler(), + video_transform: Callable[[torch.Tensor], Any] = nn.Identity(), + text_sampler: TextSampler = TextFrequencySampler(), + text_transform: Callable[[str], Any] = nn.Identity(), + seed: Optional[int] = None, + partition: Literal["file", "group"] = "file", + force_partition: bool = False, + path_mode: Literal["dir", "file"] = "dir", + num_parallel_files: int = 8, + infinite: bool = True, + shuffle: bool = True, + columns: Optional[List[str]] = None, + use_offline_emb: bool = False, + # todo: remove these once offline embs are ready + latent_channels: int = 16, + txt_in_dim: int = 4096, + system_prompt_prob: float = 0.0, + fps: int = 24, + plugin_caption_path = "", + plugin_caption_key = "", + part_idx = 0, + ): + super().__init__( + path=path, + seed=seed, + partition=partition, + num_parallel_files=num_parallel_files, + infinite=infinite, + force_partition=force_partition, + path_mode=path_mode, + shuffle=shuffle, + columns=columns, + plugin_caption_path=plugin_caption_path, + ) + self.video_frame_sampler = video_frame_sampler + self.video_transform = video_transform + self.text_sampler = text_sampler + self.text_transform = text_transform + self.use_offline_emb = use_offline_emb + self.mock_offline_emb = False # 遵循数据分布 + self.latent_channels = latent_channels + self.txt_in_dim = txt_in_dim + self.system_prompt_prob = system_prompt_prob + self.plugin_caption_path = plugin_caption_path + self.plugin_caption_key = plugin_caption_key + self.part_idx = part_idx + + if sample_size == -1: # if sample_size is None, using Identity transformation + self.pixel_transforms = transforms.Compose([ + transforms.Lambda(lambda x: x) + ]) + else: + sample_size = tuple(sample_size) if not isinstance( + sample_size, int) else (sample_size, sample_size) + self.pixel_transforms = transforms.Compose([ + transforms.Resize(sample_size[0]), + transforms.CenterCrop(sample_size), + ]) + self.fps = fps + + def __iter__(self): + seed = get_seed_for_rank_and_worker(self.seed) + + for sample in super().__iter__(): + free_memory() + if seed is not None: + seed += 1 + + # ---------------------------------------------- + try: + # limit finetune data to high degree of movements + try: + topk_avg_motion_scores_t = json.loads(json.loads(sample["meta"])["original"]["motion_v2"])["topk_avg_motion_scores_t"] + # if topk_avg_motion_scores_t < 400: + # print("motion < 400, skipping!") + # continue + except: + topk_avg_motion_scores_t = -1 + + if self.plugin_caption_path != "": + sample = patch_seed_sample(sample, self.plugin_caption_key) + if sample.get("is_abnormal_caption", False): + print("skip abnormal caption") + continue + results = {} + + # if self.use_offline_emb and "latent" not in sample: + # self.use_offline_emb = False + # self.mock_offline_emb = True + # print( + # "You are using MOCK offline_emb! Make sure it's your intention." + # ) + + # Return offline embedding if provided. + # if self.use_offline_emb: + # results["latent"] = pickle.loads(sample["latent"]).cpu() + # text_emb_dict = pickle.loads(sample["text_emb"]) + # with local_seed(seed): + # sampled_text_keys = self.text_sampler( + # text=text_emb_dict).keys + # results["text_emb"] = text_emb_dict[sampled_text_keys].cpu() + # results["text"] = ( + # json.loads(sample["text"])[ + # sampled_text_keys] if "text" in sample else "" + # ) + # results["uttid"] = sample["uttid"] + # results["meta"] = json.loads( + # sample["meta"]) if "meta" in sample else dict() + # yield results + # continue + + # Compute frame indices. + frame_raw = sample["image"] + frame_num = len(frame_raw) + meta = json.loads(sample["meta"]) + text = json.loads(sample['text']) + if text.get('pd_caption_en'): + text = text['pd_caption_en'][0] + start_idxs, end_idxs = text['index'] + text = text['image_caption'] + text['video_caption'] + else: + text = json.loads(meta['title']) + text = text['pd_caption_en'][0] + start_idxs, end_idxs = text['index'] + text = text['image_caption'] + text['video_caption'] + video_num_frames = end_idxs - start_idxs - 1 + # assert video_num_frames <= 192, f"video is too long with {video_num_frames} frames" + # print(meta['original']['clip_uri']) + # 5: (21, 41, 61, 81, 101) + # 6: (25, 49, 73, 97, 121) + # 7: (29, 57, 85, 113, 141) + # 8: (33, 65, 97, 129, 161) + # 9: (37, 73, 109, 145, 181) + # 10: (41, 81, 121, 161, 201) + # 11: (45, 89, 133, 177, 221) + # 12: (49, 97, 145, 193, 241) + + # 1: (21 - 1) * 4 + 1 = 81, 162 + # 2: (22 - 1) * 4 + 1 = 85, 170 + # 3: (23 - 1) * 4 + 1 = 89, 178 + # 4: (24 - 1) * 4 + 1 = 93, 186 + # 5: (25 - 1) * 4 + 1 = 97, 194 + # 6: (26 - 1) * 4 + 1 = 101, 202 + # 7: (27 - 1) * 4 + 1 = 105, 210 + # 8: (28 - 1) * 4 + 1 = 109, 218 + # 9: (29 - 1) * 4 + 1 = 113, 226 + # 10: (30 - 1) * 4 + 1 = 117, 234 + # 11: (31 - 1) * 4 + 1 = 121, 242 + # 12: (32 - 1) * 4 + 1 = 125, 250 + # 13: (33 - 1) * 4 + 1 = 129, 258 + # 14: (34 - 1) * 4 + 1 = 133, 266 + # 15: (35 - 1) * 4 + 1 = 137, 274 + # 16: (36 - 1) * 4 + 1 = 141, 282 + + # if self.part_idx == 0: + # assert 241 <= video_num_frames, f"Expected 241 <= video_num_frames, but got {video_num_frames}" + # elif self.part_idx == 1: + # assert 221 <= video_num_frames < 241, f"Expected 221 <= video_num_frames < 241, but got {video_num_frames}" + # elif self.part_idx == 2: + # assert 193 <= video_num_frames < 221, f"Expected 193 <= video_num_frames < 221, but got {video_num_frames}" + # elif self.part_idx == 3: + # assert 181 <= video_num_frames < 193, f"Expected 181 <= video_num_frames < 193, but got {video_num_frames}" + # elif self.part_idx == 4: + # assert 161 <= video_num_frames < 181, f"Expected 161 <= video_num_frames < 181, but got {video_num_frames}" + # elif self.part_idx == 5: + # assert 145 <= video_num_frames < 161, f"Expected 145 <= video_num_frames < 161, but got {video_num_frames}" + # elif self.part_idx == 6: + # assert 121 <= video_num_frames < 145, f"Expected 121 <= video_num_frames < 145, but got {video_num_frames}" + # else: + # assert video_num_frames < 121, f"Expected video_num_frames < 121, but got {video_num_frames}" + + if 281 <= video_num_frames: + num_extract_frames = 281 + elif 261 <= video_num_frames < 281: + num_extract_frames = 261 + elif 241 <= video_num_frames < 261: + num_extract_frames = 241 + elif 221 <= video_num_frames < 241: + num_extract_frames = 221 + elif 193 <= video_num_frames < 221: + num_extract_frames = 193 + elif 181 <= video_num_frames < 193: + num_extract_frames = 181 + elif 161 <= video_num_frames < 181: + num_extract_frames = 161 + elif 145 <= video_num_frames < 161: + num_extract_frames = 145 + elif 121 <= video_num_frames < 145: + num_extract_frames = 121 + else: + num_extract_frames = video_num_frames + + if start_idxs + num_extract_frames <= frame_num: + frame_idx = np.arange(start_idxs, start_idxs + num_extract_frames, 1) + else: + frame_idx = np.arange(0, num_extract_frames, 1) + + # import pdb;pdb.set_trace() + # self._save_frames(sample['image'], np.arange(start_idxs, end_idxs - 1, 2), sample["uttid"], self.fps, temp_output_path="5.mp4") + # self._save_frames(sample['image'], np.arange(0, sample['image'].shape[0], 1), sample["uttid"], self.fps, temp_output_path="6.mp4") + + # ----- save video ----- + stride = 2 + try: + if topk_avg_motion_scores_t >= 400: + base_path="/mnt/bn/yufan-dev-my/ysh/Datasets/sft_sftnews_videos/high_motion" + else: + base_path="/mnt/bn/yufan-dev-my/ysh/Datasets/sft_sftnews_videos/low_motion" + + full_video_frame_idx = np.arange(start_idxs, end_idxs - 1, 1) + self._save_frames(sample['image'], full_video_frame_idx, sample["uttid"], self.fps, base_path=base_path) + + stride_video_frame_idx = np.arange(start_idxs, end_idxs - 1, 2) + + if len(stride_video_frame_idx) >= 142: + stride_video_frame_idx = stride_video_frame_idx[:142] + elif len(stride_video_frame_idx) >= 138: + stride_video_frame_idx = stride_video_frame_idx[:138] + elif len(stride_video_frame_idx) >= 134: + stride_video_frame_idx = stride_video_frame_idx[:134] + elif len(stride_video_frame_idx) >= 130: + stride_video_frame_idx = stride_video_frame_idx[:130] + elif len(stride_video_frame_idx) >= 126: + stride_video_frame_idx = stride_video_frame_idx[:126] + elif len(stride_video_frame_idx) >= 122: + stride_video_frame_idx = stride_video_frame_idx[:122] + else: + stride_video_frame_idx = stride_video_frame_idx + + self._save_frames(sample['image'], stride_video_frame_idx, sample["uttid"], self.fps, stride=stride, base_path=base_path) + stride_video_frame_idx = stride_video_frame_idx.tolist() + stride_video_frames = self._decode_frames(sample['image'], stride_video_frame_idx) + + # 1: (21 - 1) * 4 + 1 = 81, 162 + # 2: (22 - 1) * 4 + 1 = 85, 170 + # 3: (23 - 1) * 4 + 1 = 89, 178 + # 4: (24 - 1) * 4 + 1 = 93, 186 + # 5: (25 - 1) * 4 + 1 = 97, 194 + # 6: (26 - 1) * 4 + 1 = 101, 202 + # 7: (27 - 1) * 4 + 1 = 105, 210 + # 8: (28 - 1) * 4 + 1 = 109, 218 + # 9: (29 - 1) * 4 + 1 = 113, 226 + # 10: (30 - 1) * 4 + 1 = 117, 234 + # 11: (31 - 1) * 4 + 1 = 121, 242 + # 12: (32 - 1) * 4 + 1 = 125, 250 + # 13: (33 - 1) * 4 + 1 = 129, 258 + # 14: (34 - 1) * 4 + 1 = 133, 266 + # 15: (35 - 1) * 4 + 1 = 137, 274 + # 16: (36 - 1) * 4 + 1 = 141, 282 + + with local_seed(seed): + stride_video_frames = self.video_transform(stride_video_frames) + stride_video_frames = self.pixel_transforms(stride_video_frames) + except: + pass + # ----- save video ----- + + frame_idx = frame_idx.tolist() + frames = self._decode_frames(sample['image'], frame_idx) + with local_seed(seed): + frames = self.video_transform(frames) + frames = self.pixel_transforms(frames) + results["video"] = frames + results["uttid"] = sample["uttid"] + results["meta"] = meta + results['text'] = text + results['stride'] = stride + + outputs = {"mp4": results['video'], "txt": results['text'], + "fps": self.fps, "num_frames": results['video'].shape[0], + "uttid": results["uttid"], + "stride": results['stride'], "stride_mp4": stride_video_frames, + "ori_num_frames": len(frame_raw), + "ori_height": results['video'].shape[-2], + "ori_width": results['video'].shape[-1], + "cur_num_frames": results['video'].shape[0], + "topk_avg_motion_scores_t": topk_avg_motion_scores_t, + } + + results["video"] = None + results["uttid"] = None + results["meta"] = None + results['text'] = None + results['stride'] = None + results["stride"] = None + results["meta"] = None + results['text'] = None + sample['image'] = None + stride_video_frame = None + frames = None + frame_raw = None + sample = None + results = None + meta = None + txt = None + stride_video_frame_idx = None + full_video_frame_idx = None + video_frame_idx = None + video_num_frames = None + + # del results["video"] + # del results["uttid"] + # del results["meta"] + # del results['text'] + # del results['stride'] + # del sample['image'] + del stride_video_frame + del frames + del frame_raw + del sample + del results + del meta + del txt + del stride_video_frame_idx + del full_video_frame_idx + del video_frame_idx + del video_num_frames + free_memory() + + # Yield. + yield outputs + + except Exception as ex: + print(f"Dataset got unexpected expcetion: {ex}") + sample = None + del sample + free_memory() + continue + # ---------------------------------------------- + + + + # ---------------------------------------------- + # results["video"] = frames + # results['latent'] = None + # results['latent_tail'] = None + # results["text"] = text['video_caption'] + # results['latent_flow'] = None + # outputs = {"mp4": results['video'], "txt": results['text'], + # "fps": self.fps, "num_frames": results['video'].shape[0], + # "latent": results['latent'], "latent_tail": results['latent_tail'],"latent_flow": results['latent_flow'] + # } + # del results + # # Yield. + # yield outputs + + + # # Frame sampling. + # with local_seed(seed): + # frame_idx, frame_info = self.video_frame_sampler(frame_num, sample.get('frames_meta', None)) + + # # Decode frames. + # frames = self._decode_frames(frame_raw, frame_idx) + # with local_seed(seed): + # frames = self.video_transform(frames) + + # if self.mock_offline_emb: + # c, f, h, w = frames.shape + # f, h, w = f // 4 + 1, h // 8, w // 8 + # text_dict = json.loads( + # sample["text"]) if "text" in sample else {} + # with local_seed(seed): + # sampled_text_keys = self.text_sampler( + # text=text_dict).keys + # results["latent"] = torch.randn( + # (f, h, w, self.latent_channels)) + # results["text_emb"] = torch.randn( + # (100, self.txt_in_dim), dtype=torch.bfloat16 + # ) + # results["text"] = self.text_transform( + # text_dict[sampled_text_keys] if "text" in sample else "" + # ) + # results["uttid"] = sample["uttid"] + # results["meta"] = json.loads( + # sample["meta"]) if "meta" in sample else dict() + # yield results + # continue + + # frames = self.pixel_transforms(frames) + # results["video"] = frames + # results.update(frame_info) + + # # Decode meta. + # meta = json.loads(sample["meta"]) + # if sample.get("text"): + # text = json.loads(sample["text"]) + # else: + # # Decode text. + # if meta.get("title"): + # text = {"text": meta["title"]} + # else: + # text = {"text": ""} + + # # Sample text + # with local_seed(seed): + # sampled_text_keys = self.text_sampler(text=text).keys + + # # Preprare system prompt + # if self.system_prompt_prob > 0: + # data_source = meta["original"]["dataset"] + # data_rename = DATA_SOURCE_MAPPING[data_source] + # sys_prompt = f" SEP {data_rename}" + # else: + # sys_prompt = "" + + # # Text transform and system appending + # with local_seed(seed): + # if isinstance(sampled_text_keys, list): + # results["text_dict"] = {} + # for i in sampled_text_keys: + # if torch.rand(1) < self.system_prompt_prob: + # results["text_dict"].update( + # {i: self.text_transform( + # text[i]) + sys_prompt} + # ) + # else: + # results["text_dict"].update( + # {i: self.text_transform(text[i])}) + # else: + # results["text"] = self.text_transform( + # text[sampled_text_keys]) + # if torch.rand(1) < self.system_prompt_prob: + # results["text"] = results["text"] + sys_prompt + + # results["uttid"] = sample["uttid"] + # results["meta"] = meta + + # outputs = {"mp4": results['video'], "txt": results['text'], + # "fps": self.fps, "num_frames": results['video'].shape[0], + # } + # del results + # # Yield. + # yield outputs + # except Exception as ex: + # print(f"SeedV1Dataset got unexpected expcetion: {ex}") + # continue + + @staticmethod + def _decode_frames(frame_raw: List[bytes], frame_idx: List[int]): + frames = [] + # save_list = [] + for idx in frame_idx: + frame_byte = frame_raw[idx] + frame = Image.open(io.BytesIO(frame_byte)) + frame = frame.convert("RGB") + # save_list.append(frame) + frame = to_tensor(frame) + + frames.append(frame) + + frame = None + del frame + frame_byte = None + del frame_byte + free_memory() + + free_memory() + # output_path = "/mnt/bn/yufan-dev-my/ysh/Codes/dummy_dataloader/test_videos" + # file_count = len([f for f in os.listdir(output_path) if os.path.isfile(os.path.join(output_path, f))]) + # video_path = f"{output_path}/{file_count:04d}.mp4" + # export_to_video(save_list, video_path, fps=30) + + frames = torch.stack(frames) + # make value from -1.0 to 1.0 + frames = frames * 2.0 - 1.0 + return frames + + + @staticmethod + def _save_frames(frame_raw: List[bytes], frame_idx: List[int], uid, fps, temp_output_path=None, stride=None, base_path="/mnt/bn/yufan-dev-my/ysh/Datasets/sft_sftnews_videos"): + if stride: + output_path = f"{base_path}/original/stride{stride}" + else: + output_path = f"{base_path}/original" + os.makedirs(output_path, exist_ok=True) + video_path = None + + save_list = [] + frame_height, frame_width = None, None + for idx in frame_idx: + frame_byte = frame_raw[idx] + frame = Image.open(io.BytesIO(frame_byte)) + frame = frame.convert("RGB") + if frame_height is None: + frame_height, frame_width = frame.height, frame.width + video_path = f"{output_path}/{uid}_{len(frame_idx)}_{frame_height}_{frame_width}.mp4" + if os.path.exists(video_path) and temp_output_path is None: + print(f"skip original video: {video_path}") + return + save_list.append(frame) + frame = None + del frame + + if not save_list: + return + + if temp_output_path is not None: + export_to_video(save_list, temp_output_path, fps=fps) + else: + export_to_video(save_list, video_path, fps=fps) + print(f"save to {video_path}") + + save_list = None + del save_list + + free_memory() + + @classmethod + def create_dataset_function(cls, json_path, args, **kwargs): + if 'video_frame_sampler' in kwargs: + kwargs['video_frame_sampler'] = create_frame_sampler( + kwargs['video_frame_sampler']) + if 'text_sampler' in kwargs: + kwargs['text_sampler'] = create_text_sampler( + kwargs['text_sampler']) + return cls(path=json_path, **kwargs) + + + + + +class SeedV1Dataset_dump(ParquetDataset): + """ + Video parquet dataset. + + Arguments: + path: a directory path that contains *.parquet files. + video_frame_sampler: a callable function to sample frames from video. + video_transform: a callable function to perform transformation on video. + text_transform: a callable function to perform transformation on text. + seed: seed for deterministic sampling. If None, just random. + partition: partition strategy. Split by *.parquet file or by row groups in each file. + force_partition: if True, raise error if partition is indivisible. + num_parallel_files: number of parallel files to read. + infinite: If True, data will be returned infinitely. + use_offline_emb: If True, load latent/text_emb from offline dataset. + """ + + def __init__( + self, + path: Union[str, List[str]], + *, + sample_size: int | List[int], + video_frame_sampler: FrameSampler = AllFrameSampler(), + video_transform: Callable[[torch.Tensor], Any] = nn.Identity(), + text_sampler: TextSampler = TextFrequencySampler(), + text_transform: Callable[[str], Any] = nn.Identity(), + seed: Optional[int] = None, + partition: Literal["file", "group"] = "file", + force_partition: bool = False, + path_mode: Literal["dir", "file"] = "dir", + num_parallel_files: int = 8, + infinite: bool = True, + shuffle: bool = True, + columns: Optional[List[str]] = None, + use_offline_emb: bool = False, + # todo: remove these once offline embs are ready + latent_channels: int = 16, + txt_in_dim: int = 4096, + system_prompt_prob: float = 0.0, + fps: int = 24, + plugin_caption_path = "", + plugin_caption_key = "", + dump_path = "", + part_idx = 0, + ): + super().__init__( + path=path, + seed=seed, + partition=partition, + num_parallel_files=num_parallel_files, + infinite=infinite, + force_partition=force_partition, + path_mode=path_mode, + shuffle=shuffle, + columns=columns, + plugin_caption_path=plugin_caption_path, + dump_path = dump_path + ) + self.video_frame_sampler = video_frame_sampler + self.video_transform = video_transform + self.text_sampler = text_sampler + self.text_transform = text_transform + self.use_offline_emb = use_offline_emb + self.mock_offline_emb = False # 遵循数据分布 + self.latent_channels = latent_channels + self.txt_in_dim = txt_in_dim + self.system_prompt_prob = system_prompt_prob + self.plugin_caption_path = plugin_caption_path + self.plugin_caption_key = plugin_caption_key + self.dump_path = dump_path + self.path = path + + if sample_size == -1: # if sample_size is None, using Identity transformation + self.pixel_transforms = transforms.Compose([ + transforms.Lambda(lambda x: x) + ]) + else: + sample_size = tuple(sample_size) if not isinstance( + sample_size, int) else (sample_size, sample_size) + self.pixel_transforms = transforms.Compose([ + transforms.Resize(sample_size[0]), + transforms.CenterCrop(sample_size), + ]) + self.fps = fps + + def __iter__(self): + seed = get_seed_for_rank_and_worker(self.seed) + abnormal_count = 0 + for sample in super().__iter__(): + if sample == "max_bad_file_count_reached": + yield sample + if seed is not None: + seed += 1 + try: + # limit finetune data to high degree of movements + topk_avg_motion_scores_t = json.loads(json.loads(sample["meta"])["original"]["motion_v2"])["topk_avg_motion_scores_t"] + if topk_avg_motion_scores_t < 400: + continue + + if self.plugin_caption_path != "": + sample = patch_seed_sample(sample, self.plugin_caption_key) + if sample.get("is_abnormal_caption", False): + print(f"skip abnormal caption, count: {abnormal_count}, path:{self.path}") + abnormal_count = abnormal_count + 1 + if abnormal_count < 200: + continue + else: + abnormal_count = 0 + yield "wtf_is_abnormal" + results = {} + abnormal_count = 0 + if self.use_offline_emb and "latent" not in sample: + self.use_offline_emb = False + self.mock_offline_emb = True + print( + "You are using MOCK offline_emb! Make sure it's your intention." + ) + + # Return offline embedding if provided. + if self.use_offline_emb: + results["latent"] = pickle.loads(sample["latent"]).cpu() + text_emb_dict = pickle.loads(sample["text_emb"]) + with local_seed(seed): + sampled_text_keys = self.text_sampler( + text=text_emb_dict).keys + results["text_emb"] = text_emb_dict[sampled_text_keys].cpu() + results["text"] = ( + json.loads(sample["text"])[ + sampled_text_keys] if "text" in sample else "" + ) + results["uttid"] = sample["uttid"] + results["meta"] = json.loads( + sample["meta"]) if "meta" in sample else dict() + yield results + continue + + ### eval data ### + if sample.get('image_bytes', None): + frames = Image.open(BytesIO(sample['image_bytes'])) + transform = transforms.Compose([ + transforms.ToTensor(), + transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]), + ]) + frames = transform(frames) + frames = frames.unsqueeze(0) + results["video"] = frames + results['text'] = sample['caption'] + + latent = np.frombuffer(sample['latent_512'], dtype=np.float32) + latent = latent.reshape(sample['latent_512_size']) + latent = torch.from_numpy(latent).to(torch.bfloat16) + latent_tail = np.frombuffer(sample['latent_512_tail'], dtype=np.float32) + latent_tail = latent_tail.reshape(sample['latent_512_size'][1],1,sample['latent_512_size'][3],sample['latent_512_size'][4]) + latent_tail = torch.from_numpy(latent_tail).to(torch.bfloat16) + results['latent'] = latent + results['latent_tail'] = latent_tail + results['latent_flow'] = None + outputs = {"mp4": results['video'], "txt": results['text'], + "fps": self.fps, "num_frames": results['video'].shape[0], + "latent": results['latent'], "latent_tail": results['latent_tail'],"latent_flow": results['latent_flow'] + } + del results + # Yield. + yield outputs + + ### high quality dataset ### + elif sample.get('video_tos_uri', None): + toskey = sample['video_tos_uri'] + client = NebuTosClient(ref_tos_bucket="nebudata-sg", idc="my2") + tos_results = [client(toskey, hashs=toskey.split('cas/')[-1])] + file_io = io.BytesIO(tos_results[0]) + backend = get_cv2_video_api() + + cap = cv2.VideoCapture(file_io, backend, []) + if not cap.isOpened(): + raise ValueError("Could not open video stream") + + video_length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + assert video_length == 121, f"video length error:', {video_length}" + # valid_indices = [0, video_length-1] + valid_indices = list(range(121)) + + width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + frames_batch = np.empty((len(valid_indices), height, width, 3), dtype=np.uint8) + + i = 0 + for idx in range(video_length): + ok = cap.grab() # next img + if not ok: + break + if idx in valid_indices: # only decompress needed + ret, frame = cap.retrieve() + if ret: + frames_batch[i] = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + i += 1 + assert i == len(valid_indices) + + # reader = decord.VideoReader(file_io, ctx=decord.cpu(0)) + # video_length = len(reader) + # assert video_length == 121, f"video length error:', {video_length}" + # valid_indices = list(range(121)) + # frames_batch = reader.get_batch(valid_indices).asnumpy() + + + del cap + del client + # frames = torch.empty((video_length, 3, height, width), dtype=torch.float32) + # frames[0] = (torch.from_numpy(frames_batch[0]).float() / 127.5 - 1).permute(2, 0, 1) + # frames[-1] = (torch.from_numpy(frames_batch[-1]).float() / 127.5 - 1).permute(2, 0, 1) + frames = torch.from_numpy(frames_batch).float() + frames = (frames / 127.5) - 1 + frames = frames.permute(0, 3, 1, 2) + results["video"] = frames + + ### 720px ### + if sample.get('latent_720', None): + latent = np.frombuffer(sample['latent_720'], dtype=np.float32) + latent = latent.reshape(sample['latent_720_size']) + latent = torch.from_numpy(latent).to(torch.bfloat16) + latent_tail = np.frombuffer(sample['latent_720_tail'], dtype=np.float32) + latent_tail = latent_tail.reshape(sample['latent_720_size'][1],1,sample['latent_720_size'][3],sample['latent_720_size'][4]) + latent_tail = torch.from_numpy(latent_tail).to(torch.bfloat16) + results['latent_flow'] = None + results['latent'] = latent + results['latent_tail'] = latent_tail + assert sample.get('caption_qwen7b_align', None) is not None, "no caption_qwen7b_align" + results["text"] = sample.get('caption_qwen7b_align', None) + ### 512px ### + else: + latent = np.frombuffer(sample['latent_512'], dtype=np.float32) + latent = latent.reshape(sample['latent_512_size']) + latent = torch.from_numpy(latent).to(torch.bfloat16) + latent_tail = np.frombuffer(sample['latent_512_tail'], dtype=np.float32) + latent_tail = latent_tail.reshape(sample['latent_512_size'][1],1,sample['latent_512_size'][3],sample['latent_512_size'][4]) + latent_tail = torch.from_numpy(latent_tail).to(torch.bfloat16) + if sample.get('latent_512_flow'): + latent_flow = np.frombuffer(sample['latent_512_flow'], dtype=np.float32) + latent_flow = latent_flow.reshape(sample['latent_512_size']) + latent_flow = torch.from_numpy(latent_flow).to(torch.bfloat16) + results['latent_flow'] = latent_flow + else: + #results['latent_flow'] = None + raise Exception("no flow!") + results['latent'] = latent + results['latent_tail'] = latent_tail + # assert sample.get('caption_qwen7b_align', None) is not None, "no caption_qwen7b_align" + # results["text"] = sample.get('caption_qwen7b_align', None) + camera_angle = ast.literal_eval(sample['amera_cat_angle'])['result'] + camera_angel = camera_angle['camera_category'] + (', ' + camera_angle['camera_angle'] if camera_angle['camera_angle'] != 'eye-level shot' else '') + s_prompt = ast.literal_eval(sample['s_prompt']) + if 'ans' in s_prompt and "ans2" in s_prompt: + s_prompt = s_prompt["ans"] if random.random() < 0.5 else s_prompt["ans2"] + elif 'ans' in s_prompt: + s_prompt = s_prompt["ans"] + elif "ans2" in s_prompt: + s_prompt = s_prompt["ans2"] + else: + raise Exception("no caption found for data") + camera_motion = ast.literal_eval(sample['camera_motion'])['result']['camera_motions'] + camera_motion = max(camera_motion, key=camera_motion.get) + if camera_motion != 'unknown': + results["text"] = camera_motion + ', ' + camera_angel + ', ' + s_prompt + else: + results["text"] = camera_angel + ', ' + s_prompt + # print(results["text"]) + + + outputs = {"mp4": results['video'], "txt": results['text'], + "fps": self.fps, "num_frames": results['video'].shape[0], + "latent": results['latent'], "latent_tail": results['latent_tail'],"latent_flow": results['latent_flow'] + } + del results + # Yield. + yield outputs + + ### VAE1011 dataset ### + else: + # Compute frame indices. + frame_raw = sample["image"] + frame_num = len(frame_raw) + + with local_seed(seed): + frame_idx, frame_info = self.video_frame_sampler(frame_num, sample.get('frames_meta', None)) + # precheck to make sure all frame_idx are in frame_raw range + if frame_idx[-1] >= frame_num: + print(f"frame_idx[-1] >= frame_num, frame_idx[-1]: {frame_idx[-1]}, frame_num: {frame_num}") + continue + # Decode frames. + frames = self._decode_frames(frame_raw, frame_idx) + with local_seed(seed): + frames = self.video_transform(frames) + + if self.mock_offline_emb: + c, f, h, w = frames.shape + f, h, w = f // 4 + 1, h // 8, w // 8 + text_dict = json.loads( + sample["text"]) if "text" in sample else {} + with local_seed(seed): + sampled_text_keys = self.text_sampler( + text=text_dict).keys + results["latent"] = torch.randn( + (f, h, w, self.latent_channels)) + results["text_emb"] = torch.randn( + (100, self.txt_in_dim), dtype=torch.bfloat16 + ) + results["text"] = self.text_transform( + text_dict[sampled_text_keys] if "text" in sample else "" + ) + results["uttid"] = sample["uttid"] + results["meta"] = json.loads( + sample["meta"]) if "meta" in sample else dict() + yield results + continue + frames = self.pixel_transforms(frames) + + results["video"] = frames + if sample.get('latent_256', None): + latent = np.frombuffer(sample['latent_256'], dtype=np.float32) + latent = latent.reshape(sample['latent_256_size']) + latent = torch.from_numpy(latent).to(torch.bfloat16) + latent_tail = np.frombuffer(sample['latent_256_tail'], dtype=np.float32) + latent_tail = latent_tail.reshape(sample['latent_256_size'][1],1,sample['latent_256_size'][3],sample['latent_256_size'][4]) + latent_tail = torch.from_numpy(latent_tail).to(torch.bfloat16) + else: + latent = np.frombuffer(sample['latent_512'], dtype=np.float32) + latent = latent.reshape(sample['latent_512_size']) + latent = torch.from_numpy(latent).to(torch.bfloat16) + latent_tail = np.frombuffer(sample['latent_512_tail'], dtype=np.float32) + latent_tail = latent_tail.reshape(sample['latent_512_size'][1],1,sample['latent_512_size'][3],sample['latent_512_size'][4]) + latent_tail = torch.from_numpy(latent_tail).to(torch.bfloat16) + + results['latent'] = latent + results['latent_tail'] = latent_tail + # results.update(frame_info) + + # Decode meta. + meta = json.loads(sample["meta"]) + if sample.get("text"): + text = json.loads(sample["text"]) + else: + # Decode text. + if meta.get("title"): + text = {"text": meta["title"]} + else: + text = {"text": ""} + + # Sample text + with local_seed(seed): + sampled_text_keys = self.text_sampler(text=text).keys + + # Preprare system prompt + if self.system_prompt_prob > 0: + data_source = meta["original"]["dataset"] + data_rename = DATA_SOURCE_MAPPING[data_source] + sys_prompt = f" SEP {data_rename}" + else: + sys_prompt = "" + + # Text transform and system appending + with local_seed(seed): + if isinstance(sampled_text_keys, list): + results["text_dict"] = {} + for i in sampled_text_keys: + if torch.rand(1) < self.system_prompt_prob: + results["text_dict"].update( + {i: self.text_transform( + text[i]) + sys_prompt} + ) + else: + results["text_dict"].update( + {i: self.text_transform(text[i])}) + else: + results["text"] = self.text_transform( + text[sampled_text_keys]) + if torch.rand(1) < self.system_prompt_prob: + results["text"] = results["text"] + sys_prompt + + results["uttid"] = sample["uttid"] + results["meta"] = meta + + outputs = {"mp4": results['video'], "txt": results['text'], + "fps": self.fps, "num_frames": results['video'].shape[0], + "latent": results['latent'], "latent_tail": results['latent_tail'], + } + del results + # Yield. + yield outputs + except Exception as ex: + print(f"SeedV1Dataset got unexpected expcetion: {ex}") + continue + + @staticmethod + def _decode_frames(frame_raw: List[bytes], frame_idx: List[int]): + frames = [] + for idx in frame_idx: + frame_byte = frame_raw[idx] + with Image.open(io.BytesIO(frame_byte)) as frame: + frame = frame.convert("RGB") + frame = to_tensor(frame) + frames.append(frame) + frames = torch.stack(frames) + # make value from -1.0 to 1.0 + frames = frames * 2.0 - 1.0 + return frames + + @classmethod + def create_dataset_function(cls, json_path, args, **kwargs): + if 'video_frame_sampler' in kwargs: + kwargs['video_frame_sampler'] = create_frame_sampler( + kwargs['video_frame_sampler']) + if 'text_sampler' in kwargs: + kwargs['text_sampler'] = create_text_sampler( + kwargs['text_sampler']) + return cls(path=json_path, **kwargs) \ No newline at end of file diff --git a/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/video_parquet1.py b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/video_parquet1.py new file mode 100644 index 0000000000000000000000000000000000000000..f2b07a32728ac8a21670b1ff7c5efb4bc1a7892a --- /dev/null +++ b/dataset_code/sft_sftnews/offload/dataset_tool/parquet_dataset/video_parquet1.py @@ -0,0 +1,664 @@ +import io +import json +import torch +import pickle + + +from torch import nn +from PIL import Image +from einops import rearrange +import torchvision.transforms as transforms +from torchvision.transforms.functional import to_tensor +from typing import Any, Callable, List, Literal, Optional, Union + +from .base_parquet import ParquetDataset +from .parquet_utils import local_seed, get_seed_for_rank_and_worker +from .samplers.utils import create_text_sampler, create_frame_sampler +from .samplers.text_sampler import TextFrequencySampler, TextSampler, TextCleaner +from .samplers.frame_sampler import FrameSampler, AllFrameSampler, AdaptiveAdvancedFrameSampler +import numpy as np +from .tos_client import NebuTosClient +#import decord +import cv2 +from datetime import datetime +import ast +import random + +DATA_SOURCE_MAPPING = { + # average quality data + "panda70m": "panda_middle_quality", + "hdvg": "hdvg_middle_quality", +} + +def get_cv2_video_api(): + import cv2.videoio_registry as vr + + api_pref = None + for backend in vr.getStreamBufferedBackends(): + if not vr.hasBackend(backend): + continue + if not vr.isBackendBuiltIn(backend): + _, abi, api = vr.getStreamBufferedBackendPluginVersion(backend) + if (abi < 1 or (abi == 1 and api < 2)): + continue + api_pref = backend + break + return api_pref +def patch_seed_sample(sample, plugin_caption_key): + # add new caption to text + new_caption = sample[plugin_caption_key] + text = sample.get("text", json.dumps({})) + text = json.loads(sample["text"]) + text[plugin_caption_key] = new_caption + sample['text'] = json.dumps(text) + # construct frames_meta + sample['frames_meta'] = { + 'start_idxs': sample['start_idxs'], + 'end_idxs': sample['end_idxs'], + } + return sample + +class SeedV1Dataset(ParquetDataset): + """ + Video parquet dataset. + + Arguments: + path: a directory path that contains *.parquet files. + video_frame_sampler: a callable function to sample frames from video. + video_transform: a callable function to perform transformation on video. + text_transform: a callable function to perform transformation on text. + seed: seed for deterministic sampling. If None, just random. + partition: partition strategy. Split by *.parquet file or by row groups in each file. + force_partition: if True, raise error if partition is indivisible. + num_parallel_files: number of parallel files to read. + infinite: If True, data will be returned infinitely. + use_offline_emb: If True, load latent/text_emb from offline dataset. + """ + + def __init__( + self, + path: Union[str, List[str]], + *, + sample_size: int | List[int], + video_frame_sampler: FrameSampler = AllFrameSampler(), + video_transform: Callable[[torch.Tensor], Any] = nn.Identity(), + text_sampler: TextSampler = TextFrequencySampler(), + text_transform: Callable[[str], Any] = nn.Identity(), + seed: Optional[int] = None, + partition: Literal["file", "group"] = "file", + force_partition: bool = False, + path_mode: Literal["dir", "file"] = "dir", + num_parallel_files: int = 8, + infinite: bool = True, + shuffle: bool = True, + columns: Optional[List[str]] = None, + use_offline_emb: bool = False, + # todo: remove these once offline embs are ready + latent_channels: int = 16, + txt_in_dim: int = 4096, + system_prompt_prob: float = 0.0, + fps: int = 24, + plugin_caption_path = "", + plugin_caption_key = "", + ): + super().__init__( + path=path, + seed=seed, + partition=partition, + num_parallel_files=num_parallel_files, + infinite=infinite, + force_partition=force_partition, + path_mode=path_mode, + shuffle=shuffle, + columns=columns, + plugin_caption_path=plugin_caption_path, + ) + self.video_frame_sampler = video_frame_sampler + self.video_transform = video_transform + self.text_sampler = text_sampler + self.text_transform = text_transform + self.use_offline_emb = use_offline_emb + self.mock_offline_emb = False # 遵循数据分布 + self.latent_channels = latent_channels + self.txt_in_dim = txt_in_dim + self.system_prompt_prob = system_prompt_prob + self.plugin_caption_path = plugin_caption_path + self.plugin_caption_key = plugin_caption_key + + if sample_size == -1: # if sample_size is None, using Identity transformation + self.pixel_transforms = transforms.Compose([ + transforms.Lambda(lambda x: x) + ]) + else: + sample_size = tuple(sample_size) if not isinstance( + sample_size, int) else (sample_size, sample_size) + self.pixel_transforms = transforms.Compose([ + transforms.Resize(sample_size[0]), + transforms.CenterCrop(sample_size), + ]) + self.fps = fps + + def __iter__(self): + seed = get_seed_for_rank_and_worker(self.seed) + + for sample in super().__iter__(): + if seed is not None: + seed += 1 + try: + if self.plugin_caption_path != "": + sample = patch_seed_sample(sample, self.plugin_caption_key) + if sample.get("is_abnormal_caption", False): + print("skip abnormal caption") + continue + results = {} + + if self.use_offline_emb and "latent" not in sample: + self.use_offline_emb = False + self.mock_offline_emb = True + print( + "You are using MOCK offline_emb! Make sure it's your intention." + ) + + # Return offline embedding if provided. + if self.use_offline_emb: + results["latent"] = pickle.loads(sample["latent"]).cpu() + text_emb_dict = pickle.loads(sample["text_emb"]) + with local_seed(seed): + sampled_text_keys = self.text_sampler( + text=text_emb_dict).keys + results["text_emb"] = text_emb_dict[sampled_text_keys].cpu() + results["text"] = ( + json.loads(sample["text"])[ + sampled_text_keys] if "text" in sample else "" + ) + results["uttid"] = sample["uttid"] + results["meta"] = json.loads( + sample["meta"]) if "meta" in sample else dict() + yield results + continue + + # Compute frame indices. + frame_raw = sample["image"] + frame_num = len(frame_raw) + + # Frame sampling. why直接start+80 + with local_seed(seed): + frame_idx, frame_info = self.video_frame_sampler(frame_num, sample.get('frames_meta', None)) + + # Decode frames. + frames = self._decode_frames(frame_raw, frame_idx) + with local_seed(seed): + frames = self.video_transform(frames) + + if self.mock_offline_emb: + c, f, h, w = frames.shape + f, h, w = f // 4 + 1, h // 8, w // 8 + text_dict = json.loads( + sample["text"]) if "text" in sample else {} + with local_seed(seed): + sampled_text_keys = self.text_sampler( + text=text_dict).keys + results["latent"] = torch.randn( + (f, h, w, self.latent_channels)) + results["text_emb"] = torch.randn( + (100, self.txt_in_dim), dtype=torch.bfloat16 + ) + results["text"] = self.text_transform( + text_dict[sampled_text_keys] if "text" in sample else "" + ) + results["uttid"] = sample["uttid"] + results["meta"] = json.loads( + sample["meta"]) if "meta" in sample else dict() + yield results + continue + + frames = self.pixel_transforms(frames) + results["video"] = frames + results.update(frame_info) + + # Decode meta. + meta = json.loads(sample["meta"]) + if sample.get("text"): + text = json.loads(sample["text"]) + else: + # Decode text. + if meta.get("title"): + text = {"text": meta["title"]} + else: + text = {"text": ""} + + # Sample text + with local_seed(seed): + sampled_text_keys = self.text_sampler(text=text).keys + + # Preprare system prompt + if self.system_prompt_prob > 0: + data_source = meta["original"]["dataset"] + data_rename = DATA_SOURCE_MAPPING[data_source] + sys_prompt = f" SEP {data_rename}" + else: + sys_prompt = "" + + # Text transform and system appending + with local_seed(seed): + if isinstance(sampled_text_keys, list): + results["text_dict"] = {} + for i in sampled_text_keys: + if torch.rand(1) < self.system_prompt_prob: + results["text_dict"].update( + {i: self.text_transform( + text[i]) + sys_prompt} + ) + else: + results["text_dict"].update( + {i: self.text_transform(text[i])}) + else: + results["text"] = self.text_transform( + text[sampled_text_keys]) + if torch.rand(1) < self.system_prompt_prob: + results["text"] = results["text"] + sys_prompt + + results["uttid"] = sample["uttid"] + results["meta"] = meta + + outputs = {"mp4": results['video'], "txt": results['text'], + "fps": self.fps, "num_frames": results['video'].shape[0], + } + del results + # Yield. + yield outputs + except Exception as ex: + print(f"SeedV1Dataset got unexpected expcetion: {ex}") + continue + + @staticmethod + def _decode_frames(frame_raw: List[bytes], frame_idx: List[int]): + frames = [] + for idx in frame_idx: + frame_byte = frame_raw[idx] + with Image.open(io.BytesIO(frame_byte)) as frame: + frame = frame.convert("RGB") + frame = to_tensor(frame) + frames.append(frame) + frames = torch.stack(frames) + # make value from -1.0 to 1.0 + frames = frames * 2.0 - 1.0 + return frames + + @classmethod + def create_dataset_function(cls, json_path, args, **kwargs): + if 'video_frame_sampler' in kwargs: + kwargs['video_frame_sampler'] = create_frame_sampler( + kwargs['video_frame_sampler']) + if 'text_sampler' in kwargs: + kwargs['text_sampler'] = create_text_sampler( + kwargs['text_sampler']) + return cls(path=json_path, **kwargs) + + + + + +class SeedV1Dataset_dump(ParquetDataset): + """ + Video parquet dataset. + + Arguments: + path: a directory path that contains *.parquet files. + video_frame_sampler: a callable function to sample frames from video. + video_transform: a callable function to perform transformation on video. + text_transform: a callable function to perform transformation on text. + seed: seed for deterministic sampling. If None, just random. + partition: partition strategy. Split by *.parquet file or by row groups in each file. + force_partition: if True, raise error if partition is indivisible. + num_parallel_files: number of parallel files to read. + infinite: If True, data will be returned infinitely. + use_offline_emb: If True, load latent/text_emb from offline dataset. + """ + + def __init__( + self, + path: Union[str, List[str]], + *, + sample_size: int | List[int], + video_frame_sampler: FrameSampler = AllFrameSampler(), + video_transform: Callable[[torch.Tensor], Any] = nn.Identity(), + text_sampler: TextSampler = TextFrequencySampler(), + text_transform: Callable[[str], Any] = nn.Identity(), + seed: Optional[int] = None, + partition: Literal["file", "group"] = "file", + force_partition: bool = False, + path_mode: Literal["dir", "file"] = "dir", + num_parallel_files: int = 8, + infinite: bool = True, + shuffle: bool = True, + columns: Optional[List[str]] = None, + use_offline_emb: bool = False, + # todo: remove these once offline embs are ready + latent_channels: int = 16, + txt_in_dim: int = 4096, + system_prompt_prob: float = 0.0, + fps: int = 24, + plugin_caption_path = "", + plugin_caption_key = "", + dump_path = "" + ): + super().__init__( + path=path, + seed=seed, + partition=partition, + num_parallel_files=num_parallel_files, + infinite=infinite, + force_partition=force_partition, + path_mode=path_mode, + shuffle=shuffle, + columns=columns, + plugin_caption_path=plugin_caption_path, + dump_path = dump_path + ) + self.video_frame_sampler = video_frame_sampler + self.video_transform = video_transform + self.text_sampler = text_sampler + self.text_transform = text_transform + self.use_offline_emb = use_offline_emb + self.mock_offline_emb = False # 遵循数据分布 + self.latent_channels = latent_channels + self.txt_in_dim = txt_in_dim + self.system_prompt_prob = system_prompt_prob + self.plugin_caption_path = plugin_caption_path + self.plugin_caption_key = plugin_caption_key + self.dump_path = dump_path + self.path = path + + if sample_size == -1: # if sample_size is None, using Identity transformation + self.pixel_transforms = transforms.Compose([ + transforms.Lambda(lambda x: x) + ]) + else: + sample_size = tuple(sample_size) if not isinstance( + sample_size, int) else (sample_size, sample_size) + self.pixel_transforms = transforms.Compose([ + transforms.Resize(sample_size[0]), + transforms.CenterCrop(sample_size), + ]) + self.fps = fps + + def __iter__(self): + seed = get_seed_for_rank_and_worker(self.seed) + abnormal_count = 0 + for sample in super().__iter__(): + if sample == "max_bad_file_count_reached": + yield sample + if seed is not None: + seed += 1 + try: + if self.plugin_caption_path != "": + sample = patch_seed_sample(sample, self.plugin_caption_key) + if sample.get("is_abnormal_caption", False): + print(f"skip abnormal caption, count: {abnormal_count}, path:{self.path}") + abnormal_count = abnormal_count + 1 + if abnormal_count < 200: + continue + else: + abnormal_count = 0 + yield "wtf_is_abnormal" + results = {} + abnormal_count = 0 + if self.use_offline_emb and "latent" not in sample: + self.use_offline_emb = False + self.mock_offline_emb = True + print( + "You are using MOCK offline_emb! Make sure it's your intention." + ) + + # Return offline embedding if provided. + if self.use_offline_emb: + results["latent"] = pickle.loads(sample["latent"]).cpu() + text_emb_dict = pickle.loads(sample["text_emb"]) + with local_seed(seed): + sampled_text_keys = self.text_sampler( + text=text_emb_dict).keys + results["text_emb"] = text_emb_dict[sampled_text_keys].cpu() + results["text"] = ( + json.loads(sample["text"])[ + sampled_text_keys] if "text" in sample else "" + ) + results["uttid"] = sample["uttid"] + results["meta"] = json.loads( + sample["meta"]) if "meta" in sample else dict() + yield results + continue + + if sample.get('video_tos_uri', None): + toskey = sample['video_tos_uri'] + client = NebuTosClient(ref_tos_bucket="nebudata-sg", idc="my2") + tos_results = [client(toskey, hashs=toskey.split('cas/')[-1])] + file_io = io.BytesIO(tos_results[0]) + backend = get_cv2_video_api() + + cap = cv2.VideoCapture(file_io, backend, []) + if not cap.isOpened(): + raise ValueError("Could not open video stream") + + video_length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + assert video_length == 121, f"video length error:', {video_length}" + valid_indices = [0, video_length-1] + + width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + frames_batch = np.empty((len(valid_indices), height, width, 3), dtype=np.uint8) + + i = 0 + for idx in range(video_length): + ok = cap.grab() # next img + if not ok: + break + if idx in valid_indices: # only decompress needed + ret, frame = cap.retrieve() + if ret: + frames_batch[i] = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + i += 1 + assert i == len(valid_indices) + + # reader = decord.VideoReader(file_io, ctx=decord.cpu(0)) + # video_length = len(reader) + # assert video_length == 121, f"video length error:', {video_length}" + # valid_indices = list(range(121)) + # frames_batch = reader.get_batch(valid_indices).asnumpy() + + + del cap + del client + frames = torch.empty((video_length, 3, height, width), dtype=torch.float32) + frames[0] = (torch.from_numpy(frames_batch[0]).float() / 127.5 - 1).permute(2, 0, 1) + frames[-1] = (torch.from_numpy(frames_batch[-1]).float() / 127.5 - 1).permute(2, 0, 1) + # frames = torch.from_numpy(frames_batch).float() + # frames = (frames / 127.5) - 1 + # frames = frames.permute(0, 3, 1, 2) + results["video"] = frames + latent = np.frombuffer(sample['latent_720'], dtype=np.float32) + latent = latent.reshape(sample['latent_720_size']) + latent = torch.from_numpy(latent).to(torch.bfloat16) + latent_tail = np.frombuffer(sample['latent_720_tail'], dtype=np.float32) + latent_tail = latent_tail.reshape(sample['latent_720_size'][1],1,sample['latent_720_size'][3],sample['latent_720_size'][4]) + latent_tail = torch.from_numpy(latent_tail).to(torch.bfloat16) + # if sample.get('latent_512_flow'): + # latent_flow = np.frombuffer(sample['latent_512_flow'], dtype=np.float32) + # latent_flow = latent_flow.reshape(sample['latent_512_size']) + # latent_flow = torch.from_numpy(latent_flow).to(torch.bfloat16) + # results['latent_flow'] = latent_flow + # else: + # #results['latent_flow'] = None + # raise Exception("no flow!") + results['latent_flow'] = None + + results['latent'] = latent + results['latent_tail'] = latent_tail + assert sample.get('caption_qwen7b_align', None) is not None, "no caption_qwen7b_align" + results["text"] = sample.get('caption_qwen7b_align', None) + + # camera_angle = ast.literal_eval(sample['amera_cat_angle'])['result'] + # camera_angel = camera_angle['camera_category'] + (', ' + camera_angle['camera_angle'] if camera_angle['camera_angle'] != 'eye-level shot' else '') + # s_prompt = ast.literal_eval(sample['s_prompt']) + # if 'ans' in s_prompt and "ans2" in s_prompt: + # s_prompt = s_prompt["ans"] if random.random() < 0.5 else s_prompt["ans2"] + # elif 'ans' in s_prompt: + # s_prompt = s_prompt["ans"] + # elif "ans2" in s_prompt: + # s_prompt = s_prompt["ans2"] + # else: + # raise Exception("no caption found for data") + # camera_motion = ast.literal_eval(sample['camera_motion'])['result']['camera_motions'] + # camera_motion = max(camera_motion, key=camera_motion.get) + # if camera_motion != 'unknown': + # results["text"] = camera_motion + ', ' + camera_angel + ', ' + s_prompt + # else: + # results["text"] = camera_angel + ', ' + s_prompt + + + outputs = {"mp4": results['video'], "txt": results['text'], + "fps": self.fps, "num_frames": results['video'].shape[0], + "latent": results['latent'], "latent_tail": results['latent_tail'],"latent_flow": results['latent_flow'] + } + del results + # Yield. + yield outputs + + else: + # Compute frame indices. + frame_raw = sample["image"] + frame_num = len(frame_raw) + + with local_seed(seed): + frame_idx, frame_info = self.video_frame_sampler(frame_num, sample.get('frames_meta', None)) + # precheck to make sure all frame_idx are in frame_raw range + if frame_idx[-1] >= frame_num: + print(f"frame_idx[-1] >= frame_num, frame_idx[-1]: {frame_idx[-1]}, frame_num: {frame_num}") + continue + # Decode frames. + frames = self._decode_frames(frame_raw, frame_idx) + with local_seed(seed): + frames = self.video_transform(frames) + + if self.mock_offline_emb: + c, f, h, w = frames.shape + f, h, w = f // 4 + 1, h // 8, w // 8 + text_dict = json.loads( + sample["text"]) if "text" in sample else {} + with local_seed(seed): + sampled_text_keys = self.text_sampler( + text=text_dict).keys + results["latent"] = torch.randn( + (f, h, w, self.latent_channels)) + results["text_emb"] = torch.randn( + (100, self.txt_in_dim), dtype=torch.bfloat16 + ) + results["text"] = self.text_transform( + text_dict[sampled_text_keys] if "text" in sample else "" + ) + results["uttid"] = sample["uttid"] + results["meta"] = json.loads( + sample["meta"]) if "meta" in sample else dict() + yield results + continue + frames = self.pixel_transforms(frames) + + results["video"] = frames + if sample.get('latent_256', None): + latent = np.frombuffer(sample['latent_256'], dtype=np.float32) + latent = latent.reshape(sample['latent_256_size']) + latent = torch.from_numpy(latent).to(torch.bfloat16) + latent_tail = np.frombuffer(sample['latent_256_tail'], dtype=np.float32) + latent_tail = latent_tail.reshape(sample['latent_256_size'][1],1,sample['latent_256_size'][3],sample['latent_256_size'][4]) + latent_tail = torch.from_numpy(latent_tail).to(torch.bfloat16) + else: + latent = np.frombuffer(sample['latent_512'], dtype=np.float32) + latent = latent.reshape(sample['latent_512_size']) + latent = torch.from_numpy(latent).to(torch.bfloat16) + latent_tail = np.frombuffer(sample['latent_512_tail'], dtype=np.float32) + latent_tail = latent_tail.reshape(sample['latent_512_size'][1],1,sample['latent_512_size'][3],sample['latent_512_size'][4]) + latent_tail = torch.from_numpy(latent_tail).to(torch.bfloat16) + + results['latent'] = latent + results['latent_tail'] = latent_tail + # results.update(frame_info) + + # Decode meta. + meta = json.loads(sample["meta"]) + if sample.get("text"): + text = json.loads(sample["text"]) + else: + # Decode text. + if meta.get("title"): + text = {"text": meta["title"]} + else: + text = {"text": ""} + + # Sample text + with local_seed(seed): + sampled_text_keys = self.text_sampler(text=text).keys + + # Preprare system prompt + if self.system_prompt_prob > 0: + data_source = meta["original"]["dataset"] + data_rename = DATA_SOURCE_MAPPING[data_source] + sys_prompt = f" SEP {data_rename}" + else: + sys_prompt = "" + + # Text transform and system appending + with local_seed(seed): + if isinstance(sampled_text_keys, list): + results["text_dict"] = {} + for i in sampled_text_keys: + if torch.rand(1) < self.system_prompt_prob: + results["text_dict"].update( + {i: self.text_transform( + text[i]) + sys_prompt} + ) + else: + results["text_dict"].update( + {i: self.text_transform(text[i])}) + else: + results["text"] = self.text_transform( + text[sampled_text_keys]) + if torch.rand(1) < self.system_prompt_prob: + results["text"] = results["text"] + sys_prompt + + results["uttid"] = sample["uttid"] + results["meta"] = meta + + outputs = {"mp4": results['video'], "txt": results['text'], + "fps": self.fps, "num_frames": results['video'].shape[0], + "latent": results['latent'], "latent_tail": results['latent_tail'], + } + del results + # Yield. + yield outputs + except Exception as ex: + print(f"SeedV1Dataset got unexpected expcetion: {ex}") + continue + + @staticmethod + def _decode_frames(frame_raw: List[bytes], frame_idx: List[int]): + frames = [] + for idx in frame_idx: + frame_byte = frame_raw[idx] + with Image.open(io.BytesIO(frame_byte)) as frame: + frame = frame.convert("RGB") + frame = to_tensor(frame) + frames.append(frame) + frames = torch.stack(frames) + # make value from -1.0 to 1.0 + frames = frames * 2.0 - 1.0 + return frames + + @classmethod + def create_dataset_function(cls, json_path, args, **kwargs): + if 'video_frame_sampler' in kwargs: + kwargs['video_frame_sampler'] = create_frame_sampler( + kwargs['video_frame_sampler']) + if 'text_sampler' in kwargs: + kwargs['text_sampler'] = create_text_sampler( + kwargs['text_sampler']) + return cls(path=json_path, **kwargs) \ No newline at end of file diff --git a/dataset_code/sft_sftnews/offload/part6.yaml b/dataset_code/sft_sftnews/offload/part6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cef41655ba4b39507439db82749587522d6a2807 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/part6.yaml @@ -0,0 +1,101 @@ +# vae1011-98022219 +# train_data: ['albatross_2_dump', 'budgie_1_dump', 'budgie_2_dump', 'canary_2_dump', 'condor_2_dump', 'falcon_dump', 'filmsupply_highres_dump', 'guillemot_2_dump', 'guillemot_4_dump', 'gull_2_dump', 'harrier_2_dump', 'hdvg_dump', 'hornbill_2_dump', 'hummingbird_2_dump', 'kingfisher_dump', 'lovebird_dump', 'macaw_2_dump', 'movie_2_dump', 'panda70m_dump', 'partridge_2_dump', 'partridge_4_dump', 'petrel_2_dump', 'pigeon_2_dump', 'puffin_2_dump', 'swallow_2_dump', 'vimeo_2_dump', 'vimeo_4_dump', 'warbler_2_dump', 'wren_2_dump'] +# train_data_weights: [68859, 1192, 15856, 203755, 1384503, 78671, 26307, 343789, 514339, 152912, 1762929, 6288112, 594676, 34082, 16263, 49979, 62714, 447823, 19018149, 7013003, 16887569, 3790563, 584691, 477319, 10022018, 9587751, 8486291, 7210, 10100894] + + +#high quality data-30372699 +# train_data: ['Istock_sports_videos','abaka_short','malayan','movie_v0_1','nexdata','rf123_1080p'] +# train_data_weights: [3431837,742656,5699324,14771089,1502775,4225018] + +#high quality data : vae1011 = 1:1 +# train_data: ['Istock_sports_videos','abaka_short','malayan','movie_v0_1','nexdata','rf123_1080p', 'albatross_2_dump', 'budgie_1_dump', 'budgie_2_dump', 'canary_2_dump', 'condor_2_dump', 'falcon_dump', 'filmsupply_highres_dump', 'guillemot_2_dump', 'guillemot_4_dump', 'gull_2_dump', 'harrier_2_dump', 'hdvg_dump', 'hornbill_2_dump', 'hummingbird_2_dump', 'kingfisher_dump', 'lovebird_dump', 'macaw_2_dump', 'movie_2_dump', 'panda70m_dump', 'partridge_2_dump', 'partridge_4_dump', 'petrel_2_dump', 'pigeon_2_dump', 'puffin_2_dump', 'swallow_2_dump', 'vimeo_2_dump', 'vimeo_4_dump', 'warbler_2_dump', 'wren_2_dump'] +# train_data_weights: [3431837,742656,5699324,14771089,1502775,4225018, 22953, 397, 5285, 67918, 461501, 26223, 8769, 114596, 171446, 50970, 587643, 2096037, 198225, 11360, 5421, 16659, 20904, 149274, 6339383, 2337667, 5629189, 1263521, 194897, 159106, 3340672, 3195917, 2828763, 2403, 3366964] + +# train_data: ['flow_test'] +# train_data_weights: [1] +# train_data: ['sft','sft_hq'] +# train_data_weights: [1,10] +# train_data: ['eval'] +# train_data_weights: [1] +train_data: ['sft_new','sft_new_1'] +train_data_weights: [536463, 135600] +# train_data: ['sft'] +# train_data_weights: [1] + +data: + params: + batch_size: 1 # the real batch size + image_batch_size: 16 # real image batch size + enable_bucket: True + dataset_collections: # list all available datasets + sft_new: + target: dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/v2_en_new/2025-02-13-05-39-30/data" + resolution: 512 + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.6": [640, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "512p-0.6": [384, 640] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: closest + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 1 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 1 + stride_prob: 1.0 + frame_lengths: [ 121 ] + frame_lengths_prob: 'harmonic' + clip: 'simple' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + part_idx: 6 + + sft_new_1: + target: dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/v2_en/2025-02-13-05-39-30/data" + resolution: 512 + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.6": [640, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "512p-0.6": [384, 640] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: closest + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 1 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 1 + stride_prob: 1.0 + frame_lengths: [ 121 ] + frame_lengths_prob: 'harmonic' + clip: 'simple' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + part_idx: 6 \ No newline at end of file diff --git a/dataset_code/sft_sftnews/offload/part7.yaml b/dataset_code/sft_sftnews/offload/part7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..61011bfee1f74ba11cd57a509dcc2b80ec7de551 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/part7.yaml @@ -0,0 +1,101 @@ +# vae1011-98022219 +# train_data: ['albatross_2_dump', 'budgie_1_dump', 'budgie_2_dump', 'canary_2_dump', 'condor_2_dump', 'falcon_dump', 'filmsupply_highres_dump', 'guillemot_2_dump', 'guillemot_4_dump', 'gull_2_dump', 'harrier_2_dump', 'hdvg_dump', 'hornbill_2_dump', 'hummingbird_2_dump', 'kingfisher_dump', 'lovebird_dump', 'macaw_2_dump', 'movie_2_dump', 'panda70m_dump', 'partridge_2_dump', 'partridge_4_dump', 'petrel_2_dump', 'pigeon_2_dump', 'puffin_2_dump', 'swallow_2_dump', 'vimeo_2_dump', 'vimeo_4_dump', 'warbler_2_dump', 'wren_2_dump'] +# train_data_weights: [68859, 1192, 15856, 203755, 1384503, 78671, 26307, 343789, 514339, 152912, 1762929, 6288112, 594676, 34082, 16263, 49979, 62714, 447823, 19018149, 7013003, 16887569, 3790563, 584691, 477319, 10022018, 9587751, 8486291, 7210, 10100894] + + +#high quality data-30372699 +# train_data: ['Istock_sports_videos','abaka_short','malayan','movie_v0_1','nexdata','rf123_1080p'] +# train_data_weights: [3431837,742656,5699324,14771089,1502775,4225018] + +#high quality data : vae1011 = 1:1 +# train_data: ['Istock_sports_videos','abaka_short','malayan','movie_v0_1','nexdata','rf123_1080p', 'albatross_2_dump', 'budgie_1_dump', 'budgie_2_dump', 'canary_2_dump', 'condor_2_dump', 'falcon_dump', 'filmsupply_highres_dump', 'guillemot_2_dump', 'guillemot_4_dump', 'gull_2_dump', 'harrier_2_dump', 'hdvg_dump', 'hornbill_2_dump', 'hummingbird_2_dump', 'kingfisher_dump', 'lovebird_dump', 'macaw_2_dump', 'movie_2_dump', 'panda70m_dump', 'partridge_2_dump', 'partridge_4_dump', 'petrel_2_dump', 'pigeon_2_dump', 'puffin_2_dump', 'swallow_2_dump', 'vimeo_2_dump', 'vimeo_4_dump', 'warbler_2_dump', 'wren_2_dump'] +# train_data_weights: [3431837,742656,5699324,14771089,1502775,4225018, 22953, 397, 5285, 67918, 461501, 26223, 8769, 114596, 171446, 50970, 587643, 2096037, 198225, 11360, 5421, 16659, 20904, 149274, 6339383, 2337667, 5629189, 1263521, 194897, 159106, 3340672, 3195917, 2828763, 2403, 3366964] + +# train_data: ['flow_test'] +# train_data_weights: [1] +# train_data: ['sft','sft_hq'] +# train_data_weights: [1,10] +# train_data: ['eval'] +# train_data_weights: [1] +train_data: ['sft_new','sft_new_1'] +train_data_weights: [536463, 135600] +# train_data: ['sft'] +# train_data_weights: [1] + +data: + params: + batch_size: 1 # the real batch size + image_batch_size: 16 # real image batch size + enable_bucket: True + dataset_collections: # list all available datasets + sft_new: + target: dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/v2_en_new/2025-02-13-05-39-30/data" + resolution: 512 + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.6": [640, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "512p-0.6": [384, 640] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: closest + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 1 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 1 + stride_prob: 1.0 + frame_lengths: [ 121 ] + frame_lengths_prob: 'harmonic' + clip: 'simple' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + part_idx: 7 + + sft_new_1: + target: dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/v2_en/2025-02-13-05-39-30/data" + resolution: 512 + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.6": [640, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "512p-0.6": [384, 640] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: closest + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 1 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 1 + stride_prob: 1.0 + frame_lengths: [ 121 ] + frame_lengths_prob: 'harmonic' + clip: 'simple' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + part_idx: 7 \ No newline at end of file diff --git a/dataset_code/sft_sftnews/offload/run.sh b/dataset_code/sft_sftnews/offload/run.sh new file mode 100644 index 0000000000000000000000000000000000000000..af1f04c897ac37b1aafaad4e8befb5635cc96eb7 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/run.sh @@ -0,0 +1,43 @@ +export OMNISTORE_LOAD_STRICT_MODE=0 +export OMNISTORE_LOGGING_LEVEL=ERROR +################################################################# +## Torch +################################################################# +export TOKENIZERS_PARALLELISM=false +export TORCH_LOGS="+dynamo,recompiles,graph_breaks" +export TORCHDYNAMO_VERBOSE=1 +export TORCH_NCCL_ENABLE_MONITORING=1 +export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9" +################################################################# + + +################################################################# +## NCCL +################################################################# +export NCCL_IB_GID_INDEX=3 +export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_SOCKET_TIMEOUT=3600000 + +export NCCL_DEBUG=WARN # disable the verbose NCCL logs +export NCCL_P2P_DISABLE=0 +export NCCL_IB_DISABLE=0 # was 1 +export NCCL_SHM_DISABLE=0 # was 1 +export NCCL_P2P_LEVEL=NVL + +export NCCL_PXN_DISABLE=0 +export NCCL_NET_GDR_LEVEL=2 +export NCCL_IB_QPS_PER_CONNECTION=4 +export NCCL_IB_TC=160 +export NCCL_IB_TIMEOUT=22 +################################################################# + + +# accelerate launch --mixed_precision="bf16" --multi_gpu offoload_features.py +# CUDA_VISIBLE_DEVICES=0 accelerate launch offoload_features.py + +export CUDA_VISIBLE_DEVICES=2,3,4,5,6,7 + +torchrun --nproc_per_node=6 --master_port=12345 offoload_features.py \ + --batch_size 1 \ + --config_path part0.yaml \ No newline at end of file diff --git a/dataset_code/sft_sftnews/offload/run_hv.sh b/dataset_code/sft_sftnews/offload/run_hv.sh new file mode 100644 index 0000000000000000000000000000000000000000..1875784aa7309b253445652afe9fc7f0d88e39c4 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/run_hv.sh @@ -0,0 +1,77 @@ +export OMNISTORE_LOAD_STRICT_MODE=0 +export OMNISTORE_LOGGING_LEVEL=ERROR +################################################################# +## Torch +################################################################# +export TOKENIZERS_PARALLELISM=false +export TORCH_LOGS="+dynamo,recompiles,graph_breaks" +export TORCHDYNAMO_VERBOSE=1 +export TORCH_NCCL_ENABLE_MONITORING=1 +export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9" +################################################################# + + +################################################################# +## NCCL +################################################################# +export NCCL_IB_GID_INDEX=3 +export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_SOCKET_TIMEOUT=3600000 + +export NCCL_DEBUG=WARN # disable the verbose NCCL logs +export NCCL_P2P_DISABLE=0 +export NCCL_IB_DISABLE=0 # was 1 +export NCCL_SHM_DISABLE=0 # was 1 +export NCCL_P2P_LEVEL=NVL + +export NCCL_PXN_DISABLE=0 +export NCCL_NET_GDR_LEVEL=2 +export NCCL_IB_QPS_PER_CONNECTION=4 +export NCCL_IB_TC=160 +export NCCL_IB_TIMEOUT=22 +################################################################# + +################################################################# +## DIST +################################################################# +MASTER_ADDR=$ARNOLD_WORKER_0_HOST +ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`) +MASTER_PORT=${ports[0]} +NNODES=$ARNOLD_WORKER_NUM +NODE_RANK=$ARNOLD_ID +GPUS_PER_NODE=$ARNOLD_WORKER_GPU +# MASTER_PORT=11173 +# GPUS_PER_NODE=1 +# NNODES=1 +# NODE_RANK=0 +WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES)) + +DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT" +if [ ! -z $RDZV_BACKEND ]; then + DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d" + export NCCL_SHM_DISABLE=1 +fi + +echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m" + +################################################################# + +#TODO: prefetching +for i in {0..100} +do + # bash kill.sh + # sleep 2 + + torchrun $DISTRIBUTED_ARGS offoload_features_hv.py \ + --batch_size 1 \ + --dataloader_num_workers 8 \ + --config_path part0.yaml + + # 检查退出状态 + if [ $? -eq 0 ]; then + echo "Iteration $i completed successfully" + else + echo "Iteration $i failed, continuing..." + fi +done \ No newline at end of file diff --git a/dataset_code/sft_sftnews/offload/run_hv_0.sh b/dataset_code/sft_sftnews/offload/run_hv_0.sh new file mode 100644 index 0000000000000000000000000000000000000000..510006766012d7509ccb0327b80414ec12e47538 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/run_hv_0.sh @@ -0,0 +1,77 @@ +export OMNISTORE_LOAD_STRICT_MODE=0 +export OMNISTORE_LOGGING_LEVEL=ERROR +################################################################# +## Torch +################################################################# +export TOKENIZERS_PARALLELISM=false +export TORCH_LOGS="+dynamo,recompiles,graph_breaks" +export TORCHDYNAMO_VERBOSE=1 +export TORCH_NCCL_ENABLE_MONITORING=1 +# export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9" +################################################################# + + +################################################################# +## NCCL +################################################################# +export NCCL_IB_GID_INDEX=3 +export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_SOCKET_TIMEOUT=3600000 + +export NCCL_DEBUG=WARN # disable the verbose NCCL logs +export NCCL_P2P_DISABLE=0 +export NCCL_IB_DISABLE=0 # was 1 +export NCCL_SHM_DISABLE=0 # was 1 +export NCCL_P2P_LEVEL=NVL + +export NCCL_PXN_DISABLE=0 +export NCCL_NET_GDR_LEVEL=2 +export NCCL_IB_QPS_PER_CONNECTION=4 +export NCCL_IB_TC=160 +export NCCL_IB_TIMEOUT=22 +################################################################# + +################################################################# +## DIST +################################################################# +MASTER_ADDR=$ARNOLD_WORKER_0_HOST +ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`) +MASTER_PORT=${ports[0]} +NNODES=$ARNOLD_WORKER_NUM +NODE_RANK=$ARNOLD_ID +GPUS_PER_NODE=$ARNOLD_WORKER_GPU +MASTER_PORT=11173 +GPUS_PER_NODE=8 +NNODES=2 +NODE_RANK=0 +WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES)) + +DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT" +if [ ! -z $RDZV_BACKEND ]; then + DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d" + export NCCL_SHM_DISABLE=1 +fi + +echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m" + +################################################################# + +#TODO: prefetching +for i in {0..1000} +do + # bash kill.sh + # sleep 2 + + torchrun $DISTRIBUTED_ARGS offoload_features_hv.py \ + --batch_size 1 \ + --dataloader_num_workers 8 \ + --config_path part0.yaml + + # 检查退出状态 + if [ $? -eq 0 ]; then + echo "Iteration $i completed successfully" + else + echo "Iteration $i failed, continuing..." + fi +done \ No newline at end of file diff --git a/dataset_code/sft_sftnews/offload/run_hv_1.sh b/dataset_code/sft_sftnews/offload/run_hv_1.sh new file mode 100644 index 0000000000000000000000000000000000000000..a17cd7aa0605fd8b2f74414369d4af30ab843ca5 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/run_hv_1.sh @@ -0,0 +1,77 @@ +export OMNISTORE_LOAD_STRICT_MODE=0 +export OMNISTORE_LOGGING_LEVEL=ERROR +################################################################# +## Torch +################################################################# +export TOKENIZERS_PARALLELISM=false +export TORCH_LOGS="+dynamo,recompiles,graph_breaks" +export TORCHDYNAMO_VERBOSE=1 +export TORCH_NCCL_ENABLE_MONITORING=1 +# export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9" +################################################################# + + +################################################################# +## NCCL +################################################################# +export NCCL_IB_GID_INDEX=3 +export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_SOCKET_TIMEOUT=3600000 + +export NCCL_DEBUG=WARN # disable the verbose NCCL logs +export NCCL_P2P_DISABLE=0 +export NCCL_IB_DISABLE=0 # was 1 +export NCCL_SHM_DISABLE=0 # was 1 +export NCCL_P2P_LEVEL=NVL + +export NCCL_PXN_DISABLE=0 +export NCCL_NET_GDR_LEVEL=2 +export NCCL_IB_QPS_PER_CONNECTION=4 +export NCCL_IB_TC=160 +export NCCL_IB_TIMEOUT=22 +################################################################# + +################################################################# +## DIST +################################################################# +MASTER_ADDR=$ARNOLD_WORKER_0_HOST +ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`) +MASTER_PORT=${ports[0]} +NNODES=$ARNOLD_WORKER_NUM +NODE_RANK=$ARNOLD_ID +GPUS_PER_NODE=$ARNOLD_WORKER_GPU +MASTER_PORT=11173 +GPUS_PER_NODE=8 +NNODES=2 +NODE_RANK=1 +WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES)) + +DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT" +if [ ! -z $RDZV_BACKEND ]; then + DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d" + export NCCL_SHM_DISABLE=1 +fi + +echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m" + +################################################################# + +#TODO: prefetching +for i in {0..1000} +do + # bash kill.sh + # sleep 2 + + torchrun $DISTRIBUTED_ARGS offoload_features_hv.py \ + --batch_size 1 \ + --dataloader_num_workers 16 \ + --config_path part0.yaml + + # 检查退出状态 + if [ $? -eq 0 ]; then + echo "Iteration $i completed successfully" + else + echo "Iteration $i failed, continuing..." + fi +done \ No newline at end of file diff --git a/dataset_code/sft_sftnews/offload/run_hv_2.sh b/dataset_code/sft_sftnews/offload/run_hv_2.sh new file mode 100644 index 0000000000000000000000000000000000000000..2a5a93f2d006d4c74bc85e5c4e4158da79b7d450 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/run_hv_2.sh @@ -0,0 +1,84 @@ +export OMNISTORE_LOAD_STRICT_MODE=0 +export OMNISTORE_LOGGING_LEVEL=ERROR +################################################################# +## Torch +################################################################# +export TOKENIZERS_PARALLELISM=false +export TORCH_LOGS="+dynamo,recompiles,graph_breaks" +export TORCHDYNAMO_VERBOSE=1 +export TORCH_NCCL_ENABLE_MONITORING=1 +# export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9" +################################################################# + + +################################################################# +## NCCL +################################################################# +export NCCL_IB_GID_INDEX=3 +export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_SOCKET_TIMEOUT=3600000 + +export NCCL_DEBUG=WARN # disable the verbose NCCL logs +export NCCL_P2P_DISABLE=0 +export NCCL_IB_DISABLE=0 # was 1 +export NCCL_SHM_DISABLE=0 # was 1 +export NCCL_P2P_LEVEL=NVL + +export NCCL_PXN_DISABLE=0 +export NCCL_NET_GDR_LEVEL=2 +export NCCL_IB_QPS_PER_CONNECTION=4 +export NCCL_IB_TC=160 +export NCCL_IB_TIMEOUT=22 +################################################################# + +################################################################# +## DIST +################################################################# +MASTER_ADDR=$ARNOLD_WORKER_0_HOST +ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`) +MASTER_PORT=${ports[0]} +NNODES=$ARNOLD_WORKER_NUM +NODE_RANK=$ARNOLD_ID +GPUS_PER_NODE=$ARNOLD_WORKER_GPU + +GROUP_ID=1 +BASE_PORT=${ports[0]} +GROUP_PORT=$((BASE_PORT + GROUP_ID * 100)) +GROUP_MASTER_ID=$((GROUP_ID * MACHINES_PER_GROUP)) +MASTER_ADDR=$(eval echo \$ARNOLD_WORKER_${GROUP_MASTER_ID}_HOST) + +MASTER_PORT=11174 +GPUS_PER_NODE=8 +NNODES=2 +NODE_RANK=0 +WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES)) + +DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT" +if [ ! -z $RDZV_BACKEND ]; then + DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d" + export NCCL_SHM_DISABLE=1 +fi + +echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m" + +################################################################# + +#TODO: prefetching +for i in {0..1000} +do + # bash kill.sh + # sleep 2 + + torchrun $DISTRIBUTED_ARGS offoload_features_hv.py \ + --batch_size 1 \ + --dataloader_num_workers 8 \ + --config_path part0.yaml + + # 检查退出状态 + if [ $? -eq 0 ]; then + echo "Iteration $i completed successfully" + else + echo "Iteration $i failed, continuing..." + fi +done \ No newline at end of file diff --git a/dataset_code/sft_sftnews/offload/run_hv_3.sh b/dataset_code/sft_sftnews/offload/run_hv_3.sh new file mode 100644 index 0000000000000000000000000000000000000000..f855fd9c6e7906e4b7718ee5db12d14659f239b2 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/run_hv_3.sh @@ -0,0 +1,84 @@ +export OMNISTORE_LOAD_STRICT_MODE=0 +export OMNISTORE_LOGGING_LEVEL=ERROR +################################################################# +## Torch +################################################################# +export TOKENIZERS_PARALLELISM=false +export TORCH_LOGS="+dynamo,recompiles,graph_breaks" +export TORCHDYNAMO_VERBOSE=1 +export TORCH_NCCL_ENABLE_MONITORING=1 +# export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9" +################################################################# + + +################################################################# +## NCCL +################################################################# +export NCCL_IB_GID_INDEX=3 +export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_SOCKET_TIMEOUT=3600000 + +export NCCL_DEBUG=WARN # disable the verbose NCCL logs +export NCCL_P2P_DISABLE=0 +export NCCL_IB_DISABLE=0 # was 1 +export NCCL_SHM_DISABLE=0 # was 1 +export NCCL_P2P_LEVEL=NVL + +export NCCL_PXN_DISABLE=0 +export NCCL_NET_GDR_LEVEL=2 +export NCCL_IB_QPS_PER_CONNECTION=4 +export NCCL_IB_TC=160 +export NCCL_IB_TIMEOUT=22 +################################################################# + +################################################################# +## DIST +################################################################# +MASTER_ADDR=$ARNOLD_WORKER_0_HOST +ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`) +MASTER_PORT=${ports[0]} +NNODES=$ARNOLD_WORKER_NUM +NODE_RANK=$ARNOLD_ID +GPUS_PER_NODE=$ARNOLD_WORKER_GPU + +GROUP_ID=1 +BASE_PORT=${ports[0]} +GROUP_PORT=$((BASE_PORT + GROUP_ID * 100)) +GROUP_MASTER_ID=$((GROUP_ID * MACHINES_PER_GROUP)) +MASTER_ADDR=$(eval echo \$ARNOLD_WORKER_${GROUP_MASTER_ID}_HOST) + +MASTER_PORT=11174 +GPUS_PER_NODE=8 +NNODES=2 +NODE_RANK=1 +WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES)) + +DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT" +if [ ! -z $RDZV_BACKEND ]; then + DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d" + export NCCL_SHM_DISABLE=1 +fi + +echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m" + +################################################################# + +#TODO: prefetching +for i in {0..1000} +do + # bash kill.sh + # sleep 2 + + torchrun $DISTRIBUTED_ARGS offoload_features_hv.py \ + --batch_size 1 \ + --dataloader_num_workers 16 \ + --config_path part0.yaml + + # 检查退出状态 + if [ $? -eq 0 ]; then + echo "Iteration $i completed successfully" + else + echo "Iteration $i failed, continuing..." + fi +done \ No newline at end of file diff --git a/dataset_code/sft_sftnews/offload/run_hv_4.sh b/dataset_code/sft_sftnews/offload/run_hv_4.sh new file mode 100644 index 0000000000000000000000000000000000000000..cfbdc093b289887894432618345fc58ff16aaf85 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/run_hv_4.sh @@ -0,0 +1,84 @@ +export OMNISTORE_LOAD_STRICT_MODE=0 +export OMNISTORE_LOGGING_LEVEL=ERROR +################################################################# +## Torch +################################################################# +export TOKENIZERS_PARALLELISM=false +export TORCH_LOGS="+dynamo,recompiles,graph_breaks" +export TORCHDYNAMO_VERBOSE=1 +export TORCH_NCCL_ENABLE_MONITORING=1 +# export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9" +################################################################# + + +################################################################# +## NCCL +################################################################# +export NCCL_IB_GID_INDEX=3 +export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_SOCKET_TIMEOUT=3600000 + +export NCCL_DEBUG=WARN # disable the verbose NCCL logs +export NCCL_P2P_DISABLE=0 +export NCCL_IB_DISABLE=0 # was 1 +export NCCL_SHM_DISABLE=0 # was 1 +export NCCL_P2P_LEVEL=NVL + +export NCCL_PXN_DISABLE=0 +export NCCL_NET_GDR_LEVEL=2 +export NCCL_IB_QPS_PER_CONNECTION=4 +export NCCL_IB_TC=160 +export NCCL_IB_TIMEOUT=22 +################################################################# + +################################################################# +## DIST +################################################################# +MASTER_ADDR=$ARNOLD_WORKER_0_HOST +ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`) +MASTER_PORT=${ports[0]} +NNODES=$ARNOLD_WORKER_NUM +NODE_RANK=$ARNOLD_ID +GPUS_PER_NODE=$ARNOLD_WORKER_GPU + +GROUP_ID=1 +BASE_PORT=${ports[0]} +GROUP_PORT=$((BASE_PORT + GROUP_ID * 200)) +GROUP_MASTER_ID=$((GROUP_ID * MACHINES_PER_GROUP)) +MASTER_ADDR=$(eval echo \$ARNOLD_WORKER_${GROUP_MASTER_ID}_HOST) + +MASTER_PORT=11175 +GPUS_PER_NODE=8 +NNODES=2 +NODE_RANK=0 +WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES)) + +DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT" +if [ ! -z $RDZV_BACKEND ]; then + DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d" + export NCCL_SHM_DISABLE=1 +fi + +echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m" + +################################################################# + +#TODO: prefetching +for i in {0..1000} +do + # bash kill.sh + # sleep 2 + + torchrun $DISTRIBUTED_ARGS offoload_features_hv.py \ + --batch_size 1 \ + --dataloader_num_workers 16 \ + --config_path part0.yaml + + # 检查退出状态 + if [ $? -eq 0 ]; then + echo "Iteration $i completed successfully" + else + echo "Iteration $i failed, continuing..." + fi +done \ No newline at end of file diff --git a/dataset_code/sft_sftnews/offload/run_hv_5.sh b/dataset_code/sft_sftnews/offload/run_hv_5.sh new file mode 100644 index 0000000000000000000000000000000000000000..376f8a3531c62a76f8c79b1acce019d46cce1559 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/run_hv_5.sh @@ -0,0 +1,84 @@ +export OMNISTORE_LOAD_STRICT_MODE=0 +export OMNISTORE_LOGGING_LEVEL=ERROR +################################################################# +## Torch +################################################################# +export TOKENIZERS_PARALLELISM=false +export TORCH_LOGS="+dynamo,recompiles,graph_breaks" +export TORCHDYNAMO_VERBOSE=1 +export TORCH_NCCL_ENABLE_MONITORING=1 +# export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9" +################################################################# + + +################################################################# +## NCCL +################################################################# +export NCCL_IB_GID_INDEX=3 +export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_SOCKET_TIMEOUT=3600000 + +export NCCL_DEBUG=WARN # disable the verbose NCCL logs +export NCCL_P2P_DISABLE=0 +export NCCL_IB_DISABLE=0 # was 1 +export NCCL_SHM_DISABLE=0 # was 1 +export NCCL_P2P_LEVEL=NVL + +export NCCL_PXN_DISABLE=0 +export NCCL_NET_GDR_LEVEL=2 +export NCCL_IB_QPS_PER_CONNECTION=4 +export NCCL_IB_TC=160 +export NCCL_IB_TIMEOUT=22 +################################################################# + +################################################################# +## DIST +################################################################# +MASTER_ADDR=$ARNOLD_WORKER_0_HOST +ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`) +MASTER_PORT=${ports[0]} +NNODES=$ARNOLD_WORKER_NUM +NODE_RANK=$ARNOLD_ID +GPUS_PER_NODE=$ARNOLD_WORKER_GPU + +GROUP_ID=1 +BASE_PORT=${ports[0]} +GROUP_PORT=$((BASE_PORT + GROUP_ID * 200)) +GROUP_MASTER_ID=$((GROUP_ID * MACHINES_PER_GROUP)) +MASTER_ADDR=$(eval echo \$ARNOLD_WORKER_${GROUP_MASTER_ID}_HOST) + +MASTER_PORT=11175 +GPUS_PER_NODE=8 +NNODES=2 +NODE_RANK=1 +WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES)) + +DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT" +if [ ! -z $RDZV_BACKEND ]; then + DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d" + export NCCL_SHM_DISABLE=1 +fi + +echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m" + +################################################################# + +#TODO: prefetching +for i in {0..1000} +do + # bash kill.sh + # sleep 2 + + torchrun $DISTRIBUTED_ARGS offoload_features_hv.py \ + --batch_size 1 \ + --dataloader_num_workers 16 \ + --config_path part0.yaml + + # 检查退出状态 + if [ $? -eq 0 ]; then + echo "Iteration $i completed successfully" + else + echo "Iteration $i failed, continuing..." + fi +done \ No newline at end of file diff --git a/dataset_code/sft_sftnews/offload/run_hv_save_videos.sh b/dataset_code/sft_sftnews/offload/run_hv_save_videos.sh new file mode 100644 index 0000000000000000000000000000000000000000..4f367409075fdfe017b1103f5e83d22bc7f037cd --- /dev/null +++ b/dataset_code/sft_sftnews/offload/run_hv_save_videos.sh @@ -0,0 +1,66 @@ +export OMNISTORE_LOAD_STRICT_MODE=0 +export OMNISTORE_LOGGING_LEVEL=ERROR +################################################################# +## Torch +################################################################# +export TOKENIZERS_PARALLELISM=false +export TORCH_LOGS="+dynamo,recompiles,graph_breaks" +export TORCHDYNAMO_VERBOSE=1 +export TORCH_NCCL_ENABLE_MONITORING=1 +export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9" +################################################################# + + +################################################################# +## NCCL +################################################################# +export NCCL_IB_GID_INDEX=3 +export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_SOCKET_TIMEOUT=3600000 + +export NCCL_DEBUG=WARN # disable the verbose NCCL logs +export NCCL_P2P_DISABLE=0 +export NCCL_IB_DISABLE=0 # was 1 +export NCCL_SHM_DISABLE=0 # was 1 +export NCCL_P2P_LEVEL=NVL + +export NCCL_PXN_DISABLE=0 +export NCCL_NET_GDR_LEVEL=2 +export NCCL_IB_QPS_PER_CONNECTION=4 +export NCCL_IB_TC=160 +export NCCL_IB_TIMEOUT=22 +################################################################# + +################################################################# +## DIST +################################################################# +MASTER_ADDR=$ARNOLD_WORKER_0_HOST +ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`) +MASTER_PORT=${ports[0]} +NNODES=$ARNOLD_WORKER_NUM +NODE_RANK=$ARNOLD_ID +GPUS_PER_NODE=$ARNOLD_WORKER_GPU +# GPUS_PER_NODE=1 +# NNODES=1 +# NODE_RANK=0 +WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES)) + +DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT" +if [ ! -z $RDZV_BACKEND ]; then + DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d" + export NCCL_SHM_DISABLE=1 +fi + +echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m" + +################################################################# + +#TODO: prefetching +for i in {0..100} +do + torchrun $DISTRIBUTED_ARGS offoload_features_hv_save_videos.py \ + --batch_size 1 \ + --dataloader_num_workers 8 \ + --config_path part0.yaml || true +done \ No newline at end of file diff --git a/dataset_code/sft_sftnews/offload/run_wan.sh b/dataset_code/sft_sftnews/offload/run_wan.sh new file mode 100644 index 0000000000000000000000000000000000000000..a1bd903927e2adf1a1b087a62cd004ef4d32de7f --- /dev/null +++ b/dataset_code/sft_sftnews/offload/run_wan.sh @@ -0,0 +1,93 @@ +export OMNISTORE_LOAD_STRICT_MODE=0 +export OMNISTORE_LOGGING_LEVEL=ERROR +################################################################# +## Torch +################################################################# +export TOKENIZERS_PARALLELISM=false +export TORCH_LOGS="+dynamo,recompiles,graph_breaks" +export TORCHDYNAMO_VERBOSE=1 +export TORCH_NCCL_ENABLE_MONITORING=1 +export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9" +################################################################# + + +################################################################# +## NCCL +################################################################# +export NCCL_IB_GID_INDEX=3 +export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_SOCKET_TIMEOUT=3600000 + +export NCCL_DEBUG=WARN # disable the verbose NCCL logs +export NCCL_P2P_DISABLE=0 +export NCCL_IB_DISABLE=0 # was 1 +export NCCL_SHM_DISABLE=0 # was 1 +export NCCL_P2P_LEVEL=NVL + +export NCCL_PXN_DISABLE=0 +export NCCL_NET_GDR_LEVEL=2 +export NCCL_IB_QPS_PER_CONNECTION=4 +export NCCL_IB_TC=160 +export NCCL_IB_TIMEOUT=22 +################################################################# + +################################################################# +## DIST +################################################################# +MASTER_ADDR=$ARNOLD_WORKER_0_HOST +ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`) +MASTER_PORT=${ports[0]} +NNODES=$ARNOLD_WORKER_NUM +NODE_RANK=$ARNOLD_ID +GPUS_PER_NODE=$ARNOLD_WORKER_GPU +# GPUS_PER_NODE=1 +# NNODES=1 +# NODE_RANK=0 +WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES)) + +DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT" +if [ ! -z $RDZV_BACKEND ]; then + DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d" + export NCCL_SHM_DISABLE=1 +fi + +echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m" + +################################################################# + +#TODO: prefetching +for i in {0..1} +do + torchrun $DISTRIBUTED_ARGS offoload_features_wan.py \ + --batch_size 1 \ + --config_path part0.yaml || true +done + +# torchrun $DISTRIBUTED_ARGS offoload_features.py \ +# --batch_size 1 \ +# --config_path part1.yaml + +# torchrun $DISTRIBUTED_ARGS offoload_features.py \ +# --batch_size 1 \ +# --config_path part2.yaml + +# torchrun $DISTRIBUTED_ARGS offoload_features.py \ +# --batch_size 1 \ +# --config_path part3.yaml + +# torchrun $DISTRIBUTED_ARGS offoload_features.py \ +# --batch_size 1 \ +# --config_path part4.yaml + +# torchrun $DISTRIBUTED_ARGS offoload_features.py \ +# --batch_size 1 \ +# --config_path part5.yaml + +# torchrun $DISTRIBUTED_ARGS offoload_features.py \ +# --batch_size 1 \ +# --config_path part6.yaml + +# torchrun $DISTRIBUTED_ARGS offoload_features.py \ +# --batch_size 1 \ +# --config_path part7.yaml \ No newline at end of file diff --git a/dataset_code/sft_sftnews/offload/utils_framepack.py b/dataset_code/sft_sftnews/offload/utils_framepack.py new file mode 100644 index 0000000000000000000000000000000000000000..007bc8e9f648ab4d0816a5d76d25eaf8995f4fe8 --- /dev/null +++ b/dataset_code/sft_sftnews/offload/utils_framepack.py @@ -0,0 +1,1229 @@ +import math +import random +from typing import Any, Dict, List, Optional, Tuple, Union + +import torch +import torch.nn.functional as F +from einops import rearrange, repeat + +from diffusers.training_utils import compute_density_for_timestep_sampling + + +DEFAULT_PROMPT_TEMPLATE = { + "template": ( + "<|start_header_id|>system<|end_header_id|>\n\nDescribe the video by detailing the following aspects: " + "1. The main content and theme of the video." + "2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects." + "3. Actions, events, behaviors temporal relationships, physical movement changes of the objects." + "4. background environment, light, style and atmosphere." + "5. camera angles, movements, and transitions used in the video:<|eot_id|>" + "<|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>" + ), + "crop_start": 95, +} + +def get_config_value(args, name): + if hasattr(args, name): + return getattr(args, name) + elif hasattr(args, 'training_config') and hasattr(args.training_config, name): + return getattr(args.training_config, name) + else: + raise AttributeError(f"Neither args nor args.training_config has attribute '{name}'") + +# Copied from diffusers.pipelines.hunyuan_video.pipeline_hunyuan_video.HunyuanVideoPipeline._get_llama_prompt_embeds +def _get_llama_prompt_embeds( + tokenizer, + text_encoder, + prompt: Union[str, List[str]], + prompt_template: Dict[str, Any], + num_videos_per_prompt: int = 1, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, + max_sequence_length: int = 256, + num_hidden_layers_to_skip: int = 2, +) -> Tuple[torch.Tensor, torch.Tensor]: + device = device + dtype = dtype + + prompt = [prompt] if isinstance(prompt, str) else prompt + batch_size = len(prompt) + + prompt = [prompt_template["template"].format(p) for p in prompt] + + crop_start = prompt_template.get("crop_start", None) + if crop_start is None: + prompt_template_input = tokenizer( + prompt_template["template"], + padding="max_length", + return_tensors="pt", + return_length=False, + return_overflowing_tokens=False, + return_attention_mask=False, + ) + crop_start = prompt_template_input["input_ids"].shape[-1] + # Remove <|eot_id|> token and placeholder {} + crop_start -= 2 + + max_sequence_length += crop_start + text_inputs = tokenizer( + prompt, + max_length=max_sequence_length, + padding="max_length", + truncation=True, + return_tensors="pt", + return_length=False, + return_overflowing_tokens=False, + return_attention_mask=True, + ) + text_input_ids = text_inputs.input_ids.to(device=device) + prompt_attention_mask = text_inputs.attention_mask.to(device=device) + + prompt_embeds = text_encoder( + input_ids=text_input_ids, + attention_mask=prompt_attention_mask, + output_hidden_states=True, + ).hidden_states[-(num_hidden_layers_to_skip + 1)] + prompt_embeds = prompt_embeds.to(dtype=dtype) + + if crop_start is not None and crop_start > 0: + prompt_embeds = prompt_embeds[:, crop_start:] + prompt_attention_mask = prompt_attention_mask[:, crop_start:] + + # duplicate text embeddings for each generation per prompt, using mps friendly method + _, seq_len, _ = prompt_embeds.shape + prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1) + prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1) + prompt_attention_mask = prompt_attention_mask.repeat(1, num_videos_per_prompt) + prompt_attention_mask = prompt_attention_mask.view(batch_size * num_videos_per_prompt, seq_len) + + return prompt_embeds, prompt_attention_mask + + +# Copied from diffusers.pipelines.hunyuan_video.pipeline_hunyuan_video.HunyuanVideoPipeline._get_clip_prompt_embeds +def _get_clip_prompt_embeds( + tokenizer_2, + text_encoder_2, + prompt: Union[str, List[str]], + num_videos_per_prompt: int = 1, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, + max_sequence_length: int = 77, +) -> torch.Tensor: + device = device + dtype = dtype + + prompt = [prompt] if isinstance(prompt, str) else prompt + batch_size = len(prompt) + + text_inputs = tokenizer_2( + prompt, + padding="max_length", + max_length=max_sequence_length, + truncation=True, + return_tensors="pt", + ) + + text_input_ids = text_inputs.input_ids + untruncated_ids = tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids + if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids): + _ = tokenizer_2.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1]) + + prompt_embeds = text_encoder_2(text_input_ids.to(device), output_hidden_states=False).pooler_output + + # duplicate text embeddings for each generation per prompt, using mps friendly method + prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt) + prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, -1) + + return prompt_embeds + + +# Copied from diffusers.pipelines.hunyuan_video.pipeline_hunyuan_video.HunyuanVideoPipeline.encode_prompt +def encode_prompt( + tokenizer, + text_encoder, + tokenizer_2, + text_encoder_2, + prompt: Union[str, List[str]], + prompt_2: Union[str, List[str]] = None, + prompt_template: Dict[str, Any] = DEFAULT_PROMPT_TEMPLATE, + num_videos_per_prompt: int = 1, + prompt_embeds: Optional[torch.Tensor] = None, + pooled_prompt_embeds: Optional[torch.Tensor] = None, + prompt_attention_mask: Optional[torch.Tensor] = None, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, + max_sequence_length: int = 256, +): + if prompt_embeds is None: + prompt_embeds, prompt_attention_mask = _get_llama_prompt_embeds( + tokenizer, + text_encoder, + prompt, + prompt_template, + num_videos_per_prompt, + device=device, + dtype=dtype, + max_sequence_length=max_sequence_length, + ) + + if pooled_prompt_embeds is None: + if prompt_2 is None: + prompt_2 = prompt + pooled_prompt_embeds = _get_clip_prompt_embeds( + tokenizer_2, + text_encoder_2, + prompt, + num_videos_per_prompt, + device=device, + dtype=dtype, + max_sequence_length=77, + ) + + return prompt_embeds, pooled_prompt_embeds, prompt_attention_mask + + +def encode_image( + feature_extractor, + image_encoder, + image: torch.Tensor, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, +): + device = device + image = (image + 1) / 2.0 # [-1, 1] -> [0, 1] + image = feature_extractor(images=image, return_tensors="pt", do_rescale=False).to( + device=device, dtype=image_encoder.dtype + ) + image_embeds = image_encoder(**image).last_hidden_state + return image_embeds.to(dtype=dtype) + + +def get_framepack_input_t2v( + vae, + pixel_values, # [-1, 1], (B, C, F, H, W) + latent_window_size: int = 9, + vanilla_sampling: bool = False, + dtype: Optional[torch.dtype] = None, + is_keep_x0=False, +): + # calculate latent frame count from original frame count (4n+1) + latent_f = (pixel_values.shape[2] - 1) // 4 + 1 + # assert latent_f % latent_window_size == 0 + + # calculate the total number of sections (excluding the first frame, divided by window size) + total_latent_sections = math.floor(latent_f / latent_window_size) # 2.0 + if total_latent_sections < 1: + min_frames_needed = latent_window_size * 4 + 1 + raise ValueError( + f"Not enough frames for FramePack: {pixel_values.shape[2]} frames ({latent_f} latent frames), minimum required: {min_frames_needed} frames ({latent_window_size + 1} latent frames)" + ) + + # actual latent frame count (aligned to section boundaries) + latent_f_aligned = total_latent_sections * latent_window_size + + # actual video frame count + frame_count_aligned = (latent_f_aligned - 1) * 4 + 1 # 73 + if frame_count_aligned != pixel_values.shape[2]: # 73 != 89 + print( + f"Frame count mismatch: required={frame_count_aligned} != actual={pixel_values.shape[2]}, trimming to {frame_count_aligned}" + ) + pixel_values = pixel_values[ + :, :, :frame_count_aligned, :, : + ] # torch.Size([1, 3, 89, 480, 832]) -> torch.Size([1, 3, 73, 480, 832]) + + latent_f = latent_f_aligned # Update to the aligned value + + # VAE encode + pixel_values = pixel_values.to(device=vae.device, dtype=vae.dtype) + latents = vae.encode(pixel_values).latent_dist.sample() + latents = latents * vae.config.scaling_factor + latents = latents.to(dtype=dtype) + + all_target_latents = [] + all_target_latent_indices = [] + all_clean_latents = [] + all_clean_latent_indices = [] + all_clean_latents_2x = [] + all_clean_latent_2x_indices = [] + all_clean_latents_4x = [] + all_clean_latent_4x_indices = [] + section_to_video_idx = [] + + if vanilla_sampling: + # Vanilla Sampling Logic + if is_keep_x0: + for b in range(latents.shape[0]): + video_lat = latents[b : b + 1] # Keep batch dim: 1, C, F_aligned, H, W + + for section_index in range(total_latent_sections): + target_start_f = section_index * latent_window_size + target_end_f = target_start_f + latent_window_size + start_latent = video_lat[:, :, 0:1, :, :] + target_latents = video_lat[:, :, target_start_f:target_end_f, :, :] + + # Clean latents preparation (Vanilla) + if section_index == 0: + clean_latents_total_count = 2 + 2 + 16 + else: + clean_latents_total_count = 1 + 2 + 16 + history_latents = torch.zeros( + size=( + 1, + 16, + clean_latents_total_count, + video_lat.shape[-2], + video_lat.shape[-1], + ), + device=video_lat.device, + dtype=video_lat.dtype, + ) + + history_start_f = 0 + video_start_f = target_start_f - clean_latents_total_count + copy_count = clean_latents_total_count + + if video_start_f < 0: + history_start_f = -video_start_f + copy_count = clean_latents_total_count - history_start_f + video_start_f = 0 + if copy_count > 0: + history_latents[:, :, history_start_f:] = video_lat[ + :, :, video_start_f : video_start_f + copy_count, :, : + ] + + # indices generation (Vanilla): copy from FramePack-F1 + if section_index == 0: + indices = torch.arange(0, sum([16, 2, 2, latent_window_size])).unsqueeze(0) + ( + clean_latent_4x_indices, + clean_latent_2x_indices, + clean_latent_indices, + latent_indices, + ) = indices.split([16, 2, 2, latent_window_size], dim=1) + clean_latents_4x, clean_latents_2x, clean_latents = history_latents.split([16, 2, 2], dim=2) + else: + indices = torch.arange(0, sum([1, 16, 2, 1, latent_window_size])).unsqueeze(0) + ( + clean_latent_indices_start, + clean_latent_4x_indices, + clean_latent_2x_indices, + clean_latent_1x_indices, + latent_indices, + ) = indices.split([1, 16, 2, 1, latent_window_size], dim=1) + clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1) + + clean_latents_4x, clean_latents_2x, clean_latents_1x = history_latents.split([16, 2, 1], dim=2) + clean_latents = torch.cat([start_latent, clean_latents_1x], dim=2) + + all_target_latents.append(target_latents) + all_target_latent_indices.append(latent_indices) + all_clean_latents.append(clean_latents) + all_clean_latent_indices.append(clean_latent_indices) + all_clean_latents_2x.append(clean_latents_2x) + all_clean_latent_2x_indices.append(clean_latent_2x_indices) + all_clean_latents_4x.append(clean_latents_4x) + all_clean_latent_4x_indices.append(clean_latent_4x_indices) + section_to_video_idx.append(b) + else: + for b in range(latents.shape[0]): + video_lat = latents[b : b + 1] # Keep batch dim: 1, C, F_aligned, H, W + + for section_index in range(total_latent_sections): + target_start_f = section_index * latent_window_size + target_end_f = target_start_f + latent_window_size + target_latents = video_lat[:, :, target_start_f:target_end_f, :, :] + + # Clean latents preparation (Vanilla) + clean_latents_total_count = 2 + 2 + 16 + history_latents = torch.zeros( + size=( + 1, + 16, + clean_latents_total_count, + video_lat.shape[-2], + video_lat.shape[-1], + ), + device=video_lat.device, + dtype=video_lat.dtype, + ) + + history_start_f = 0 + video_start_f = target_start_f - clean_latents_total_count + copy_count = clean_latents_total_count + + if video_start_f < 0: + history_start_f = -video_start_f + copy_count = clean_latents_total_count - history_start_f + video_start_f = 0 + if copy_count > 0: + history_latents[:, :, history_start_f:] = video_lat[ + :, :, video_start_f : video_start_f + copy_count, :, : + ] + + # indices generation (Vanilla): copy from FramePack-F1 + indices = torch.arange(0, sum([16, 2, 2, latent_window_size])).unsqueeze(0) + ( + clean_latent_4x_indices, + clean_latent_2x_indices, + clean_latent_indices, + latent_indices, + ) = indices.split([16, 2, 2, latent_window_size], dim=1) + clean_latents_4x, clean_latents_2x, clean_latents = history_latents.split([16, 2, 2], dim=2) + + all_target_latents.append(target_latents) + all_target_latent_indices.append(latent_indices) + all_clean_latents.append(clean_latents) + all_clean_latent_indices.append(clean_latent_indices) + all_clean_latents_2x.append(clean_latents_2x) + all_clean_latent_2x_indices.append(clean_latent_2x_indices) + all_clean_latents_4x.append(clean_latents_4x) + all_clean_latent_4x_indices.append(clean_latent_4x_indices) + section_to_video_idx.append(b) + else: + pass + + # Stack all sections into batches + batched_target_latents = torch.cat(all_target_latents, dim=0) + batched_target_latent_indices = torch.cat(all_target_latent_indices, dim=0) + batched_clean_latents = torch.cat(all_clean_latents, dim=0) + batched_clean_latent_indices = torch.cat(all_clean_latent_indices, dim=0) + batched_clean_latents_2x = torch.cat(all_clean_latents_2x, dim=0) + batched_clean_latent_2x_indices = torch.cat(all_clean_latent_2x_indices, dim=0) + batched_clean_latents_4x = torch.cat(all_clean_latents_4x, dim=0) + batched_clean_latent_4x_indices = torch.cat(all_clean_latent_4x_indices, dim=0) + + return ( + batched_target_latents, + batched_target_latent_indices, + batched_clean_latents, + batched_clean_latent_indices, + batched_clean_latents_2x, + batched_clean_latent_2x_indices, + batched_clean_latents_4x, + batched_clean_latent_4x_indices, + section_to_video_idx, + ) + + +def get_framepack_input_i2v( + vae, + pixel_values, # [-1, 1], (B, C, F, H, W) + latent_window_size: int = 9, + vanilla_sampling: bool = False, + dtype: Optional[torch.dtype] = None, +): + # calculate latent frame count from original frame count (4n+1) + latent_f = (pixel_values.shape[2] - 1) // 4 + 1 + + # calculate the total number of sections (excluding the first frame, divided by window size) + total_latent_sections = math.floor((latent_f - 1) / latent_window_size) # 2.0 + if total_latent_sections < 1: + min_frames_needed = latent_window_size * 4 + 1 + raise ValueError( + f"Not enough frames for FramePack: {pixel_values.shape[2]} frames ({latent_f} latent frames), minimum required: {min_frames_needed} frames ({latent_window_size + 1} latent frames)" + ) + + # actual latent frame count (aligned to section boundaries) + latent_f_aligned = total_latent_sections * latent_window_size + 1 + + # actual video frame count + frame_count_aligned = (latent_f_aligned - 1) * 4 + 1 # 73 + if frame_count_aligned != pixel_values.shape[2]: # 73 != 89 + print( + f"Frame count mismatch: required={frame_count_aligned} != actual={pixel_values.shape[2]}, trimming to {frame_count_aligned}" + ) + pixel_values = pixel_values[ + :, :, :frame_count_aligned, :, : + ] # torch.Size([1, 3, 89, 480, 832]) -> torch.Size([1, 3, 73, 480, 832]) + + latent_f = latent_f_aligned # Update to the aligned value + + # VAE encode + pixel_values = pixel_values.to(device=vae.device, dtype=vae.dtype) + latents = vae.encode(pixel_values).latent_dist.sample() + latents = latents * vae.config.scaling_factor + latents = latents.to(dtype=dtype) + + all_target_latents = [] + all_target_latent_indices = [] + all_clean_latents = [] + all_clean_latent_indices = [] + all_clean_latents_2x = [] + all_clean_latent_2x_indices = [] + all_clean_latents_4x = [] + all_clean_latent_4x_indices = [] + section_to_video_idx = [] + + if vanilla_sampling: + # Vanilla Sampling Logic + for b in range(latents.shape[0]): + video_lat = latents[b : b + 1] # Keep batch dim: 1, C, F_aligned, H, W + + for section_index in range(total_latent_sections): + target_start_f = section_index * latent_window_size + 1 + target_end_f = target_start_f + latent_window_size + target_latents = video_lat[:, :, target_start_f:target_end_f, :, :] + start_latent = video_lat[:, :, 0:1, :, :] + + # Clean latents preparation (Vanilla) + clean_latents_total_count = 1 + 2 + 16 + history_latents = torch.zeros( + size=( + 1, + 16, + clean_latents_total_count, + video_lat.shape[-2], + video_lat.shape[-1], + ), + device=video_lat.device, + dtype=video_lat.dtype, + ) + + history_start_f = 0 + video_start_f = target_start_f - clean_latents_total_count + copy_count = clean_latents_total_count + + if video_start_f < 0: + history_start_f = -video_start_f + copy_count = clean_latents_total_count - history_start_f + video_start_f = 0 + if copy_count > 0: + history_latents[:, :, history_start_f:] = video_lat[ + :, :, video_start_f : video_start_f + copy_count, :, : + ] + + # indices generation (Vanilla): copy from FramePack-F1 + indices = torch.arange(0, sum([1, 16, 2, 1, latent_window_size])).unsqueeze(0) + ( + clean_latent_indices_start, + clean_latent_4x_indices, + clean_latent_2x_indices, + clean_latent_1x_indices, + latent_indices, + ) = indices.split([1, 16, 2, 1, latent_window_size], dim=1) + clean_latent_indices = torch.cat([clean_latent_indices_start, clean_latent_1x_indices], dim=1) + + clean_latents_4x, clean_latents_2x, clean_latents_1x = history_latents.split([16, 2, 1], dim=2) + clean_latents = torch.cat([start_latent, clean_latents_1x], dim=2) + + all_target_latents.append(target_latents) + all_target_latent_indices.append(latent_indices) + all_clean_latents.append(clean_latents) + all_clean_latent_indices.append(clean_latent_indices) + all_clean_latents_2x.append(clean_latents_2x) + all_clean_latent_2x_indices.append(clean_latent_2x_indices) + all_clean_latents_4x.append(clean_latents_4x) + all_clean_latent_4x_indices.append(clean_latent_4x_indices) + section_to_video_idx.append(b) + else: + # padding is reversed for inference (future to past) + latent_paddings = list(reversed(range(total_latent_sections))) # [1, 0] + # Note: The padding trick for inference. See the paper for details. + if total_latent_sections > 4: + latent_paddings = [3] + [2] * (total_latent_sections - 3) + [1, 0] + + for b in range(latents.shape[0]): + video_lat = latents[ + b : b + 1 + ] # keep batch dim, (1, C, F, H, W) # torch.Size([1, 16, 19, 60, 104]) + + # emulate inference step (history latents) + # Note: In inference, history_latents stores *generated* future latents. + # Here, for caching, we just need its shape and type for clean_* tensors. + # The actual content doesn't matter much as clean_* will be overwritten. + history_latents = torch.zeros( + ( + 1, + video_lat.shape[1], + 1 + 2 + 16, + video_lat.shape[3], + video_lat.shape[4], + ), + dtype=video_lat.dtype, + ).to(video_lat.device) # torch.Size([1, 16, 19, 60, 104]) + + latent_f_index = latent_f - latent_window_size # Start from the last section # 19 - 9 = 10 + section_index = total_latent_sections - 1 # 2 - 1 = 1 + + for latent_padding in latent_paddings: + is_last_section = ( + section_index == 0 + ) # the last section in inference order == the first section in time + latent_padding_size = latent_padding * latent_window_size + if is_last_section: + assert latent_f_index == 1, "Last section should be starting from frame 1" + + # indices generation (same as inference) + indices = torch.arange(0, sum([1, latent_padding_size, latent_window_size, 1, 2, 16])).unsqueeze(0) + ( + clean_latent_indices_pre, # Index for start_latent + blank_indices, # Indices for padding (future context in inference) + latent_indices, # Indices for the target latents to predict + clean_latent_indices_post, # Index for the most recent history frame + clean_latent_2x_indices, # Indices for the next 2 history frames + clean_latent_4x_indices, # Indices for the next 16 history frames + ) = indices.split([1, latent_padding_size, latent_window_size, 1, 2, 16], dim=1) + + # Indices for clean_latents (start + recent history) + clean_latent_indices = torch.cat([clean_latent_indices_pre, clean_latent_indices_post], dim=1) + + # clean latents preparation (emulating inference) + clean_latents_pre = video_lat[:, :, 0:1, :, :] # Always the first frame (start_latent) + clean_latents_post, clean_latents_2x, clean_latents_4x = history_latents[ + :, :, : 1 + 2 + 16, :, : + ].split([1, 2, 16], dim=2) + clean_latents = torch.cat( + [clean_latents_pre, clean_latents_post], dim=2 + ) # Combine start frame + placeholder + + # Target latents for this section (ground truth) + target_latents = video_lat[:, :, latent_f_index : latent_f_index + latent_window_size, :, :] + + all_target_latents.append(target_latents) + all_target_latent_indices.append(latent_indices) + all_clean_latents.append(clean_latents) + all_clean_latent_indices.append(clean_latent_indices) + all_clean_latents_2x.append(clean_latents_2x) + all_clean_latent_2x_indices.append(clean_latent_2x_indices) + all_clean_latents_4x.append(clean_latents_4x) + all_clean_latent_4x_indices.append(clean_latent_4x_indices) + section_to_video_idx.append(b) + + if is_last_section: # If this was the first section generated in inference (time=0) + # History gets the start frame + the generated first section + generated_latents_for_history = video_lat[:, :, : latent_window_size + 1, :, :] + else: + # History gets the generated current section + generated_latents_for_history = target_latents # Use true latents as stand-in for generated + + history_latents = torch.cat([generated_latents_for_history, history_latents], dim=2) + + section_index -= 1 + latent_f_index -= latent_window_size + + # Stack all sections into batches + batched_target_latents = torch.cat(all_target_latents, dim=0) + batched_target_latent_indices = torch.cat(all_target_latent_indices, dim=0) + batched_clean_latents = torch.cat(all_clean_latents, dim=0) + batched_clean_latent_indices = torch.cat(all_clean_latent_indices, dim=0) + batched_clean_latents_2x = torch.cat(all_clean_latents_2x, dim=0) + batched_clean_latent_2x_indices = torch.cat(all_clean_latent_2x_indices, dim=0) + batched_clean_latents_4x = torch.cat(all_clean_latents_4x, dim=0) + batched_clean_latent_4x_indices = torch.cat(all_clean_latent_4x_indices, dim=0) + + return ( + batched_target_latents, + batched_target_latent_indices, + batched_clean_latents, + batched_clean_latent_indices, + batched_clean_latents_2x, + batched_clean_latent_2x_indices, + batched_clean_latents_4x, + batched_clean_latent_4x_indices, + section_to_video_idx, + ) + + +def get_pyramid_input( + args, + scheduler, + latents, # [b c t h w] + pyramid_stage_num=3, + pyramid_sample_ratios=[1, 2, 1], + pyramid_sample_mode="efficient", # ["efficient", "full", "diffusion_forcing", "stream_sample"] + pyramid_stream_inference_steps=[10, 10, 10], + stream_chunk_size=5, +): + assert pyramid_stage_num == len(pyramid_sample_ratios) + if pyramid_sample_mode not in ["efficient", "full", "diffusion_forcing", "stream_sample"]: + raise ValueError( + f"Invalid pyramid_sample_mode: {pyramid_sample_mode}. Must be one of ['efficient', 'full', 'diffusion_forcing', 'dance_forcing']." + ) + + # Get clen pyramid latent list + pyramid_latent_list = [] + pyramid_latent_list.append(latents) + num_frames, height, width = latents.shape[-3], latents.shape[-2], latents.shape[-1] + for _ in range(pyramid_stage_num - 1): + height //= 2 + width //= 2 + latents = rearrange(latents, "b c t h w -> (b t) c h w") + latents = torch.nn.functional.interpolate(latents, size=(height, width), mode="bilinear") + latents = rearrange(latents, "(b t) c h w -> b c t h w", t=num_frames) + pyramid_latent_list.append(latents) + pyramid_latent_list = list(reversed(pyramid_latent_list)) + + # Get pyramid noise list + noise = torch.randn_like(pyramid_latent_list[-1]) + device = noise.device + dtype = pyramid_latent_list[-1].dtype + latent_frame_num = noise.shape[2] + input_video_num = noise.shape[0] + + height, width = noise.shape[-2], noise.shape[-1] + noise_list = [noise] + cur_noise = noise + for i_s in range(pyramid_stage_num - 1): + height //= 2 + width //= 2 + cur_noise = rearrange(cur_noise, "b c t h w -> (b t) c h w") + cur_noise = F.interpolate(cur_noise, size=(height, width), mode="bilinear") * 2 + cur_noise = rearrange(cur_noise, "(b t) c h w -> b c t h w", t=latent_frame_num) + noise_list.append(cur_noise) + noise_list = list(reversed(noise_list)) # make sure from low res to high res + + # Get pyramid target list + if pyramid_sample_mode == "efficient": + assert input_video_num % (int(sum(pyramid_sample_ratios))) == 0 + # To calculate the padding batchsize and column size + bsz = input_video_num // int(sum(pyramid_sample_ratios)) + column_size = int(sum(pyramid_sample_ratios)) + column_to_stage = {} + i_sum = 0 + for i_s, column_num in enumerate(pyramid_sample_ratios): + for index in range(i_sum, i_sum + column_num): + column_to_stage[index] = i_s + i_sum += column_num + + # from low resolution to high resolution + noisy_latents_list = [] + sigmas_list = [] + targets_list = [] + timesteps_list = [] + training_steps = scheduler.config.num_train_timesteps + for index in range(column_size): + i_s = column_to_stage[index] + clean_latent = pyramid_latent_list[i_s][index::column_size] # [bs, c, t, h, w] + last_clean_latent = None if i_s == 0 else pyramid_latent_list[i_s - 1][index::column_size] + start_sigma = scheduler.start_sigmas[i_s] + end_sigma = scheduler.end_sigmas[i_s] + + if i_s == 0: + start_point = noise_list[i_s][index::column_size] + else: + # Get the upsampled latent + last_clean_latent = rearrange(last_clean_latent, "b c t h w -> (b t) c h w") + last_clean_latent = F.interpolate( + last_clean_latent, + size=( + last_clean_latent.shape[-2] * 2, + last_clean_latent.shape[-1] * 2, + ), + mode="nearest", + ) + last_clean_latent = rearrange(last_clean_latent, "(b t) c h w -> b c t h w", t=latent_frame_num) + start_point = start_sigma * noise_list[i_s][index::column_size] + (1 - start_sigma) * last_clean_latent + + if i_s == pyramid_stage_num - 1: + end_point = clean_latent + else: + end_point = end_sigma * noise_list[i_s][index::column_size] + (1 - end_sigma) * clean_latent + + # Sample a random timestep for each image + # for weighting schemes where we sample timesteps non-uniformly + u = compute_density_for_timestep_sampling( + weighting_scheme=get_config_value(args, 'weighting_scheme'), + batch_size=bsz, + logit_mean=get_config_value(args, 'logit_mean'), + logit_std=get_config_value(args, 'logit_std'), + mode_scale=get_config_value(args, 'mode_scale'), + ) + indices = (u * training_steps).long() # Totally 1000 training steps per stage + indices = indices.clamp(0, training_steps - 1) + timesteps = scheduler.timesteps_per_stage[i_s][indices].to(device=device) + + # Add noise according to flow matching. + # zt = (1 - texp) * x + texp * z1 + sigmas = scheduler.sigmas_per_stage[i_s][indices].to(device=device) + while len(sigmas.shape) < start_point.ndim: + sigmas = sigmas.unsqueeze(-1) + + noisy_latents = sigmas * start_point + (1 - sigmas) * end_point + + # [stage1_latent, stage2_latent, ..., stagen_latent], which will be concat after patching + noisy_latents_list.append([noisy_latents.to(dtype)]) + sigmas_list.append(sigmas.to(dtype)) + timesteps_list.append(timesteps.to(dtype)) + targets_list.append(start_point - end_point) # The standard rectified flow matching objective + elif pyramid_sample_mode == "full": + # To calculate the batchsize + bsz = input_video_num + + # from low resolution to high resolution + noisy_latents_list = [] + sigmas_list = [] + targets_list = [] + timesteps_list = [] + training_steps = scheduler.config.num_train_timesteps + for i_s, cur_sample_ratio in zip(range(pyramid_stage_num), pyramid_sample_ratios): + clean_latent = pyramid_latent_list[i_s] # [bs, c, t, h, w] + last_clean_latent = None if i_s == 0 else pyramid_latent_list[i_s - 1] + start_sigma = scheduler.start_sigmas[i_s] + end_sigma = scheduler.end_sigmas[i_s] + + if i_s == 0: + start_point = noise_list[i_s] + else: + # Get the upsampled latent + last_clean_latent = rearrange(last_clean_latent, "b c t h w -> (b t) c h w") + last_clean_latent = F.interpolate( + last_clean_latent, + size=( + last_clean_latent.shape[-2] * 2, + last_clean_latent.shape[-1] * 2, + ), + mode="nearest", + ) + last_clean_latent = rearrange(last_clean_latent, "(b t) c h w -> b c t h w", t=latent_frame_num) + start_point = start_sigma * noise_list[i_s] + (1 - start_sigma) * last_clean_latent + + if i_s == pyramid_stage_num - 1: + end_point = clean_latent + else: + end_point = end_sigma * noise_list[i_s] + (1 - end_sigma) * clean_latent + + for _ in range(cur_sample_ratio): + # Sample a random timestep for each image + # for weighting schemes where we sample timesteps non-uniformly + u = compute_density_for_timestep_sampling( + weighting_scheme=get_config_value(args, 'weighting_scheme'), + batch_size=bsz, + logit_mean=get_config_value(args, 'logit_mean'), + logit_std=get_config_value(args, 'logit_std'), + mode_scale=get_config_value(args, 'mode_scale'), + ) + indices = (u * training_steps).long() # Totally 1000 training steps per stage + indices = indices.clamp(0, training_steps - 1) + timesteps = scheduler.timesteps_per_stage[i_s][indices].to(device=device) + + # Add noise according to flow matching. + # zt = (1 - texp) * x + texp * z1 + sigmas = scheduler.sigmas_per_stage[i_s][indices].to(device=device) + while len(sigmas.shape) < start_point.ndim: + sigmas = sigmas.unsqueeze(-1) + + noisy_latents = sigmas * start_point + (1 - sigmas) * end_point + + # [stage1_latent, stage2_latent, ..., stagen_latent] + noisy_latents_list.append(noisy_latents.to(dtype)) + sigmas_list.append(sigmas.to(dtype)) + timesteps_list.append(timesteps.to(dtype)) + targets_list.append(start_point - end_point) # The standard rectified flow matching objective + elif pyramid_sample_mode == "diffusion_forcing": + # To calculate the batchsize + bsz = input_video_num + latent_chunk_num = latent_frame_num // stream_chunk_size + assert latent_frame_num % stream_chunk_size == 0 + + # from low resolution to high resolution + noisy_latents_list = [] + sigmas_list = [] + targets_list = [] + timesteps_list = [] + training_steps = scheduler.config.num_train_timesteps + for i_s, cur_sample_ratio in zip(range(pyramid_stage_num), pyramid_sample_ratios): + clean_latent = pyramid_latent_list[i_s] # [bs, c, t, h, w] + last_clean_latent = None if i_s == 0 else pyramid_latent_list[i_s - 1] + start_sigma = scheduler.start_sigmas[i_s] + end_sigma = scheduler.end_sigmas[i_s] + + if i_s == 0: + start_point = noise_list[i_s] + else: + # Get the upsampled latent + last_clean_latent = rearrange(last_clean_latent, "b c t h w -> (b t) c h w") + last_clean_latent = F.interpolate( + last_clean_latent, + size=( + last_clean_latent.shape[-2] * 2, + last_clean_latent.shape[-1] * 2, + ), + mode="nearest", + ) + last_clean_latent = rearrange(last_clean_latent, "(b t) c h w -> b c t h w", t=latent_frame_num) + start_point = start_sigma * noise_list[i_s] + (1 - start_sigma) * last_clean_latent + + if i_s == pyramid_stage_num - 1: + end_point = clean_latent + else: + end_point = end_sigma * noise_list[i_s] + (1 - end_sigma) * clean_latent + + for _ in range(cur_sample_ratio): + # Sample a random timestep for each image + # for weighting schemes where we sample timesteps non-uniformly + u = compute_density_for_timestep_sampling( + weighting_scheme=get_config_value(args, 'weighting_scheme'), + batch_size=bsz * latent_chunk_num, + logit_mean=get_config_value(args, 'logit_mean'), + logit_std=get_config_value(args, 'logit_std'), + mode_scale=get_config_value(args, 'mode_scale'), + ) + indices = (u * training_steps).long() # Totally 1000 training steps per stage + indices = indices.clamp(0, training_steps - 1) + + timesteps = scheduler.timesteps_per_stage[i_s][indices].to(device=device) + timesteps = timesteps.view(bsz, latent_chunk_num) # [bsz, latent_chunk_num] + sigmas = scheduler.sigmas_per_stage[i_s][indices].to(device=device) + sigmas = sigmas.view(bsz, latent_chunk_num) # [bsz, latent_chunk_num] + + chunk_index = ( + torch.arange(latent_frame_num, device=device).unsqueeze(0).expand(bsz, -1) // stream_chunk_size + ) + chunk_index = chunk_index.clamp(max=latent_chunk_num - 1) + sigmas = torch.gather(sigmas, 1, chunk_index) # [bsz, t] + timesteps = torch.gather(timesteps, 1, chunk_index) + + # Add noise according to flow matching. + # zt = (1 - texp) * x + texp * z1 + sigmas = ( + sigmas.unsqueeze(1).unsqueeze(-1).unsqueeze(-1) + ) # reshape to [bsz, 1, t, 1, 1] for broadcasting + noisy_latents = sigmas * start_point + (1 - sigmas) * end_point + + # [stage1_latent, stage2_latent, ..., stagen_latent] + noisy_latents_list.append(noisy_latents.to(dtype)) # torch.Size([2, 16, 10, 12, 20]) + sigmas_list.append(sigmas.to(dtype)) # torch.Size([2, 1, 10, 1, 1]) + timesteps_list.append(timesteps.to(dtype)) # torch.Size([2, 10]) + targets_list.append(start_point - end_point) # The standard rectified flow matching objective + elif pyramid_sample_mode == "stream_sample": + # training_all_progressive_timesteps + # skip 0. (1, max_inference_steps):[1.3850, 44.1200, 86.8550, 129.5900, 172.3250, + # 215.0600, 257.7950, 300.5300, 343.2650, 386.0000, + # 386.3580, 426.0960, 465.8340, 505.5720, 545.3100, + # 585.0480, 624.7860, 664.5240, 704.2620, 744.0000, + # 744.2560, 772.6720, 801.0880, 829.5040, 857.9200, + # 886.3360, 914.7520, 943.1680, 971.5840, 1000.0000] + + # progressive_timesteps_stages + # stream_chunk_size=3: + # [ 386., 386., 386., 744., 744., 744., 1000., 1000., 1000.] high, mid, low + # [343.2650, 343.2650, 343.2650, 704.2620, 704.2620, 704.2620, 971.5840, 971.5840, 971.5840] high, mid, low + # [300.5300, 300.5300, 300.5300, 664.5240, 664.5240, 664.5240, 943.1680, 943.1680, 943.1680] high, mid, low + # [257.7950, 257.7950, 257.7950, 624.7860, 624.7860, 624.7860, 914.7520, 914.7520, 914.7520] high, mid, low + # [215.0600, 215.0600, 215.0600, 585.0480, 585.0480, 585.0480, 886.3360, 886.3360, 886.3360] high, mid, low + # [172.3250, 172.3250, 172.3250, 545.3100, 545.3100, 545.3100, 857.9200, 857.9200, 857.9200] high, mid, low + # [129.5900, 129.5900, 129.5900, 505.5720, 505.5720, 505.5720, 829.5040, 829.5040, 829.5040] high, mid, low + # [ 86.8550, 86.8550, 86.8550, 465.8340, 465.8340, 465.8340, 801.0880, 801.0880, 801.0880] high, mid, low + # [ 44.1200, 44.1200, 44.1200, 426.0960, 426.0960, 426.0960, 772.6720, 772.6720, 772.6720] high, mid, low + # [ 1.3850, 1.3850, 1.3850, 386.3580, 386.3580, 386.3580, 744.2560, 744.2560, 744.2560] high, mid, low + + # stream_chunk_size=5, shape = (training_num_steps_to_be_saved, latent_frame_num): + # [545.3100, 545.3100, 545.3100, 545.3100, 545.3100, 1000.0000, 1000.0000, 1000.0000, 1000.0000, 1000.0000] mid, low + # [505.5720, 505.5720, 505.5720, 505.5720, 505.5720, 971.5840, 971.5840, 971.5840, 971.5840, 971.5840] mid, low + # [465.8340, 465.8340, 465.8340, 465.8340, 465.8340, 943.1680, 943.1680, 943.1680, 943.1680, 943.1680] mid, low + # [426.0960, 426.0960, 426.0960, 426.0960, 426.0960, 914.7520, 914.7520, 914.7520, 914.7520, 914.7520] mid, low + # [386.3580, 386.3580, 386.3580, 386.3580, 386.3580, 886.3360, 886.3360, 886.3360, 886.3360, 886.3360] mid, low + # [386.0000, 386.0000, 386.0000, 386.0000, 386.0000, 857.9200, 857.9200, 857.9200, 857.9200, 857.9200] high, low + # [343.2650, 343.2650, 343.2650, 343.2650, 343.2650, 829.5040, 829.5040, 829.5040, 829.5040, 829.5040] high, low + # [300.5300, 300.5300, 300.5300, 300.5300, 300.5300, 801.0880, 801.0880, 801.0880, 801.0880, 801.0880] high, low + # [257.7950, 257.7950, 257.7950, 257.7950, 257.7950, 772.6720, 772.6720, 772.6720, 772.6720, 772.6720] high, low + # [215.0600, 215.0600, 215.0600, 215.0600, 215.0600, 744.2560, 744.2560, 744.2560, 744.2560, 744.2560] high, low + # [172.3250, 172.3250, 172.3250, 172.3250, 172.3250, 744.0000, 744.0000, 744.0000, 744.0000, 744.0000] high, mid + # [129.5900, 129.5900, 129.5900, 129.5900, 129.5900, 704.2620, 704.2620, 704.2620, 704.2620, 704.2620] high, mid + # [ 86.8550, 86.8550, 86.8550, 86.8550, 86.8550, 664.5240, 664.5240, 664.5240, 664.5240, 664.5240] high, mid + # [ 44.1200, 44.1200, 44.1200, 44.1200, 44.1200, 624.7860, 624.7860, 624.7860, 624.7860, 624.7860] high, mid + # [ 1.3850, 1.3850, 1.3850, 1.3850, 1.3850, 585.0480, 585.0480, 585.0480, 585.0480, 585.0480] high, mid + + # To calculate the batchsize + bsz = input_video_num + + # Get multi stage timesteps for streamgen + ( + training_num_steps_to_be_saved, + training_all_timesteps_stage_ids, + training_all_progressive_timesteps, + progressive_timesteps_stages, + ) = get_stream_sample( + scheduler=scheduler, + max_latent_frame_num=latent_frame_num, + stream_chunk_size=stream_chunk_size, + pyramid_stage_num=pyramid_stage_num, + pyramid_stream_inference_steps=pyramid_stream_inference_steps, + ) + timestep_to_stage = { + float(t.item()): int(stage.item()) + for t, stage in zip(training_all_progressive_timesteps[0], training_all_timesteps_stage_ids[0]) + } + + while True: + initialization = random.choice([True, False]) + termination = random.choice([True, False]) + if not (initialization and termination): # Make sure not both are True + break + + stage_i = random.randint(0, training_num_steps_to_be_saved - 1) + timesteps = progressive_timesteps_stages[stage_i].clone().repeat(bsz, 1) # (b, f) + if initialization: # get the ending timesteps, [999]x5 from [91, 192, ..., 999]x5 + timesteps = timesteps[:, -latent_frame_num:] + elif termination: # get the starting timesteps, [91]x5 from [91, ..., 999]x5 + timesteps = timesteps[:, :latent_frame_num] + + # For stage mapping / Get sigmas + sigmas, stage_latent_mapping = get_sigmas_from_pyramid_timesteps(scheduler, timesteps, timestep_to_stage) + + # To device + timesteps = timesteps.to(device) + sigmas = sigmas.to(device) + + # Get pyramid stage points + stage_point_list = [] + for i_s in range(pyramid_stage_num): + clean_latent = pyramid_latent_list[i_s] # [bs, c, t, h, w] + last_clean_latent = None if i_s == 0 else pyramid_latent_list[i_s - 1] + start_sigma = scheduler.start_sigmas[i_s] + end_sigma = scheduler.end_sigmas[i_s] + + if i_s == 0: + start_point = noise_list[i_s] + else: + # Get the upsampled latent + last_clean_latent = rearrange(last_clean_latent, "b c t h w -> (b t) c h w") + last_clean_latent = F.interpolate( + last_clean_latent, + size=( + last_clean_latent.shape[-2] * 2, + last_clean_latent.shape[-1] * 2, + ), + mode="nearest", + ) + last_clean_latent = rearrange(last_clean_latent, "(b t) c h w -> b c t h w", t=latent_frame_num) + start_point = start_sigma * noise_list[i_s] + (1 - start_sigma) * last_clean_latent + + if i_s == pyramid_stage_num - 1: + end_point = clean_latent + else: + end_point = end_sigma * noise_list[i_s] + (1 - end_sigma) * clean_latent + + stage_point_list.append((start_point, end_point)) + + noisy_latents_list = [] # torch.Size([2, 16, 10, 12, 20]) + targets_list = [] # torch.Size([2, 16, 10, 12, 20]) + sigmas_list = [] # torch.Size([2, 1, 10, 1, 1]) + timesteps_list = [] # torch.Size([2, 10]) + temp_noisy_latents_list = [] + temp_targets_list = [] + + unique_elements = list(map(int, torch.unique(stage_latent_mapping))) + for cur_stage in reversed(unique_elements): + stage_indices = torch.nonzero(stage_latent_mapping == cur_stage, as_tuple=True) + start_index = stage_indices[1][0].item() + end_index = start_index + stream_chunk_size + + start_point, end_point = stage_point_list[cur_stage] + start_point_slice = start_point[:, :, start_index:end_index, :, :] + end_point_slice = end_point[:, :, start_index:end_index, :, :] + + sigmas_slice = sigmas[:, :, start_index:end_index, :, :] + noisy_latents = sigmas_slice * start_point_slice + (1 - sigmas_slice) * end_point_slice + target = start_point_slice - end_point_slice + + temp_noisy_latents_list.append(noisy_latents.to(dtype)) + temp_targets_list.append(target) + + noisy_latents_list.append(temp_noisy_latents_list) + targets_list.append(temp_targets_list) + sigmas_list.append(sigmas.to(dtype)) + timesteps_list.append(timesteps.to(dtype=dtype)) + + return noisy_latents_list, sigmas_list, timesteps_list, targets_list + + +def get_sigmas_from_pyramid_timesteps(scheduler, timesteps, timestep_to_stage): + # For stage mapping + flat_timesteps = timesteps.flatten() + stage_latent_mapping = torch.tensor( + [timestep_to_stage.get(float(t.item()), -1) for t in flat_timesteps], + device=timesteps.device, + ).view(timesteps.shape) + + # Get sigmas + sigmas = torch.full_like(timesteps, -1.0) + for i in range(timesteps.shape[0]): + for j in range(timesteps.shape[1]): + temp_stage_mapping = int(stage_latent_mapping[i, j]) + target_value = timesteps[i, j] + temp_indice = ( + ( + torch.isclose( + scheduler.timesteps_per_stage[temp_stage_mapping], + target_value.clone().detach().to(scheduler.timesteps_per_stage[temp_stage_mapping].dtype), + ) + ) + .nonzero(as_tuple=True)[0] + .item() + ) + sigmas[i, j] = scheduler.sigmas_per_stage[temp_stage_mapping][temp_indice] + sigmas = sigmas.unsqueeze(1).unsqueeze(-1).unsqueeze(-1) + + return sigmas, stage_latent_mapping + + +def get_stream_sample( + scheduler, + max_latent_frame_num, + stream_chunk_size, + pyramid_stage_num=3, + pyramid_stream_inference_steps=[10, 10, 10], +): + max_inference_steps = sum(pyramid_stream_inference_steps) + + # Set training all progressive timesteps and stage mapping + all_progressive_timesteps_list = [] + timestep_stage_list = [] + for stage_idx in range(pyramid_stage_num): + scheduler.set_timesteps(pyramid_stream_inference_steps[stage_idx], stage_idx) + temp_timesteps = scheduler.timesteps # shape: (n_i,) + all_progressive_timesteps_list.append(temp_timesteps) + timestep_stage_list.append( + torch.full_like(temp_timesteps, fill_value=stage_idx) + ) # same shape, filled with stage_idx + all_progressive_timesteps = torch.cat(all_progressive_timesteps_list).unsqueeze(0).flip(1) # (1, T) + all_timesteps_stage_ids = torch.cat(timestep_stage_list).unsqueeze(0).flip(1) + + # Set training progressive timesteps stages + # every stream_chunk_size frames is treated as one, using the same noise level. f' = f / c + assert max_latent_frame_num % stream_chunk_size == 0, ( + f"num_frames should be multiple of stream_chunk_size, {max_latent_frame_num} % {stream_chunk_size} != 0" + ) + assert max_inference_steps % (max_latent_frame_num // stream_chunk_size) == 0, ( + f"max_inference_steps should be multiple of max_latent_frame_num // stream_chunk_size, {max_inference_steps} % {max_latent_frame_num // stream_chunk_size} != 0" + ) + num_steps_to_be_saved = max_inference_steps // ( + max_latent_frame_num // stream_chunk_size + ) # every m steps, save stream_chunk_size frames. m = t / f' = t / (f / c) = c * (t / f) + + # (b, t) -> [(b, t / m) in reverse range(m)] -> [(b, f) in reverse range(m)] + progressive_timesteps_stages = [ + repeat( + all_progressive_timesteps[:, (num_steps_to_be_saved - 1) - s :: num_steps_to_be_saved], + "b f -> b f c", + c=stream_chunk_size, + ).flatten(1, 2) + for s in range(num_steps_to_be_saved) + ] + + return num_steps_to_be_saved, all_timesteps_stage_ids, all_progressive_timesteps, progressive_timesteps_stages + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Simple example of a training script.") + parser.add_argument( + "--weighting_scheme", + type=str, + default="logit_normal", + choices=["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"], + help=('We default to the "none" weighting scheme for uniform sampling and uniform loss'), + ) + parser.add_argument( + "--logit_mean", + type=float, + default=0.0, + help="mean to use when using the `'logit_normal'` weighting scheme.", + ) + parser.add_argument( + "--logit_std", + type=float, + default=1.0, + help="std to use when using the `'logit_normal'` weighting scheme.", + ) + parser.add_argument( + "--mode_scale", + type=float, + default=1.29, + help="Scale of mode weighting scheme. Only effective when using the `'mode'` as the `weighting_scheme`.", + ) + args = parser.parse_args() + + device = "cuda" + + import sys + + sys.path.append("../") + from scheduler.scheduling_flow_matching_pyramid import PyramidFlowMatchEulerDiscreteScheduler + + stages = [1, 2, 4] + timestep_shift = 1.0 + stage_range = [0, 1 / 3, 2 / 3, 1] + scheduler_gamma = 1 / 3 + scheduler = PyramidFlowMatchEulerDiscreteScheduler( + shift=timestep_shift, + stages=len(stages), + stage_range=stage_range, + gamma=scheduler_gamma, + ) + print( + f"The start sigmas and end sigmas of each stage is Start: {scheduler.start_sigmas}, End: {scheduler.end_sigmas}, Ori_start: {scheduler.ori_start_sigmas}" + ) + + # Test get_framepack_input + from diffusers import AutoencoderKLHunyuanVideo + + # 5: (21, 41, 61, 81, 101) + # 6: (25, 49, 73, 97, 121) + # 7: (29, 57, 85, 113, 141) + # 8: (33, 65, 97, 129, 161) + # 9: (37, 73, 109, 145, 181) + # 10: (41, 81, 121, 161, 201) + # 11: (45, 89, 133, 177, 221) + # 12: (49, 97, 145, 193, 241) + + pixel_values = torch.randn([2, 3, 241, 384, 640], device=device).clamp(-1, 1) + pixel_values = pixel_values.to(torch.bfloat16) + vae = AutoencoderKLHunyuanVideo.from_pretrained( + "/mnt/workspace/checkpoints/hunyuanvideo-community/HunyuanVideo/", + subfolder="vae", + weight_dtype=torch.bfloat16, + ).to(device) + vae.requires_grad_(False) + vae.eval() + + ( + model_input, # torch.Size([2, 16, 9, 60, 104]) + indices_latents, # torch.Size([2, 9]) + latents_clean, # torch.Size([2, 16, 2, 60, 104]) + indices_clean_latents, # torch.Size([2, 2]) + latents_history_2x, # torch.Size([2, 16, 2, 60, 104]) + indices_latents_history_2x, # torch.Size([2, 2]) + latents_history_4x, # torch.Size([2, 16, 16, 60, 104]) + indices_latents_history_4x, # torch.Size([2, 16]) + section_to_video_idx, + ) = get_framepack_input_i2v( + vae=vae, + pixel_values=pixel_values, # torch.Size([1, 3, 73, 480, 832]) + latent_window_size=12, + vanilla_sampling=False, + dtype=torch.bfloat16, + ) + + print(indices_latents, "\n", indices_clean_latents, "\n", indices_latents_history_2x, "\n", indices_latents_history_4x) + + # print( + # indices_latents, + # "\n", + # indices_clean_latents, + # "\n", + # indices_latents_history_2x, + # "\n", + # indices_latents_history_4x, + # ) + + # Test get_pyramid_input + # model_input = torch.randn([2, 16, 10, 48, 80], device=device) + # noisy_model_input_list, sigmas_list, timesteps_list, targets_list = get_pyramid_input( + # args=args, + # scheduler=scheduler, + # latents=model_input, + # pyramid_stage_num=3, + # pyramid_sample_ratios=[1, 2, 1], + # pyramid_sample_mode="stream_sample", + # stream_chunk_size=3, + # pyramid_stream_inference_steps=[10, 10, 10], + # ) + + # if isinstance(noisy_model_input_list[0], list): + # total_sample_count = sum(y.shape[0] for x in noisy_model_input_list for y in x) + # else: + # total_sample_count = sum(x.shape[0] for x in noisy_model_input_list) + # batch_size = model_input.shape[0] diff --git a/dataset_code/sft_sftnews/offload/yyy_dummy.yaml b/dataset_code/sft_sftnews/offload/yyy_dummy.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0c72e22be0161664169c2a7f933c2bb49f7f8a2c --- /dev/null +++ b/dataset_code/sft_sftnews/offload/yyy_dummy.yaml @@ -0,0 +1,1867 @@ +# seedv2-t2i is a image datasets +# albatross_1, albatross_2: seems to be outdoor sports related videos (skydiving, ski, bouldering etc) +# 1 image dataset, 54 video datasets +# train_data: [ 'seedv2-t2i', '123rf', 'albatross_1', 'albatross_2','budgie_1', 'budgie_2', 'canary_1', 'canary_2', 'condor_1', 'condor_2', 'falcon', 'filmsupply_highres', +# 'guillemot_1', 'guillemot_2', 'guillemot_3', 'guillemot_4', 'gull_1', 'gull_2', 'harrier_1', 'harrier_2', 'hdvg', 'hornbill_1', 'hornbill_2', 'hummingbird_1', 'hummingbird_2', +# 'kingfisher', 'lovebird', 'macaw_1', 'macaw_2', 'movie_1', 'movie_2', 'panda70m', 'partridge_1', 'partridge_2', 'partridge_3', 'partridge_4', 'petrel_1', 'petrel_2', 'pigeon_1', 'pigeon_2', +# 'pond5', 'puffin_1', 'puffin_2', 'swallow_1', 'swallow_2', 'vimeo_1', 'vimeo_2', 'vimeo_3', 'vimeo_4', 'warbler_1', 'warbler_2', 'wren_1', 'wren_2'] # 256px Train data path +# train_data_weights: [13, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # Train data weights, image:video = 1:4 + +# 1 image dataset, 29 video datasets +# train_data: [ 'seedv2-t2i', 'albatross_2', 'budgie_1', 'budgie_2', 'canary_2', 'condor_2', 'falcon', 'filmsupply_highres', 'guillemot_2', 'guillemot_4', 'gull_2', 'harrier_2', 'hdvg', 'hornbill_2', 'hummingbird_2', 'kingfisher', 'lovebird', +# 'macaw_2', 'movie_2', 'panda70m', 'partridge_2', 'partridge_4', 'petrel_2', 'pigeon_2', 'puffin_2', 'swallow_2', 'vimeo_2', 'vimeo_4', 'warbler_2', 'wren_2'] # 512px Train data path +# train_data_weights: [7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # Train data weights, image:video = 1:4 + +# 123rf xiaobao pond5 + +# train_data: ['albatross_2', 'budgie_1', 'budgie_2', 'canary_2', 'condor_2', 'falcon', 'filmsupply_highres', 'guillemot_2', 'guillemot_4', 'gull_2', 'harrier_2', 'hdvg', 'hornbill_2', 'hummingbird_2', 'kingfisher', 'lovebird', +# 'macaw_2', 'movie_2', 'panda70m', 'partridge_2', 'partridge_4', 'petrel_2', 'pigeon_2', 'puffin_2', 'swallow_2', 'vimeo_2', 'vimeo_4', 'warbler_2', 'wren_2'] # 512px Train data path +# train_data_weights: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # Train data weights, image:video = 1:4 + +# train_data: ['123rf'] # 512px Train data path , 'xiaobao', 'pond5' +# train_data: ['xiaobao'] +#123rf 2075933 +#pond5 5270119 + +# train_data: ['pond5','123rf'] +# train_data_weights: [1,1] +train_data: ['pond5'] +train_data_weights: [1] + +# #### image data #### +# seedv2-t2i +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/seed_t2i/kexuanyi/data/train_data/pretrained_data/kv/v2.0/pretrained_en/v2.0_data_512_src_data + +# #### original video data #### +# nexdata0 +# hdfs://harunava/home/byte_ailab_us_cvg/user/cma/video_gen/data_pipeline/nexdata/stage4/processing_parquet_out_merged/world_size_1/ + +# xiaobao +# hdfs://harunava/home/byte_ailab_us_cvg/user/cma/video_gen/data_pipeline/graydata_xiaobao_video_20241209/final_passed_whole_20241222/world_size_1000 + +# vulture +# hdfs://harunasg/home/byte_data_tt_m/warehouse/content_ecom.db/video_gen/dataset/vulture + +# 123rf +# /mnt/bn/icvg/video_gen/captions/123rf_res/123rf_data_res.json + +# hdvg +# hdfs://harunasg/home/byte_data_tt_m/warehouse/content_ecom.db/video_gen/dataset/base-stage-2/hdvg/v1/data/ + +# pond5 +# /mnt/bn/icvg/video_gen/captions/pond5_res/pond5_data_res.json + +# panda70m +# hdfs://harunasg/home/byte_data_tt_m/warehouse/content_ecom.db/video_gen/dataset/base-stage-2/panda70m/v1/data/ + +# #### new video data #### +# albatross +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/albatross/2024-10-10-05-40-01/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/albatross/2024-10-11-04-44-59/data + +# budgie +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/budgie/p2/2024-10-11-04-42-30/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/budgie/p3/2024-10-11-04-43-39/data + +# canary +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/canary/2024-10-10-05-40-25/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/canary/2024-10-11-04-44-41/data + +# condor +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/condor/2024-10-10-05-41-37/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/condor/2024-10-11-04-45-40/data + +# falcon +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/falcon/2024-10-11-04-44-18/data + +# filmsupply_highres +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/filmsupply_highres/2024-10-11-04-43-38/data + +# guillemot +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/guillemot/p1/2024-10-10-05-40-24/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/guillemot/p1/2024-10-11-04-45-38/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/guillemot/p2/2024-10-10-05-40-36/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/guillemot/p2/2024-10-11-04-45-41/data + +# gull +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/gull/2024-10-10-05-39-41/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/gull/2024-10-11-04-43-41/data + +# harrier +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/harrier/2024-10-10-05-41-40/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/harrier/2024-10-11-04-45-41/data + +# hornbill +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/hornbill/2024-10-10-05-40-53/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/hornbill/2024-10-11-04-46-51/data + +# hummingbird +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/hummingbird/2024-10-10-05-39-30/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/hummingbird/2024-10-11-04-43-38/data + +# kingfisher +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/kingfisher/2024-10-11-04-44-18/data + +# lovebird +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/lovebird/2024-10-11-04-44-18/data + +# macaw +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/macaw/2024-10-10-05-40-29/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/macaw/2024-10-11-04-43-38/data + +# movie +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/movie/2024-10-10-05-40-40/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/movie/2024-10-11-04-44-40/data + +# partridge +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/partridge/p1/2024-10-10-07-14-43/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/partridge/p1/2024-10-11-04-49-38/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/partridge/p2/2024-10-10-20-08-27/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/partridge/p2/2024-10-11-04-47-38/data + +# petrel +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/petrel/2024-10-10-05-41-55/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/petrel/2024-10-11-04-45-52/data + +# pheasant +# No data!!! + +# pigeon +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/pigeon/2024-10-10-05-40-25/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/pigeon/2024-10-11-04-45-39/data + +# puffin +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/puffin/2024-10-10-05-40-41/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/puffin/2024-10-11-04-45-44/data + +# swallow +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/swallow/2024-10-10-07-09-33/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/swallow/2024-10-11-04-45-13/data + +# vimeo +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/vimeo/2024-10-10-05-49-07/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/vimeo/2024-10-11-04-45-19/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/vimeo/p3/2024-10-10-05-49-53/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/vimeo/p3/2024-10-11-04-46-50/data + +# warbler +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/warbler/2024-10-10-05-40-37/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/warbler/2024-10-11-04-43-41/data + +# wren +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/wren/2024-10-10-05-43-46/data +# hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/wren/2024-10-11-04-46-40/data + +data: + params: + batch_size: 1 # the real batch size + image_batch_size: 16 # real image batch size + enable_bucket: True + dataset_collections: # list all available datasets + seedv2-t2i: + target: training.dataset_tool.T2IHDFSDataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/seed_t2i/kexuanyi/data/train_data/pretrained_data/kv/v2.0/pretrained_en/v2.0_data_512_src_data" + aspect_ratios: + "i-256p-3.0": [768,256] + "i-320p-2.4": [768, 320] + "i-320p-2.2": [704, 320] + "i-384p-2.0": [768, 384] + "i-384p-1.67": [640, 384] + "i-512p-1.5": [768, 512] + "i-448p-1.29": [576, 448] + "i-512p-1.0": [512, 512] + "i-448p-0.78": [448, 576] + "i-512p-0.67": [512, 768] + "i-384p-0.6": [384, 640] + "i-384p-0.5": [384, 768] + "i-320p-0.45": [320, 704] + "i-320p-0.42": [320, 768] + "i-256p-0.33": [256, 768] + # # default buckets + # "i-256p-0.33": [256, 768] + # "i-320p-0.42": [320, 768] + # "i-320p-0.45": [320, 704] + # "i-384p-0.6": [384, 640] + # "i-448p-0.78": [448, 576] + # "i-512p-1.0": [512, 512] + # "i-448p-1.29": [576, 448] + # "i-384p-1.67": [640, 384] + # "i-320p-2.2": [704, 320] + # "i-320p-2.4": [768, 320] + # "i-256p-3.0": [768, 256] + # 256px buckets for image, if use this config, need to set the params.resolution to 256 + # "i-256p-0.33": [128, 384] + # "i-256p-0.4": [128, 320] + # "i-256p-0.6": [192, 320] + # "i-256p-0.75": [192, 256] + # "i-256p-1.0": [256, 256] + # "i-256p-1.33": [256, 192] + # "i-256p-1.67": [320, 192] + # "i-256p-2.5": [320, 128] + # "i-256p-3.0": [384, 128] + ratio_strategy: closest + params: + resolution: 512 + debug: False + caption_key: ["english_caption_qwenllm_v1_emb_dict", "english_caption_qwenllm_v2_emb_dict", "qwenllm_v2.0_orig_caption_emb_dict"] # priority to use the first two, and use the original caption with a low probability + aspect_ratios: + "i-256p-0.33": [256, 768] + "i-320p-0.42": [320, 768] + "i-320p-0.45": [320, 704] + "i-384p-0.6": [384, 640] + "i-448p-0.78": [448, 576] + "i-512p-1.0": [512, 512] + "i-448p-1.29": [576, 448] + "i-384p-1.67": [640, 384] + "i-320p-2.2": [704, 320] + "i-320p-2.4": [768, 320] + "i-256p-3.0": [768, 256] + 123rf: + target: training.dataset_tool.T2VHDFSDataset + path: "/mnt/bn/wanyangyue-va/yinyuanyang/WanX/123rf_data_res.json" + aspect_ratios: + # "320p-2.4": [768, 320] + # "384p-2.0": [768, 384] + # "512p-1.5": [768, 512] + # "448p-1.29": [576, 448] + # "512p-1.0": [512, 512] + # "448p-0.78": [448, 576] + # "512p-0.67": [512, 768] + # "384p-0.5": [384, 768] + # "320p-0.42": [320, 768] + "480p-0.58": [480, 832] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 16 + sample_n_frames: 81 + sample_stride: 1 + hdvg: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_data_tt_m/warehouse/content_ecom.db/video_gen/dataset/base-stage-2/hdvg/v1/data/" + aspect_ratios: + # "320p-2.4": [768, 320] + # "384p-2.0": [768, 384] + # "512p-1.5": [768, 512] + # "448p-1.29": [576, 448] + # "512p-1.0": [512, 512] + # "448p-0.78": [448, 576] + # "512p-0.67": [512, 768] + # "384p-0.5": [384, 768] + # "320p-0.42": [320, 768] + "480p-0.58": [480, 832] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 16 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 81 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + panda70m: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_data_tt_m/warehouse/content_ecom.db/video_gen/dataset/base-stage-2/panda70m/v1/data/" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + pond5: + target: training.dataset_tool.T2VHDFSDataset + # path: "/mnt/bn/wanyangyue-va/yinyuanyang/WanX/pond5_data_res.json" + path: "/mnt/bn/wanyangyue-va/yinyuanyang/WanX/recaptions/pond5_shortcaptions_2.json" + # path: "/mnt/bn/wanyangyue-va/yinyuanyang/WanX/recaptions/pond5_human.json" + aspect_ratios: + # "320p-2.4": [768, 320] + # "384p-2.0": [768, 384] + # "512p-1.5": [768, 512] + # "448p-1.29": [576, 448] + # "512p-1.0": [512, 512] + # "448p-0.78": [448, 576] + # "512p-0.67": [512, 768] + # "384p-0.5": [384, 768] + # "320p-0.42": [320, 768] + "480p-0.58": [480, 832] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 16 + sample_n_frames: 81 + sample_stride: 1 + xiaobao: + target: training.dataset_tool.d + path: "hdfs://harunava/home/byte_ailab_us_cvg/user/cma/video_gen/data_pipeline/graydata_xiaobao_video_20241209/final_passed_whole_20241222/world_size_1000" + aspect_ratios: + # "320p-2.4": [768, 320] + # "384p-2.0": [768, 384] + # "512p-1.5": [768, 512] + # "448p-1.29": [576, 448] + # "512p-1.0": [512, 512] + # "448p-0.78": [448, 576] + # "512p-0.67": [512, 768] + # "384p-0.5": [384, 768] + # "320p-0.42": [320, 768] + "480p-0.58": [480, 832] + ratio_strategy: random + params: + caption_path: '' # extra caption file, used for seed dataset + caption_key: 'caption_short' # the key stores caption + sample_size: -1 # set to -1 to keep the original resolution + fps: 16 + sample_n_frames: 81 + sample_stride: 2 + parquet_batch: 128 + video_toskey: 'clip_toskey' + bytes_key: 'bytes' + decode_backend: 'pyav' # imageio pyav + vulture: + target: training.dataset_tool.AIPVideoDataset + path: "hdfs://harunasg/home/byte_data_tt_m/warehouse/content_ecom.db/video_gen/dataset/vulture/v1/data/" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + caption_path: 'hdfs://harunasg/home/byte_data_tt_m/warehouse/content_ecom.db/video_gen/dataset/v2/vulture/vulture_data_res.json' + caption_key: 'caption' # the key stores caption + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + sample_n_frames: 17 + sample_stride: 2 + parquet_batch: 128 + video_toskey: '' + bytes_key: 'video' + decode_backend: 'pyav' # imageio pyav + albatross_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/albatross/2024-10-10-05-40-01/data" + # old_path: "hdfs://harunasg/home/byte_data_tt_m/VGFM/data/packed/vae-1011/albatross/2024-10-10-05-40-01/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + albatross_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/albatross/2024-10-11-04-44-59/data" + # old_path: "hdfs://harunasg/home/byte_data_tt_m/VGFM/data/packed/vae-1011/albatross/2024-10-11-04-44-59/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + budgie_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/budgie/p2/2024-10-11-04-42-30/data" + #old_path: "hdfs://harunasg/home/byte_data_tt_m/VGFM/data/packed/vae-1011/budgie/p2/2024-10-11-04-42-30/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + budgie_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/budgie/p3/2024-10-11-04-43-39/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + canary_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/canary/2024-10-10-05-40-25/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + canary_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/canary/2024-10-11-04-44-41/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + condor_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/condor/2024-10-10-05-41-37/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + condor_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/condor/2024-10-11-04-45-40/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + falcon: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/falcon/2024-10-11-04-44-18/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + filmsupply_highres: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/filmsupply_highres/2024-10-11-04-43-38/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + guillemot_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/guillemot/p1/2024-10-10-05-40-24/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + guillemot_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/guillemot/p1/2024-10-11-04-45-38/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + guillemot_3: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/guillemot/p2/2024-10-10-05-40-36/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + guillemot_4: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/guillemot/p2/2024-10-11-04-45-41/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + gull_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/gull/2024-10-10-05-39-41/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + gull_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/gull/2024-10-11-04-43-41/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + harrier_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/harrier/2024-10-10-05-41-40/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + harrier_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/harrier/2024-10-11-04-45-41/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + hornbill_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/hornbill/2024-10-10-05-40-53/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + hornbill_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/hornbill/2024-10-11-04-46-51/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + hummingbird_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/hummingbird/2024-10-10-05-39-30/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + hummingbird_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/hummingbird/2024-10-11-04-43-38/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + kingfisher: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/kingfisher/2024-10-11-04-44-18/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + lovebird: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/lovebird/2024-10-11-04-44-18/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + macaw_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/macaw/2024-10-10-05-40-29/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + macaw_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/macaw/2024-10-11-04-43-38/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + movie_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/movie/2024-10-10-05-40-40/data" + aspect_ratios: + # "320p-2.4": [768, 320] + # "384p-2.0": [768, 384] + # "512p-1.5": [768, 512] + # "448p-1.29": [576, 448] + # "512p-1.0": [512, 512] + # "448p-0.78": [448, 576] + # "512p-0.67": [512, 768] + # "384p-0.5": [384, 768] + # "320p-0.42": [320, 768] + "480p-0.58": [480, 832] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 16 #24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 81 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + movie_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/movie/2024-10-11-04-44-40/data" + aspect_ratios: + # "320p-2.4": [768, 320] + # "384p-2.0": [768, 384] + # "512p-1.5": [768, 512] + # "448p-1.29": [576, 448] + # "512p-1.0": [512, 512] + # "448p-0.78": [448, 576] + # "512p-0.67": [512, 768] + # "384p-0.5": [384, 768] + # "320p-0.42": [320, 768] + "480p-0.58": [480, 832] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 16 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 81 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + partridge_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/partridge/p1/2024-10-10-07-14-43/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + partridge_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/partridge/p1/2024-10-11-04-49-38/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + partridge_3: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/partridge/p2/2024-10-10-20-08-27/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + partridge_4: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/partridge/p2/2024-10-11-04-47-38/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + petrel_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/petrel/2024-10-10-05-41-55/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + petrel_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/petrel/2024-10-11-04-45-52/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + pigeon_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/pigeon/2024-10-10-05-40-25/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + pigeon_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/pigeon/2024-10-11-04-45-39/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + puffin_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/puffin/2024-10-10-05-40-41/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + puffin_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/puffin/2024-10-11-04-45-44/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + swallow_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/swallow/2024-10-10-07-09-33/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + swallow_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/swallow/2024-10-11-04-45-13/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + vimeo_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/vimeo/2024-10-10-05-49-07/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + vimeo_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/vimeo/2024-10-11-04-45-19/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + vimeo_3: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/vimeo/p3/2024-10-10-05-49-53/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + vimeo_4: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/vimeo/p3/2024-10-11-04-46-50/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + warbler_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/warbler/2024-10-10-05-40-37/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + warbler_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/warbler/2024-10-11-04-43-41/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + wren_1: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/wren/2024-10-10-05-43-46/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 + wren_2: + target: training.dataset_tool.SeedV1Dataset + path: "hdfs://harunasg/home/byte_icvg_aigc_cp/user/video/temp/19900101/packed/vae-1011/wren/2024-10-11-04-46-40/data" + aspect_ratios: + "320p-2.4": [768, 320] + "384p-2.0": [768, 384] + "512p-1.5": [768, 512] + "448p-1.29": [576, 448] + "512p-1.0": [512, 512] + "448p-0.78": [448, 576] + "512p-0.67": [512, 768] + "384p-0.5": [384, 768] + "320p-0.42": [320, 768] + ratio_strategy: random + params: + sample_size: -1 # set to -1 to keep the original resolution + fps: 24 + num_parallel_files: 2 + video_frame_sampler: + type: 'adaptive_advanced' + strategies: + - stride: 2 + stride_prob: 1.0 + frame_lengths: [ 17 ] + frame_lengths_prob: 'harmonic' + clip: 'uniform' + text_sampler: + type: 'frequency' + frequency: + recaption_7B_: 1.0 + origin_title: 0.0 \ No newline at end of file diff --git a/dataset_code/spatialvid/add_config_old.py b/dataset_code/spatialvid/add_config_old.py new file mode 100644 index 0000000000000000000000000000000000000000..b54b7b2a754610277bba287de49bc976f57830fc --- /dev/null +++ b/dataset_code/spatialvid/add_config_old.py @@ -0,0 +1,117 @@ +import pandas as pd + +length_bucket_options = { + 1: [321, 301, 281, 261, 241, 221, 193, 181, 161, 141, 121, 101, 81, 61, 41, 21], + 2: [193, 177, 161, 156, 145, 133, 129, 121, 113, 109, 97, 85, 81, 73, 65, 61, 49, 37, 25], +} + +def find_nearest_length_bucket(length, stride=1): + buckets = length_bucket_options[stride] + min_bucket = min(buckets) + if length < min_bucket: + return length + valid_buckets = [bucket for bucket in buckets if bucket <= length] + return max(valid_buckets) + +def split_long_videos(df, stride=1, skip_frames=0, overlap=0): + """ + 将长视频分割成多个段,充分利用所有帧 + + Args: + df: 输入DataFrame + stride: bucket选择的stride参数 + skip_frames: 跳过开头的帧数 + overlap: 段之间的重叠帧数,默认为0 + """ + result_rows = [] + max_bucket = max(length_bucket_options[stride]) + + for idx, row in df.iterrows(): + num_frames = row['num frames'] + + if num_frames <= max_bucket: + # 短视频,直接处理 + new_row = row.copy() + new_row['start_frame'] = skip_frames + bucket_length = find_nearest_length_bucket(num_frames - skip_frames, stride) + new_row['end_frame'] = skip_frames + bucket_length + new_row['segment_id'] = 0 + result_rows.append(new_row) + else: + # 长视频,分割成多个段 + available_frames = num_frames - skip_frames + step_size = max_bucket - overlap + segment_count = 0 + + start_pos = skip_frames + while start_pos < num_frames: + remaining_frames = num_frames - start_pos + + # 如果剩余帧数小于最小bucket,跳过 + if remaining_frames < min(length_bucket_options[stride]): + break + + new_row = row.copy() + new_row['start_frame'] = start_pos + + # 计算这个段的长度 + segment_length = min(remaining_frames, max_bucket) + bucket_length = find_nearest_length_bucket(segment_length, stride) + new_row['end_frame'] = start_pos + bucket_length + new_row['segment_id'] = segment_count + + result_rows.append(new_row) + + # 移动到下一个段的起始位置 + start_pos += step_size + segment_count += 1 + + # 如果剩余帧数不足以形成新段,退出 + if start_pos + min(length_bucket_options[stride]) > num_frames: + break + + return pd.DataFrame(result_rows) + +def add_frame_range_with_segments(csv_path, output_path=None, stride=1, skip_frames=0, overlap=0): + """ + 为CSV添加start_frame和end_frame列,并将长视频分割成多个段 + + Args: + csv_path: 输入CSV文件路径 + output_path: 输出CSV文件路径,如果为None则覆盖原文件 + stride: bucket选择的stride参数 + skip_frames: 跳过开头的帧数,默认为0 + overlap: 段之间的重叠帧数,默认为0 + """ + # 读取CSV + df = pd.read_csv(csv_path) + + # 分割长视频并添加帧范围 + result_df = split_long_videos(df, stride, skip_frames, overlap) + + # 保存结果 + if output_path is None: + output_path = csv_path + result_df.to_csv(output_path, index=False) + + return result_df + +# 使用示例 +if __name__ == "__main__": + # 示例1: 基本用法,无重叠 + input_csv = '/mnt/bn/yufan-dev-my/ysh/Ckpts/SpatialVID/SpatialVID-HQ/data/train/SpatialVID_HQ_metadata.csv' # 替换为你的输入文件名 + output_csv = 'test.csv' + df = add_frame_range_with_segments(input_csv, output_csv, stride=1, skip_frames=11, overlap=0) + + # 示例2: 带重叠,确保段之间的连续性 + # df = add_frame_range_with_segments('your_file.csv', 'output.csv', stride=1, skip_frames=0, overlap=20) + + # 示例3: 使用stride=2的bucket + # df = add_frame_range_with_segments('your_file.csv', 'output.csv', stride=2, skip_frames=5, overlap=10) + + # 打印结果统计 + print(f"原始行数可能更少,处理后行数: {len(df)}") + print(f"分段统计:") + print(df['segment_id'].value_counts().sort_index()) + print("\n前几行示例:") + print(df.head(10)) \ No newline at end of file diff --git a/dataset_code/spatialvid/add_config_step0.py b/dataset_code/spatialvid/add_config_step0.py new file mode 100644 index 0000000000000000000000000000000000000000..1850ce1117c9cf8643fa1bbdb79b57c5d1cfe820 --- /dev/null +++ b/dataset_code/spatialvid/add_config_step0.py @@ -0,0 +1,243 @@ +import pandas as pd +import cv2 +import os +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor, as_completed +from threading import Lock +import time +import ffmpeg + +class VideoProcessor: + def __init__(self, max_workers=4): + self.max_workers = max_workers + self.progress_lock = Lock() + self.processed_count = 0 + self.total_count = 0 + + # def get_video_properties(self, video_path): + # """ + # 获取视频的基本属性:高度、宽度、帧率 + + # Args: + # video_path (str): 视频文件路径 + + # Returns: + # tuple: (height, width, fps) 或 (None, None, None) 如果读取失败 + # """ + # try: + # # 打开视频文件 + # cap = cv2.VideoCapture(video_path) + + # if not cap.isOpened(): + # return None, None, None + + # # 获取视频属性 + # num_frame = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + # width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + # height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + # fps = cap.get(cv2.CAP_PROP_FPS) + + # # 释放视频捕获对象 + # cap.release() + + # return num_frame, height, width, fps + + # except Exception as e: + # print(f"读取视频 {video_path} 时出错: {str(e)}") + # return None, None, None + + def get_video_properties(self, video_path): + try: + probe = ffmpeg.probe(video_path) + video_stream = next((stream for stream in probe['streams'] + if stream['codec_type'] == 'video'), None) + + if not video_stream: + return None, None, None, None + + width = int(video_stream['width']) + height = int(video_stream['height']) + fps = eval(video_stream['r_frame_rate']) + + if 'nb_frames' in video_stream: + num_frames = int(video_stream['nb_frames']) + else: + duration = float(probe['format']['duration']) + num_frames = int(duration * fps) + + return num_frames, height, width, fps + + except Exception as e: + print(f"读取视频 {video_path} 时出错: {str(e)}") + return None, None, None, None + + def process_single_video(self, args): + """ + 处理单个视频文件 + + Args: + args: (idx, video_file, video_dir) + + Returns: + tuple: (idx, num_frame, height, width, fps, success, message) + """ + idx, video_file, video_dir = args + video_path = os.path.join(video_dir, video_file) + + # 检查视频文件是否存在 + if not os.path.exists(video_path): + message = f"视频文件不存在: {video_path}" + return idx, None, None, None, None, False, message + + # 获取视频属性 + num_frame, height, width, fps = self.get_video_properties(video_path) + + # 更新进度 + with self.progress_lock: + self.processed_count += 1 + progress = (self.processed_count / self.total_count) * 100 + + if height is not None: + message = f"[{self.processed_count}/{self.total_count}] ({progress:.1f}%) {video_file} → {num_frame}, {width}x{height}, {fps:.2f}fps" + success = True + fps = round(fps, 2) + else: + message = f"[{self.processed_count}/{self.total_count}] ({progress:.1f}%) {video_file} → 获取信息失败" + success = False + + print(message) + + return idx, num_frame, height, width, fps, success, message + + def process_video_csv(self, csv_path, video_dir="./", output_csv_path=None, max_workers=None): + # """ + # 多线程处理CSV文件,添加视频的height、width、fps信息 + + # Args: + # csv_path (str): 输入CSV文件路径 + # video_dir (str): 视频文件所在目录 + # output_csv_path (str): 输出CSV文件路径,如果为None则覆盖原文件 + # max_workers (int): 最大线程数,如果为None则使用初始化时的值 + # """ + if max_workers is None: + max_workers = self.max_workers + + # try: + # 读取CSV文件 + df = pd.read_csv(csv_path) + self.total_count = len(df) + self.processed_count = 0 + + print(f"成功读取CSV文件,共 {len(df)} 行数据") + print(f"使用 {max_workers} 个线程进行处理...") + + # 初始化新列 + df['new_num_frame'] = None + df['new_height'] = None + df['new_width'] = None + df['new_fps'] = None + + # 准备任务列表 + tasks = [(idx, row['video path'], video_dir) for idx, row in df.iterrows()] + + # 记录开始时间 + start_time = time.time() + + # 使用线程池执行任务 + with ThreadPoolExecutor(max_workers=max_workers) as executor: + # 提交所有任务 + future_to_task = {executor.submit(self.process_single_video, task): task for task in tasks} + + # 处理完成的任务 + for future in as_completed(future_to_task): + idx, num_frame, height, width, fps, success, message = future.result() + + # 更新DataFrame + if success and height is not None: + df.at[idx, 'new_num_frame'] = num_frame + df.at[idx, 'new_height'] = height + df.at[idx, 'new_width'] = width + df.at[idx, 'new_fps'] = fps + + # 计算处理时间 + end_time = time.time() + processing_time = end_time - start_time + + # 保存结果 + if output_csv_path is None: + output_csv_path = csv_path + + df.to_csv(output_csv_path, index=False) + + # 显示统计信息 + valid_videos = df['new_height'].notna().sum() + print(f"\n{'='*60}") + print(f"处理完成!") + print(f"总处理时间: {processing_time:.2f}秒") + print(f"平均每个视频: {processing_time/len(df):.2f}秒") + print(f"成功处理视频数量: {valid_videos}/{len(df)}") + print(f"结果已保存到: {output_csv_path}") + print(f"{'='*60}") + + return df + + # except Exception as e: + # print(f"处理过程中出错: {str(e)}") + # return None + +# 便捷函数 +def process_video_csv_multithread(csv_path, video_dir="./", output_csv_path=None, max_workers=4): + """ + 便捷的多线程视频处理函数 + + Args: + csv_path (str): 输入CSV文件路径 + video_dir (str): 视频文件所在目录 + output_csv_path (str): 输出CSV文件路径 + max_workers (int): 最大线程数 + """ + processor = VideoProcessor(max_workers=max_workers) + return processor.process_video_csv(csv_path, video_dir, output_csv_path, max_workers) + +# 使用示例 +if __name__ == "__main__": + # 配置参数 + # base_names = ["sekai-real-walking-hq-193", "sekai-game-walking-193", "sekai-real-walking-hq-386", "sekai-game-walking-386"] + # base_names = ["sekai-real-walking-hq-193"] + # base_names = ["sekai-game-walking-193"] + # base_names = ["sekai-real-walking-hq-386"] + base_names = ["sekai-game-walking-386"] + + for base_name in base_names: + csv_file_path = f"/mnt/bn/yufan-dev-my/ysh/Ckpts/SpatialVID/SpatialVID-HQ-Final/data/train/SpatialVID_HQ_metadata.csv" + video_directory = f"/mnt/bn/yufan-dev-my/ysh/Ckpts/SpatialVID/SpatialVID-HQ-Final" + output_file_path = f"/mnt/bn/yufan-dev-my/ysh/Ckpts/SpatialVID/SpatialVID-HQ-Final/data/SpatialVID_HQ_step0.csv" + thread_count = 192 + + # 方法1: 使用便捷函数 + result_df = process_video_csv_multithread( + csv_path=csv_file_path, + video_dir=video_directory, + output_csv_path=output_file_path, + max_workers=thread_count + ) + + # 方法2: 使用类的方式(更灵活) + """ + processor = VideoProcessor(max_workers=thread_count) + result_df = processor.process_video_csv( + csv_path=csv_file_path, + video_dir=video_directory, + output_csv_path=output_file_path + ) + """ + + # 显示前几行结果 + if result_df is not None: + print("\n处理后的数据预览:") + print(result_df[['videoFile', 'new_num_frame', 'new_height', 'new_width', 'new_fps']].head()) + + # 显示一些统计信息 + print(f"\n视频分辨率统计:") + resolution_stats = result_df.groupby(['new_width', 'new_height']).size().reset_index(name='count') + print(resolution_stats.head(10)) diff --git a/dataset_code/spatialvid/add_config_step1.py b/dataset_code/spatialvid/add_config_step1.py new file mode 100644 index 0000000000000000000000000000000000000000..c276c4b0c306d1c0f9bea134402ab0aea346b442 --- /dev/null +++ b/dataset_code/spatialvid/add_config_step1.py @@ -0,0 +1,127 @@ +import pandas as pd +from tqdm import tqdm +from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor +from functools import partial +import numpy as np + +length_bucket_options = { + 1: [321, 301, 281, 261, 241, 221, 193, 181, 161, 141, 121, 101, 81, 61, 41, 21], + 2: [193, 177, 161, 156, 145, 133, 129, 121, 113, 109, 97, 85, 81, 73, 65, 61, 49, 37, 25], +} + +def find_nearest_length_bucket(length, stride=1): + buckets = length_bucket_options[stride] + min_bucket = min(buckets) + if length < min_bucket: + return length + valid_buckets = [bucket for bucket in buckets if bucket <= length] + return max(valid_buckets) + +def split_long_videos(df, stride=1, skip_frames=0, skip_end_frames=0, overlap=0): + """ + 将长视频分割成多个段,充分利用所有帧 + + Args: + df: 输入DataFrame + stride: bucket选择的stride参数 + skip_frames: 跳过开头的帧数 + skip_end_frames: 跳过结尾的帧数 + overlap: 段之间的重叠帧数,默认为0 + """ + result_rows = [] + max_bucket = max(length_bucket_options[stride]) + + for idx, row in tqdm(df.iterrows(), total=len(df), desc="Processing videos"): + if pd.isna(row.get('new_num_frame')): + print(f"Skipping row {idx}: new_num_frame is NaN or missing") + continue + + num_frames = row['new_num_frame'] + # 计算可用帧数(去除开头和结尾) + available_frames = num_frames - skip_frames - skip_end_frames + + # 如果可用帧数太少,跳过这个视频 + if available_frames < min(length_bucket_options[stride]): + continue + + if available_frames <= max_bucket: + # 短视频,直接处理 + new_row = row.copy() + new_row['start_frame'] = skip_frames + bucket_length = find_nearest_length_bucket(available_frames, stride) + new_row['end_frame'] = skip_frames + bucket_length + new_row['segment_id'] = 0 + result_rows.append(new_row) + else: + # 长视频,分割成多个段 + step_size = max_bucket - overlap + segment_count = 0 + + start_pos = skip_frames + effective_end = num_frames - skip_end_frames # 有效结束位置 + + while start_pos < effective_end: + remaining_frames = effective_end - start_pos + + # 如果剩余帧数小于最小bucket,跳过 + if remaining_frames < min(length_bucket_options[stride]): + break + + new_row = row.copy() + new_row['start_frame'] = start_pos + + # 计算这个段的长度 + segment_length = min(remaining_frames, max_bucket) + bucket_length = find_nearest_length_bucket(segment_length, stride) + new_row['end_frame'] = start_pos + bucket_length + new_row['segment_id'] = segment_count + + result_rows.append(new_row) + + # 移动到下一个段的起始位置 + start_pos += step_size + segment_count += 1 + + # 如果剩余帧数不足以形成新段,退出 + if start_pos + min(length_bucket_options[stride]) > effective_end: + break + + return pd.DataFrame(result_rows) + +def add_frame_range_with_segments(csv_path, output_path=None, stride=1, skip_frames=0, skip_end_frames=0, overlap=0): + """ + 为CSV添加start_frame和end_frame列,并将长视频分割成多个段 + + Args: + csv_path: 输入CSV文件路径 + output_path: 输出CSV文件路径,如果为None则覆盖原文件 + stride: bucket选择的stride参数 + skip_frames: 跳过开头的帧数,默认为0 + skip_end_frames: 跳过结尾的帧数,默认为0 + overlap: 段之间的重叠帧数,默认为0 + """ + # 读取CSV + df = pd.read_csv(csv_path) + + # 分割长视频并添加帧范围 + result_df = split_long_videos(df, stride, skip_frames, skip_end_frames, overlap) + + # 保存结果 + if output_path is None: + output_path = csv_path + result_df.to_csv(output_path, index=False) + + return result_df + +# 使用示例 +if __name__ == "__main__": + input_csv = '/mnt/bn/yufan-dev-my/ysh/Ckpts/SpatialVID/SpatialVID-HQ-Final/data/SpatialVID_HQ_step0.csv' + output_csv = '/mnt/bn/yufan-dev-my/ysh/Ckpts/SpatialVID/SpatialVID-HQ-Final/data/SpatialVID_HQ_step1.csv' + df = add_frame_range_with_segments(input_csv, output_csv, stride=1, skip_frames=11, skip_end_frames=19, overlap=0) + + # 打印结果统计 + print(f"处理后行数: {len(df)}") + print(f"分段统计:") + print(df['segment_id'].value_counts().sort_index()) + print("\n前几行示例:") + print(df.head(10)) diff --git a/dataset_code/spatialvid/add_config_step2.py b/dataset_code/spatialvid/add_config_step2.py new file mode 100644 index 0000000000000000000000000000000000000000..696392557c618a36982981fd7a0146d2aabe1fb7 --- /dev/null +++ b/dataset_code/spatialvid/add_config_step2.py @@ -0,0 +1,159 @@ +from tqdm import tqdm +import pandas as pd +import json +import os +from concurrent.futures import ThreadPoolExecutor, as_completed +import threading + +def process_single_row(args): + """ + 处理单个行的函数 + + Args: + args: 元组,包含 (index, row, video_folder) + + Returns: + tuple: (index, prompt) + """ + index, row, video_folder = args + + try: + # 构建caption.json文件路径 + prompt_path = os.path.join(video_folder, row["annotation path"], "caption.json") + + # 读取JSON文件 + with open(prompt_path, 'r', encoding='utf-8') as f: + data = json.load(f) + + # 构建prompt + prompt = data['SceneDescription'] + " " + data["CameraMotion"] + return (index, prompt) + + except FileNotFoundError: + print(f"Warning: File not found - {prompt_path}") + return (index, "") + except KeyError as e: + print(f"Warning: Key {e} not found in {prompt_path}") + return (index, "") + except Exception as e: + print(f"Error processing row {index}: {e}") + return (index, "") + +def add_prompt_to_csv(csv_path, video_folder, output_path=None, max_workers=4): + """ + 为CSV文件添加prompt字段(多线程版本) + + Args: + csv_path: 输入CSV文件路径 + video_folder: 视频文件夹路径(self.video_folder的值) + output_path: 输出CSV文件路径,如果为None则覆盖原文件 + max_workers: 最大线程数,默认为4 + """ + # 读取CSV文件 + df = pd.read_csv(csv_path) + + # 准备任务参数 + tasks = [(index, row, video_folder) for index, row in df.iterrows()] + + # 初始化结果字典 + results = {} + + # 使用ThreadPoolExecutor进行多线程处理 + with ThreadPoolExecutor(max_workers=max_workers) as executor: + # 提交所有任务 + future_to_index = {executor.submit(process_single_row, task): task[0] for task in tasks} + + # 收集结果,使用tqdm显示进度 + for future in tqdm(as_completed(future_to_index), + desc="Processing videos", + total=len(tasks)): + try: + index, prompt = future.result() + results[index] = prompt + except Exception as e: + index = future_to_index[future] + print(f"Error in thread processing row {index}: {e}") + results[index] = "" + + # 按索引顺序构建prompt列表 + prompts = [results[i] for i in range(len(df))] + + # 添加prompt列到DataFrame + df['prompt'] = prompts + + # 保存结果 + if output_path is None: + output_path = csv_path + + df.to_csv(output_path, index=False) + print(f"Updated CSV saved to: {output_path}") + + return df + +# 如果需要更高的性能,也可以考虑使用进程池版本 +def add_prompt_to_csv_multiprocess(csv_path, video_folder, output_path=None, max_workers=4): + """ + 为CSV文件添加prompt字段(多进程版本) + 适用于CPU密集型任务 + + Args: + csv_path: 输入CSV文件路径 + video_folder: 视频文件夹路径 + output_path: 输出CSV文件路径,如果为None则覆盖原文件 + max_workers: 最大进程数,默认为4 + """ + from concurrent.futures import ProcessPoolExecutor + + # 读取CSV文件 + df = pd.read_csv(csv_path) + + # 准备任务参数 + tasks = [(index, row, video_folder) for index, row in df.iterrows()] + + # 初始化结果字典 + results = {} + + # 使用ProcessPoolExecutor进行多进程处理 + with ProcessPoolExecutor(max_workers=max_workers) as executor: + # 提交所有任务 + future_to_index = {executor.submit(process_single_row, task): task[0] for task in tasks} + + # 收集结果,使用tqdm显示进度 + for future in tqdm(as_completed(future_to_index), + desc="Processing videos", + total=len(tasks)): + try: + index, prompt = future.result() + results[index] = prompt + except Exception as e: + index = future_to_index[future] + print(f"Error in process processing row {index}: {e}") + results[index] = "" + + # 按索引顺序构建prompt列表 + prompts = [results[i] for i in range(len(df))] + + # 添加prompt列到DataFrame + df['prompt'] = prompts + + # 保存结果 + if output_path is None: + output_path = csv_path + + df.to_csv(output_path, index=False) + print(f"Updated CSV saved to: {output_path}") + + return df + +# 使用示例 +if __name__ == "__main__": + # 替换为您的实际路径 + csv_file_path = "/mnt/bn/yufan-dev-my/ysh/Ckpts/SpatialVID/SpatialVID-HQ-Final/data/SpatialVID_HQ_step1.csv" + output_csv_file_path = "/mnt/bn/yufan-dev-my/ysh/Ckpts/SpatialVID/SpatialVID-HQ-Final/data/SpatialVID_HQ_step2.csv" + video_folder_path = "/mnt/bn/yufan-dev-my/ysh/Ckpts/SpatialVID/SpatialVID-HQ-Final" + + # 使用多线程版本(推荐用于I/O密集型任务) + updated_df = add_prompt_to_csv(csv_file_path, video_folder_path, output_csv_file_path, max_workers=128) + + # 如果是CPU密集型任务,可以使用多进程版本 + # updated_df = add_prompt_to_csv_multiprocess(csv_file_path, video_folder_path, output_csv_file_path, max_workers=4) diff --git a/dataset_code/spatialvid/dummy_dataloader_official.py b/dataset_code/spatialvid/dummy_dataloader_official.py new file mode 100644 index 0000000000000000000000000000000000000000..d65dc9092621709475864ffdc45ec7c52b319172 --- /dev/null +++ b/dataset_code/spatialvid/dummy_dataloader_official.py @@ -0,0 +1,491 @@ +import os +import json +import pickle +import random +import numpy as np +import pandas as pd +from collections import defaultdict + +import torch +import torchvision +from torch.utils.data import DataLoader, Dataset, Sampler + +from video_reader import PyVideoReader + +from diffusers.utils import export_to_video +from diffusers.training_utils import free_memory + +# 5: (21, 41, 61, 81, 101) +# 6: (25, 49, 73, 97, 121) +# 7: (29, 57, 85, 113, 141) +# 8: (33, 65, 97, 129, 161) +# 9: (37, 73, 109, 145, 181) +# 10: (41, 81, 121, 161, 201) +# 11: (45, 89, 133, 177, 221) +# 12: (49, 97, 145, 193, 241) + +# 1: (21 - 1) * 4 + 1 = 81, 162 +# 2: (22 - 1) * 4 + 1 = 85, 170 +# 3: (23 - 1) * 4 + 1 = 89, 178 +# 4: (24 - 1) * 4 + 1 = 93, 186 +# 5: (25 - 1) * 4 + 1 = 97, 194 +# 6: (26 - 1) * 4 + 1 = 101, 202 +# 7: (27 - 1) * 4 + 1 = 105, 210 +# 8: (28 - 1) * 4 + 1 = 109, 218 +# 9: (29 - 1) * 4 + 1 = 113, 226 +# 10: (30 - 1) * 4 + 1 = 117, 234 +# 11: (31 - 1) * 4 + 1 = 121, 242 +# 12: (32 - 1) * 4 + 1 = 125, 250 +# 13: (33 - 1) * 4 + 1 = 129, 258 +# 14: (34 - 1) * 4 + 1 = 133, 266 +# 15: (35 - 1) * 4 + 1 = 137, 274 +# 16: (36 - 1) * 4 + 1 = 141, 282 + +resolution_bucket_options = { + 640: [ + (768, 320), + (768, 384), + (640, 384), + (768, 512), + (576, 448), + (512, 512), + (448, 576), + (512, 768), + (384, 640), + (384, 768), + (320, 768), + ], +} + +length_bucket_options = { + 1: [321, 301, 281, 261, 241, 221, 193, 181, 161, 141, 121, 101, 81, 61, 41, 21], + 2: [193, 177, 161, 156, 145, 133, 129, 121, 113, 109, 97, 85, 81, 73, 65, 61, 49, 37, 25], +} + +def find_nearest_resolution_bucket(h, w, resolution=640): + min_metric = float('inf') + best_bucket = None + for (bucket_h, bucket_w) in resolution_bucket_options[resolution]: + metric = abs(h * bucket_w - w * bucket_h) + if metric <= min_metric: + min_metric = metric + best_bucket = (bucket_h, bucket_w) + return best_bucket + +def find_nearest_length_bucket(length, stride=1): + buckets = length_bucket_options[stride] + min_bucket = min(buckets) + if length < min_bucket: + return length + valid_buckets = [bucket for bucket in buckets if bucket <= length] + return max(valid_buckets) + +def read_cut_crop_and_resize(video_path, f_prime, h_prime, w_prime, stride=1, start_frame=None, end_frame=None): + vr = PyVideoReader(video_path, threads=0) # 0 means auto (let ffmpeg pick the optimal number) + total_frames = len(vr) + + # if stride != 1: + # required_span = stride * (f_prime - 1) + # start_frame = max(0, total_frames - required_span - 1) + # else: + # start_frame = max(0, total_frames - f_prime) + + frame_indices = list(range(start_frame, end_frame, stride)) + assert len(frame_indices) == f_prime + frames = torch.from_numpy(vr.get_batch(frame_indices)).float() + + # if stride != 1: + # required_span = stride * (f_prime - 1) + # start_frame = max(0, total_frames - required_span - 1) + # frame_indices = list(range(start_frame, total_frames, stride)) + # assert len(frame_indices) == f_prime + # frames = torch.from_numpy(np.stack(vr.decode_fast(start_frame=0, end_frame=total_frames))).float() + # frames = frames[frame_indices] + # else: + # start_frame = max(0, total_frames - f_prime) + # frames = torch.from_numpy(np.stack(vr.decode_fast(start_frame=start_frame, end_frame=total_frames))).float() + + + # total_frames = len(vr) + # start_frame = max(0, total_frames - f_prime) + # # frame_indices = list(range(start_frame, total_frames)) + # # frames = torch.from_numpy(vr.get_batch(frame_indices)).float() + # frames = torch.from_numpy(np.stack(vr.decode_fast(start_frame=start_frame, end_frame=total_frames))).float() + + + frames = (frames / 127.5) - 1 + video = frames.permute(0, 3, 1, 2) + + frames, channels, h, w = video.shape + aspect_ratio_original = h / w + aspect_ratio_target = h_prime / w_prime + + if aspect_ratio_original >= aspect_ratio_target: + new_h = int(w * aspect_ratio_target) + top = (h - new_h) // 2 + bottom = top + new_h + left = 0 + right = w + else: + new_w = int(h / aspect_ratio_target) + left = (w - new_w) // 2 + right = left + new_w + top = 0 + bottom = h + + # Crop the video + cropped_video = video[:, :, top:bottom, left:right] + # Resize the cropped video + resized_video = torchvision.transforms.functional.resize(cropped_video, (h_prime, w_prime)) + return resized_video + +def save_frames(frame_raw, fps=24, video_path="1.mp4"): + save_list = [] + for frame in frame_raw: + frame = (frame + 1) / 2 * 255 + frame = torchvision.transforms.transforms.ToPILImage()(frame.to(torch.uint8)).convert("RGB") + save_list.append(frame) + frame = None + del frame + export_to_video(save_list, video_path, fps=fps) + + save_list = None + del save_list + free_memory() + +class BucketedFeatureDataset(Dataset): + def __init__(self, csv_file, video_folder, stride=1, cache_file=None, force_rebuild=False): + self.csv_file = csv_file + self.video_folder = video_folder + self.stride = stride + + if cache_file is None: + cache_file = os.path.join(video_folder, f"dataset_cache_stride{stride}.pkl") + + if force_rebuild or not os.path.exists(cache_file): + print("Building metadata cache...") + self._build_metadata() + self._save_cache(cache_file) + else: + print("Loading cached metadata...") + with open(cache_file, "rb") as f: + cached_data = pickle.load(f) + if cached_data.get("stride", 1) != stride: + print(f"Stride mismatch in cache (cached: {cached_data.get('stride', 1)}, current: {stride}). Rebuilding...") + self._build_metadata() + self._save_cache(cache_file) + else: + self.samples = cached_data["samples"] + self.buckets = cached_data["buckets"] + print(f"Loaded {len(self.samples)} samples from cache") + + + def _save_cache(self, cache_file): + print("Saving metadata cache...") + cached_data = { + "samples": self.samples, + "buckets": self.buckets, + "stride": self.stride + } + with open(cache_file, "wb") as f: + pickle.dump(cached_data, f) + print(f"Cached {len(self.samples)} samples with stride={self.stride}") + + # def _build_metadata(self): + # self.feature_files = [f for f in os.listdir(self.video_folder) if f.endswith(".mp4")] + # self.samples = [] + # self.buckets = defaultdict(list) + # sample_idx = 0 + + # print(f"Processing {len(self.feature_files)} files...") + # for i, feature_file in enumerate(self.feature_files): + # if i % 10000 == 0: + # print(f"Processed {i}/{len(self.feature_files)} files") + + # video_path = os.path.join(self.video_folder, feature_file) + + # # Parse filename + # parts = feature_file.split("_")[:4] + # uttid = parts[0] + # num_frame = int(parts[1]) + # height = int(parts[2]) + # width = int(parts[3].replace(".mp4", "")) + + def _build_metadata(self): + self.df = pd.read_csv(self.csv_file) + + self.samples = [] + self.buckets = defaultdict(list) + sample_idx = 0 + + print(f"Processing {len(self.df)} records from CSV with stride={self.stride}...") + for i, row in self.df.iterrows(): + if i % 10000 == 0: + print(f"Processed {i}/{len(self.df)} records") + + uttid = row['id'] + video_file = row['video path'] + video_path = os.path.join(self.video_folder, video_file) + start_frame = row["start_frame"] + end_frame = row["end_frame"] + segment_id = row["segment_id"] + num_frame = end_frame - start_frame + # resolution = row["resolution"] + # width, height = map(int, row["resolution"].split('x')) + width = row["new_width"] + height = row["new_height"] + fps = row["new_fps"] + + uttid = f"{uttid}_{start_frame}_{end_frame}" + prompt = row["prompt"] + + # prompt_path = os.path.join(self.video_folder, row["annotation path"], "caption.json") + # with open(prompt_path, 'r') as f: + # data = json.load(f) + # prompt = data['SceneDescription'] + " " + data["CameraMotion"] + + # # keep length >= 121 + # if num_frame < 121: + # continue + + effective_num_frame = (num_frame + self.stride - 1) // self.stride + bucket_height, bucket_width = find_nearest_resolution_bucket(height, width, resolution=640) + bucket_num_frame = find_nearest_length_bucket(effective_num_frame, stride=self.stride) + bucket_key = (bucket_num_frame, bucket_height, bucket_width) + + sample_info = { + "uttid": uttid, + "bucket_key": bucket_key, + "video_path": video_path, + "prompt": prompt, + "fps": fps, + "stride": self.stride, + "effective_num_frame": effective_num_frame, + "num_frame": num_frame, + "height": height, + "width": width, + "bucket_num_frame": bucket_num_frame, + "bucket_height": bucket_height, + "bucket_width": bucket_width, + "start_frame": start_frame, + "end_frame": end_frame, + } + + self.samples.append(sample_info) + self.buckets[bucket_key].append(sample_idx) + sample_idx += 1 + + def __len__(self): + return len(self.samples) + + def __getitem__(self, idx): + # sample_info = self.samples[idx] + # video_data = read_cut_crop_and_resize( + # video_path=sample_info["video_path"], + # f_prime=sample_info["bucket_num_frame"], + # h_prime=sample_info["bucket_height"], + # w_prime=sample_info["bucket_width"], + # stride=self.stride, + # ) + while True: + sample_info = self.samples[idx] + try: + video_data = read_cut_crop_and_resize( + video_path=sample_info["video_path"], + f_prime=sample_info["bucket_num_frame"], + h_prime=sample_info["bucket_height"], + w_prime=sample_info["bucket_width"], + stride=self.stride, + start_frame=sample_info["start_frame"], + end_frame=sample_info["end_frame"], + ) + break + except Exception: + idx = random.randint(0, len(self.samples) - 1) + print(f"Error loading {sample_info['video_path']}, retrying...") + + return { + "uttid": sample_info["uttid"], + "bucket_key": sample_info["bucket_key"], + "video_metadata": { + "num_frames": sample_info["bucket_num_frame"], + "height": sample_info["bucket_height"], + "width": sample_info["bucket_width"], + "fps": sample_info["fps"], + "stride": self.stride, + "effective_num_frame": sample_info["effective_num_frame"], + }, + "videos": video_data, + "prompts": sample_info["prompt"], + "first_frames_images": (video_data[0] + 1) / 2 * 255, + } + +class BucketedSampler(Sampler): + def __init__(self, dataset, batch_size, drop_last=False, shuffle=False, seed=42): + self.dataset = dataset + self.batch_size = batch_size + self.drop_last = drop_last + self.shuffle = shuffle + self.seed = seed + self.generator = torch.Generator() + self.buckets = dataset.buckets + self._epoch = 0 + + def set_epoch(self, epoch): + self._epoch = epoch + + def __iter__(self): + if self.shuffle: + self.generator.manual_seed(self.seed + self._epoch) + else: + self.generator.manual_seed(self.seed) + + bucket_iterators = {} + bucket_batches = {} + + for bucket_key, sample_indices in self.buckets.items(): + indices = sample_indices.copy() + if self.shuffle: + indices = torch.randperm(len(indices), generator=self.generator).tolist() + indices = [sample_indices[i] for i in indices] + + batches = [] + for i in range(0, len(indices), self.batch_size): + batch = indices[i : i + self.batch_size] + if len(batch) == self.batch_size or not self.drop_last: + batches.append(batch) + + if batches: + bucket_batches[bucket_key] = batches + bucket_iterators[bucket_key] = iter(batches) + + remaining_buckets = list(bucket_iterators.keys()) + + while remaining_buckets: + idx = torch.randint(len(remaining_buckets), (1,), generator=self.generator).item() + bucket_key = remaining_buckets[idx] + + bucket_iter = bucket_iterators[bucket_key] + + try: + batch = next(bucket_iter) + for sample_idx in batch: + sample_bucket = self.dataset.samples[sample_idx]['bucket_key'] + if sample_bucket != bucket_key: + print(f"❌ BUCKET MISMATCH! Expected {bucket_key}, got {sample_bucket} for sample {sample_idx}") + yield batch + except StopIteration: + remaining_buckets.remove(bucket_key) + + def __len__(self): + total_batches = 0 + for sample_indices in self.buckets.values(): + num_batches = len(sample_indices) // self.batch_size + if not self.drop_last and len(sample_indices) % self.batch_size != 0: + num_batches += 1 + total_batches += num_batches + return total_batches + + +def collate_fn(batch): + def collate_dict(data_list): + if isinstance(data_list[0], dict): + return { + key: collate_dict([d[key] for d in data_list]) + for key in data_list[0] + } + elif isinstance(data_list[0], torch.Tensor): + return torch.stack(data_list) + else: + return data_list + + return { + key: collate_dict([d[key] for d in batch]) + for key in batch[0] + } + + +if __name__ == "__main__": + from accelerate import Accelerator + + csv_file = f"/mnt/bn/yufan-dev-my/ysh/Ckpts/SpatialVID/SpatialVID-HQ-Final/test_prompt_filtered" + video_folder = f"/mnt/bn/yufan-dev-my/ysh/Ckpts/SpatialVID/SpatialVID-HQ-Final" + stride = 1 + batch_size = 64 + num_train_epochs = 1 + seed = 0 + output_dir = "accelerate_checkpoints" + checkpoint_dirs = ( + [ + d + for d in os.listdir(output_dir) + if d.startswith("checkpoint-") and os.path.isdir(os.path.join(output_dir, d)) + ] + if os.path.exists(output_dir) + else [] + ) + + dataset = BucketedFeatureDataset(csv_file=csv_file, video_folder=video_folder, stride=stride) + sampler = BucketedSampler(dataset, batch_size=batch_size, drop_last=True, shuffle=False, seed=seed) + dataloader = DataLoader(dataset, batch_sampler=sampler, collate_fn=collate_fn, num_workers=8) + + print(len(dataset), len(dataloader)) + accelerator = Accelerator() + dataloader = accelerator.prepare(dataloader) + print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}") + print(f"Process index: {accelerator.process_index}, World size: {accelerator.num_processes}") + + step = 0 + global_step = 0 + first_epoch = 0 + num_update_steps_per_epoch = len(dataloader) + + print("Testing dataloader...") + step = global_step + for epoch in range(first_epoch, num_train_epochs): + sampler.set_epoch(epoch) + skip_steps = 0 + printed_skip_log = False + for i, batch in enumerate(dataloader): + if epoch == first_epoch and skip_steps < (global_step % num_update_steps_per_epoch): + skip_steps += 1 + continue + if epoch == first_epoch and not printed_skip_log: + print(f"Skip {skip_steps} steps in epoch {epoch}") + printed_skip_log = True + + # Get metadata + uttid = batch["uttid"] + bucket_key = batch["bucket_key"] + num_frame = batch["video_metadata"]["num_frames"] + height = batch["video_metadata"]["height"] + width = batch["video_metadata"]["width"] + + # Get feature + video_data = batch["videos"] + prompt = batch["prompts"] + first_frames_images = batch["first_frames_images"] + first_frames_images = [torchvision.transforms.ToPILImage()(x.to(torch.uint8)) for x in first_frames_images] + + # import pdb;pdb.set_trace() + # save_frames(video_data[0].squeeze(0), video_path="1.mp4") + + if accelerator.process_index == 0: + # print info + print(f" Step {step}:") + print(f" Batch {i}:") + print(f" Batch size: {len(uttid)}") + print(f" Uttids: {uttid}") + print(f" Dimensions - frames: {num_frame[0]}, height: {height[0]}, width: {width[0]}") + print(f" Bucket key: {bucket_key[0]}") + print(f" Videos shape: {video_data.shape}") + print(f" Cpation: {prompt}") + + # verify + assert all(nf == num_frame[0] for nf in num_frame), "Frame numbers not consistent in batch" + assert all(h == height[0] for h in height), "Heights not consistent in batch" + assert all(w == width[0] for w in width), "Widths not consistent in batch" + + print(" ✓ Batch dimensions are consistent") + + step += 1 \ No newline at end of file diff --git a/dataset_code/spatialvid/get_data_dist.py b/dataset_code/spatialvid/get_data_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..ada2a0699dc8ef58cd5e97a03bca9537a055aafb --- /dev/null +++ b/dataset_code/spatialvid/get_data_dist.py @@ -0,0 +1,19 @@ +import pandas as pd + +# 读取 CSV 文件 +df = pd.read_csv("/mnt/bn/yufan-dev-my/ysh/Ckpts/SpatialVID/SpatialVID-HQ/data/train/SpatialVID_HQ_metadata.csv") + +# 统计各字段的数量分布 +num_frames_count = df['num frames'].value_counts() +fps_count = df['fps'].value_counts() +resolution_count = df['resolution'].value_counts() + +# 输出结果 +print("num_frames 分布:") +print(num_frames_count) + +print("\nfps 分布:") +print(fps_count) + +print("\nresolution 分布:") +print(resolution_count) diff --git a/dataset_code/spatialvid/get_temp_csv.py b/dataset_code/spatialvid/get_temp_csv.py new file mode 100644 index 0000000000000000000000000000000000000000..9cf588e09d9d4a956f54b305902e7481c9c9f0d9 --- /dev/null +++ b/dataset_code/spatialvid/get_temp_csv.py @@ -0,0 +1,115 @@ +import os +import pandas as pd +import argparse +from tqdm import tqdm + +def extract_uttid_from_row(row): + """ + 从CSV的行数据中提取uttid(通过start_frame和end_frame组合) + """ + uttid = f"{row['id']}_{row['start_frame']}_{row['end_frame']}" + return uttid + +def create_filtered_csv(csv_file, output_latent_folder, output_csv_file): + """ + 创建一个过滤后的CSV文件,只包含需要处理的样本 + 只使用uttid匹配,不依赖其他元数据 + """ + # 读取原始CSV + df = pd.read_csv(csv_file) + print(f"Original dataset size: {len(df)}") + + # 获取已经存在的latent文件 + existing_files = set() + if os.path.exists(output_latent_folder): + for filename in os.listdir(output_latent_folder): + if filename.endswith('.pt'): + parts = filename[:-3].split('_') + if len(parts) >= 4: # 至少要有uttid + 3个元数据 + uttid_parts = parts[:-3] # 提取uttid部分 + uttid = '_'.join(uttid_parts) + existing_files.add(uttid) + + print(f"Found {len(existing_files)} existing latent files") + + # 使用新的方法从行数据中提取uttid + df_uttids = df.apply(extract_uttid_from_row, axis=1) + + # 筛选出未处理的样本 + mask = ~df_uttids.isin(existing_files) + filtered_df = df[mask] + + # 保存到新的CSV文件 + os.makedirs(os.path.dirname(output_csv_file), exist_ok=True) + filtered_df.to_csv(output_csv_file, index=False) + + print(f"Filtered dataset size: {len(filtered_df)}") + print(f"Filtered CSV saved to: {output_csv_file}") + + return len(filtered_df) + +def create_all_filtered_csvs(): + """ + 为所有数据集创建过滤后的CSV文件 + """ + base_csv_path = "/mnt/bn/yufan-dev-my/ysh/Ckpts/SpatialVID/SpatialVID-HQ-Final/" + base_output_latent_path = "/mnt/bn/yufan-dev-my/ysh/Ckpts/SpatialVID/SpatialVID-HQ-Final" + + csv_paths = [ + "data/SpatialVID_HQ_step2.csv", + + ] + output_latent_paths = [ + "latents_stride1", + ] + + for csv_path, output_latent_path in zip(csv_paths, output_latent_paths): + original_csv = os.path.join(base_csv_path, csv_path) + output_latent_folder = os.path.join(base_output_latent_path, output_latent_path) + + # 创建过滤后的CSV文件名 + filtered_csv_name = csv_path.replace('.csv', '_filtered.csv') + filtered_csv_path = os.path.join(base_csv_path, filtered_csv_name) + + print(f"\nProcessing: {csv_path}") + + filtered_count = create_filtered_csv( + csv_file=original_csv, + output_latent_folder=output_latent_folder, + output_csv_file=filtered_csv_path + ) + + print(f"Created filtered CSV: {filtered_csv_path} with {filtered_count} samples") + +def main(): + parser = argparse.ArgumentParser(description="Create filtered CSV for processing") + # parser.add_argument("--csv_file", type=str, help="Original CSV file path") + # parser.add_argument("--output_latent_folder", type=str, help="Output latent folder path") + # parser.add_argument("--output_csv_file", type=str, help="Output filtered CSV file path") + parser.add_argument("--batch", action="store_true", help="Process all datasets in batch") + + args = parser.parse_args() + create_all_filtered_csvs() + + # if args.batch: + # # 批量处理所有数据集 + # create_all_filtered_csvs() + # else: + # # 单个处理 + # if not all([args.csv_file, args.output_latent_folder, args.output_csv_file]): + # print("Error: For single processing, --csv_file, --output_latent_folder, and --output_csv_file are required") + # return + + # filtered_count = create_filtered_csv( + # csv_file=args.csv_file, + # output_latent_folder=args.output_latent_folder, + # output_csv_file=args.output_csv_file + # ) + + # if filtered_count == 0: + # print("No samples need processing!") + # else: + # print(f"Ready to process {filtered_count} samples") + +if __name__ == "__main__": + main()