forked from hao-ai-lab/FastVideo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[feat]: Add vae encoder embedded generator to main (hao-ai-lab#30)
- Loading branch information
Showing
8 changed files
with
252 additions
and
26 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,7 +5,6 @@ __pycache__ | |
*.pth | ||
UCF-101/ | ||
results/ | ||
vae | ||
build/ | ||
fastvideo.egg-info/ | ||
wandb/ | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
import argparse | ||
import torch | ||
from accelerate.logging import get_logger | ||
from diffusers import MochiPipeline | ||
from diffusers.utils import export_to_video | ||
import json | ||
import os | ||
import torch.distributed as dist | ||
logger = get_logger(__name__) | ||
|
||
def main(args): | ||
local_rank = int(os.getenv('RANK', 0)) | ||
world_size = int(os.getenv('WORLD_SIZE', 1)) | ||
print('world_size', world_size, 'local rank', local_rank) | ||
|
||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | ||
torch.cuda.set_device(local_rank) | ||
if not dist.is_initialized(): | ||
dist.init_process_group(backend='nccl', init_method='env://', world_size=world_size, rank=local_rank) | ||
|
||
pipe = MochiPipeline.from_pretrained(args.model_path, torch_dtype=torch.bfloat16).to(device) | ||
pipe.vae.enable_tiling() | ||
os.makedirs(args.output_dir, exist_ok=True) | ||
os.makedirs(os.path.join(args.output_dir, "video"), exist_ok=True) | ||
os.makedirs(os.path.join(args.output_dir, "latent"), exist_ok=True) | ||
os.makedirs(os.path.join(args.output_dir, "prompt_embed"), exist_ok=True) | ||
os.makedirs(os.path.join(args.output_dir, "prompt_attention_mask"), exist_ok=True) | ||
|
||
latents_json_path = os.path.join(args.output_dir, "videos2caption_temp.json") | ||
with open(latents_json_path, "r") as f: | ||
train_dataset = json.load(f) | ||
train_dataset = sorted(train_dataset, key=lambda x: x['latent_path']) | ||
|
||
json_data = [] | ||
for _, data in enumerate(train_dataset): | ||
video_name =data['latent_path'].split(".")[0] | ||
if int(video_name) % world_size != local_rank: | ||
continue | ||
try: | ||
with torch.inference_mode(): | ||
with torch.autocast("cuda", dtype=torch.bfloat16): | ||
latent = torch.load(os.path.join(args.output_dir, 'latent', data['latent_path'])) | ||
prompt_embeds, prompt_attention_mask, _, _ = pipe.encode_prompt( | ||
prompt=data['caption'], | ||
) | ||
prompt_embed_path = os.path.join(args.output_dir, "prompt_embed", video_name + ".pt") | ||
video_path = os.path.join(args.output_dir, "video", video_name + ".mp4") | ||
prompt_attention_mask_path = os.path.join(args.output_dir, "prompt_attention_mask", video_name + ".pt") | ||
# save latent | ||
torch.save(prompt_embeds[0], prompt_embed_path) | ||
torch.save(prompt_attention_mask[0], prompt_attention_mask_path) | ||
print(f"sample {video_name} saved") | ||
video = pipe.vae.decode(latent.unsqueeze(0).to(device), return_dict=False)[0] | ||
video = pipe.video_processor.postprocess_video(video) | ||
export_to_video(video[0], video_path, fps=30) | ||
item = {} | ||
item["latent_path"] = video_name + ".pt" | ||
item["prompt_embed_path"] = video_name + ".pt" | ||
item["prompt_attention_mask"] = video_name + ".pt" | ||
item["caption"] = data['caption'] | ||
json_data.append(item) | ||
except: | ||
print("video out of memory") | ||
continue | ||
dist.barrier() | ||
local_data = json_data | ||
gathered_data = [None] * world_size | ||
dist.all_gather_object(gathered_data, local_data) | ||
if local_rank == 0: | ||
# os.remove(latents_json_path) | ||
all_json_data = [item for sublist in gathered_data for item in sublist] | ||
with open(os.path.join(args.output_dir, "videos2caption.json"), 'w') as f: | ||
json.dump(all_json_data, f, indent=4) | ||
|
||
if __name__ == "__main__": | ||
parser = argparse.ArgumentParser() | ||
# dataset & dataloader | ||
parser.add_argument("--model_path", type=str, default="data/mochi") | ||
# text encoder & vae & diffusion model | ||
parser.add_argument("--text_encoder_name", type=str, default='google/t5-v1_1-xxl') | ||
parser.add_argument("--cache_dir", type=str, default='./cache_dir') | ||
parser.add_argument("--output_dir", type=str, default=None, help="The output directory where the model predictions and checkpoints will be written.") | ||
|
||
args = parser.parse_args() | ||
main(args) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
from fastvideo.dataset import getdataset | ||
from torch.utils.data import DataLoader | ||
from fastvideo.utils.dataset_utils import Collate | ||
import argparse | ||
import torch | ||
from accelerate import Accelerator | ||
from accelerate.logging import get_logger | ||
from accelerate.utils import ProjectConfiguration | ||
import json | ||
import os | ||
from diffusers import AutoencoderKLMochi | ||
import torch.distributed as dist | ||
|
||
logger = get_logger(__name__) | ||
|
||
def main(args): | ||
local_rank = int(os.getenv('RANK', 0)) | ||
world_size = int(os.getenv('WORLD_SIZE', 1)) | ||
print('world_size', world_size, 'local rank', local_rank) | ||
args.ae_stride_t, args.ae_stride_h, args.ae_stride_w = 4, 8, 8 | ||
args.ae_stride = args.ae_stride_h | ||
patch_size_t, patch_size_h, patch_size_w = 1, 2, 2 | ||
args.patch_size = patch_size_h | ||
args.patch_size_t, args.patch_size_h, args.patch_size_w = patch_size_t, patch_size_h, patch_size_w | ||
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=args.logging_dir) | ||
accelerator = Accelerator( | ||
project_config=accelerator_project_config, | ||
) | ||
train_dataset = getdataset(args) | ||
train_dataloader = DataLoader( | ||
train_dataset, | ||
shuffle=True, | ||
batch_size=args.train_batch_size, | ||
num_workers=args.dataloader_num_workers, | ||
) | ||
|
||
|
||
encoder_device = torch.device(f"cuda" if torch.cuda.is_available() else "cpu") | ||
torch.cuda.set_device(local_rank) | ||
if not dist.is_initialized(): | ||
dist.init_process_group(backend='nccl', init_method='env://', world_size=world_size, rank=local_rank) | ||
vae = AutoencoderKLMochi.from_pretrained(args.model_path, subfolder="vae", torch_dtype=torch.bfloat16).to("cuda") | ||
vae.enable_tiling() | ||
os.makedirs(args.output_dir, exist_ok=True) | ||
os.makedirs(os.path.join(args.output_dir, "latent"), exist_ok=True) | ||
|
||
json_data = [] | ||
for _, data in enumerate(train_dataloader): | ||
video_name = os.path.basename(data['path'][0]).split(".")[0] | ||
if int(video_name) % world_size != local_rank: | ||
continue | ||
with torch.inference_mode(): | ||
with torch.autocast("cuda", dtype=torch.bfloat16): | ||
latents = vae.encode(data['pixel_values'][0].to(encoder_device))['latent_dist'].sample() | ||
latent_path = os.path.join(args.output_dir, "latent", video_name + ".pt") | ||
torch.save(latents[0].to(torch.bfloat16), latent_path) | ||
item = {} | ||
item["latent_path"] = video_name + ".pt" | ||
item["caption"] = data['text'] | ||
json_data.append(item) | ||
print(f"{video_name} processed") | ||
dist.barrier() | ||
local_data = json_data | ||
gathered_data = [None] * world_size | ||
dist.all_gather_object(gathered_data, local_data) | ||
if local_rank == 0: | ||
all_json_data = [item for sublist in gathered_data for item in sublist] | ||
with open(os.path.join(args.output_dir, "videos2caption_temp.json"), 'w') as f: | ||
json.dump(all_json_data, f, indent=4) | ||
|
||
if __name__ == "__main__": | ||
parser = argparse.ArgumentParser() | ||
# dataset & dataloader | ||
parser.add_argument("--model_path", type=str, default="data/mochi") | ||
parser.add_argument("--data_merge_path", type=str, required=True) | ||
parser.add_argument("--num_frames", type=int, default=65) | ||
parser.add_argument("--target_length", type=int, default=65) | ||
parser.add_argument("--dataloader_num_workers", type=int, default=1, help="Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process.") | ||
parser.add_argument("--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader.") | ||
parser.add_argument("--num_latent_t", type=int, default=28, help="Number of latent timesteps.") | ||
parser.add_argument("--max_height", type=int, default=480) | ||
parser.add_argument("--max_width", type=int, default=848) | ||
parser.add_argument("--group_frame", action="store_true") # TODO | ||
parser.add_argument("--group_resolution", action="store_true") # TODO | ||
parser.add_argument("--dataset", default='t2v') | ||
parser.add_argument("--train_fps", type=int, default=24) | ||
parser.add_argument("--use_image_num", type=int, default=0) | ||
parser.add_argument("--text_max_length", type=int, default=256) | ||
parser.add_argument("--speed_factor", type=float, default=1.0) | ||
parser.add_argument("--drop_short_ratio", type=float, default=1.0) | ||
# text encoder & vae & diffusion model | ||
parser.add_argument("--text_encoder_name", type=str, default='google/t5-v1_1-xxl') | ||
parser.add_argument("--cache_dir", type=str, default='./cache_dir') | ||
parser.add_argument('--cfg', type=float, default=0.1) | ||
parser.add_argument("--output_dir", type=str, default=None, help="The output directory where the model predictions and checkpoints will be written.") | ||
parser.add_argument("--logging_dir", type=str, default="logs", | ||
help=( | ||
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to" | ||
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***." | ||
), | ||
) | ||
|
||
args = parser.parse_args() | ||
main(args) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
# export WANDB_MODE="offline" | ||
GPU_NUM=8 | ||
MODEL_PATH="/ephemeral/hao.zhang/outputfolder/ckptfolder/mochi_diffuser" | ||
MOCHI_DIR="/ephemeral/hao.zhang/resourcefolder/mochi/mochi-1-preview" | ||
DATA_MERGE_PATH="/ephemeral/hao.zhang/resourcefolder/Mochi-Synthetic-Data-BW-Finetune/merge.txt" | ||
OUTPUT_DIR="./data/BW-Finetune-Synthetic-Data_test" | ||
|
||
torchrun --nproc_per_node=$GPU_NUM \ | ||
./fastvideo/utils/data_preprocess/finetune_data_VAE.py \ | ||
--model_path $MODEL_PATH \ | ||
--data_merge_path $DATA_MERGE_PATH \ | ||
--train_batch_size=1 \ | ||
--max_height=480 \ | ||
--max_width=848 \ | ||
--target_length=163 \ | ||
--dataloader_num_workers 1 \ | ||
--output_dir=$OUTPUT_DIR | ||
|
||
torchrun --nproc_per_node=$GPU_NUM \ | ||
./fastvideo/utils/data_preprocess/finetune_data_T5.py \ | ||
--model_path $MODEL_PATH \ | ||
--output_dir=$OUTPUT_DIR |