diff --git a/sonique/Video_LLaMA/apply_delta.py b/sonique/Video_LLaMA/apply_delta.py deleted file mode 100644 index 06225c6841d006c9b570933385be7451ca16aaf2..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/apply_delta.py +++ /dev/null @@ -1,49 +0,0 @@ -""" -Apply the delta weights on top of a base model. -Adapted from: https://github.com/lm-sys/FastChat/blob/main/fastchat/model/apply_delta.py. -""" -import argparse - -import torch -from tqdm import tqdm -from transformers import AutoTokenizer, AutoModelForCausalLM - - -def apply_delta(base_model_path, target_model_path, delta_path): - print(f"Loading the base model from {base_model_path}") - base = AutoModelForCausalLM.from_pretrained( - base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True) - - print(f"Loading the delta from {delta_path}") - delta = AutoModelForCausalLM.from_pretrained(delta_path, torch_dtype=torch.float16, low_cpu_mem_usage=True) - delta_tokenizer = AutoTokenizer.from_pretrained(delta_path, use_fast=False) - - DEFAULT_PAD_TOKEN = "[PAD]" - base_tokenizer = AutoTokenizer.from_pretrained(base_model_path, use_fast=False) - num_new_tokens = base_tokenizer.add_special_tokens(dict(pad_token=DEFAULT_PAD_TOKEN)) - - base.resize_token_embeddings(len(base_tokenizer)) - input_embeddings = base.get_input_embeddings().weight.data - output_embeddings = base.get_output_embeddings().weight.data - input_embeddings[-num_new_tokens:] = 0 - output_embeddings[-num_new_tokens:] = 0 - - print("Applying the delta") - for name, param in tqdm(base.state_dict().items(), desc="Applying delta"): - assert name in delta.state_dict() - param.data += delta.state_dict()[name] - - print(f"Saving the target model to {target_model_path}") - base.save_pretrained(target_model_path) - delta_tokenizer.save_pretrained(target_model_path) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--base-model-path", type=str, required=True) - parser.add_argument("--target-model-path", type=str, required=True) - parser.add_argument("--delta-path", type=str, required=True) - - args = parser.parse_args() - - apply_delta(args.base_model_path, args.target_model_path, args.delta_path) diff --git a/sonique/Video_LLaMA/eval_configs/video_llama_eval_only_vl.yaml b/sonique/Video_LLaMA/eval_configs/video_llama_eval_only_vl.yaml deleted file mode 100644 index 590c96abc24e3ea49c787dfe553e1e5adc79417f..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/eval_configs/video_llama_eval_only_vl.yaml +++ /dev/null @@ -1,36 +0,0 @@ -model: - arch: video_llama - model_type: pretrain_vicuna - freeze_vit: True - freeze_qformer: True - max_txt_len: 512 - end_sym: "###" - low_resource: False - - frozen_llama_proj: False - - # If you want use LLaMA-2-chat, - # some ckpts could be download from our provided huggingface repo - # i.e. https://huggingface.co/DAMO-NLP-SG/Video-LLaMA-2-13B-Finetuned - llama_model: "./ckpts/video-llama/llama-2-7b-chat-hf" # "ckpt/vicuna-13b/" or "ckpt/vicuna-7b/" or "ckpt/llama-2-7b-chat-hf" or "ckpt/llama-2-13b-chat-hf" - ckpt: './ckpts/video-llama/VL_LLaMA_2_7B_Finetuned.pth' # you can use our pretrained ckpt from https://huggingface.co/DAMO-NLP-SG/Video-LLaMA-2-13B-Pretrained/ - equip_audio_branch: False - - fusion_head_layers: 2 - max_frame_pos: 32 - fusion_header_type: "seqTransf" - - -datasets: - webvid: - vis_processor: - train: - name: "alpro_video_eval" - n_frms: 8 - image_size: 224 - text_processor: - train: - name: "blip_caption" - -run: - task: video_text_pretrain diff --git a/sonique/Video_LLaMA/eval_configs/video_llama_eval_withaudio.yaml b/sonique/Video_LLaMA/eval_configs/video_llama_eval_withaudio.yaml deleted file mode 100644 index c2fa1178fc62fa378b332500831d955d17652bd3..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/eval_configs/video_llama_eval_withaudio.yaml +++ /dev/null @@ -1,38 +0,0 @@ -model: - arch: video_llama - model_type: pretrain_vicuna - freeze_vit: True - freeze_qformer: True - max_txt_len: 512 - end_sym: "###" - low_resource: False - - frozen_llama_proj: False - - # If you want use LLaMA-2-chat, - # some ckpts could be download from our provided huggingface repo - # i.e. https://huggingface.co/DAMO-NLP-SG/Video-LLaMA-2-13B-Finetuned - llama_model: "./ckpt/llama-2-13b-chat-hf" # "ckpt/vicuna-13b/" or "ckpt/vicuna-7b/" or "ckpt/llama-2-7b-chat-hf" or "ckpt/llama-2-13b-chat-hf" - imagebind_ckpt_path: "./ckpt/" - ckpt: './ckpt/VL_LLaMA_2_13B_Finetuned.pth' # you can use our pretrained ckpt from https://huggingface.co/DAMO-NLP-SG/Video-LLaMA-2-13B-Pretrained/ - ckpt_2: './ckpt/AL_LLaMA_2_13B_Finetuned.pth' - - equip_audio_branch: True # whether equips the audio branch - fusion_head_layers: 2 - max_frame_pos: 32 - fusion_header_type: "seqTransf" - - -datasets: - webvid: - vis_processor: - train: - name: "alpro_video_eval" - n_frms: 8 - image_size: 224 - text_processor: - train: - name: "blip_caption" - -run: - task: video_text_pretrain diff --git a/sonique/Video_LLaMA/inference.py b/sonique/Video_LLaMA/inference.py deleted file mode 100644 index cf96ca7187028f97319ce27a68d078570ca83d8d..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/inference.py +++ /dev/null @@ -1,94 +0,0 @@ -import argparse -import os -import random - -import numpy as np -import torch -import torch.backends.cudnn as cudnn -import gradio as gr -from torch.cuda.amp import autocast - -from sonique.Video_LLaMA.video_llama.common.config import Config -from sonique.Video_LLaMA.video_llama.common.dist_utils import get_rank -from sonique.Video_LLaMA.video_llama.common.registry import registry -from sonique.Video_LLaMA.video_llama.conversation.conversation_video import Chat, Conversation, default_conversation,SeparatorStyle,conv_llava_llama_2 -import decord -import gc - -decord.bridge.set_bridge('torch') - -from sonique.Video_LLaMA.video_llama.datasets.builders import * -from sonique.Video_LLaMA.video_llama.models import * -from sonique.Video_LLaMA.video_llama.processors import * -from sonique.Video_LLaMA.video_llama.runners import * -from sonique.Video_LLaMA.video_llama.tasks import * - -decord.bridge.set_bridge('torch') - - -def generate_prompt_from_video_description(cfg_path, gpu_id, model_type, input_file, num_beams=1, temperature=1.0, low_resource=False): - # initialize model - args = argparse.Namespace(cfg_path=cfg_path, gpu_id=gpu_id, model_type=model_type, options=[]) - cfg = Config(args) - - model_config = cfg.model_cfg - model_config.device_8bit = args.gpu_id - model_config.low_resource = low_resource - model_cls = registry.get_model_class(model_config.arch) - - model = model_cls.from_config(model_config).to('cuda:{}'.format(args.gpu_id)) - model.eval() - vis_processor_cfg = cfg.datasets_cfg.webvid.vis_processor.train - vis_processor = registry.get_processor_class(vis_processor_cfg.name).from_config(vis_processor_cfg) - if args.model_type == 'vicuna': - chat_state = default_conversation.copy() - else: - chat_state = conv_llava_llama_2.copy() - chat = Chat(model, vis_processor, device=f'cuda:{args.gpu_id}') - - # process input - if input_file.endswith('.jpg') or input_file.endswith('.png'): - print(input_file) - # chatbot = chatbot + [((input_file,), None)] - chat_state.system = "You are able to understand the visual content that the user provides. Follow the instructions carefully and explain your answers in detail." - img_list = [] - llm_message = chat.upload_img(input_file, chat_state, img_list) - elif input_file.endswith('.mp4'): - print(input_file) - # chatbot = chatbot + [((input_file,), None)] - chat_state.system = "You are able to understand the visual content that the user provides. Follow the instructions carefully and explain your answers in detail." - img_list = [] - llm_message = chat.upload_video_without_audio(input_file, chat_state, img_list) - - else: - print("Unsupported file type") - return - - question = "Describe the scene in detail" - # question = """ - # As a music composer fluent in English, you're tasked with creating background music for a video. - # Based on the scene described, provide a set of tags in English that describe this background music for the video. - # Do not use the tags from the example. - # Please only return the set of tags that describe this background music for the input video without any explanation. - # Return the tags in the following format: - # Tags: [Tags1, Tags2, ..., Tempo (BPM)] - # Example format: - # Tags: [Piano, Synths, Strings, Violin, Flute, Reflective, Slow tempo, 96 BPM] - # """ - with autocast(): - chat.ask(question, chat_state) - - llm_response = chat.answer(conv=chat_state, - img_list=img_list, - num_beams=num_beams, - temperature=temperature, - max_new_tokens=512, - max_length=2000)[0] - print("Chatbot response:", llm_response) - - # clean up cache - del model - gc.collect() - torch.cuda.empty_cache() - return llm_response - diff --git a/sonique/Video_LLaMA/video_llama/__init__.py b/sonique/Video_LLaMA/video_llama/__init__.py deleted file mode 100644 index b1d7ae12a3dba7b6dcfcf9681a8530e3794172ae..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/__init__.py +++ /dev/null @@ -1,31 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import os -import sys - -from omegaconf import OmegaConf - -from sonique.Video_LLaMA.video_llama.common.registry import registry - -from sonique.Video_LLaMA.video_llama.datasets.builders import * -from sonique.Video_LLaMA.video_llama.models import * -from sonique.Video_LLaMA.video_llama.processors import * -from sonique.Video_LLaMA.video_llama.tasks import * - - -root_dir = os.path.dirname(os.path.abspath(__file__)) -default_cfg = OmegaConf.load(os.path.join(root_dir, "configs/default.yaml")) - -registry.register_path("library_root", root_dir) -repo_root = os.path.join(root_dir, "..") -registry.register_path("repo_root", repo_root) -cache_root = os.path.join(repo_root, default_cfg.env.cache_root) -registry.register_path("cache_root", cache_root) - -registry.register("MAX_INT", sys.maxsize) -registry.register("SPLIT_NAMES", ["train", "val", "test"]) diff --git a/sonique/Video_LLaMA/video_llama/common/__init__.py b/sonique/Video_LLaMA/video_llama/common/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/sonique/Video_LLaMA/video_llama/common/config.py b/sonique/Video_LLaMA/video_llama/common/config.py deleted file mode 100644 index 8a0fa488f6f3cc5d522e071ed424c73cd3c23ba3..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/common/config.py +++ /dev/null @@ -1,468 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import logging -import json -from typing import Dict - -from omegaconf import OmegaConf -from sonique.Video_LLaMA.video_llama.common.registry import registry - - -class Config: - def __init__(self, args): - self.config = {} - - self.args = args - - # Register the config and configuration for setup - registry.register("configuration", self) - - user_config = self._build_opt_list(self.args.options) - - config = OmegaConf.load(self.args.cfg_path) - - runner_config = self.build_runner_config(config) - model_config = self.build_model_config(config, **user_config) - dataset_config = self.build_dataset_config(config) - - # Validate the user-provided runner configuration - # model and dataset configuration are supposed to be validated by the respective classes - # [TODO] validate the model/dataset configuration - # self._validate_runner_config(runner_config) - - # Override the default configuration with user options. - self.config = OmegaConf.merge( - runner_config, model_config, dataset_config, user_config - ) - - def _validate_runner_config(self, runner_config): - """ - This method validates the configuration, such that - 1) all the user specified options are valid; - 2) no type mismatches between the user specified options and the config. - """ - runner_config_validator = create_runner_config_validator() - runner_config_validator.validate(runner_config) - - def _build_opt_list(self, opts): - opts_dot_list = self._convert_to_dot_list(opts) - return OmegaConf.from_dotlist(opts_dot_list) - - @staticmethod - def build_model_config(config, **kwargs): - model = config.get("model", None) - assert model is not None, "Missing model configuration file." - - model_cls = registry.get_model_class(model.arch) - assert model_cls is not None, f"Model '{model.arch}' has not been registered." - - model_type = kwargs.get("model.model_type", None) - if not model_type: - model_type = model.get("model_type", None) - # else use the model type selected by user. - - assert model_type is not None, "Missing model_type." - - model_config_path = model_cls.default_config_path(model_type=model_type) - - model_config = OmegaConf.create() - # hierarchy override, customized config > default config - model_config = OmegaConf.merge( - model_config, - OmegaConf.load(model_config_path), - {"model": config["model"]}, - ) - - return model_config - - @staticmethod - def build_runner_config(config): - return {"run": config.run} - - @staticmethod - def build_dataset_config(config): - datasets = config.get("datasets", None) - if datasets is None: - raise KeyError( - "Expecting 'datasets' as the root key for dataset configuration." - ) - - dataset_config = OmegaConf.create() - - for dataset_name in datasets: - builder_cls = registry.get_builder_class(dataset_name) - - dataset_config_type = datasets[dataset_name].get("type", "default") - dataset_config_path = builder_cls.default_config_path( - type=dataset_config_type - ) - - # hierarchy override, customized config > default config - dataset_config = OmegaConf.merge( - dataset_config, - OmegaConf.load(dataset_config_path), - {"datasets": {dataset_name: config["datasets"][dataset_name]}}, - ) - - return dataset_config - - def _convert_to_dot_list(self, opts): - if opts is None: - opts = [] - - if len(opts) == 0: - return opts - - has_equal = opts[0].find("=") != -1 - - if has_equal: - return opts - - return [(opt + "=" + value) for opt, value in zip(opts[0::2], opts[1::2])] - - def get_config(self): - return self.config - - @property - def run_cfg(self): - return self.config.run - - @property - def datasets_cfg(self): - return self.config.datasets - - @property - def model_cfg(self): - return self.config.model - - def pretty_print(self): - logging.info("\n===== Running Parameters =====") - logging.info(self._convert_node_to_json(self.config.run)) - - logging.info("\n====== Dataset Attributes ======") - datasets = self.config.datasets - - for dataset in datasets: - if dataset in self.config.datasets: - logging.info(f"\n======== {dataset} =======") - dataset_config = self.config.datasets[dataset] - logging.info(self._convert_node_to_json(dataset_config)) - else: - logging.warning(f"No dataset named '{dataset}' in config. Skipping") - - logging.info(f"\n====== Model Attributes ======") - logging.info(self._convert_node_to_json(self.config.model)) - - def _convert_node_to_json(self, node): - container = OmegaConf.to_container(node, resolve=True) - return json.dumps(container, indent=4, sort_keys=True) - - def to_dict(self): - return OmegaConf.to_container(self.config) - - -def node_to_dict(node): - return OmegaConf.to_container(node) - - -class ConfigValidator: - """ - This is a preliminary implementation to centralize and validate the configuration. - May be altered in the future. - - A helper class to validate configurations from yaml file. - - This serves the following purposes: - 1. Ensure all the options in the yaml are defined, raise error if not. - 2. when type mismatches are found, the validator will raise an error. - 3. a central place to store and display helpful messages for supported configurations. - - """ - - class _Argument: - def __init__(self, name, choices=None, type=None, help=None): - self.name = name - self.val = None - self.choices = choices - self.type = type - self.help = help - - def __str__(self): - s = f"{self.name}={self.val}" - if self.type is not None: - s += f", ({self.type})" - if self.choices is not None: - s += f", choices: {self.choices}" - if self.help is not None: - s += f", ({self.help})" - return s - - def __init__(self, description): - self.description = description - - self.arguments = dict() - - self.parsed_args = None - - def __getitem__(self, key): - assert self.parsed_args is not None, "No arguments parsed yet." - - return self.parsed_args[key] - - def __str__(self) -> str: - return self.format_help() - - def add_argument(self, *args, **kwargs): - """ - Assume the first argument is the name of the argument. - """ - self.arguments[args[0]] = self._Argument(*args, **kwargs) - - def validate(self, config=None): - """ - Convert yaml config (dict-like) to list, required by argparse. - """ - for k, v in config.items(): - assert ( - k in self.arguments - ), f"""{k} is not a valid argument. Support arguments are {self.format_arguments()}.""" - - if self.arguments[k].type is not None: - try: - self.arguments[k].val = self.arguments[k].type(v) - except ValueError: - raise ValueError(f"{k} is not a valid {self.arguments[k].type}.") - - if self.arguments[k].choices is not None: - assert ( - v in self.arguments[k].choices - ), f"""{k} must be one of {self.arguments[k].choices}.""" - - return config - - def format_arguments(self): - return str([f"{k}" for k in sorted(self.arguments.keys())]) - - def format_help(self): - # description + key-value pair string for each argument - help_msg = str(self.description) - return help_msg + ", available arguments: " + self.format_arguments() - - def print_help(self): - # display help message - print(self.format_help()) - - -def create_runner_config_validator(): - validator = ConfigValidator(description="Runner configurations") - - validator.add_argument( - "runner", - type=str, - choices=["runner_base", "runner_iter"], - help="""Runner to use. The "runner_base" uses epoch-based training while iter-based - runner runs based on iters. Default: runner_base""", - ) - # add argumetns for training dataset ratios - validator.add_argument( - "train_dataset_ratios", - type=Dict[str, float], - help="""Ratios of training dataset. This is used in iteration-based runner. - Do not support for epoch-based runner because how to define an epoch becomes tricky. - Default: None""", - ) - validator.add_argument( - "max_iters", - type=float, - help="Maximum number of iterations to run.", - ) - validator.add_argument( - "max_epoch", - type=int, - help="Maximum number of epochs to run.", - ) - # add arguments for iters_per_inner_epoch - validator.add_argument( - "iters_per_inner_epoch", - type=float, - help="Number of iterations per inner epoch. This is required when runner is runner_iter.", - ) - lr_scheds_choices = registry.list_lr_schedulers() - validator.add_argument( - "lr_sched", - type=str, - choices=lr_scheds_choices, - help="Learning rate scheduler to use, from {}".format(lr_scheds_choices), - ) - task_choices = registry.list_tasks() - validator.add_argument( - "task", - type=str, - choices=task_choices, - help="Task to use, from {}".format(task_choices), - ) - # add arguments for init_lr - validator.add_argument( - "init_lr", - type=float, - help="Initial learning rate. This will be the learning rate after warmup and before decay.", - ) - # add arguments for min_lr - validator.add_argument( - "min_lr", - type=float, - help="Minimum learning rate (after decay).", - ) - # add arguments for warmup_lr - validator.add_argument( - "warmup_lr", - type=float, - help="Starting learning rate for warmup.", - ) - # add arguments for learning rate decay rate - validator.add_argument( - "lr_decay_rate", - type=float, - help="Learning rate decay rate. Required if using a decaying learning rate scheduler.", - ) - # add arguments for weight decay - validator.add_argument( - "weight_decay", - type=float, - help="Weight decay rate.", - ) - # add arguments for training batch size - validator.add_argument( - "batch_size_train", - type=int, - help="Training batch size.", - ) - # add arguments for evaluation batch size - validator.add_argument( - "batch_size_eval", - type=int, - help="Evaluation batch size, including validation and testing.", - ) - # add arguments for number of workers for data loading - validator.add_argument( - "num_workers", - help="Number of workers for data loading.", - ) - # add arguments for warm up steps - validator.add_argument( - "warmup_steps", - type=int, - help="Number of warmup steps. Required if a warmup schedule is used.", - ) - # add arguments for random seed - validator.add_argument( - "seed", - type=int, - help="Random seed.", - ) - # add arguments for output directory - validator.add_argument( - "output_dir", - type=str, - help="Output directory to save checkpoints and logs.", - ) - # add arguments for whether only use evaluation - validator.add_argument( - "evaluate", - help="Whether to only evaluate the model. If true, training will not be performed.", - ) - # add arguments for splits used for training, e.g. ["train", "val"] - validator.add_argument( - "train_splits", - type=list, - help="Splits to use for training.", - ) - # add arguments for splits used for validation, e.g. ["val"] - validator.add_argument( - "valid_splits", - type=list, - help="Splits to use for validation. If not provided, will skip the validation.", - ) - # add arguments for splits used for testing, e.g. ["test"] - validator.add_argument( - "test_splits", - type=list, - help="Splits to use for testing. If not provided, will skip the testing.", - ) - # add arguments for accumulating gradient for iterations - validator.add_argument( - "accum_grad_iters", - type=int, - help="Number of iterations to accumulate gradient for.", - ) - - # ====== distributed training ====== - validator.add_argument( - "device", - type=str, - choices=["cpu", "cuda"], - help="Device to use. Support 'cuda' or 'cpu' as for now.", - ) - validator.add_argument( - "world_size", - type=int, - help="Number of processes participating in the job.", - ) - validator.add_argument("dist_url", type=str) - validator.add_argument("distributed", type=bool) - # add arguments to opt using distributed sampler during evaluation or not - validator.add_argument( - "use_dist_eval_sampler", - type=bool, - help="Whether to use distributed sampler during evaluation or not.", - ) - - # ====== task specific ====== - # generation task specific arguments - # add arguments for maximal length of text output - validator.add_argument( - "max_len", - type=int, - help="Maximal length of text output.", - ) - # add arguments for minimal length of text output - validator.add_argument( - "min_len", - type=int, - help="Minimal length of text output.", - ) - # add arguments number of beams - validator.add_argument( - "num_beams", - type=int, - help="Number of beams used for beam search.", - ) - - # vqa task specific arguments - # add arguments for number of answer candidates - validator.add_argument( - "num_ans_candidates", - type=int, - help="""For ALBEF and BLIP, these models first rank answers according to likelihood to select answer candidates.""", - ) - # add arguments for inference method - validator.add_argument( - "inference_method", - type=str, - choices=["genearte", "rank"], - help="""Inference method to use for question answering. If rank, requires a answer list.""", - ) - - # ====== model specific ====== - validator.add_argument( - "k_test", - type=int, - help="Number of top k most similar samples from ITC/VTC selection to be tested.", - ) - - return validator diff --git a/sonique/Video_LLaMA/video_llama/common/dist_utils.py b/sonique/Video_LLaMA/video_llama/common/dist_utils.py deleted file mode 100644 index 9280150bf5122d51bb810a9f0258a233e7088647..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/common/dist_utils.py +++ /dev/null @@ -1,137 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import datetime -import functools -import os - -import torch -import torch.distributed as dist -import timm.models.hub as timm_hub - - -def setup_for_distributed(is_master): - """ - This function disables printing when not in master process - """ - import builtins as __builtin__ - - builtin_print = __builtin__.print - - def print(*args, **kwargs): - force = kwargs.pop("force", False) - if is_master or force: - builtin_print(*args, **kwargs) - - __builtin__.print = print - - -def is_dist_avail_and_initialized(): - if not dist.is_available(): - return False - if not dist.is_initialized(): - return False - return True - - -def get_world_size(): - if not is_dist_avail_and_initialized(): - return 1 - return dist.get_world_size() - - -def get_rank(): - if not is_dist_avail_and_initialized(): - return 0 - return dist.get_rank() - - -def is_main_process(): - return get_rank() == 0 - - -def init_distributed_mode(args): - if "RANK" in os.environ and "WORLD_SIZE" in os.environ: - args.rank = int(os.environ["RANK"]) - args.world_size = int(os.environ["WORLD_SIZE"]) - args.gpu = int(os.environ["LOCAL_RANK"]) - elif "SLURM_PROCID" in os.environ: - args.rank = int(os.environ["SLURM_PROCID"]) - args.gpu = args.rank % torch.cuda.device_count() - else: - print("Not using distributed mode") - args.distributed = False - return - - args.distributed = True - - torch.cuda.set_device(args.gpu) - args.dist_backend = "nccl" - print( - "| distributed init (rank {}, world {}): {}".format( - args.rank, args.world_size, args.dist_url - ), - flush=True, - ) - torch.distributed.init_process_group( - backend=args.dist_backend, - init_method=args.dist_url, - world_size=args.world_size, - rank=args.rank, - timeout=datetime.timedelta( - days=365 - ), # allow auto-downloading and de-compressing - ) - torch.distributed.barrier() - setup_for_distributed(args.rank == 0) - - -def get_dist_info(): - if torch.__version__ < "1.0": - initialized = dist._initialized - else: - initialized = dist.is_initialized() - if initialized: - rank = dist.get_rank() - world_size = dist.get_world_size() - else: # non-distributed training - rank = 0 - world_size = 1 - return rank, world_size - - -def main_process(func): - @functools.wraps(func) - def wrapper(*args, **kwargs): - rank, _ = get_dist_info() - if rank == 0: - return func(*args, **kwargs) - - return wrapper - - -def download_cached_file(url, check_hash=True, progress=False): - """ - Download a file from a URL and cache it locally. If the file already exists, it is not downloaded again. - If distributed, only the main process downloads the file, and the other processes wait for the file to be downloaded. - """ - - def get_cached_file_path(): - # a hack to sync the file path across processes - parts = torch.hub.urlparse(url) - filename = os.path.basename(parts.path) - cached_file = os.path.join(timm_hub.get_cache_dir(), filename) - - return cached_file - - if is_main_process(): - timm_hub.download_cached_file(url, check_hash, progress) - - if is_dist_avail_and_initialized(): - dist.barrier() - - return get_cached_file_path() diff --git a/sonique/Video_LLaMA/video_llama/common/gradcam.py b/sonique/Video_LLaMA/video_llama/common/gradcam.py deleted file mode 100644 index d53a5254d4b319eaf2cbfbd081b0ca8e38c5c7a0..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/common/gradcam.py +++ /dev/null @@ -1,24 +0,0 @@ -import numpy as np -from matplotlib import pyplot as plt -from scipy.ndimage import filters -from skimage import transform as skimage_transform - - -def getAttMap(img, attMap, blur=True, overlap=True): - attMap -= attMap.min() - if attMap.max() > 0: - attMap /= attMap.max() - attMap = skimage_transform.resize(attMap, (img.shape[:2]), order=3, mode="constant") - if blur: - attMap = filters.gaussian_filter(attMap, 0.02 * max(img.shape[:2])) - attMap -= attMap.min() - attMap /= attMap.max() - cmap = plt.get_cmap("jet") - attMapV = cmap(attMap) - attMapV = np.delete(attMapV, 3, 2) - if overlap: - attMap = ( - 1 * (1 - attMap**0.7).reshape(attMap.shape + (1,)) * img - + (attMap**0.7).reshape(attMap.shape + (1,)) * attMapV - ) - return attMap diff --git a/sonique/Video_LLaMA/video_llama/common/logger.py b/sonique/Video_LLaMA/video_llama/common/logger.py deleted file mode 100644 index f800a6d039566544e7373e16d7993ee6c34b69c1..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/common/logger.py +++ /dev/null @@ -1,195 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import datetime -import logging -import time -from collections import defaultdict, deque - -import torch -import torch.distributed as dist - -from sonique.Video_LLaMA.video_llama.common import dist_utils - - -class SmoothedValue(object): - """Track a series of values and provide access to smoothed values over a - window or the global series average. - """ - - def __init__(self, window_size=20, fmt=None): - if fmt is None: - fmt = "{median:.4f} ({global_avg:.4f})" - self.deque = deque(maxlen=window_size) - self.total = 0.0 - self.count = 0 - self.fmt = fmt - - def update(self, value, n=1): - self.deque.append(value) - self.count += n - self.total += value * n - - def synchronize_between_processes(self): - """ - Warning: does not synchronize the deque! - """ - if not dist_utils.is_dist_avail_and_initialized(): - return - t = torch.tensor([self.count, self.total], dtype=torch.float64, device="cuda") - dist.barrier() - dist.all_reduce(t) - t = t.tolist() - self.count = int(t[0]) - self.total = t[1] - - @property - def median(self): - d = torch.tensor(list(self.deque)) - return d.median().item() - - @property - def avg(self): - d = torch.tensor(list(self.deque), dtype=torch.float32) - return d.mean().item() - - @property - def global_avg(self): - return self.total / self.count - - @property - def max(self): - return max(self.deque) - - @property - def value(self): - return self.deque[-1] - - def __str__(self): - return self.fmt.format( - median=self.median, - avg=self.avg, - global_avg=self.global_avg, - max=self.max, - value=self.value, - ) - - -class MetricLogger(object): - def __init__(self, delimiter="\t"): - self.meters = defaultdict(SmoothedValue) - self.delimiter = delimiter - - def update(self, **kwargs): - for k, v in kwargs.items(): - if isinstance(v, torch.Tensor): - v = v.item() - assert isinstance(v, (float, int)) - self.meters[k].update(v) - - def __getattr__(self, attr): - if attr in self.meters: - return self.meters[attr] - if attr in self.__dict__: - return self.__dict__[attr] - raise AttributeError( - "'{}' object has no attribute '{}'".format(type(self).__name__, attr) - ) - - def __str__(self): - loss_str = [] - for name, meter in self.meters.items(): - loss_str.append("{}: {}".format(name, str(meter))) - return self.delimiter.join(loss_str) - - def global_avg(self): - loss_str = [] - for name, meter in self.meters.items(): - loss_str.append("{}: {:.4f}".format(name, meter.global_avg)) - return self.delimiter.join(loss_str) - - def synchronize_between_processes(self): - for meter in self.meters.values(): - meter.synchronize_between_processes() - - def add_meter(self, name, meter): - self.meters[name] = meter - - def log_every(self, iterable, print_freq, header=None): - i = 0 - if not header: - header = "" - start_time = time.time() - end = time.time() - iter_time = SmoothedValue(fmt="{avg:.4f}") - data_time = SmoothedValue(fmt="{avg:.4f}") - space_fmt = ":" + str(len(str(len(iterable)))) + "d" - log_msg = [ - header, - "[{0" + space_fmt + "}/{1}]", - "eta: {eta}", - "{meters}", - "time: {time}", - "data: {data}", - ] - if torch.cuda.is_available(): - log_msg.append("max mem: {memory:.0f}") - log_msg = self.delimiter.join(log_msg) - MB = 1024.0 * 1024.0 - for obj in iterable: - data_time.update(time.time() - end) - yield obj - iter_time.update(time.time() - end) - if i % print_freq == 0 or i == len(iterable) - 1: - eta_seconds = iter_time.global_avg * (len(iterable) - i) - eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) - if torch.cuda.is_available(): - print( - log_msg.format( - i, - len(iterable), - eta=eta_string, - meters=str(self), - time=str(iter_time), - data=str(data_time), - memory=torch.cuda.max_memory_allocated() / MB, - ) - ) - else: - print( - log_msg.format( - i, - len(iterable), - eta=eta_string, - meters=str(self), - time=str(iter_time), - data=str(data_time), - ) - ) - i += 1 - end = time.time() - total_time = time.time() - start_time - total_time_str = str(datetime.timedelta(seconds=int(total_time))) - print( - "{} Total time: {} ({:.4f} s / it)".format( - header, total_time_str, total_time / len(iterable) - ) - ) - - -class AttrDict(dict): - def __init__(self, *args, **kwargs): - super(AttrDict, self).__init__(*args, **kwargs) - self.__dict__ = self - - -def setup_logger(): - logging.basicConfig( - level=logging.INFO if dist_utils.is_main_process() else logging.WARN, - format="%(asctime)s [%(levelname)s] %(message)s", - handlers=[logging.StreamHandler()], - ) diff --git a/sonique/Video_LLaMA/video_llama/common/optims.py b/sonique/Video_LLaMA/video_llama/common/optims.py deleted file mode 100644 index c6825c6131d22e67a15140207bdf9c2858149734..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/common/optims.py +++ /dev/null @@ -1,119 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import math - -from sonique.Video_LLaMA.video_llama.common.registry import registry - - -@registry.register_lr_scheduler("linear_warmup_step_lr") -class LinearWarmupStepLRScheduler: - def __init__( - self, - optimizer, - max_epoch, - min_lr, - init_lr, - decay_rate=1, - warmup_start_lr=-1, - warmup_steps=0, - **kwargs - ): - self.optimizer = optimizer - - self.max_epoch = max_epoch - self.min_lr = min_lr - - self.decay_rate = decay_rate - - self.init_lr = init_lr - self.warmup_steps = warmup_steps - self.warmup_start_lr = warmup_start_lr if warmup_start_lr >= 0 else init_lr - - def step(self, cur_epoch, cur_step): - if cur_epoch == 0: - warmup_lr_schedule( - step=cur_step, - optimizer=self.optimizer, - max_step=self.warmup_steps, - init_lr=self.warmup_start_lr, - max_lr=self.init_lr, - ) - else: - step_lr_schedule( - epoch=cur_epoch, - optimizer=self.optimizer, - init_lr=self.init_lr, - min_lr=self.min_lr, - decay_rate=self.decay_rate, - ) - - -@registry.register_lr_scheduler("linear_warmup_cosine_lr") -class LinearWarmupCosineLRScheduler: - def __init__( - self, - optimizer, - max_epoch, - iters_per_epoch, - min_lr, - init_lr, - warmup_steps=0, - warmup_start_lr=-1, - **kwargs - ): - self.optimizer = optimizer - - self.max_epoch = max_epoch - self.iters_per_epoch = iters_per_epoch - self.min_lr = min_lr - - self.init_lr = init_lr - self.warmup_steps = warmup_steps - self.warmup_start_lr = warmup_start_lr if warmup_start_lr >= 0 else init_lr - - def step(self, cur_epoch, cur_step): - total_cur_step = cur_epoch * self.iters_per_epoch + cur_step - if total_cur_step < self.warmup_steps: - warmup_lr_schedule( - step=cur_step, - optimizer=self.optimizer, - max_step=self.warmup_steps, - init_lr=self.warmup_start_lr, - max_lr=self.init_lr, - ) - else: - cosine_lr_schedule( - epoch=total_cur_step, - optimizer=self.optimizer, - max_epoch=self.max_epoch * self.iters_per_epoch, - init_lr=self.init_lr, - min_lr=self.min_lr, - ) - - -def cosine_lr_schedule(optimizer, epoch, max_epoch, init_lr, min_lr): - """Decay the learning rate""" - lr = (init_lr - min_lr) * 0.5 * ( - 1.0 + math.cos(math.pi * epoch / max_epoch) - ) + min_lr - for param_group in optimizer.param_groups: - param_group["lr"] = lr - - -def warmup_lr_schedule(optimizer, step, max_step, init_lr, max_lr): - """Warmup the learning rate""" - lr = min(max_lr, init_lr + (max_lr - init_lr) * step / max(max_step, 1)) - for param_group in optimizer.param_groups: - param_group["lr"] = lr - - -def step_lr_schedule(optimizer, epoch, init_lr, min_lr, decay_rate): - """Decay the learning rate""" - lr = max(min_lr, init_lr * (decay_rate**epoch)) - for param_group in optimizer.param_groups: - param_group["lr"] = lr diff --git a/sonique/Video_LLaMA/video_llama/common/registry.py b/sonique/Video_LLaMA/video_llama/common/registry.py deleted file mode 100644 index 0be0b1b7324ff500787ea2ca4029d5835898acb8..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/common/registry.py +++ /dev/null @@ -1,329 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - - -class Registry: - mapping = { - "builder_name_mapping": {}, - "task_name_mapping": {}, - "processor_name_mapping": {}, - "model_name_mapping": {}, - "lr_scheduler_name_mapping": {}, - "runner_name_mapping": {}, - "state": {}, - "paths": {}, - } - - @classmethod - def register_builder(cls, name): - r"""Register a dataset builder to registry with key 'name' - - Args: - name: Key with which the builder will be registered. - - Usage: - - from video_llama.common.registry import registry - from video_llama.datasets.base_dataset_builder import BaseDatasetBuilder - """ - - def wrap(builder_cls): - from sonique.Video_LLaMA.video_llama.datasets.builders.base_dataset_builder import BaseDatasetBuilder - - assert issubclass( - builder_cls, BaseDatasetBuilder - ), "All builders must inherit BaseDatasetBuilder class, found {}".format( - builder_cls - ) - if name in cls.mapping["builder_name_mapping"]: - raise KeyError( - "Name '{}' already registered for {}.".format( - name, cls.mapping["builder_name_mapping"][name] - ) - ) - cls.mapping["builder_name_mapping"][name] = builder_cls - return builder_cls - - return wrap - - @classmethod - def register_task(cls, name): - r"""Register a task to registry with key 'name' - - Args: - name: Key with which the task will be registered. - - Usage: - - from video_llama.common.registry import registry - """ - - def wrap(task_cls): - from sonique.Video_LLaMA.video_llama.tasks.base_task import BaseTask - - assert issubclass( - task_cls, BaseTask - ), "All tasks must inherit BaseTask class" - if name in cls.mapping["task_name_mapping"]: - raise KeyError( - "Name '{}' already registered for {}.".format( - name, cls.mapping["task_name_mapping"][name] - ) - ) - cls.mapping["task_name_mapping"][name] = task_cls - return task_cls - - return wrap - - @classmethod - def register_model(cls, name): - r"""Register a task to registry with key 'name' - - Args: - name: Key with which the task will be registered. - - Usage: - - from video_llama.common.registry import registry - """ - - def wrap(model_cls): - from sonique.Video_LLaMA.video_llama.models import BaseModel - - assert issubclass( - model_cls, BaseModel - ), "All models must inherit BaseModel class" - if name in cls.mapping["model_name_mapping"]: - raise KeyError( - "Name '{}' already registered for {}.".format( - name, cls.mapping["model_name_mapping"][name] - ) - ) - cls.mapping["model_name_mapping"][name] = model_cls - return model_cls - - return wrap - - @classmethod - def register_processor(cls, name): - r"""Register a processor to registry with key 'name' - - Args: - name: Key with which the task will be registered. - - Usage: - - from video_llama.common.registry import registry - """ - - def wrap(processor_cls): - from sonique.Video_LLaMA.video_llama.processors import BaseProcessor - - assert issubclass( - processor_cls, BaseProcessor - ), "All processors must inherit BaseProcessor class" - if name in cls.mapping["processor_name_mapping"]: - raise KeyError( - "Name '{}' already registered for {}.".format( - name, cls.mapping["processor_name_mapping"][name] - ) - ) - cls.mapping["processor_name_mapping"][name] = processor_cls - return processor_cls - - return wrap - - @classmethod - def register_lr_scheduler(cls, name): - r"""Register a model to registry with key 'name' - - Args: - name: Key with which the task will be registered. - - Usage: - - from video_llama.common.registry import registry - """ - - def wrap(lr_sched_cls): - if name in cls.mapping["lr_scheduler_name_mapping"]: - raise KeyError( - "Name '{}' already registered for {}.".format( - name, cls.mapping["lr_scheduler_name_mapping"][name] - ) - ) - cls.mapping["lr_scheduler_name_mapping"][name] = lr_sched_cls - return lr_sched_cls - - return wrap - - @classmethod - def register_runner(cls, name): - r"""Register a model to registry with key 'name' - - Args: - name: Key with which the task will be registered. - - Usage: - - from video_llama.common.registry import registry - """ - - def wrap(runner_cls): - if name in cls.mapping["runner_name_mapping"]: - raise KeyError( - "Name '{}' already registered for {}.".format( - name, cls.mapping["runner_name_mapping"][name] - ) - ) - cls.mapping["runner_name_mapping"][name] = runner_cls - return runner_cls - - return wrap - - @classmethod - def register_path(cls, name, path): - r"""Register a path to registry with key 'name' - - Args: - name: Key with which the path will be registered. - - Usage: - - from video_llama.common.registry import registry - """ - assert isinstance(path, str), "All path must be str." - if name in cls.mapping["paths"]: - raise KeyError("Name '{}' already registered.".format(name)) - cls.mapping["paths"][name] = path - - @classmethod - def register(cls, name, obj): - r"""Register an item to registry with key 'name' - - Args: - name: Key with which the item will be registered. - - Usage:: - - from video_llama.common.registry import registry - - registry.register("config", {}) - """ - path = name.split(".") - current = cls.mapping["state"] - - for part in path[:-1]: - if part not in current: - current[part] = {} - current = current[part] - - current[path[-1]] = obj - - # @classmethod - # def get_trainer_class(cls, name): - # return cls.mapping["trainer_name_mapping"].get(name, None) - - @classmethod - def get_builder_class(cls, name): - return cls.mapping["builder_name_mapping"].get(name, None) - - @classmethod - def get_model_class(cls, name): - return cls.mapping["model_name_mapping"].get(name, None) - - @classmethod - def get_task_class(cls, name): - return cls.mapping["task_name_mapping"].get(name, None) - - @classmethod - def get_processor_class(cls, name): - return cls.mapping["processor_name_mapping"].get(name, None) - - @classmethod - def get_lr_scheduler_class(cls, name): - return cls.mapping["lr_scheduler_name_mapping"].get(name, None) - - @classmethod - def get_runner_class(cls, name): - return cls.mapping["runner_name_mapping"].get(name, None) - - @classmethod - def list_runners(cls): - return sorted(cls.mapping["runner_name_mapping"].keys()) - - @classmethod - def list_models(cls): - return sorted(cls.mapping["model_name_mapping"].keys()) - - @classmethod - def list_tasks(cls): - return sorted(cls.mapping["task_name_mapping"].keys()) - - @classmethod - def list_processors(cls): - return sorted(cls.mapping["processor_name_mapping"].keys()) - - @classmethod - def list_lr_schedulers(cls): - return sorted(cls.mapping["lr_scheduler_name_mapping"].keys()) - - @classmethod - def list_datasets(cls): - return sorted(cls.mapping["builder_name_mapping"].keys()) - - @classmethod - def get_path(cls, name): - return cls.mapping["paths"].get(name, None) - - @classmethod - def get(cls, name, default=None, no_warning=False): - r"""Get an item from registry with key 'name' - - Args: - name (string): Key whose value needs to be retrieved. - default: If passed and key is not in registry, default value will - be returned with a warning. Default: None - no_warning (bool): If passed as True, warning when key doesn't exist - will not be generated. Useful for MMF's - internal operations. Default: False - """ - original_name = name - name = name.split(".") - value = cls.mapping["state"] - for subname in name: - value = value.get(subname, default) - if value is default: - break - - if ( - "writer" in cls.mapping["state"] - and value == default - and no_warning is False - ): - cls.mapping["state"]["writer"].warning( - "Key {} is not present in registry, returning default value " - "of {}".format(original_name, default) - ) - return value - - @classmethod - def unregister(cls, name): - r"""Remove an item from registry with key 'name' - - Args: - name: Key which needs to be removed. - Usage:: - - from mmf.common.registry import registry - - config = registry.unregister("config") - """ - return cls.mapping["state"].pop(name, None) - - -registry = Registry() diff --git a/sonique/Video_LLaMA/video_llama/common/utils.py b/sonique/Video_LLaMA/video_llama/common/utils.py deleted file mode 100644 index 6b526e1084da98350b279039acf5ba8e698dcbb6..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/common/utils.py +++ /dev/null @@ -1,424 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import io -import json -import logging -import os -import pickle -import re -import shutil -import urllib -import urllib.error -import urllib.request -from typing import Optional -from urllib.parse import urlparse - -import numpy as np -import pandas as pd -import yaml -from iopath.common.download import download -from iopath.common.file_io import file_lock, g_pathmgr -from sonique.Video_LLaMA.video_llama.common.registry import registry -from torch.utils.model_zoo import tqdm -from torchvision.datasets.utils import ( - check_integrity, - download_file_from_google_drive, - extract_archive, -) - - -def now(): - from datetime import datetime - - return datetime.now().strftime("%Y%m%d%H%M")[:-1] - - -def is_url(url_or_filename): - parsed = urlparse(url_or_filename) - return parsed.scheme in ("http", "https") - - -def get_cache_path(rel_path): - return os.path.expanduser(os.path.join(registry.get_path("cache_root"), rel_path)) - - -def get_abs_path(rel_path): - return os.path.join(registry.get_path("library_root"), rel_path) - - -def load_json(filename): - with open(filename, "r") as f: - return json.load(f) - - -# The following are adapted from torchvision and vissl -# torchvision: https://github.com/pytorch/vision -# vissl: https://github.com/facebookresearch/vissl/blob/main/vissl/utils/download.py - - -def makedir(dir_path): - """ - Create the directory if it does not exist. - """ - is_success = False - try: - if not g_pathmgr.exists(dir_path): - g_pathmgr.mkdirs(dir_path) - is_success = True - except BaseException: - print(f"Error creating directory: {dir_path}") - return is_success - - -def get_redirected_url(url: str): - """ - Given a URL, returns the URL it redirects to or the - original URL in case of no indirection - """ - import requests - - with requests.Session() as session: - with session.get(url, stream=True, allow_redirects=True) as response: - if response.history: - return response.url - else: - return url - - -def to_google_drive_download_url(view_url: str) -> str: - """ - Utility function to transform a view URL of google drive - to a download URL for google drive - Example input: - https://drive.google.com/file/d/137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp/view - Example output: - https://drive.google.com/uc?export=download&id=137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp - """ - splits = view_url.split("/") - assert splits[-1] == "view" - file_id = splits[-2] - return f"https://drive.google.com/uc?export=download&id={file_id}" - - -def download_google_drive_url(url: str, output_path: str, output_file_name: str): - """ - Download a file from google drive - Downloading an URL from google drive requires confirmation when - the file of the size is too big (google drive notifies that - anti-viral checks cannot be performed on such files) - """ - import requests - - with requests.Session() as session: - - # First get the confirmation token and append it to the URL - with session.get(url, stream=True, allow_redirects=True) as response: - for k, v in response.cookies.items(): - if k.startswith("download_warning"): - url = url + "&confirm=" + v - - # Then download the content of the file - with session.get(url, stream=True, verify=True) as response: - makedir(output_path) - path = os.path.join(output_path, output_file_name) - total_size = int(response.headers.get("Content-length", 0)) - with open(path, "wb") as file: - from tqdm import tqdm - - with tqdm(total=total_size) as progress_bar: - for block in response.iter_content( - chunk_size=io.DEFAULT_BUFFER_SIZE - ): - file.write(block) - progress_bar.update(len(block)) - - -def _get_google_drive_file_id(url: str) -> Optional[str]: - parts = urlparse(url) - - if re.match(r"(drive|docs)[.]google[.]com", parts.netloc) is None: - return None - - match = re.match(r"/file/d/(?P[^/]*)", parts.path) - if match is None: - return None - - return match.group("id") - - -def _urlretrieve(url: str, filename: str, chunk_size: int = 1024) -> None: - with open(filename, "wb") as fh: - with urllib.request.urlopen( - urllib.request.Request(url, headers={"User-Agent": "vissl"}) - ) as response: - with tqdm(total=response.length) as pbar: - for chunk in iter(lambda: response.read(chunk_size), ""): - if not chunk: - break - pbar.update(chunk_size) - fh.write(chunk) - - -def download_url( - url: str, - root: str, - filename: Optional[str] = None, - md5: Optional[str] = None, -) -> None: - """Download a file from a url and place it in root. - Args: - url (str): URL to download file from - root (str): Directory to place downloaded file in - filename (str, optional): Name to save the file under. - If None, use the basename of the URL. - md5 (str, optional): MD5 checksum of the download. If None, do not check - """ - root = os.path.expanduser(root) - if not filename: - filename = os.path.basename(url) - fpath = os.path.join(root, filename) - - makedir(root) - - # check if file is already present locally - if check_integrity(fpath, md5): - print("Using downloaded and verified file: " + fpath) - return - - # expand redirect chain if needed - url = get_redirected_url(url) - - # check if file is located on Google Drive - file_id = _get_google_drive_file_id(url) - if file_id is not None: - return download_file_from_google_drive(file_id, root, filename, md5) - - # download the file - try: - print("Downloading " + url + " to " + fpath) - _urlretrieve(url, fpath) - except (urllib.error.URLError, IOError) as e: # type: ignore[attr-defined] - if url[:5] == "https": - url = url.replace("https:", "http:") - print( - "Failed download. Trying https -> http instead." - " Downloading " + url + " to " + fpath - ) - _urlretrieve(url, fpath) - else: - raise e - - # check integrity of downloaded file - if not check_integrity(fpath, md5): - raise RuntimeError("File not found or corrupted.") - - -def download_and_extract_archive( - url: str, - download_root: str, - extract_root: Optional[str] = None, - filename: Optional[str] = None, - md5: Optional[str] = None, - remove_finished: bool = False, -) -> None: - download_root = os.path.expanduser(download_root) - if extract_root is None: - extract_root = download_root - if not filename: - filename = os.path.basename(url) - - download_url(url, download_root, filename, md5) - - archive = os.path.join(download_root, filename) - print("Extracting {} to {}".format(archive, extract_root)) - extract_archive(archive, extract_root, remove_finished) - - -def cache_url(url: str, cache_dir: str) -> str: - """ - This implementation downloads the remote resource and caches it locally. - The resource will only be downloaded if not previously requested. - """ - parsed_url = urlparse(url) - dirname = os.path.join(cache_dir, os.path.dirname(parsed_url.path.lstrip("/"))) - makedir(dirname) - filename = url.split("/")[-1] - cached = os.path.join(dirname, filename) - with file_lock(cached): - if not os.path.isfile(cached): - logging.info(f"Downloading {url} to {cached} ...") - cached = download(url, dirname, filename=filename) - logging.info(f"URL {url} cached in {cached}") - return cached - - -# TODO (prigoyal): convert this into RAII-style API -def create_file_symlink(file1, file2): - """ - Simply create the symlinks for a given file1 to file2. - Useful during model checkpointing to symlinks to the - latest successful checkpoint. - """ - try: - if g_pathmgr.exists(file2): - g_pathmgr.rm(file2) - g_pathmgr.symlink(file1, file2) - except Exception as e: - logging.info(f"Could NOT create symlink. Error: {e}") - - -def save_file(data, filename, append_to_json=True, verbose=True): - """ - Common i/o utility to handle saving data to various file formats. - Supported: - .pkl, .pickle, .npy, .json - Specifically for .json, users have the option to either append (default) - or rewrite by passing in Boolean value to append_to_json. - """ - if verbose: - logging.info(f"Saving data to file: {filename}") - file_ext = os.path.splitext(filename)[1] - if file_ext in [".pkl", ".pickle"]: - with g_pathmgr.open(filename, "wb") as fopen: - pickle.dump(data, fopen, pickle.HIGHEST_PROTOCOL) - elif file_ext == ".npy": - with g_pathmgr.open(filename, "wb") as fopen: - np.save(fopen, data) - elif file_ext == ".json": - if append_to_json: - with g_pathmgr.open(filename, "a") as fopen: - fopen.write(json.dumps(data, sort_keys=True) + "\n") - fopen.flush() - else: - with g_pathmgr.open(filename, "w") as fopen: - fopen.write(json.dumps(data, sort_keys=True) + "\n") - fopen.flush() - elif file_ext == ".yaml": - with g_pathmgr.open(filename, "w") as fopen: - dump = yaml.dump(data) - fopen.write(dump) - fopen.flush() - else: - raise Exception(f"Saving {file_ext} is not supported yet") - - if verbose: - logging.info(f"Saved data to file: {filename}") - - -def load_file(filename, mmap_mode=None, verbose=True, allow_pickle=False): - """ - Common i/o utility to handle loading data from various file formats. - Supported: - .pkl, .pickle, .npy, .json - For the npy files, we support reading the files in mmap_mode. - If the mmap_mode of reading is not successful, we load data without the - mmap_mode. - """ - if verbose: - logging.info(f"Loading data from file: {filename}") - - file_ext = os.path.splitext(filename)[1] - if file_ext == ".txt": - with g_pathmgr.open(filename, "r") as fopen: - data = fopen.readlines() - elif file_ext in [".pkl", ".pickle"]: - with g_pathmgr.open(filename, "rb") as fopen: - data = pickle.load(fopen, encoding="latin1") - elif file_ext == ".npy": - if mmap_mode: - try: - with g_pathmgr.open(filename, "rb") as fopen: - data = np.load( - fopen, - allow_pickle=allow_pickle, - encoding="latin1", - mmap_mode=mmap_mode, - ) - except ValueError as e: - logging.info( - f"Could not mmap {filename}: {e}. Trying without g_pathmgr" - ) - data = np.load( - filename, - allow_pickle=allow_pickle, - encoding="latin1", - mmap_mode=mmap_mode, - ) - logging.info("Successfully loaded without g_pathmgr") - except Exception: - logging.info("Could not mmap without g_pathmgr. Trying without mmap") - with g_pathmgr.open(filename, "rb") as fopen: - data = np.load(fopen, allow_pickle=allow_pickle, encoding="latin1") - else: - with g_pathmgr.open(filename, "rb") as fopen: - data = np.load(fopen, allow_pickle=allow_pickle, encoding="latin1") - elif file_ext == ".json": - with g_pathmgr.open(filename, "r") as fopen: - data = json.load(fopen) - elif file_ext == ".yaml": - with g_pathmgr.open(filename, "r") as fopen: - data = yaml.load(fopen, Loader=yaml.FullLoader) - elif file_ext == ".csv": - with g_pathmgr.open(filename, "r") as fopen: - data = pd.read_csv(fopen) - else: - raise Exception(f"Reading from {file_ext} is not supported yet") - return data - - -def abspath(resource_path: str): - """ - Make a path absolute, but take into account prefixes like - "http://" or "manifold://" - """ - regex = re.compile(r"^\w+://") - if regex.match(resource_path) is None: - return os.path.abspath(resource_path) - else: - return resource_path - - -def makedir(dir_path): - """ - Create the directory if it does not exist. - """ - is_success = False - try: - if not g_pathmgr.exists(dir_path): - g_pathmgr.mkdirs(dir_path) - is_success = True - except BaseException: - logging.info(f"Error creating directory: {dir_path}") - return is_success - - -def is_url(input_url): - """ - Check if an input string is a url. look for http(s):// and ignoring the case - """ - is_url = re.match(r"^(?:http)s?://", input_url, re.IGNORECASE) is not None - return is_url - - -def cleanup_dir(dir): - """ - Utility for deleting a directory. Useful for cleaning the storage space - that contains various training artifacts like checkpoints, data etc. - """ - if os.path.exists(dir): - logging.info(f"Deleting directory: {dir}") - shutil.rmtree(dir) - logging.info(f"Deleted contents of directory: {dir}") - - -def get_file_size(filename): - """ - Given a file, get the size of file in MB - """ - size_in_mb = os.path.getsize(filename) / float(1024**2) - return size_in_mb diff --git a/sonique/Video_LLaMA/video_llama/configs/datasets/cc_sbu/align.yaml b/sonique/Video_LLaMA/video_llama/configs/datasets/cc_sbu/align.yaml deleted file mode 100644 index 180ea8ff0a3548219165e8864d4a59a951206298..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/configs/datasets/cc_sbu/align.yaml +++ /dev/null @@ -1,5 +0,0 @@ -datasets: - cc_sbu_align: - data_type: images - build_info: - storage: /path/to/cc_sbu_align_dataset diff --git a/sonique/Video_LLaMA/video_llama/configs/datasets/cc_sbu/defaults.yaml b/sonique/Video_LLaMA/video_llama/configs/datasets/cc_sbu/defaults.yaml deleted file mode 100644 index 359de601d2511acd6cac34e7ee1c20a1dfe9ae04..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/configs/datasets/cc_sbu/defaults.yaml +++ /dev/null @@ -1,5 +0,0 @@ -datasets: - cc_sbu: - data_type: images - build_info: - storage: /path/to/cc_sbu_dataset/{00000..00001}.tar diff --git a/sonique/Video_LLaMA/video_llama/configs/datasets/instruct/llava_instruct.yaml b/sonique/Video_LLaMA/video_llama/configs/datasets/instruct/llava_instruct.yaml deleted file mode 100644 index 0ec4a938e299f98f6d84104c909da210385003af..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/configs/datasets/instruct/llava_instruct.yaml +++ /dev/null @@ -1,6 +0,0 @@ -datasets: - llava_instruct: - data_type: image - build_info: - anno_dir: /path/llava_instruct_150k.json - videos_dir: /path/train2014/train2014/ diff --git a/sonique/Video_LLaMA/video_llama/configs/datasets/instruct/webvid_instruct.yaml b/sonique/Video_LLaMA/video_llama/configs/datasets/instruct/webvid_instruct.yaml deleted file mode 100644 index 9619106ad8cb1000c3c40fa48672fb9247988d74..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/configs/datasets/instruct/webvid_instruct.yaml +++ /dev/null @@ -1,6 +0,0 @@ -datasets: - webvid_instruct: - data_type: image - build_info: - anno_dir: /path/webvid_align/videochat_instruct_11k.json - videos_dir: /path/webvid_align/videos/ diff --git a/sonique/Video_LLaMA/video_llama/configs/datasets/laion/defaults.yaml b/sonique/Video_LLaMA/video_llama/configs/datasets/laion/defaults.yaml deleted file mode 100644 index 7dfff3ba891d96a136510f34b1dcf1b774705f4a..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/configs/datasets/laion/defaults.yaml +++ /dev/null @@ -1,5 +0,0 @@ -datasets: - laion: - data_type: images - build_info: - storage: path/laion/laion_dataset/{00000..00001}.tar diff --git a/sonique/Video_LLaMA/video_llama/configs/datasets/webvid/defaults.yaml b/sonique/Video_LLaMA/video_llama/configs/datasets/webvid/defaults.yaml deleted file mode 100644 index 046ae32dde61e2d79d1f519e1c8c653d8e2b5886..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/configs/datasets/webvid/defaults.yaml +++ /dev/null @@ -1,6 +0,0 @@ -datasets: - webvid: - data_type: video - build_info: - anno_dir: path/webvid/webvid_tain_data/annotations/ - videos_dir: path//webvid/webvid_tain_data/videos/ diff --git a/sonique/Video_LLaMA/video_llama/configs/default.yaml b/sonique/Video_LLaMA/video_llama/configs/default.yaml deleted file mode 100644 index ff5a6a23fa2e3914938631b96c71fdf723dbbc10..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/configs/default.yaml +++ /dev/null @@ -1,5 +0,0 @@ -env: - # For default users - # cache_root: "cache" - # For internal use with persistent storage - cache_root: "/export/home/.cache/minigpt4" diff --git a/sonique/Video_LLaMA/video_llama/configs/models/minigpt4.yaml b/sonique/Video_LLaMA/video_llama/configs/models/minigpt4.yaml deleted file mode 100644 index 358c3f5f7b53251c607ea490ee262a890e531dc6..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/configs/models/minigpt4.yaml +++ /dev/null @@ -1,33 +0,0 @@ -model: - arch: mini_gpt4 - - # vit encoder - image_size: 224 - drop_path_rate: 0 - use_grad_checkpoint: False - vit_precision: "fp16" - freeze_vit: True - freeze_qformer: True - - # Q-Former - num_query_token: 32 - - # Vicuna - llama_model: "ckpt/vicuna-13b/" - - # generation configs - prompt: "" - -preprocess: - vis_processor: - train: - name: "blip2_image_train" - image_size: 224 - eval: - name: "blip2_image_eval" - image_size: 224 - text_processor: - train: - name: "blip_caption" - eval: - name: "blip_caption" diff --git a/sonique/Video_LLaMA/video_llama/configs/models/video_llama.yaml b/sonique/Video_LLaMA/video_llama/configs/models/video_llama.yaml deleted file mode 100644 index 27ce07c3fbaa5a867279572c5b7d1dc31d469791..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/configs/models/video_llama.yaml +++ /dev/null @@ -1,36 +0,0 @@ -model: - arch: video_llama - - # vit encoder - image_size: 224 - drop_path_rate: 0 - use_grad_checkpoint: False - vit_precision: "fp16" - freeze_vit: True - freeze_qformer: True - - # Q-Former - num_query_token: 32 - - # Vicuna - llama_model: "ckpt/vicuna-7b/" - - # generation configs - prompt: "" - -preprocess: - vis_processor: - train: - name: "alpro_video_train" - image_size: 224 - n_frms: 8 - eval: - name: "alpro_video_eval" - image_size: 224 - n_frms: 8 - text_processor: - train: - name: "blip_caption" - eval: - name: "blip_caption" - \ No newline at end of file diff --git a/sonique/Video_LLaMA/video_llama/conversation/__init__.py b/sonique/Video_LLaMA/video_llama/conversation/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/sonique/Video_LLaMA/video_llama/conversation/conversation_video.py b/sonique/Video_LLaMA/video_llama/conversation/conversation_video.py deleted file mode 100644 index 782d178c555a35f1ff225941ad16f559a58e7180..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/conversation/conversation_video.py +++ /dev/null @@ -1,348 +0,0 @@ -""" -Conversation prompt template of Video-LLaMA. -Adapted from: https://github.com/Vision-CAIR/MiniGPT-4/blob/main/minigpt4/conversation/conversation.py -""" -import argparse -import time -from PIL import Image -import sys -import os -import torch -from transformers import AutoTokenizer, AutoModelForCausalLM, LlamaTokenizer -from transformers import StoppingCriteria, StoppingCriteriaList - -import dataclasses -from enum import auto, Enum -from typing import List, Tuple, Any -import os -from sonique.Video_LLaMA.video_llama.common.registry import registry -from sonique.Video_LLaMA.video_llama.processors.video_processor import ToTHWC,ToUint8,load_video -from sonique.Video_LLaMA.video_llama.processors import Blip2ImageEvalProcessor - -from sonique.Video_LLaMA.video_llama.models.ImageBind.data import load_and_transform_audio_data -class SeparatorStyle(Enum): - """Different separator style.""" - SINGLE = auto() - TWO = auto() - LLAMA_2 = auto() - - -@dataclasses.dataclass -class Conversation: - """A class that keeps all conversation history.""" - system: str - roles: List[str] - messages: List[List[str]] - offset: int - # system_img: List[Image.Image] = [] - sep_style: SeparatorStyle = SeparatorStyle.SINGLE - sep: str = "###" - sep2: str = None - - skip_next: bool = False - conv_id: Any = None - - def get_prompt(self): - if self.sep_style == SeparatorStyle.SINGLE: - ret = self.system + self.sep - for role, message in self.messages: - if message: - ret += role + ": " + message + self.sep - else: - ret += role + ":" - return ret - elif self.sep_style == SeparatorStyle.TWO: - seps = [self.sep, self.sep2] - ret = self.system + seps[0] - for i, (role, message) in enumerate(self.messages): - if message: - ret += role + ": " + message + seps[i % 2] - else: - ret += role + ":" - return ret - elif self.sep_style == SeparatorStyle.LLAMA_2: - wrap_sys = lambda msg: f"<>\n{msg}\n<>\n\n" - wrap_inst = lambda msg: f"[INST] {msg} [/INST]" - ret = "" - - for i, (role, message) in enumerate(self.messages): - if i == 0: - assert message, "first message should not be none" - assert role == self.roles[0], "first message should come from user" - if message: - if type(message) is tuple: - message, _, _ = message - if i == 0: message = wrap_sys(self.system) + message - if i % 2 == 0: - message = wrap_inst(message) - ret += self.sep + message - else: - ret += " " + message + " " + self.sep2 - else: - ret += "" - ret = ret.lstrip(self.sep) - return ret - else: - raise ValueError(f"Invalid style: {self.sep_style}") - - def append_message(self, role, message): - self.messages.append([role, message]) - - def to_gradio_chatbot(self): - ret = [] - for i, (role, msg) in enumerate(self.messages[self.offset:]): - if i % 2 == 0: - ret.append([msg, None]) - else: - ret[-1][-1] = msg - return ret - - def copy(self): - return Conversation( - system=self.system, - # system_img=self.system_img, - roles=self.roles, - messages=[[x, y] for x, y in self.messages], - offset=self.offset, - sep_style=self.sep_style, - sep=self.sep, - sep2=self.sep2, - conv_id=self.conv_id) - - def dict(self): - return { - "system": self.system, - # "system_img": self.system_img, - "roles": self.roles, - "messages": self.messages, - "offset": self.offset, - "sep": self.sep, - "sep2": self.sep2, - "conv_id": self.conv_id, - } - - -class StoppingCriteriaSub(StoppingCriteria): - - def __init__(self, stops=[], encounters=1): - super().__init__() - self.stops = stops - - def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor): - for stop in self.stops: - if torch.all((stop == input_ids[0][-len(stop):])).item(): - return True - - return False - - -CONV_VISION = Conversation( - system="Give the following image: ImageContent. " - "You will be able to see the image once I provide it to you. Please answer my questions.", - roles=("Human", "Assistant"), - messages=[], - offset=0, - sep_style=SeparatorStyle.SINGLE, - sep="###", -) - -default_conversation = Conversation( - system="", - roles=("Human", "Assistant"), - messages=[], - offset=0, - sep_style=SeparatorStyle.SINGLE, - sep="###", -) -conv_llava_llama_2 = Conversation( - system="You are a helpful language and vision assistant. " - "You are able to understand the visual content that the user provides, " - "and assist the user with a variety of tasks using natural language.", - roles=("USER", "ASSISTANT"), - messages=(), - offset=0, - sep_style=SeparatorStyle.LLAMA_2, - sep="", - sep2="", -) -class Chat: - def __init__(self, model, vis_processor, device='cuda:0'): - self.device = device - self.model = model - self.vis_processor = vis_processor - self.image_vis_processor = Blip2ImageEvalProcessor() - # stop_words_ids = [torch.tensor([835]).to(self.device), - # torch.tensor([2277, 29937]).to(self.device)] # '###' can be encoded in two different ways. - # self.stopping_criteria = StoppingCriteriaList([StoppingCriteriaSub(stops=stop_words_ids)]) - - def ask(self, text, conv): - if len(conv.messages) > 0 and conv.messages[-1][0] == conv.roles[0] \ - and ('' in conv.messages[-1][1] or '' in conv.messages[-1][1]): # last message is image. - conv.messages[-1][1] = ' '.join([conv.messages[-1][1], text]) - else: - conv.append_message(conv.roles[0], text) - - def answer(self, conv, img_list, max_new_tokens=300, num_beams=1, min_length=1, top_p=0.9, - repetition_penalty=1.0, length_penalty=1, temperature=1.0, max_length=2000): - conv.append_message(conv.roles[1], None) - embs = self.get_context_emb(conv, img_list) - - current_max_len = embs.shape[1] + max_new_tokens - if current_max_len - max_length > 0: - print('Warning: The number of tokens in current conversation exceeds the max length. ' - 'The model will not see the contexts outside the range.') - begin_idx = max(0, current_max_len - max_length) - - embs = embs[:, begin_idx:] - if conv.sep =="###": - stop_words_ids = [torch.tensor([835]).to(self.device), - torch.tensor([2277, 29937]).to(self.device)] # '###' can be encoded in two different ways. - stopping_criteria = StoppingCriteriaList([StoppingCriteriaSub(stops=stop_words_ids)]) - else: - stop_words_ids = [torch.tensor([2]).to(self.device)] - stopping_criteria = StoppingCriteriaList([StoppingCriteriaSub(stops=stop_words_ids)]) - - # stopping_criteria - outputs = self.model.llama_model.generate( - inputs_embeds=embs, - max_new_tokens=max_new_tokens, - stopping_criteria=stopping_criteria, - num_beams=num_beams, - do_sample=True, - min_length=min_length, - top_p=top_p, - repetition_penalty=repetition_penalty, - length_penalty=length_penalty, - temperature=temperature, - ) - output_token = outputs[0] - if output_token[0] == 0: # the model might output a unknow token at the beginning. remove it - output_token = output_token[1:] - if output_token[0] == 1: # some users find that there is a start token at the beginning. remove it - output_token = output_token[1:] - output_text = self.model.llama_tokenizer.decode(output_token, add_special_tokens=False) - if conv.sep =="###": - output_text = output_text.split('###')[0] # remove the stop sign '###' - output_text = output_text.split('Assistant:')[-1].strip() - else: - output_text = output_text.split(conv.sep2)[0] # remove the stop sign '###' - output_text = output_text.split(conv.roles[1]+':')[-1].strip() - conv.messages[-1][1] = output_text - return output_text, output_token.cpu().numpy() - - def upload_video(self, video_path, conv, img_list): - - msg = "" - if isinstance(video_path, str): # is a video path - ext = os.path.splitext(video_path)[-1].lower() - print(video_path) - # image = self.vis_processor(image).unsqueeze(0).to(self.device) - video, msg = load_video( - video_path=video_path, - n_frms=8, - height=224, - width=224, - sampling ="uniform", return_msg = True - ) - video = self.vis_processor.transform(video) - video = video.unsqueeze(0).to(self.device) - # print(image) - else: - raise NotImplementedError - - try: - audio_flag = 1 - audio = load_and_transform_audio_data([video_path],"cpu", clips_per_video=8) - audio = audio.to(self.device) - except : - print('no audio is found') - audio_flag = 0 - finally: - if audio_flag == 1: - # image_emb, _ = self.model.encode_videoQformer_audiovideo(video,audio) - image_emb, _ = self.model.encode_videoQformer_visual(video) - audio_emb,_ = self.model.encode_audioQformer(audio) - img_list.append(audio_emb) - img_list.append(image_emb) - conv.system = "" - # conv.append_message(conv.roles[0], "The audio of this video is ") - conv.append_message(conv.roles[0], "Close your eyes, open your ears and you imagine only based on the sound that: . \ - Close your ears, open your eyes and you see that . \ - Now answer my question based on what you have just seen and heard.") - - else: # only vison no audio - # conv.system = "You can understand the video that the user provides. Follow the instructions carefully and explain your answers in detail." - image_emb, _ = self.model.encode_videoQformer_visual(video) - img_list.append(image_emb) - conv.append_message(conv.roles[0], " "+ msg) - return "Received." - - def upload_video_without_audio(self, video_path, conv, img_list): - msg = "" - if isinstance(video_path, str): # is a video path - ext = os.path.splitext(video_path)[-1].lower() - print(video_path) - # image = self.vis_processor(image).unsqueeze(0).to(self.device) - video, msg = load_video( - video_path=video_path, - n_frms=8, - height=224, - width=224, - sampling ="uniform", return_msg = True - ) - video = self.vis_processor.transform(video) - video = video.unsqueeze(0).to(self.device) - # print(image) - else: - raise NotImplementedError - - - # conv.system = "You can understand the video that the user provides. Follow the instructions carefully and explain your answers in detail." - image_emb, _ = self.model.encode_videoQformer_visual(video) - img_list.append(image_emb) - conv.append_message(conv.roles[0], " "+ msg) - return "Received." - - def upload_img(self, image, conv, img_list): - - msg = "" - if isinstance(image, str): # is a image path - raw_image = Image.open(image).convert('RGB') # 增加一个时间维度 - image = self.image_vis_processor(raw_image).unsqueeze(0).unsqueeze(2).to(self.device) - elif isinstance(image, Image.Image): - raw_image = image - image = self.image_vis_processor(raw_image).unsqueeze(0).unsqueeze(2).to(self.device) - elif isinstance(image, torch.Tensor): - if len(image.shape) == 3: - image = image.unsqueeze(0) - image = image.to(self.device) - else: - raise NotImplementedError - - image_emb, _ = self.model.encode_videoQformer_visual(image) - img_list.append(image_emb) - # Todo msg="" - conv.append_message(conv.roles[0], " "+ msg) - - return "Received." - - def get_context_emb(self, conv, img_list): - prompt = conv.get_prompt() - prompt_segs = prompt.split('') - assert len(prompt_segs) == len(img_list) + 1, "Unmatched numbers of image placeholders and images." - seg_tokens = [ - self.model.llama_tokenizer( - seg, return_tensors="pt", add_special_tokens=i == 0).to(self.device).input_ids - # only add bos to the first seg - for i, seg in enumerate(prompt_segs) - ] - seg_embs = [self.model.llama_model.model.embed_tokens(seg_t) for seg_t in seg_tokens] - mixed_embs = [emb for pair in zip(seg_embs[:-1], img_list) for emb in pair] + [seg_embs[-1]] - mixed_embs = torch.cat(mixed_embs, dim=1) - return mixed_embs - -if __name__ =='__main__': - video_path = '/mnt/workspace/videoGPT/Video-LLaMA/examples/applausing.mp4' - # import torch.classes.torchaudio.ffmpeg_StreamReader - # ffmpeg_StreamReader(video_path) - load_and_transform_audio_data([video_path],"cpu", clips_per_video=8) diff --git a/sonique/Video_LLaMA/video_llama/datasets/__init__.py b/sonique/Video_LLaMA/video_llama/datasets/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/sonique/Video_LLaMA/video_llama/datasets/builders/__init__.py b/sonique/Video_LLaMA/video_llama/datasets/builders/__init__.py deleted file mode 100644 index 71a5ee94ad728953f0339d8ebc58bfbc95586867..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/datasets/builders/__init__.py +++ /dev/null @@ -1,77 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -from sonique.Video_LLaMA.video_llama.datasets.builders.base_dataset_builder import load_dataset_config -from sonique.Video_LLaMA.video_llama.datasets.builders.image_text_pair_builder import ( - CCSBUBuilder, - LaionBuilder, - CCSBUAlignBuilder -) -from sonique.Video_LLaMA.video_llama.datasets.builders.video_caption_builder import WebvidBuilder -from sonique.Video_LLaMA.video_llama.common.registry import registry -from sonique.Video_LLaMA.video_llama.datasets.builders.instruct_builder import WebvidInstruct_Builder,LlavaInstruct_Builder -__all__ = [ - "CCSBUBuilder", - "LaionBuilder", - "CCSBUAlignBuilder", - "WebvidBuilder", - "LlavaInstruct_Builder", - "WebvidInstruct_Builder" - -] - - -def load_dataset(name, cfg_path=None, vis_path=None, data_type=None): - """ - Example - - >>> dataset = load_dataset("coco_caption", cfg=None) - >>> splits = dataset.keys() - >>> print([len(dataset[split]) for split in splits]) - - """ - if cfg_path is None: - cfg = None - else: - cfg = load_dataset_config(cfg_path) - - try: - builder = registry.get_builder_class(name)(cfg) - except TypeError: - print( - f"Dataset {name} not found. Available datasets:\n" - + ", ".join([str(k) for k in dataset_zoo.get_names()]) - ) - exit(1) - - if vis_path is not None: - if data_type is None: - # use default data type in the config - data_type = builder.config.data_type - - assert ( - data_type in builder.config.build_info - ), f"Invalid data_type {data_type} for {name}." - - builder.config.build_info.get(data_type).storage = vis_path - - dataset = builder.build_datasets() - return dataset - - -class DatasetZoo: - def __init__(self) -> None: - self.dataset_zoo = { - k: list(v.DATASET_CONFIG_DICT.keys()) - for k, v in sorted(registry.mapping["builder_name_mapping"].items()) - } - - def get_names(self): - return list(self.dataset_zoo.keys()) - - -dataset_zoo = DatasetZoo() diff --git a/sonique/Video_LLaMA/video_llama/datasets/builders/base_dataset_builder.py b/sonique/Video_LLaMA/video_llama/datasets/builders/base_dataset_builder.py deleted file mode 100644 index d8dc1470c46aed3ccef3b8f3712849ad5eefaf0f..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/datasets/builders/base_dataset_builder.py +++ /dev/null @@ -1,236 +0,0 @@ -""" - This file is from - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import logging -import os -import shutil -import warnings - -from omegaconf import OmegaConf -import torch.distributed as dist -from torchvision.datasets.utils import download_url - -import sonique.Video_LLaMA.video_llama.common.utils as utils -from sonique.Video_LLaMA.video_llama.common.dist_utils import is_dist_avail_and_initialized, is_main_process -from sonique.Video_LLaMA.video_llama.common.registry import registry -from sonique.Video_LLaMA.video_llama.processors.base_processor import BaseProcessor - - - -class BaseDatasetBuilder: - train_dataset_cls, eval_dataset_cls = None, None - - def __init__(self, cfg=None): - super().__init__() - - if cfg is None: - # help to create datasets from default config. - self.config = load_dataset_config(self.default_config_path()) - elif isinstance(cfg, str): - self.config = load_dataset_config(cfg) - else: - # when called from task.build_dataset() - self.config = cfg - - self.data_type = self.config.data_type - - self.vis_processors = {"train": BaseProcessor(), "eval": BaseProcessor()} - self.text_processors = {"train": BaseProcessor(), "eval": BaseProcessor()} - - def build_datasets(self): - # download, split, etc... - # only called on 1 GPU/TPU in distributed - - if is_main_process(): - self._download_data() - - if is_dist_avail_and_initialized(): - dist.barrier() - - # at this point, all the annotations and image/videos should be all downloaded to the specified locations. - logging.info("Building datasets...") - datasets = self.build() # dataset['train'/'val'/'test'] - - return datasets - - def build_processors(self): - vis_proc_cfg = self.config.get("vis_processor") - txt_proc_cfg = self.config.get("text_processor") - - if vis_proc_cfg is not None: - vis_train_cfg = vis_proc_cfg.get("train") - vis_eval_cfg = vis_proc_cfg.get("eval") - - self.vis_processors["train"] = self._build_proc_from_cfg(vis_train_cfg) - self.vis_processors["eval"] = self._build_proc_from_cfg(vis_eval_cfg) - - if txt_proc_cfg is not None: - txt_train_cfg = txt_proc_cfg.get("train") - txt_eval_cfg = txt_proc_cfg.get("eval") - - self.text_processors["train"] = self._build_proc_from_cfg(txt_train_cfg) - self.text_processors["eval"] = self._build_proc_from_cfg(txt_eval_cfg) - - @staticmethod - def _build_proc_from_cfg(cfg): - return ( - registry.get_processor_class(cfg.name).from_config(cfg) - if cfg is not None - else None - ) - - @classmethod - def default_config_path(cls, type="default"): - return utils.get_abs_path(cls.DATASET_CONFIG_DICT[type]) - - def _download_data(self): - self._download_ann() - self._download_vis() - - def _download_ann(self): - """ - Download annotation files if necessary. - All the vision-language datasets should have annotations of unified format. - - storage_path can be: - (1) relative/absolute: will be prefixed with env.cache_root to make full path if relative. - (2) basename/dirname: will be suffixed with base name of URL if dirname is provided. - - Local annotation paths should be relative. - """ - anns = self.config.build_info.annotations - - splits = anns.keys() - - cache_root = registry.get_path("cache_root") - - for split in splits: - info = anns[split] - - urls, storage_paths = info.get("url", None), info.storage - - if isinstance(urls, str): - urls = [urls] - if isinstance(storage_paths, str): - storage_paths = [storage_paths] - - assert len(urls) == len(storage_paths) - - for url_or_filename, storage_path in zip(urls, storage_paths): - # if storage_path is relative, make it full by prefixing with cache_root. - if not os.path.isabs(storage_path): - storage_path = os.path.join(cache_root, storage_path) - - dirname = os.path.dirname(storage_path) - if not os.path.exists(dirname): - os.makedirs(dirname) - - if os.path.isfile(url_or_filename): - src, dst = url_or_filename, storage_path - if not os.path.exists(dst): - shutil.copyfile(src=src, dst=dst) - else: - logging.info("Using existing file {}.".format(dst)) - else: - if os.path.isdir(storage_path): - # if only dirname is provided, suffix with basename of URL. - raise ValueError( - "Expecting storage_path to be a file path, got directory {}".format( - storage_path - ) - ) - else: - filename = os.path.basename(storage_path) - - download_url(url=url_or_filename, root=dirname, filename=filename) - - def _download_vis(self): - - storage_path = self.config.build_info.get(self.data_type).storage - storage_path = utils.get_cache_path(storage_path) - - if not os.path.exists(storage_path): - warnings.warn( - f""" - The specified path {storage_path} for visual inputs does not exist. - Please provide a correct path to the visual inputs or - refer to datasets/download_scripts/README.md for downloading instructions. - """ - ) - - def build(self): - """ - Create by split datasets inheriting torch.utils.data.Datasets. - - # build() can be dataset-specific. Overwrite to customize. - """ - self.build_processors() - - build_info = self.config.build_info - - ann_info = build_info.annotations - vis_info = build_info.get(self.data_type) - - datasets = dict() - for split in ann_info.keys(): - if split not in ["train", "val", "test"]: - continue - - is_train = split == "train" - - # processors - vis_processor = ( - self.vis_processors["train"] - if is_train - else self.vis_processors["eval"] - ) - text_processor = ( - self.text_processors["train"] - if is_train - else self.text_processors["eval"] - ) - - # annotation path - ann_paths = ann_info.get(split).storage - if isinstance(ann_paths, str): - ann_paths = [ann_paths] - - abs_ann_paths = [] - for ann_path in ann_paths: - if not os.path.isabs(ann_path): - ann_path = utils.get_cache_path(ann_path) - abs_ann_paths.append(ann_path) - ann_paths = abs_ann_paths - - # visual data storage path - vis_path = os.path.join(vis_info.storage, split) - - if not os.path.isabs(vis_path): - # vis_path = os.path.join(utils.get_cache_path(), vis_path) - vis_path = utils.get_cache_path(vis_path) - - if not os.path.exists(vis_path): - warnings.warn("storage path {} does not exist.".format(vis_path)) - - # create datasets - dataset_cls = self.train_dataset_cls if is_train else self.eval_dataset_cls - datasets[split] = dataset_cls( - vis_processor=vis_processor, - text_processor=text_processor, - ann_paths=ann_paths, - vis_root=vis_path, - ) - - return datasets - - -def load_dataset_config(cfg_path): - cfg = OmegaConf.load(cfg_path).datasets - cfg = cfg[list(cfg.keys())[0]] - - return cfg diff --git a/sonique/Video_LLaMA/video_llama/datasets/builders/image_text_pair_builder.py b/sonique/Video_LLaMA/video_llama/datasets/builders/image_text_pair_builder.py deleted file mode 100644 index 0ae176bacb9d29abe9ad051f3d1a9e95343859d3..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/datasets/builders/image_text_pair_builder.py +++ /dev/null @@ -1,106 +0,0 @@ -import os -import logging -import warnings - -from sonique.Video_LLaMA.video_llama.common.registry import registry -from sonique.Video_LLaMA.video_llama.datasets.builders.base_dataset_builder import BaseDatasetBuilder -from sonique.Video_LLaMA.video_llama.datasets.datasets.laion_dataset import LaionDataset -from sonique.Video_LLaMA.video_llama.datasets.datasets.cc_sbu_dataset import CCSBUDataset, CCSBUAlignDataset - - -@registry.register_builder("cc_sbu") -class CCSBUBuilder(BaseDatasetBuilder): - train_dataset_cls = CCSBUDataset - - DATASET_CONFIG_DICT = {"default": "configs/datasets/cc_sbu/defaults.yaml"} - - def _download_ann(self): - pass - - def _download_vis(self): - pass - - def build(self): - self.build_processors() - - build_info = self.config.build_info - - datasets = dict() - split = "train" - - # create datasets - # [NOTE] return inner_datasets (wds.DataPipeline) - dataset_cls = self.train_dataset_cls - datasets[split] = dataset_cls( - vis_processor=self.vis_processors[split], - text_processor=self.text_processors[split], - location=build_info.storage, - ).inner_dataset - - return datasets - - -@registry.register_builder("laion") -class LaionBuilder(BaseDatasetBuilder): - train_dataset_cls = LaionDataset - - DATASET_CONFIG_DICT = {"default": "configs/datasets/laion/defaults.yaml"} - - def _download_ann(self): - pass - - def _download_vis(self): - pass - - def build(self): - self.build_processors() - - build_info = self.config.build_info - - datasets = dict() - split = "train" - - # create datasets - # [NOTE] return inner_datasets (wds.DataPipeline) - dataset_cls = self.train_dataset_cls - datasets[split] = dataset_cls( - vis_processor=self.vis_processors[split], - text_processor=self.text_processors[split], - location=build_info.storage, - ).inner_dataset - - return datasets - - -@registry.register_builder("cc_sbu_align") -class CCSBUAlignBuilder(BaseDatasetBuilder): - train_dataset_cls = CCSBUAlignDataset - - DATASET_CONFIG_DICT = { - "default": "configs/datasets/cc_sbu/align.yaml", - } - - def build_datasets(self): - # at this point, all the annotations and image/videos should be all downloaded to the specified locations. - logging.info("Building datasets...") - self.build_processors() - - build_info = self.config.build_info - storage_path = build_info.storage - - datasets = dict() - - if not os.path.exists(storage_path): - warnings.warn("storage path {} does not exist.".format(storage_path)) - - # create datasets - dataset_cls = self.train_dataset_cls - datasets['train'] = dataset_cls( - vis_processor=self.vis_processors["train"], - text_processor=self.text_processors["train"], - ann_paths=[os.path.join(storage_path, 'filter_cap.json')], - vis_root=os.path.join(storage_path, 'image'), - ) - - return datasets - diff --git a/sonique/Video_LLaMA/video_llama/datasets/builders/instruct_builder.py b/sonique/Video_LLaMA/video_llama/datasets/builders/instruct_builder.py deleted file mode 100644 index 05c863edfac332c855eadd23f54f45e6e940f46e..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/datasets/builders/instruct_builder.py +++ /dev/null @@ -1,79 +0,0 @@ -import os -import logging -import warnings - -from sonique.Video_LLaMA.video_llama.common.registry import registry -from sonique.Video_LLaMA.video_llama.datasets.builders.base_dataset_builder import BaseDatasetBuilder -from sonique.Video_LLaMA.video_llama.datasets.datasets.laion_dataset import LaionDataset -from sonique.Video_LLaMA.video_llama.datasets.datasets.llava_instruct_dataset import Instruct_Dataset -from sonique.Video_LLaMA.video_llama.datasets.datasets.video_instruct_dataset import Video_Instruct_Dataset - -@registry.register_builder("instruct") -class Instruct_Builder(BaseDatasetBuilder): - train_dataset_cls = Instruct_Dataset - - DATASET_CONFIG_DICT = {"default": "configs/datasets/instruct/defaults.yaml"} - - def _download_ann(self): - pass - - def _download_vis(self): - pass - - def build(self): - self.build_processors() - datasets = dict() - split = "train" - - build_info = self.config.build_info - dataset_cls = self.train_dataset_cls - if self.config.num_video_query_token: - num_video_query_token = self.config.num_video_query_token - else: - num_video_query_token = 32 - - if self.config.tokenizer_name: - tokenizer_name = self.config.tokenizer_name - else: - tokenizer_name = '/mnt/workspace/ckpt/vicuna-13b/' - - - datasets[split] = dataset_cls( - vis_processor=self.vis_processors[split], - text_processor=self.text_processors[split], - vis_root=build_info.videos_dir, - ann_root=build_info.anno_dir, - num_video_query_token = num_video_query_token, - tokenizer_name = tokenizer_name, - data_type = self.config.data_type, - model_type = self.config.model_type - ) - - return datasets - -@registry.register_builder("webvid_instruct") -class WebvidInstruct_Builder(Instruct_Builder): - train_dataset_cls = Video_Instruct_Dataset - - DATASET_CONFIG_DICT = { - "default": "configs/datasets/instruct/webvid_instruct.yaml", - } - -@registry.register_builder("webvid_instruct_zh") -class WebvidInstruct_zh_Builder(Instruct_Builder): - train_dataset_cls = Video_Instruct_Dataset - - DATASET_CONFIG_DICT = { - "default": "configs/datasets/instruct/webvid_instruct.yaml", - } - - - -@registry.register_builder("llava_instruct") -class LlavaInstruct_Builder(Instruct_Builder): - train_dataset_cls = Instruct_Dataset - - DATASET_CONFIG_DICT = { - "default": "configs/datasets/instruct/llava_instruct.yaml", - } - diff --git a/sonique/Video_LLaMA/video_llama/datasets/builders/video_caption_builder.py b/sonique/Video_LLaMA/video_llama/datasets/builders/video_caption_builder.py deleted file mode 100644 index e115070f929e379cdae5190c0149e40f9752f7d0..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/datasets/builders/video_caption_builder.py +++ /dev/null @@ -1,34 +0,0 @@ -import os -import logging -import warnings - -from sonique.Video_LLaMA.video_llama.common.registry import registry -from sonique.Video_LLaMA.video_llama.datasets.builders.base_dataset_builder import BaseDatasetBuilder -from sonique.Video_LLaMA.video_llama.datasets.datasets.webvid_datasets import WebvidDataset - -@registry.register_builder("webvid") -class WebvidBuilder(BaseDatasetBuilder): - train_dataset_cls = WebvidDataset - DATASET_CONFIG_DICT = {"default": "configs/datasets/webvid/defaults.yaml"} - - def _download_ann(self): - pass - - def _download_vis(self): - pass - - def build(self): - self.build_processors() - datasets = dict() - split = "train" - - build_info = self.config.build_info - dataset_cls = self.train_dataset_cls - datasets[split] = dataset_cls( - vis_processor=self.vis_processors[split], - text_processor=self.text_processors[split], - vis_root=build_info.videos_dir, - ann_root=build_info.anno_dir - ) - - return datasets \ No newline at end of file diff --git a/sonique/Video_LLaMA/video_llama/datasets/data_utils.py b/sonique/Video_LLaMA/video_llama/datasets/data_utils.py deleted file mode 100644 index 435a1c5649da56fdfd2a6df2d60dfd94e9c5fbb7..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/datasets/data_utils.py +++ /dev/null @@ -1,196 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import gzip -import logging -import os -import random as rnd -import tarfile -import zipfile -import random -from typing import List -from tqdm import tqdm - -import decord -from decord import VideoReader -import webdataset as wds -import numpy as np -import torch -from torch.utils.data.dataset import IterableDataset - -from sonique.Video_LLaMA.video_llama.common.registry import registry -from sonique.Video_LLaMA.video_llama.datasets.datasets.base_dataset import ConcatDataset - - -decord.bridge.set_bridge("torch") -MAX_INT = registry.get("MAX_INT") - - -class ChainDataset(wds.DataPipeline): - r"""Dataset for chaining multiple :class:`DataPipeline` s. - - This class is useful to assemble different existing dataset streams. The - chaining operation is done on-the-fly, so concatenating large-scale - datasets with this class will be efficient. - - Args: - datasets (iterable of IterableDataset): datasets to be chained together - """ - def __init__(self, datasets: List[wds.DataPipeline]) -> None: - super().__init__() - self.datasets = datasets - self.prob = [] - self.names = [] - for dataset in self.datasets: - if hasattr(dataset, 'name'): - self.names.append(dataset.name) - else: - self.names.append('Unknown') - if hasattr(dataset, 'sample_ratio'): - self.prob.append(dataset.sample_ratio) - else: - self.prob.append(1) - logging.info("One of the datapipeline doesn't define ratio and set to 1 automatically.") - - def __iter__(self): - datastreams = [iter(dataset) for dataset in self.datasets] - while True: - select_datastream = random.choices(datastreams, weights=self.prob, k=1)[0] - yield next(select_datastream) - - -def apply_to_sample(f, sample): - if len(sample) == 0: - return {} - - def _apply(x): - if torch.is_tensor(x): - return f(x) - elif isinstance(x, dict): - return {key: _apply(value) for key, value in x.items()} - elif isinstance(x, list): - return [_apply(x) for x in x] - else: - return x - - return _apply(sample) - - -def move_to_cuda(sample): - def _move_to_cuda(tensor): - return tensor.cuda() - - return apply_to_sample(_move_to_cuda, sample) - - -def prepare_sample(samples, cuda_enabled=True): - if cuda_enabled: - samples = move_to_cuda(samples) - - # TODO fp16 support - - return samples - - -def reorg_datasets_by_split(datasets): - """ - Organizes datasets by split. - - Args: - datasets: dict of torch.utils.data.Dataset objects by name. - - Returns: - Dict of datasets by split {split_name: List[Datasets]}. - """ - # if len(datasets) == 1: - # return datasets[list(datasets.keys())[0]] - # else: - reorg_datasets = dict() - - # reorganize by split - for _, dataset in datasets.items(): - for split_name, dataset_split in dataset.items(): - if split_name not in reorg_datasets: - reorg_datasets[split_name] = [dataset_split] - else: - reorg_datasets[split_name].append(dataset_split) - - return reorg_datasets - - -def concat_datasets(datasets): - """ - Concatenates multiple datasets into a single dataset. - - It supports may-style datasets and DataPipeline from WebDataset. Currently, does not support - generic IterableDataset because it requires creating separate samplers. - - Now only supports conctenating training datasets and assuming validation and testing - have only a single dataset. This is because metrics should not be computed on the concatenated - datasets. - - Args: - datasets: dict of torch.utils.data.Dataset objects by split. - - Returns: - Dict of concatenated datasets by split, "train" is the concatenation of multiple datasets, - "val" and "test" remain the same. - - If the input training datasets contain both map-style and DataPipeline datasets, returns - a tuple, where the first element is a concatenated map-style dataset and the second - element is a chained DataPipeline dataset. - - """ - # concatenate datasets in the same split - for split_name in datasets: - if split_name != "train": - assert ( - len(datasets[split_name]) == 1 - ), "Do not support multiple {} datasets.".format(split_name) - datasets[split_name] = datasets[split_name][0] - else: - iterable_datasets, map_datasets = [], [] - for dataset in datasets[split_name]: - if isinstance(dataset, wds.DataPipeline): - logging.info( - "Dataset {} is IterableDataset, can't be concatenated.".format( - dataset - ) - ) - iterable_datasets.append(dataset) - elif isinstance(dataset, IterableDataset): - raise NotImplementedError( - "Do not support concatenation of generic IterableDataset." - ) - else: - map_datasets.append(dataset) - - # if len(iterable_datasets) > 0: - # concatenate map-style datasets and iterable-style datasets separately - if len(iterable_datasets) > 1: - chained_datasets = ( - ChainDataset(iterable_datasets) - ) - elif len(iterable_datasets) == 1: - chained_datasets = iterable_datasets[0] - else: - chained_datasets = None - - concat_datasets = ( - ConcatDataset(map_datasets) if len(map_datasets) > 0 else None - ) - - train_datasets = concat_datasets, chained_datasets - train_datasets = tuple([x for x in train_datasets if x is not None]) - train_datasets = ( - train_datasets[0] if len(train_datasets) == 1 else train_datasets - ) - - datasets[split_name] = train_datasets - - return datasets - diff --git a/sonique/Video_LLaMA/video_llama/datasets/datasets/__init__.py b/sonique/Video_LLaMA/video_llama/datasets/datasets/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/sonique/Video_LLaMA/video_llama/datasets/datasets/base_dataset.py b/sonique/Video_LLaMA/video_llama/datasets/datasets/base_dataset.py deleted file mode 100644 index ae2a8d0e21370129c0182cddc427eb293bbe5982..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/datasets/datasets/base_dataset.py +++ /dev/null @@ -1,68 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import json -from typing import Iterable - -from torch.utils.data import Dataset, ConcatDataset -from torch.utils.data.dataloader import default_collate - - -class BaseDataset(Dataset): - def __init__( - self, vis_processor=None, text_processor=None, vis_root=None, ann_paths=[] - ): - """ - vis_root (string): Root directory of images (e.g. coco/images/) - ann_root (string): directory to store the annotation file - """ - self.vis_root = vis_root - - self.annotation = [] - for ann_path in ann_paths: - self.annotation.extend(json.load(open(ann_path, "r"))['annotations']) - - self.vis_processor = vis_processor - self.text_processor = text_processor - - self._add_instance_ids() - - def __len__(self): - return len(self.annotation) - - def collater(self, samples): - return default_collate(samples) - - def set_processors(self, vis_processor, text_processor): - self.vis_processor = vis_processor - self.text_processor = text_processor - - def _add_instance_ids(self, key="instance_id"): - for idx, ann in enumerate(self.annotation): - ann[key] = str(idx) - - -class ConcatDataset(ConcatDataset): - def __init__(self, datasets: Iterable[Dataset]) -> None: - super().__init__(datasets) - - def collater(self, samples): - # TODO For now only supports datasets with same underlying collater implementations - - all_keys = set() - for s in samples: - all_keys.update(s) - - shared_keys = all_keys - for s in samples: - shared_keys = shared_keys & set(s.keys()) - - samples_shared_keys = [] - for s in samples: - samples_shared_keys.append({k: s[k] for k in s.keys() if k in shared_keys}) - - return self.datasets[0].collater(samples_shared_keys) diff --git a/sonique/Video_LLaMA/video_llama/datasets/datasets/caption_datasets.py b/sonique/Video_LLaMA/video_llama/datasets/datasets/caption_datasets.py deleted file mode 100644 index ec7d2ef1bddbd8053eff8831f2f296c0c6f75f45..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/datasets/datasets/caption_datasets.py +++ /dev/null @@ -1,85 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import os -from collections import OrderedDict - -from sonique.Video_LLaMA.video_llama.datasets.datasets.base_dataset import BaseDataset -from PIL import Image - - -class __DisplMixin: - def displ_item(self, index): - sample, ann = self.__getitem__(index), self.annotation[index] - - return OrderedDict( - { - "file": ann["image"], - "caption": ann["caption"], - "image": sample["image"], - } - ) - - -class CaptionDataset(BaseDataset, __DisplMixin): - def __init__(self, vis_processor, text_processor, vis_root, ann_paths): - """ - vis_root (string): Root directory of images (e.g. coco/images/) - ann_root (string): directory to store the annotation file - """ - super().__init__(vis_processor, text_processor, vis_root, ann_paths) - - self.img_ids = {} - n = 0 - for ann in self.annotation: - img_id = ann["image_id"] - if img_id not in self.img_ids.keys(): - self.img_ids[img_id] = n - n += 1 - - def __getitem__(self, index): - - # TODO this assumes image input, not general enough - ann = self.annotation[index] - - img_file = '{:0>12}.jpg'.format(ann["image_id"]) - image_path = os.path.join(self.vis_root, img_file) - image = Image.open(image_path).convert("RGB") - - image = self.vis_processor(image) - caption = self.text_processor(ann["caption"]) - - return { - "image": image, - "text_input": caption, - "image_id": self.img_ids[ann["image_id"]], - } - - -class CaptionEvalDataset(BaseDataset, __DisplMixin): - def __init__(self, vis_processor, text_processor, vis_root, ann_paths): - """ - vis_root (string): Root directory of images (e.g. coco/images/) - ann_root (string): directory to store the annotation file - split (string): val or test - """ - super().__init__(vis_processor, text_processor, vis_root, ann_paths) - - def __getitem__(self, index): - - ann = self.annotation[index] - - image_path = os.path.join(self.vis_root, ann["image"]) - image = Image.open(image_path).convert("RGB") - - image = self.vis_processor(image) - - return { - "image": image, - "image_id": ann["image_id"], - "instance_id": ann["instance_id"], - } diff --git a/sonique/Video_LLaMA/video_llama/datasets/datasets/cc_sbu_dataset.py b/sonique/Video_LLaMA/video_llama/datasets/datasets/cc_sbu_dataset.py deleted file mode 100644 index bada3308eb05183440ce1fd44f311126e6acc93a..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/datasets/datasets/cc_sbu_dataset.py +++ /dev/null @@ -1,49 +0,0 @@ -import os -from PIL import Image -import webdataset as wds -from sonique.Video_LLaMA.video_llama.datasets.datasets.base_dataset import BaseDataset -from sonique.Video_LLaMA.video_llama.datasets.datasets.caption_datasets import CaptionDataset - - -class CCSBUDataset(BaseDataset): - def __init__(self, vis_processor, text_processor, location): - super().__init__(vis_processor=vis_processor, text_processor=text_processor) - - self.inner_dataset = wds.DataPipeline( - wds.ResampledShards(location), - wds.tarfile_to_samples(handler=wds.warn_and_continue), - wds.shuffle(1000, handler=wds.warn_and_continue), - wds.decode("pilrgb", handler=wds.warn_and_continue), - wds.to_tuple("jpg", "json", handler=wds.warn_and_continue), - wds.map_tuple(self.vis_processor, handler=wds.warn_and_continue), - wds.map(self.to_dict, handler=wds.warn_and_continue), - ) - - def to_dict(self, sample): - return { - "image": sample[0], - "text_input": self.text_processor(sample[1]["caption"]), - "type":'image', - } - - -class CCSBUAlignDataset(CaptionDataset): - - def __getitem__(self, index): - - # TODO this assumes image input, not general enough - ann = self.annotation[index] - - img_file = '{}.jpg'.format(ann["image_id"]) - image_path = os.path.join(self.vis_root, img_file) - image = Image.open(image_path).convert("RGB") - - image = self.vis_processor(image) - caption = ann["caption"] - - return { - "image": image, - "text_input": caption, - "image_id": self.img_ids[ann["image_id"]], - "type":'image', - } \ No newline at end of file diff --git a/sonique/Video_LLaMA/video_llama/datasets/datasets/dataloader_utils.py b/sonique/Video_LLaMA/video_llama/datasets/datasets/dataloader_utils.py deleted file mode 100644 index 2abb40192344765938ade6da7addb882f7a7b07c..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/datasets/datasets/dataloader_utils.py +++ /dev/null @@ -1,162 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import time -import random -import torch -from sonique.Video_LLaMA.video_llama.datasets.data_utils import move_to_cuda -from torch.utils.data import DataLoader - - -class MultiIterLoader: - """ - A simple wrapper for iterating over multiple iterators. - - Args: - loaders (List[Loader]): List of Iterator loaders. - ratios (List[float]): List of ratios to sample from each loader. If None, all loaders are sampled uniformly. - """ - - def __init__(self, loaders, ratios=None): - # assert all loaders has __next__ method - for loader in loaders: - assert hasattr( - loader, "__next__" - ), "Loader {} has no __next__ method.".format(loader) - - if ratios is None: - ratios = [1.0] * len(loaders) - else: - assert len(ratios) == len(loaders) - ratios = [float(ratio) / sum(ratios) for ratio in ratios] - - self.loaders = loaders - self.ratios = ratios - - def __next__(self): - # random sample from each loader by ratio - loader_idx = random.choices(range(len(self.loaders)), self.ratios, k=1)[0] - return next(self.loaders[loader_idx]) - - -class PrefetchLoader(object): - """ - Modified from https://github.com/ChenRocks/UNITER. - - overlap compute and cuda data transfer - (copied and then modified from nvidia apex) - """ - - def __init__(self, loader): - self.loader = loader - self.stream = torch.cuda.Stream() - - def __iter__(self): - loader_it = iter(self.loader) - self.preload(loader_it) - batch = self.next(loader_it) - while batch is not None: - is_tuple = isinstance(batch, tuple) - if is_tuple: - task, batch = batch - - if is_tuple: - yield task, batch - else: - yield batch - batch = self.next(loader_it) - - def __len__(self): - return len(self.loader) - - def preload(self, it): - try: - self.batch = next(it) - except StopIteration: - self.batch = None - return - # if record_stream() doesn't work, another option is to make sure - # device inputs are created on the main stream. - # self.next_input_gpu = torch.empty_like(self.next_input, - # device='cuda') - # self.next_target_gpu = torch.empty_like(self.next_target, - # device='cuda') - # Need to make sure the memory allocated for next_* is not still in use - # by the main stream at the time we start copying to next_*: - # self.stream.wait_stream(torch.cuda.current_stream()) - with torch.cuda.stream(self.stream): - self.batch = move_to_cuda(self.batch) - # more code for the alternative if record_stream() doesn't work: - # copy_ will record the use of the pinned source tensor in this - # side stream. - # self.next_input_gpu.copy_(self.next_input, non_blocking=True) - # self.next_target_gpu.copy_(self.next_target, non_blocking=True) - # self.next_input = self.next_input_gpu - # self.next_target = self.next_target_gpu - - def next(self, it): - torch.cuda.current_stream().wait_stream(self.stream) - batch = self.batch - if batch is not None: - record_cuda_stream(batch) - self.preload(it) - return batch - - def __getattr__(self, name): - method = self.loader.__getattribute__(name) - return method - - -def record_cuda_stream(batch): - if isinstance(batch, torch.Tensor): - batch.record_stream(torch.cuda.current_stream()) - elif isinstance(batch, list) or isinstance(batch, tuple): - for t in batch: - record_cuda_stream(t) - elif isinstance(batch, dict): - for t in batch.values(): - record_cuda_stream(t) - else: - pass - - -class IterLoader: - """ - A wrapper to convert DataLoader as an infinite iterator. - - Modified from: - https://github.com/open-mmlab/mmcv/blob/master/mmcv/runner/iter_based_runner.py - """ - - def __init__(self, dataloader: DataLoader, use_distributed: bool = False): - self._dataloader = dataloader - self.iter_loader = iter(self._dataloader) - self._use_distributed = use_distributed - self._epoch = 0 - - @property - def epoch(self) -> int: - return self._epoch - - def __next__(self): - try: - data = next(self.iter_loader) - except StopIteration: - self._epoch += 1 - if hasattr(self._dataloader.sampler, "set_epoch") and self._use_distributed: - self._dataloader.sampler.set_epoch(self._epoch) - time.sleep(2) # Prevent possible deadlock during epoch transition - self.iter_loader = iter(self._dataloader) - data = next(self.iter_loader) - - return data - - def __iter__(self): - return self - - def __len__(self): - return len(self._dataloader) diff --git a/sonique/Video_LLaMA/video_llama/datasets/datasets/laion_dataset.py b/sonique/Video_LLaMA/video_llama/datasets/datasets/laion_dataset.py deleted file mode 100644 index a0a680e73719d0fb10db95614edd2b1cb8423656..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/datasets/datasets/laion_dataset.py +++ /dev/null @@ -1,31 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import webdataset as wds -from sonique.Video_LLaMA.video_llama.datasets.datasets.base_dataset import BaseDataset - - -class LaionDataset(BaseDataset): - def __init__(self, vis_processor, text_processor, location): - super().__init__(vis_processor=vis_processor, text_processor=text_processor) - - self.inner_dataset = wds.DataPipeline( - wds.ResampledShards(location), - wds.tarfile_to_samples(handler=wds.warn_and_continue), - wds.shuffle(1000, handler=wds.warn_and_continue), - wds.decode("pilrgb", handler=wds.warn_and_continue), - wds.to_tuple("jpg", "json", handler=wds.warn_and_continue), - wds.map_tuple(self.vis_processor, handler=wds.warn_and_continue), - wds.map(self.to_dict, handler=wds.warn_and_continue), - ) - - def to_dict(self, sample): - return { - "image": sample[0], - "text_input": self.text_processor(sample[1]["caption"]), - } - diff --git a/sonique/Video_LLaMA/video_llama/datasets/datasets/llava_instruct_dataset.py b/sonique/Video_LLaMA/video_llama/datasets/datasets/llava_instruct_dataset.py deleted file mode 100644 index 512fc18de4c29524a43840581b0610fec42f5df9..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/datasets/datasets/llava_instruct_dataset.py +++ /dev/null @@ -1,312 +0,0 @@ -import os -from sonique.Video_LLaMA.video_llama.datasets.datasets.base_dataset import BaseDataset -from sonique.Video_LLaMA.video_llama.datasets.datasets.caption_datasets import CaptionDataset -import pandas as pd -import decord -from decord import VideoReader -import random -import torch -from torch.utils.data.dataloader import default_collate -from PIL import Image -from typing import Dict, Optional, Sequence -import transformers -import pathlib -import json -from transformers import AutoTokenizer, AutoModelForCausalLM, LlamaTokenizer -from sonique.Video_LLaMA.video_llama.conversation.conversation_video import Conversation,SeparatorStyle -DEFAULT_IMAGE_PATCH_TOKEN = '' -DEFAULT_IMAGE_TOKEN = "" -import copy -from sonique.Video_LLaMA.video_llama.processors import transforms_video,AlproVideoTrainProcessor -IGNORE_INDEX = -100 -image_conversation = Conversation( - system="", - roles=("Human", "Assistant"), - messages=[], - offset=0, - sep_style=SeparatorStyle.SINGLE, - sep="###", -) -llama_v2_image_conversation = Conversation( - system=" ", - roles=("USER", "ASSISTANT"), - messages=(), - offset=0, - sep_style=SeparatorStyle.LLAMA_2, - sep="", - sep2="", -) -IGNORE_INDEX = -100 - -class Instruct_Dataset(BaseDataset): - def __init__(self, vis_processor, text_processor, vis_root, ann_root,num_video_query_token=32,tokenizer_name = '/mnt/workspace/ckpt/vicuna-13b/',data_type = 'image', model_type='vicuna'): - """ - vis_root (string): Root directory of Llava images (e.g. webvid_eval/video/) - ann_root (string): Root directory of video (e.g. webvid_eval/annotations/) - split (string): val or test - """ - super().__init__(vis_processor=vis_processor, text_processor=text_processor) - - data_path = pathlib.Path(ann_root) - with data_path.open(encoding='utf-8') as f: - self.annotation = json.load(f) - - self.vis_root = vis_root - self.resize_size = 224 - self.num_frm = 8 - self.tokenizer = LlamaTokenizer.from_pretrained(tokenizer_name, use_fast=False) - self.tokenizer.pad_token = self.tokenizer.unk_token - self.tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True) - self.num_video_query_token = num_video_query_token - self.IMAGE_PATCH_TOKEN_ID = self.tokenizer.get_vocab()[DEFAULT_IMAGE_PATCH_TOKEN] - - self.transform = AlproVideoTrainProcessor( - image_size=self.resize_size, n_frms = self.num_frm - ).transform - self.data_type = data_type - self.model_type = model_type - - def _get_image_path(self, sample): - rel_video_fp ='COCO_train2014_' + sample['image'] - full_video_fp = os.path.join(self.vis_root, rel_video_fp) - return full_video_fp - - def __getitem__(self, index): - num_retries = 10 # skip error videos - for _ in range(num_retries): - try: - sample = self.annotation[index] - - image_path = self._get_image_path(sample) - conversation_list = sample['conversations'] - image = Image.open(image_path).convert("RGB") - - image = self.vis_processor(image) - # text = self.text_processor(text) - sources = preprocess_multimodal(copy.deepcopy(conversation_list), None, cur_token_len=self.num_video_query_token) - if self.model_type =='vicuna': - data_dict = preprocess( - sources, - self.tokenizer) - elif self.model_type =='llama_v2': - data_dict = preprocess_for_llama_v2( - sources, - self.tokenizer) - else: - print('not support') - raise('not support') - data_dict = dict(input_ids=data_dict["input_ids"][0], - labels=data_dict["labels"][0]) - - # image exist in the data - data_dict['image'] = image - except: - print(f"Failed to load examples with image: {image_path}. " - f"Will randomly sample an example as a replacement.") - index = random.randint(0, len(self) - 1) - continue - break - else: - raise RuntimeError(f"Failed to fetch image after {num_retries} retries.") - # "image_id" is kept to stay compatible with the COCO evaluation format - return { - "image": image, - "text_input": data_dict["input_ids"], - "labels": data_dict["labels"], - "type":'image', - } - - def __len__(self): - return len(self.annotation) - - def collater(self, instances): - input_ids, labels = tuple([instance[key] for instance in instances] - for key in ("text_input", "labels")) - input_ids = torch.nn.utils.rnn.pad_sequence( - input_ids, - batch_first=True, - padding_value=self.tokenizer.pad_token_id) - labels = torch.nn.utils.rnn.pad_sequence(labels, - batch_first=True, - padding_value=IGNORE_INDEX) - batch = dict( - input_ids=input_ids, - labels=labels, - attention_mask=input_ids.ne(self.tokenizer.pad_token_id), - ) - - if 'image' in instances[0]: - images = [instance['image'] for instance in instances] - if all(x is not None and x.shape == images[0].shape for x in images): - batch['images'] = torch.stack(images) - else: - batch['images'] = images - batch['conv_type'] = 'multi' - return batch - - -def preprocess_multimodal( - conversation_list: Sequence[str], - multimodal_cfg: dict, - cur_token_len: int, -) -> Dict: - # 将conversational list中 - is_multimodal = True - # image_token_len = multimodal_cfg['image_token_len'] - image_token_len = cur_token_len - - for sentence in conversation_list: - replace_token = ''+DEFAULT_IMAGE_PATCH_TOKEN * image_token_len+'' - sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token) - - return [conversation_list] - -def _add_speaker_and_signal(header, source, get_conversation=True): - """Add speaker and start/end signal on each round.""" - BEGIN_SIGNAL = "###" - END_SIGNAL = "\n" - conversation = header - for sentence in source: - from_str = sentence["from"] - if from_str.lower() == "human": - from_str = image_conversation.roles[0] - elif from_str.lower() == "gpt": - from_str = image_conversation.roles[1] - else: - from_str = 'unknown' - sentence["value"] = (BEGIN_SIGNAL + from_str + ": " + - sentence["value"] + END_SIGNAL) - if get_conversation: - conversation += sentence["value"] - conversation += BEGIN_SIGNAL - return conversation - -def _tokenize_fn(strings: Sequence[str], - tokenizer: transformers.PreTrainedTokenizer) -> Dict: - """Tokenize a list of strings.""" - tokenized_list = [ - tokenizer( - text, - return_tensors="pt", - padding="longest", - max_length=512, - truncation=True, - ) for text in strings - ] - input_ids = labels = [ - tokenized.input_ids[0] for tokenized in tokenized_list - ] - input_ids_lens = labels_lens = [ - tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() - for tokenized in tokenized_list - ] - return dict( - input_ids=input_ids, - labels=labels, - input_ids_lens=input_ids_lens, - labels_lens=labels_lens, - ) - -def preprocess( - sources: Sequence[str], - tokenizer: transformers.PreTrainedTokenizer, -) -> Dict: - """ - Given a list of sources, each is a conversation list. This transform: - 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; - 2. Concatenate conversations together; - 3. Tokenize the concatenated conversation; - 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX. - """ - # add end signal and concatenate together - conversations = [] - for source in sources: - header = f"{image_conversation.system}\n\n" - conversation = _add_speaker_and_signal(header, source) - conversations.append(conversation) - # tokenize conversations - conversations_tokenized = _tokenize_fn(conversations, tokenizer) - input_ids = conversations_tokenized["input_ids"] - targets = copy.deepcopy(input_ids) - for target, source in zip(targets, sources): - tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], - tokenizer)["input_ids_lens"] - speakers = [sentence["from"] for sentence in source] - _mask_targets(target, tokenized_lens, speakers) - - return dict(input_ids=input_ids, labels=targets) - -def preprocess_for_llama_v2( - sources: Sequence[str], - tokenizer: transformers.PreTrainedTokenizer, -) -> Dict: - """ - Given a list of sources, each is a conversation list. This transform: - 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; - 2. Concatenate conversations together; - 3. Tokenize the concatenated conversation; - 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX. - """ - # add end signal and concatenate together - conversations = [] - conv = copy.deepcopy(llama_v2_image_conversation.copy()) - roles = {"human": conv.roles[0], "gpt": conv.roles[1]} - for source in sources: - # [INST] <>\n{system_prompt}\n<>\n\n - header = f"[INST] <>\n{conv.system}\n>\n\n" - - if roles[source[0]["from"]] != conv.roles[0]: - # Skip the first one if it is not from human - source = source[1:] - conv.messages = [] - for j, sentence in enumerate(source): - role = roles[sentence["from"]] - assert role == conv.roles[j % 2] - conv.append_message(role, sentence["value"]) - conversations.append(conv.get_prompt()) - - input_ids = tokenizer( - conversations, - return_tensors="pt", - padding="longest", - max_length=512, - truncation=True, - ).input_ids - targets = copy.deepcopy(input_ids) - - - sep = "[/INST] " - for conversation, target in zip(conversations, targets): - # total_len = int(target.ne(tokenizer.pad_token_id).sum()) - rounds = conversation.split(conv.sep2) - cur_len = 1 - target[:cur_len] = IGNORE_INDEX - for i, rou in enumerate(rounds): - if rou == "": - break - - parts = rou.split(sep) - if len(parts) != 2: - break - parts[0] += sep - - - round_len = len(tokenizer(rou).input_ids) - instruction_len = len(tokenizer(parts[0]).input_ids) - 2 # 为什么减去2,speical token 的数目 - - target[cur_len : cur_len + instruction_len] = IGNORE_INDEX - - cur_len += round_len - target[cur_len:] = IGNORE_INDEX - - return dict(input_ids=input_ids, labels=targets) - -def _mask_targets(target, tokenized_lens, speakers): - # cur_idx = 0 - cur_idx = tokenized_lens[0] - tokenized_lens = tokenized_lens[1:] - target[:cur_idx] = IGNORE_INDEX - for tokenized_len, speaker in zip(tokenized_lens, speakers): - if speaker == "human": - target[cur_idx+2:cur_idx + tokenized_len] = IGNORE_INDEX - cur_idx += tokenized_len diff --git a/sonique/Video_LLaMA/video_llama/datasets/datasets/video_instruct_dataset.py b/sonique/Video_LLaMA/video_llama/datasets/datasets/video_instruct_dataset.py deleted file mode 100644 index 3600c7de497e74be3f36c4136996603f991af1af..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/datasets/datasets/video_instruct_dataset.py +++ /dev/null @@ -1,335 +0,0 @@ -import os -from sonique.Video_LLaMA.video_llama.datasets.datasets.base_dataset import BaseDataset -from sonique.Video_LLaMA.video_llama.datasets.datasets.caption_datasets import CaptionDataset -import pandas as pd -import decord -from decord import VideoReader -import random -import torch -from torch.utils.data.dataloader import default_collate -from PIL import Image -from typing import Dict, Optional, Sequence -import transformers -import pathlib -import json -from transformers import AutoTokenizer, AutoModelForCausalLM, LlamaTokenizer -import copy -from sonique.Video_LLaMA.video_llama.processors import transforms_video,AlproVideoTrainProcessor -from torchvision import transforms -from sonique.Video_LLaMA.video_llama.processors.video_processor import ToTHWC,ToUint8,load_video -from sonique.Video_LLaMA.video_llama.conversation.conversation_video import Conversation,SeparatorStyle - -DEFAULT_IMAGE_PATCH_TOKEN = '' -video_conversation = Conversation( - system="", - roles=("Human", "Assistant"), - messages=[], - offset=0, - sep_style=SeparatorStyle.SINGLE, - sep="###", -) -llama_v2_video_conversation = Conversation( - system=" ", - roles=("USER", "ASSISTANT"), - messages=(), - offset=0, - sep_style=SeparatorStyle.LLAMA_2, - sep="", - sep2="", -) -IGNORE_INDEX = -100 - -class Video_Instruct_Dataset(BaseDataset): - def __init__(self, vis_processor, text_processor, vis_root, ann_root,num_video_query_token=32,tokenizer_name = '/mnt/workspace/ckpt/vicuna-13b/',data_type = 'video', model_type='vicuna'): - """ - vis_root (string): Root directory of Llava images (e.g. webvid_eval/video/) - ann_root (string): Root directory of video (e.g. webvid_eval/annotations/) - split (string): val or test - """ - super().__init__(vis_processor=vis_processor, text_processor=text_processor) - - data_path = pathlib.Path(ann_root) - with data_path.open(encoding='utf-8') as f: - self.annotation = json.load(f) - - self.num_video_query_token = num_video_query_token - self.vis_root = vis_root - self.resize_size = 224 - self.num_frm = 8 - self.tokenizer = LlamaTokenizer.from_pretrained(tokenizer_name, use_fast=False) - self.tokenizer.pad_token = self.tokenizer.unk_token - self.tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True) - self.IMAGE_PATCH_TOKEN_ID = self.tokenizer.get_vocab()[DEFAULT_IMAGE_PATCH_TOKEN] - - self.transform = AlproVideoTrainProcessor( - image_size=self.resize_size, n_frms = self.num_frm - ).transform - self.data_type = data_type - self.model_type = model_type - - def _get_video_path(self, sample): - rel_video_fp = sample['video'] - full_video_fp = os.path.join(self.vis_root, rel_video_fp) - return full_video_fp - - def __getitem__(self, index): - num_retries = 10 # skip error videos - for _ in range(num_retries): - try: - sample = self.annotation[index] - - video_path = self._get_video_path(sample) - conversation_list = sample['QA'] - - video, msg = load_video( - video_path=video_path, - n_frms=self.num_frm, - height=self.resize_size, - width=self.resize_size, - sampling ="uniform", return_msg = True - ) - video = self.transform(video) - if 'cn' in self.data_type: - msg = "" - # 添加视频,以及msg到convsation list 0 - sources = preprocess_multimodal(copy.deepcopy(conversation_list), None, cur_token_len=self.num_video_query_token,msg = msg) - new_sources = convert_source_vicuna_format(sources) - - if self.model_type =='vicuna': - data_dict = preprocess( - new_sources, - self.tokenizer) - elif self.model_type =='llama_v2': - data_dict = preprocess_for_llama_v2( - new_sources, - self.tokenizer) - else: - print('not support') - raise('not support') - data_dict = dict(input_ids=data_dict["input_ids"][0], - labels=data_dict["labels"][0]) - # image exist in the data - data_dict['image'] = video - except: - print(f"Failed to load examples with video: {video_path}. " - f"Will randomly sample an example as a replacement.") - index = random.randint(0, len(self) - 1) - continue - break - else: - raise RuntimeError(f"Failed to fetch video after {num_retries} retries.") - # "image_id" is kept to stay compatible with the COCO evaluation format - return { - "image": video, - "text_input": data_dict["input_ids"], - "labels": data_dict["labels"], - "type":'video', - } - - def __len__(self): - return len(self.annotation) - - def collater(self, instances): - input_ids, labels = tuple([instance[key] for instance in instances] - for key in ("text_input", "labels")) - input_ids = torch.nn.utils.rnn.pad_sequence( - input_ids, - batch_first=True, - padding_value=self.tokenizer.pad_token_id) - labels = torch.nn.utils.rnn.pad_sequence(labels, - batch_first=True, - padding_value=IGNORE_INDEX) - batch = dict( - input_ids=input_ids, - labels=labels, - attention_mask=input_ids.ne(self.tokenizer.pad_token_id), - ) - - if 'image' in instances[0]: - images = [instance['image'] for instance in instances] - if all(x is not None and x.shape == images[0].shape for x in images): - batch['images'] = torch.stack(images) - else: - batch['images'] = images - batch['conv_type'] = 'multi' - return batch - -def convert_source_vicuna_format(sources): - new_sources = [] - for source in sources: - new_source = [] - for i, sentence in enumerate(source): - role_0_msg = sentence['q'] - role_1_msg = sentence['a'] - new_source.append({ - 'from':'human', - 'value': role_0_msg, - }) - new_source.append({ - 'from':'gpt', - 'value': role_1_msg, - }) - new_sources.append(new_source) - return new_sources - -def preprocess_multimodal( - conversation_list: Sequence[str], - multimodal_cfg: dict, - cur_token_len: int, - msg='' -) -> Dict: - # 将conversational list中 - is_multimodal = True - # image_token_len = multimodal_cfg['image_token_len'] - image_token_len = cur_token_len - conversation_list[0]["q"] = " " + msg + conversation_list[0]["q"] - return [conversation_list] - -def _add_speaker_and_signal(header, source, get_conversation=True): - """Add speaker and start/end signal on each round.""" - BEGIN_SIGNAL = "###" - END_SIGNAL = "\n" - conversation = header - for sentence in source: - from_str = sentence["from"] - if from_str.lower() == "human": - from_str = video_conversation.roles[0] - elif from_str.lower() == "gpt": - from_str = video_conversation.roles[1] - else: - from_str = 'unknown' - sentence["value"] = (BEGIN_SIGNAL + from_str + ": " + - sentence["value"] + END_SIGNAL) - if get_conversation: - conversation += sentence["value"] - conversation += BEGIN_SIGNAL - return conversation - -def _tokenize_fn(strings: Sequence[str], - tokenizer: transformers.PreTrainedTokenizer) -> Dict: - """Tokenize a list of strings.""" - tokenized_list = [ - tokenizer( - text, - return_tensors="pt", - padding="longest", - max_length=512, - truncation=True, - ) for text in strings - ] - input_ids = labels = [ - tokenized.input_ids[0] for tokenized in tokenized_list - ] - input_ids_lens = labels_lens = [ - tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() - for tokenized in tokenized_list - ] - return dict( - input_ids=input_ids, - labels=labels, - input_ids_lens=input_ids_lens, - labels_lens=labels_lens, - ) - -def preprocess( - sources: Sequence[str], - tokenizer: transformers.PreTrainedTokenizer, -) -> Dict: - """ - Given a list of sources, each is a conversation list. This transform: - 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; - 2. Concatenate conversations together; - 3. Tokenize the concatenated conversation; - 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX. - """ - # add end signal and concatenate together - conversations = [] - for source in sources: - header = f"{video_conversation.system}\n\n" - conversation = _add_speaker_and_signal(header, source) - conversations.append(conversation) - # tokenize conversations - conversations_tokenized = _tokenize_fn(conversations, tokenizer) - input_ids = conversations_tokenized["input_ids"] - targets = copy.deepcopy(input_ids) - for target, source in zip(targets, sources): - tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], - tokenizer)["input_ids_lens"] - speakers = [sentence["from"] for sentence in source] - _mask_targets(target, tokenized_lens, speakers) - - return dict(input_ids=input_ids, labels=targets) - -def preprocess_for_llama_v2( - sources: Sequence[str], - tokenizer: transformers.PreTrainedTokenizer, -) -> Dict: - """ - Given a list of sources, each is a conversation list. This transform: - 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; - 2. Concatenate conversations together; - 3. Tokenize the concatenated conversation; - 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX. - """ - # add end signal and concatenate together - conversations = [] - conv = copy.deepcopy(llama_v2_video_conversation.copy()) - roles = {"human": conv.roles[0], "gpt": conv.roles[1]} - for source in sources: - # [INST] <>\n{system_prompt}\n<>\n\n - header = f"[INST] <>\n{conv.system}\n>\n\n" - - if roles[source[0]["from"]] != conv.roles[0]: - # Skip the first one if it is not from human - source = source[1:] - conv.messages = [] - for j, sentence in enumerate(source): - role = roles[sentence["from"]] - assert role == conv.roles[j % 2] - conv.append_message(role, sentence["value"]) - conversations.append(conv.get_prompt()) - - input_ids = tokenizer( - conversations, - return_tensors="pt", - padding="longest", - max_length=512, - truncation=True, - ).input_ids - targets = copy.deepcopy(input_ids) - - - sep = "[/INST] " - for conversation, target in zip(conversations, targets): - # total_len = int(target.ne(tokenizer.pad_token_id).sum()) - rounds = conversation.split(conv.sep2) - cur_len = 1 - target[:cur_len] = IGNORE_INDEX - for i, rou in enumerate(rounds): - if rou == "": - break - - parts = rou.split(sep) - if len(parts) != 2: - break - parts[0] += sep - - - round_len = len(tokenizer(rou).input_ids) - instruction_len = len(tokenizer(parts[0]).input_ids) - 2 # 为什么减去2,speical token 的数目 - - target[cur_len : cur_len + instruction_len] = IGNORE_INDEX - - cur_len += round_len - target[cur_len:] = IGNORE_INDEX - - return dict(input_ids=input_ids, labels=targets) -def _mask_targets(target, tokenized_lens, speakers): - # cur_idx = 0 - cur_idx = tokenized_lens[0] - tokenized_lens = tokenized_lens[1:] - target[:cur_idx] = IGNORE_INDEX - for tokenized_len, speaker in zip(tokenized_lens, speakers): - if speaker == "human": - target[cur_idx+2:cur_idx + tokenized_len] = IGNORE_INDEX - cur_idx += tokenized_len diff --git a/sonique/Video_LLaMA/video_llama/datasets/datasets/webvid_datasets.py b/sonique/Video_LLaMA/video_llama/datasets/datasets/webvid_datasets.py deleted file mode 100644 index d9706f7c8c89a422650b4b7a8325122e50125ea0..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/datasets/datasets/webvid_datasets.py +++ /dev/null @@ -1,122 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import os -from sonique.Video_LLaMA.video_llama.datasets.datasets.base_dataset import BaseDataset -from sonique.Video_LLaMA.video_llama.datasets.datasets.caption_datasets import CaptionDataset -import pandas as pd -import decord -from decord import VideoReader -import random -import torch -from torch.utils.data.dataloader import default_collate -class WebvidDataset(BaseDataset): - def __init__(self, vis_processor, text_processor, vis_root, ann_root): - """ - vis_root (string): Root directory of video (e.g. webvid_eval/video/) - ann_root (string): Root directory of video (e.g. webvid_eval/annotations/) - split (string): val or test - """ - super().__init__(vis_processor=vis_processor, text_processor=text_processor) - - - # 读取一个路径下所有的 - - ts_df = [] - for file_name in os.listdir(ann_root): - if file_name.endswith('.csv'): - df = pd.read_csv(os.path.join(ann_root, file_name)) - ts_df.append(df) - - merged_df = pd.concat(ts_df) - self.annotation = merged_df - self.vis_root = vis_root - self.resize_size = 224 - self.num_frm = 8 - self.frm_sampling_strategy = 'headtail' - - def _get_video_path(self, sample): - rel_video_fp = os.path.join(sample['page_dir'], str(sample['videoid']) + '.mp4') - full_video_fp = os.path.join(self.vis_root, rel_video_fp) - return full_video_fp - - def __getitem__(self, index): - num_retries = 10 # skip error videos - for _ in range(num_retries): - sample = self.annotation.iloc[index] - sample_dict = sample.to_dict() - video_id = sample_dict['videoid'] - - if 'name' in sample_dict.keys(): - text = sample_dict['name'].strip() - else: - raise NotImplementedError("Un-supported text annotation format.") - - # fetch video - video_path = self._get_video_path(sample_dict) - # if os.path.exists(video_path): - try: - video = self.vis_processor(video_path) - except: - print(f"Failed to load examples with video: {video_path}. " - f"Will randomly sample an example as a replacement.") - index = random.randint(0, len(self) - 1) - continue - caption = self.text_processor(text) - - # print(video.size()) - if video is None or caption is None \ - or video.size()!=torch.Size([3,self.vis_processor.n_frms,224,224]): - print(f"Failed to load examples with video: {video_path}. " - f"Will randomly sample an example as a replacement.") - index = random.randint(0, len(self) - 1) - continue - else: - break - else: - raise RuntimeError(f"Failed to fetch video after {num_retries} retries.") - # "image_id" is kept to stay compatible with the COCO evaluation format - return { - "image": video, - "text_input": caption, - "type":'video', - } - - def __len__(self): - return len(self.annotation) - - # def collater(self, samples): - # new_result = {} - # new_result['image'] = default_collate( [sample["image"] for sample in samples]) - # new_result['text_input'] = default_collate( [sample["text_input"] for sample in samples]) - # return new_result - -class WebvidDatasetEvalDataset(BaseDataset): - def __init__(self, vis_processor, text_processor, vis_root, ann_paths): - """ - vis_root (string): Root directory of images (e.g. coco/images/) - ann_root (string): directory to store the annotation file - split (string): val or test - """ - super().__init__(vis_processor, text_processor, vis_root, ann_paths) - - def __getitem__(self, index): - - ann = self.annotation[index] - - vname = ann["video"] - video_path = os.path.join(self.vis_root, vname) - - video = self.vis_processor(video_path) - - return { - "video": video, - "image_id": ann["image_id"], - "instance_id": ann["instance_id"], - } - - diff --git a/sonique/Video_LLaMA/video_llama/models/ImageBind/.assets/bird_image.jpg b/sonique/Video_LLaMA/video_llama/models/ImageBind/.assets/bird_image.jpg deleted file mode 100644 index 78b10ab1fe76f42e3dda1dc515e69312f02713d9..0000000000000000000000000000000000000000 Binary files a/sonique/Video_LLaMA/video_llama/models/ImageBind/.assets/bird_image.jpg and /dev/null differ diff --git a/sonique/Video_LLaMA/video_llama/models/ImageBind/.assets/car_image.jpg b/sonique/Video_LLaMA/video_llama/models/ImageBind/.assets/car_image.jpg deleted file mode 100644 index e33288eb765882c594f479bfb35d941fd51a19b1..0000000000000000000000000000000000000000 Binary files a/sonique/Video_LLaMA/video_llama/models/ImageBind/.assets/car_image.jpg and /dev/null differ diff --git a/sonique/Video_LLaMA/video_llama/models/ImageBind/.assets/dog_image.jpg b/sonique/Video_LLaMA/video_llama/models/ImageBind/.assets/dog_image.jpg deleted file mode 100644 index a54bffa5c80869c6b96246ba29c9e2462c698e3b..0000000000000000000000000000000000000000 Binary files a/sonique/Video_LLaMA/video_llama/models/ImageBind/.assets/dog_image.jpg and /dev/null differ diff --git a/sonique/Video_LLaMA/video_llama/models/ImageBind/CODE_OF_CONDUCT.md b/sonique/Video_LLaMA/video_llama/models/ImageBind/CODE_OF_CONDUCT.md deleted file mode 100644 index f913b6a55a6c5ab6e1224e11fc039c3d4c3b6283..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/ImageBind/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,80 +0,0 @@ -# Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to make participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, sex characteristics, gender identity and expression, -level of experience, education, socio-economic status, nationality, personal -appearance, race, religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic -address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a -professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies within all project spaces, and it also applies when -an individual is representing the project or its community in public spaces. -Examples of representing a project or community include using an official -project e-mail address, posting via an official social media account, or acting -as an appointed representative at an online or offline event. Representation of -a project may be further defined and clarified by project maintainers. - -This Code of Conduct also applies outside the project spaces when there is a -reasonable belief that an individual's behavior may have a negative impact on -the project or its community. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at . All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see -https://www.contributor-covenant.org/faq \ No newline at end of file diff --git a/sonique/Video_LLaMA/video_llama/models/ImageBind/CONTRIBUTING.md b/sonique/Video_LLaMA/video_llama/models/ImageBind/CONTRIBUTING.md deleted file mode 100644 index 63d0b751e8a00b606ddff92e2524faa3c90a63b0..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/ImageBind/CONTRIBUTING.md +++ /dev/null @@ -1,31 +0,0 @@ -# Contributing to ImageBind -We want to make contributing to this project as easy and transparent as -possible. - -## Pull Requests -We actively welcome your pull requests. - -1. Fork the repo and create your branch from `main`. -2. If you've added code that should be tested, add tests. -3. If you've changed APIs, update the documentation. -4. Ensure the test suite passes. -5. Make sure your code lints. -6. If you haven't already, complete the Contributor License Agreement ("CLA"). - -## Contributor License Agreement ("CLA") -In order to accept your pull request, we need you to submit a CLA. You only need -to do this once to work on any of Meta's open source projects. - -Complete your CLA here: - -## Issues -We use GitHub issues to track public bugs. Please ensure your description is -clear and has sufficient instructions to be able to reproduce the issue. - -Meta has a [bounty program](https://www.facebook.com/whitehat/) for the safe -disclosure of security bugs. In those cases, please go through the process -outlined on that page and do not file a public issue. - -## License -By contributing to Omnivore, you agree that your contributions will be licensed -under the [LICENSE](LICENSE) file in the root directory of this source tree. diff --git a/sonique/Video_LLaMA/video_llama/models/ImageBind/LICENSE b/sonique/Video_LLaMA/video_llama/models/ImageBind/LICENSE deleted file mode 100644 index bfef380bf7d9cb74ec9ba533b37c3fbeef3bdc09..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/ImageBind/LICENSE +++ /dev/null @@ -1,437 +0,0 @@ -Attribution-NonCommercial-ShareAlike 4.0 International - -======================================================================= - -Creative Commons Corporation ("Creative Commons") is not a law firm and -does not provide legal services or legal advice. Distribution of -Creative Commons public licenses does not create a lawyer-client or -other relationship. Creative Commons makes its licenses and related -information available on an "as-is" basis. Creative Commons gives no -warranties regarding its licenses, any material licensed under their -terms and conditions, or any related information. Creative Commons -disclaims all liability for damages resulting from their use to the -fullest extent possible. - -Using Creative Commons Public Licenses - -Creative Commons public licenses provide a standard set of terms and -conditions that creators and other rights holders may use to share -original works of authorship and other material subject to copyright -and certain other rights specified in the public license below. The -following considerations are for informational purposes only, are not -exhaustive, and do not form part of our licenses. - - Considerations for licensors: Our public licenses are - intended for use by those authorized to give the public - permission to use material in ways otherwise restricted by - copyright and certain other rights. Our licenses are - irrevocable. Licensors should read and understand the terms - and conditions of the license they choose before applying it. - Licensors should also secure all rights necessary before - applying our licenses so that the public can reuse the - material as expected. Licensors should clearly mark any - material not subject to the license. This includes other CC- - licensed material, or material used under an exception or - limitation to copyright. More considerations for licensors: - wiki.creativecommons.org/Considerations_for_licensors - - Considerations for the public: By using one of our public - licenses, a licensor grants the public permission to use the - licensed material under specified terms and conditions. If - the licensor's permission is not necessary for any reason--for - example, because of any applicable exception or limitation to - copyright--then that use is not regulated by the license. Our - licenses grant only permissions under copyright and certain - other rights that a licensor has authority to grant. Use of - the licensed material may still be restricted for other - reasons, including because others have copyright or other - rights in the material. A licensor may make special requests, - such as asking that all changes be marked or described. - Although not required by our licenses, you are encouraged to - respect those requests where reasonable. More considerations - for the public: - wiki.creativecommons.org/Considerations_for_licensees - -======================================================================= - -Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International -Public License - -By exercising the Licensed Rights (defined below), You accept and agree -to be bound by the terms and conditions of this Creative Commons -Attribution-NonCommercial-ShareAlike 4.0 International Public License -("Public License"). To the extent this Public License may be -interpreted as a contract, You are granted the Licensed Rights in -consideration of Your acceptance of these terms and conditions, and the -Licensor grants You such rights in consideration of benefits the -Licensor receives from making the Licensed Material available under -these terms and conditions. - - -Section 1 -- Definitions. - - a. Adapted Material means material subject to Copyright and Similar - Rights that is derived from or based upon the Licensed Material - and in which the Licensed Material is translated, altered, - arranged, transformed, or otherwise modified in a manner requiring - permission under the Copyright and Similar Rights held by the - Licensor. For purposes of this Public License, where the Licensed - Material is a musical work, performance, or sound recording, - Adapted Material is always produced where the Licensed Material is - synched in timed relation with a moving image. - - b. Adapter's License means the license You apply to Your Copyright - and Similar Rights in Your contributions to Adapted Material in - accordance with the terms and conditions of this Public License. - - c. BY-NC-SA Compatible License means a license listed at - creativecommons.org/compatiblelicenses, approved by Creative - Commons as essentially the equivalent of this Public License. - - d. Copyright and Similar Rights means copyright and/or similar rights - closely related to copyright including, without limitation, - performance, broadcast, sound recording, and Sui Generis Database - Rights, without regard to how the rights are labeled or - categorized. For purposes of this Public License, the rights - specified in Section 2(b)(1)-(2) are not Copyright and Similar - Rights. - - e. Effective Technological Measures means those measures that, in the - absence of proper authority, may not be circumvented under laws - fulfilling obligations under Article 11 of the WIPO Copyright - Treaty adopted on December 20, 1996, and/or similar international - agreements. - - f. Exceptions and Limitations means fair use, fair dealing, and/or - any other exception or limitation to Copyright and Similar Rights - that applies to Your use of the Licensed Material. - - g. License Elements means the license attributes listed in the name - of a Creative Commons Public License. The License Elements of this - Public License are Attribution, NonCommercial, and ShareAlike. - - h. Licensed Material means the artistic or literary work, database, - or other material to which the Licensor applied this Public - License. - - i. Licensed Rights means the rights granted to You subject to the - terms and conditions of this Public License, which are limited to - all Copyright and Similar Rights that apply to Your use of the - Licensed Material and that the Licensor has authority to license. - - j. Licensor means the individual(s) or entity(ies) granting rights - under this Public License. - - k. NonCommercial means not primarily intended for or directed towards - commercial advantage or monetary compensation. For purposes of - this Public License, the exchange of the Licensed Material for - other material subject to Copyright and Similar Rights by digital - file-sharing or similar means is NonCommercial provided there is - no payment of monetary compensation in connection with the - exchange. - - l. Share means to provide material to the public by any means or - process that requires permission under the Licensed Rights, such - as reproduction, public display, public performance, distribution, - dissemination, communication, or importation, and to make material - available to the public including in ways that members of the - public may access the material from a place and at a time - individually chosen by them. - - m. Sui Generis Database Rights means rights other than copyright - resulting from Directive 96/9/EC of the European Parliament and of - the Council of 11 March 1996 on the legal protection of databases, - as amended and/or succeeded, as well as other essentially - equivalent rights anywhere in the world. - - n. You means the individual or entity exercising the Licensed Rights - under this Public License. Your has a corresponding meaning. - - -Section 2 -- Scope. - - a. License grant. - - 1. Subject to the terms and conditions of this Public License, - the Licensor hereby grants You a worldwide, royalty-free, - non-sublicensable, non-exclusive, irrevocable license to - exercise the Licensed Rights in the Licensed Material to: - - a. reproduce and Share the Licensed Material, in whole or - in part, for NonCommercial purposes only; and - - b. produce, reproduce, and Share Adapted Material for - NonCommercial purposes only. - - 2. Exceptions and Limitations. For the avoidance of doubt, where - Exceptions and Limitations apply to Your use, this Public - License does not apply, and You do not need to comply with - its terms and conditions. - - 3. Term. The term of this Public License is specified in Section - 6(a). - - 4. Media and formats; technical modifications allowed. The - Licensor authorizes You to exercise the Licensed Rights in - all media and formats whether now known or hereafter created, - and to make technical modifications necessary to do so. The - Licensor waives and/or agrees not to assert any right or - authority to forbid You from making technical modifications - necessary to exercise the Licensed Rights, including - technical modifications necessary to circumvent Effective - Technological Measures. For purposes of this Public License, - simply making modifications authorized by this Section 2(a) - (4) never produces Adapted Material. - - 5. Downstream recipients. - - a. Offer from the Licensor -- Licensed Material. Every - recipient of the Licensed Material automatically - receives an offer from the Licensor to exercise the - Licensed Rights under the terms and conditions of this - Public License. - - b. Additional offer from the Licensor -- Adapted Material. - Every recipient of Adapted Material from You - automatically receives an offer from the Licensor to - exercise the Licensed Rights in the Adapted Material - under the conditions of the Adapter's License You apply. - - c. No downstream restrictions. You may not offer or impose - any additional or different terms or conditions on, or - apply any Effective Technological Measures to, the - Licensed Material if doing so restricts exercise of the - Licensed Rights by any recipient of the Licensed - Material. - - 6. No endorsement. Nothing in this Public License constitutes or - may be construed as permission to assert or imply that You - are, or that Your use of the Licensed Material is, connected - with, or sponsored, endorsed, or granted official status by, - the Licensor or others designated to receive attribution as - provided in Section 3(a)(1)(A)(i). - - b. Other rights. - - 1. Moral rights, such as the right of integrity, are not - licensed under this Public License, nor are publicity, - privacy, and/or other similar personality rights; however, to - the extent possible, the Licensor waives and/or agrees not to - assert any such rights held by the Licensor to the limited - extent necessary to allow You to exercise the Licensed - Rights, but not otherwise. - - 2. Patent and trademark rights are not licensed under this - Public License. - - 3. To the extent possible, the Licensor waives any right to - collect royalties from You for the exercise of the Licensed - Rights, whether directly or through a collecting society - under any voluntary or waivable statutory or compulsory - licensing scheme. In all other cases the Licensor expressly - reserves any right to collect such royalties, including when - the Licensed Material is used other than for NonCommercial - purposes. - - -Section 3 -- License Conditions. - -Your exercise of the Licensed Rights is expressly made subject to the -following conditions. - - a. Attribution. - - 1. If You Share the Licensed Material (including in modified - form), You must: - - a. retain the following if it is supplied by the Licensor - with the Licensed Material: - - i. identification of the creator(s) of the Licensed - Material and any others designated to receive - attribution, in any reasonable manner requested by - the Licensor (including by pseudonym if - designated); - - ii. a copyright notice; - - iii. a notice that refers to this Public License; - - iv. a notice that refers to the disclaimer of - warranties; - - v. a URI or hyperlink to the Licensed Material to the - extent reasonably practicable; - - b. indicate if You modified the Licensed Material and - retain an indication of any previous modifications; and - - c. indicate the Licensed Material is licensed under this - Public License, and include the text of, or the URI or - hyperlink to, this Public License. - - 2. You may satisfy the conditions in Section 3(a)(1) in any - reasonable manner based on the medium, means, and context in - which You Share the Licensed Material. For example, it may be - reasonable to satisfy the conditions by providing a URI or - hyperlink to a resource that includes the required - information. - 3. If requested by the Licensor, You must remove any of the - information required by Section 3(a)(1)(A) to the extent - reasonably practicable. - - b. ShareAlike. - - In addition to the conditions in Section 3(a), if You Share - Adapted Material You produce, the following conditions also apply. - - 1. The Adapter's License You apply must be a Creative Commons - license with the same License Elements, this version or - later, or a BY-NC-SA Compatible License. - - 2. You must include the text of, or the URI or hyperlink to, the - Adapter's License You apply. You may satisfy this condition - in any reasonable manner based on the medium, means, and - context in which You Share Adapted Material. - - 3. You may not offer or impose any additional or different terms - or conditions on, or apply any Effective Technological - Measures to, Adapted Material that restrict exercise of the - rights granted under the Adapter's License You apply. - - -Section 4 -- Sui Generis Database Rights. - -Where the Licensed Rights include Sui Generis Database Rights that -apply to Your use of the Licensed Material: - - a. for the avoidance of doubt, Section 2(a)(1) grants You the right - to extract, reuse, reproduce, and Share all or a substantial - portion of the contents of the database for NonCommercial purposes - only; - - b. if You include all or a substantial portion of the database - contents in a database in which You have Sui Generis Database - Rights, then the database in which You have Sui Generis Database - Rights (but not its individual contents) is Adapted Material, - including for purposes of Section 3(b); and - - c. You must comply with the conditions in Section 3(a) if You Share - all or a substantial portion of the contents of the database. - -For the avoidance of doubt, this Section 4 supplements and does not -replace Your obligations under this Public License where the Licensed -Rights include other Copyright and Similar Rights. - - -Section 5 -- Disclaimer of Warranties and Limitation of Liability. - - a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE - EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS - AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF - ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, - IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, - WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR - PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, - ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT - KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT - ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. - - b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE - TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, - NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, - INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, - COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR - USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN - ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR - DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR - IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. - - c. The disclaimer of warranties and limitation of liability provided - above shall be interpreted in a manner that, to the extent - possible, most closely approximates an absolute disclaimer and - waiver of all liability. - - -Section 6 -- Term and Termination. - - a. This Public License applies for the term of the Copyright and - Similar Rights licensed here. However, if You fail to comply with - this Public License, then Your rights under this Public License - terminate automatically. - - b. Where Your right to use the Licensed Material has terminated under - Section 6(a), it reinstates: - - 1. automatically as of the date the violation is cured, provided - it is cured within 30 days of Your discovery of the - violation; or - - 2. upon express reinstatement by the Licensor. - - For the avoidance of doubt, this Section 6(b) does not affect any - right the Licensor may have to seek remedies for Your violations - of this Public License. - - c. For the avoidance of doubt, the Licensor may also offer the - Licensed Material under separate terms or conditions or stop - distributing the Licensed Material at any time; however, doing so - will not terminate this Public License. - - d. Sections 1, 5, 6, 7, and 8 survive termination of this Public - License. - - -Section 7 -- Other Terms and Conditions. - - a. The Licensor shall not be bound by any additional or different - terms or conditions communicated by You unless expressly agreed. - - b. Any arrangements, understandings, or agreements regarding the - Licensed Material not stated herein are separate from and - independent of the terms and conditions of this Public License. - - -Section 8 -- Interpretation. - - a. For the avoidance of doubt, this Public License does not, and - shall not be interpreted to, reduce, limit, restrict, or impose - conditions on any use of the Licensed Material that could lawfully - be made without permission under this Public License. - - b. To the extent possible, if any provision of this Public License is - deemed unenforceable, it shall be automatically reformed to the - minimum extent necessary to make it enforceable. If the provision - cannot be reformed, it shall be severed from this Public License - without affecting the enforceability of the remaining terms and - conditions. - - c. No term or condition of this Public License will be waived and no - failure to comply consented to unless expressly agreed to by the - Licensor. - - d. Nothing in this Public License constitutes or may be interpreted - as a limitation upon, or waiver of, any privileges and immunities - that apply to the Licensor or You, including from the legal - processes of any jurisdiction or authority. - -======================================================================= - -Creative Commons is not a party to its public -licenses. Notwithstanding, Creative Commons may elect to apply one of -its public licenses to material it publishes and in those instances -will be considered the “Licensor.” The text of the Creative Commons -public licenses is dedicated to the public domain under the CC0 Public -Domain Dedication. Except for the limited purpose of indicating that -material is shared under a Creative Commons public license or as -otherwise permitted by the Creative Commons policies published at -creativecommons.org/policies, Creative Commons does not authorize the -use of the trademark "Creative Commons" or any other trademark or logo -of Creative Commons without its prior written consent including, -without limitation, in connection with any unauthorized modifications -to any of its public licenses or any other arrangements, -understandings, or agreements concerning use of licensed material. For -the avoidance of doubt, this paragraph does not form part of the -public licenses. - -Creative Commons may be contacted at creativecommons.org. \ No newline at end of file diff --git a/sonique/Video_LLaMA/video_llama/models/ImageBind/README.md b/sonique/Video_LLaMA/video_llama/models/ImageBind/README.md deleted file mode 100644 index 028fa988bb6cd9843aec9454636e1541b53680e7..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/ImageBind/README.md +++ /dev/null @@ -1,155 +0,0 @@ -# ImageBind: One Embedding Space To Bind Them All - -**[FAIR, Meta AI](https://ai.facebook.com/research/)** - -Rohit Girdhar*, -Alaaeldin El-Nouby*, -Zhuang Liu, -Mannat Singh, -Kalyan Vasudev Alwala, -Armand Joulin, -Ishan Misra* - -To appear at CVPR 2023 (*Highlighted paper*) - -[[`Paper`](https://facebookresearch.github.io/ImageBind/paper)] [[`Blog`](https://ai.facebook.com/blog/imagebind-six-modalities-binding-ai/)] [[`Demo`](https://imagebind.metademolab.com/)] [[`Supplementary Video`](https://dl.fbaipublicfiles.com/imagebind/imagebind_video.mp4)] [[`BibTex`](#citing-imagebind)] - -PyTorch implementation and pretrained models for ImageBind. For details, see the paper: **[ImageBind: One Embedding Space To Bind Them All](https://facebookresearch.github.io/ImageBind/paper)**. - -ImageBind learns a joint embedding across six different modalities - images, text, audio, depth, thermal, and IMU data. It enables novel emergent applications ‘out-of-the-box’ including cross-modal retrieval, composing modalities with arithmetic, cross-modal detection and generation. - - - -![ImageBind](https://user-images.githubusercontent.com/8495451/236859695-ffa13364-3e39-4d99-a8da-fbfab17f9a6b.gif) - -## ImageBind model - -Emergent zero-shot classification performance. - - - - - - - - - - - - - - - - - - - - - - - -
ModelIN1kK400NYU-DESCLLVIPEgo4Ddownload
imagebind_huge77.750.054.066.963.425.0checkpoint
- -## Usage - -Install pytorch 1.13+ and other 3rd party dependencies. - -```shell -conda create --name imagebind python=3.8 -y -conda activate imagebind - -pip install -r requirements.txt -``` - -For windows users, you might need to install `soundfile` for reading/writing audio files. (Thanks @congyue1977) - -``` -pip install soundfile -``` - - -Extract and compare features across modalities (e.g. Image, Text and Audio). - -```python -import data -import torch -from models import imagebind_model -from models.imagebind_model import ModalityType - -text_list=["A dog.", "A car", "A bird"] -image_paths=[".assets/dog_image.jpg", ".assets/car_image.jpg", ".assets/bird_image.jpg"] -audio_paths=[".assets/dog_audio.wav", ".assets/car_audio.wav", ".assets/bird_audio.wav"] - -device = "cuda:0" if torch.cuda.is_available() else "cpu" - -# Instantiate model -model = imagebind_model.imagebind_huge(pretrained=True) -model.eval() -model.to(device) - -# Load data -inputs = { - ModalityType.TEXT: data.load_and_transform_text(text_list, device), - ModalityType.VISION: data.load_and_transform_vision_data(image_paths, device), - ModalityType.AUDIO: data.load_and_transform_audio_data(audio_paths, device), -} - -with torch.no_grad(): - embeddings = model(inputs) - -print( - "Vision x Text: ", - torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.TEXT].T, dim=-1), -) -print( - "Audio x Text: ", - torch.softmax(embeddings[ModalityType.AUDIO] @ embeddings[ModalityType.TEXT].T, dim=-1), -) -print( - "Vision x Audio: ", - torch.softmax(embeddings[ModalityType.VISION] @ embeddings[ModalityType.AUDIO].T, dim=-1), -) - -# Expected output: -# -# Vision x Text: -# tensor([[9.9761e-01, 2.3694e-03, 1.8612e-05], -# [3.3836e-05, 9.9994e-01, 2.4118e-05], -# [4.7997e-05, 1.3496e-02, 9.8646e-01]]) -# -# Audio x Text: -# tensor([[1., 0., 0.], -# [0., 1., 0.], -# [0., 0., 1.]]) -# -# Vision x Audio: -# tensor([[0.8070, 0.1088, 0.0842], -# [0.1036, 0.7884, 0.1079], -# [0.0018, 0.0022, 0.9960]]) - -``` - -## Model card -Please see the [model card](model_card.md) for details. - -## License - -ImageBind code and model weights are released under the CC-BY-NC 4.0 license. See [LICENSE](LICENSE) for additional details. - -## Contributing - -See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md). - -## Citing ImageBind - -If you find this repository useful, please consider giving a star :star: and citation - -``` -@inproceedings{girdhar2023imagebind, - title={ImageBind: One Embedding Space To Bind Them All}, - author={Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang -and Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan}, - booktitle={CVPR}, - year={2023} -} -``` diff --git a/sonique/Video_LLaMA/video_llama/models/ImageBind/bpe/bpe_simple_vocab_16e6.txt.gz b/sonique/Video_LLaMA/video_llama/models/ImageBind/bpe/bpe_simple_vocab_16e6.txt.gz deleted file mode 100644 index 36a15856e00a06a9fbed8cdd34d2393fea4a3113..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/ImageBind/bpe/bpe_simple_vocab_16e6.txt.gz +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a -size 1356917 diff --git a/sonique/Video_LLaMA/video_llama/models/ImageBind/data.py b/sonique/Video_LLaMA/video_llama/models/ImageBind/data.py deleted file mode 100644 index 993ff696bd98f1b380f2e9537b3f70ca38501f22..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/ImageBind/data.py +++ /dev/null @@ -1,338 +0,0 @@ -#!/usr/bin/env python3 -# Portions Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. - -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -import logging -import math - -import torch -import torch.nn as nn -import torchaudio -from PIL import Image -from pytorchvideo import transforms as pv_transforms -from pytorchvideo.data.clip_sampling import ConstantClipsPerVideoSampler -from pytorchvideo.data.encoded_video import EncodedVideo -from torchvision import transforms -from torchvision.transforms._transforms_video import NormalizeVideo - -from .models.multimodal_preprocessors import SimpleTokenizer - -DEFAULT_AUDIO_FRAME_SHIFT_MS = 10 # in milliseconds - -BPE_PATH = "bpe/bpe_simple_vocab_16e6.txt.gz" - - -def waveform2melspec(waveform, sample_rate, num_mel_bins, target_length): - # Based on https://github.com/YuanGongND/ast/blob/d7d8b4b8e06cdaeb6c843cdb38794c1c7692234c/src/dataloader.py#L102 - waveform -= waveform.mean() - fbank = torchaudio.compliance.kaldi.fbank( - waveform, - htk_compat=True, - sample_frequency=sample_rate, - use_energy=False, - window_type="hanning", - num_mel_bins=num_mel_bins, - dither=0.0, - frame_length=25, - frame_shift=DEFAULT_AUDIO_FRAME_SHIFT_MS, - ) - # Convert to [mel_bins, num_frames] shape - fbank = fbank.transpose(0, 1) - # Pad to target_length - n_frames = fbank.size(1) - p = target_length - n_frames - # if p is too large (say >20%), flash a warning - if abs(p) / n_frames > 0.2: - logging.warning( - "Large gap between audio n_frames(%d) and " - "target_length (%d). Is the audio_target_length " - "setting correct?", - n_frames, - target_length, - ) - # cut and pad - if p > 0: - fbank = torch.nn.functional.pad(fbank, (0, p), mode="constant", value=0) - elif p < 0: - fbank = fbank[:, 0:target_length] - # Convert to [1, mel_bins, num_frames] shape, essentially like a 1 - # channel image - fbank = fbank.unsqueeze(0) - return fbank - - -def get_clip_timepoints(clip_sampler, duration): - # Read out all clips in this video - all_clips_timepoints = [] - is_last_clip = False - end = 0.0 - while not is_last_clip: - start, end, _, _, is_last_clip = clip_sampler(end, duration, annotation=None) - all_clips_timepoints.append((start, end)) - return all_clips_timepoints - - -def load_and_transform_vision_data(image_paths, device): - if image_paths is None: - return None - - image_ouputs = [] - for image_path in image_paths: - data_transform = transforms.Compose( - [ - transforms.Resize( - 224, interpolation=transforms.InterpolationMode.BICUBIC - ), - transforms.CenterCrop(224), - transforms.ToTensor(), - transforms.Normalize( - mean=(0.48145466, 0.4578275, 0.40821073), - std=(0.26862954, 0.26130258, 0.27577711), - ), - ] - ) - with open(image_path, "rb") as fopen: - image = Image.open(fopen).convert("RGB") - - image = data_transform(image).to(device) - image_ouputs.append(image) - return torch.stack(image_ouputs, dim=0) - - -def load_and_transform_text(text, device): - if text is None: - return None - tokenizer = SimpleTokenizer(bpe_path=BPE_PATH) - tokens = [tokenizer(t).unsqueeze(0).to(device) for t in text] - tokens = torch.cat(tokens, dim=0) - return tokens - - -def load_and_transform_audio_data( - audio_paths, - device, - num_mel_bins=128, - target_length=204, - sample_rate=16000, - clip_duration=2, - clips_per_video=3, - mean=-4.268, - std=9.138, -): - if audio_paths is None: - return None - - audio_outputs = [] - clip_sampler = ConstantClipsPerVideoSampler( - clip_duration=clip_duration, clips_per_video=clips_per_video - ) - - for audio_path in audio_paths: - waveform, sr = torchaudio.load(audio_path) - if sample_rate != sr: - waveform = torchaudio.functional.resample( - waveform, orig_freq=sr, new_freq=sample_rate - ) - all_clips_timepoints = get_clip_timepoints( - clip_sampler, waveform.size(1) / sample_rate - ) - all_clips = [] - for clip_timepoints in all_clips_timepoints: - waveform_clip = waveform[ - :, - int(clip_timepoints[0] * sample_rate) : int( - clip_timepoints[1] * sample_rate - ), - ] - waveform_melspec = waveform2melspec( - waveform_clip, sample_rate, num_mel_bins, target_length - ) - all_clips.append(waveform_melspec) - - normalize = transforms.Normalize(mean=mean, std=std) - all_clips = [normalize(ac).to(device) for ac in all_clips] - - all_clips = torch.stack(all_clips, dim=0) - audio_outputs.append(all_clips) - - return torch.stack(audio_outputs, dim=0) - - -def crop_boxes(boxes, x_offset, y_offset): - """ - Perform crop on the bounding boxes given the offsets. - Args: - boxes (ndarray or None): bounding boxes to perform crop. The dimension - is `num boxes` x 4. - x_offset (int): cropping offset in the x axis. - y_offset (int): cropping offset in the y axis. - Returns: - cropped_boxes (ndarray or None): the cropped boxes with dimension of - `num boxes` x 4. - """ - cropped_boxes = boxes.copy() - cropped_boxes[:, [0, 2]] = boxes[:, [0, 2]] - x_offset - cropped_boxes[:, [1, 3]] = boxes[:, [1, 3]] - y_offset - - return cropped_boxes - - -def uniform_crop(images, size, spatial_idx, boxes=None, scale_size=None): - """ - Perform uniform spatial sampling on the images and corresponding boxes. - Args: - images (tensor): images to perform uniform crop. The dimension is - `num frames` x `channel` x `height` x `width`. - size (int): size of height and weight to crop the images. - spatial_idx (int): 0, 1, or 2 for left, center, and right crop if width - is larger than height. Or 0, 1, or 2 for top, center, and bottom - crop if height is larger than width. - boxes (ndarray or None): optional. Corresponding boxes to images. - Dimension is `num boxes` x 4. - scale_size (int): optinal. If not None, resize the images to scale_size before - performing any crop. - Returns: - cropped (tensor): images with dimension of - `num frames` x `channel` x `size` x `size`. - cropped_boxes (ndarray or None): the cropped boxes with dimension of - `num boxes` x 4. - """ - assert spatial_idx in [0, 1, 2] - ndim = len(images.shape) - if ndim == 3: - images = images.unsqueeze(0) - height = images.shape[2] - width = images.shape[3] - - if scale_size is not None: - if width <= height: - width, height = scale_size, int(height / width * scale_size) - else: - width, height = int(width / height * scale_size), scale_size - images = torch.nn.functional.interpolate( - images, - size=(height, width), - mode="bilinear", - align_corners=False, - ) - - y_offset = int(math.ceil((height - size) / 2)) - x_offset = int(math.ceil((width - size) / 2)) - - if height > width: - if spatial_idx == 0: - y_offset = 0 - elif spatial_idx == 2: - y_offset = height - size - else: - if spatial_idx == 0: - x_offset = 0 - elif spatial_idx == 2: - x_offset = width - size - cropped = images[:, :, y_offset : y_offset + size, x_offset : x_offset + size] - cropped_boxes = crop_boxes(boxes, x_offset, y_offset) if boxes is not None else None - if ndim == 3: - cropped = cropped.squeeze(0) - return cropped, cropped_boxes - - -class SpatialCrop(nn.Module): - """ - Convert the video into 3 smaller clips spatially. Must be used after the - temporal crops to get spatial crops, and should be used with - -2 in the spatial crop at the slowfast augmentation stage (so full - frames are passed in here). Will return a larger list with the - 3x spatial crops as well. - """ - - def __init__(self, crop_size: int = 224, num_crops: int = 3): - super().__init__() - self.crop_size = crop_size - if num_crops == 3: - self.crops_to_ext = [0, 1, 2] - self.flipped_crops_to_ext = [] - elif num_crops == 1: - self.crops_to_ext = [1] - self.flipped_crops_to_ext = [] - else: - raise NotImplementedError("Nothing else supported yet") - - def forward(self, videos): - """ - Args: - videos: A list of C, T, H, W videos. - Returns: - videos: A list with 3x the number of elements. Each video converted - to C, T, H', W' by spatial cropping. - """ - assert isinstance(videos, list), "Must be a list of videos after temporal crops" - assert all([video.ndim == 4 for video in videos]), "Must be (C,T,H,W)" - res = [] - for video in videos: - for spatial_idx in self.crops_to_ext: - res.append(uniform_crop(video, self.crop_size, spatial_idx)[0]) - if not self.flipped_crops_to_ext: - continue - flipped_video = transforms.functional.hflip(video) - for spatial_idx in self.flipped_crops_to_ext: - res.append(uniform_crop(flipped_video, self.crop_size, spatial_idx)[0]) - return res - - -def load_and_transform_video_data( - video_paths, - device, - clip_duration=2, - clips_per_video=5, - sample_rate=16000, -): - if video_paths is None: - return None - - video_outputs = [] - video_transform = transforms.Compose( - [ - pv_transforms.ShortSideScale(224), - NormalizeVideo( - mean=(0.48145466, 0.4578275, 0.40821073), - std=(0.26862954, 0.26130258, 0.27577711), - ), - ] - ) - - clip_sampler = ConstantClipsPerVideoSampler( - clip_duration=clip_duration, clips_per_video=clips_per_video - ) - frame_sampler = pv_transforms.UniformTemporalSubsample(num_samples=clip_duration) - - for video_path in video_paths: - video = EncodedVideo.from_path( - video_path, - decoder="decord", - decode_audio=False, - **{"sample_rate": sample_rate}, - ) - - all_clips_timepoints = get_clip_timepoints(clip_sampler, video.duration) - - all_video = [] - for clip_timepoints in all_clips_timepoints: - # Read the clip, get frames - clip = video.get_clip(clip_timepoints[0], clip_timepoints[1]) - if clip is None: - raise ValueError("No clip found") - video_clip = frame_sampler(clip["video"]) - video_clip = video_clip / 255.0 # since this is float, need 0-1 - - all_video.append(video_clip) - - all_video = [video_transform(clip) for clip in all_video] - all_video = SpatialCrop(224, num_crops=3)(all_video) - - all_video = torch.stack(all_video, dim=0) - video_outputs.append(all_video) - - return torch.stack(video_outputs, dim=0).to(device) diff --git a/sonique/Video_LLaMA/video_llama/models/ImageBind/model_card.md b/sonique/Video_LLaMA/video_llama/models/ImageBind/model_card.md deleted file mode 100644 index c7bb26500b6590b64ffa6350f37be80dc88612d8..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/ImageBind/model_card.md +++ /dev/null @@ -1,94 +0,0 @@ -# Model Card for ImageBind - -Multimodal joint embedding model for image/video, text, audio, depth, IMU, and thermal images. -Input any of the six modalities and get the same sized embedding that can be used for cross-modal and multimodal tasks. - -# Model Details - -## Model Description - - -Multimodal joint embedding model for image/video, text, audio, depth, IMU, and thermal images - -- **Developed by:** Meta AI -- **Model type:** Multimodal model -- **Language(s) (NLP):** en -- **License:** CC BY-NC-SA 4.0 -- **Resources for more information:** - - [GitHub Repo](https://github.com/facebookresearch/ImageBind) - - -# Uses - - -This model is intended only for research purposes. It provides a joint embedding space for different modalities -- image/video, text, audio, depth, IMU and thermal images. -We hope that these joint embeddings can be used for a variety of different cross-modal research, e.g., cross-modal retrieval and combining embeddings from different modalities. - -## Out-of-Scope Use - - - - -This model is *NOT* intended to be used in any real world application -- commercial or otherwise. -It may produce harmful associations with different inputs. -The model needs to be investigated and likely re-trained on specific data for any such application. -The model is expected to work better on web-based visual data since it was trained on such data. -The text encoder is likely to work only on English language text because of the underlying training datasets. - -# Bias, Risks, and Limitations - - -Open-domain joint embedding models are prone to producing specific biases, e.g., study from [CLIP](https://github.com/openai/CLIP/blob/main/model-card.md#bias-and-fairness). -Since our model uses such models as initialization, it will exhibit such biases too. -Moreover, for learning joint embeddings for other modalities such as audio, thermal, depth, and IMU we leverage datasets that are relatively small. These joint embeddings are thus limited to the concepts present in the datasets. For example, the thermal datasets we used are limited to outdoor street scenes, while the depth datasets are limited to indoor scenes. - - - -# Training Details - -## Training Data - - - -ImageBind uses image-paired data for training -- (image, X) where X is one of text, audio, depth, IMU or thermal data. -In particular, we initialize and freeze the image and text encoders using an OpenCLIP ViT-H encoder. -We train audio embeddings using Audioset, depth embeddings using the SUN RGB-D dataset, IMU using the Ego4D dataset and thermal embeddings using the LLVIP dataset. -We provide the exact training data details in the paper. - - -## Training Procedure - - -Please refer to the research paper and github repo for exact details on this. - -# Evaluation - -## Testing Data, Factors & Metrics - -We evaluate the model on a variety of different classification benchmarks for each modality. -The evaluation details are presented in the paper. -The models performance is measured using standard classification metrics such as accuracy and mAP. - -# Citation - - - -**BibTeX:** -``` -@inproceedings{girdhar2023imagebind, - title={ImageBind: One Embedding Space To Bind Them All}, - author={Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang -and Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan}, - booktitle={CVPR}, - year={2023} -} -``` - - -# Model Card Contact - -Please reach out to the authors at: rgirdhar@meta.com imisra@meta.com alaaelnouby@gmail.com - -# How to Get Started with the Model - -Our github repo provides a simple example to extract embeddings from images, audio etc. diff --git a/sonique/Video_LLaMA/video_llama/models/ImageBind/models/__init__.py b/sonique/Video_LLaMA/video_llama/models/ImageBind/models/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/sonique/Video_LLaMA/video_llama/models/ImageBind/models/helpers.py b/sonique/Video_LLaMA/video_llama/models/ImageBind/models/helpers.py deleted file mode 100644 index 71abe9b1fc32ed22ba46ea89ae7439d4ea49afca..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/ImageBind/models/helpers.py +++ /dev/null @@ -1,140 +0,0 @@ -#!/usr/bin/env python3 -# Portions Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. - -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - - -import einops -import numpy as np -import torch -import torch.nn as nn - - -class Normalize(nn.Module): - def __init__(self, dim: int) -> None: - super().__init__() - self.dim = dim - - def forward(self, x): - return torch.nn.functional.normalize(x, dim=self.dim, p=2) - - -class LearnableLogitScaling(nn.Module): - def __init__( - self, - logit_scale_init: float = 1 / 0.07, - learnable: bool = True, - max_logit_scale: float = 100, - ) -> None: - super().__init__() - self.max_logit_scale = max_logit_scale - self.logit_scale_init = logit_scale_init - self.learnable = learnable - log_logit_scale = torch.ones([]) * np.log(self.logit_scale_init) - if learnable: - self.log_logit_scale = nn.Parameter(log_logit_scale) - else: - self.register_buffer("log_logit_scale", log_logit_scale) - - def forward(self, x): - return torch.clip(self.log_logit_scale.exp(), max=self.max_logit_scale) * x - - def extra_repr(self): - st = f"logit_scale_init={self.logit_scale_init},learnable={self.learnable}," \ - f" max_logit_scale={self.max_logit_scale}" - return st - - -class EinOpsRearrange(nn.Module): - def __init__(self, rearrange_expr: str, **kwargs) -> None: - super().__init__() - self.rearrange_expr = rearrange_expr - self.kwargs = kwargs - - def forward(self, x): - assert isinstance(x, torch.Tensor) - return einops.rearrange(x, self.rearrange_expr, **self.kwargs) - - -class VerboseNNModule(nn.Module): - """ - Wrapper around nn.Module that prints registered buffers and parameter names. - """ - - @staticmethod - def get_readable_tensor_repr(name: str, tensor: torch.Tensor) -> str: - st = ( - "(" - + name - + "): " - + "tensor(" - + str(tuple(tensor[1].shape)) - + ", requires_grad=" - + str(tensor[1].requires_grad) - + ")\n" - ) - return st - - def extra_repr(self) -> str: - named_modules = set() - for p in self.named_modules(): - named_modules.update([p[0]]) - named_modules = list(named_modules) - - string_repr = "" - for p in self.named_parameters(): - name = p[0].split(".")[0] - if name not in named_modules: - string_repr += self.get_readable_tensor_repr(name, p) - - for p in self.named_buffers(): - name = p[0].split(".")[0] - string_repr += self.get_readable_tensor_repr(name, p) - - return string_repr - - -def cast_if_src_dtype( - tensor: torch.Tensor, src_dtype: torch.dtype, tgt_dtype: torch.dtype -): - updated = False - if tensor.dtype == src_dtype: - tensor = tensor.to(dtype=tgt_dtype) - updated = True - return tensor, updated - - -class QuickGELU(nn.Module): - # From https://github.com/openai/CLIP/blob/d50d76daa670286dd6cacf3bcd80b5e4823fc8e1/clip/model.py#L166 - def forward(self, x: torch.Tensor): - return x * torch.sigmoid(1.702 * x) - - -class SelectElement(nn.Module): - def __init__(self, index) -> None: - super().__init__() - self.index = index - - def forward(self, x): - assert x.ndim >= 3 - return x[:, self.index, ...] - - -class SelectEOSAndProject(nn.Module): - """ - Text Pooling used in OpenCLIP - """ - - def __init__(self, proj: nn.Module) -> None: - super().__init__() - self.proj = proj - - def forward(self, x, seq_len): - assert x.ndim == 3 - # x is of shape B x L x D - # take features from the eot embedding (eot_token is the highest number in each sequence) - x = x[torch.arange(x.shape[0]), seq_len] - x = self.proj(x) - return x diff --git a/sonique/Video_LLaMA/video_llama/models/ImageBind/models/imagebind_model.py b/sonique/Video_LLaMA/video_llama/models/ImageBind/models/imagebind_model.py deleted file mode 100644 index 4430d2ea7a0acb19ca0bdf16dfebfc252164cccd..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/ImageBind/models/imagebind_model.py +++ /dev/null @@ -1,541 +0,0 @@ -#!/usr/bin/env python3 -# Portions Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. - -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - - -import os -from functools import partial -from types import SimpleNamespace - -import torch -import torch.nn as nn - -from .helpers import (EinOpsRearrange, LearnableLogitScaling, Normalize, - SelectElement, SelectEOSAndProject) -from .multimodal_preprocessors import (AudioPreprocessor, - IMUPreprocessor, PadIm2Video, - PatchEmbedGeneric, - RGBDTPreprocessor, - SpatioTemporalPosEmbeddingHelper, - TextPreprocessor, - ThermalPreprocessor) -from .transformer import MultiheadAttention, SimpleTransformer - -ModalityType = SimpleNamespace( - VISION="vision", - TEXT="text", - AUDIO="audio", - THERMAL="thermal", - DEPTH="depth", - IMU="imu", -) - - -class ImageBindModel(nn.Module): - def __init__( - self, - video_frames=2, - kernel_size=(2, 14, 14), - audio_kernel_size=16, - audio_stride=10, - out_embed_dim=768, - vision_embed_dim=1024, - vision_num_blocks=24, - vision_num_heads=16, - audio_embed_dim=768, - audio_num_blocks=12, - audio_num_heads=12, - audio_num_mel_bins=128, - audio_target_len=204, - audio_drop_path=0.1, - text_embed_dim=768, - text_num_blocks=12, - text_num_heads=12, - depth_embed_dim=384, - depth_kernel_size=16, - depth_num_blocks=12, - depth_num_heads=8, - depth_drop_path=0.0, - thermal_embed_dim=768, - thermal_kernel_size=16, - thermal_num_blocks=12, - thermal_num_heads=12, - thermal_drop_path=0.0, - imu_embed_dim=512, - imu_kernel_size=8, - imu_num_blocks=6, - imu_num_heads=8, - imu_drop_path=0.7, - ): - super().__init__() - - self.modality_preprocessors = self._create_modality_preprocessors( - video_frames, - vision_embed_dim, - kernel_size, - text_embed_dim, - audio_embed_dim, - audio_kernel_size, - audio_stride, - audio_num_mel_bins, - audio_target_len, - depth_embed_dim, - depth_kernel_size, - thermal_embed_dim, - thermal_kernel_size, - imu_embed_dim, - ) - - self.modality_trunks = self._create_modality_trunks( - vision_embed_dim, - vision_num_blocks, - vision_num_heads, - text_embed_dim, - text_num_blocks, - text_num_heads, - audio_embed_dim, - audio_num_blocks, - audio_num_heads, - audio_drop_path, - depth_embed_dim, - depth_num_blocks, - depth_num_heads, - depth_drop_path, - thermal_embed_dim, - thermal_num_blocks, - thermal_num_heads, - thermal_drop_path, - imu_embed_dim, - imu_num_blocks, - imu_num_heads, - imu_drop_path, - ) - - self.modality_heads = self._create_modality_heads( - out_embed_dim, - vision_embed_dim, - text_embed_dim, - audio_embed_dim, - depth_embed_dim, - thermal_embed_dim, - imu_embed_dim, - ) - - self.modality_postprocessors = self._create_modality_postprocessors( - out_embed_dim - ) - - def _create_modality_preprocessors( - self, - video_frames=2, - vision_embed_dim=1024, - kernel_size=(2, 14, 14), - text_embed_dim=768, - audio_embed_dim=768, - audio_kernel_size=16, - audio_stride=10, - audio_num_mel_bins=128, - audio_target_len=204, - depth_embed_dim=768, - depth_kernel_size=16, - thermal_embed_dim=768, - thermal_kernel_size=16, - imu_embed_dim=512, - ): - rgbt_stem = PatchEmbedGeneric( - proj_stem=[ - PadIm2Video(pad_type="repeat", ntimes=2), - nn.Conv3d( - in_channels=3, - kernel_size=kernel_size, - out_channels=vision_embed_dim, - stride=kernel_size, - bias=False, - ), - ] - ) - rgbt_preprocessor = RGBDTPreprocessor( - img_size=[3, video_frames, 224, 224], - num_cls_tokens=1, - pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True), - rgbt_stem=rgbt_stem, - depth_stem=None, - ) - - text_preprocessor = TextPreprocessor( - context_length=77, - vocab_size=49408, - embed_dim=text_embed_dim, - causal_masking=True, - ) - - audio_stem = PatchEmbedGeneric( - proj_stem=[ - nn.Conv2d( - in_channels=1, - kernel_size=audio_kernel_size, - stride=audio_stride, - out_channels=audio_embed_dim, - bias=False, - ), - ], - norm_layer=nn.LayerNorm(normalized_shape=audio_embed_dim), - ) - audio_preprocessor = AudioPreprocessor( - img_size=[1, audio_num_mel_bins, audio_target_len], - num_cls_tokens=1, - pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True), - audio_stem=audio_stem, - ) - - depth_stem = PatchEmbedGeneric( - [ - nn.Conv2d( - kernel_size=depth_kernel_size, - in_channels=1, - out_channels=depth_embed_dim, - stride=depth_kernel_size, - bias=False, - ), - ], - norm_layer=nn.LayerNorm(normalized_shape=depth_embed_dim), - ) - - depth_preprocessor = RGBDTPreprocessor( - img_size=[1, 224, 224], - num_cls_tokens=1, - pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True), - rgbt_stem=None, - depth_stem=depth_stem, - ) - - thermal_stem = PatchEmbedGeneric( - [ - nn.Conv2d( - kernel_size=thermal_kernel_size, - in_channels=1, - out_channels=thermal_embed_dim, - stride=thermal_kernel_size, - bias=False, - ), - ], - norm_layer=nn.LayerNorm(normalized_shape=thermal_embed_dim), - ) - thermal_preprocessor = ThermalPreprocessor( - img_size=[1, 224, 224], - num_cls_tokens=1, - pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True), - thermal_stem=thermal_stem, - ) - - imu_stem = PatchEmbedGeneric( - [ - nn.Linear( - in_features=48, - out_features=imu_embed_dim, - bias=False, - ), - ], - norm_layer=nn.LayerNorm(normalized_shape=imu_embed_dim), - ) - - imu_preprocessor = IMUPreprocessor( - img_size=[6, 2000], - num_cls_tokens=1, - kernel_size=8, - embed_dim=imu_embed_dim, - pos_embed_fn=partial(SpatioTemporalPosEmbeddingHelper, learnable=True), - imu_stem=imu_stem, - ) - - modality_preprocessors = { - ModalityType.VISION: rgbt_preprocessor, - ModalityType.TEXT: text_preprocessor, - ModalityType.AUDIO: audio_preprocessor, - ModalityType.DEPTH: depth_preprocessor, - ModalityType.THERMAL: thermal_preprocessor, - ModalityType.IMU: imu_preprocessor, - } - - return nn.ModuleDict(modality_preprocessors) - - def _create_modality_trunks( - self, - vision_embed_dim=1024, - vision_num_blocks=24, - vision_num_heads=16, - text_embed_dim=768, - text_num_blocks=12, - text_num_heads=12, - audio_embed_dim=768, - audio_num_blocks=12, - audio_num_heads=12, - audio_drop_path=0.0, - depth_embed_dim=768, - depth_num_blocks=12, - depth_num_heads=12, - depth_drop_path=0.0, - thermal_embed_dim=768, - thermal_num_blocks=12, - thermal_num_heads=12, - thermal_drop_path=0.0, - imu_embed_dim=512, - imu_num_blocks=6, - imu_num_heads=8, - imu_drop_path=0.7, - ): - def instantiate_trunk( - embed_dim, num_blocks, num_heads, pre_transformer_ln, add_bias_kv, drop_path - ): - return SimpleTransformer( - embed_dim=embed_dim, - num_blocks=num_blocks, - ffn_dropout_rate=0.0, - drop_path_rate=drop_path, - attn_target=partial( - MultiheadAttention, - embed_dim=embed_dim, - num_heads=num_heads, - bias=True, - add_bias_kv=add_bias_kv, - ), - pre_transformer_layer=nn.Sequential( - nn.LayerNorm(embed_dim, eps=1e-6) - if pre_transformer_ln - else nn.Identity(), - EinOpsRearrange("b l d -> l b d"), - ), - post_transformer_layer=EinOpsRearrange("l b d -> b l d"), - ) - - modality_trunks = {} - modality_trunks[ModalityType.VISION] = instantiate_trunk( - vision_embed_dim, - vision_num_blocks, - vision_num_heads, - pre_transformer_ln=True, - add_bias_kv=False, - drop_path=0.0, - ) - modality_trunks[ModalityType.TEXT] = instantiate_trunk( - text_embed_dim, - text_num_blocks, - text_num_heads, - pre_transformer_ln=False, - add_bias_kv=False, - drop_path=0.0, - ) - modality_trunks[ModalityType.AUDIO] = instantiate_trunk( - audio_embed_dim, - audio_num_blocks, - audio_num_heads, - pre_transformer_ln=False, - add_bias_kv=True, - drop_path=audio_drop_path, - ) - modality_trunks[ModalityType.DEPTH] = instantiate_trunk( - depth_embed_dim, - depth_num_blocks, - depth_num_heads, - pre_transformer_ln=False, - add_bias_kv=True, - drop_path=depth_drop_path, - ) - modality_trunks[ModalityType.THERMAL] = instantiate_trunk( - thermal_embed_dim, - thermal_num_blocks, - thermal_num_heads, - pre_transformer_ln=False, - add_bias_kv=True, - drop_path=thermal_drop_path, - ) - modality_trunks[ModalityType.IMU] = instantiate_trunk( - imu_embed_dim, - imu_num_blocks, - imu_num_heads, - pre_transformer_ln=False, - add_bias_kv=True, - drop_path=imu_drop_path, - ) - - return nn.ModuleDict(modality_trunks) - - def _create_modality_heads( - self, - out_embed_dim, - vision_embed_dim, - text_embed_dim, - audio_embed_dim, - depth_embed_dim, - thermal_embed_dim, - imu_embed_dim, - ): - modality_heads = {} - - modality_heads[ModalityType.VISION] = nn.Sequential( - nn.LayerNorm(normalized_shape=vision_embed_dim, eps=1e-6), - SelectElement(index=0), - nn.Linear(vision_embed_dim, out_embed_dim, bias=False), - ) - - modality_heads[ModalityType.TEXT] = SelectEOSAndProject( - proj=nn.Sequential( - nn.LayerNorm(normalized_shape=text_embed_dim, eps=1e-6), - nn.Linear(text_embed_dim, out_embed_dim, bias=False), - ) - ) - - modality_heads[ModalityType.AUDIO] = nn.Sequential( - nn.LayerNorm(normalized_shape=audio_embed_dim, eps=1e-6), - SelectElement(index=0), - nn.Linear(audio_embed_dim, out_embed_dim, bias=False), - ) - - modality_heads[ModalityType.DEPTH] = nn.Sequential( - nn.LayerNorm(normalized_shape=depth_embed_dim, eps=1e-6), - SelectElement(index=0), - nn.Linear(depth_embed_dim, out_embed_dim, bias=False), - ) - - modality_heads[ModalityType.THERMAL] = nn.Sequential( - nn.LayerNorm(normalized_shape=thermal_embed_dim, eps=1e-6), - SelectElement(index=0), - nn.Linear(thermal_embed_dim, out_embed_dim, bias=False), - ) - - modality_heads[ModalityType.IMU] = nn.Sequential( - nn.LayerNorm(normalized_shape=imu_embed_dim, eps=1e-6), - SelectElement(index=0), - nn.Dropout(p=0.5), - nn.Linear(imu_embed_dim, out_embed_dim, bias=False), - ) - - return nn.ModuleDict(modality_heads) - - def _create_modality_postprocessors(self, out_embed_dim): - modality_postprocessors = {} - - modality_postprocessors[ModalityType.VISION] = Normalize(dim=-1) - modality_postprocessors[ModalityType.TEXT] = nn.Sequential( - Normalize(dim=-1), LearnableLogitScaling(learnable=True) - ) - modality_postprocessors[ModalityType.AUDIO] = nn.Sequential( - Normalize(dim=-1), - LearnableLogitScaling(logit_scale_init=20.0, learnable=False), - ) - modality_postprocessors[ModalityType.DEPTH] = nn.Sequential( - Normalize(dim=-1), - LearnableLogitScaling(logit_scale_init=5.0, learnable=False), - ) - modality_postprocessors[ModalityType.THERMAL] = nn.Sequential( - Normalize(dim=-1), - LearnableLogitScaling(logit_scale_init=10.0, learnable=False), - ) - modality_postprocessors[ModalityType.IMU] = nn.Sequential( - Normalize(dim=-1), - LearnableLogitScaling(logit_scale_init=5.0, learnable=False), - ) - - return nn.ModuleDict(modality_postprocessors) - - def forward(self, inputs): - outputs = {} - for modality_key, modality_value in inputs.items(): - reduce_list = ( - modality_value.ndim >= 5 - ) # Audio and Video inputs consist of multiple clips - if reduce_list: - B, S = modality_value.shape[:2] - modality_value = modality_value.reshape( - B * S, *modality_value.shape[2:] - ) - - if modality_value is not None: - modality_value = self.modality_preprocessors[modality_key]( - **{modality_key: modality_value} - ) - trunk_inputs = modality_value["trunk"] - head_inputs = modality_value["head"] - modality_value = self.modality_trunks[modality_key](**trunk_inputs) - modality_value = self.modality_heads[modality_key]( - modality_value, **head_inputs - ) - modality_value = self.modality_postprocessors[modality_key]( - modality_value - ) - - if reduce_list: - modality_value = modality_value.reshape(B, S, -1) - modality_value = modality_value.mean(dim=1) - - outputs[modality_key] = modality_value - # modality_heads normalize 后768->linear 1024 -> - return outputs - def get_audio_feature(self, inputs, modality_type): - modality_value = inputs - modality_key = modality_type - reduce_list = ( - modality_value.ndim >= 5 - ) # Audio and Video inputs consist of multiple clips - if reduce_list: - B, S = modality_value.shape[:2] - modality_value = modality_value.reshape( - B * S, *modality_value.shape[2:] - ) - - if modality_value is not None: - modality_value = self.modality_preprocessors[modality_key]( - **{modality_key: modality_value} - ) - trunk_inputs = modality_value["trunk"] - head_inputs = modality_value["head"] - modality_value = self.modality_trunks[modality_key](**trunk_inputs) - - audio_feature = self.modality_heads[modality_key][:-1]( - modality_value, **head_inputs - ) - modality_value = self.modality_heads[modality_key][-1:]( - audio_feature, **head_inputs - ) - modality_value = self.modality_postprocessors[modality_key]( - modality_value - ) - - if reduce_list: - audio_feature = audio_feature.reshape(B, S, -1) - modality_value = modality_value.reshape(B, S, -1) - # modality_heads - return audio_feature, modality_value - - -def imagebind_huge(pretrained=False): - model = ImageBindModel( - vision_embed_dim=1280, - vision_num_blocks=32, - vision_num_heads=16, - text_embed_dim=1024, - text_num_blocks=24, - text_num_heads=16, - out_embed_dim=1024, - audio_drop_path=0.1, - imu_drop_path=0.7, - ) - - if pretrained: - if not os.path.exists(".checkpoints/imagebind_huge.pth"): - print( - "Downloading imagebind weights to .checkpoints/imagebind_huge.pth ..." - ) - os.makedirs(".checkpoints", exist_ok=True) - torch.hub.download_url_to_file( - "https://dl.fbaipublicfiles.com/imagebind/imagebind_huge.pth", - ".checkpoints/imagebind_huge.pth", - progress=True, - ) - - model.load_state_dict(torch.load(".checkpoints/imagebind_huge.pth")) - - return model,1024 diff --git a/sonique/Video_LLaMA/video_llama/models/ImageBind/models/multimodal_preprocessors.py b/sonique/Video_LLaMA/video_llama/models/ImageBind/models/multimodal_preprocessors.py deleted file mode 100644 index 768c5b9c4f3f9b17b04ee41fec7ca2d99c15335e..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/ImageBind/models/multimodal_preprocessors.py +++ /dev/null @@ -1,685 +0,0 @@ -#!/usr/bin/env python3 -# Portions Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. - -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -import gzip -import html -import io -import math -from functools import lru_cache -from typing import Callable, List, Optional, Tuple - -import ftfy -import numpy as np -import regex as re -import torch -import torch.nn as nn -from iopath.common.file_io import g_pathmgr -from timm.models.layers import trunc_normal_ - -from .helpers import VerboseNNModule, cast_if_src_dtype - - -def get_sinusoid_encoding_table(n_position, d_hid): - """Sinusoid position encoding table""" - - # TODO: make it with torch instead of numpy - def get_position_angle_vec(position): - return [ - position / np.power(10000, 2 * (hid_j // 2) / d_hid) - for hid_j in range(d_hid) - ] - - sinusoid_table = np.array( - [get_position_angle_vec(pos_i) for pos_i in range(n_position)] - ) - sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i - sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1 - - return torch.FloatTensor(sinusoid_table).unsqueeze(0) - - -def interpolate_pos_encoding_2d(target_spatial_size, pos_embed): - N = pos_embed.shape[1] - if N == target_spatial_size: - return pos_embed - dim = pos_embed.shape[-1] - # nn.functional.interpolate doesn't work with bfloat16 so we cast to float32 - pos_embed, updated = cast_if_src_dtype(pos_embed, torch.bfloat16, torch.float32) - pos_embed = nn.functional.interpolate( - pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute( - 0, 3, 1, 2 - ), - scale_factor=math.sqrt(target_spatial_size / N), - mode="bicubic", - ) - if updated: - pos_embed, _ = cast_if_src_dtype(pos_embed, torch.float32, torch.bfloat16) - pos_embed = pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) - return pos_embed - - -def interpolate_pos_encoding( - npatch_per_img, - pos_embed, - patches_layout, - input_shape=None, - first_patch_idx=1, -): - assert first_patch_idx == 0 or first_patch_idx == 1, "there is 1 CLS token or none" - N = pos_embed.shape[1] - first_patch_idx # since it's 1 if cls_token exists - if npatch_per_img == N: - return pos_embed - - assert ( - patches_layout[-1] == patches_layout[-2] - ), "Interpolation of pos embed not supported for non-square layouts" - - class_emb = pos_embed[:, :first_patch_idx] - pos_embed = pos_embed[:, first_patch_idx:] - - if input_shape is None or patches_layout[0] == 1: - # simple 2D pos embedding, no temporal component - pos_embed = interpolate_pos_encoding_2d(npatch_per_img, pos_embed) - elif patches_layout[0] > 1: - # pos embed has a temporal component - assert len(input_shape) == 4, "temporal interpolation not supported" - # we only support 2D interpolation in this case - num_frames = patches_layout[0] - num_spatial_tokens = patches_layout[1] * patches_layout[2] - pos_embed = pos_embed.view(1, num_frames, num_spatial_tokens, -1) - # interpolate embedding for zeroth frame - pos_embed = interpolate_pos_encoding_2d( - npatch_per_img, pos_embed[0, 0, ...].unsqueeze(0) - ) - else: - raise ValueError("This type of interpolation isn't implemented") - - return torch.cat((class_emb, pos_embed), dim=1) - - -def _get_pos_embedding( - npatch_per_img, - pos_embed, - patches_layout, - input_shape, - first_patch_idx=1, -): - pos_embed = interpolate_pos_encoding( - npatch_per_img, - pos_embed, - patches_layout, - input_shape=input_shape, - first_patch_idx=first_patch_idx, - ) - return pos_embed - - -class PatchEmbedGeneric(nn.Module): - """ - PatchEmbed from Hydra - """ - - def __init__(self, proj_stem, norm_layer: Optional[nn.Module] = None): - super().__init__() - - if len(proj_stem) > 1: - self.proj = nn.Sequential(*proj_stem) - else: - # Special case to be able to load pre-trained models that were - # trained with a standard stem - self.proj = proj_stem[0] - self.norm_layer = norm_layer - - def get_patch_layout(self, img_size): - with torch.no_grad(): - dummy_img = torch.zeros( - [ - 1, - ] - + img_size - ) - dummy_out = self.proj(dummy_img) - embed_dim = dummy_out.shape[1] - patches_layout = tuple(dummy_out.shape[2:]) - num_patches = np.prod(patches_layout) - return patches_layout, num_patches, embed_dim - - def forward(self, x): - x = self.proj(x) - # B C (T) H W -> B (T)HW C - x = x.flatten(2).transpose(1, 2) - if self.norm_layer is not None: - x = self.norm_layer(x) - return x - - -class SpatioTemporalPosEmbeddingHelper(VerboseNNModule): - def __init__( - self, - patches_layout: List, - num_patches: int, - num_cls_tokens: int, - embed_dim: int, - learnable: bool, - ) -> None: - super().__init__() - self.num_cls_tokens = num_cls_tokens - self.patches_layout = patches_layout - self.num_patches = num_patches - self.num_tokens = num_cls_tokens + num_patches - self.learnable = learnable - if self.learnable: - self.pos_embed = nn.Parameter(torch.zeros(1, self.num_tokens, embed_dim)) - trunc_normal_(self.pos_embed, std=0.02) - else: - self.register_buffer( - "pos_embed", get_sinusoid_encoding_table(self.num_tokens, embed_dim) - ) - - def get_pos_embedding(self, vision_input, all_vision_tokens): - input_shape = vision_input.shape - pos_embed = _get_pos_embedding( - all_vision_tokens.size(1) - self.num_cls_tokens, - pos_embed=self.pos_embed, - patches_layout=self.patches_layout, - input_shape=input_shape, - first_patch_idx=self.num_cls_tokens, - ) - return pos_embed - - -class RGBDTPreprocessor(VerboseNNModule): - def __init__( - self, - rgbt_stem: PatchEmbedGeneric, - depth_stem: Optional[PatchEmbedGeneric], - img_size: Tuple = (3, 224, 224), - num_cls_tokens: int = 1, - pos_embed_fn: Optional[Callable] = None, - use_type_embed: bool = False, - init_param_style: str = "openclip", - ) -> None: - super().__init__() - stem = rgbt_stem if rgbt_stem is not None else depth_stem - ( - self.patches_layout, - self.num_patches, - self.embed_dim, - ) = stem.get_patch_layout(img_size) - self.rgbt_stem = rgbt_stem - self.depth_stem = depth_stem - self.use_pos_embed = pos_embed_fn is not None - self.use_type_embed = use_type_embed - self.num_cls_tokens = num_cls_tokens - - if self.use_pos_embed: - self.pos_embedding_helper = pos_embed_fn( - patches_layout=self.patches_layout, - num_cls_tokens=num_cls_tokens, - num_patches=self.num_patches, - embed_dim=self.embed_dim, - ) - if self.num_cls_tokens > 0: - self.cls_token = nn.Parameter( - torch.zeros(1, self.num_cls_tokens, self.embed_dim) - ) - if self.use_type_embed: - self.type_embed = nn.Parameter(torch.zeros(1, 1, self.embed_dim)) - - self.init_parameters(init_param_style) - - @torch.no_grad() - def init_parameters(self, init_param_style): - if init_param_style == "openclip": - # OpenCLIP style initialization - scale = self.embed_dim**-0.5 - if self.use_pos_embed: - nn.init.normal_(self.pos_embedding_helper.pos_embed) - self.pos_embedding_helper.pos_embed *= scale - - if self.num_cls_tokens > 0: - nn.init.normal_(self.cls_token) - self.cls_token *= scale - elif init_param_style == "vit": - self.cls_token.data.fill_(0) - else: - raise ValueError(f"Unknown init {init_param_style}") - - if self.use_type_embed: - nn.init.normal_(self.type_embed) - - def tokenize_input_and_cls_pos(self, input, stem, mask): - # tokens is of shape B x L x D - tokens = stem(input) - assert tokens.ndim == 3 - assert tokens.shape[2] == self.embed_dim - B = tokens.shape[0] - if self.num_cls_tokens > 0: - class_tokens = self.cls_token.expand( - B, -1, -1 - ) # stole class_tokens impl from Phil Wang, thanks - tokens = torch.cat((class_tokens, tokens), dim=1) - if self.use_pos_embed: - pos_embed = self.pos_embedding_helper.get_pos_embedding(input, tokens) - tokens = tokens + pos_embed - if self.use_type_embed: - tokens = tokens + self.type_embed.expand(B, -1, -1) - return tokens - - def forward(self, vision=None, depth=None, patch_mask=None): - if patch_mask is not None: - raise NotImplementedError() - - if vision is not None: - vision_tokens = self.tokenize_input_and_cls_pos( - vision, self.rgbt_stem, patch_mask - ) - - if depth is not None: - depth_tokens = self.tokenize_input_and_cls_pos( - depth, self.depth_stem, patch_mask - ) - - # aggregate tokens - if vision is not None and depth is not None: - final_tokens = vision_tokens + depth_tokens - else: - final_tokens = vision_tokens if vision is not None else depth_tokens - return_dict = { - "trunk": { - "tokens": final_tokens, - }, - "head": {}, - } - return return_dict - - -class AudioPreprocessor(RGBDTPreprocessor): - def __init__(self, audio_stem: PatchEmbedGeneric, **kwargs) -> None: - super().__init__(rgbt_stem=audio_stem, depth_stem=None, **kwargs) - - def forward(self, audio=None): - return super().forward(vision=audio) - - -class ThermalPreprocessor(RGBDTPreprocessor): - def __init__(self, thermal_stem: PatchEmbedGeneric, **kwargs) -> None: - super().__init__(rgbt_stem=thermal_stem, depth_stem=None, **kwargs) - - def forward(self, thermal=None): - return super().forward(vision=thermal) - - -def build_causal_attention_mask(context_length): - # lazily create causal attention mask, with full attention between the vision tokens - # pytorch uses additive attention mask; fill with -inf - mask = torch.empty(context_length, context_length, requires_grad=False) - mask.fill_(float("-inf")) - mask.triu_(1) # zero out the lower diagonal - return mask - - -class TextPreprocessor(VerboseNNModule): - def __init__( - self, - vocab_size: int, - context_length: int, - embed_dim: int, - causal_masking: bool, - supply_seq_len_to_head: bool = True, - num_cls_tokens: int = 0, - init_param_style: str = "openclip", - ) -> None: - super().__init__() - self.vocab_size = vocab_size - self.context_length = context_length - self.token_embedding = nn.Embedding(vocab_size, embed_dim) - self.pos_embed = nn.Parameter( - torch.empty(1, self.context_length + num_cls_tokens, embed_dim) - ) - self.causal_masking = causal_masking - if self.causal_masking: - mask = build_causal_attention_mask(self.context_length) - # register the mask as a buffer so it can be moved to the right device - self.register_buffer("mask", mask) - - self.supply_seq_len_to_head = supply_seq_len_to_head - self.num_cls_tokens = num_cls_tokens - self.embed_dim = embed_dim - if num_cls_tokens > 0: - assert self.causal_masking is False, "Masking + CLS token isn't implemented" - self.cls_token = nn.Parameter( - torch.zeros(1, self.num_cls_tokens, embed_dim) - ) - - self.init_parameters(init_param_style) - - @torch.no_grad() - def init_parameters(self, init_param_style="openclip"): - # OpenCLIP style initialization - nn.init.normal_(self.token_embedding.weight, std=0.02) - nn.init.normal_(self.pos_embed, std=0.01) - - if init_param_style == "openclip": - # OpenCLIP style initialization - scale = self.embed_dim**-0.5 - if self.num_cls_tokens > 0: - nn.init.normal_(self.cls_token) - self.cls_token *= scale - elif init_param_style == "vit": - self.cls_token.data.fill_(0) - else: - raise ValueError(f"Unknown init {init_param_style}") - - def forward(self, text): - # text tokens are of shape B x L x D - text_tokens = self.token_embedding(text) - # concat CLS tokens if any - if self.num_cls_tokens > 0: - B = text_tokens.shape[0] - class_tokens = self.cls_token.expand( - B, -1, -1 - ) # stole class_tokens impl from Phil Wang, thanks - text_tokens = torch.cat((class_tokens, text_tokens), dim=1) - text_tokens = text_tokens + self.pos_embed - return_dict = { - "trunk": { - "tokens": text_tokens, - }, - "head": {}, - } - # Compute sequence length after adding CLS tokens - if self.supply_seq_len_to_head: - text_lengths = text.argmax(dim=-1) - return_dict["head"] = { - "seq_len": text_lengths, - } - if self.causal_masking: - return_dict["trunk"].update({"attn_mask": self.mask}) - return return_dict - - -class Im2Video(nn.Module): - """Convert an image into a trivial video.""" - - def __init__(self, time_dim=2): - super().__init__() - self.time_dim = time_dim - - def forward(self, x): - if x.ndim == 4: - # B, C, H, W -> B, C, T, H, W - return x.unsqueeze(self.time_dim) - elif x.ndim == 5: - return x - else: - raise ValueError(f"Dimension incorrect {x.shape}") - - -class PadIm2Video(Im2Video): - def __init__(self, ntimes, pad_type, time_dim=2): - super().__init__(time_dim=time_dim) - assert ntimes > 0 - assert pad_type in ["zero", "repeat"] - self.ntimes = ntimes - self.pad_type = pad_type - - def forward(self, x): - x = super().forward(x) - if x.shape[self.time_dim] == 1: - if self.pad_type == "repeat": - new_shape = [1] * len(x.shape) - new_shape[self.time_dim] = self.ntimes - x = x.repeat(new_shape) - elif self.pad_type == "zero": - padarg = [0, 0] * len(x.shape) - padarg[2 * self.time_dim + 1] = self.ntimes - x.shape[self.time_dim] - x = nn.functional.pad(x, padarg) - return x - - -# Modified from github.com/openai/CLIP -@lru_cache() -def bytes_to_unicode(): - """ - Returns list of utf-8 byte and a corresponding list of unicode strings. - The reversible bpe codes work on unicode strings. - This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. - When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. - This is a signficant percentage of your normal, say, 32K bpe vocab. - To avoid that, we want lookup tables between utf-8 bytes and unicode strings. - And avoids mapping to whitespace/control characters the bpe code barfs on. - """ - bs = ( - list(range(ord("!"), ord("~") + 1)) - + list(range(ord("¡"), ord("¬") + 1)) - + list(range(ord("®"), ord("ÿ") + 1)) - ) - cs = bs[:] - n = 0 - for b in range(2**8): - if b not in bs: - bs.append(b) - cs.append(2**8 + n) - n += 1 - cs = [chr(n) for n in cs] - return dict(zip(bs, cs)) - - -def get_pairs(word): - """Return set of symbol pairs in a word. - Word is represented as tuple of symbols (symbols being variable-length strings). - """ - pairs = set() - prev_char = word[0] - for char in word[1:]: - pairs.add((prev_char, char)) - prev_char = char - return pairs - - -def basic_clean(text): - text = ftfy.fix_text(text) - text = html.unescape(html.unescape(text)) - return text.strip() - - -def whitespace_clean(text): - text = re.sub(r"\s+", " ", text) - text = text.strip() - return text - - -class SimpleTokenizer(object): - def __init__(self, bpe_path: str, context_length=77): - self.byte_encoder = bytes_to_unicode() - self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} - - with g_pathmgr.open(bpe_path, "rb") as fh: - bpe_bytes = io.BytesIO(fh.read()) - merges: List[str] = gzip.open(bpe_bytes).read().decode("utf-8").split("\n") - merges = merges[1 : 49152 - 256 - 2 + 1] - merges: List[Tuple[str, ...]] = [tuple(merge.split()) for merge in merges] - vocab = list(bytes_to_unicode().values()) - vocab = vocab + [v + "" for v in vocab] - for merge in merges: - vocab.append("".join(merge)) - vocab.extend(["<|startoftext|>", "<|endoftext|>"]) - self.encoder = dict(zip(vocab, range(len(vocab)))) - self.decoder = {v: k for k, v in self.encoder.items()} - self.bpe_ranks = dict(zip(merges, range(len(merges)))) - self.cache = { - "<|startoftext|>": "<|startoftext|>", - "<|endoftext|>": "<|endoftext|>", - } - self.pat = re.compile( - r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", - re.IGNORECASE, - ) - self.context_length = context_length - - def bpe(self, token): - if token in self.cache: - return self.cache[token] - word = tuple(token[:-1]) + (token[-1] + "",) - pairs = get_pairs(word) - - if not pairs: - return token + "" - - while True: - bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf"))) - if bigram not in self.bpe_ranks: - break - first, second = bigram - new_word = [] - i = 0 - while i < len(word): - try: - j = word.index(first, i) - new_word.extend(word[i:j]) - i = j - except: - new_word.extend(word[i:]) - break - - if word[i] == first and i < len(word) - 1 and word[i + 1] == second: - new_word.append(first + second) - i += 2 - else: - new_word.append(word[i]) - i += 1 - new_word = tuple(new_word) - word = new_word - if len(word) == 1: - break - else: - pairs = get_pairs(word) - word = " ".join(word) - self.cache[token] = word - return word - - def encode(self, text): - bpe_tokens = [] - text = whitespace_clean(basic_clean(text)).lower() - for token in re.findall(self.pat, text): - token = "".join(self.byte_encoder[b] for b in token.encode("utf-8")) - bpe_tokens.extend( - self.encoder[bpe_token] for bpe_token in self.bpe(token).split(" ") - ) - return bpe_tokens - - def decode(self, tokens): - text = "".join([self.decoder[token] for token in tokens]) - text = ( - bytearray([self.byte_decoder[c] for c in text]) - .decode("utf-8", errors="replace") - .replace("", " ") - ) - return text - - def __call__(self, texts, context_length=None): - if not context_length: - context_length = self.context_length - - if isinstance(texts, str): - texts = [texts] - - sot_token = self.encoder["<|startoftext|>"] - eot_token = self.encoder["<|endoftext|>"] - all_tokens = [[sot_token] + self.encode(text) + [eot_token] for text in texts] - result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) - - for i, tokens in enumerate(all_tokens): - tokens = tokens[:context_length] - result[i, : len(tokens)] = torch.tensor(tokens) - - if len(result) == 1: - return result[0] - return result - - -class IMUPreprocessor(VerboseNNModule): - def __init__( - self, - kernel_size: int, - imu_stem: PatchEmbedGeneric, - embed_dim: int, - img_size: Tuple = (6, 2000), - num_cls_tokens: int = 1, - pos_embed_fn: Optional[Callable] = None, - init_param_style: str = "openclip", - ) -> None: - super().__init__() - self.imu_stem = imu_stem - self.embed_dim = embed_dim - self.use_pos_embed = pos_embed_fn is not None - self.num_cls_tokens = num_cls_tokens - self.kernel_size = kernel_size - self.pos_embed = nn.Parameter( - torch.empty(1, (img_size[1] // kernel_size) + num_cls_tokens, embed_dim) - ) - - if self.num_cls_tokens > 0: - self.cls_token = nn.Parameter( - torch.zeros(1, self.num_cls_tokens, self.embed_dim) - ) - - self.init_parameters(init_param_style) - - @torch.no_grad() - def init_parameters(self, init_param_style): - nn.init.normal_(self.pos_embed, std=0.01) - - if init_param_style == "openclip": - # OpenCLIP style initialization - scale = self.embed_dim**-0.5 - - if self.num_cls_tokens > 0: - nn.init.normal_(self.cls_token) - self.cls_token *= scale - elif init_param_style == "vit": - self.cls_token.data.fill_(0) - else: - raise ValueError(f"Unknown init {init_param_style}") - - def tokenize_input_and_cls_pos(self, input, stem): - # tokens is of shape B x L x D - tokens = stem.norm_layer(stem.proj(input)) - assert tokens.ndim == 3 - assert tokens.shape[2] == self.embed_dim - B = tokens.shape[0] - if self.num_cls_tokens > 0: - class_tokens = self.cls_token.expand( - B, -1, -1 - ) # stole class_tokens impl from Phil Wang, thanks - tokens = torch.cat((class_tokens, tokens), dim=1) - if self.use_pos_embed: - tokens = tokens + self.pos_embed - return tokens - - def forward(self, imu): - # Patchify - imu = imu.unfold( - -1, - self.kernel_size, - self.kernel_size, - ).permute(0, 2, 1, 3) - imu = imu.reshape(imu.size(0), imu.size(1), -1) - - imu_tokens = self.tokenize_input_and_cls_pos( - imu, - self.imu_stem, - ) - - return_dict = { - "trunk": { - "tokens": imu_tokens, - }, - "head": {}, - } - return return_dict diff --git a/sonique/Video_LLaMA/video_llama/models/ImageBind/models/transformer.py b/sonique/Video_LLaMA/video_llama/models/ImageBind/models/transformer.py deleted file mode 100644 index 6224faf89d620de010d148bd50dae85176995031..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/ImageBind/models/transformer.py +++ /dev/null @@ -1,280 +0,0 @@ -#!/usr/bin/env python3 -# Portions Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. - -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -# Code modified from -# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py ; -# https://github.com/facebookresearch/deit/blob/main/models.py -# and https://github.com/facebookresearch/vissl/blob/main/vissl/models/trunks/vision_transformer.py - - -from functools import partial -from typing import Callable, List, Optional - -import torch -import torch.nn as nn -import torch.utils.checkpoint as checkpoint -from timm.models.layers import DropPath, trunc_normal_ - - -class Attention(nn.Module): - def __init__( - self, - dim, - num_heads=8, - qkv_bias=False, - qk_scale=None, - attn_drop=0.0, - proj_drop=0.0, - ): - super().__init__() - self.num_heads = num_heads - head_dim = dim // num_heads - # NOTE scale factor was wrong in my original version, - # can set manually to be compat with prev weights - self.scale = qk_scale or head_dim**-0.5 - - self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) - self.attn_drop = nn.Dropout(attn_drop) - self.proj = nn.Linear(dim, dim) - self.proj_drop = nn.Dropout(proj_drop) - - def forward(self, x): - B, N, C = x.shape - qkv = ( - self.qkv(x) - .reshape(B, N, 3, self.num_heads, C // self.num_heads) - .permute(2, 0, 3, 1, 4) - ) - q, k, v = ( - qkv[0], - qkv[1], - qkv[2], - ) # make torchscript happy (cannot use tensor as tuple) - - attn = (q @ k.transpose(-2, -1)) * self.scale - attn = attn.softmax(dim=-1) - attn = self.attn_drop(attn) - - x = (attn @ v).transpose(1, 2).reshape(B, N, C) - x = self.proj(x) - x = self.proj_drop(x) - return x - - -class Mlp(nn.Module): - def __init__( - self, - in_features, - hidden_features=None, - out_features=None, - act_layer=nn.GELU, - drop=0.0, - ): - super().__init__() - out_features = out_features or in_features - hidden_features = hidden_features or in_features - self.fc1 = nn.Linear(in_features, hidden_features) - self.act = act_layer() - self.fc2 = nn.Linear(hidden_features, out_features) - self.drop = nn.Dropout(drop) - - def forward(self, x): - x = self.fc1(x) - x = self.act(x) - x = self.drop(x) - x = self.fc2(x) - x = self.drop(x) - return x - - -class MultiheadAttention(nn.MultiheadAttention): - def forward(self, x: torch.Tensor, attn_mask: torch.Tensor): - return super().forward(x, x, x, need_weights=False, attn_mask=attn_mask)[0] - - -class ViTAttention(Attention): - def forward(self, x: torch.Tensor, attn_mask: torch.Tensor): - assert attn_mask is None - return super().forward(x) - - -class BlockWithMasking(nn.Module): - def __init__( - self, - dim: int, - attn_target: Callable, - mlp_ratio: int = 4, - act_layer: Callable = nn.GELU, - norm_layer: Callable = nn.LayerNorm, - ffn_dropout_rate: float = 0.0, - drop_path: float = 0.0, - layer_scale_type: Optional[str] = None, - layer_scale_init_value: float = 1e-4, - ): - super().__init__() - - assert not isinstance( - attn_target, nn.Module - ), "attn_target should be a Callable. Otherwise attn_target is shared across blocks!" - self.attn = attn_target() - if drop_path > 0.0: - self.drop_path = DropPath(drop_path) - else: - self.drop_path = nn.Identity() - self.norm_1 = norm_layer(dim) - mlp_hidden_dim = int(mlp_ratio * dim) - self.mlp = Mlp( - in_features=dim, - hidden_features=mlp_hidden_dim, - act_layer=act_layer, - drop=ffn_dropout_rate, - ) - self.norm_2 = norm_layer(dim) - self.layer_scale_type = layer_scale_type - if self.layer_scale_type is not None: - assert self.layer_scale_type in [ - "per_channel", - "scalar", - ], f"Found Layer scale type {self.layer_scale_type}" - if self.layer_scale_type == "per_channel": - # one gamma value per channel - gamma_shape = [1, 1, dim] - elif self.layer_scale_type == "scalar": - # single gamma value for all channels - gamma_shape = [1, 1, 1] - # two gammas: for each part of the fwd in the encoder - self.layer_scale_gamma1 = nn.Parameter( - torch.ones(size=gamma_shape) * layer_scale_init_value, - requires_grad=True, - ) - self.layer_scale_gamma2 = nn.Parameter( - torch.ones(size=gamma_shape) * layer_scale_init_value, - requires_grad=True, - ) - - def forward(self, x: torch.Tensor, attn_mask: torch.Tensor): - if self.layer_scale_type is None: - x = x + self.drop_path(self.attn(self.norm_1(x), attn_mask)) - x = x + self.drop_path(self.mlp(self.norm_2(x))) - else: - x = ( - x - + self.drop_path(self.attn(self.norm_1(x), attn_mask)) - * self.layer_scale_gamma1 - ) - x = x + self.drop_path(self.mlp(self.norm_2(x))) * self.layer_scale_gamma2 - return x - - -_LAYER_NORM = partial(nn.LayerNorm, eps=1e-6) - - -class SimpleTransformer(nn.Module): - def __init__( - self, - attn_target: Callable, - embed_dim: int, - num_blocks: int, - block: Callable = BlockWithMasking, - pre_transformer_layer: Optional[Callable] = None, - post_transformer_layer: Optional[Callable] = None, - drop_path_rate: float = 0.0, - drop_path_type: str = "progressive", - norm_layer: Callable = _LAYER_NORM, - mlp_ratio: int = 4, - ffn_dropout_rate: float = 0.0, - layer_scale_type: Optional[str] = None, # from cait; possible values are None, "per_channel", "scalar" - layer_scale_init_value: float = 1e-4, # from cait; float - weight_init_style: str = "jax", # possible values jax or pytorch - ): - """ - Simple Transformer with the following features - 1. Supports masked attention - 2. Supports DropPath - 3. Supports LayerScale - 4. Supports Dropout in Attention and FFN - 5. Makes few assumptions about the input except that it is a Tensor - """ - super().__init__() - self.pre_transformer_layer = pre_transformer_layer - if drop_path_type == "progressive": - dpr = [x.item() for x in torch.linspace(0, drop_path_rate, num_blocks)] - elif drop_path_type == "uniform": - dpr = [drop_path_rate for i in range(num_blocks)] - else: - raise ValueError(f"Unknown drop_path_type: {drop_path_type}") - - self.blocks = nn.Sequential( - *[ - block( - dim=embed_dim, - attn_target=attn_target, - mlp_ratio=mlp_ratio, - ffn_dropout_rate=ffn_dropout_rate, - drop_path=dpr[i], - norm_layer=norm_layer, - layer_scale_type=layer_scale_type, - layer_scale_init_value=layer_scale_init_value, - ) - for i in range(num_blocks) - ] - ) - self.post_transformer_layer = post_transformer_layer - self.weight_init_style = weight_init_style - self.apply(self._init_weights) - - def _init_weights(self, m): - if isinstance(m, nn.Linear): - if self.weight_init_style == "jax": - # Based on MAE and official Jax ViT implementation - torch.nn.init.xavier_uniform_(m.weight) - elif self.weight_init_style == "pytorch": - # PyTorch ViT uses trunc_normal_ - trunc_normal_(m.weight, std=0.02) - - if m.bias is not None: - nn.init.constant_(m.bias, 0) - elif isinstance(m, (nn.LayerNorm)): - nn.init.constant_(m.bias, 0) - nn.init.constant_(m.weight, 1.0) - - def forward( - self, - tokens: torch.Tensor, - attn_mask: torch.Tensor = None, - use_checkpoint: bool = False, - checkpoint_every_n: int = 1, - checkpoint_blk_ids: Optional[List[int]] = None, - ): - """ - Inputs - - tokens: data of shape N x L x D (or L x N x D depending on the attention implementation) - - attn: mask of shape L x L - - Output - - x: data of shape N x L x D (or L x N x D depending on the attention implementation) - """ - if self.pre_transformer_layer: - tokens = self.pre_transformer_layer(tokens) - if use_checkpoint and checkpoint_blk_ids is None: - checkpoint_blk_ids = [ - blk_id - for blk_id in range(len(self.blocks)) - if blk_id % checkpoint_every_n == 0 - ] - if checkpoint_blk_ids: - checkpoint_blk_ids = set(checkpoint_blk_ids) - for blk_id, blk in enumerate(self.blocks): - if use_checkpoint and blk_id in checkpoint_blk_ids: - tokens = checkpoint.checkpoint( - blk, tokens, attn_mask, use_reentrant=False - ) - else: - tokens = blk(tokens, attn_mask=attn_mask) - if self.post_transformer_layer: - tokens = self.post_transformer_layer(tokens) - return tokens diff --git a/sonique/Video_LLaMA/video_llama/models/ImageBind/requirements.txt b/sonique/Video_LLaMA/video_llama/models/ImageBind/requirements.txt deleted file mode 100644 index d35cb65aedcc46b805aac9328ca2e0e246a76dae..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/ImageBind/requirements.txt +++ /dev/null @@ -1,17 +0,0 @@ ---extra-index-url https://download.pytorch.org/whl/cu113 -torch==1.13.0 -torchvision==0.14.0 -torchaudio==0.13.0 -pytorchvideo @ git+https://github.com/facebookresearch/pytorchvideo.git@28fe037d212663c6a24f373b94cc5d478c8c1a1d -timm==0.6.7 -ftfy -regex -einops -fvcore -decord==0.6.0 -iopath -numpy -matplotlib -types-regex -mayavi -cartopy diff --git a/sonique/Video_LLaMA/video_llama/models/Qformer.py b/sonique/Video_LLaMA/video_llama/models/Qformer.py deleted file mode 100644 index 4902165ec6574d89f04cbeb2141b018278324ca6..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/Qformer.py +++ /dev/null @@ -1,1217 +0,0 @@ -""" -Adapted from salesforce@LAVIS. Below is the original copyright: - * Copyright (c) 2023, salesforce.com, inc. - * All rights reserved. - * SPDX-License-Identifier: BSD-3-Clause - * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause - * By Junnan Li - * Based on huggingface code base - * https://github.com/huggingface/transformers/blob/v4.15.0/src/transformers/models/bert -""" - -import math -import os -import warnings -from dataclasses import dataclass -from typing import Optional, Tuple, Dict, Any - -import torch -from torch import Tensor, device, dtype, nn -import torch.utils.checkpoint -from torch import nn -from torch.nn import CrossEntropyLoss -import torch.nn.functional as F - -from transformers.activations import ACT2FN -from transformers.file_utils import ( - ModelOutput, -) -from transformers.modeling_outputs import ( - BaseModelOutputWithPastAndCrossAttentions, - BaseModelOutputWithPoolingAndCrossAttentions, - CausalLMOutputWithCrossAttentions, - MaskedLMOutput, - MultipleChoiceModelOutput, - NextSentencePredictorOutput, - QuestionAnsweringModelOutput, - SequenceClassifierOutput, - TokenClassifierOutput, -) -from transformers.modeling_utils import ( - PreTrainedModel, - apply_chunking_to_forward, - find_pruneable_heads_and_indices, - prune_linear_layer, -) -from transformers.utils import logging -from transformers.models.bert.configuration_bert import BertConfig - -logger = logging.get_logger(__name__) - - -class BertEmbeddings(nn.Module): - """Construct the embeddings from word and position embeddings.""" - - def __init__(self, config): - super().__init__() - self.word_embeddings = nn.Embedding( - config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id - ) - self.position_embeddings = nn.Embedding( - config.max_position_embeddings, config.hidden_size - ) - - # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load - # any TensorFlow checkpoint file - self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) - self.dropout = nn.Dropout(config.hidden_dropout_prob) - - # position_ids (1, len position emb) is contiguous in memory and exported when serialized - self.register_buffer( - "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)) - ) - self.position_embedding_type = getattr( - config, "position_embedding_type", "absolute" - ) - - self.config = config - - def forward( - self, - input_ids=None, - position_ids=None, - query_embeds=None, - past_key_values_length=0, - ): - if input_ids is not None: - seq_length = input_ids.size()[1] - else: - seq_length = 0 - - if position_ids is None: - position_ids = self.position_ids[ - :, past_key_values_length : seq_length + past_key_values_length - ].clone() - - if input_ids is not None: - embeddings = self.word_embeddings(input_ids) - if self.position_embedding_type == "absolute": - position_embeddings = self.position_embeddings(position_ids) - embeddings = embeddings + position_embeddings - - if query_embeds is not None: - embeddings = torch.cat((query_embeds, embeddings), dim=1) - else: - embeddings = query_embeds - - embeddings = self.LayerNorm(embeddings) - embeddings = self.dropout(embeddings) - return embeddings - - -class BertSelfAttention(nn.Module): - def __init__(self, config, is_cross_attention): - super().__init__() - self.config = config - if config.hidden_size % config.num_attention_heads != 0 and not hasattr( - config, "embedding_size" - ): - raise ValueError( - "The hidden size (%d) is not a multiple of the number of attention " - "heads (%d)" % (config.hidden_size, config.num_attention_heads) - ) - - self.num_attention_heads = config.num_attention_heads - self.attention_head_size = int(config.hidden_size / config.num_attention_heads) - self.all_head_size = self.num_attention_heads * self.attention_head_size - - self.query = nn.Linear(config.hidden_size, self.all_head_size) - if is_cross_attention: - self.key = nn.Linear(config.encoder_width, self.all_head_size) - self.value = nn.Linear(config.encoder_width, self.all_head_size) - else: - self.key = nn.Linear(config.hidden_size, self.all_head_size) - self.value = nn.Linear(config.hidden_size, self.all_head_size) - - self.dropout = nn.Dropout(config.attention_probs_dropout_prob) - self.position_embedding_type = getattr( - config, "position_embedding_type", "absolute" - ) - if ( - self.position_embedding_type == "relative_key" - or self.position_embedding_type == "relative_key_query" - ): - self.max_position_embeddings = config.max_position_embeddings - self.distance_embedding = nn.Embedding( - 2 * config.max_position_embeddings - 1, self.attention_head_size - ) - self.save_attention = False - - def save_attn_gradients(self, attn_gradients): - self.attn_gradients = attn_gradients - - def get_attn_gradients(self): - return self.attn_gradients - - def save_attention_map(self, attention_map): - self.attention_map = attention_map - - def get_attention_map(self): - return self.attention_map - - def transpose_for_scores(self, x): - new_x_shape = x.size()[:-1] + ( - self.num_attention_heads, - self.attention_head_size, - ) - x = x.view(*new_x_shape) - return x.permute(0, 2, 1, 3) - - def forward( - self, - hidden_states, - attention_mask=None, - head_mask=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - past_key_value=None, - output_attentions=False, - ): - - # If this is instantiated as a cross-attention module, the keys - # and values come from an encoder; the attention mask needs to be - # such that the encoder's padding tokens are not attended to. - is_cross_attention = encoder_hidden_states is not None - - if is_cross_attention: - key_layer = self.transpose_for_scores(self.key(encoder_hidden_states)) - value_layer = self.transpose_for_scores(self.value(encoder_hidden_states)) - attention_mask = encoder_attention_mask - elif past_key_value is not None: - key_layer = self.transpose_for_scores(self.key(hidden_states)) - value_layer = self.transpose_for_scores(self.value(hidden_states)) - key_layer = torch.cat([past_key_value[0], key_layer], dim=2) - value_layer = torch.cat([past_key_value[1], value_layer], dim=2) - else: - key_layer = self.transpose_for_scores(self.key(hidden_states)) - value_layer = self.transpose_for_scores(self.value(hidden_states)) - - mixed_query_layer = self.query(hidden_states) - - query_layer = self.transpose_for_scores(mixed_query_layer) - - past_key_value = (key_layer, value_layer) - - # Take the dot product between "query" and "key" to get the raw attention scores. - attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) - - if ( - self.position_embedding_type == "relative_key" - or self.position_embedding_type == "relative_key_query" - ): - seq_length = hidden_states.size()[1] - position_ids_l = torch.arange( - seq_length, dtype=torch.long, device=hidden_states.device - ).view(-1, 1) - position_ids_r = torch.arange( - seq_length, dtype=torch.long, device=hidden_states.device - ).view(1, -1) - distance = position_ids_l - position_ids_r - positional_embedding = self.distance_embedding( - distance + self.max_position_embeddings - 1 - ) - positional_embedding = positional_embedding.to( - dtype=query_layer.dtype - ) # fp16 compatibility - - if self.position_embedding_type == "relative_key": - relative_position_scores = torch.einsum( - "bhld,lrd->bhlr", query_layer, positional_embedding - ) - attention_scores = attention_scores + relative_position_scores - elif self.position_embedding_type == "relative_key_query": - relative_position_scores_query = torch.einsum( - "bhld,lrd->bhlr", query_layer, positional_embedding - ) - relative_position_scores_key = torch.einsum( - "bhrd,lrd->bhlr", key_layer, positional_embedding - ) - attention_scores = ( - attention_scores - + relative_position_scores_query - + relative_position_scores_key - ) - - attention_scores = attention_scores / math.sqrt(self.attention_head_size) - if attention_mask is not None: - # Apply the attention mask is (precomputed for all layers in BertModel forward() function) - attention_scores = attention_scores + attention_mask - - # Normalize the attention scores to probabilities. - attention_probs = nn.Softmax(dim=-1)(attention_scores) - - if is_cross_attention and self.save_attention: - self.save_attention_map(attention_probs) - attention_probs.register_hook(self.save_attn_gradients) - - # This is actually dropping out entire tokens to attend to, which might - # seem a bit unusual, but is taken from the original Transformer paper. - attention_probs_dropped = self.dropout(attention_probs) - - # Mask heads if we want to - if head_mask is not None: - attention_probs_dropped = attention_probs_dropped * head_mask - - context_layer = torch.matmul(attention_probs_dropped, value_layer) - - context_layer = context_layer.permute(0, 2, 1, 3).contiguous() - new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) - context_layer = context_layer.view(*new_context_layer_shape) - - outputs = ( - (context_layer, attention_probs) if output_attentions else (context_layer,) - ) - - outputs = outputs + (past_key_value,) - return outputs - - -class BertSelfOutput(nn.Module): - def __init__(self, config): - super().__init__() - self.dense = nn.Linear(config.hidden_size, config.hidden_size) - self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) - self.dropout = nn.Dropout(config.hidden_dropout_prob) - - def forward(self, hidden_states, input_tensor): - hidden_states = self.dense(hidden_states) - hidden_states = self.dropout(hidden_states) - hidden_states = self.LayerNorm(hidden_states + input_tensor) - return hidden_states - - -class BertAttention(nn.Module): - def __init__(self, config, is_cross_attention=False): - super().__init__() - self.self = BertSelfAttention(config, is_cross_attention) - self.output = BertSelfOutput(config) - self.pruned_heads = set() - - def prune_heads(self, heads): - if len(heads) == 0: - return - heads, index = find_pruneable_heads_and_indices( - heads, - self.self.num_attention_heads, - self.self.attention_head_size, - self.pruned_heads, - ) - - # Prune linear layers - self.self.query = prune_linear_layer(self.self.query, index) - self.self.key = prune_linear_layer(self.self.key, index) - self.self.value = prune_linear_layer(self.self.value, index) - self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) - - # Update hyper params and store pruned heads - self.self.num_attention_heads = self.self.num_attention_heads - len(heads) - self.self.all_head_size = ( - self.self.attention_head_size * self.self.num_attention_heads - ) - self.pruned_heads = self.pruned_heads.union(heads) - - def forward( - self, - hidden_states, - attention_mask=None, - head_mask=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - past_key_value=None, - output_attentions=False, - ): - self_outputs = self.self( - hidden_states, - attention_mask, - head_mask, - encoder_hidden_states, - encoder_attention_mask, - past_key_value, - output_attentions, - ) - attention_output = self.output(self_outputs[0], hidden_states) - - outputs = (attention_output,) + self_outputs[ - 1: - ] # add attentions if we output them - return outputs - - -class BertIntermediate(nn.Module): - def __init__(self, config): - super().__init__() - self.dense = nn.Linear(config.hidden_size, config.intermediate_size) - if isinstance(config.hidden_act, str): - self.intermediate_act_fn = ACT2FN[config.hidden_act] - else: - self.intermediate_act_fn = config.hidden_act - - def forward(self, hidden_states): - hidden_states = self.dense(hidden_states) - hidden_states = self.intermediate_act_fn(hidden_states) - return hidden_states - - -class BertOutput(nn.Module): - def __init__(self, config): - super().__init__() - self.dense = nn.Linear(config.intermediate_size, config.hidden_size) - self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) - self.dropout = nn.Dropout(config.hidden_dropout_prob) - - def forward(self, hidden_states, input_tensor): - hidden_states = self.dense(hidden_states) - hidden_states = self.dropout(hidden_states) - hidden_states = self.LayerNorm(hidden_states + input_tensor) - return hidden_states - - -class BertLayer(nn.Module): - def __init__(self, config, layer_num): - super().__init__() - self.config = config - self.chunk_size_feed_forward = config.chunk_size_feed_forward - self.seq_len_dim = 1 - self.attention = BertAttention(config) - self.layer_num = layer_num - if ( - self.config.add_cross_attention - and layer_num % self.config.cross_attention_freq == 0 - ): - self.crossattention = BertAttention( - config, is_cross_attention=self.config.add_cross_attention - ) - self.has_cross_attention = True - else: - self.has_cross_attention = False - self.intermediate = BertIntermediate(config) - self.output = BertOutput(config) - - self.intermediate_query = BertIntermediate(config) - self.output_query = BertOutput(config) - - def forward( - self, - hidden_states, - attention_mask=None, - head_mask=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - past_key_value=None, - output_attentions=False, - query_length=0, - ): - # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 - self_attn_past_key_value = ( - past_key_value[:2] if past_key_value is not None else None - ) - self_attention_outputs = self.attention( - hidden_states, - attention_mask, - head_mask, - output_attentions=output_attentions, - past_key_value=self_attn_past_key_value, - ) - attention_output = self_attention_outputs[0] - outputs = self_attention_outputs[1:-1] - - present_key_value = self_attention_outputs[-1] - - if query_length > 0: - query_attention_output = attention_output[:, :query_length, :] - - if self.has_cross_attention: - assert ( - encoder_hidden_states is not None - ), "encoder_hidden_states must be given for cross-attention layers" - cross_attention_outputs = self.crossattention( - query_attention_output, - attention_mask, - head_mask, - encoder_hidden_states, - encoder_attention_mask, - output_attentions=output_attentions, - ) - query_attention_output = cross_attention_outputs[0] - outputs = ( - outputs + cross_attention_outputs[1:-1] - ) # add cross attentions if we output attention weights - - layer_output = apply_chunking_to_forward( - self.feed_forward_chunk_query, - self.chunk_size_feed_forward, - self.seq_len_dim, - query_attention_output, - ) - if attention_output.shape[1] > query_length: - layer_output_text = apply_chunking_to_forward( - self.feed_forward_chunk, - self.chunk_size_feed_forward, - self.seq_len_dim, - attention_output[:, query_length:, :], - ) - layer_output = torch.cat([layer_output, layer_output_text], dim=1) - else: - layer_output = apply_chunking_to_forward( - self.feed_forward_chunk, - self.chunk_size_feed_forward, - self.seq_len_dim, - attention_output, - ) - outputs = (layer_output,) + outputs - - outputs = outputs + (present_key_value,) - - return outputs - - def feed_forward_chunk(self, attention_output): - intermediate_output = self.intermediate(attention_output) - layer_output = self.output(intermediate_output, attention_output) - return layer_output - - def feed_forward_chunk_query(self, attention_output): - intermediate_output = self.intermediate_query(attention_output) - layer_output = self.output_query(intermediate_output, attention_output) - return layer_output - - -class BertEncoder(nn.Module): - def __init__(self, config): - super().__init__() - self.config = config - self.layer = nn.ModuleList( - [BertLayer(config, i) for i in range(config.num_hidden_layers)] - ) - - def forward( - self, - hidden_states, - attention_mask=None, - head_mask=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - past_key_values=None, - use_cache=None, - output_attentions=False, - output_hidden_states=False, - return_dict=True, - query_length=0, - ): - all_hidden_states = () if output_hidden_states else None - all_self_attentions = () if output_attentions else None - all_cross_attentions = ( - () if output_attentions and self.config.add_cross_attention else None - ) - - next_decoder_cache = () if use_cache else None - - for i in range(self.config.num_hidden_layers): - layer_module = self.layer[i] - if output_hidden_states: - all_hidden_states = all_hidden_states + (hidden_states,) - - layer_head_mask = head_mask[i] if head_mask is not None else None - past_key_value = past_key_values[i] if past_key_values is not None else None - - if getattr(self.config, "gradient_checkpointing", False) and self.training: - - if use_cache: - logger.warn( - "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." - ) - use_cache = False - - def create_custom_forward(module): - def custom_forward(*inputs): - return module( - *inputs, past_key_value, output_attentions, query_length - ) - - return custom_forward - - layer_outputs = torch.utils.checkpoint.checkpoint( - create_custom_forward(layer_module), - hidden_states, - attention_mask, - layer_head_mask, - encoder_hidden_states, - encoder_attention_mask, - ) - else: - layer_outputs = layer_module( - hidden_states, - attention_mask, - layer_head_mask, - encoder_hidden_states, - encoder_attention_mask, - past_key_value, - output_attentions, - query_length, - ) - - hidden_states = layer_outputs[0] - if use_cache: - next_decoder_cache += (layer_outputs[-1],) - if output_attentions: - all_self_attentions = all_self_attentions + (layer_outputs[1],) - all_cross_attentions = all_cross_attentions + (layer_outputs[2],) - - if output_hidden_states: - all_hidden_states = all_hidden_states + (hidden_states,) - - if not return_dict: - return tuple( - v - for v in [ - hidden_states, - next_decoder_cache, - all_hidden_states, - all_self_attentions, - all_cross_attentions, - ] - if v is not None - ) - return BaseModelOutputWithPastAndCrossAttentions( - last_hidden_state=hidden_states, - past_key_values=next_decoder_cache, - hidden_states=all_hidden_states, - attentions=all_self_attentions, - cross_attentions=all_cross_attentions, - ) - - -class BertPooler(nn.Module): - def __init__(self, config): - super().__init__() - self.dense = nn.Linear(config.hidden_size, config.hidden_size) - self.activation = nn.Tanh() - - def forward(self, hidden_states): - # We "pool" the model by simply taking the hidden state corresponding - # to the first token. - first_token_tensor = hidden_states[:, 0] - pooled_output = self.dense(first_token_tensor) - pooled_output = self.activation(pooled_output) - return pooled_output - - -class BertPredictionHeadTransform(nn.Module): - def __init__(self, config): - super().__init__() - self.dense = nn.Linear(config.hidden_size, config.hidden_size) - if isinstance(config.hidden_act, str): - self.transform_act_fn = ACT2FN[config.hidden_act] - else: - self.transform_act_fn = config.hidden_act - self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) - - def forward(self, hidden_states): - hidden_states = self.dense(hidden_states) - hidden_states = self.transform_act_fn(hidden_states) - hidden_states = self.LayerNorm(hidden_states) - return hidden_states - - -class BertLMPredictionHead(nn.Module): - def __init__(self, config): - super().__init__() - self.transform = BertPredictionHeadTransform(config) - - # The output weights are the same as the input embeddings, but there is - # an output-only bias for each token. - self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) - - self.bias = nn.Parameter(torch.zeros(config.vocab_size)) - - # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` - self.decoder.bias = self.bias - - def forward(self, hidden_states): - hidden_states = self.transform(hidden_states) - hidden_states = self.decoder(hidden_states) - return hidden_states - - -class BertOnlyMLMHead(nn.Module): - def __init__(self, config): - super().__init__() - self.predictions = BertLMPredictionHead(config) - - def forward(self, sequence_output): - prediction_scores = self.predictions(sequence_output) - return prediction_scores - - -class BertPreTrainedModel(PreTrainedModel): - """ - An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained - models. - """ - - config_class = BertConfig - base_model_prefix = "bert" - _keys_to_ignore_on_load_missing = [r"position_ids"] - - def _init_weights(self, module): - """Initialize the weights""" - if isinstance(module, (nn.Linear, nn.Embedding)): - # Slightly different from the TF version which uses truncated_normal for initialization - # cf https://github.com/pytorch/pytorch/pull/5617 - module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) - elif isinstance(module, nn.LayerNorm): - module.bias.data.zero_() - module.weight.data.fill_(1.0) - if isinstance(module, nn.Linear) and module.bias is not None: - module.bias.data.zero_() - - -class BertModel(BertPreTrainedModel): - """ - The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of - cross-attention is added between the self-attention layers, following the architecture described in `Attention is - all you need `__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, - Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. - argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an - input to the forward pass. - """ - - def __init__(self, config, add_pooling_layer=False): - super().__init__(config) - self.config = config - - self.embeddings = BertEmbeddings(config) - - self.encoder = BertEncoder(config) - - self.pooler = BertPooler(config) if add_pooling_layer else None - - self.init_weights() - - def get_input_embeddings(self): - return self.embeddings.word_embeddings - - def set_input_embeddings(self, value): - self.embeddings.word_embeddings = value - - def _prune_heads(self, heads_to_prune): - """ - Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base - class PreTrainedModel - """ - for layer, heads in heads_to_prune.items(): - self.encoder.layer[layer].attention.prune_heads(heads) - - def get_extended_attention_mask( - self, - attention_mask: Tensor, - input_shape: Tuple[int], - device: device, - is_decoder: bool, - has_query: bool = False, - ) -> Tensor: - """ - Makes broadcastable attention and causal masks so that future and masked tokens are ignored. - - Arguments: - attention_mask (:obj:`torch.Tensor`): - Mask with ones indicating tokens to attend to, zeros for tokens to ignore. - input_shape (:obj:`Tuple[int]`): - The shape of the input to the model. - device: (:obj:`torch.device`): - The device of the input to the model. - - Returns: - :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`. - """ - # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] - # ourselves in which case we just need to make it broadcastable to all heads. - if attention_mask.dim() == 3: - extended_attention_mask = attention_mask[:, None, :, :] - elif attention_mask.dim() == 2: - # Provided a padding mask of dimensions [batch_size, seq_length] - # - if the model is a decoder, apply a causal mask in addition to the padding mask - # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length] - if is_decoder: - batch_size, seq_length = input_shape - - seq_ids = torch.arange(seq_length, device=device) - causal_mask = ( - seq_ids[None, None, :].repeat(batch_size, seq_length, 1) - <= seq_ids[None, :, None] - ) - - # add a prefix ones mask to the causal mask - # causal and attention masks must have same type with pytorch version < 1.3 - causal_mask = causal_mask.to(attention_mask.dtype) - - if causal_mask.shape[1] < attention_mask.shape[1]: - prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1] - if has_query: # UniLM style attention mask - causal_mask = torch.cat( - [ - torch.zeros( - (batch_size, prefix_seq_len, seq_length), - device=device, - dtype=causal_mask.dtype, - ), - causal_mask, - ], - axis=1, - ) - causal_mask = torch.cat( - [ - torch.ones( - (batch_size, causal_mask.shape[1], prefix_seq_len), - device=device, - dtype=causal_mask.dtype, - ), - causal_mask, - ], - axis=-1, - ) - extended_attention_mask = ( - causal_mask[:, None, :, :] * attention_mask[:, None, None, :] - ) - else: - extended_attention_mask = attention_mask[:, None, None, :] - else: - raise ValueError( - "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format( - input_shape, attention_mask.shape - ) - ) - - # Since attention_mask is 1.0 for positions we want to attend and 0.0 for - # masked positions, this operation will create a tensor which is 0.0 for - # positions we want to attend and -10000.0 for masked positions. - # Since we are adding it to the raw scores before the softmax, this is - # effectively the same as removing these entirely. - extended_attention_mask = extended_attention_mask.to( - dtype=self.dtype - ) # fp16 compatibility - extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0 - return extended_attention_mask - - def forward( - self, - input_ids=None, - attention_mask=None, - position_ids=None, - head_mask=None, - query_embeds=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - past_key_values=None, - use_cache=None, - output_attentions=None, - output_hidden_states=None, - return_dict=None, - is_decoder=False, - ): - r""" - encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): - Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if - the model is configured as a decoder. - encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): - Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in - the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``: - - 1 for tokens that are **not masked**, - - 0 for tokens that are **masked**. - past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): - Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. - If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` - (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` - instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`. - use_cache (:obj:`bool`, `optional`): - If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up - decoding (see :obj:`past_key_values`). - """ - output_attentions = ( - output_attentions - if output_attentions is not None - else self.config.output_attentions - ) - output_hidden_states = ( - output_hidden_states - if output_hidden_states is not None - else self.config.output_hidden_states - ) - return_dict = ( - return_dict if return_dict is not None else self.config.use_return_dict - ) - - # use_cache = use_cache if use_cache is not None else self.config.use_cache - - if input_ids is None: - assert ( - query_embeds is not None - ), "You have to specify query_embeds when input_ids is None" - - # past_key_values_length - past_key_values_length = ( - past_key_values[0][0].shape[2] - self.config.query_length - if past_key_values is not None - else 0 - ) - - query_length = query_embeds.shape[1] if query_embeds is not None else 0 - - embedding_output = self.embeddings( - input_ids=input_ids, - position_ids=position_ids, - query_embeds=query_embeds, - past_key_values_length=past_key_values_length, - ) - - input_shape = embedding_output.size()[:-1] - batch_size, seq_length = input_shape - device = embedding_output.device - - if attention_mask is None: - attention_mask = torch.ones( - ((batch_size, seq_length + past_key_values_length)), device=device - ) - - # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] - # ourselves in which case we just need to make it broadcastable to all heads. - if is_decoder: - extended_attention_mask = self.get_extended_attention_mask( - attention_mask, - input_ids.shape, - device, - is_decoder, - has_query=(query_embeds is not None), - ) - else: - extended_attention_mask = self.get_extended_attention_mask( - attention_mask, input_shape, device, is_decoder - ) - - # If a 2D or 3D attention mask is provided for the cross-attention - # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] - if encoder_hidden_states is not None: - if type(encoder_hidden_states) == list: - encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[ - 0 - ].size() - else: - ( - encoder_batch_size, - encoder_sequence_length, - _, - ) = encoder_hidden_states.size() - encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) - - if type(encoder_attention_mask) == list: - encoder_extended_attention_mask = [ - self.invert_attention_mask(mask) for mask in encoder_attention_mask - ] - elif encoder_attention_mask is None: - encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) - encoder_extended_attention_mask = self.invert_attention_mask( - encoder_attention_mask - ) - else: - encoder_extended_attention_mask = self.invert_attention_mask( - encoder_attention_mask - ) - else: - encoder_extended_attention_mask = None - - # Prepare head mask if needed - # 1.0 in head_mask indicate we keep the head - # attention_probs has shape bsz x n_heads x N x N - # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] - # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] - head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) - - encoder_outputs = self.encoder( - embedding_output, - attention_mask=extended_attention_mask, - head_mask=head_mask, - encoder_hidden_states=encoder_hidden_states, - encoder_attention_mask=encoder_extended_attention_mask, - past_key_values=past_key_values, - use_cache=use_cache, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - query_length=query_length, - ) - sequence_output = encoder_outputs[0] - pooled_output = ( - self.pooler(sequence_output) if self.pooler is not None else None - ) - - if not return_dict: - return (sequence_output, pooled_output) + encoder_outputs[1:] - - return BaseModelOutputWithPoolingAndCrossAttentions( - last_hidden_state=sequence_output, - pooler_output=pooled_output, - past_key_values=encoder_outputs.past_key_values, - hidden_states=encoder_outputs.hidden_states, - attentions=encoder_outputs.attentions, - cross_attentions=encoder_outputs.cross_attentions, - ) - - -class BertLMHeadModel(BertPreTrainedModel): - - _keys_to_ignore_on_load_unexpected = [r"pooler"] - _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"] - - def __init__(self, config): - super().__init__(config) - - self.bert = BertModel(config, add_pooling_layer=False) - self.cls = BertOnlyMLMHead(config) - - self.init_weights() - - def get_output_embeddings(self): - return self.cls.predictions.decoder - - def set_output_embeddings(self, new_embeddings): - self.cls.predictions.decoder = new_embeddings - - def forward( - self, - input_ids=None, - attention_mask=None, - position_ids=None, - head_mask=None, - query_embeds=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - labels=None, - past_key_values=None, - use_cache=True, - output_attentions=None, - output_hidden_states=None, - return_dict=None, - return_logits=False, - is_decoder=True, - reduction="mean", - ): - r""" - encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): - Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if - the model is configured as a decoder. - encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): - Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in - the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``: - - 1 for tokens that are **not masked**, - - 0 for tokens that are **masked**. - labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): - Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in - ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are - ignored (masked), the loss is only computed for the tokens with labels n ``[0, ..., config.vocab_size]`` - past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): - Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. - If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` - (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` - instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`. - use_cache (:obj:`bool`, `optional`): - If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up - decoding (see :obj:`past_key_values`). - Returns: - Example:: - >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig - >>> import torch - >>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased') - >>> config = BertConfig.from_pretrained("bert-base-cased") - >>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config) - >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") - >>> outputs = model(**inputs) - >>> prediction_logits = outputs.logits - """ - return_dict = ( - return_dict if return_dict is not None else self.config.use_return_dict - ) - if labels is not None: - use_cache = False - if past_key_values is not None: - query_embeds = None - - outputs = self.bert( - input_ids, - attention_mask=attention_mask, - position_ids=position_ids, - head_mask=head_mask, - query_embeds=query_embeds, - encoder_hidden_states=encoder_hidden_states, - encoder_attention_mask=encoder_attention_mask, - past_key_values=past_key_values, - use_cache=use_cache, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - is_decoder=is_decoder, - ) - - sequence_output = outputs[0] - if query_embeds is not None: - sequence_output = outputs[0][:, query_embeds.shape[1] :, :] - - prediction_scores = self.cls(sequence_output) - - if return_logits: - return prediction_scores[:, :-1, :].contiguous() - - lm_loss = None - if labels is not None: - # we are doing next-token prediction; shift prediction scores and input ids by one - shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous() - labels = labels[:, 1:].contiguous() - loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=0.1) - lm_loss = loss_fct( - shifted_prediction_scores.view(-1, self.config.vocab_size), - labels.view(-1), - ) - if reduction == "none": - lm_loss = lm_loss.view(prediction_scores.size(0), -1).sum(1) - - if not return_dict: - output = (prediction_scores,) + outputs[2:] - return ((lm_loss,) + output) if lm_loss is not None else output - - return CausalLMOutputWithCrossAttentions( - loss=lm_loss, - logits=prediction_scores, - past_key_values=outputs.past_key_values, - hidden_states=outputs.hidden_states, - attentions=outputs.attentions, - cross_attentions=outputs.cross_attentions, - ) - - def prepare_inputs_for_generation( - self, input_ids, query_embeds, past=None, attention_mask=None, **model_kwargs - ): - # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly - if attention_mask is None: - attention_mask = input_ids.new_ones(input_ids.shape) - query_mask = input_ids.new_ones(query_embeds.shape[:-1]) - attention_mask = torch.cat([query_mask, attention_mask], dim=-1) - - # cut decoder_input_ids if past is used - if past is not None: - input_ids = input_ids[:, -1:] - - return { - "input_ids": input_ids, - "query_embeds": query_embeds, - "attention_mask": attention_mask, - "past_key_values": past, - "encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None), - "encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None), - "is_decoder": True, - } - - def _reorder_cache(self, past, beam_idx): - reordered_past = () - for layer_past in past: - reordered_past += ( - tuple( - past_state.index_select(0, beam_idx) for past_state in layer_past - ), - ) - return reordered_past - - -class BertForMaskedLM(BertPreTrainedModel): - - _keys_to_ignore_on_load_unexpected = [r"pooler"] - _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"] - - def __init__(self, config): - super().__init__(config) - - self.bert = BertModel(config, add_pooling_layer=False) - self.cls = BertOnlyMLMHead(config) - - self.init_weights() - - def get_output_embeddings(self): - return self.cls.predictions.decoder - - def set_output_embeddings(self, new_embeddings): - self.cls.predictions.decoder = new_embeddings - - def forward( - self, - input_ids=None, - attention_mask=None, - position_ids=None, - head_mask=None, - query_embeds=None, - encoder_hidden_states=None, - encoder_attention_mask=None, - labels=None, - output_attentions=None, - output_hidden_states=None, - return_dict=None, - return_logits=False, - is_decoder=False, - ): - r""" - labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): - Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ..., - config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored - (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]`` - """ - - return_dict = ( - return_dict if return_dict is not None else self.config.use_return_dict - ) - - outputs = self.bert( - input_ids, - attention_mask=attention_mask, - position_ids=position_ids, - head_mask=head_mask, - query_embeds=query_embeds, - encoder_hidden_states=encoder_hidden_states, - encoder_attention_mask=encoder_attention_mask, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - is_decoder=is_decoder, - ) - - if query_embeds is not None: - sequence_output = outputs[0][:, query_embeds.shape[1] :, :] - prediction_scores = self.cls(sequence_output) - - if return_logits: - return prediction_scores - - masked_lm_loss = None - if labels is not None: - loss_fct = CrossEntropyLoss() # -100 index = padding token - masked_lm_loss = loss_fct( - prediction_scores.view(-1, self.config.vocab_size), labels.view(-1) - ) - - if not return_dict: - output = (prediction_scores,) + outputs[2:] - return ( - ((masked_lm_loss,) + output) if masked_lm_loss is not None else output - ) - - return MaskedLMOutput( - loss=masked_lm_loss, - logits=prediction_scores, - hidden_states=outputs.hidden_states, - attentions=outputs.attentions, - ) diff --git a/sonique/Video_LLaMA/video_llama/models/__init__.py b/sonique/Video_LLaMA/video_llama/models/__init__.py deleted file mode 100644 index 2a07e2f17ff1d0b22316b8b8e194d55aca31b0cb..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/__init__.py +++ /dev/null @@ -1,201 +0,0 @@ -""" -Adapted from salesforce@LAVIS Vision-CAIR@MiniGPT-4. Below is the original copyright: - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import logging -import torch -from omegaconf import OmegaConf - -from sonique.Video_LLaMA.video_llama.common.registry import registry -from sonique.Video_LLaMA.video_llama.models.base_model import BaseModel -from sonique.Video_LLaMA.video_llama.models.blip2 import Blip2Base -from sonique.Video_LLaMA.video_llama.models.video_llama import VideoLLAMA -from sonique.Video_LLaMA.video_llama.processors.base_processor import BaseProcessor - - -__all__ = [ - "load_model", - "BaseModel", - "Blip2Base", - "VideoLLAMA" -] - - -def load_model(name, model_type, is_eval=False, device="cpu", checkpoint=None): - """ - Load supported models. - - To list all available models and types in registry: - >>> from video_llama.models import model_zoo - >>> print(model_zoo) - - Args: - name (str): name of the model. - model_type (str): type of the model. - is_eval (bool): whether the model is in eval mode. Default: False. - device (str): device to use. Default: "cpu". - checkpoint (str): path or to checkpoint. Default: None. - Note that expecting the checkpoint to have the same keys in state_dict as the model. - - Returns: - model (torch.nn.Module): model. - """ - - model = registry.get_model_class(name).from_pretrained(model_type=model_type) - - if checkpoint is not None: - model.load_checkpoint(checkpoint) - - if is_eval: - model.eval() - - if device == "cpu": - model = model.float() - - return model.to(device) - - -def load_preprocess(config): - """ - Load preprocessor configs and construct preprocessors. - - If no preprocessor is specified, return BaseProcessor, which does not do any preprocessing. - - Args: - config (dict): preprocessor configs. - - Returns: - vis_processors (dict): preprocessors for visual inputs. - txt_processors (dict): preprocessors for text inputs. - - Key is "train" or "eval" for processors used in training and evaluation respectively. - """ - - def _build_proc_from_cfg(cfg): - return ( - registry.get_processor_class(cfg.name).from_config(cfg) - if cfg is not None - else BaseProcessor() - ) - - vis_processors = dict() - txt_processors = dict() - - vis_proc_cfg = config.get("vis_processor") - txt_proc_cfg = config.get("text_processor") - - if vis_proc_cfg is not None: - vis_train_cfg = vis_proc_cfg.get("train") - vis_eval_cfg = vis_proc_cfg.get("eval") - else: - vis_train_cfg = None - vis_eval_cfg = None - - vis_processors["train"] = _build_proc_from_cfg(vis_train_cfg) - vis_processors["eval"] = _build_proc_from_cfg(vis_eval_cfg) - - if txt_proc_cfg is not None: - txt_train_cfg = txt_proc_cfg.get("train") - txt_eval_cfg = txt_proc_cfg.get("eval") - else: - txt_train_cfg = None - txt_eval_cfg = None - - txt_processors["train"] = _build_proc_from_cfg(txt_train_cfg) - txt_processors["eval"] = _build_proc_from_cfg(txt_eval_cfg) - - return vis_processors, txt_processors - - -def load_model_and_preprocess(name, model_type, is_eval=False, device="cpu"): - """ - Load model and its related preprocessors. - - List all available models and types in registry: - >>> from video_llama.models import model_zoo - >>> print(model_zoo) - - Args: - name (str): name of the model. - model_type (str): type of the model. - is_eval (bool): whether the model is in eval mode. Default: False. - device (str): device to use. Default: "cpu". - - Returns: - model (torch.nn.Module): model. - vis_processors (dict): preprocessors for visual inputs. - txt_processors (dict): preprocessors for text inputs. - """ - model_cls = registry.get_model_class(name) - - # load model - model = model_cls.from_pretrained(model_type=model_type) - - if is_eval: - model.eval() - - # load preprocess - cfg = OmegaConf.load(model_cls.default_config_path(model_type)) - if cfg is not None: - preprocess_cfg = cfg.preprocess - - vis_processors, txt_processors = load_preprocess(preprocess_cfg) - else: - vis_processors, txt_processors = None, None - logging.info( - f"""No default preprocess for model {name} ({model_type}). - This can happen if the model is not finetuned on downstream datasets, - or it is not intended for direct use without finetuning. - """ - ) - - if device == "cpu" or device == torch.device("cpu"): - model = model.float() - - return model.to(device), vis_processors, txt_processors - - -class ModelZoo: - """ - A utility class to create string representation of available model architectures and types. - - >>> from video_llama.models import model_zoo - >>> # list all available models - >>> print(model_zoo) - >>> # show total number of models - >>> print(len(model_zoo)) - """ - - def __init__(self) -> None: - self.model_zoo = { - k: list(v.PRETRAINED_MODEL_CONFIG_DICT.keys()) - for k, v in registry.mapping["model_name_mapping"].items() - } - - def __str__(self) -> str: - return ( - "=" * 50 - + "\n" - + f"{'Architectures':<30} {'Types'}\n" - + "=" * 50 - + "\n" - + "\n".join( - [ - f"{name:<30} {', '.join(types)}" - for name, types in self.model_zoo.items() - ] - ) - ) - - def __iter__(self): - return iter(self.model_zoo.items()) - - def __len__(self): - return sum([len(v) for v in self.model_zoo.values()]) - - -model_zoo = ModelZoo() diff --git a/sonique/Video_LLaMA/video_llama/models/base_model.py b/sonique/Video_LLaMA/video_llama/models/base_model.py deleted file mode 100644 index bc08f577d315c1bb78eba98a5b10bbd65e1ea8df..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/base_model.py +++ /dev/null @@ -1,248 +0,0 @@ -""" -Adapted from salesforce@LAVIS. Below is the original copyright: - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import logging -import os - -import numpy as np -import torch -import torch.nn as nn -from sonique.Video_LLaMA.video_llama.common.dist_utils import download_cached_file, is_dist_avail_and_initialized -from sonique.Video_LLaMA.video_llama.common.utils import get_abs_path, is_url -from omegaconf import OmegaConf - - -class BaseModel(nn.Module): - """Base class for models.""" - - def __init__(self): - super().__init__() - - @property - def device(self): - return list(self.parameters())[0].device - - def load_checkpoint(self, url_or_filename): - """ - Load from a finetuned checkpoint. - - This should expect no mismatch in the model keys and the checkpoint keys. - """ - - if is_url(url_or_filename): - cached_file = download_cached_file( - url_or_filename, check_hash=False, progress=True - ) - checkpoint = torch.load(cached_file, map_location="cpu") - elif os.path.isfile(url_or_filename): - checkpoint = torch.load(url_or_filename, map_location="cpu") - else: - raise RuntimeError("checkpoint url or path is invalid") - - if "model" in checkpoint.keys(): - state_dict = checkpoint["model"] - else: - state_dict = checkpoint - - msg = self.load_state_dict(state_dict, strict=False) - - logging.info("Missing keys {}".format(msg.missing_keys)) - logging.info("load checkpoint from %s" % url_or_filename) - - return msg - - @classmethod - def from_pretrained(cls, model_type): - """ - Build a pretrained model from default configuration file, specified by model_type. - - Args: - - model_type (str): model type, specifying architecture and checkpoints. - - Returns: - - model (nn.Module): pretrained or finetuned model, depending on the configuration. - """ - model_cfg = OmegaConf.load(cls.default_config_path(model_type)).model - model = cls.from_config(model_cfg) - - return model - - @classmethod - def default_config_path(cls, model_type): - assert ( - model_type in cls.PRETRAINED_MODEL_CONFIG_DICT - ), "Unknown model type {}".format(model_type) - return get_abs_path(cls.PRETRAINED_MODEL_CONFIG_DICT[model_type]) - - def load_checkpoint_from_config(self, cfg, **kwargs): - """ - Load checkpoint as specified in the config file. - - If load_finetuned is True, load the finetuned model; otherwise, load the pretrained model. - When loading the pretrained model, each task-specific architecture may define their - own load_from_pretrained() method. - """ - load_finetuned = cfg.get("load_finetuned", True) - if load_finetuned: - finetune_path = cfg.get("finetuned", None) - assert ( - finetune_path is not None - ), "Found load_finetuned is True, but finetune_path is None." - self.load_checkpoint(url_or_filename=finetune_path) - else: - # load pre-trained weights - pretrain_path = cfg.get("pretrained", None) - assert "Found load_finetuned is False, but pretrain_path is None." - self.load_from_pretrained(url_or_filename=pretrain_path, **kwargs) - - def before_evaluation(self, **kwargs): - pass - - def show_n_params(self, return_str=True): - tot = 0 - for p in self.parameters(): - w = 1 - for x in p.shape: - w *= x - tot += w - if return_str: - if tot >= 1e6: - return "{:.1f}M".format(tot / 1e6) - else: - return "{:.1f}K".format(tot / 1e3) - else: - return tot - - -class BaseEncoder(nn.Module): - """ - Base class for primitive encoders, such as ViT, TimeSformer, etc. - """ - - def __init__(self): - super().__init__() - - def forward_features(self, samples, **kwargs): - raise NotImplementedError - - @property - def device(self): - return list(self.parameters())[0].device - - -class SharedQueueMixin: - @torch.no_grad() - def _dequeue_and_enqueue(self, image_feat, text_feat, idxs=None): - # gather keys before updating queue - image_feats = concat_all_gather(image_feat) - text_feats = concat_all_gather(text_feat) - - batch_size = image_feats.shape[0] - - ptr = int(self.queue_ptr) - assert self.queue_size % batch_size == 0 # for simplicity - - # replace the keys at ptr (dequeue and enqueue) - self.image_queue[:, ptr : ptr + batch_size] = image_feats.T - self.text_queue[:, ptr : ptr + batch_size] = text_feats.T - - if idxs is not None: - idxs = concat_all_gather(idxs) - self.idx_queue[:, ptr : ptr + batch_size] = idxs.T - - ptr = (ptr + batch_size) % self.queue_size # move pointer - self.queue_ptr[0] = ptr - - -class MomentumDistilationMixin: - @torch.no_grad() - def copy_params(self): - for model_pair in self.model_pairs: - for param, param_m in zip( - model_pair[0].parameters(), model_pair[1].parameters() - ): - param_m.data.copy_(param.data) # initialize - param_m.requires_grad = False # not update by gradient - - @torch.no_grad() - def _momentum_update(self): - for model_pair in self.model_pairs: - for param, param_m in zip( - model_pair[0].parameters(), model_pair[1].parameters() - ): - param_m.data = param_m.data * self.momentum + param.data * ( - 1.0 - self.momentum - ) - - -class GatherLayer(torch.autograd.Function): - """ - Gather tensors from all workers with support for backward propagation: - This implementation does not cut the gradients as torch.distributed.all_gather does. - """ - - @staticmethod - def forward(ctx, x): - output = [ - torch.zeros_like(x) for _ in range(torch.distributed.get_world_size()) - ] - torch.distributed.all_gather(output, x) - return tuple(output) - - @staticmethod - def backward(ctx, *grads): - all_gradients = torch.stack(grads) - torch.distributed.all_reduce(all_gradients) - return all_gradients[torch.distributed.get_rank()] - - -def all_gather_with_grad(tensors): - """ - Performs all_gather operation on the provided tensors. - Graph remains connected for backward grad computation. - """ - # Queue the gathered tensors - world_size = torch.distributed.get_world_size() - # There is no need for reduction in the single-proc case - if world_size == 1: - return tensors - - # tensor_all = GatherLayer.apply(tensors) - tensor_all = GatherLayer.apply(tensors) - - return torch.cat(tensor_all, dim=0) - - -@torch.no_grad() -def concat_all_gather(tensor): - """ - Performs all_gather operation on the provided tensors. - *** Warning ***: torch.distributed.all_gather has no gradient. - """ - # if use distributed training - if not is_dist_avail_and_initialized(): - return tensor - - tensors_gather = [ - torch.ones_like(tensor) for _ in range(torch.distributed.get_world_size()) - ] - torch.distributed.all_gather(tensors_gather, tensor, async_op=False) - - output = torch.cat(tensors_gather, dim=0) - return output - - -def tile(x, dim, n_tile): - init_dim = x.size(dim) - repeat_idx = [1] * x.dim() - repeat_idx[dim] = n_tile - x = x.repeat(*(repeat_idx)) - order_index = torch.LongTensor( - np.concatenate([init_dim * np.arange(n_tile) + i for i in range(init_dim)]) - ) - return torch.index_select(x, dim, order_index.to(x.device)) diff --git a/sonique/Video_LLaMA/video_llama/models/blip2.py b/sonique/Video_LLaMA/video_llama/models/blip2.py deleted file mode 100644 index 8653386b36c4fc5d1313348db516d285cccdbd9a..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/blip2.py +++ /dev/null @@ -1,222 +0,0 @@ -""" -Adapted from salesforce@LAVIS. Below is the original copyright: - Copyright (c) 2023, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" -import contextlib -import logging -import os -import time -import datetime - -import torch -import torch.nn as nn -import torch.distributed as dist -import torch.nn.functional as F - -import sonique.Video_LLaMA.video_llama.common.dist_utils as dist_utils -from sonique.Video_LLaMA.video_llama.common.dist_utils import download_cached_file -from sonique.Video_LLaMA.video_llama.common.utils import is_url -from sonique.Video_LLaMA.video_llama.common.logger import MetricLogger -from sonique.Video_LLaMA.video_llama.models.base_model import BaseModel -from sonique.Video_LLaMA.video_llama.models.Qformer import BertConfig, BertLMHeadModel -from sonique.Video_LLaMA.video_llama.models.eva_vit import create_eva_vit_g -from transformers import BertTokenizer - - -class Blip2Base(BaseModel): - @classmethod - def init_tokenizer(cls): - tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") - tokenizer.add_special_tokens({"bos_token": "[DEC]"}) - return tokenizer - - def maybe_autocast(self, dtype=torch.float16): - # if on cpu, don't use autocast - # if on gpu, use autocast with dtype if provided, otherwise use torch.float16 - enable_autocast = self.device != torch.device("cpu") - - if enable_autocast: - return torch.cuda.amp.autocast(dtype=dtype) - else: - return contextlib.nullcontext() - - @classmethod - def init_Qformer(cls, num_query_token, vision_width, cross_attention_freq=2): - encoder_config = BertConfig.from_pretrained("bert-base-uncased") - encoder_config.encoder_width = vision_width - # insert cross-attention layer every other block - encoder_config.add_cross_attention = True - encoder_config.cross_attention_freq = cross_attention_freq - encoder_config.query_length = num_query_token - Qformer = BertLMHeadModel(config=encoder_config) - query_tokens = nn.Parameter( - torch.zeros(1, num_query_token, encoder_config.hidden_size) - ) - query_tokens.data.normal_(mean=0.0, std=encoder_config.initializer_range) - return Qformer, query_tokens - - @classmethod - def init_vision_encoder( - cls, model_name, img_size, drop_path_rate, use_grad_checkpoint, precision - ): - assert model_name == "eva_clip_g", "vit model must be eva_clip_g for current version of MiniGPT-4" - visual_encoder = create_eva_vit_g( - img_size, drop_path_rate, use_grad_checkpoint, precision - ) - - ln_vision = LayerNorm(visual_encoder.num_features) - return visual_encoder, ln_vision - - def load_from_pretrained(self, url_or_filename): - if is_url(url_or_filename): - cached_file = download_cached_file( - url_or_filename, check_hash=False, progress=True - ) - checkpoint = torch.load(cached_file, map_location="cpu") - elif os.path.isfile(url_or_filename): - checkpoint = torch.load(url_or_filename, map_location="cpu") - else: - raise RuntimeError("checkpoint url or path is invalid") - - state_dict = checkpoint["model"] - - msg = self.load_state_dict(state_dict, strict=False) - - # logging.info("Missing keys {}".format(msg.missing_keys)) - logging.info("load checkpoint from %s" % url_or_filename) - - return msg - - -def disabled_train(self, mode=True): - """Overwrite model.train with this function to make sure train/eval mode - does not change anymore.""" - return self - - -class LayerNorm(nn.LayerNorm): - """Subclass torch's LayerNorm to handle fp16.""" - - def forward(self, x: torch.Tensor): - orig_type = x.dtype - ret = super().forward(x.type(torch.float32)) - return ret.type(orig_type) - - -def compute_sim_matrix(model, data_loader, **kwargs): - k_test = kwargs.pop("k_test") - - metric_logger = MetricLogger(delimiter=" ") - header = "Evaluation:" - - logging.info("Computing features for evaluation...") - start_time = time.time() - - texts = data_loader.dataset.text - num_text = len(texts) - text_bs = 256 - text_ids = [] - text_embeds = [] - text_atts = [] - for i in range(0, num_text, text_bs): - text = texts[i : min(num_text, i + text_bs)] - text_input = model.tokenizer( - text, - padding="max_length", - truncation=True, - max_length=35, - return_tensors="pt", - ).to(model.device) - text_feat = model.forward_text(text_input) - text_embed = F.normalize(model.text_proj(text_feat)) - text_embeds.append(text_embed) - text_ids.append(text_input.input_ids) - text_atts.append(text_input.attention_mask) - - text_embeds = torch.cat(text_embeds, dim=0) - text_ids = torch.cat(text_ids, dim=0) - text_atts = torch.cat(text_atts, dim=0) - - vit_feats = [] - image_embeds = [] - for samples in data_loader: - image = samples["image"] - - image = image.to(model.device) - image_feat, vit_feat = model.forward_image(image) - image_embed = model.vision_proj(image_feat) - image_embed = F.normalize(image_embed, dim=-1) - - vit_feats.append(vit_feat.cpu()) - image_embeds.append(image_embed) - - vit_feats = torch.cat(vit_feats, dim=0) - image_embeds = torch.cat(image_embeds, dim=0) - - sims_matrix = [] - for image_embed in image_embeds: - sim_q2t = image_embed @ text_embeds.t() - sim_i2t, _ = sim_q2t.max(0) - sims_matrix.append(sim_i2t) - sims_matrix = torch.stack(sims_matrix, dim=0) - - score_matrix_i2t = torch.full( - (len(data_loader.dataset.image), len(texts)), -100.0 - ).to(model.device) - - num_tasks = dist_utils.get_world_size() - rank = dist_utils.get_rank() - step = sims_matrix.size(0) // num_tasks + 1 - start = rank * step - end = min(sims_matrix.size(0), start + step) - - for i, sims in enumerate( - metric_logger.log_every(sims_matrix[start:end], 50, header) - ): - topk_sim, topk_idx = sims.topk(k=k_test, dim=0) - image_inputs = vit_feats[start + i].repeat(k_test, 1, 1).to(model.device) - score = model.compute_itm( - image_inputs=image_inputs, - text_ids=text_ids[topk_idx], - text_atts=text_atts[topk_idx], - ).float() - score_matrix_i2t[start + i, topk_idx] = score + topk_sim - - sims_matrix = sims_matrix.t() - score_matrix_t2i = torch.full( - (len(texts), len(data_loader.dataset.image)), -100.0 - ).to(model.device) - - step = sims_matrix.size(0) // num_tasks + 1 - start = rank * step - end = min(sims_matrix.size(0), start + step) - - for i, sims in enumerate( - metric_logger.log_every(sims_matrix[start:end], 50, header) - ): - topk_sim, topk_idx = sims.topk(k=k_test, dim=0) - image_inputs = vit_feats[topk_idx.cpu()].to(model.device) - score = model.compute_itm( - image_inputs=image_inputs, - text_ids=text_ids[start + i].repeat(k_test, 1), - text_atts=text_atts[start + i].repeat(k_test, 1), - ).float() - score_matrix_t2i[start + i, topk_idx] = score + topk_sim - - if dist_utils.is_dist_avail_and_initialized(): - dist.barrier() - torch.distributed.all_reduce( - score_matrix_i2t, op=torch.distributed.ReduceOp.SUM - ) - torch.distributed.all_reduce( - score_matrix_t2i, op=torch.distributed.ReduceOp.SUM - ) - - total_time = time.time() - start_time - total_time_str = str(datetime.timedelta(seconds=int(total_time))) - logging.info("Evaluation time {}".format(total_time_str)) - - return score_matrix_i2t.cpu().numpy(), score_matrix_t2i.cpu().numpy() diff --git a/sonique/Video_LLaMA/video_llama/models/blip2_outputs.py b/sonique/Video_LLaMA/video_llama/models/blip2_outputs.py deleted file mode 100644 index 92d83a0556e6c5c3c0a603279f318605ae25d6d5..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/blip2_outputs.py +++ /dev/null @@ -1,111 +0,0 @@ -""" -Adapted from salesforce@LAVIS. Below is the original copyright: - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -from dataclasses import dataclass -from typing import Optional - -import torch -from transformers.modeling_outputs import ( - ModelOutput, - BaseModelOutputWithPoolingAndCrossAttentions, - CausalLMOutputWithCrossAttentions, -) - - -@dataclass -class BlipSimilarity(ModelOutput): - sim_i2t: torch.FloatTensor = None - sim_t2i: torch.FloatTensor = None - - sim_i2t_m: Optional[torch.FloatTensor] = None - sim_t2i_m: Optional[torch.FloatTensor] = None - - sim_i2t_targets: Optional[torch.FloatTensor] = None - sim_t2i_targets: Optional[torch.FloatTensor] = None - - -@dataclass -class BlipIntermediateOutput(ModelOutput): - """ - Data class for intermediate outputs of BLIP models. - - image_embeds (torch.FloatTensor): Image embeddings, shape (batch_size, num_patches, embed_dim). - text_embeds (torch.FloatTensor): Text embeddings, shape (batch_size, seq_len, embed_dim). - - image_embeds_m (torch.FloatTensor): Image embeddings from momentum visual encoder, shape (batch_size, num_patches, embed_dim). - text_embeds_m (torch.FloatTensor): Text embeddings from momentum text encoder, shape (batch_size, seq_len, embed_dim). - - encoder_output (BaseModelOutputWithPoolingAndCrossAttentions): output from the image-grounded text encoder. - encoder_output_neg (BaseModelOutputWithPoolingAndCrossAttentions): output from the image-grounded text encoder for negative pairs. - - decoder_output (CausalLMOutputWithCrossAttentions): output from the image-grounded text decoder. - decoder_labels (torch.LongTensor): labels for the captioning loss. - - itm_logits (torch.FloatTensor): logits for the image-text matching loss, shape (batch_size * 3, 2). - itm_labels (torch.LongTensor): labels for the image-text matching loss, shape (batch_size * 3,) - - """ - - # uni-modal features - image_embeds: torch.FloatTensor = None - text_embeds: Optional[torch.FloatTensor] = None - - image_embeds_m: Optional[torch.FloatTensor] = None - text_embeds_m: Optional[torch.FloatTensor] = None - - # intermediate outputs of multimodal encoder - encoder_output: Optional[BaseModelOutputWithPoolingAndCrossAttentions] = None - encoder_output_neg: Optional[BaseModelOutputWithPoolingAndCrossAttentions] = None - - itm_logits: Optional[torch.FloatTensor] = None - itm_labels: Optional[torch.LongTensor] = None - - # intermediate outputs of multimodal decoder - decoder_output: Optional[CausalLMOutputWithCrossAttentions] = None - decoder_labels: Optional[torch.LongTensor] = None - - -@dataclass -class BlipOutput(ModelOutput): - # some finetuned models (e.g. BlipVQA) do not compute similarity, thus optional. - sims: Optional[BlipSimilarity] = None - - intermediate_output: BlipIntermediateOutput = None - - loss: Optional[torch.FloatTensor] = None - - loss_itc: Optional[torch.FloatTensor] = None - - loss_itm: Optional[torch.FloatTensor] = None - - loss_lm: Optional[torch.FloatTensor] = None - - -@dataclass -class BlipOutputFeatures(ModelOutput): - """ - Data class of features from BlipFeatureExtractor. - - Args: - image_embeds: (torch.FloatTensor) of shape (batch_size, num_patches+1, embed_dim), optional - image_features: (torch.FloatTensor) of shape (batch_size, num_patches+1, feature_dim), optional - text_embeds: (torch.FloatTensor) of shape (batch_size, sequence_length+1, embed_dim), optional - text_features: (torch.FloatTensor) of shape (batch_size, sequence_length+1, feature_dim), optional - - The first embedding or feature is for the [CLS] token. - - Features are obtained by projecting the corresponding embedding into a normalized low-dimensional space. - """ - - image_embeds: Optional[torch.FloatTensor] = None - image_embeds_proj: Optional[torch.FloatTensor] = None - - text_embeds: Optional[torch.FloatTensor] = None - text_embeds_proj: Optional[torch.FloatTensor] = None - - multimodal_embeds: Optional[torch.FloatTensor] = None diff --git a/sonique/Video_LLaMA/video_llama/models/eva_vit.py b/sonique/Video_LLaMA/video_llama/models/eva_vit.py deleted file mode 100644 index 8b0db61c7fec159e60620920c5d4b292f9e0ee3a..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/eva_vit.py +++ /dev/null @@ -1,442 +0,0 @@ -# Based on EVA, BEIT, timm and DeiT code bases -# https://github.com/baaivision/EVA -# https://github.com/rwightman/pytorch-image-models/tree/master/timm -# https://github.com/microsoft/unilm/tree/master/beit -# https://github.com/facebookresearch/deit/ -# https://github.com/facebookresearch/dino -# --------------------------------------------------------' -import math -from functools import partial - -import torch -import torch.nn as nn -import torch.nn.functional as F -import torch.utils.checkpoint as checkpoint -from timm.models.layers import drop_path, to_2tuple, trunc_normal_ -from timm.models.registry import register_model - -from sonique.Video_LLaMA.video_llama.common.dist_utils import download_cached_file - -def _cfg(url='', **kwargs): - return { - 'url': url, - 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None, - 'crop_pct': .9, 'interpolation': 'bicubic', - 'mean': (0.5, 0.5, 0.5), 'std': (0.5, 0.5, 0.5), - **kwargs - } - - -class DropPath(nn.Module): - """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). - """ - def __init__(self, drop_prob=None): - super(DropPath, self).__init__() - self.drop_prob = drop_prob - - def forward(self, x): - return drop_path(x, self.drop_prob, self.training) - - def extra_repr(self) -> str: - return 'p={}'.format(self.drop_prob) - - -class Mlp(nn.Module): - def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): - super().__init__() - out_features = out_features or in_features - hidden_features = hidden_features or in_features - self.fc1 = nn.Linear(in_features, hidden_features) - self.act = act_layer() - self.fc2 = nn.Linear(hidden_features, out_features) - self.drop = nn.Dropout(drop) - - def forward(self, x): - x = self.fc1(x) - x = self.act(x) - # x = self.drop(x) - # commit this for the orignal BERT implement - x = self.fc2(x) - x = self.drop(x) - return x - - -class Attention(nn.Module): - def __init__( - self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., - proj_drop=0., window_size=None, attn_head_dim=None): - super().__init__() - self.num_heads = num_heads - head_dim = dim // num_heads - if attn_head_dim is not None: - head_dim = attn_head_dim - all_head_dim = head_dim * self.num_heads - self.scale = qk_scale or head_dim ** -0.5 - - self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False) - if qkv_bias: - self.q_bias = nn.Parameter(torch.zeros(all_head_dim)) - self.v_bias = nn.Parameter(torch.zeros(all_head_dim)) - else: - self.q_bias = None - self.v_bias = None - - if window_size: - self.window_size = window_size - self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3 - self.relative_position_bias_table = nn.Parameter( - torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH - # cls to token & token 2 cls & cls to cls - - # get pair-wise relative position index for each token inside the window - coords_h = torch.arange(window_size[0]) - coords_w = torch.arange(window_size[1]) - coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww - coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww - relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww - relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 - relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0 - relative_coords[:, :, 1] += window_size[1] - 1 - relative_coords[:, :, 0] *= 2 * window_size[1] - 1 - relative_position_index = \ - torch.zeros(size=(window_size[0] * window_size[1] + 1, ) * 2, dtype=relative_coords.dtype) - relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww - relative_position_index[0, 0:] = self.num_relative_distance - 3 - relative_position_index[0:, 0] = self.num_relative_distance - 2 - relative_position_index[0, 0] = self.num_relative_distance - 1 - - self.register_buffer("relative_position_index", relative_position_index) - else: - self.window_size = None - self.relative_position_bias_table = None - self.relative_position_index = None - - self.attn_drop = nn.Dropout(attn_drop) - self.proj = nn.Linear(all_head_dim, dim) - self.proj_drop = nn.Dropout(proj_drop) - - def forward(self, x, rel_pos_bias=None): - B, N, C = x.shape - qkv_bias = None - if self.q_bias is not None: - qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias)) - # qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) - qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias) - qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) - q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) - - q = q * self.scale - attn = (q @ k.transpose(-2, -1)) - - if self.relative_position_bias_table is not None: - relative_position_bias = \ - self.relative_position_bias_table[self.relative_position_index.view(-1)].view( - self.window_size[0] * self.window_size[1] + 1, - self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH - relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww - attn = attn + relative_position_bias.unsqueeze(0) - - if rel_pos_bias is not None: - attn = attn + rel_pos_bias - - attn = attn.softmax(dim=-1) - attn = self.attn_drop(attn) - - x = (attn @ v).transpose(1, 2).reshape(B, N, -1) - x = self.proj(x) - x = self.proj_drop(x) - return x - - -class Block(nn.Module): - - def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., - drop_path=0., init_values=None, act_layer=nn.GELU, norm_layer=nn.LayerNorm, - window_size=None, attn_head_dim=None): - super().__init__() - self.norm1 = norm_layer(dim) - self.attn = Attention( - dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, - attn_drop=attn_drop, proj_drop=drop, window_size=window_size, attn_head_dim=attn_head_dim) - # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here - self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() - self.norm2 = norm_layer(dim) - mlp_hidden_dim = int(dim * mlp_ratio) - self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) - - if init_values is not None and init_values > 0: - self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True) - self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True) - else: - self.gamma_1, self.gamma_2 = None, None - - def forward(self, x, rel_pos_bias=None): - if self.gamma_1 is None: - x = x + self.drop_path(self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias)) - x = x + self.drop_path(self.mlp(self.norm2(x))) - else: - x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias)) - x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x))) - return x - - -class PatchEmbed(nn.Module): - """ Image to Patch Embedding - """ - def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768): - super().__init__() - img_size = to_2tuple(img_size) - patch_size = to_2tuple(patch_size) - num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0]) - self.patch_shape = (img_size[0] // patch_size[0], img_size[1] // patch_size[1]) - self.img_size = img_size - self.patch_size = patch_size - self.num_patches = num_patches - - self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) - - def forward(self, x, **kwargs): - B, C, H, W = x.shape - # FIXME look at relaxing size constraints - assert H == self.img_size[0] and W == self.img_size[1], \ - f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." - x = self.proj(x).flatten(2).transpose(1, 2) - return x - - -class RelativePositionBias(nn.Module): - - def __init__(self, window_size, num_heads): - super().__init__() - self.window_size = window_size - self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3 - self.relative_position_bias_table = nn.Parameter( - torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH - # cls to token & token 2 cls & cls to cls - - # get pair-wise relative position index for each token inside the window - coords_h = torch.arange(window_size[0]) - coords_w = torch.arange(window_size[1]) - coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww - coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww - relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww - relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 - relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0 - relative_coords[:, :, 1] += window_size[1] - 1 - relative_coords[:, :, 0] *= 2 * window_size[1] - 1 - relative_position_index = \ - torch.zeros(size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype) - relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww - relative_position_index[0, 0:] = self.num_relative_distance - 3 - relative_position_index[0:, 0] = self.num_relative_distance - 2 - relative_position_index[0, 0] = self.num_relative_distance - 1 - - self.register_buffer("relative_position_index", relative_position_index) - - # trunc_normal_(self.relative_position_bias_table, std=.02) - - def forward(self): - relative_position_bias = \ - self.relative_position_bias_table[self.relative_position_index.view(-1)].view( - self.window_size[0] * self.window_size[1] + 1, - self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH - return relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww - - -class VisionTransformer(nn.Module): - """ Vision Transformer with support for patch or hybrid CNN input stage - """ - def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12, - num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0., - drop_path_rate=0., norm_layer=nn.LayerNorm, init_values=None, - use_abs_pos_emb=True, use_rel_pos_bias=False, use_shared_rel_pos_bias=False, - use_mean_pooling=True, init_scale=0.001, use_checkpoint=False): - super().__init__() - self.image_size = img_size - self.num_classes = num_classes - self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models - - self.patch_embed = PatchEmbed( - img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) - num_patches = self.patch_embed.num_patches - - self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) - if use_abs_pos_emb: - self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) - else: - self.pos_embed = None - self.pos_drop = nn.Dropout(p=drop_rate) - - if use_shared_rel_pos_bias: - self.rel_pos_bias = RelativePositionBias(window_size=self.patch_embed.patch_shape, num_heads=num_heads) - else: - self.rel_pos_bias = None - self.use_checkpoint = use_checkpoint - - dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule - self.use_rel_pos_bias = use_rel_pos_bias - self.blocks = nn.ModuleList([ - Block( - dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, - drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, - init_values=init_values, window_size=self.patch_embed.patch_shape if use_rel_pos_bias else None) - for i in range(depth)]) -# self.norm = nn.Identity() if use_mean_pooling else norm_layer(embed_dim) -# self.fc_norm = norm_layer(embed_dim) if use_mean_pooling else None -# self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity() - - if self.pos_embed is not None: - trunc_normal_(self.pos_embed, std=.02) - trunc_normal_(self.cls_token, std=.02) - # trunc_normal_(self.mask_token, std=.02) -# if isinstance(self.head, nn.Linear): -# trunc_normal_(self.head.weight, std=.02) - self.apply(self._init_weights) - self.fix_init_weight() -# if isinstance(self.head, nn.Linear): -# self.head.weight.data.mul_(init_scale) -# self.head.bias.data.mul_(init_scale) - - def fix_init_weight(self): - def rescale(param, layer_id): - param.div_(math.sqrt(2.0 * layer_id)) - - for layer_id, layer in enumerate(self.blocks): - rescale(layer.attn.proj.weight.data, layer_id + 1) - rescale(layer.mlp.fc2.weight.data, layer_id + 1) - - def _init_weights(self, m): - if isinstance(m, nn.Linear): - trunc_normal_(m.weight, std=.02) - if isinstance(m, nn.Linear) and m.bias is not None: - nn.init.constant_(m.bias, 0) - elif isinstance(m, nn.LayerNorm): - nn.init.constant_(m.bias, 0) - nn.init.constant_(m.weight, 1.0) - - def get_classifier(self): - return self.head - - def reset_classifier(self, num_classes, global_pool=''): - self.num_classes = num_classes - self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() - - def forward_features(self, x): - x = self.patch_embed(x) - batch_size, seq_len, _ = x.size() - - cls_tokens = self.cls_token.expand(batch_size, -1, -1) # stole cls_tokens impl from Phil Wang, thanks - x = torch.cat((cls_tokens, x), dim=1) - if self.pos_embed is not None: - x = x + self.pos_embed - x = self.pos_drop(x) - - rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None - for blk in self.blocks: - if self.use_checkpoint: - x = checkpoint.checkpoint(blk, x, rel_pos_bias) - else: - x = blk(x, rel_pos_bias) - return x -# x = self.norm(x) - -# if self.fc_norm is not None: -# t = x[:, 1:, :] -# return self.fc_norm(t.mean(1)) -# else: -# return x[:, 0] - - def forward(self, x): - x = self.forward_features(x) -# x = self.head(x) - return x - - def get_intermediate_layers(self, x): - x = self.patch_embed(x) - batch_size, seq_len, _ = x.size() - - cls_tokens = self.cls_token.expand(batch_size, -1, -1) # stole cls_tokens impl from Phil Wang, thanks - x = torch.cat((cls_tokens, x), dim=1) - if self.pos_embed is not None: - x = x + self.pos_embed - x = self.pos_drop(x) - - features = [] - rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None - for blk in self.blocks: - x = blk(x, rel_pos_bias) - features.append(x) - - return features - - -def interpolate_pos_embed(model, checkpoint_model): - if 'pos_embed' in checkpoint_model: - pos_embed_checkpoint = checkpoint_model['pos_embed'].float() - embedding_size = pos_embed_checkpoint.shape[-1] - num_patches = model.patch_embed.num_patches - num_extra_tokens = model.pos_embed.shape[-2] - num_patches - # height (== width) for the checkpoint position embedding - orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5) - # height (== width) for the new position embedding - new_size = int(num_patches ** 0.5) - # class_token and dist_token are kept unchanged - if orig_size != new_size: - print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, new_size, new_size)) - extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens] - # only the position tokens are interpolated - pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:] - pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2) - pos_tokens = torch.nn.functional.interpolate( - pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False) - pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2) - new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1) - checkpoint_model['pos_embed'] = new_pos_embed - - -def convert_weights_to_fp16(model: nn.Module): - """Convert applicable model parameters to fp16""" - - def _convert_weights_to_fp16(l): - if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): - l.weight.data = l.weight.data.half() - if l.bias is not None: - l.bias.data = l.bias.data.half() - -# if isinstance(l, (nn.MultiheadAttention, Attention)): -# for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]: -# tensor = getattr(l, attr) -# if tensor is not None: -# tensor.data = tensor.data.half() - - model.apply(_convert_weights_to_fp16) - - -def create_eva_vit_g(img_size=224,drop_path_rate=0.4,use_checkpoint=False,precision="fp16"): - model = VisionTransformer( - img_size=img_size, - patch_size=14, - use_mean_pooling=False, - embed_dim=1408, - depth=39, - num_heads=1408//88, - mlp_ratio=4.3637, - qkv_bias=True, - drop_path_rate=drop_path_rate, - norm_layer=partial(nn.LayerNorm, eps=1e-6), - use_checkpoint=use_checkpoint, - ) - url = "https://storage.googleapis.com/sfr-vision-language-research/LAVIS/models/BLIP2/eva_vit_g.pth" - cached_file = download_cached_file( - url, check_hash=False, progress=True - ) - state_dict = torch.load(cached_file, map_location="cpu") - interpolate_pos_embed(model,state_dict) - - incompatible_keys = model.load_state_dict(state_dict, strict=False) -# print(incompatible_keys) - - if precision == "fp16": -# model.to("cuda") - convert_weights_to_fp16(model) - return model \ No newline at end of file diff --git a/sonique/Video_LLaMA/video_llama/models/modeling_llama.py b/sonique/Video_LLaMA/video_llama/models/modeling_llama.py deleted file mode 100644 index 12d980e189d902fb1a6d9ea05dc3ca91959b1c8c..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/modeling_llama.py +++ /dev/null @@ -1,755 +0,0 @@ -# This script is based on https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py - -""" PyTorch LLaMA model.""" -import math -from typing import List, Optional, Tuple, Union - -import torch -import torch.utils.checkpoint -from torch import nn -from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss - -from transformers.activations import ACT2FN -from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast -from transformers.modeling_utils import PreTrainedModel -from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings -from transformers.models.llama.configuration_llama import LlamaConfig - - -logger = logging.get_logger(__name__) - -_CONFIG_FOR_DOC = "LlamaConfig" - - -# Copied from transformers.models.bart.modeling_bart._make_causal_mask -def _make_causal_mask( - input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0 -): - """ - Make causal mask used for bi-directional self-attention. - """ - bsz, tgt_len = input_ids_shape - mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device) - mask_cond = torch.arange(mask.size(-1), device=device) - mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) - mask = mask.to(dtype) - - if past_key_values_length > 0: - mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1) - return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length) - - -# Copied from transformers.models.bart.modeling_bart._expand_mask -def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): - """ - Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. - """ - bsz, src_len = mask.size() - tgt_len = tgt_len if tgt_len is not None else src_len - - expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) - - inverted_mask = 1.0 - expanded_mask - - return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min) - - -class LlamaRMSNorm(nn.Module): - def __init__(self, hidden_size, eps=1e-6): - """ - LlamaRMSNorm is equivalent to T5LayerNorm - """ - super().__init__() - self.weight = nn.Parameter(torch.ones(hidden_size)) - self.variance_epsilon = eps - - def forward(self, hidden_states): - variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True) - hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) - - # convert into half-precision if necessary - if self.weight.dtype in [torch.float16, torch.bfloat16]: - hidden_states = hidden_states.to(self.weight.dtype) - - return self.weight * hidden_states - - -class LlamaRotaryEmbedding(torch.nn.Module): - def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None): - super().__init__() - inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim)) - self.register_buffer("inv_freq", inv_freq) - - # Build here to make `torch.jit.trace` work. - self.max_seq_len_cached = max_position_embeddings - t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype) - freqs = torch.einsum("i,j->ij", t, self.inv_freq) - # Different from paper, but it uses a different permutation in order to obtain the same calculation - emb = torch.cat((freqs, freqs), dim=-1) - self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False) - self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False) - - def forward(self, x, seq_len=None): - # x: [bs, num_attention_heads, seq_len, head_size] - # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case. - if seq_len > self.max_seq_len_cached: - self.max_seq_len_cached = seq_len - t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype) - freqs = torch.einsum("i,j->ij", t, self.inv_freq) - # Different from paper, but it uses a different permutation in order to obtain the same calculation - emb = torch.cat((freqs, freqs), dim=-1).to(x.device) - self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False) - self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False) - return ( - self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype), - self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype), - ) - - -def rotate_half(x): - """Rotates half the hidden dims of the input.""" - x1 = x[..., : x.shape[-1] // 2] - x2 = x[..., x.shape[-1] // 2 :] - return torch.cat((-x2, x1), dim=-1) - - -def apply_rotary_pos_emb(q, k, cos, sin, position_ids): - gather_indices = position_ids[:, None, :, None] # [bs, 1, seq_len, 1] - gather_indices = gather_indices.repeat(1, cos.shape[1], 1, cos.shape[3]) - cos = torch.gather(cos.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices) - sin = torch.gather(sin.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices) - q_embed = (q * cos) + (rotate_half(q) * sin) - k_embed = (k * cos) + (rotate_half(k) * sin) - return q_embed, k_embed - - -class LlamaMLP(nn.Module): - def __init__( - self, - hidden_size: int, - intermediate_size: int, - hidden_act: str, - ): - super().__init__() - self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False) - self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False) - self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False) - self.act_fn = ACT2FN[hidden_act] - - def forward(self, x): - return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) - - -class LlamaAttention(nn.Module): - """Multi-headed attention from 'Attention Is All You Need' paper""" - - def __init__(self, config: LlamaConfig): - super().__init__() - self.config = config - self.hidden_size = config.hidden_size - self.num_heads = config.num_attention_heads - self.head_dim = self.hidden_size // self.num_heads - self.max_position_embeddings = config.max_position_embeddings - - if (self.head_dim * self.num_heads) != self.hidden_size: - raise ValueError( - f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}" - f" and `num_heads`: {self.num_heads})." - ) - self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False) - self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False) - self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False) - self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False) - self.rotary_emb = LlamaRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings) - - def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): - return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() - - def forward( - self, - hidden_states: torch.Tensor, - attention_mask: Optional[torch.Tensor] = None, - position_ids: Optional[torch.LongTensor] = None, - past_key_value: Optional[Tuple[torch.Tensor]] = None, - output_attentions: bool = False, - use_cache: bool = False, - ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: - bsz, q_len, _ = hidden_states.size() - - query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) - key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) - value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) - - kv_seq_len = key_states.shape[-2] - if past_key_value is not None: - kv_seq_len += past_key_value[0].shape[-2] - cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) - query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) - # [bsz, nh, t, hd] - - if past_key_value is not None: - # reuse k, v, self_attention - key_states = torch.cat([past_key_value[0], key_states], dim=2) - value_states = torch.cat([past_key_value[1], value_states], dim=2) - - past_key_value = (key_states, value_states) if use_cache else None - - attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) - - if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len): - raise ValueError( - f"Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is" - f" {attn_weights.size()}" - ) - - if attention_mask is not None: - if attention_mask.size() != (bsz, 1, q_len, kv_seq_len): - raise ValueError( - f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}" - ) - attn_weights = attn_weights + attention_mask - attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min)) - - # upcast attention to fp32 - attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) - attn_output = torch.matmul(attn_weights, value_states) - - if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim): - raise ValueError( - f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is" - f" {attn_output.size()}" - ) - - attn_output = attn_output.transpose(1, 2) - attn_output = attn_output.reshape(bsz, q_len, self.hidden_size) - - attn_output = self.o_proj(attn_output) - - if not output_attentions: - attn_weights = None - - return attn_output, attn_weights, past_key_value - - -class LlamaDecoderLayer(nn.Module): - def __init__(self, config: LlamaConfig): - super().__init__() - self.hidden_size = config.hidden_size - self.self_attn = LlamaAttention(config=config) - self.mlp = LlamaMLP( - hidden_size=self.hidden_size, - intermediate_size=config.intermediate_size, - hidden_act=config.hidden_act, - ) - self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) - self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) - - def forward( - self, - hidden_states: torch.Tensor, - attention_mask: Optional[torch.Tensor] = None, - position_ids: Optional[torch.LongTensor] = None, - past_key_value: Optional[Tuple[torch.Tensor]] = None, - output_attentions: Optional[bool] = False, - use_cache: Optional[bool] = False, - ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: - """ - Args: - hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` - attention_mask (`torch.FloatTensor`, *optional*): attention mask of size - `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. - output_attentions (`bool`, *optional*): - Whether or not to return the attentions tensors of all attention layers. See `attentions` under - returned tensors for more detail. - use_cache (`bool`, *optional*): - If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding - (see `past_key_values`). - past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states - """ - - residual = hidden_states - - hidden_states = self.input_layernorm(hidden_states) - - # Self Attention - hidden_states, self_attn_weights, present_key_value = self.self_attn( - hidden_states=hidden_states, - attention_mask=attention_mask, - position_ids=position_ids, - past_key_value=past_key_value, - output_attentions=output_attentions, - use_cache=use_cache, - ) - hidden_states = residual + hidden_states - - # Fully Connected - residual = hidden_states - hidden_states = self.post_attention_layernorm(hidden_states) - hidden_states = self.mlp(hidden_states) - hidden_states = residual + hidden_states - - outputs = (hidden_states,) - - if output_attentions: - outputs += (self_attn_weights,) - - if use_cache: - outputs += (present_key_value,) - - return outputs - - -LLAMA_START_DOCSTRING = r""" - This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the - library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads - etc.) - - This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. - Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage - and behavior. - - Parameters: - config ([`LlamaConfig`]): - Model configuration class with all the parameters of the model. Initializing with a config file does not - load the weights associated with the model, only the configuration. Check out the - [`~PreTrainedModel.from_pretrained`] method to load the model weights. -""" - - -@add_start_docstrings( - "The bare LLaMA Model outputting raw hidden-states without any specific head on top.", - LLAMA_START_DOCSTRING, -) -class LlamaPreTrainedModel(PreTrainedModel): - config_class = LlamaConfig - base_model_prefix = "model" - supports_gradient_checkpointing = True - _no_split_modules = ["LlamaDecoderLayer"] - _keys_to_ignore_on_load_unexpected = [r"decoder\.version"] - - def _init_weights(self, module): - std = self.config.initializer_range - if isinstance(module, nn.Linear): - module.weight.data.normal_(mean=0.0, std=std) - if module.bias is not None: - module.bias.data.zero_() - elif isinstance(module, nn.Embedding): - module.weight.data.normal_(mean=0.0, std=std) - if module.padding_idx is not None: - module.weight.data[module.padding_idx].zero_() - - def _set_gradient_checkpointing(self, module, value=False): - if isinstance(module, LlamaModel): - module.gradient_checkpointing = value - - -LLAMA_INPUTS_DOCSTRING = r""" - Args: - input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): - Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide - it. - - Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and - [`PreTrainedTokenizer.__call__`] for details. - - [What are input IDs?](../glossary#input-ids) - attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): - Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - - - 1 for tokens that are **not masked**, - - 0 for tokens that are **masked**. - - [What are attention masks?](../glossary#attention-mask) - - Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and - [`PreTrainedTokenizer.__call__`] for details. - - If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see - `past_key_values`). - - If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] - and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more - information on the default strategy. - - - 1 indicates the head is **not masked**, - - 0 indicates the head is **masked**. - position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): - Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, - config.n_positions - 1]`. - - [What are position IDs?](../glossary#position-ids) - past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape - `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape - `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. - - Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention - blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. - - If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that - don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all - `decoder_input_ids` of shape `(batch_size, sequence_length)`. - inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): - Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This - is useful if you want more control over how to convert `input_ids` indices into associated vectors than the - model's internal embedding lookup matrix. - use_cache (`bool`, *optional*): - If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see - `past_key_values`). - output_attentions (`bool`, *optional*): - Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned - tensors for more detail. - output_hidden_states (`bool`, *optional*): - Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for - more detail. - return_dict (`bool`, *optional*): - Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. -""" - - -@add_start_docstrings( - "The bare LLaMA Model outputting raw hidden-states without any specific head on top.", - LLAMA_START_DOCSTRING, -) -class LlamaModel(LlamaPreTrainedModel): - """ - Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`] - - Args: - config: LlamaConfig - """ - - def __init__(self, config: LlamaConfig): - super().__init__(config) - self.padding_idx = config.pad_token_id - self.vocab_size = config.vocab_size - - self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) - self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)]) - self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) - - self.gradient_checkpointing = False - # Initialize weights and apply final processing - self.post_init() - - def get_input_embeddings(self): - return self.embed_tokens - - def set_input_embeddings(self, value): - self.embed_tokens = value - - # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask - def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length): - # create causal mask - # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] - combined_attention_mask = None - if input_shape[-1] > 1: - combined_attention_mask = _make_causal_mask( - input_shape, - inputs_embeds.dtype, - device=inputs_embeds.device, - past_key_values_length=past_key_values_length, - ) - - if attention_mask is not None: - # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] - expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to( - inputs_embeds.device - ) - combined_attention_mask = ( - expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask - ) - - return combined_attention_mask - - @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING) - def forward( - self, - input_ids: torch.LongTensor = None, - attention_mask: Optional[torch.Tensor] = None, - position_ids: Optional[torch.LongTensor] = None, - past_key_values: Optional[List[torch.FloatTensor]] = None, - inputs_embeds: Optional[torch.FloatTensor] = None, - query_embeds: Optional[torch.FloatTensor] = None, - use_cache: Optional[bool] = None, - output_attentions: Optional[bool] = None, - output_hidden_states: Optional[bool] = None, - return_dict: Optional[bool] = None, - ) -> Union[Tuple, BaseModelOutputWithPast]: - output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions - output_hidden_states = ( - output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states - ) - use_cache = use_cache if use_cache is not None else self.config.use_cache - - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - # retrieve input_ids and inputs_embeds - if input_ids is not None and inputs_embeds is not None: - raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") - elif input_ids is not None: - batch_size, seq_length = input_ids.shape - elif inputs_embeds is not None: - batch_size, seq_length, _ = inputs_embeds.shape - else: - raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") - - if inputs_embeds is None: - inputs_embeds = self.embed_tokens(input_ids) - if query_embeds is not None: - inputs_embeds = torch.cat([query_embeds, inputs_embeds], dim=1) - batch_size, seq_length, _ = inputs_embeds.shape - - seq_length_with_past = seq_length - past_key_values_length = 0 - - if past_key_values is not None: - past_key_values_length = past_key_values[0][0].shape[2] - seq_length_with_past = seq_length_with_past + past_key_values_length - - if position_ids is None: - device = input_ids.device if input_ids is not None else inputs_embeds.device - position_ids = torch.arange( - past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device - ) - position_ids = position_ids.unsqueeze(0).view(-1, seq_length) - else: - position_ids = position_ids.view(-1, seq_length).long() - - # embed positions - if attention_mask is None: - attention_mask = torch.ones( - (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device - ) - attention_mask = self._prepare_decoder_attention_mask( - attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length - ) - - hidden_states = inputs_embeds - - if self.gradient_checkpointing and self.training: - if use_cache: - logger.warning_once( - "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." - ) - use_cache = False - - # decoder layers - all_hidden_states = () if output_hidden_states else None - all_self_attns = () if output_attentions else None - next_decoder_cache = () if use_cache else None - - for idx, decoder_layer in enumerate(self.layers): - if output_hidden_states: - all_hidden_states += (hidden_states,) - - past_key_value = past_key_values[idx] if past_key_values is not None else None - - if self.gradient_checkpointing and self.training: - - def create_custom_forward(module): - def custom_forward(*inputs): - # None for past_key_value - return module(*inputs, output_attentions, None) - - return custom_forward - - layer_outputs = torch.utils.checkpoint.checkpoint( - create_custom_forward(decoder_layer), - hidden_states, - attention_mask, - position_ids, - None, - ) - else: - layer_outputs = decoder_layer( - hidden_states, - attention_mask=attention_mask, - position_ids=position_ids, - past_key_value=past_key_value, - output_attentions=output_attentions, - use_cache=use_cache, - ) - - hidden_states = layer_outputs[0] - - if use_cache: - next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) - - if output_attentions: - all_self_attns += (layer_outputs[1],) - - hidden_states = self.norm(hidden_states) - - # add hidden states from the last decoder layer - if output_hidden_states: - all_hidden_states += (hidden_states,) - - next_cache = next_decoder_cache if use_cache else None - if not return_dict: - return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) - return BaseModelOutputWithPast( - last_hidden_state=hidden_states, - past_key_values=next_cache, - hidden_states=all_hidden_states, - attentions=all_self_attns, - ) - - -class LlamaForCausalLM(LlamaPreTrainedModel): - def __init__(self, config): - super().__init__(config) - self.model = LlamaModel(config) - - self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) - - # Initialize weights and apply final processing - self.post_init() - - def get_input_embeddings(self): - return self.model.embed_tokens - - def set_input_embeddings(self, value): - self.model.embed_tokens = value - - def get_output_embeddings(self): - return self.lm_head - - def set_output_embeddings(self, new_embeddings): - self.lm_head = new_embeddings - - def set_decoder(self, decoder): - self.model = decoder - - def get_decoder(self): - return self.model - - @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING) - @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) - def forward( - self, - input_ids: torch.LongTensor = None, - attention_mask: Optional[torch.Tensor] = None, - position_ids: Optional[torch.LongTensor] = None, - past_key_values: Optional[List[torch.FloatTensor]] = None, - inputs_embeds: Optional[torch.FloatTensor] = None, - query_embeds: Optional[torch.FloatTensor] = None, - labels: Optional[torch.LongTensor] = None, - use_cache: Optional[bool] = None, - output_attentions: Optional[bool] = None, - output_hidden_states: Optional[bool] = None, - return_dict: Optional[bool] = None, - ) -> Union[Tuple, CausalLMOutputWithPast]: - r""" - Args: - labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): - Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., - config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored - (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. - - Returns: - - Example: - - ```python - >>> from transformers import AutoTokenizer, LlamaForCausalLM - - >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS) - >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER) - - >>> prompt = "Hey, are you consciours? Can you talk to me?" - >>> inputs = tokenizer(prompt, return_tensors="pt") - - >>> # Generate - >>> generate_ids = model.generate(inputs.input_ids, max_length=30) - >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] - "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you." - ```""" - - output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions - output_hidden_states = ( - output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states - ) - return_dict = return_dict if return_dict is not None else self.config.use_return_dict - - # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) - outputs = self.model( - input_ids=input_ids, - attention_mask=attention_mask, - position_ids=position_ids, - past_key_values=past_key_values, - inputs_embeds=inputs_embeds, - query_embeds=query_embeds, - use_cache=use_cache, - output_attentions=output_attentions, - output_hidden_states=output_hidden_states, - return_dict=return_dict, - ) - - hidden_states = outputs[0] - logits = self.lm_head(hidden_states) - - loss = None - if labels is not None: - # Shift so that tokens < n predict n - shift_logits = logits[..., :-1, :].contiguous() - shift_labels = labels[..., 1:].contiguous() - # Flatten the tokens - loss_fct = CrossEntropyLoss() - shift_logits = shift_logits.view(-1, self.config.vocab_size) - shift_labels = shift_labels.view(-1) - # Enable model parallelism - shift_labels = shift_labels.to(shift_logits.device) - loss = loss_fct(shift_logits, shift_labels) - - if not return_dict: - output = (logits,) + outputs[1:] - return (loss,) + output if loss is not None else output - - return CausalLMOutputWithPast( - loss=loss, - logits=logits, - past_key_values=outputs.past_key_values, - hidden_states=outputs.hidden_states, - attentions=outputs.attentions, - ) - - def prepare_inputs_for_generation( - self, input_ids, query_embeds=None, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs - ): - if past_key_values: - input_ids = input_ids[:, -1:] - - position_ids = kwargs.get("position_ids", None) - if attention_mask is not None and position_ids is None: - # create position_ids on the fly for batch generation - position_ids = attention_mask.long().cumsum(-1) - 1 - position_ids.masked_fill_(attention_mask == 0, 1) - if past_key_values: - position_ids = position_ids[:, -1].unsqueeze(-1) - query_embeds = None - - # if `inputs_embeds` are passed, we only want to use them in the 1st generation step - if inputs_embeds is not None and past_key_values is None: - model_inputs = {"inputs_embeds": inputs_embeds} - else: - model_inputs = {"input_ids": input_ids} - - model_inputs.update( - { - "position_ids": position_ids, - "query_embeds": query_embeds, - "past_key_values": past_key_values, - "use_cache": kwargs.get("use_cache"), - "attention_mask": attention_mask, - } - ) - return model_inputs - - @staticmethod - def _reorder_cache(past_key_values, beam_idx): - reordered_past = () - for layer_past in past_key_values: - reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),) - return reordered_past - diff --git a/sonique/Video_LLaMA/video_llama/models/video_llama.py b/sonique/Video_LLaMA/video_llama/models/video_llama.py deleted file mode 100644 index 4e38211585ef20082dc25a87e0d055d5457366aa..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/models/video_llama.py +++ /dev/null @@ -1,620 +0,0 @@ -import logging -import random - -import torch -from torch.cuda.amp import autocast as autocast -import torch.nn as nn - -from sonique.Video_LLaMA.video_llama.common.registry import registry -from sonique.Video_LLaMA.video_llama.models.blip2 import Blip2Base, disabled_train -from sonique.Video_LLaMA.video_llama.models.modeling_llama import LlamaForCausalLM -# from video_llama.models.Qformer import BertEncoder -from transformers import LlamaTokenizer,BertConfig, AutoModelForCausalLM, BitsAndBytesConfig -# from transformers.models.bert.modeling_bert import BertEncoder -import einops -import copy -from sonique.Video_LLaMA.video_llama.models.Qformer import BertConfig, BertLMHeadModel -from sonique.Video_LLaMA.video_llama.models.ImageBind.models.imagebind_model import ImageBindModel,ModalityType -from sonique.Video_LLaMA.video_llama.models.ImageBind.models import imagebind_model -# from flamingo_pytorch import PerceiverResampler -@registry.register_model("video_llama") -class VideoLLAMA(Blip2Base): - """ - BLIP2 GPT-LLAMA model. - """ - - PRETRAINED_MODEL_CONFIG_DICT = { - "pretrain_vicuna": "configs/models/video_llama.yaml", - "pretrain_llama_v2": "configs/models/video_llama.yaml", - } - - @classmethod - def init_video_Qformer(cls, num_query_token, vision_width,num_hidden_layers =2): - encoder_config = BertConfig.from_pretrained("bert-base-uncased") - encoder_config.num_hidden_layers = num_hidden_layers - encoder_config.encoder_width = vision_width - # insert cross-attention layer every other block - encoder_config.add_cross_attention = True - encoder_config.cross_attention_freq = 1 - encoder_config.query_length = num_query_token - Qformer = BertLMHeadModel(config=encoder_config) - query_tokens = nn.Parameter( - torch.zeros(1, num_query_token, encoder_config.hidden_size) - ) - query_tokens.data.normal_(mean=0.0, std=encoder_config.initializer_range) - return Qformer, query_tokens - - def __init__( - self, - vit_model="eva_clip_g", - q_former_model="https://storage.googleapis.com/sfr-vision-language-research/LAVIS/models/BLIP2/blip2_pretrained_flant5xxl.pth", - img_size=224, - drop_path_rate=0, - use_grad_checkpoint=False, - vit_precision="fp16", - freeze_vit=True, - freeze_qformer=True, - num_query_token=32, - llama_model="", - prompt_path="", - prompt_template="", - max_txt_len=32, - end_sym='\n', - low_resource=False, # use 8 bit and put vit in cpu - device_8bit=0, # the device of 8bit model should be set when loading and cannot be changed anymore. - - frozen_llama_proj=True, - frozen_video_Qformer=True, - frozen_audio_Qformer=True, - - llama_proj_model='', - fusion_header_type= "seqTransf", - max_frame_pos= 32, - fusion_head_layers = 2, - num_video_query_token = 32, - num_audio_query_token = 8, - imagebind_ckpt_path = '/mnt/workspace/ckpt', - equip_audio_branch = True - ): - super().__init__() - - self.tokenizer = self.init_tokenizer() - self.low_resource = low_resource - - print('Loading VIT') - self.visual_encoder, self.ln_vision = self.init_vision_encoder( - vit_model, img_size, drop_path_rate, use_grad_checkpoint, vit_precision - ) - if freeze_vit: - for name, param in self.visual_encoder.named_parameters(): - param.requires_grad = False - self.visual_encoder = self.visual_encoder.eval() - self.visual_encoder.train = disabled_train - for name, param in self.ln_vision.named_parameters(): - param.requires_grad = False - self.ln_vision = self.ln_vision.eval() - self.ln_vision.train = disabled_train - logging.info("freeze vision encoder") - print('Loading VIT Done') - - print('Loading Q-Former') - self.Qformer, self.query_tokens = self.init_Qformer( - num_query_token, self.visual_encoder.num_features - ) - self.Qformer.cls = None - self.Qformer.bert.embeddings.word_embeddings = None - self.Qformer.bert.embeddings.position_embeddings = None - for layer in self.Qformer.bert.encoder.layer: - layer.output = None - layer.intermediate = None - self.load_from_pretrained(url_or_filename=q_former_model) - - if freeze_qformer: - for name, param in self.Qformer.named_parameters(): - param.requires_grad = False - self.Qformer = self.Qformer.eval() - self.Qformer.train = disabled_train - self.query_tokens.requires_grad = False - logging.info("freeze Qformer") - logging.info('Loading Q-Former Done') - - logging.info('Loading LLAMA Tokenizer') - self.llama_tokenizer = LlamaTokenizer.from_pretrained(llama_model, use_fast=False) - if self.llama_tokenizer.pad_token is None: - self.llama_tokenizer.pad_token = self.llama_tokenizer.unk_token - DEFAULT_IMAGE_PATCH_TOKEN = '' - DEFAULT_AUDIO_PATCH_TOKEN = '' - self.llama_tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True) - self.llama_tokenizer.add_tokens([DEFAULT_AUDIO_PATCH_TOKEN], special_tokens=True) - - self.IMAGE_PATCH_TOKEN_ID = self.llama_tokenizer.get_vocab()[DEFAULT_IMAGE_PATCH_TOKEN] - self.AUDIO_PATCH_TOKEN_ID = self.llama_tokenizer.get_vocab()[DEFAULT_AUDIO_PATCH_TOKEN] - - logging.info('Loading LLAMA Model') - if self.low_resource: - self.llama_model = AutoModelForCausalLM.from_pretrained( - llama_model, - # quantization_config=BitsAndBytesConfig( - # load_in_4bit=True, - # bnb_4bit_quant_type="nf4", - # bnb_4bit_use_double_quant=True, - # bnb_4bit_compute_dtype=torch.float16 - # ) - torch_dtype=torch.bfloat16, - load_in_8bit=True, - device_map={'': device_8bit} - ) - else: - self.llama_model = LlamaForCausalLM.from_pretrained( - llama_model, - torch_dtype=torch.float16, - ) - - for name, param in self.llama_model.named_parameters(): - param.requires_grad = False - logging.info('Loading LLAMA Done') - - - logging.info('Loading LLAMA proj') - self.llama_proj = nn.Linear( - self.Qformer.config.hidden_size, self.llama_model.config.hidden_size - ) - if llama_proj_model: - print("load llama proj weight: {}".format(llama_proj_model)) - llama_proj_weight = torch.load(llama_proj_model, map_location="cpu") - msg = self.load_state_dict(llama_proj_weight['model'], strict=False) - - if frozen_llama_proj: - # todo frozen llama_proj - for name, param in self.llama_proj.named_parameters(): - param.requires_grad = False - logging.info('LLAMA proj is frozen') - else: - for name, param in self.llama_proj.named_parameters(): - param.requires_grad = True - logging.info('LLAMA proj is not frozen') - - logging.info('Loading llama_proj Done') - - self.max_txt_len = max_txt_len - self.end_sym = end_sym - - if prompt_path: - with open(prompt_path, 'r') as f: - raw_prompts = f.read().splitlines() - filted_prompts = [raw_prompt for raw_prompt in raw_prompts if "" in raw_prompt] - self.prompt_list = [prompt_template.format(p) for p in filted_prompts] - print('Load {} training prompts'.format(len(self.prompt_list))) - print('Prompt Example \n{}'.format(random.choice(self.prompt_list))) - else: - self.prompt_list = [] - - self.video_frame_position_embedding = nn.Embedding(max_frame_pos, self.Qformer.config.hidden_size) - - self.num_video_query_token = num_video_query_token - self.video_Qformer,self.video_query_tokens = self.init_video_Qformer(num_query_token = num_video_query_token,\ - vision_width=self.Qformer.config.hidden_size, num_hidden_layers =2) - - self.video_Qformer.cls = None - self.video_Qformer.bert.embeddings.word_embeddings = None - self.video_Qformer.bert.embeddings.position_embeddings = None - for layer in self.video_Qformer.bert.encoder.layer: - layer.output = None - layer.intermediate = None - - - if frozen_video_Qformer: - # todo frozen llama_proj - for name, param in self.video_Qformer.named_parameters(): - param.requires_grad = False - for name, param in self.video_frame_position_embedding.named_parameters(): - param.requires_grad = False - self.video_query_tokens.requires_grad = False - - logging.info('video_Qformer is frozen') - else: - for name, param in self.video_Qformer.named_parameters(): - param.requires_grad = True - for name, param in self.video_frame_position_embedding.named_parameters(): - param.requires_grad = True - self.video_query_tokens.requires_grad = True - logging.info('video_Qformer is not frozen') - - if frozen_video_Qformer and (not frozen_audio_Qformer): - self.train_flag = 1 # 只训练audio_Qformer - elif not(frozen_video_Qformer) and frozen_audio_Qformer: - self.train_flag = 0 # 训练video_Qformer - elif not(frozen_video_Qformer) and not(frozen_audio_Qformer): - self.train_flag = 2 # video_Qformer and AL trained - else: - self.train_flag = 3 - - if equip_audio_branch: - print (f'Initializing audio encoder from {imagebind_ckpt_path} ...') - self.audio_encoder,self.audio_hidden_size = \ - imagebind_model.imagebind_huge() - self.audio_encoder.load_state_dict(torch.load("{}/imagebind_huge.pth".format(imagebind_ckpt_path))) - # free vision encoder - for name, param in self.audio_encoder.named_parameters(): - param.requires_grad = False - self.audio_encoder.eval() - print ('audio encoder initialized.') - - self.num_audio_query_token = num_audio_query_token - self.audio_Qformer,self.audio_query_tokens = self.init_video_Qformer(num_query_token = self.num_audio_query_token,\ - vision_width=self.audio_hidden_size, num_hidden_layers =2) - self.audio_Qformer.cls = None - self.audio_Qformer.bert.embeddings.word_embeddings = None - self.audio_Qformer.bert.embeddings.position_embeddings = None - for layer in self.audio_Qformer.bert.encoder.layer: - layer.output = None - layer.intermediate = None - self.audio_llama_proj = nn.Linear( - self.audio_Qformer.config.hidden_size, self.llama_model.config.hidden_size - ) - self.audio_position_embedding = nn.Embedding(8, self.audio_hidden_size) - - if frozen_audio_Qformer: - # todo frozen llama_proj - for name, param in self.audio_Qformer.named_parameters(): - param.requires_grad = False - self.audio_query_tokens.requires_grad = False - for name, param in self.audio_llama_proj.named_parameters(): - param.requires_grad = False - for name, param in self.audio_position_embedding.named_parameters(): - param.requires_grad = False - logging.info('audio_Qformer and audio-LLAMA proj is frozen') - else: - for name, param in self.audio_Qformer.named_parameters(): - param.requires_grad = True - self.audio_query_tokens.requires_grad = True - for name, param in self.audio_llama_proj.named_parameters(): - param.requires_grad = True - for name, param in self.audio_position_embedding.named_parameters(): - param.requires_grad = True - logging.info('audio_Qformer is not frozen') - - - # self.audio_hidden_size - def vit_to_cpu(self): - self.ln_vision.to("cpu") - self.ln_vision.float() - self.visual_encoder.to("cpu") - self.visual_encoder.float() - - def encode_videoQformer_visual(self, image): - device = image.device - - # input shape b,c,t,h,w - batch_size,_,time_length,_,_ = image.size() - image = einops.rearrange(image, 'b c t h w -> (b t) c h w') - with self.maybe_autocast(): - # embed image features with blip2, out: (b t) q h - image_embeds = self.ln_vision(self.visual_encoder(image)).to(device) - image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(device) - - query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1) - query_output = self.Qformer.bert( - query_embeds=query_tokens, - encoder_hidden_states=image_embeds, - encoder_attention_mask=image_atts, - return_dict=True, - ) - - # add frame_pos embedding - position_ids = torch.arange(time_length, dtype=torch.long, device=query_tokens.device) - position_ids = position_ids.unsqueeze(0).expand(batch_size, -1) - frame_position_embeddings = self.video_frame_position_embedding(position_ids) - q_hidden_state = query_output.last_hidden_state - - frame_position_embeddings = frame_position_embeddings.unsqueeze(-2) - frame_hidden_state = einops.rearrange(q_hidden_state, '(b t) q h -> b t q h',b=batch_size,t=time_length) - frame_hidden_state = frame_position_embeddings + frame_hidden_state - - # frame attention - frame_hidden_state = einops.rearrange(frame_hidden_state, 'b t q h -> b (t q) h',b=batch_size,t=time_length) - frame_atts = torch.ones(frame_hidden_state.size()[:-1], dtype=torch.long).to(device) - video_query_tokens = self.video_query_tokens.expand(frame_hidden_state.shape[0], -1, -1) - - video_query_output = self.video_Qformer.bert( - query_embeds=video_query_tokens, - encoder_hidden_states=frame_hidden_state, - encoder_attention_mask=frame_atts, - return_dict=True, - ) - video_hidden = video_query_output.last_hidden_state - - inputs_llama = self.llama_proj(video_hidden) - atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(image_embeds.device) - return inputs_llama, atts_llama - - - def prompt_wrap(self, img_embeds, atts_img, prompt): - if prompt: - batch_size = img_embeds.shape[0] - # print(prompt) - p_before, p_after = prompt.split('') - p_before_tokens = self.llama_tokenizer( - p_before, return_tensors="pt", add_special_tokens=False).to(img_embeds.device) - p_after_tokens = self.llama_tokenizer( - p_after, return_tensors="pt", add_special_tokens=False).to(img_embeds.device) - p_before_embeds = self.llama_model.model.embed_tokens(p_before_tokens.input_ids).expand(batch_size, -1, -1) - p_after_embeds = self.llama_model.model.embed_tokens(p_after_tokens.input_ids).expand(batch_size, -1, -1) - wrapped_img_embeds = torch.cat([p_before_embeds, img_embeds, p_after_embeds], dim=1) - wrapped_atts_img = atts_img[:, :1].expand(-1, wrapped_img_embeds.shape[1]) - - return wrapped_img_embeds, wrapped_atts_img - else: - return img_embeds, atts_img - # input audio shape [b t c h w] - def encode_audioQformer(self, audio,modality_type=ModalityType.AUDIO): - device = audio.device - with self.maybe_autocast(): - audio_feature, audio_imagebind_finalout = self.audio_encoder.get_audio_feature(audio,modality_type=modality_type) - batch_size,time_length = audio.size()[:2] - - - position_ids = torch.arange(time_length, dtype=torch.long, device=device) - position_ids = position_ids.unsqueeze(0).expand(batch_size, -1) - - audio_position_embeddings = self.audio_position_embedding(position_ids) - audio_imagebind_finalout = audio_imagebind_finalout + audio_position_embeddings - - audio_query_tokens = self.audio_query_tokens.expand(audio_imagebind_finalout.shape[0], -1, -1) - frame_atts = torch.ones(audio_imagebind_finalout.size()[:-1], dtype=torch.long).to(device) - - audio_query_output = self.audio_Qformer.bert( - query_embeds=audio_query_tokens, #[32,768] - encoder_hidden_states=audio_imagebind_finalout, - encoder_attention_mask=frame_atts, - return_dict=True, - ) - audio_hidden = audio_query_output.last_hidden_state - - inputs_llama = self.audio_llama_proj(audio_hidden) - atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(device) - - return inputs_llama, atts_llama - - def encode_videoQformer_audiovideo(self, image, audio): - device = image.device - - # input shape b,c,t,h,w - batch_size,_,time_length,_,_ = image.size() - image = einops.rearrange(image, 'b c t h w -> (b t) c h w') - with self.maybe_autocast(): - # embed image features with blip2, out: (b t) q h - image_embeds = self.ln_vision(self.visual_encoder(image)).to(device) - image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(device) - - query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1) - query_output = self.Qformer.bert( - query_embeds=query_tokens, - encoder_hidden_states=image_embeds, - encoder_attention_mask=image_atts, - return_dict=True, - ) - - # add frame_pos embedding - position_ids = torch.arange(time_length, dtype=torch.long, device=query_tokens.device) - position_ids = position_ids.unsqueeze(0).expand(batch_size, -1) - frame_position_embeddings = self.video_frame_position_embedding(position_ids) - q_hidden_state = query_output.last_hidden_state - - frame_position_embeddings = frame_position_embeddings.unsqueeze(-2) - frame_hidden_state = einops.rearrange(q_hidden_state, '(b t) q h -> b t q h',b=batch_size,t=time_length) - frame_hidden_state = frame_position_embeddings + frame_hidden_state - - # encode audio - audio_feature, audio_imagebind_finalout = self.audio_encoder.get_audio_feature(audio,modality_type=ModalityType.AUDIO) # [batch,8*1,768] 8*32, 768 - audio_frame_position_embeddings = frame_position_embeddings.squeeze(-2) - audio_feature = audio_feature + audio_frame_position_embeddings - - # frame attention a - frame_hidden_state = einops.rearrange(frame_hidden_state, 'b t q h -> b (t q) h',b=batch_size,t=time_length) - frame_hidden_state = torch.cat([frame_hidden_state,audio_feature],dim = 1) - video_query_tokens = self.video_query_tokens.expand(frame_hidden_state.shape[0], -1, -1) - frame_atts = torch.ones(frame_hidden_state.size()[:-1], dtype=torch.long).to(device) - - video_query_output = self.video_Qformer.bert( - query_embeds=video_query_tokens, #[32,768] - encoder_hidden_states=frame_hidden_state, - encoder_attention_mask=frame_atts, - return_dict=True, - ) - video_hidden = video_query_output.last_hidden_state - - inputs_llama = self.llama_proj(video_hidden) - atts_llama = torch.ones(inputs_llama.size()[:-1], dtype=torch.long).to(image_embeds.device) - - return inputs_llama, atts_llama - - def forward(self, samples): - if 'conv_type' in samples.keys() and samples['conv_type']=='multi': - - im_patch_token_id = self.IMAGE_PATCH_TOKEN_ID - image = samples["images"] - input_ids = samples['input_ids'] - if len(image.size())==4: - time = 1 - image = einops.repeat(image, 'b c h w -> b c t h w',t = time) - - if self.train_flag == 0: - num_patch_tokens = self.num_video_query_token - img_embeds, atts_img = self.encode_videoQformer_visual(image) - elif self.train_flag == 1: - num_patch_tokens = self.num_audio_query_token - image = einops.rearrange(image, 'b c t h w -> b t c h w') - img_embeds, atts_img = self.encode_audioQformer(image, modality_type=ModalityType.VISION) - - temp_input_ids = copy.deepcopy(input_ids) - temp_input_ids[temp_input_ids == im_patch_token_id] = 0 - temp_input_embedding = self.llama_model.model.embed_tokens(temp_input_ids) - - new_input_embeds=[] - cur_image_idx = 0 - for cur_input_ids, cur_input_embeds in zip(input_ids, temp_input_embedding): - cur_image_features = img_embeds[cur_image_idx] - - if (cur_input_ids == im_patch_token_id).sum() != num_patch_tokens: - raise ValueError("The number of image patch tokens should be the same as the number of image patches.") - masked_indices = torch.where(cur_input_ids == im_patch_token_id)[0] - mask_index_start = masked_indices[0] - if (masked_indices != torch.arange(mask_index_start, mask_index_start+num_patch_tokens, device=masked_indices.device, dtype=masked_indices.dtype)).any(): - raise ValueError("The image patch tokens should be consecutive.") - - cur_new_input_embeds = torch.cat((cur_input_embeds[:mask_index_start], cur_image_features, cur_input_embeds[mask_index_start+num_patch_tokens:]), dim=0) - new_input_embeds.append(cur_new_input_embeds) - - cur_image_idx+=1 - inputs_embeds = torch.stack(new_input_embeds, dim=0) - targets = samples['labels'] - attention_mask = samples['attention_mask'] - with self.maybe_autocast(): - outputs = self.llama_model( - inputs_embeds=inputs_embeds, - attention_mask=attention_mask, - return_dict=True, - labels=targets, - ) - loss = outputs.loss - return {"loss": loss} - else: - image = samples["image"] - - if len(image.size()) != 5: - time = 1 - image = einops.repeat(image, 'b c h w -> b c t h w',t = time) - - if self.train_flag == 1: - image = einops.rearrange(image, 'b c t h w -> b t c h w') - img_embeds, atts_img = self.encode_audioQformer(image, modality_type=ModalityType.VISION) - else: - img_embeds, atts_img = self.encode_videoQformer_visual(image) - - if self.prompt_list: - prompt = random.choice(self.prompt_list) - img_embeds, atts_img = self.prompt_wrap(img_embeds, atts_img, prompt) - - - self.llama_tokenizer.padding_side = "right" - - text = [t + self.end_sym for t in samples["text_input"]] - - to_regress_tokens = self.llama_tokenizer( - text, - return_tensors="pt", - padding="longest", - truncation=True, - max_length=self.max_txt_len, - add_special_tokens=False - ).to(image.device) - - targets = to_regress_tokens.input_ids.masked_fill( - to_regress_tokens.input_ids == self.llama_tokenizer.pad_token_id, -100 - ) - - empty_targets = ( - torch.ones([atts_img.shape[0], atts_img.shape[1]+1], - dtype=torch.long).to(image.device).fill_(-100) # plus one for bos - ) - targets = torch.cat([empty_targets, targets], dim=1) - - batch_size = img_embeds.shape[0] - bos = torch.ones([batch_size, 1], - dtype=to_regress_tokens.input_ids.dtype, - device=to_regress_tokens.input_ids.device) * self.llama_tokenizer.bos_token_id - bos_embeds = self.llama_model.model.embed_tokens(bos) - atts_bos = atts_img[:, :1] - - to_regress_embeds = self.llama_model.model.embed_tokens(to_regress_tokens.input_ids) - inputs_embeds = torch.cat([bos_embeds, img_embeds, to_regress_embeds], dim=1) - attention_mask = torch.cat([atts_bos, atts_img, to_regress_tokens.attention_mask], dim=1) - - with self.maybe_autocast(): - outputs = self.llama_model( - inputs_embeds=inputs_embeds, - attention_mask=attention_mask, - return_dict=True, - labels=targets, - ) - loss = outputs.loss - - return {"loss": loss} - - @classmethod - def from_config(cls, cfg): - vit_model = cfg.get("vit_model", "eva_clip_g") - q_former_model = cfg.get("q_former_model", "https://storage.googleapis.com/sfr-vision-language-research/LAVIS/models/BLIP2/blip2_pretrained_flant5xxl.pth") - img_size = cfg.get("image_size") - num_query_token = cfg.get("num_query_token") - llama_model = cfg.get("llama_model") - - drop_path_rate = cfg.get("drop_path_rate", 0) - use_grad_checkpoint = cfg.get("use_grad_checkpoint", False) - vit_precision = cfg.get("vit_precision", "fp16") - freeze_vit = cfg.get("freeze_vit", True) - freeze_qformer = cfg.get("freeze_qformer", True) - low_resource = cfg.get("low_resource", False) - device_8bit = cfg.get("device_8bit", 0) - - prompt_path = cfg.get("prompt_path", "") - prompt_template = cfg.get("prompt_template", "") - max_txt_len = cfg.get("max_txt_len", 32) - end_sym = cfg.get("end_sym", '\n') - - frozen_llama_proj = cfg.get("frozen_llama_proj", True) - frozen_video_Qformer = cfg.get("frozen_video_Qformer", True) - frozen_audio_Qformer = cfg.get("frozen_audio_Qformer", True) - - llama_proj_model = cfg.get("llama_proj_model", '') - - fusion_header_type = cfg.get("fusion_header_type", 'seqTransf') - max_frame_pos = cfg.get("max_frame_pos", 32) - fusion_head_layers = cfg.get("fusion_head_layers", 2) - num_video_query_token = cfg.get("num_video_query_token", 32) - - equip_audio_branch= cfg.get("equip_audio_branch", True) - num_audio_query_token = cfg.get("num_audio_query_token", 8) - imagebind_ckpt_path = cfg.get("imagebind_ckpt_path", '/mnt/workspace/ckpt') - model = cls( - vit_model=vit_model, - q_former_model=q_former_model, - img_size=img_size, - drop_path_rate=drop_path_rate, - use_grad_checkpoint=use_grad_checkpoint, - vit_precision=vit_precision, - freeze_vit=freeze_vit, - freeze_qformer=freeze_qformer, - num_query_token=num_query_token, - llama_model=llama_model, - prompt_path=prompt_path, - prompt_template=prompt_template, - max_txt_len=max_txt_len, - end_sym=end_sym, - low_resource=low_resource, - device_8bit=device_8bit, - fusion_header_type=fusion_header_type, - max_frame_pos=max_frame_pos, - fusion_head_layers=fusion_head_layers, - frozen_llama_proj=frozen_llama_proj, - frozen_video_Qformer=frozen_video_Qformer, - frozen_audio_Qformer=frozen_audio_Qformer, - num_video_query_token=num_video_query_token, - num_audio_query_token = num_audio_query_token, - imagebind_ckpt_path = imagebind_ckpt_path, - equip_audio_branch = equip_audio_branch, - llama_proj_model = llama_proj_model - ) - - ckpt_path = cfg.get("ckpt", "") # load weights of MiniGPT-4 - if ckpt_path: - print("Load first Checkpoint: {}".format(ckpt_path)) - ckpt = torch.load(ckpt_path, map_location="cpu") - msg = model.load_state_dict(ckpt['model'], strict=False) - ckpt_path_2 = cfg.get("ckpt_2", "") - if ckpt_path_2: - print("Load second Checkpoint: {}".format(ckpt_path_2)) - ckpt = torch.load(ckpt_path_2, map_location="cpu") - msg = model.load_state_dict(ckpt['model'], strict=False) - return model diff --git a/sonique/Video_LLaMA/video_llama/processors/.ipynb_checkpoints/video_processor-checkpoint.py b/sonique/Video_LLaMA/video_llama/processors/.ipynb_checkpoints/video_processor-checkpoint.py deleted file mode 100644 index ac0f3a9d56aef53de0ee9f2ee3d6d2cda0ea1674..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/processors/.ipynb_checkpoints/video_processor-checkpoint.py +++ /dev/null @@ -1,243 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import torch -from video_llama.common.registry import registry -from decord import VideoReader -import decord -import numpy as np -from video_llama.processors import transforms_video -from video_llama.processors.base_processor import BaseProcessor -from video_llama.processors.randaugment import VideoRandomAugment -from video_llama.processors import functional_video as F -from omegaconf import OmegaConf -from torchvision import transforms -import random as rnd -MAX_INT = registry.get("MAX_INT") - -def load_video(video_path, n_frms=MAX_INT, height=-1, width=-1, sampling="uniform"): - vr = VideoReader(uri=video_path, height=height, width=width) - - vlen = len(vr) - start, end = 0, vlen - - n_frms = min(n_frms, vlen) - - if sampling == "uniform": - indices = np.arange(start, end, vlen / n_frms).astype(int).tolist() - elif sampling == "headtail": - indices_h = sorted(rnd.sample(range(vlen // 2), n_frms // 2)) - indices_t = sorted(rnd.sample(range(vlen // 2, vlen), n_frms // 2)) - indices = indices_h + indices_t - else: - raise NotImplementedError - - # get_batch -> T, H, W, C - print(video_path) - print(indices) - print(vr.get_batch(indices)) - - frms = vr.get_batch(indices).permute(3, 0, 1, 2).float() # (C, T, H, W) - # print(111) - return frms - -class AlproVideoBaseProcessor(BaseProcessor): - def __init__(self, mean=None, std=None, n_frms=MAX_INT): - if mean is None: - mean = (0.48145466, 0.4578275, 0.40821073) - if std is None: - std = (0.26862954, 0.26130258, 0.27577711) - - self.normalize = transforms_video.NormalizeVideo(mean, std) - - self.n_frms = n_frms - - -class ToUint8(object): - def __init__(self): - pass - - def __call__(self, tensor): - return tensor.to(torch.uint8) - - def __repr__(self): - return self.__class__.__name__ - - -class ToTHWC(object): - """ - Args: - clip (torch.tensor, dtype=torch.uint8): Size is (C, T, H, W) - Return: - clip (torch.tensor, dtype=torch.float): Size is (T, H, W, C) - """ - - def __init__(self): - pass - - def __call__(self, tensor): - return tensor.permute(1, 2, 3, 0) - - def __repr__(self): - return self.__class__.__name__ - - -class ResizeVideo(object): - def __init__(self, target_size, interpolation_mode="bilinear"): - self.target_size = target_size - self.interpolation_mode = interpolation_mode - - def __call__(self, clip): - """ - Args: - clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) - Returns: - torch.tensor: central cropping of video clip. Size is - (C, T, crop_size, crop_size) - """ - return F.resize(clip, self.target_size, self.interpolation_mode) - - def __repr__(self): - return self.__class__.__name__ + "(resize_size={0})".format(self.target_size) - - -@registry.register_processor("alpro_video_train") -class AlproVideoTrainProcessor(AlproVideoBaseProcessor): - def __init__( - self, - image_size=384, - mean=None, - std=None, - min_scale=0.5, - max_scale=1.0, - n_frms=MAX_INT, - ): - super().__init__(mean=mean, std=std, n_frms=n_frms) - - self.image_size = image_size - - self.transform = transforms.Compose( - [ - # Video size is (C, T, H, W) - transforms_video.RandomResizedCropVideo( - image_size, - scale=(min_scale, max_scale), - interpolation_mode="bicubic", - ), - transforms_video.RandomHorizontalFlipVideo(), - ToTHWC(), # C, T, H, W -> T, H, W, C - VideoRandomAugment( - 2, - 5, - augs=[ - "Identity", - "AutoContrast", - "Brightness", - "Sharpness", - "Equalize", - "ShearX", - "ShearY", - "TranslateX", - "TranslateY", - "Rotate", - ], - ), - ToUint8(), - transforms_video.ToTensorVideo(), # T, H, W, C -> C, T, H, W - self.normalize, - ] - ) - - def __call__(self, vpath): - """ - Args: - clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) - Returns: - torch.tensor: video clip after transforms. Size is (C, T, size, size). - """ - clip = load_video( - video_path=vpath, - n_frms=self.n_frms, - height=self.image_size, - width=self.image_size, - sampling="headtail", - ) - - return self.transform(clip) - - @classmethod - def from_config(cls, cfg=None): - if cfg is None: - cfg = OmegaConf.create() - - image_size = cfg.get("image_size", 256) - - mean = cfg.get("mean", None) - std = cfg.get("std", None) - - min_scale = cfg.get("min_scale", 0.5) - max_scale = cfg.get("max_scale", 1.0) - - n_frms = cfg.get("n_frms", MAX_INT) - - return cls( - image_size=image_size, - mean=mean, - std=std, - min_scale=min_scale, - max_scale=max_scale, - n_frms=n_frms, - ) - - -@registry.register_processor("alpro_video_eval") -class AlproVideoEvalProcessor(AlproVideoBaseProcessor): - def __init__(self, image_size=256, mean=None, std=None, n_frms=MAX_INT): - super().__init__(mean=mean, std=std, n_frms=n_frms) - - self.image_size = image_size - - # Input video size is (C, T, H, W) - self.transform = transforms.Compose( - [ - # frames will be resized during decord loading. - ToUint8(), # C, T, H, W - ToTHWC(), # T, H, W, C - transforms_video.ToTensorVideo(), # C, T, H, W - self.normalize, # C, T, H, W - ] - ) - - def __call__(self, vpath): - """ - Args: - clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) - Returns: - torch.tensor: video clip after transforms. Size is (C, T, size, size). - """ - clip = load_video( - video_path=vpath, - n_frms=self.n_frms, - height=self.image_size, - width=self.image_size, - ) - - return self.transform(clip) - - @classmethod - def from_config(cls, cfg=None): - if cfg is None: - cfg = OmegaConf.create() - - image_size = cfg.get("image_size", 256) - - mean = cfg.get("mean", None) - std = cfg.get("std", None) - - n_frms = cfg.get("n_frms", MAX_INT) - - return cls(image_size=image_size, mean=mean, std=std, n_frms=n_frms) diff --git a/sonique/Video_LLaMA/video_llama/processors/__init__.py b/sonique/Video_LLaMA/video_llama/processors/__init__.py deleted file mode 100644 index 3079e947f0c1474eac32a8bfafeca450556ad29b..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/processors/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -from sonique.Video_LLaMA.video_llama.processors.base_processor import BaseProcessor -from sonique.Video_LLaMA.video_llama.processors.blip_processors import ( - Blip2ImageTrainProcessor, - Blip2ImageEvalProcessor, - BlipCaptionProcessor, -) -from sonique.Video_LLaMA.video_llama.processors.video_processor import ( - AlproVideoTrainProcessor, - AlproVideoEvalProcessor -) -from sonique.Video_LLaMA.video_llama.common.registry import registry - -__all__ = [ - "BaseProcessor", - "Blip2ImageTrainProcessor", - "Blip2ImageEvalProcessor", - "BlipCaptionProcessor", - "AlproVideoTrainProcessor", - "AlproVideoEvalProcessor", -] - - -def load_processor(name, cfg=None): - """ - Example - - >>> processor = load_processor("alpro_video_train", cfg=None) - """ - processor = registry.get_processor_class(name).from_config(cfg) - - return processor diff --git a/sonique/Video_LLaMA/video_llama/processors/base_processor.py b/sonique/Video_LLaMA/video_llama/processors/base_processor.py deleted file mode 100644 index 39b33cdf8fcd97cfd3e4a5fbece6593357af9d41..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/processors/base_processor.py +++ /dev/null @@ -1,26 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -from omegaconf import OmegaConf - - -class BaseProcessor: - def __init__(self): - self.transform = lambda x: x - return - - def __call__(self, item): - return self.transform(item) - - @classmethod - def from_config(cls, cfg=None): - return cls() - - def build(self, **kwargs): - cfg = OmegaConf.create(kwargs) - - return self.from_config(cfg) diff --git a/sonique/Video_LLaMA/video_llama/processors/blip_processors.py b/sonique/Video_LLaMA/video_llama/processors/blip_processors.py deleted file mode 100644 index a4404f4cf5375e46c0f56c643679949fdb697b2e..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/processors/blip_processors.py +++ /dev/null @@ -1,142 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import re - -from sonique.Video_LLaMA.video_llama.common.registry import registry -from sonique.Video_LLaMA.video_llama.processors.base_processor import BaseProcessor -from sonique.Video_LLaMA.video_llama.processors.randaugment import RandomAugment -from omegaconf import OmegaConf -from torchvision import transforms -from torchvision.transforms.functional import InterpolationMode - - -class BlipImageBaseProcessor(BaseProcessor): - def __init__(self, mean=None, std=None): - if mean is None: - mean = (0.48145466, 0.4578275, 0.40821073) - if std is None: - std = (0.26862954, 0.26130258, 0.27577711) - - self.normalize = transforms.Normalize(mean, std) - - -@registry.register_processor("blip_caption") -class BlipCaptionProcessor(BaseProcessor): - def __init__(self, prompt="", max_words=50): - self.prompt = prompt - self.max_words = max_words - - def __call__(self, caption): - caption = self.prompt + self.pre_caption(caption) - - return caption - - @classmethod - def from_config(cls, cfg=None): - if cfg is None: - cfg = OmegaConf.create() - - prompt = cfg.get("prompt", "") - max_words = cfg.get("max_words", 50) - - return cls(prompt=prompt, max_words=max_words) - - def pre_caption(self, caption): - caption = re.sub( - r"([.!\"()*#:;~])", - " ", - caption.lower(), - ) - caption = re.sub( - r"\s{2,}", - " ", - caption, - ) - caption = caption.rstrip("\n") - caption = caption.strip(" ") - - # truncate caption - caption_words = caption.split(" ") - if len(caption_words) > self.max_words: - caption = " ".join(caption_words[: self.max_words]) - - return caption - - -@registry.register_processor("blip2_image_train") -class Blip2ImageTrainProcessor(BlipImageBaseProcessor): - def __init__(self, image_size=224, mean=None, std=None, min_scale=0.5, max_scale=1.0): - super().__init__(mean=mean, std=std) - - self.transform = transforms.Compose( - [ - transforms.RandomResizedCrop( - image_size, - scale=(min_scale, max_scale), - interpolation=InterpolationMode.BICUBIC, - ), - transforms.ToTensor(), - self.normalize, - ] - ) - - def __call__(self, item): - return self.transform(item) - - @classmethod - def from_config(cls, cfg=None): - if cfg is None: - cfg = OmegaConf.create() - - image_size = cfg.get("image_size", 224) - - mean = cfg.get("mean", None) - std = cfg.get("std", None) - - min_scale = cfg.get("min_scale", 0.5) - max_scale = cfg.get("max_scale", 1.0) - - return cls( - image_size=image_size, - mean=mean, - std=std, - min_scale=min_scale, - max_scale=max_scale, - ) - - -@registry.register_processor("blip2_image_eval") -class Blip2ImageEvalProcessor(BlipImageBaseProcessor): - def __init__(self, image_size=224, mean=None, std=None): - super().__init__(mean=mean, std=std) - - self.transform = transforms.Compose( - [ - transforms.Resize( - (image_size, image_size), interpolation=InterpolationMode.BICUBIC - ), - transforms.ToTensor(), - self.normalize, - ] - ) - - def __call__(self, item): - return self.transform(item) - - @classmethod - def from_config(cls, cfg=None): - if cfg is None: - cfg = OmegaConf.create() - - image_size = cfg.get("image_size", 224) - - mean = cfg.get("mean", None) - std = cfg.get("std", None) - - return cls(image_size=image_size, mean=mean, std=std) - diff --git a/sonique/Video_LLaMA/video_llama/processors/functional_video.py b/sonique/Video_LLaMA/video_llama/processors/functional_video.py deleted file mode 100644 index 597a29315d4e1a575e7209edb0618eeaf4fc024a..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/processors/functional_video.py +++ /dev/null @@ -1,121 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import warnings - -import torch - - -def _is_tensor_video_clip(clip): - if not torch.is_tensor(clip): - raise TypeError("clip should be Tensor. Got %s" % type(clip)) - - if not clip.ndimension() == 4: - raise ValueError("clip should be 4D. Got %dD" % clip.dim()) - - return True - - -def crop(clip, i, j, h, w): - """ - Args: - clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) - """ - if len(clip.size()) != 4: - raise ValueError("clip should be a 4D tensor") - return clip[..., i : i + h, j : j + w] - - -def resize(clip, target_size, interpolation_mode): - if len(target_size) != 2: - raise ValueError( - f"target size should be tuple (height, width), instead got {target_size}" - ) - return torch.nn.functional.interpolate( - clip, size=target_size, mode=interpolation_mode, align_corners=False - ) - - -def resized_crop(clip, i, j, h, w, size, interpolation_mode="bilinear"): - """ - Do spatial cropping and resizing to the video clip - Args: - clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) - i (int): i in (i,j) i.e coordinates of the upper left corner. - j (int): j in (i,j) i.e coordinates of the upper left corner. - h (int): Height of the cropped region. - w (int): Width of the cropped region. - size (tuple(int, int)): height and width of resized clip - Returns: - clip (torch.tensor): Resized and cropped clip. Size is (C, T, H, W) - """ - if not _is_tensor_video_clip(clip): - raise ValueError("clip should be a 4D torch.tensor") - clip = crop(clip, i, j, h, w) - clip = resize(clip, size, interpolation_mode) - return clip - - -def center_crop(clip, crop_size): - if not _is_tensor_video_clip(clip): - raise ValueError("clip should be a 4D torch.tensor") - h, w = clip.size(-2), clip.size(-1) - th, tw = crop_size - if h < th or w < tw: - raise ValueError("height and width must be no smaller than crop_size") - - i = int(round((h - th) / 2.0)) - j = int(round((w - tw) / 2.0)) - return crop(clip, i, j, th, tw) - - -def to_tensor(clip): - """ - Convert tensor data type from uint8 to float, divide value by 255.0 and - permute the dimensions of clip tensor - Args: - clip (torch.tensor, dtype=torch.uint8): Size is (T, H, W, C) - Return: - clip (torch.tensor, dtype=torch.float): Size is (C, T, H, W) - """ - _is_tensor_video_clip(clip) - if not clip.dtype == torch.uint8: - raise TypeError( - "clip tensor should have data type uint8. Got %s" % str(clip.dtype) - ) - return clip.float().permute(3, 0, 1, 2) / 255.0 - - -def normalize(clip, mean, std, inplace=False): - """ - Args: - clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W) - mean (tuple): pixel RGB mean. Size is (3) - std (tuple): pixel standard deviation. Size is (3) - Returns: - normalized clip (torch.tensor): Size is (C, T, H, W) - """ - if not _is_tensor_video_clip(clip): - raise ValueError("clip should be a 4D torch.tensor") - if not inplace: - clip = clip.clone() - mean = torch.as_tensor(mean, dtype=clip.dtype, device=clip.device) - std = torch.as_tensor(std, dtype=clip.dtype, device=clip.device) - clip.sub_(mean[:, None, None, None]).div_(std[:, None, None, None]) - return clip - - -def hflip(clip): - """ - Args: - clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W) - Returns: - flipped clip (torch.tensor): Size is (C, T, H, W) - """ - if not _is_tensor_video_clip(clip): - raise ValueError("clip should be a 4D torch.tensor") - return clip.flip(-1) diff --git a/sonique/Video_LLaMA/video_llama/processors/randaugment.py b/sonique/Video_LLaMA/video_llama/processors/randaugment.py deleted file mode 100644 index 7034a49ad5fc63b97910790017432617ff4c6d7b..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/processors/randaugment.py +++ /dev/null @@ -1,398 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import cv2 -import numpy as np - -import torch - - -## aug functions -def identity_func(img): - return img - - -def autocontrast_func(img, cutoff=0): - """ - same output as PIL.ImageOps.autocontrast - """ - n_bins = 256 - - def tune_channel(ch): - n = ch.size - cut = cutoff * n // 100 - if cut == 0: - high, low = ch.max(), ch.min() - else: - hist = cv2.calcHist([ch], [0], None, [n_bins], [0, n_bins]) - low = np.argwhere(np.cumsum(hist) > cut) - low = 0 if low.shape[0] == 0 else low[0] - high = np.argwhere(np.cumsum(hist[::-1]) > cut) - high = n_bins - 1 if high.shape[0] == 0 else n_bins - 1 - high[0] - if high <= low: - table = np.arange(n_bins) - else: - scale = (n_bins - 1) / (high - low) - offset = -low * scale - table = np.arange(n_bins) * scale + offset - table[table < 0] = 0 - table[table > n_bins - 1] = n_bins - 1 - table = table.clip(0, 255).astype(np.uint8) - return table[ch] - - channels = [tune_channel(ch) for ch in cv2.split(img)] - out = cv2.merge(channels) - return out - - -def equalize_func(img): - """ - same output as PIL.ImageOps.equalize - PIL's implementation is different from cv2.equalize - """ - n_bins = 256 - - def tune_channel(ch): - hist = cv2.calcHist([ch], [0], None, [n_bins], [0, n_bins]) - non_zero_hist = hist[hist != 0].reshape(-1) - step = np.sum(non_zero_hist[:-1]) // (n_bins - 1) - if step == 0: - return ch - n = np.empty_like(hist) - n[0] = step // 2 - n[1:] = hist[:-1] - table = (np.cumsum(n) // step).clip(0, 255).astype(np.uint8) - return table[ch] - - channels = [tune_channel(ch) for ch in cv2.split(img)] - out = cv2.merge(channels) - return out - - -def rotate_func(img, degree, fill=(0, 0, 0)): - """ - like PIL, rotate by degree, not radians - """ - H, W = img.shape[0], img.shape[1] - center = W / 2, H / 2 - M = cv2.getRotationMatrix2D(center, degree, 1) - out = cv2.warpAffine(img, M, (W, H), borderValue=fill) - return out - - -def solarize_func(img, thresh=128): - """ - same output as PIL.ImageOps.posterize - """ - table = np.array([el if el < thresh else 255 - el for el in range(256)]) - table = table.clip(0, 255).astype(np.uint8) - out = table[img] - return out - - -def color_func(img, factor): - """ - same output as PIL.ImageEnhance.Color - """ - ## implementation according to PIL definition, quite slow - # degenerate = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)[:, :, np.newaxis] - # out = blend(degenerate, img, factor) - # M = ( - # np.eye(3) * factor - # + np.float32([0.114, 0.587, 0.299]).reshape(3, 1) * (1. - factor) - # )[np.newaxis, np.newaxis, :] - M = np.float32( - [[0.886, -0.114, -0.114], [-0.587, 0.413, -0.587], [-0.299, -0.299, 0.701]] - ) * factor + np.float32([[0.114], [0.587], [0.299]]) - out = np.matmul(img, M).clip(0, 255).astype(np.uint8) - return out - - -def contrast_func(img, factor): - """ - same output as PIL.ImageEnhance.Contrast - """ - mean = np.sum(np.mean(img, axis=(0, 1)) * np.array([0.114, 0.587, 0.299])) - table = ( - np.array([(el - mean) * factor + mean for el in range(256)]) - .clip(0, 255) - .astype(np.uint8) - ) - out = table[img] - return out - - -def brightness_func(img, factor): - """ - same output as PIL.ImageEnhance.Contrast - """ - table = (np.arange(256, dtype=np.float32) * factor).clip(0, 255).astype(np.uint8) - out = table[img] - return out - - -def sharpness_func(img, factor): - """ - The differences the this result and PIL are all on the 4 boundaries, the center - areas are same - """ - kernel = np.ones((3, 3), dtype=np.float32) - kernel[1][1] = 5 - kernel /= 13 - degenerate = cv2.filter2D(img, -1, kernel) - if factor == 0.0: - out = degenerate - elif factor == 1.0: - out = img - else: - out = img.astype(np.float32) - degenerate = degenerate.astype(np.float32)[1:-1, 1:-1, :] - out[1:-1, 1:-1, :] = degenerate + factor * (out[1:-1, 1:-1, :] - degenerate) - out = out.astype(np.uint8) - return out - - -def shear_x_func(img, factor, fill=(0, 0, 0)): - H, W = img.shape[0], img.shape[1] - M = np.float32([[1, factor, 0], [0, 1, 0]]) - out = cv2.warpAffine( - img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR - ).astype(np.uint8) - return out - - -def translate_x_func(img, offset, fill=(0, 0, 0)): - """ - same output as PIL.Image.transform - """ - H, W = img.shape[0], img.shape[1] - M = np.float32([[1, 0, -offset], [0, 1, 0]]) - out = cv2.warpAffine( - img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR - ).astype(np.uint8) - return out - - -def translate_y_func(img, offset, fill=(0, 0, 0)): - """ - same output as PIL.Image.transform - """ - H, W = img.shape[0], img.shape[1] - M = np.float32([[1, 0, 0], [0, 1, -offset]]) - out = cv2.warpAffine( - img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR - ).astype(np.uint8) - return out - - -def posterize_func(img, bits): - """ - same output as PIL.ImageOps.posterize - """ - out = np.bitwise_and(img, np.uint8(255 << (8 - bits))) - return out - - -def shear_y_func(img, factor, fill=(0, 0, 0)): - H, W = img.shape[0], img.shape[1] - M = np.float32([[1, 0, 0], [factor, 1, 0]]) - out = cv2.warpAffine( - img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR - ).astype(np.uint8) - return out - - -def cutout_func(img, pad_size, replace=(0, 0, 0)): - replace = np.array(replace, dtype=np.uint8) - H, W = img.shape[0], img.shape[1] - rh, rw = np.random.random(2) - pad_size = pad_size // 2 - ch, cw = int(rh * H), int(rw * W) - x1, x2 = max(ch - pad_size, 0), min(ch + pad_size, H) - y1, y2 = max(cw - pad_size, 0), min(cw + pad_size, W) - out = img.copy() - out[x1:x2, y1:y2, :] = replace - return out - - -### level to args -def enhance_level_to_args(MAX_LEVEL): - def level_to_args(level): - return ((level / MAX_LEVEL) * 1.8 + 0.1,) - - return level_to_args - - -def shear_level_to_args(MAX_LEVEL, replace_value): - def level_to_args(level): - level = (level / MAX_LEVEL) * 0.3 - if np.random.random() > 0.5: - level = -level - return (level, replace_value) - - return level_to_args - - -def translate_level_to_args(translate_const, MAX_LEVEL, replace_value): - def level_to_args(level): - level = (level / MAX_LEVEL) * float(translate_const) - if np.random.random() > 0.5: - level = -level - return (level, replace_value) - - return level_to_args - - -def cutout_level_to_args(cutout_const, MAX_LEVEL, replace_value): - def level_to_args(level): - level = int((level / MAX_LEVEL) * cutout_const) - return (level, replace_value) - - return level_to_args - - -def solarize_level_to_args(MAX_LEVEL): - def level_to_args(level): - level = int((level / MAX_LEVEL) * 256) - return (level,) - - return level_to_args - - -def none_level_to_args(level): - return () - - -def posterize_level_to_args(MAX_LEVEL): - def level_to_args(level): - level = int((level / MAX_LEVEL) * 4) - return (level,) - - return level_to_args - - -def rotate_level_to_args(MAX_LEVEL, replace_value): - def level_to_args(level): - level = (level / MAX_LEVEL) * 30 - if np.random.random() < 0.5: - level = -level - return (level, replace_value) - - return level_to_args - - -func_dict = { - "Identity": identity_func, - "AutoContrast": autocontrast_func, - "Equalize": equalize_func, - "Rotate": rotate_func, - "Solarize": solarize_func, - "Color": color_func, - "Contrast": contrast_func, - "Brightness": brightness_func, - "Sharpness": sharpness_func, - "ShearX": shear_x_func, - "TranslateX": translate_x_func, - "TranslateY": translate_y_func, - "Posterize": posterize_func, - "ShearY": shear_y_func, -} - -translate_const = 10 -MAX_LEVEL = 10 -replace_value = (128, 128, 128) -arg_dict = { - "Identity": none_level_to_args, - "AutoContrast": none_level_to_args, - "Equalize": none_level_to_args, - "Rotate": rotate_level_to_args(MAX_LEVEL, replace_value), - "Solarize": solarize_level_to_args(MAX_LEVEL), - "Color": enhance_level_to_args(MAX_LEVEL), - "Contrast": enhance_level_to_args(MAX_LEVEL), - "Brightness": enhance_level_to_args(MAX_LEVEL), - "Sharpness": enhance_level_to_args(MAX_LEVEL), - "ShearX": shear_level_to_args(MAX_LEVEL, replace_value), - "TranslateX": translate_level_to_args(translate_const, MAX_LEVEL, replace_value), - "TranslateY": translate_level_to_args(translate_const, MAX_LEVEL, replace_value), - "Posterize": posterize_level_to_args(MAX_LEVEL), - "ShearY": shear_level_to_args(MAX_LEVEL, replace_value), -} - - -class RandomAugment(object): - def __init__(self, N=2, M=10, isPIL=False, augs=[]): - self.N = N - self.M = M - self.isPIL = isPIL - if augs: - self.augs = augs - else: - self.augs = list(arg_dict.keys()) - - def get_random_ops(self): - sampled_ops = np.random.choice(self.augs, self.N) - return [(op, 0.5, self.M) for op in sampled_ops] - - def __call__(self, img): - if self.isPIL: - img = np.array(img) - ops = self.get_random_ops() - for name, prob, level in ops: - if np.random.random() > prob: - continue - args = arg_dict[name](level) - img = func_dict[name](img, *args) - return img - - -class VideoRandomAugment(object): - def __init__(self, N=2, M=10, p=0.0, tensor_in_tensor_out=True, augs=[]): - self.N = N - self.M = M - self.p = p - self.tensor_in_tensor_out = tensor_in_tensor_out - if augs: - self.augs = augs - else: - self.augs = list(arg_dict.keys()) - - def get_random_ops(self): - sampled_ops = np.random.choice(self.augs, self.N, replace=False) - return [(op, self.M) for op in sampled_ops] - - def __call__(self, frames): - assert ( - frames.shape[-1] == 3 - ), "Expecting last dimension for 3-channels RGB (b, h, w, c)." - - if self.tensor_in_tensor_out: - frames = frames.numpy().astype(np.uint8) - - num_frames = frames.shape[0] - - ops = num_frames * [self.get_random_ops()] - apply_or_not = num_frames * [np.random.random(size=self.N) > self.p] - - frames = torch.stack( - list(map(self._aug, frames, ops, apply_or_not)), dim=0 - ).float() - - return frames - - def _aug(self, img, ops, apply_or_not): - for i, (name, level) in enumerate(ops): - if not apply_or_not[i]: - continue - args = arg_dict[name](level) - img = func_dict[name](img, *args) - return torch.from_numpy(img) - - -if __name__ == "__main__": - a = RandomAugment() - img = np.random.randn(32, 32, 3) - a(img) diff --git a/sonique/Video_LLaMA/video_llama/processors/transforms_video.py b/sonique/Video_LLaMA/video_llama/processors/transforms_video.py deleted file mode 100644 index 1fd485cf35b3c5bf755e758b878d48ebba9d61f2..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/processors/transforms_video.py +++ /dev/null @@ -1,179 +0,0 @@ -#!/usr/bin/env python3 -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - - -import numbers -import random - -from torchvision.transforms import ( - RandomCrop, - RandomResizedCrop, -) - -import sonique.Video_LLaMA.video_llama.processors.functional_video as F - - -__all__ = [ - "RandomCropVideo", - "RandomResizedCropVideo", - "CenterCropVideo", - "NormalizeVideo", - "ToTensorVideo", - "RandomHorizontalFlipVideo", -] - - -class RandomCropVideo(RandomCrop): - def __init__(self, size): - if isinstance(size, numbers.Number): - self.size = (int(size), int(size)) - else: - self.size = size - - def __call__(self, clip): - """ - Args: - clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) - Returns: - torch.tensor: randomly cropped/resized video clip. - size is (C, T, OH, OW) - """ - i, j, h, w = self.get_params(clip, self.size) - return F.crop(clip, i, j, h, w) - - def __repr__(self) -> str: - return f"{self.__class__.__name__}(size={self.size})" - - -class RandomResizedCropVideo(RandomResizedCrop): - def __init__( - self, - size, - scale=(0.08, 1.0), - ratio=(3.0 / 4.0, 4.0 / 3.0), - interpolation_mode="bilinear", - ): - if isinstance(size, tuple): - if len(size) != 2: - raise ValueError( - f"size should be tuple (height, width), instead got {size}" - ) - self.size = size - else: - self.size = (size, size) - - self.interpolation_mode = interpolation_mode - self.scale = scale - self.ratio = ratio - - def __call__(self, clip): - """ - Args: - clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) - Returns: - torch.tensor: randomly cropped/resized video clip. - size is (C, T, H, W) - """ - i, j, h, w = self.get_params(clip, self.scale, self.ratio) - return F.resized_crop(clip, i, j, h, w, self.size, self.interpolation_mode) - - def __repr__(self) -> str: - return f"{self.__class__.__name__}(size={self.size}, interpolation_mode={self.interpolation_mode}, scale={self.scale}, ratio={self.ratio})" - - -class CenterCropVideo: - def __init__(self, crop_size): - if isinstance(crop_size, numbers.Number): - self.crop_size = (int(crop_size), int(crop_size)) - else: - self.crop_size = crop_size - - def __call__(self, clip): - """ - Args: - clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) - Returns: - torch.tensor: central cropping of video clip. Size is - (C, T, crop_size, crop_size) - """ - return F.center_crop(clip, self.crop_size) - - def __repr__(self) -> str: - return f"{self.__class__.__name__}(crop_size={self.crop_size})" - - -class NormalizeVideo: - """ - Normalize the video clip by mean subtraction and division by standard deviation - Args: - mean (3-tuple): pixel RGB mean - std (3-tuple): pixel RGB standard deviation - inplace (boolean): whether do in-place normalization - """ - - def __init__(self, mean, std, inplace=False): - self.mean = mean - self.std = std - self.inplace = inplace - - def __call__(self, clip): - """ - Args: - clip (torch.tensor): video clip to be normalized. Size is (C, T, H, W) - """ - return F.normalize(clip, self.mean, self.std, self.inplace) - - def __repr__(self) -> str: - return f"{self.__class__.__name__}(mean={self.mean}, std={self.std}, inplace={self.inplace})" - - -class ToTensorVideo: - """ - Convert tensor data type from uint8 to float, divide value by 255.0 and - permute the dimensions of clip tensor - """ - - def __init__(self): - pass - - def __call__(self, clip): - """ - Args: - clip (torch.tensor, dtype=torch.uint8): Size is (T, H, W, C) - Return: - clip (torch.tensor, dtype=torch.float): Size is (C, T, H, W) - """ - return F.to_tensor(clip) - - def __repr__(self) -> str: - return self.__class__.__name__ - - -class RandomHorizontalFlipVideo: - """ - Flip the video clip along the horizonal direction with a given probability - Args: - p (float): probability of the clip being flipped. Default value is 0.5 - """ - - def __init__(self, p=0.5): - self.p = p - - def __call__(self, clip): - """ - Args: - clip (torch.tensor): Size is (C, T, H, W) - Return: - clip (torch.tensor): Size is (C, T, H, W) - """ - if random.random() < self.p: - clip = F.hflip(clip) - return clip - - def __repr__(self) -> str: - return f"{self.__class__.__name__}(p={self.p})" diff --git a/sonique/Video_LLaMA/video_llama/processors/video_processor.py b/sonique/Video_LLaMA/video_llama/processors/video_processor.py deleted file mode 100644 index f8fbca52f220d9250cee101c67280f744bcb3c43..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/processors/video_processor.py +++ /dev/null @@ -1,237 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import torch -from sonique.Video_LLaMA.video_llama.common.registry import registry -from decord import VideoReader -import decord -import numpy as np -from sonique.Video_LLaMA.video_llama.processors import transforms_video -from sonique.Video_LLaMA.video_llama.processors.base_processor import BaseProcessor -from sonique.Video_LLaMA.video_llama.processors.randaugment import VideoRandomAugment -from sonique.Video_LLaMA.video_llama.processors import functional_video as F -from omegaconf import OmegaConf -from torchvision import transforms -import random as rnd - - -MAX_INT = registry.get("MAX_INT") -decord.bridge.set_bridge("torch") - -def load_video(video_path, n_frms=MAX_INT, height=-1, width=-1, sampling="uniform", return_msg = False): - decord.bridge.set_bridge("torch") - vr = VideoReader(uri=video_path, height=height, width=width) - - vlen = len(vr) - start, end = 0, vlen - - n_frms = min(n_frms, vlen) - - if sampling == "uniform": - indices = np.arange(start, end, vlen / n_frms).astype(int).tolist() - elif sampling == "headtail": - indices_h = sorted(rnd.sample(range(vlen // 2), n_frms // 2)) - indices_t = sorted(rnd.sample(range(vlen // 2, vlen), n_frms // 2)) - indices = indices_h + indices_t - else: - raise NotImplementedError - - # get_batch -> T, H, W, C - temp_frms = vr.get_batch(indices) - # print(type(temp_frms)) - tensor_frms = torch.from_numpy(temp_frms) if type(temp_frms) is not torch.Tensor else temp_frms - frms = tensor_frms.permute(3, 0, 1, 2).float() # (C, T, H, W) - - if not return_msg: - return frms - - fps = float(vr.get_avg_fps()) - sec = ", ".join([str(round(f / fps, 1)) for f in indices]) - # " " should be added in the start and end - msg = f"The video contains {len(indices)} frames sampled at {sec} seconds. " - return frms, msg - - -class AlproVideoBaseProcessor(BaseProcessor): - def __init__(self, mean=None, std=None, n_frms=MAX_INT): - if mean is None: - mean = (0.48145466, 0.4578275, 0.40821073) - if std is None: - std = (0.26862954, 0.26130258, 0.27577711) - - self.normalize = transforms_video.NormalizeVideo(mean, std) - - self.n_frms = n_frms - - -class ToUint8(object): - def __init__(self): - pass - - def __call__(self, tensor): - return tensor.to(torch.uint8) - - def __repr__(self): - return self.__class__.__name__ - - -class ToTHWC(object): - """ - Args: - clip (torch.tensor, dtype=torch.uint8): Size is (C, T, H, W) - Return: - clip (torch.tensor, dtype=torch.float): Size is (T, H, W, C) - """ - - def __init__(self): - pass - - def __call__(self, tensor): - return tensor.permute(1, 2, 3, 0) - - def __repr__(self): - return self.__class__.__name__ - - -class ResizeVideo(object): - def __init__(self, target_size, interpolation_mode="bilinear"): - self.target_size = target_size - self.interpolation_mode = interpolation_mode - - def __call__(self, clip): - """ - Args: - clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) - Returns: - torch.tensor: central cropping of video clip. Size is - (C, T, crop_size, crop_size) - """ - return F.resize(clip, self.target_size, self.interpolation_mode) - - def __repr__(self): - return self.__class__.__name__ + "(resize_size={0})".format(self.target_size) - - -@registry.register_processor("alpro_video_train") -class AlproVideoTrainProcessor(AlproVideoBaseProcessor): - def __init__( - self, - image_size=384, - mean=None, - std=None, - min_scale=0.5, - max_scale=1.0, - n_frms=MAX_INT, - ): - super().__init__(mean=mean, std=std, n_frms=n_frms) - - self.image_size = image_size - - self.transform = transforms.Compose( - [ - # Video size is (C, T, H, W) - transforms_video.RandomResizedCropVideo( - image_size, - scale=(min_scale, max_scale), - interpolation_mode="bicubic", - ), - ToTHWC(), # C, T, H, W -> T, H, W, C - ToUint8(), - transforms_video.ToTensorVideo(), # T, H, W, C -> C, T, H, W - self.normalize, - ] - ) - - def __call__(self, vpath): - """ - Args: - clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) - Returns: - torch.tensor: video clip after transforms. Size is (C, T, size, size). - """ - clip = load_video( - video_path=vpath, - n_frms=self.n_frms, - height=self.image_size, - width=self.image_size, - sampling="headtail", - ) - - return self.transform(clip) - - @classmethod - def from_config(cls, cfg=None): - if cfg is None: - cfg = OmegaConf.create() - - image_size = cfg.get("image_size", 256) - - mean = cfg.get("mean", None) - std = cfg.get("std", None) - - min_scale = cfg.get("min_scale", 0.5) - max_scale = cfg.get("max_scale", 1.0) - - n_frms = cfg.get("n_frms", MAX_INT) - - return cls( - image_size=image_size, - mean=mean, - std=std, - min_scale=min_scale, - max_scale=max_scale, - n_frms=n_frms, - ) - - -@registry.register_processor("alpro_video_eval") -class AlproVideoEvalProcessor(AlproVideoBaseProcessor): - def __init__(self, image_size=256, mean=None, std=None, n_frms=MAX_INT): - super().__init__(mean=mean, std=std, n_frms=n_frms) - - self.image_size = image_size - - # Input video size is (C, T, H, W) - self.transform = transforms.Compose( - [ - # frames will be resized during decord loading. - ToUint8(), # C, T, H, W - ToTHWC(), # T, H, W, C - transforms_video.ToTensorVideo(), # C, T, H, W - self.normalize, # C, T, H, W - ] - ) - - def __call__(self, vpath): - """ - Args: - clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) - Returns: - torch.tensor: video clip after transforms. Size is (C, T, size, size). - """ - clip = load_video( - video_path=vpath, - n_frms=self.n_frms, - height=self.image_size, - width=self.image_size, - ) - - return self.transform(clip) - - @classmethod - def from_config(cls, cfg=None): - if cfg is None: - cfg = OmegaConf.create() - - image_size = cfg.get("image_size", 256) - - mean = cfg.get("mean", None) - std = cfg.get("std", None) - - n_frms = cfg.get("n_frms", MAX_INT) - - return cls(image_size=image_size, mean=mean, std=std, n_frms=n_frms) diff --git a/sonique/Video_LLaMA/video_llama/runners/__init__.py b/sonique/Video_LLaMA/video_llama/runners/__init__.py deleted file mode 100644 index 546e77e8383c7dc61695eb4b23dc3c29e054d1c6..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/runners/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -from sonique.Video_LLaMA.video_llama.runners.runner_base import RunnerBase - -__all__ = ["RunnerBase"] diff --git a/sonique/Video_LLaMA/video_llama/runners/runner_base.py b/sonique/Video_LLaMA/video_llama/runners/runner_base.py deleted file mode 100644 index c5ae235da0c47746bcae2b50f011e1fcdb3dc2ab..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/runners/runner_base.py +++ /dev/null @@ -1,658 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import datetime -import json -import logging -import os -import time -from pathlib import Path - -import torch -import torch.distributed as dist -import webdataset as wds -from sonique.Video_LLaMA.video_llama.common.dist_utils import ( - download_cached_file, - get_rank, - get_world_size, - is_main_process, - main_process, -) -from sonique.Video_LLaMA.video_llama.common.registry import registry -from sonique.Video_LLaMA.video_llama.common.utils import is_url -from sonique.Video_LLaMA.video_llama.datasets.data_utils import concat_datasets, reorg_datasets_by_split, ChainDataset -from sonique.Video_LLaMA.video_llama.datasets.datasets.dataloader_utils import ( - IterLoader, - MultiIterLoader, - PrefetchLoader, -) -from torch.nn.parallel import DistributedDataParallel as DDP -from torch.utils.data import DataLoader, DistributedSampler - - -@registry.register_runner("runner_base") -class RunnerBase: - """ - A runner class to train and evaluate a model given a task and datasets. - - The runner uses pytorch distributed data parallel by default. Future release - will support other distributed frameworks. - """ - - def __init__(self, cfg, task, model, datasets, job_id): - self.config = cfg - self.job_id = job_id - - self.task = task - self.datasets = datasets - - self._model = model - - self._wrapped_model = None - self._device = None - self._optimizer = None - self._scaler = None - self._dataloaders = None - self._lr_sched = None - - self.start_epoch = 0 - - # self.setup_seeds() - self.setup_output_dir() - - @property - def device(self): - if self._device is None: - self._device = torch.device(self.config.run_cfg.device) - - return self._device - - @property - def use_distributed(self): - return self.config.run_cfg.distributed - - @property - def model(self): - """ - A property to get the DDP-wrapped model on the device. - """ - # move model to device - if self._model.device != self.device: - self._model = self._model.to(self.device) - - # distributed training wrapper - if self.use_distributed: - if self._wrapped_model is None: - self._wrapped_model = DDP( - self._model, device_ids=[self.config.run_cfg.gpu] - ) - else: - self._wrapped_model = self._model - - return self._wrapped_model - - @property - def optimizer(self): - # TODO make optimizer class and configurations - if self._optimizer is None: - num_parameters = 0 - p_wd, p_non_wd = [], [] - for n, p in self.model.named_parameters(): - if not p.requires_grad: - continue # frozen weights - print(n) - if p.ndim < 2 or "bias" in n or "ln" in n or "bn" in n: - p_non_wd.append(p) - else: - p_wd.append(p) - num_parameters += p.data.nelement() - logging.info("number of trainable parameters: %d" % num_parameters) - optim_params = [ - { - "params": p_wd, - "weight_decay": float(self.config.run_cfg.weight_decay), - }, - {"params": p_non_wd, "weight_decay": 0}, - ] - beta2 = self.config.run_cfg.get("beta2", 0.999) - self._optimizer = torch.optim.AdamW( - optim_params, - lr=float(self.config.run_cfg.init_lr), - weight_decay=float(self.config.run_cfg.weight_decay), - betas=(0.9, beta2), - ) - - return self._optimizer - - @property - def scaler(self): - amp = self.config.run_cfg.get("amp", False) - - if amp: - if self._scaler is None: - self._scaler = torch.cuda.amp.GradScaler() - - return self._scaler - - @property - def lr_scheduler(self): - """ - A property to get and create learning rate scheduler by split just in need. - """ - if self._lr_sched is None: - lr_sched_cls = registry.get_lr_scheduler_class(self.config.run_cfg.lr_sched) - - # max_epoch = self.config.run_cfg.max_epoch - max_epoch = self.max_epoch - # min_lr = self.config.run_cfg.min_lr - min_lr = self.min_lr - # init_lr = self.config.run_cfg.init_lr - init_lr = self.init_lr - - # optional parameters - decay_rate = self.config.run_cfg.get("lr_decay_rate", None) - warmup_start_lr = self.config.run_cfg.get("warmup_lr", -1) - warmup_steps = self.config.run_cfg.get("warmup_steps", 0) - iters_per_epoch = self.config.run_cfg.get("iters_per_epoch", None) - - if iters_per_epoch is None: - try: - iters_per_epoch = len(self.dataloaders['train']) - except (AttributeError, TypeError): - iters_per_epoch = 10000 - - self._lr_sched = lr_sched_cls( - optimizer=self.optimizer, - max_epoch=max_epoch, - iters_per_epoch=iters_per_epoch, - min_lr=min_lr, - init_lr=init_lr, - decay_rate=decay_rate, - warmup_start_lr=warmup_start_lr, - warmup_steps=warmup_steps, - ) - - return self._lr_sched - - @property - def dataloaders(self) -> dict: - """ - A property to get and create dataloaders by split just in need. - - If no train_dataset_ratio is provided, concatenate map-style datasets and - chain wds.DataPipe datasets separately. Training set becomes a tuple - (ConcatDataset, ChainDataset), both are optional but at least one of them is - required. The resultant ConcatDataset and ChainDataset will be sampled evenly. - - If train_dataset_ratio is provided, create a MultiIterLoader to sample - each dataset by ratios during training. - - Currently do not support multiple datasets for validation and test. - - Returns: - dict: {split_name: (tuples of) dataloader} - """ - if self._dataloaders is None: - - # concatenate map-style datasets and chain wds.DataPipe datasets separately - # training set becomes a tuple (ConcatDataset, ChainDataset), both are - # optional but at least one of them is required. The resultant ConcatDataset - # and ChainDataset will be sampled evenly. - logging.info( - "dataset_ratios not specified, datasets will be concatenated (map-style datasets) or chained (webdataset.DataPipeline)." - ) - - datasets = reorg_datasets_by_split(self.datasets) - self.datasets = datasets - # self.datasets = concat_datasets(datasets) - - # print dataset statistics after concatenation/chaining - for split_name in self.datasets: - if isinstance(self.datasets[split_name], tuple) or isinstance( - self.datasets[split_name], list - ): - # mixed wds.DataPipeline and torch.utils.data.Dataset - num_records = sum( - [ - len(d) - if not type(d) in [wds.DataPipeline, ChainDataset] - else 0 - for d in self.datasets[split_name] - ] - ) - - else: - if hasattr(self.datasets[split_name], "__len__"): - # a single map-style dataset - num_records = len(self.datasets[split_name]) - else: - # a single wds.DataPipeline - num_records = -1 - logging.info( - "Only a single wds.DataPipeline dataset, no __len__ attribute." - ) - - if num_records >= 0: - logging.info( - "Loaded {} records for {} split from the dataset.".format( - num_records, split_name - ) - ) - - # create dataloaders - split_names = sorted(self.datasets.keys()) - - datasets = [self.datasets[split] for split in split_names] - is_trains = [split in self.train_splits for split in split_names] - - batch_sizes = [ - self.config.run_cfg.batch_size_train - if split == "train" - else self.config.run_cfg.batch_size_eval - for split in split_names - ] - - collate_fns = [] - for dataset in datasets: - if isinstance(dataset, tuple) or isinstance(dataset, list): - collate_fns.append([getattr(d, "collater", None) for d in dataset]) - else: - collate_fns.append(getattr(dataset, "collater", None)) - - dataloaders = self.create_loaders( - datasets=datasets, - num_workers=self.config.run_cfg.num_workers, - batch_sizes=batch_sizes, - is_trains=is_trains, - collate_fns=collate_fns, - ) - - self._dataloaders = {k: v for k, v in zip(split_names, dataloaders)} - - return self._dataloaders - - @property - def cuda_enabled(self): - return self.device.type == "cuda" - - @property - def max_epoch(self): - return int(self.config.run_cfg.max_epoch) - - @property - def log_freq(self): - log_freq = self.config.run_cfg.get("log_freq", 50) - return int(log_freq) - - @property - def init_lr(self): - return float(self.config.run_cfg.init_lr) - - @property - def min_lr(self): - return float(self.config.run_cfg.min_lr) - - @property - def accum_grad_iters(self): - return int(self.config.run_cfg.get("accum_grad_iters", 1)) - - @property - def valid_splits(self): - valid_splits = self.config.run_cfg.get("valid_splits", []) - - if len(valid_splits) == 0: - logging.info("No validation splits found.") - - return valid_splits - - @property - def test_splits(self): - test_splits = self.config.run_cfg.get("test_splits", []) - - return test_splits - - @property - def train_splits(self): - train_splits = self.config.run_cfg.get("train_splits", []) - - if len(train_splits) == 0: - logging.info("Empty train splits.") - - return train_splits - - @property - def evaluate_only(self): - """ - Set to True to skip training. - """ - return self.config.run_cfg.evaluate - - @property - def use_dist_eval_sampler(self): - return self.config.run_cfg.get("use_dist_eval_sampler", True) - - @property - def resume_ckpt_path(self): - return self.config.run_cfg.get("resume_ckpt_path", None) - - @property - def train_loader(self): - train_dataloader = self.dataloaders["train"] - - return train_dataloader - - def setup_output_dir(self): - lib_root = Path(registry.get_path("library_root")) - - output_dir = lib_root / self.config.run_cfg.output_dir / self.job_id - result_dir = output_dir / "result" - - output_dir.mkdir(parents=True, exist_ok=True) - result_dir.mkdir(parents=True, exist_ok=True) - - registry.register_path("result_dir", str(result_dir)) - registry.register_path("output_dir", str(output_dir)) - - self.result_dir = result_dir - self.output_dir = output_dir - - def train(self): - start_time = time.time() - best_agg_metric = 0 - best_epoch = 0 - - self.log_config() - - # resume from checkpoint if specified - if not self.evaluate_only and self.resume_ckpt_path is not None: - self._load_checkpoint(self.resume_ckpt_path) - - for cur_epoch in range(self.start_epoch, self.max_epoch): - # training phase - if not self.evaluate_only: - logging.info("Start training") - train_stats = self.train_epoch(cur_epoch) - self.log_stats(split_name="train", stats=train_stats) - - # evaluation phase - if len(self.valid_splits) > 0: - for split_name in self.valid_splits: - logging.info("Evaluating on {}.".format(split_name)) - - val_log = self.eval_epoch( - split_name=split_name, cur_epoch=cur_epoch - ) - if val_log is not None: - if is_main_process(): - assert ( - "agg_metrics" in val_log - ), "No agg_metrics found in validation log." - - agg_metrics = val_log["agg_metrics"] - if agg_metrics > best_agg_metric and split_name == "val": - best_epoch, best_agg_metric = cur_epoch, agg_metrics - - self._save_checkpoint(cur_epoch, is_best=True) - - val_log.update({"best_epoch": best_epoch}) - self.log_stats(val_log, split_name) - - else: - # if no validation split is provided, we just save the checkpoint at the end of each epoch. - if not self.evaluate_only: - self._save_checkpoint(cur_epoch, is_best=False) - - if self.evaluate_only: - break - - if self.config.run_cfg.distributed: - dist.barrier() - - # testing phase - test_epoch = "best" if len(self.valid_splits) > 0 else cur_epoch - self.evaluate(cur_epoch=test_epoch, skip_reload=self.evaluate_only) - - total_time = time.time() - start_time - total_time_str = str(datetime.timedelta(seconds=int(total_time))) - logging.info("Training time {}".format(total_time_str)) - - def evaluate(self, cur_epoch="best", skip_reload=False): - test_logs = dict() - - if len(self.test_splits) > 0: - for split_name in self.test_splits: - test_logs[split_name] = self.eval_epoch( - split_name=split_name, cur_epoch=cur_epoch, skip_reload=skip_reload - ) - - return test_logs - - def train_epoch(self, epoch): - # train - self.model.train() - - return self.task.train_epoch( - epoch=epoch, - model=self.model, - data_loader=self.train_loader, - optimizer=self.optimizer, - scaler=self.scaler, - lr_scheduler=self.lr_scheduler, - cuda_enabled=self.cuda_enabled, - log_freq=self.log_freq, - accum_grad_iters=self.accum_grad_iters, - ) - - @torch.no_grad() - def eval_epoch(self, split_name, cur_epoch, skip_reload=False): - """ - Evaluate the model on a given split. - - Args: - split_name (str): name of the split to evaluate on. - cur_epoch (int): current epoch. - skip_reload_best (bool): whether to skip reloading the best checkpoint. - During training, we will reload the best checkpoint for validation. - During testing, we will use provided weights and skip reloading the best checkpoint . - """ - data_loader = self.dataloaders.get(split_name, None) - assert data_loader, "data_loader for split {} is None.".format(split_name) - - # TODO In validation, you need to compute loss as well as metrics - # TODO consider moving to model.before_evaluation() - model = self.unwrap_dist_model(self.model) - if not skip_reload and cur_epoch == "best": - model = self._reload_best_model(model) - model.eval() - - self.task.before_evaluation( - model=model, - dataset=self.datasets[split_name], - ) - results = self.task.evaluation(model, data_loader) - - if results is not None: - return self.task.after_evaluation( - val_result=results, - split_name=split_name, - epoch=cur_epoch, - ) - - def unwrap_dist_model(self, model): - if self.use_distributed: - return model.module - else: - return model - - def create_loaders( - self, - datasets, - num_workers, - batch_sizes, - is_trains, - collate_fns, - dataset_ratios=None, - ): - """ - Create dataloaders for training and validation. - """ - - def _create_loader(dataset, num_workers, bsz, is_train, collate_fn): - # create a single dataloader for each split - if isinstance(dataset, ChainDataset) or isinstance( - dataset, wds.DataPipeline - ): - # wds.WebdDataset instance are chained together - # webdataset.DataPipeline has its own sampler and collate_fn - loader = iter( - DataLoader( - dataset, - batch_size=bsz, - num_workers=num_workers, - pin_memory=True, - ) - ) - else: - # map-style dataset are concatenated together - # setup distributed sampler - if self.use_distributed: - sampler = DistributedSampler( - dataset, - shuffle=is_train, - num_replicas=get_world_size(), - rank=get_rank(), - ) - if not self.use_dist_eval_sampler: - # e.g. retrieval evaluation - sampler = sampler if is_train else None - else: - sampler = None - - loader = DataLoader( - dataset, - batch_size=bsz, - num_workers=num_workers, - pin_memory=True, - sampler=sampler, - shuffle=sampler is None and is_train, - collate_fn=collate_fn, - drop_last=True if is_train else False, - ) - loader = PrefetchLoader(loader) - - if is_train: - loader = IterLoader(loader, use_distributed=self.use_distributed) - - return loader - - loaders = [] - - for dataset, bsz, is_train, collate_fn in zip( - datasets, batch_sizes, is_trains, collate_fns - ): - if isinstance(dataset, list) or isinstance(dataset, tuple): - if hasattr(dataset[0], 'sample_ratio') and dataset_ratios is None: - dataset_ratios = [d.sample_ratio for d in dataset] - loader = MultiIterLoader( - loaders=[ - _create_loader(d, num_workers, bsz, is_train, collate_fn[i]) - for i, d in enumerate(dataset) - ], - ratios=dataset_ratios, - ) - else: - loader = _create_loader(dataset, num_workers, bsz, is_train, collate_fn) - - loaders.append(loader) - - return loaders - - @main_process - def _save_checkpoint(self, cur_epoch, is_best=False): - """ - Save the checkpoint at the current epoch. - """ - model_no_ddp = self.unwrap_dist_model(self.model) - param_grad_dic = { - k: v.requires_grad for (k, v) in model_no_ddp.named_parameters() - } - state_dict = model_no_ddp.state_dict() - for k in list(state_dict.keys()): - if k in param_grad_dic.keys() and not param_grad_dic[k]: - # delete parameters that do not require gradient - del state_dict[k] - save_obj = { - "model": state_dict, - "optimizer": self.optimizer.state_dict(), - "config": self.config.to_dict(), - "scaler": self.scaler.state_dict() if self.scaler else None, - "epoch": cur_epoch, - } - save_to = os.path.join( - self.output_dir, - "checkpoint_{}.pth".format("best" if is_best else cur_epoch), - ) - logging.info("Saving checkpoint at epoch {} to {}.".format(cur_epoch, save_to)) - torch.save(save_obj, save_to) - - def _reload_best_model(self, model): - """ - Load the best checkpoint for evaluation. - """ - checkpoint_path = os.path.join(self.output_dir, "checkpoint_best.pth") - - logging.info("Loading checkpoint from {}.".format(checkpoint_path)) - checkpoint = torch.load(checkpoint_path, map_location="cpu") - try: - model.load_state_dict(checkpoint["model"]) - except RuntimeError as e: - logging.warning( - """ - Key mismatch when loading checkpoint. This is expected if only part of the model is saved. - Trying to load the model with strict=False. - """ - ) - model.load_state_dict(checkpoint["model"], strict=False) - return model - - def _load_checkpoint(self, url_or_filename): - """ - Resume from a checkpoint. - """ - if is_url(url_or_filename): - cached_file = download_cached_file( - url_or_filename, check_hash=False, progress=True - ) - checkpoint = torch.load(cached_file, map_location=self.device, strict=False) - elif os.path.isfile(url_or_filename): - checkpoint = torch.load(url_or_filename, map_location=self.device, strict=False) - else: - raise RuntimeError("checkpoint url or path is invalid") - - state_dict = checkpoint["model"] - self.unwrap_dist_model(self.model).load_state_dict(state_dict) - - self.optimizer.load_state_dict(checkpoint["optimizer"]) - if self.scaler and "scaler" in checkpoint: - self.scaler.load_state_dict(checkpoint["scaler"]) - - self.start_epoch = checkpoint["epoch"] + 1 - logging.info("Resume checkpoint from {}".format(url_or_filename)) - - @main_process - def log_stats(self, stats, split_name): - if isinstance(stats, dict): - log_stats = {**{f"{split_name}_{k}": v for k, v in stats.items()}} - with open(os.path.join(self.output_dir, "log.txt"), "a") as f: - f.write(json.dumps(log_stats) + "\n") - elif isinstance(stats, list): - pass - - @main_process - def log_config(self): - with open(os.path.join(self.output_dir, "log.txt"), "a") as f: - f.write(json.dumps(self.config.to_dict(), indent=4) + "\n") diff --git a/sonique/Video_LLaMA/video_llama/runners/test.py b/sonique/Video_LLaMA/video_llama/runners/test.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/sonique/Video_LLaMA/video_llama/tasks/__init__.py b/sonique/Video_LLaMA/video_llama/tasks/__init__.py deleted file mode 100644 index 2ea393042fb75a3997ca4c41914fea56356e3ab1..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/tasks/__init__.py +++ /dev/null @@ -1,28 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -from sonique.Video_LLaMA.video_llama.common.registry import registry -from sonique.Video_LLaMA.video_llama.tasks.base_task import BaseTask -from sonique.Video_LLaMA.video_llama.tasks.image_text_pretrain import ImageTextPretrainTask -from sonique.Video_LLaMA.video_llama.tasks.video_text_pretrain import VideoTextPretrainTask - - -def setup_task(cfg): - assert "task" in cfg.run_cfg, "Task name must be provided." - - task_name = cfg.run_cfg.task - task = registry.get_task_class(task_name).setup_task(cfg=cfg) - assert task is not None, "Task {} not properly registered.".format(task_name) - - return task - - -__all__ = [ - "BaseTask", - "ImageTextPretrainTask", - "VideoTextPretrainTask" -] diff --git a/sonique/Video_LLaMA/video_llama/tasks/base_task.py b/sonique/Video_LLaMA/video_llama/tasks/base_task.py deleted file mode 100644 index 9a60932d2d87e1b337a77ab011035ee97d934df9..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/tasks/base_task.py +++ /dev/null @@ -1,286 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -import logging -import os - -import torch -import torch.distributed as dist -from sonique.Video_LLaMA.video_llama.common.dist_utils import get_rank, get_world_size, is_main_process, is_dist_avail_and_initialized -from sonique.Video_LLaMA.video_llama.common.logger import MetricLogger, SmoothedValue -from sonique.Video_LLaMA.video_llama.common.registry import registry -from sonique.Video_LLaMA.video_llama.datasets.data_utils import prepare_sample - - -class BaseTask: - def __init__(self, **kwargs): - super().__init__() - - self.inst_id_key = "instance_id" - - @classmethod - def setup_task(cls, **kwargs): - return cls() - - def build_model(self, cfg): - model_config = cfg.model_cfg - - model_cls = registry.get_model_class(model_config.arch) - return model_cls.from_config(model_config) - - def build_datasets(self, cfg): - """ - Build a dictionary of datasets, keyed by split 'train', 'valid', 'test'. - Download dataset and annotations automatically if not exist. - - Args: - cfg (common.config.Config): _description_ - - Returns: - dict: Dictionary of torch.utils.data.Dataset objects by split. - """ - - datasets = dict() - - datasets_config = cfg.datasets_cfg - - assert len(datasets_config) > 0, "At least one dataset has to be specified." - - for name in datasets_config: - dataset_config = datasets_config[name] - - builder = registry.get_builder_class(name)(dataset_config) - dataset = builder.build_datasets() - - dataset['train'].name = name - if 'sample_ratio' in dataset_config: - dataset['train'].sample_ratio = dataset_config.sample_ratio - - datasets[name] = dataset - - return datasets - - def train_step(self, model, samples): - loss = model(samples)["loss"] - return loss - - def valid_step(self, model, samples): - raise NotImplementedError - - def before_evaluation(self, model, dataset, **kwargs): - model.before_evaluation(dataset=dataset, task_type=type(self)) - - def after_evaluation(self, **kwargs): - pass - - def inference_step(self): - raise NotImplementedError - - def evaluation(self, model, data_loader, cuda_enabled=True): - metric_logger = MetricLogger(delimiter=" ") - header = "Evaluation" - # TODO make it configurable - print_freq = 10 - - results = [] - - for samples in metric_logger.log_every(data_loader, print_freq, header): - samples = prepare_sample(samples, cuda_enabled=cuda_enabled) - - eval_output = self.valid_step(model=model, samples=samples) - results.extend(eval_output) - - if is_dist_avail_and_initialized(): - dist.barrier() - - return results - - def train_epoch( - self, - epoch, - model, - data_loader, - optimizer, - lr_scheduler, - scaler=None, - cuda_enabled=False, - log_freq=50, - accum_grad_iters=1, - ): - return self._train_inner_loop( - epoch=epoch, - iters_per_epoch=lr_scheduler.iters_per_epoch, - model=model, - data_loader=data_loader, - optimizer=optimizer, - scaler=scaler, - lr_scheduler=lr_scheduler, - log_freq=log_freq, - cuda_enabled=cuda_enabled, - accum_grad_iters=accum_grad_iters, - ) - - def train_iters( - self, - epoch, - start_iters, - iters_per_inner_epoch, - model, - data_loader, - optimizer, - lr_scheduler, - scaler=None, - cuda_enabled=False, - log_freq=50, - accum_grad_iters=1, - ): - return self._train_inner_loop( - epoch=epoch, - start_iters=start_iters, - iters_per_epoch=iters_per_inner_epoch, - model=model, - data_loader=data_loader, - optimizer=optimizer, - scaler=scaler, - lr_scheduler=lr_scheduler, - log_freq=log_freq, - cuda_enabled=cuda_enabled, - accum_grad_iters=accum_grad_iters, - ) - - def _train_inner_loop( - self, - epoch, - iters_per_epoch, - model, - data_loader, - optimizer, - lr_scheduler, - scaler=None, - start_iters=None, - log_freq=50, - cuda_enabled=False, - accum_grad_iters=1, - ): - """ - An inner training loop compatible with both epoch-based and iter-based training. - - When using epoch-based, training stops after one epoch; when using iter-based, - training stops after #iters_per_epoch iterations. - """ - use_amp = scaler is not None - - if not hasattr(data_loader, "__next__"): - # convert to iterator if not already - data_loader = iter(data_loader) - - metric_logger = MetricLogger(delimiter=" ") - metric_logger.add_meter("lr", SmoothedValue(window_size=1, fmt="{value:.6f}")) - metric_logger.add_meter("loss", SmoothedValue(window_size=1, fmt="{value:.4f}")) - - # if iter-based runner, schedule lr based on inner epoch. - logging.info( - "Start training epoch {}, {} iters per inner epoch.".format( - epoch, iters_per_epoch - ) - ) - header = "Train: data epoch: [{}]".format(epoch) - if start_iters is None: - # epoch-based runner - inner_epoch = epoch - else: - # In iter-based runner, we schedule the learning rate based on iterations. - inner_epoch = start_iters // iters_per_epoch - header = header + "; inner epoch [{}]".format(inner_epoch) - - for i in metric_logger.log_every(range(iters_per_epoch), log_freq, header): - # if using iter-based runner, we stop after iters_per_epoch iterations. - if i >= iters_per_epoch: - break - - samples = next(data_loader) - - samples = prepare_sample(samples, cuda_enabled=cuda_enabled) - samples.update( - { - "epoch": inner_epoch, - "num_iters_per_epoch": iters_per_epoch, - "iters": i, - } - ) - - lr_scheduler.step(cur_epoch=inner_epoch, cur_step=i) - - with torch.cuda.amp.autocast(enabled=use_amp): - loss = self.train_step(model=model, samples=samples) - - # after_train_step() - if use_amp: - scaler.scale(loss).backward() - else: - loss.backward() - - # update gradients every accum_grad_iters iterations - if (i + 1) % accum_grad_iters == 0: - if use_amp: - scaler.step(optimizer) - scaler.update() - else: - optimizer.step() - optimizer.zero_grad() - - metric_logger.update(loss=loss.item()) - metric_logger.update(lr=optimizer.param_groups[0]["lr"]) - - # after train_epoch() - # gather the stats from all processes - metric_logger.synchronize_between_processes() - logging.info("Averaged stats: " + str(metric_logger.global_avg())) - return { - k: "{:.3f}".format(meter.global_avg) - for k, meter in metric_logger.meters.items() - } - - @staticmethod - def save_result(result, result_dir, filename, remove_duplicate=""): - import json - - result_file = os.path.join( - result_dir, "%s_rank%d.json" % (filename, get_rank()) - ) - final_result_file = os.path.join(result_dir, "%s.json" % filename) - - json.dump(result, open(result_file, "w")) - - if is_dist_avail_and_initialized(): - dist.barrier() - - if is_main_process(): - logging.warning("rank %d starts merging results." % get_rank()) - # combine results from all processes - result = [] - - for rank in range(get_world_size()): - result_file = os.path.join( - result_dir, "%s_rank%d.json" % (filename, rank) - ) - res = json.load(open(result_file, "r")) - result += res - - if remove_duplicate: - result_new = [] - id_list = [] - for res in result: - if res[remove_duplicate] not in id_list: - id_list.append(res[remove_duplicate]) - result_new.append(res) - result = result_new - - json.dump(result, open(final_result_file, "w")) - print("result file saved to %s" % final_result_file) - - return final_result_file diff --git a/sonique/Video_LLaMA/video_llama/tasks/image_text_pretrain.py b/sonique/Video_LLaMA/video_llama/tasks/image_text_pretrain.py deleted file mode 100644 index 733c3fb20dbcd613811f6b6a5c3405068e21f3dc..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/tasks/image_text_pretrain.py +++ /dev/null @@ -1,18 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -from sonique.Video_LLaMA.video_llama.common.registry import registry -from sonique.Video_LLaMA.video_llama.tasks.base_task import BaseTask - - -@registry.register_task("image_text_pretrain") -class ImageTextPretrainTask(BaseTask): - def __init__(self): - super().__init__() - - def evaluation(self, model, data_loader, cuda_enabled=True): - pass diff --git a/sonique/Video_LLaMA/video_llama/tasks/video_text_pretrain.py b/sonique/Video_LLaMA/video_llama/tasks/video_text_pretrain.py deleted file mode 100644 index 1e07c7ae6e97da691933920c84bc405a963d4c5f..0000000000000000000000000000000000000000 --- a/sonique/Video_LLaMA/video_llama/tasks/video_text_pretrain.py +++ /dev/null @@ -1,18 +0,0 @@ -""" - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -from sonique.Video_LLaMA.video_llama.common.registry import registry -from sonique.Video_LLaMA.video_llama.tasks.base_task import BaseTask - - -@registry.register_task("video_text_pretrain") -class VideoTextPretrainTask(BaseTask): - def __init__(self): - super().__init__() - - def evaluation(self, model, data_loader, cuda_enabled=True): - pass diff --git a/sonique/__init__.py b/sonique/__init__.py deleted file mode 100644 index a0892814f23360779caf1bbb23934392f49f5f5e..0000000000000000000000000000000000000000 --- a/sonique/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from .stable_audio_tools.models.factory import create_model_from_config, create_model_from_config_path -from .stable_audio_tools.models.pretrained import get_pretrained_model \ No newline at end of file diff --git a/sonique/evaluation/__init__.py b/sonique/evaluation/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/sonique/inference/__init__.py b/sonique/inference/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/sonique/inference/generation.py b/sonique/inference/generation.py deleted file mode 100644 index af519c69c77148cb9d282f24e206804df2339017..0000000000000000000000000000000000000000 --- a/sonique/inference/generation.py +++ /dev/null @@ -1,174 +0,0 @@ -import numpy as np -import torch -import typing as tp -import math -from torchaudio import transforms as T - -from .utils import prepare_audio -from .sampling import sample, sample_k -from ..stable_audio_tools.data.utils import PadCrop -import gc -import time - -def generate_diffusion_cond( - model, - steps: int = 250, - cfg_scale=6, - conditioning: dict = None, - conditioning_tensors: tp.Optional[dict] = None, - negative_conditioning: dict = None, - negative_conditioning_tensors: tp.Optional[dict] = None, - batch_size: int = 1, - sample_size: int = 2097152, - sample_rate: int = 48000, - seed: int = -1, - device: str = "cuda", - init_audio: tp.Optional[tp.Tuple[int, torch.Tensor]] = None, - init_noise_level: float = 1.0, - mask_args: dict = None, - return_latents = False, - **sampler_kwargs - ) -> torch.Tensor: - """ - Generate audio from a prompt using a diffusion model. - - Args: - model: The diffusion model to use for generation. - steps: The number of diffusion steps to use. - cfg_scale: Classifier-free guidance scale - conditioning: A dictionary of conditioning parameters to use for generation. - conditioning_tensors: A dictionary of precomputed conditioning tensors to use for generation. - batch_size: The batch size to use for generation. - sample_size: The length of the audio to generate, in samples. - sample_rate: The sample rate of the audio to generate (Deprecated, now pulled from the model directly) - seed: The random seed to use for generation, or -1 to use a random seed. - device: The device to use for generation. - init_audio: A tuple of (sample_rate, audio) to use as the initial audio for generation. - init_noise_level: The noise level to use when generating from an initial audio sample. - return_latents: Whether to return the latents used for generation instead of the decoded audio. - **sampler_kwargs: Additional keyword arguments to pass to the sampler. - """ - model.to("cuda") - # The length of the output in audio samples - audio_sample_size = sample_size - - # If this is latent diffusion, change sample_size instead to the downsampled latent size - if model.pretransform is not None: - sample_size = sample_size // model.pretransform.downsampling_ratio - - # Seed - # The user can explicitly set the seed to deterministically generate the same output. Otherwise, use a random seed. - # seed = seed if seed != -1 else np.random.randint(0, 2**31 - 1) - print(seed) - torch.manual_seed(seed) - # Define the initial noise immediately after setting the seed - noise = torch.randn([batch_size, model.io_channels, sample_size], device=device) - - # Conditioning - assert conditioning is not None or conditioning_tensors is not None, "Must provide either conditioning or conditioning_tensors" - if conditioning_tensors is None: - conditioning_tensors = model.conditioner(conditioning, device) - conditioning_tensors = model.get_conditioning_inputs(conditioning_tensors) - - if negative_conditioning is not None or negative_conditioning_tensors is not None: - - if negative_conditioning_tensors is None: - negative_conditioning_tensors = model.conditioner(negative_conditioning, device) - - negative_conditioning_tensors = model.get_conditioning_inputs(negative_conditioning_tensors, negative=True) - else: - negative_conditioning_tensors = {} - - if init_audio is not None: - # The user supplied some initial audio (for inpainting or variation). Let us prepare the input audio. - in_sr, init_audio = init_audio - - io_channels = model.io_channels - - # For latent models, set the io_channels to the autoencoder's io_channels - if model.pretransform is not None: - io_channels = model.pretransform.io_channels - - # Prepare the initial audio for use by the model - init_audio = prepare_audio(init_audio, in_sr=in_sr, target_sr=model.sample_rate, target_length=audio_sample_size, target_channels=io_channels, device=device) - - # For latent models, encode the initial audio into latents - if model.pretransform is not None: - init_audio = model.pretransform.encode(init_audio) - - init_audio = init_audio.repeat(batch_size, 1, 1) - else: - # The user did not supply any initial audio for inpainting or variation. Generate new output from scratch. - init_audio = None - init_noise_level = None - mask_args = None - - # Inpainting mask - if init_audio is not None and mask_args is not None: - # Cut and paste init_audio according to cropfrom, pastefrom, pasteto - # This is helpful for forward and reverse outpainting - cropfrom = math.floor(mask_args["cropfrom"]/100.0 * sample_size) - pastefrom = math.floor(mask_args["pastefrom"]/100.0 * sample_size) - pasteto = math.ceil(mask_args["pasteto"]/100.0 * sample_size) - assert pastefrom < pasteto, "Paste From should be less than Paste To" - croplen = pasteto - pastefrom - if cropfrom + croplen > sample_size: - croplen = sample_size - cropfrom - cropto = cropfrom + croplen - pasteto = pastefrom + croplen - cutpaste = init_audio.new_zeros(init_audio.shape) - cutpaste[:, :, pastefrom:pasteto] = init_audio[:,:,cropfrom:cropto] - #print(cropfrom, cropto, pastefrom, pasteto) - init_audio = cutpaste - # Build a soft mask (list of floats 0 to 1, the size of the latent) from the given args - mask = build_mask(sample_size, mask_args) - mask = mask.to(device) - elif init_audio is not None and mask_args is None: - # variations - sampler_kwargs["sigma_max"] = init_noise_level - mask = None - else: - mask = None - - # Now the generative AI part: - # k-diffusion denoising process go! - sampled = sample_k(model.model, noise, init_audio, mask, steps, **sampler_kwargs, **conditioning_tensors, **negative_conditioning_tensors, cfg_scale=cfg_scale, batch_cfg=True, rescale_cfg=True, device=device) - - # v-diffusion: - #sampled = sample(model.model, noise, steps, 0, **conditioning_tensors, embedding_scale=cfg_scale) - - # Denoising process done. - # If this is latent diffusion, decode latents back into audio - if model.pretransform is not None and not return_latents: - sampled = model.pretransform.decode(sampled) - - model.to('cpu') - if torch.cuda.is_available(): - torch.cuda.empty_cache() - gc.collect() - # Return audio - return sampled - -# builds a softmask given the parameters -# returns array of values 0 to 1, size sample_size, where 0 means noise / fresh generation, 1 means keep the input audio, -# and anything between is a mixture of old/new -# ideally 0.5 is half/half mixture but i haven't figured this out yet -def build_mask(sample_size, mask_args): - maskstart = math.floor(mask_args["maskstart"]/100.0 * sample_size) - maskend = math.ceil(mask_args["maskend"]/100.0 * sample_size) - softnessL = round(mask_args["softnessL"]/100.0 * sample_size) - softnessR = round(mask_args["softnessR"]/100.0 * sample_size) - marination = mask_args["marination"] - # use hann windows for softening the transition (i don't know if this is correct) - hannL = torch.hann_window(softnessL*2, periodic=False)[:softnessL] - hannR = torch.hann_window(softnessR*2, periodic=False)[softnessR:] - # build the mask. - mask = torch.zeros((sample_size)) - mask[maskstart:maskend] = 1 - mask[maskstart:maskstart+softnessL] = hannL - mask[maskend-softnessR:maskend] = hannR - # marination finishes the inpainting early in the denoising schedule, and lets audio get changed in the final rounds - if marination > 0: - mask = mask * (1-marination) - #print(mask) - return mask \ No newline at end of file diff --git a/sonique/inference/priors.py b/sonique/inference/priors.py deleted file mode 100644 index d3c57a955e9befb08a7c8ad40df59ad125e17f4f..0000000000000000000000000000000000000000 --- a/sonique/inference/priors.py +++ /dev/null @@ -1,65 +0,0 @@ -from .generation import generate_diffusion_cond -from ..stable_audio_tools.models.diffusion import ConditionedDiffusionModelWrapper -from ..inference.utils import prepare_audio - -import torch -from torchaudio import transforms as T -from torch.nn import functional as F - -def generate_mono_to_stereo( - model: ConditionedDiffusionModelWrapper, - audio: torch.Tensor, # (batch, channels, time) - in_sr: int, - steps: int, - sampler_kwargs: dict = {}, - ): - """ - Generate stereo audio from mono audio using a diffusion model. - - Args: - model: A mono-to-stereo diffusion prior wrapper - audio: The mono audio to convert to stereo - in_sr: The sample rate of the input audio - steps: The number of diffusion steps to run - sampler_kwargs: Keyword arguments to pass to the diffusion sampler - """ - - device = audio.device - - sample_rate = model.sample_rate - - # Resample input audio if necessary - if in_sr != sample_rate: - resample_tf = T.Resample(in_sr, sample_rate).to(audio.device) - audio = resample_tf(audio) - - audio_length = audio.shape[-1] - - # Pad input audio to be compatible with the model - min_length = model.min_input_length - padded_input_length = audio_length + (min_length - (audio_length % min_length)) % min_length - - # Pad input audio to be compatible with the model - if padded_input_length > audio_length: - audio = F.pad(audio, (0, padded_input_length - audio_length)) - - # Make audio mono, duplicate to stereo - dual_mono = audio.mean(1, keepdim=True).repeat(1, 2, 1) - - if model.pretransform is not None: - dual_mono = model.pretransform.encode(dual_mono) - - conditioning = {"source": [dual_mono]} - - stereo_audio = generate_diffusion_cond( - model, - conditioning_tensors=conditioning, - steps=steps, - sample_size=padded_input_length, - sample_rate=sample_rate, - device=device, - **sampler_kwargs, - ) - - return stereo_audio - diff --git a/sonique/inference/sampling.py b/sonique/inference/sampling.py deleted file mode 100644 index 1c6efcd3770416c7e43a672b805dbd47f646fc4e..0000000000000000000000000000000000000000 --- a/sonique/inference/sampling.py +++ /dev/null @@ -1,170 +0,0 @@ -import torch -import math -from tqdm import trange - -import k_diffusion as K - -# Define the noise schedule and sampling loop -def get_alphas_sigmas(t): - """Returns the scaling factors for the clean image (alpha) and for the - noise (sigma), given a timestep.""" - return torch.cos(t * math.pi / 2), torch.sin(t * math.pi / 2) - -def alpha_sigma_to_t(alpha, sigma): - """Returns a timestep, given the scaling factors for the clean image and for - the noise.""" - return torch.atan2(sigma, alpha) / math.pi * 2 - -def t_to_alpha_sigma(t): - """Returns the scaling factors for the clean image and for the noise, given - a timestep.""" - return torch.cos(t * math.pi / 2), torch.sin(t * math.pi / 2) - -@torch.no_grad() -def sample(model, x, steps, eta, **extra_args): - """Draws samples from a model given starting noise. v-diffusion""" - ts = x.new_ones([x.shape[0]]) - - # Create the noise schedule - t = torch.linspace(1, 0, steps + 1)[:-1] - - alphas, sigmas = get_alphas_sigmas(t) - - # The sampling loop - for i in trange(steps): - - # Get the model output (v, the predicted velocity) - with torch.cuda.amp.autocast(): - v = model(x, ts * t[i], **extra_args).float() - - # Predict the noise and the denoised image - pred = x * alphas[i] - v * sigmas[i] - eps = x * sigmas[i] + v * alphas[i] - - # If we are not on the last timestep, compute the noisy image for the - # next timestep. - if i < steps - 1: - # If eta > 0, adjust the scaling factor for the predicted noise - # downward according to the amount of additional noise to add - ddim_sigma = eta * (sigmas[i + 1]**2 / sigmas[i]**2).sqrt() * \ - (1 - alphas[i]**2 / alphas[i + 1]**2).sqrt() - adjusted_sigma = (sigmas[i + 1]**2 - ddim_sigma**2).sqrt() - - # Recombine the predicted noise and predicted denoised image in the - # correct proportions for the next step - x = pred * alphas[i + 1] + eps * adjusted_sigma - - # Add the correct amount of fresh noise - if eta: - x += torch.randn_like(x) * ddim_sigma - - # If we are on the last timestep, output the denoised image - return pred - -# Soft mask inpainting is just shrinking hard (binary) mask inpainting -# Given a float-valued soft mask (values between 0 and 1), get the binary mask for this particular step -def get_bmask(i, steps, mask): - strength = (i+1)/(steps) - # convert to binary mask - bmask = torch.where(mask<=strength,1,0) - return bmask - -def make_cond_model_fn(model, cond_fn): - def cond_model_fn(x, sigma, **kwargs): - with torch.enable_grad(): - x = x.detach().requires_grad_() - denoised = model(x, sigma, **kwargs) - cond_grad = cond_fn(x, sigma, denoised=denoised, **kwargs).detach() - cond_denoised = denoised.detach() + cond_grad * K.utils.append_dims(sigma**2, x.ndim) - return cond_denoised - return cond_model_fn - -# Uses k-diffusion from https://github.com/crowsonkb/k-diffusion -# init_data is init_audio as latents (if this is latent diffusion) -# For sampling, set both init_data and mask to None -# For variations, set init_data -# For inpainting, set both init_data & mask -def sample_k( - model_fn, - noise, - init_data=None, - mask=None, - steps=100, - sampler_type="dpmpp-2m-sde", - sigma_min=0.5, - sigma_max=50, - rho=1.0, device="cuda", - callback=None, - cond_fn=None, - **extra_args - ): - - denoiser = K.external.VDenoiser(model_fn) - - if cond_fn is not None: - denoiser = make_cond_model_fn(denoiser, cond_fn) - - # Make the list of sigmas. Sigma values are scalars related to the amount of noise each denoising step has - sigmas = K.sampling.get_sigmas_polyexponential(steps, sigma_min, sigma_max, rho, device=device) - # Scale the initial noise by sigma - noise = noise * sigmas[0] - - wrapped_callback = callback - - if mask is None and init_data is not None: - # VARIATION (no inpainting) - # set the initial latent to the init_data, and noise it with initial sigma - x = init_data + noise - elif mask is not None and init_data is not None: - # INPAINTING - bmask = get_bmask(0, steps, mask) - # initial noising - input_noised = init_data + noise - # set the initial latent to a mix of init_data and noise, based on step 0's binary mask - x = input_noised * bmask + noise * (1-bmask) - # define the inpainting callback function (Note: side effects, it mutates x) - # See https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/sampling.py#L596C13-L596C105 - # callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) - # This is called immediately after `denoised = model(x, sigmas[i] * s_in, **extra_args)` - def inpainting_callback(args): - i = args["i"] - x = args["x"] - sigma = args["sigma"] - #denoised = args["denoised"] - # noise the init_data input with this step's appropriate amount of noise - input_noised = init_data + torch.randn_like(init_data) * sigma - # shrinking hard mask - bmask = get_bmask(i, steps, mask) - # mix input_noise with x, using binary mask - new_x = input_noised * bmask + x * (1-bmask) - # mutate x - x[:,:,:] = new_x[:,:,:] - # wrap together the inpainting callback and the user-submitted callback. - if callback is None: - wrapped_callback = inpainting_callback - else: - wrapped_callback = lambda args: (inpainting_callback(args), callback(args)) - else: - # SAMPLING - # set the initial latent to noise - x = noise - - - with torch.cuda.amp.autocast(): - if sampler_type == "k-heun": - return K.sampling.sample_heun(denoiser, x, sigmas, disable=False, callback=wrapped_callback, extra_args=extra_args) - elif sampler_type == "k-lms": - return K.sampling.sample_lms(denoiser, x, sigmas, disable=False, callback=wrapped_callback, extra_args=extra_args) - elif sampler_type == "k-dpmpp-2s-ancestral": - return K.sampling.sample_dpmpp_2s_ancestral(denoiser, x, sigmas, disable=False, callback=wrapped_callback, extra_args=extra_args) - elif sampler_type == "k-dpm-2": - return K.sampling.sample_dpm_2(denoiser, x, sigmas, disable=False, callback=wrapped_callback, extra_args=extra_args) - elif sampler_type == "k-dpm-fast": - return K.sampling.sample_dpm_fast(denoiser, x, sigma_min, sigma_max, steps, disable=False, callback=wrapped_callback, extra_args=extra_args) - elif sampler_type == "k-dpm-adaptive": - return K.sampling.sample_dpm_adaptive(denoiser, x, sigma_min, sigma_max, rtol=0.01, atol=0.01, disable=False, callback=wrapped_callback, extra_args=extra_args) - elif sampler_type == "dpmpp-2m-sde": - return K.sampling.sample_dpmpp_2m_sde(denoiser, x, sigmas, disable=False, callback=wrapped_callback, extra_args=extra_args) - elif sampler_type == "dpmpp-3m-sde": - return K.sampling.sample_dpmpp_3m_sde(denoiser, x, sigmas, disable=False, callback=wrapped_callback, extra_args=extra_args) - diff --git a/sonique/inference/utils.py b/sonique/inference/utils.py deleted file mode 100644 index ea218c9dbc2adfa3f4dd6681e8228f5a59b62ee3..0000000000000000000000000000000000000000 --- a/sonique/inference/utils.py +++ /dev/null @@ -1,35 +0,0 @@ -from ..stable_audio_tools.data.utils import PadCrop - -from torchaudio import transforms as T - -def set_audio_channels(audio, target_channels): - if target_channels == 1: - # Convert to mono - audio = audio.mean(1, keepdim=True) - elif target_channels == 2: - # Convert to stereo - if audio.shape[1] == 1: - audio = audio.repeat(1, 2, 1) - elif audio.shape[1] > 2: - audio = audio[:, :2, :] - return audio - -def prepare_audio(audio, in_sr, target_sr, target_length, target_channels, device): - - audio = audio.to(device) - - if in_sr != target_sr: - resample_tf = T.Resample(in_sr, target_sr).to(device) - audio = resample_tf(audio) - - audio = PadCrop(target_length, randomize=False)(audio) - - # Add batch dimension - if audio.dim() == 1: - audio = audio.unsqueeze(0).unsqueeze(0) - elif audio.dim() == 2: - audio = audio.unsqueeze(0) - - audio = set_audio_channels(audio, target_channels) - - return audio \ No newline at end of file diff --git a/sonique/interface/__init__.py b/sonique/interface/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/sonique/interface/gradio.py b/sonique/interface/gradio.py deleted file mode 100644 index 8715473cbcccbc7f128b6c868bd0a8545501cc07..0000000000000000000000000000000000000000 --- a/sonique/interface/gradio.py +++ /dev/null @@ -1,882 +0,0 @@ -import gc -import numpy as np -import gradio as gr -import json -import torch -import torchaudio -import os -import random - -from aeiou.viz import audio_spectrogram_image -from einops import rearrange -from safetensors.torch import load_file -from torch.nn import functional as F -from torchaudio import transforms as T -from torch.cuda.amp import autocast - -from ..inference.generation import generate_diffusion_cond -from ..inference.priors import generate_mono_to_stereo -from ..stable_audio_tools.models.factory import create_model_from_config -from ..stable_audio_tools.models.pretrained import get_pretrained_model -from ..stable_audio_tools.models.utils import load_ckpt_state_dict -from ..inference.utils import prepare_audio -from ..stable_audio_tools.training.utils import copy_state_dict -from ..Video_LLaMA.inference import generate_prompt_from_video_description - -from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig -from moviepy.editor import VideoFileClip, AudioFileClip -import re - - -model = None -sample_rate = 32000 -sample_size = 1920000 - -def add_music_to_video(video, music, output_path): - v = VideoFileClip(video) - m = AudioFileClip(music) - m = m.subclip(0, min(m.duration, v.duration)) - demo_clip = v.set_audio(m) - demo_clip.write_videofile(output_path, codec="libx264", audio_codec="aac") - v.close() - m.close() - return output_path - -def load_model(model_config=None, model_ckpt_path=None, pretrained_name=None, pretransform_ckpt_path=None, device="cuda"): - global model, sample_rate, sample_size - - if pretrained_name is not None: - print(f"Loading pretrained model {pretrained_name}") - model, model_config = get_pretrained_model(pretrained_name) - - elif model_config is not None and model_ckpt_path is not None: - print(f"Creating model from config") - model = create_model_from_config(model_config) - - print(f"Loading model checkpoint from {model_ckpt_path}") - # Load checkpoint - copy_state_dict(model, load_ckpt_state_dict(model_ckpt_path)) - #model.load_state_dict(load_ckpt_state_dict(model_ckpt_path)) - - sample_rate = model_config["sample_rate"] - sample_size = model_config["sample_size"] - - if pretransform_ckpt_path is not None: - print(f"Loading pretransform checkpoint from {pretransform_ckpt_path}") - model.pretransform.load_state_dict(load_ckpt_state_dict(pretransform_ckpt_path), strict=False) - print(f"Done loading pretransform") - - model.to(device).eval().requires_grad_(False) - - print(f"Done loading model") - - return model, model_config - -def generate_cond( - instruments, - genres, - tempo, - negative_prompt=None, - seconds_start=0, - seconds_total=23, - cfg_scale=6.0, - steps=300, - preview_every=None, - seed=-1, - sampler_type="dpmpp-2m-sde", - sigma_min=0.03, - sigma_max=50, - cfg_rescale=0.4, - use_init=False, - init_audio=None, - init_noise_level=1.0, - use_video=False, - input_video=None, - llms="mistral-7b", - low_resource=True, - mask_cropfrom=None, - mask_pastefrom=None, - mask_pasteto=None, - mask_maskstart=None, - mask_maskend=None, - mask_softnessL=None, - mask_softnessR=None, - mask_marination=None, - prompt=None, - batch_size=1 - ): - import time - start_time = time.time() - - global preview_images - preview_images = [] - if preview_every == 0: - preview_every = None - print(f'use video? {use_video}, use melody? {use_init}') - - if prompt is not None: - prompt = prompt.lower() - else: - prompt = f"{instruments}, {genres}, {tempo}" - prompt = prompt.lower() - - print(prompt) - # Return fake stereo audio - conditioning = [{"prompt": prompt, "seconds_start": seconds_start, "seconds_total": seconds_total}] * batch_size - - if negative_prompt: - negative_conditioning = [{"prompt": negative_prompt, "seconds_start": seconds_start, "seconds_total": seconds_total}] * batch_size - else: - negative_conditioning = None - - #Get the device from the model - # device = next(model.parameters()).device - device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - - seed = int(seed) if int(seed) != -1 else np.random.randint(0, 2**31 - 1) - print(f'Seed: {seed}') - if not use_video: - input_video = None - video_duration = 0 - if input_video is not None: - video_clip = VideoFileClip(input_video) - video_duration = video_clip.duration - if video_duration > 23: - video_clip = video_clip.subclip(0, 23) - video_des = generate_prompt_from_video_description(cfg_path="sonique/Video_LLaMA/eval_configs/video_llama_eval_only_vl.yaml", model_type="llama_v2", gpu_id=0, input_file=input_video, low_resource=low_resource) - # # Low resource code adapt from: https://huggingface.co/blog/4bit-transformers-bitsandbytes - # # Qwen - if llms == "qwen-14b": - if low_resource: - llm = AutoModelForCausalLM.from_pretrained( - "Qwen/Qwen1.5-14B-Chat", - quantization_config=BitsAndBytesConfig( - load_in_4bit=True, - bnb_4bit_compute_dtype=torch.float16 - ) - ) - else: - llm = AutoModelForCausalLM.from_pretrained( - "Qwen/Qwen1.5-14B-Chat", - device_map="cuda", - torch_dtype=torch.float16, - ) - tokenizer = AutoTokenizer.from_pretrained( - "Qwen/Qwen1.5-14B-Chat" - ) - messages = [ - {"role": "system", "content": "As a music composer fluent in English, you're tasked with creating background music for video. Based on the scene described, provide only one set of tags in English that describe this background music for the video. These tags must includes instruments, music genres, and tempo (BPM). Avoid any non-English words. Example of expected output: Piano, Synths, Strings, Violin, Flute, Reflective, Slow tempo, 96 BPM"}, - {"role": "user", "content": str(video_des)} - ] - text = tokenizer.apply_chat_template( - messages, - tokenize=False, - add_generation_prompt=True - ) - llm_inputs = tokenizer([text], return_tensors="pt").to(llm.device) - generated_ids = llm.generate( - llm_inputs.input_ids, - max_new_tokens=512 - ) - generated_ids = [ - output_ids[len(input_ids):] for input_ids, output_ids in zip(llm_inputs.input_ids, generated_ids) - ] - response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] - - elif llms == "mistral-7b": - # Mistral - 7B - if low_resource: - llm = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3", - quantization_config=BitsAndBytesConfig( - load_in_4bit=True, - bnb_4bit_compute_dtype=torch.float16 - ) - ) - else: - llm = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3", - device_map="cuda", - torch_dtype=torch.float16 - ) - tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3") - messages = [{"role": "user", "content": f"As a music composer fluent in English, you're tasked with creating background music for video. \ - Based on the scene described, provide only one set of tags in English that describe this background \ - music for the video. These tags must include instruments, music genres, and tempo rate(e.g. 90 BPM). \ - Avoid any non-English words. \ - The output must be only one and must be in one line. Do not provide multiple sets of output. \ - Example output: Soft, Relaxing, Piano, Cover, Grand, Calm, Classical \ - Input: {video_des}"}] - - encodeds = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) - llm_inputs = tokenizer([encodeds], return_tensors="pt").to(device) - # llm.to(device) - - generated_ids = llm.generate(llm_inputs.input_ids, max_new_tokens=512) - generated_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(llm_inputs.input_ids, generated_ids)] - response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] - - # elif llms == "mistral-7b-ft": - # # Fine-tuned version of Mistral-7B - # from peft import AutoPeftModelForCausalLM - # from transformers import pipeline - # peft_model_id = "./ckpts/mistral-7b-audio-tags" - # llm = AutoPeftModelForCausalLM.from_pretrained( - # peft_model_id, - # quantization_config=BitsAndBytesConfig( - # load_in_4bit=True, - # bnb_4bit_compute_dtype=torch.float16 - # ) - # ) - # tokenizer = AutoTokenizer.from_pretrained(peft_model_id) - # pipe = pipeline("text-generation", model=llm, tokenizer=tokenizer) - # messages = [{"role": "system", "content": "As a music composer \ - # fluent in English, you're tasked with creating \ - # background music for video. \ - # Based on the scene described, \ - # provide only one set of tags in English that \ - # describe this background \ - # music for the video. \ - # These tags must include instruments, \ - # music genres, and tempo rate(e.g. 90 BPM). \ - # Avoid any non-English words. Please return the tags in the \ - # following JSON structure: {{'tags': ['tag1', 'tag2', 'tag3']}}"}, - # {"role": "user", "content": video_des} - # ] - # prompt = pipe.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) - # outputs = pipe(prompt, max_new_tokens=256, do_sample=False, temperature=0.1, top_k=50, top_p=0.1, eos_token_id=pipe.tokenizer.eos_token_id, pad_token_id=pipe.tokenizer.pad_token_id) - # response = outputs[0]['generated_text'][len(prompt):].strip() - # print(f'ft llm response {response}') - - elif llms == "gemma-7b": - # Gemma - 7B - if low_resource: - llm = AutoModelForCausalLM.from_pretrained("google/gemma-7b-it", - quantization_config=BitsAndBytesConfig( - load_in_4bit=True, - bnb_4bit_compute_dtype=torch.float16 - ) - # device_map="auto", - # torch_dtype=torch.float16, - # low_cpu_mem_usage=True, - # load_in_4bit=True - ) - else: - llm = AutoModelForCausalLM.from_pretrained("google/gemma-7b-it", - device_map="cuda", - torch_dtype=torch.float16 - ) - tokenizer = AutoTokenizer.from_pretrained("google/gemma-7b-it") - - inputs = f"As a music composer fluent in English, you're tasked with creating background music for video. \ - Based on the scene described, provide only one set of tags in English that describe this background \ - music for the video. These tags must include instruments, music genres, and tempo rate(e.g. 90 BPM). \ - Avoid any non-English words. Please return the tags in the following JSON structure: {{\'tags\': [\'tag1\', \'tag2\', \'tag3\']}} \ - Inputs: {video_des}" - input_ids = tokenizer(inputs, return_tensors="pt").to(llm.device) - outputs = llm.generate(**input_ids, max_new_tokens=512) - responses = tokenizer.decode(outputs[0]) - responses = responses.split("Inputs:")[-1] - print(responses) - # Extract only tags from gemma response - matched = re.findall(r"\{'tags': \[.*?\]\}|\{\"tags\": \[.*?\]\}", responses) - if matched: - json_str = matched[-1] - - json_str = json_str.replace("'", '"') - - try: - parsed_json = json.loads(json_str) - - lst = parsed_json['tags'] - response = ', '.join(lst) - print("Extracted Tags:", response) - except json.JSONDecodeError as e: - print("Failed to parse JSON:", e) - else: - print("Failed to extract JSON string from response.") - - # elif llms == "llama3-8b": - # if low_resource: - # llm = AutoModelForCausalLM.from_pretrained( - # "meta-llama/Meta-Llama-3-8B-Instruct", - # quantization_config=BitsAndBytesConfig( - # load_in_4bit=True, - # bnb_4bit_compute_dtype=torch.float16 - # ) - # ) - # else: - # llm = AutoModelForCausalLM.from_pretrained( - # "meta-llama/Meta-Llama-3-8B-Instruct", - # device_map="cuda", - # torch_dtype=torch.float16 - # ) - # tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct") - # messages = [ - # {"role": "system", "content": "As a music composer fluent in English, you're tasked with creating background music for video. \ - # Based on the scene described, provide only one set of tags in English that describe this background music for the video. \ - # These tags must includes instruments, music genres, and tempo (BPM). Avoid any non-English words. \ - # Example of expected output: Piano, Synths, Strings, Violin, Flute, Reflective, Slow tempo, 96 BPM \ - # Please return the tags in the following JSON structure: {{\'tags\': [\'tag1\', \'tag2\', \'tag3\']}}"}, - # {"role": "user", "content": str(video_des)} - # ] - # text = tokenizer.apply_chat_template( - # messages, - # tokenize=False, - # add_generation_prompt=True - # ) - # llm_inputs = tokenizer([text], return_tensors="pt").to(llm.device) - # generated_ids = llm.generate( - # llm_inputs.input_ids, - # max_new_tokens=512 - # ) - # generated_ids = [ - # output_ids[len(input_ids):] for input_ids, output_ids in zip(llm_inputs.input_ids, generated_ids) - # ] - # responses = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] - # print(f'responses:{responses}') - # matched = re.findall(r"\{'tags': \[.*?\]\}|\{\"tags\": \[.*?\]\}", responses) - # if matched: - # json_str = matched[-1] - - # json_str = json_str.replace("'", '"') - - # try: - # parsed_json = json.loads(json_str) - - # lst = parsed_json['tags'] - # response = ', '.join(lst) - # print("Extracted Tags:", response) - # except json.JSONDecodeError as e: - # print("Failed to parse JSON:", e) - # else: - # print("Failed to extract JSON string from response.") - - # elif llms == "llama2-13b": - # if low_resource: - # llm = AutoModelForCausalLM.from_pretrained( - # "meta-llama/Llama-2-13b-chat-hf", - # quantization_config=BitsAndBytesConfig( - # load_in_4bit=True, - # bnb_4bit_compute_dtype=torch.float16 - # ) - # ) - # else: - # llm = AutoModelForCausalLM.from_pretrained( - # "meta-llama/Llama-2-13b-chat-hf", - # device_map="cuda", - # torch_dtype=torch.float16 - # ) - # tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-13b-chat-hf") - # messages = [ - # {"role": "system", "content": "As a music composer fluent in English, you're tasked with creating background music for video. \ - # Based on the scene described, provide only one set of tags in English that describe this background music for the video. \ - # These tags must includes instruments, music genres, and tempo (BPM). Avoid any non-English words. \ - # Example of expected output: Piano, Synths, Strings, Violin, Flute, Reflective, Slow tempo, 96 BPM \ - # Please return the tags in the following JSON structure: {{\'tags\': [\'tag1\', \'tag2\', \'tag3\']}}"}, - # {"role": "user", "content": str(video_des)} - # ] - # text = tokenizer.apply_chat_template( - # messages, - # tokenize=False, - # add_generation_prompt=True - # ) - # llm_inputs = tokenizer([text], return_tensors="pt").to(llm.device) - # generated_ids = llm.generate( - # llm_inputs.input_ids, - # max_new_tokens=512 - # ) - # generated_ids = [ - # output_ids[len(input_ids):] for input_ids, output_ids in zip(llm_inputs.input_ids, generated_ids) - # ] - # responses = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] - # print(responses) - # matched = re.findall(r"\{'tags': \[.*?\]\}|\{\"tags\": \[.*?\]\}", responses) - # if matched: - # json_str = matched[-1] - - # json_str = json_str.replace("'", '"') - - # try: - # parsed_json = json.loads(json_str) - - # lst = parsed_json['tags'] - # response = ', '.join(lst) - # print("Extracted Tags:", response) - # except json.JSONDecodeError as e: - # print("Failed to parse JSON:", e) - # else: - # print("Failed to extract JSON string from response.") - # Clean up memory - del llm - gc.collect() - torch.cuda.empty_cache() - - current_prompt = conditioning[0]['prompt'] - current_elements = current_prompt.split(', ') - new_elements = response.split(', ') - - print(f'current element: {current_elements}') - print(f'new elements: {new_elements}') - - current_bpm = next((element for element in current_elements if 'bpm' in element), None) - new_bpm = next((element for element in new_elements if 'BPM' in element), None) - - if current_bpm: - current_elements.remove(current_bpm) - if new_bpm: - new_elements.remove(new_bpm) - - updated_elements = set(current_elements) - updated_elements.update(new_elements) - - bpm_to_include = current_bpm if current_bpm else new_bpm - bpm_to_include = bpm_to_include - updated_prompt = ', '.join(sorted(updated_elements)) + (', ' + bpm_to_include if bpm_to_include else '') - conditioning[0]['prompt'] = updated_prompt.lower() - conditioning[0]['seconds_start'] = 0 - conditioning[0]['seconds_total'] = int(video_duration) - - print(f'updated conditioning prompt: {conditioning}') - - if not use_init: - init_audio = None - - input_sample_size = sample_size - - if init_audio is not None: - in_sr, init_audio = init_audio - # Turn into torch tensor, converting from int16 to float32 - init_audio = torch.from_numpy(init_audio).float().div(32767) - - if init_audio.dim() == 1: - init_audio = init_audio.unsqueeze(0) # [1, n] - elif init_audio.dim() == 2: - init_audio = init_audio.transpose(0, 1) # [n, 2] -> [2, n] - - if in_sr != sample_rate: - resample_tf = T.Resample(in_sr, sample_rate).to(init_audio.device) - init_audio = resample_tf(init_audio) - - audio_length = init_audio.shape[-1] - - if audio_length > sample_size: - - input_sample_size = audio_length + (model.min_input_length - (audio_length % model.min_input_length)) % model.min_input_length - - init_audio = (sample_rate, init_audio) - - def progress_callback(callback_info): - print(f'getting callback info: {callback_info}') - global preview_images - denoised = callback_info["denoised"] - current_step = callback_info["i"] - sigma = callback_info["sigma"] - - if (current_step - 1) % preview_every == 0: - if model.pretransform is not None: - denoised = model.pretransform.decode(denoised) - denoised = rearrange(denoised, "b d n -> d (b n)") - denoised = denoised.clamp(-1, 1).mul(32767).to(torch.int16).cpu() - audio_spectrogram = audio_spectrogram_image(denoised, sample_rate=sample_rate) - preview_images.append((audio_spectrogram, f"Step {current_step} sigma={sigma:.3f})")) - - # If inpainting, send mask args - # This will definitely change in the future - if mask_cropfrom is not None: - mask_args = { - "cropfrom": mask_cropfrom, - "pastefrom": mask_pastefrom, - "pasteto": mask_pasteto, - "maskstart": mask_maskstart, - "maskend": mask_maskend, - "softnessL": mask_softnessL, - "softnessR": mask_softnessR, - "marination": mask_marination, - } - else: - mask_args = None - - # Do the audio generation - audio = generate_diffusion_cond( - model, - conditioning=conditioning, - negative_conditioning=negative_conditioning, - steps=steps, - cfg_scale=cfg_scale, - batch_size=batch_size, - sample_size=input_sample_size, - sample_rate=sample_rate, - seed=seed, - device=device, - sampler_type=sampler_type, - sigma_min=sigma_min, - sigma_max=sigma_max, - init_audio=init_audio, - init_noise_level=init_noise_level, - mask_args = mask_args, - callback = progress_callback if preview_every is not None else None, - scale_phi = cfg_rescale - ) - - # Convert to WAV file - audio = rearrange(audio, "b d n -> d (b n)") - audio = audio.clamp(-1, 1).mul(32767).to(torch.int16).cpu() - torchaudio.save("output.wav", audio, sample_rate) - end = time.time() - print(f'Total process time: {end - start_time}') - - # Let's look at a nice spectrogram too - if use_video: - demo_video = add_music_to_video(input_video, "output.wav", "output.mp4") - audio_spectrogram = audio_spectrogram_image(audio, sample_rate=sample_rate) - return ("output.wav", demo_video, [audio_spectrogram, *preview_images], updated_prompt) - - else: - audio_spectrogram = audio_spectrogram_image(audio, sample_rate=sample_rate) - return ("output.wav", None, [audio_spectrogram, *preview_images], prompt) - - - -def clear_all(): - return "", "", "", "", 0, 23, 3.0, 300, 0, -1, "dpmpp-2m-sde", 0.03, 80, 0.2, False, None, 3, False, None, "mistral-7b" - -case_note_upload = (""" -### Some examples provided at the bottom of the page. Click on them to try them out! -""") - -def create_sampling_ui(model_config, inpainting=False): - - model_conditioning_config = model_config["model"].get("conditioning", None) - - has_seconds_start = False - has_seconds_total = False - - if model_conditioning_config is not None: - for conditioning_config in model_conditioning_config["configs"]: - if conditioning_config["id"] == "seconds_start": - has_seconds_start = True - if conditioning_config["id"] == "seconds_total": - has_seconds_total = True - with gr.Row(): - with gr.Column(scale=6): - use_video = gr.Checkbox(label="Use video", value=False) - video_input = gr.Video(label="Input video(23 secs max)") - gr.Markdown(case_note_upload) - with gr.Column(scale=6): - instruments = gr.Textbox(label="Optional: enter instruments", placeholder="Enter desired instruments. E.G: piano, drums...") - genres = gr.Textbox(label="Optional: enter genres", placeholder="Enter desired genres. E.G: rock, jazz...") - tempo = gr.Textbox(label="Optional: enter tempo rate", placeholder="Enter desired tempo rate. E.G: 120 bpm,") - negative_prompt = gr.Textbox(label="Optional: enter negative tags", placeholder="Negative tags - things you don't want in the output.") - llms = gr.Dropdown(["mistral-7b", - "gemma-7b", - # "llama3-8b", - "qwen-14b", - # "llama2-13b", - # "mistral-7b-ft" - ], - label="Required: LLMs", info="Select llm to extract video description to tags. Default Mistral-7B") - low_resource = gr.Checkbox(label="Optional: To run the model in low_resource mode", value=True) - generate_button = gr.Button("Generate", variant='primary', scale=1) - clear_all_button = gr.Button("Clear all") - - with gr.Row(equal_height=False): - with gr.Column(): - with gr.Accordion("Optional: use melody condition(inpaint)", open=False): - with gr.Row(): - init_audio_checkbox = gr.Checkbox(label="Use melody condition") - init_audio_input = gr.Audio(label="Melody condition audio") - init_noise_level_slider = gr.Slider(minimum=0.1, maximum=100.0, step=0.01, value=3, label="Init noise level") - with gr.Accordion("Generation params", open=False): - with gr.Row(): - # Steps slider - steps_slider = gr.Slider(minimum=1, maximum=500, step=1, value=300, label="Steps") - - # Preview Every slider - preview_every_slider = gr.Slider(minimum=0, maximum=100, step=1, value=0, label="Preview Every") - - # CFG scale - cfg_scale_slider = gr.Slider(minimum=0.0, maximum=25.0, step=0.1, value=3.0, label="CFG scale") - - seconds_start_slider = gr.Slider(minimum=0, maximum=512, step=1, value=0, label="Seconds start", visible=has_seconds_start) - seconds_total_slider = gr.Slider(minimum=0, maximum=512, step=1, value=sample_size//sample_rate, label="Seconds total", visible=has_seconds_total) - with gr.Accordion("Sampler params", open=False): - - # Seed - seed_textbox = gr.Textbox(label="Seed (set to -1 for random seed)", value="-1") - - # Sampler params - with gr.Row(): - sampler_type_dropdown = gr.Dropdown(["dpmpp-2m-sde", "dpmpp-3m-sde", "k-heun", "k-lms", "k-dpmpp-2s-ancestral", "k-dpm-2", "k-dpm-fast"], label="Sampler type", value="dpmpp-2m-sde") - sigma_min_slider = gr.Slider(minimum=0.0, maximum=2.0, step=0.01, value=0.03, label="Sigma min") - sigma_max_slider = gr.Slider(minimum=0.0, maximum=200.0, step=0.1, value=80, label="Sigma max") - cfg_rescale_slider = gr.Slider(minimum=0.0, maximum=1, step=0.01, value=0.2, label="CFG rescale amount") - - inputs = [ - # prompt, - instruments, - genres, - tempo, - negative_prompt, - seconds_start_slider, - seconds_total_slider, - cfg_scale_slider, - steps_slider, - preview_every_slider, - seed_textbox, - sampler_type_dropdown, - sigma_min_slider, - sigma_max_slider, - cfg_rescale_slider, - init_audio_checkbox, - init_audio_input, - init_noise_level_slider, - use_video, - video_input, - llms, - low_resource - ] - - with gr.Row(): - with gr.Column(): - audio_output = gr.Audio(label="Output audio", interactive=False) - audio_spectrogram_output = gr.Gallery(label="Output spectrogram", show_label=False) - with gr.Column(): - video_output = gr.Video(label="Preview Video") - current_prompt = gr.Text(label="Currently used prompt") - - generate_button.click(fn=generate_cond, - inputs=inputs, - outputs=[ - audio_output, - video_output, - audio_spectrogram_output, - current_prompt - ], - api_name="generate") - - clear_all_button.click(fn=clear_all,inputs=[],outputs=[instruments, - genres, - tempo, - negative_prompt, - seconds_start_slider, - seconds_total_slider, - cfg_scale_slider, - steps_slider, - preview_every_slider, - seed_textbox, - sampler_type_dropdown, - sigma_min_slider, - sigma_max_slider, - cfg_rescale_slider, - init_audio_checkbox, - init_audio_input, - init_noise_level_slider, - use_video, - video_input, - llms]) - - video_only_inputs = [ - use_video, - video_input, - init_audio_checkbox, - init_audio_input, - llms - ] - video_examples = gr.Examples(examples=[ - [True, "./demo_videos/Infinite_car_chase.mp4", False, None, "mistral-7b"], - [True, "./demo_videos/Lei_and_Josh.mp4", False, None, "mistral-7b"], - [True, "./demo_videos/breakingbad_6.mp4", False, None, "mistral-7b"], - [True, "./demo_videos/zootopia.mp4", False, None, "mistral-7b"], - [True, "./demo_videos/friends.mp4", False, None, "mistral-7b"], - [True, "./demo_videos/balenciaga_22.mp4", False, None, "mistral-7b"], - ], - inputs=video_only_inputs, - outputs=[audio_output, - video_output, - audio_spectrogram_output, - current_prompt], - fn=generate_cond, - cache_examples=False, - label="Example Video Input") - # video_with_melody = [ - # init_audio_checkbox, - # init_audio_input, - # init_noise_level_slider, - # use_video, - # video_input, - # llms - # ] - # video_melody_examples = gr.Examples(examples=[ - # [True,"./demo_videos/000590.wav", 3, True, "./demo_videos/Better_Call_Saul2.mp4", "mistral-7b"], - # [True,"./demo_videos/1908-1.wav", 3, True, "./demo_videos/breakingbad_6.mp4", "mistral-7b"], - # ], - # inputs=video_with_melody, - # outputs=[audio_output, - # video_output, - # audio_spectrogram_output, - # current_prompt], - # fn=generate_cond, - # cache_examples=False, - # label="Example Video+Melody Input") - - # prompt_input = [ - # instruments, - # genres, - # tempo, - # init_audio_checkbox, - # init_audio_input, - # use_video, - # video_input - # ] - # prompt_examples = gr.Examples(examples=[ - # ["Guitar, Drums, Bass", "Rock", "130 bpm", False, None, False, None], - # ["Piano", "Classical, Ambient, Slow", "80 bpm", False, None, False, None], - # ["Drums", "", "80 bpm", False, None, False, None] - # ], - # inputs=prompt_input, - # outputs=[audio_output, - # video_output, - # audio_spectrogram_output, - # current_prompt], - # fn=generate_cond, - # cache_examples=False, - # label="Example Prompt Input") - - # prompt_melody_input = [ - # instruments, - # genres, - # tempo, - # init_audio_checkbox, - # init_audio_input, - # init_noise_level_slider, - # use_video, - # video_input - # ] - # prompt_melody_examples = gr.Examples(examples=[ - # ["Guitar, Piano, Bass", "Jazz", "130 bpm", True, "./demo_videos/drums.wav", 5, False, None], - # ["Piano", "Ambient, Slow", "70 bpm", True, "./demo_videos/1908-4.wav", 3, False, None], - # ], - # inputs=prompt_melody_input, - # outputs=[audio_output, - # video_output, - # audio_spectrogram_output, - # current_prompt], - # fn=generate_cond, - # cache_examples=False, - # label="Example Prompt+Melody Input") - with gr.Blocks(): - - with gr.Row(): - video_examples - - # with gr.Row(): - # video_melody_examples - - # with gr.Row(): - # prompt_examples - # with gr.Row(): - # prompt_melody_examples - - - - - -def create_txt2audio_ui(model_config): - with gr.Blocks() as ui: - gr.Markdown( - """ -

SONIQUE: Video Background Music Generation Using Unpaired Audio-Visual Data

- -
A model for generating background music tailored to video content. \ - Users can control specific aspects of the music, such as instruments, \ - genres, tempo, and melodies, ensuring the generated output fits their creative vision. -
- -

Video Music:

-
  • 1.Drop or upload videos to the section, check `use video` box.
  • -
  • 2.Optional: enter any desire instruments, genres and tempo on the right. \ - Also negative tags for things you don't want in the generated music.
  • -
  • 3.Choose a desire LLM from the list. Default: Mistral-7B.
  • -
  • 4.Click Generate button.
  • -
  • Optional: You may upload melody as condition(inpaint) in below section.\ - You may also tune the Generation parameters and Sampler parameters.
  • - - To use without video, simply uncheck the `use video` box and enter any desired instruments, \ - genres, and tempo. Including any melody condition you want. - - Please note: Only uncheck `low_resource` mode if you have enough GPU memory (> 24GB) - - """ - ) - with gr.Tab("Generation"): - create_sampling_ui(model_config) - # with gr.Tab("Inpainting"): - # create_sampling_ui(model_config, inpainting=True) - return ui - -def diffusion_prior_process(audio, steps, sampler_type, sigma_min, sigma_max): - - if torch.cuda.is_available(): - torch.cuda.empty_cache() - gc.collect() - - #Get the device from the model - device = next(model.parameters()).device - - in_sr, audio = audio - - audio = torch.from_numpy(audio).float().div(32767).to(device) - - if audio.dim() == 1: - audio = audio.unsqueeze(0) # [1, n] - elif audio.dim() == 2: - audio = audio.transpose(0, 1) # [n, 2] -> [2, n] - - audio = audio.unsqueeze(0) - - audio = generate_mono_to_stereo(model, audio, in_sr, steps, sampler_kwargs={"sampler_type": sampler_type, "sigma_min": sigma_min, "sigma_max": sigma_max}) - - audio = rearrange(audio, "b d n -> d (b n)") - - audio = audio.clamp(-1, 1).mul(32767).to(torch.int16).cpu() - - torchaudio.save("output.wav", audio, sample_rate) - - return "output.wav" - -def create_diffusion_prior_ui(model_config): - with gr.Blocks() as ui: - input_audio = gr.Audio(label="Input audio") - output_audio = gr.Audio(label="Output audio", interactive=False) - # Sampler params - with gr.Row(): - steps_slider = gr.Slider(minimum=1, maximum=500, step=1, value=100, label="Steps") - sampler_type_dropdown = gr.Dropdown(["dpmpp-2m-sde", "dpmpp-3m-sde", "k-heun", "k-lms", "k-dpmpp-2s-ancestral", "k-dpm-2", "k-dpm-fast"], label="Sampler type", value="dpmpp-2m-sde") - sigma_min_slider = gr.Slider(minimum=0.0, maximum=2.0, step=0.01, value=0.03, label="Sigma min") - sigma_max_slider = gr.Slider(minimum=0.0, maximum=200.0, step=0.1, value=80, label="Sigma max") - process_button = gr.Button("Process", variant='primary', scale=1) - process_button.click(fn=diffusion_prior_process, inputs=[input_audio, steps_slider, sampler_type_dropdown, sigma_min_slider, sigma_max_slider], outputs=output_audio, api_name="process") - - return ui - -def create_ui(model_config_path=None, ckpt_path=None, pretrained_name=None, pretransform_ckpt_path=None): - - assert (pretrained_name is not None) ^ (model_config_path is not None and ckpt_path is not None), "Must specify either pretrained name or provide a model config and checkpoint, but not both" - - if model_config_path is not None: - # Load config from json file - with open(model_config_path) as f: - model_config = json.load(f) - else: - model_config = None - - device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - _, model_config = load_model(model_config, ckpt_path, pretrained_name=pretrained_name, pretransform_ckpt_path=pretransform_ckpt_path, device=device) - - model_type = model_config["model_type"] - - if model_type == "diffusion_cond": - ui = create_txt2audio_ui(model_config) - elif model_type == "diffusion_prior": - ui = create_diffusion_prior_ui(model_config) - - return ui \ No newline at end of file diff --git a/sonique/stable_audio_tools/data/__init__.py b/sonique/stable_audio_tools/data/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/sonique/stable_audio_tools/data/dataset.py b/sonique/stable_audio_tools/data/dataset.py deleted file mode 100644 index c80ae1366610313b41ccf7401b5db2cef9497387..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/data/dataset.py +++ /dev/null @@ -1,637 +0,0 @@ -import importlib -import numpy as np -import io -import os -import posixpath -import random -import re -import subprocess -import time -import torch -import torchaudio -import webdataset as wds - -from aeiou.core import is_silence -from os import path -from pedalboard.io import AudioFile -from torchaudio import transforms as T -from typing import Optional, Callable, List - -from .utils import Stereo, Mono, PhaseFlipper, PadCrop_Normalized_T -import json -import yaml -from pathlib import Path -import os -import librosa - -AUDIO_KEYS = ("flac", "wav", "mp3", "m4a", "ogg", "opus") - - -class MetadataNotFoundError(Exception): - pass - -def parse_time(time_str): - seconds, _ = map(int, time_str.split(':')) - return seconds - -def load_metadata(metadata_file): - with open(metadata_file, 'r', encoding='utf-8') as f: - return json.load(f) - -def generate_combined_tags(chunks, seconds_start, seconds_end): - combined_tags_set = set() - for chunk in chunks: - chunk_start = parse_time(chunk['start']) - chunk_end = parse_time(chunk['end']) - if seconds_start < chunk_end and seconds_end > chunk_start: - tags_words = [tag.strip() for tag in chunk['tags'].split(",") if tag.strip()] - combined_tags_set.update(tags_words) - combined_tags = ", ".join(sorted(combined_tags_set)) - return combined_tags - -def get_custom_metadata(info, audio): - pass - - raise MetadataNotFoundError(f"No suitable metadata source found for path: {info['path']}") - -# fast_scandir implementation by Scott Hawley originally in https://github.com/zqevans/audio-diffusion/blob/main/dataset/dataset.py - -def fast_scandir( - dir:str, # top-level directory at which to begin scanning - ext:list, # list of allowed file extensions, - #max_size = 1 * 1000 * 1000 * 1000 # Only files < 1 GB - ): - "very fast `glob` alternative. from https://stackoverflow.com/a/59803793/4259243" - subfolders, files = [], [] - ext = ['.'+x if x[0]!='.' else x for x in ext] # add starting period to extensions if needed - try: # hope to avoid 'permission denied' by this try - for f in os.scandir(dir): - try: # 'hope to avoid too many levels of symbolic links' error - if f.is_dir(): - subfolders.append(f.path) - elif f.is_file(): - file_ext = os.path.splitext(f.name)[1].lower() - is_hidden = os.path.basename(f.path).startswith(".") - - if file_ext in ext and not is_hidden: - files.append(f.path) - except: - pass - except: - pass - - for dir in list(subfolders): - sf, f = fast_scandir(dir, ext) - subfolders.extend(sf) - files.extend(f) - return subfolders, files - -def keyword_scandir( - dir: str, # top-level directory at which to begin scanning - ext: list, # list of allowed file extensions - keywords: list, # list of keywords to search for in the file name -): - "very fast `glob` alternative. from https://stackoverflow.com/a/59803793/4259243" - subfolders, files = [], [] - # make keywords case insensitive - keywords = [keyword.lower() for keyword in keywords] - # add starting period to extensions if needed - ext = ['.'+x if x[0] != '.' else x for x in ext] - banned_words = ["paxheader", "__macosx"] - try: # hope to avoid 'permission denied' by this try - for f in os.scandir(dir): - try: # 'hope to avoid too many levels of symbolic links' error - if f.is_dir(): - subfolders.append(f.path) - elif f.is_file(): - is_hidden = f.name.split("/")[-1][0] == '.' - has_ext = os.path.splitext(f.name)[1].lower() in ext - name_lower = f.name.lower() - has_keyword = any( - [keyword in name_lower for keyword in keywords]) - has_banned = any( - [banned_word in name_lower for banned_word in banned_words]) - if has_ext and has_keyword and not has_banned and not is_hidden and not os.path.basename(f.path).startswith("._"): - files.append(f.path) - except: - pass - except: - pass - - for dir in list(subfolders): - sf, f = keyword_scandir(dir, ext, keywords) - subfolders.extend(sf) - files.extend(f) - return subfolders, files - -def get_audio_filenames( - paths: list, # directories in which to search - keywords=None, - exts=['.wav', '.mp3', '.flac', '.ogg', '.aif', '.opus'] -): - "recursively get a list of audio filenames" - filenames = [] - if type(paths) is str: - paths = [paths] - for path in paths: # get a list of relevant filenames - if keywords is not None: - subfolders, files = keyword_scandir(path, exts, keywords) - else: - subfolders, files = fast_scandir(path, exts) - filenames.extend(files) - return filenames - -class SampleDataset(torch.utils.data.Dataset): - def __init__( - self, - paths, - sample_size=65536, - sample_rate=48000, - keywords=None, - relpath=None, - random_crop=True, - force_channels="stereo", - custom_metadata_fn: Optional[Callable[[str], str]] = None - ): - super().__init__() - self.filenames = [] - self.relpath = relpath - - self.augs = torch.nn.Sequential( - PhaseFlipper(), - ) - - self.pad_crop = PadCrop_Normalized_T(sample_size, sample_rate, randomize=random_crop) - - self.force_channels = force_channels - - self.encoding = torch.nn.Sequential( - Stereo() if self.force_channels == "stereo" else torch.nn.Identity(), - Mono() if self.force_channels == "mono" else torch.nn.Identity(), - ) - - self.filenames = get_audio_filenames(paths, keywords) - - print(f'Found {len(self.filenames)} files') - - self.sr = sample_rate - - self.custom_metadata_fn = custom_metadata_fn - - def load_file(self, filename): - ext = filename.split(".")[-1] - - if ext == "mp3": - # with AudioFile(filename) as f: - # audio = f.read(f.frames) - # audio = torch.from_numpy(audio) - # in_sr = f.samplerate - audio, in_sr = librosa.load(filename, sr=self.sr) - audio = torch.from_numpy(audio).float() - if audio.ndim < 2: - audio = audio.unsqueeze(0) - else: - audio, in_sr = torchaudio.load(filename, format=ext) - - if in_sr != self.sr: - resample_tf = T.Resample(in_sr, self.sr) - audio = resample_tf(audio) - - return (audio, in_sr) - - def __len__(self): - return len(self.filenames) - - def __getitem__(self, idx): - audio_filename = self.filenames[idx] - try: - start_time = time.time() - audio, sr= self.load_file(audio_filename) - - audio, t_start, t_end, seconds_start, seconds_total, padding_mask = self.pad_crop(audio) - - # Run augmentations on this sample (including random crop) - if self.augs is not None: - audio = self.augs(audio) - - audio = audio.clamp(-1, 1) - - # Encode the file to assist in prediction - if self.encoding is not None: - audio = self.encoding(audio) - - info = {} - - info["path"] = audio_filename - - if self.relpath is not None: - info["relpath"] = path.relpath(audio_filename, self.relpath) - - info["timestamps"] = (t_start, t_end) - info["seconds_start"] = seconds_start - info["seconds_total"] = seconds_total - info["padding_mask"] = padding_mask - - # #=================================== - # info['audio'] = prev_chunk - # #=================================== - end_time = time.time() - - info["load_time"] = end_time - start_time - - if self.custom_metadata_fn is not None: - custom_metadata = self.custom_metadata_fn(info, audio) - info.update(custom_metadata) - if "__reject__" in info and info["__reject__"]: - return self[random.randrange(len(self))] - # print(f'Seconds start: {seconds_start}, Seconds Total: {seconds_total}, Prev Start: {prev_start}, Prev End: {prev_end}') - # print(f'Audio shape: {audio.shape}, custom metadata shape: {prev_chunk.shape}') - # print(f'loading data: {info}') - return (audio, info) - # return (audio, prev_audio) - except Exception as e: - print(f'Couldn\'t load file {audio_filename}: {e}') - return self[random.randrange(len(self))] - -def group_by_keys(data, keys=wds.tariterators.base_plus_ext, lcase=True, suffixes=None, handler=None): - """Return function over iterator that groups key, value pairs into samples. - :param keys: function that splits the key into key and extension (base_plus_ext) - :param lcase: convert suffixes to lower case (Default value = True) - """ - current_sample = None - for filesample in data: - assert isinstance(filesample, dict) - fname, value = filesample["fname"], filesample["data"] - prefix, suffix = keys(fname) - if wds.tariterators.trace: - print( - prefix, - suffix, - current_sample.keys() if isinstance(current_sample, dict) else None, - ) - if prefix is None: - continue - if lcase: - suffix = suffix.lower() - if current_sample is None or prefix != current_sample["__key__"]: - if wds.tariterators.valid_sample(current_sample): - yield current_sample - current_sample = dict(__key__=prefix, __url__=filesample["__url__"]) - if suffix in current_sample: - print(f"{fname}: duplicate file name in tar file {suffix} {current_sample.keys()}") - if suffixes is None or suffix in suffixes: - current_sample[suffix] = value - if wds.tariterators.valid_sample(current_sample): - yield current_sample - -wds.tariterators.group_by_keys = group_by_keys - -# S3 code and WDS preprocessing code based on implementation by Scott Hawley originally in https://github.com/zqevans/audio-diffusion/blob/main/dataset/dataset.py - -def get_s3_contents(dataset_path, s3_url_prefix=None, filter='', recursive=True, debug=False, profile='default'): - """ - Returns a list of full S3 paths to files in a given S3 bucket and directory path. - """ - # Ensure dataset_path ends with a trailing slash - if dataset_path != '' and not dataset_path.endswith('/'): - dataset_path += '/' - # Use posixpath to construct the S3 URL path - bucket_path = posixpath.join(s3_url_prefix or '', dataset_path) - # Construct the `aws s3 ls` command - cmd = ['aws', 's3', 'ls', bucket_path, '--profile', profile] - if recursive: - # Add the --recursive flag if requested - cmd.append('--recursive') - - # Run the `aws s3 ls` command and capture the output - run_ls = subprocess.run(cmd, capture_output=True, check=True) - # Split the output into lines and strip whitespace from each line - contents = run_ls.stdout.decode('utf-8').split('\n') - contents = [x.strip() for x in contents if x] - # Remove the timestamp from lines that begin with a timestamp - contents = [re.sub(r'^\S+\s+\S+\s+\d+\s+', '', x) - if re.match(r'^\S+\s+\S+\s+\d+\s+', x) else x for x in contents] - # Construct a full S3 path for each file in the contents list - contents = [posixpath.join(s3_url_prefix or '', x) - for x in contents if not x.endswith('/')] - # Apply the filter, if specified - if filter: - contents = [x for x in contents if filter in x] - # Remove redundant directory names in the S3 URL - if recursive: - # Get the main directory name from the S3 URL - main_dir = "/".join(bucket_path.split('/')[3:]) - # Remove the redundant directory names from each file path - contents = [x.replace(f'{main_dir}', '').replace( - '//', '/') for x in contents] - # Print debugging information, if requested - if debug: - print("contents = \n", contents) - # Return the list of S3 paths to files - return contents - - -def get_all_s3_urls( - names=[], # list of all valid [LAION AudioDataset] dataset names - # list of subsets you want from those datasets, e.g. ['train','valid'] - subsets=[''], - s3_url_prefix=None, # prefix for those dataset names - recursive=True, # recursively list all tar files in all subdirs - filter_str='tar', # only grab files with this substring - # print debugging info -- note: info displayed likely to change at dev's whims - debug=False, - profiles={}, # dictionary of profiles for each item in names, e.g. {'dataset1': 'profile1', 'dataset2': 'profile2'} -): - "get urls of shards (tar files) for multiple datasets in one s3 bucket" - urls = [] - for name in names: - # If s3_url_prefix is not specified, assume the full S3 path is included in each element of the names list - if s3_url_prefix is None: - contents_str = name - else: - # Construct the S3 path using the s3_url_prefix and the current name value - contents_str = posixpath.join(s3_url_prefix, name) - if debug: - print(f"get_all_s3_urls: {contents_str}:") - for subset in subsets: - subset_str = posixpath.join(contents_str, subset) - if debug: - print(f"subset_str = {subset_str}") - # Get the list of tar files in the current subset directory - profile = profiles.get(name, 'default') - tar_list = get_s3_contents( - subset_str, s3_url_prefix=None, recursive=recursive, filter=filter_str, debug=debug, profile=profile) - for tar in tar_list: - # Escape spaces and parentheses in the tar filename for use in the shell command - tar = tar.replace(" ", "\ ").replace( - "(", "\(").replace(")", "\)") - # Construct the S3 path to the current tar file - s3_path = posixpath.join(name, subset, tar) + " -" - # Construct the AWS CLI command to download the current tar file - if s3_url_prefix is None: - request_str = f"pipe:aws s3 --cli-connect-timeout 0 cp {s3_path}" - else: - request_str = f"pipe:aws s3 --cli-connect-timeout 0 cp {posixpath.join(s3_url_prefix, s3_path)}" - if profiles.get(name): - request_str += f" --profile {profiles.get(name)}" - if debug: - print("request_str = ", request_str) - # Add the constructed URL to the list of URLs - urls.append(request_str) - return urls - - -def log_and_continue(exn): - """Call in an exception handler to ignore any exception, isssue a warning, and continue.""" - print(f"Handling webdataset error ({repr(exn)}). Ignoring.") - return True - - -def is_valid_sample(sample): - has_json = "json" in sample - has_audio = "audio" in sample - is_silent = is_silence(sample["audio"]) - is_rejected = "__reject__" in sample["json"] and sample["json"]["__reject__"] - - return has_json and has_audio and not is_silent and not is_rejected - -class S3DatasetConfig: - def __init__( - self, - id: str, - s3_path: str, - custom_metadata_fn: Optional[Callable[[str], str]] = None, - profile: Optional[str] = None, - ): - self.id = id - self.s3_path = s3_path - self.custom_metadata_fn = custom_metadata_fn - self.profile = profile - self.urls = [] - - def load_data_urls(self): - self.urls = get_all_s3_urls( - names=[self.s3_path], - s3_url_prefix=None, - recursive=True, - profiles={self.s3_path: self.profile} if self.profile else {}, - ) - - return self.urls - -def audio_decoder(key, value): - # Get file extension from key - ext = key.split(".")[-1] - - if ext in AUDIO_KEYS: - return torchaudio.load(io.BytesIO(value)) - else: - return None - -def collation_fn(samples): - batched = list(zip(*samples)) - result = [] - for b in batched: - if isinstance(b[0], (int, float)): - b = np.array(b) - elif isinstance(b[0], torch.Tensor): - b = torch.stack(b) - elif isinstance(b[0], np.ndarray): - b = np.array(b) - else: - b = b - result.append(b) - return result - -class S3WebDataLoader(): - def __init__( - self, - datasets: List[S3DatasetConfig], - batch_size, - sample_size, - sample_rate=48000, - num_workers=8, - epoch_steps=1000, - random_crop=True, - force_channels="stereo", - augment_phase=True, - **data_loader_kwargs - ): - - self.datasets = datasets - - self.sample_size = sample_size - self.sample_rate = sample_rate - self.random_crop = random_crop - self.force_channels = force_channels - self.augment_phase = augment_phase - - urls = [dataset.load_data_urls() for dataset in datasets] - - # Flatten the list of lists of URLs - urls = [url for dataset_urls in urls for url in dataset_urls] - - self.dataset = wds.DataPipeline( - wds.ResampledShards(urls), - wds.tarfile_to_samples(handler=log_and_continue), - wds.decode(audio_decoder, handler=log_and_continue), - wds.map(self.wds_preprocess, handler=log_and_continue), - wds.select(is_valid_sample), - wds.to_tuple("audio", "json", handler=log_and_continue), - wds.batched(batch_size, partial=False, collation_fn=collation_fn), - ).with_epoch(epoch_steps//num_workers if num_workers > 0 else epoch_steps) - - self.data_loader = wds.WebLoader(self.dataset, num_workers=num_workers, **data_loader_kwargs) - - def wds_preprocess(self, sample): - - found_key, rewrite_key = '', '' - for k, v in sample.items(): # print the all entries in dict - for akey in AUDIO_KEYS: - if k.endswith(akey): - # to rename long/weird key with its simpler counterpart - found_key, rewrite_key = k, akey - break - if '' != found_key: - break - if '' == found_key: # got no audio! - return None # try returning None to tell WebDataset to skip this one - - audio, in_sr = sample[found_key] - if in_sr != self.sample_rate: - resample_tf = T.Resample(in_sr, self.sample_rate) - audio = resample_tf(audio) - - if self.sample_size is not None: - # Pad/crop and get the relative timestamp - pad_crop = PadCrop_Normalized_T( - self.sample_size, randomize=self.random_crop, sample_rate=self.sample_rate) - audio, t_start, t_end, seconds_start, seconds_total, padding_mask = pad_crop( - audio) - sample["json"]["seconds_start"] = seconds_start - sample["json"]["seconds_total"] = seconds_total - sample["json"]["padding_mask"] = padding_mask - else: - t_start, t_end = 0, 1 - - # Check if audio is length zero, initialize to a single zero if so - if audio.shape[-1] == 0: - audio = torch.zeros(1, 1) - - # Make the audio stereo and augment by randomly inverting phase - augs = torch.nn.Sequential( - Stereo() if self.force_channels == "stereo" else torch.nn.Identity(), - Mono() if self.force_channels == "mono" else torch.nn.Identity(), - PhaseFlipper() if self.augment_phase else torch.nn.Identity() - ) - - audio = augs(audio) - - sample["json"]["timestamps"] = (t_start, t_end) - - if "text" in sample["json"]: - sample["json"]["prompt"] = sample["json"]["text"] - - # Check for custom metadata functions - for dataset in self.datasets: - if dataset.custom_metadata_fn is None: - continue - - if dataset.s3_path in sample["__url__"]: - custom_metadata = dataset.custom_metadata_fn(sample["json"], audio) - sample["json"].update(custom_metadata) - - if found_key != rewrite_key: # rename long/weird key with its simpler counterpart - del sample[found_key] - - sample["audio"] = audio - - # Add audio to the metadata as well for conditioning - sample["json"]["audio"] = audio - - return sample - -def create_dataloader_from_configs_and_args(model_config, args, dataset_config): - - dataset_type = dataset_config.get("dataset_type", None) - - assert dataset_type is not None, "Dataset type must be specified in dataset config" - - audio_channels = model_config.get("audio_channels", 2) - - if audio_channels == 1: - force_channels = "mono" - else: - force_channels = "stereo" - - if dataset_type == "audio_dir": - - audio_dir_configs = dataset_config.get("datasets", None) - - assert audio_dir_configs is not None, "Directory configuration must be specified in datasets[\"dataset\"]" - - training_dirs = [] - - custom_metadata_fn = None - custom_metadata_module_path = dataset_config.get("custom_metadata_module", None) - - if custom_metadata_module_path is not None: - spec = importlib.util.spec_from_file_location("metadata_module", custom_metadata_module_path) - metadata_module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(metadata_module) - - custom_metadata_fn = metadata_module.get_custom_metadata - - for audio_dir_config in audio_dir_configs: - audio_dir_path = audio_dir_config.get("path", None) - assert audio_dir_path is not None, "Path must be set for local audio directory configuration" - training_dirs.append(audio_dir_path) - - train_set = SampleDataset( - training_dirs, - sample_rate=model_config["sample_rate"], - sample_size=model_config["sample_size"], - random_crop=dataset_config.get("random_crop", True), - force_channels=force_channels, - custom_metadata_fn=get_custom_metadata, - relpath=training_dirs[0] #TODO: Make relpath relative to each training dir - ) - - return torch.utils.data.DataLoader(train_set, args.batch_size, shuffle=True, - num_workers=args.num_workers, persistent_workers=True, pin_memory=True, drop_last=True, collate_fn=collation_fn) - - elif dataset_type == "s3": - dataset_configs = [] - - for s3_config in dataset_config["datasets"]: - - custom_metadata_fn = None - custom_metadata_module_path = s3_config.get("custom_metadata_module", None) - - if custom_metadata_module_path is not None: - spec = importlib.util.spec_from_file_location("metadata_module", custom_metadata_module_path) - metadata_module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(metadata_module) - - custom_metadata_fn = metadata_module.get_custom_metadata - - dataset_configs.append( - S3DatasetConfig( - id=s3_config["id"], - s3_path=s3_config["s3_path"], - custom_metadata_fn=custom_metadata_fn, - profile=s3_config.get("profile", None), - ) - ) - - return S3WebDataLoader( - dataset_configs, - sample_rate=model_config["sample_rate"], - sample_size=model_config["sample_size"], - batch_size=args.batch_size, - random_crop=True, - num_workers=args.num_workers, - persistent_workers=True, - force_channels=force_channels, - epoch_steps=dataset_config.get("epoch_steps", 2000), - ).data_loader \ No newline at end of file diff --git a/sonique/stable_audio_tools/data/utils.py b/sonique/stable_audio_tools/data/utils.py deleted file mode 100644 index 01e153e5aca7afd4accf7bcde0962e3bf2a52172..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/data/utils.py +++ /dev/null @@ -1,95 +0,0 @@ -import math -import random -import torch - -from torch import nn -from typing import Tuple - -class PadCrop(nn.Module): - def __init__(self, n_samples, randomize=True): - super().__init__() - self.n_samples = n_samples - self.randomize = randomize - - def __call__(self, signal): - n, s = signal.shape - start = 0 if (not self.randomize) else torch.randint(0, max(0, s - self.n_samples) + 1, []).item() - end = start + self.n_samples - output = signal.new_zeros([n, self.n_samples]) - output[:, :min(s, self.n_samples)] = signal[:, start:end] - return output - -class PadCrop_Normalized_T(nn.Module): - - def __init__(self, n_samples: int, sample_rate: int, randomize: bool = True): - - super().__init__() - - self.n_samples = n_samples - self.sample_rate = sample_rate - self.randomize = randomize - - def __call__(self, source: torch.Tensor) -> Tuple[torch.Tensor, float, float, int, int]: - - n_channels, n_samples = source.shape - - # If the audio is shorter than the desired length, pad it - upper_bound = max(0, n_samples - self.n_samples) - - # If randomize is False, always start at the beginning of the audio - offset = 0 - if(self.randomize and n_samples > self.n_samples): - offset = random.randint(0, upper_bound) - - # Calculate the start and end times of the chunk - t_start = offset / (upper_bound + self.n_samples) - t_end = (offset + self.n_samples) / (upper_bound + self.n_samples) - - # Create the chunk - chunk = source.new_zeros([n_channels, self.n_samples]) - - # Copy the audio into the chunk - chunk[:, :min(n_samples, self.n_samples)] = source[:, offset:offset + self.n_samples] - - - # Calculate the start and end times of the chunk in seconds - seconds_start = math.floor(offset / self.sample_rate) - seconds_total = math.ceil(n_samples / self.sample_rate) - # Create a mask the same length as the chunk with 1s where the audio is and 0s where it isn't - padding_mask = torch.zeros([self.n_samples]) - padding_mask[:min(n_samples, self.n_samples)] = 1 - # print(f'Chunk shape from utils: {chunk.shape}, Prev chunk shape: {prev_chunk.shape}') - return ( - chunk, - t_start, - t_end, - seconds_start, - seconds_total, - padding_mask - ) - -class PhaseFlipper(nn.Module): - "Randomly invert the phase of a signal" - def __init__(self, p=0.5): - super().__init__() - self.p = p - def __call__(self, signal): - return -signal if (random.random() < self.p) else signal - -class Mono(nn.Module): - def __call__(self, signal): - return torch.mean(signal, dim=0, keepdims=True) if len(signal.shape) > 1 else signal - -class Stereo(nn.Module): - def __call__(self, signal): - signal_shape = signal.shape - # Check if it's mono - if len(signal_shape) == 1: # s -> 2, s - signal = signal.unsqueeze(0).repeat(2, 1) - elif len(signal_shape) == 2: - if signal_shape[0] == 1: #1, s -> 2, s - signal = signal.repeat(2, 1) - elif signal_shape[0] > 2: #?, s -> 2,s - signal = signal[:2, :] - - return signal diff --git a/sonique/stable_audio_tools/models/__init__.py b/sonique/stable_audio_tools/models/__init__.py deleted file mode 100644 index 7e27bbcb19a00a93e05ed6cf2a3a38895f26975d..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/models/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .factory import create_model_from_config, create_model_from_config_path \ No newline at end of file diff --git a/sonique/stable_audio_tools/models/adp.py b/sonique/stable_audio_tools/models/adp.py deleted file mode 100644 index 60332abd6d59ac7b02dd18d4ba769aad32c1b77c..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/models/adp.py +++ /dev/null @@ -1,1567 +0,0 @@ -# Copied and modified from https://github.com/archinetai/audio-diffusion-pytorch/blob/v0.0.94/audio_diffusion_pytorch/modules.py under MIT License -# License can be found in LICENSES/LICENSE_ADP.txt - -from inspect import isfunction -from math import ceil, floor, log, pi, log2 -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, TypeVar, Union -from packaging import version - -import torch -import torch.nn as nn -from einops import rearrange, reduce, repeat -from einops.layers.torch import Rearrange -from einops_exts import rearrange_many -from torch import Tensor, einsum -from torch.backends.cuda import sdp_kernel -from torch.nn import functional as F -from dac.nn.layers import Snake1d - -from audiocraft.modules.conv import get_extra_padding_for_conv1d, pad1d, unpad1d - -""" -Utils -""" - - -class ConditionedSequential(nn.Module): - def __init__(self, *modules): - super().__init__() - self.module_list = nn.ModuleList(*modules) - - def forward(self, x: Tensor, mapping: Optional[Tensor] = None): - for module in self.module_list: - x = module(x, mapping) - return x - -T = TypeVar("T") - -def default(val: Optional[T], d: Union[Callable[..., T], T]) -> T: - if exists(val): - return val - return d() if isfunction(d) else d - -def exists(val: Optional[T]) -> T: - return val is not None - -def closest_power_2(x: float) -> int: - exponent = log2(x) - distance_fn = lambda z: abs(x - 2 ** z) # noqa - exponent_closest = min((floor(exponent), ceil(exponent)), key=distance_fn) - return 2 ** int(exponent_closest) - -def group_dict_by_prefix(prefix: str, d: Dict) -> Tuple[Dict, Dict]: - return_dicts: Tuple[Dict, Dict] = ({}, {}) - for key in d.keys(): - no_prefix = int(not key.startswith(prefix)) - return_dicts[no_prefix][key] = d[key] - return return_dicts - -def groupby(prefix: str, d: Dict, keep_prefix: bool = False) -> Tuple[Dict, Dict]: - kwargs_with_prefix, kwargs = group_dict_by_prefix(prefix, d) - if keep_prefix: - return kwargs_with_prefix, kwargs - kwargs_no_prefix = {k[len(prefix) :]: v for k, v in kwargs_with_prefix.items()} - return kwargs_no_prefix, kwargs - -""" -Convolutional Blocks -""" - -class Conv1d(nn.Conv1d): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def forward(self, x: Tensor, causal=False) -> Tensor: - kernel_size = self.kernel_size[0] - stride = self.stride[0] - dilation = self.dilation[0] - kernel_size = (kernel_size - 1) * dilation + 1 # effective kernel size with dilations - padding_total = kernel_size - stride - extra_padding = get_extra_padding_for_conv1d(x, kernel_size, stride, padding_total) - if causal: - # Left padding for causal - x = pad1d(x, (padding_total, extra_padding)) - else: - # Asymmetric padding required for odd strides - padding_right = padding_total // 2 - padding_left = padding_total - padding_right - x = pad1d(x, (padding_left, padding_right + extra_padding)) - - return super().forward(x) - -class ConvTranspose1d(nn.ConvTranspose1d): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def forward(self, x: Tensor, causal=False) -> Tensor: - kernel_size = self.kernel_size[0] - stride = self.stride[0] - padding_total = kernel_size - stride - - y = super().forward(x) - - # We will only trim fixed padding. Extra padding from `pad_for_conv1d` would be - # removed at the very end, when keeping only the right length for the output, - # as removing it here would require also passing the length at the matching layer - # in the encoder. - if causal: - padding_right = ceil(padding_total) - padding_left = padding_total - padding_right - y = unpad1d(y, (padding_left, padding_right)) - else: - # Asymmetric padding required for odd strides - padding_right = padding_total // 2 - padding_left = padding_total - padding_right - y = unpad1d(y, (padding_left, padding_right)) - return y - - -def Downsample1d( - in_channels: int, out_channels: int, factor: int, kernel_multiplier: int = 2 -) -> nn.Module: - assert kernel_multiplier % 2 == 0, "Kernel multiplier must be even" - # print(f'downsample getting in_channel: {in_channels}, out_channels: {out_channels}, factor:{factor}') - return Conv1d( - in_channels=in_channels, - out_channels=out_channels, - kernel_size=factor * kernel_multiplier + 1, - stride=factor - ) - - -def Upsample1d( - in_channels: int, out_channels: int, factor: int, use_nearest: bool = False -) -> nn.Module: - # print(f'Upsample1d getting in_channel: {in_channels}, out_channel: {out_channels}, factor:{factor}') - if factor == 1: - return Conv1d( - in_channels=in_channels, out_channels=out_channels, kernel_size=3 - ) - - if use_nearest: - return nn.Sequential( - nn.Upsample(scale_factor=factor, mode="nearest"), - Conv1d( - in_channels=in_channels, - out_channels=out_channels, - kernel_size=3 - ), - ) - else: - return ConvTranspose1d( - in_channels=in_channels, - out_channels=out_channels, - kernel_size=factor * 2, - stride=factor - ) - - -class ConvBlock1d(nn.Module): - def __init__( - self, - in_channels: int, - out_channels: int, - *, - kernel_size: int = 3, - stride: int = 1, - dilation: int = 1, - num_groups: int = 8, - use_norm: bool = True, - use_snake: bool = False - ) -> None: - super().__init__() - - self.groupnorm = ( - nn.GroupNorm(num_groups=num_groups, num_channels=in_channels) - if use_norm - else nn.Identity() - ) - - if use_snake: - self.activation = Snake1d(in_channels) - else: - self.activation = nn.SiLU() - - self.project = Conv1d( - in_channels=in_channels, - out_channels=out_channels, - kernel_size=kernel_size, - stride=stride, - dilation=dilation, - ) - - def forward( - self, x: Tensor, scale_shift: Optional[Tuple[Tensor, Tensor]] = None, causal=False - ) -> Tensor: - x = self.groupnorm(x) - if exists(scale_shift): - scale, shift = scale_shift - x = x * (scale + 1) + shift - x = self.activation(x) - return self.project(x, causal=causal) - - -class MappingToScaleShift(nn.Module): - def __init__( - self, - features: int, - channels: int, - ): - super().__init__() - - self.to_scale_shift = nn.Sequential( - nn.SiLU(), - nn.Linear(in_features=features, out_features=channels * 2), - ) - - def forward(self, mapping: Tensor) -> Tuple[Tensor, Tensor]: - scale_shift = self.to_scale_shift(mapping) - scale_shift = rearrange(scale_shift, "b c -> b c 1") - scale, shift = scale_shift.chunk(2, dim=1) - return scale, shift - - -class ResnetBlock1d(nn.Module): - def __init__( - self, - in_channels: int, - out_channels: int, - *, - kernel_size: int = 3, - stride: int = 1, - dilation: int = 1, - use_norm: bool = True, - use_snake: bool = False, - num_groups: int = 8, - context_mapping_features: Optional[int] = None, - ) -> None: - super().__init__() - - self.use_mapping = exists(context_mapping_features) - - self.block1 = ConvBlock1d( - in_channels=in_channels, - out_channels=out_channels, - kernel_size=kernel_size, - stride=stride, - dilation=dilation, - use_norm=use_norm, - num_groups=num_groups, - use_snake=use_snake - ) - - if self.use_mapping: - assert exists(context_mapping_features) - self.to_scale_shift = MappingToScaleShift( - features=context_mapping_features, channels=out_channels - ) - - self.block2 = ConvBlock1d( - in_channels=out_channels, - out_channels=out_channels, - use_norm=use_norm, - num_groups=num_groups, - use_snake=use_snake - ) - - self.to_out = ( - Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=1) - if in_channels != out_channels - else nn.Identity() - ) - - def forward(self, x: Tensor, mapping: Optional[Tensor] = None, causal=False) -> Tensor: - # print(f"ResnetBlock1d input shape {x.shape}") - assert_message = "context mapping required if context_mapping_features > 0" - assert not (self.use_mapping ^ exists(mapping)), assert_message - - h = self.block1(x, causal=causal) - - scale_shift = None - if self.use_mapping: - scale_shift = self.to_scale_shift(mapping) - - h = self.block2(h, scale_shift=scale_shift, causal=causal) - # print(f"ResnetBlock1d output shape {h.shape}") - - return h + self.to_out(x) - - -class Patcher(nn.Module): - def __init__( - self, - in_channels: int, - out_channels: int, - patch_size: int, - context_mapping_features: Optional[int] = None, - use_snake: bool = False, - ): - super().__init__() - assert_message = f"out_channels must be divisible by patch_size ({patch_size})" - assert out_channels % patch_size == 0, assert_message - self.patch_size = patch_size - - self.block = ResnetBlock1d( - in_channels=in_channels, - out_channels=out_channels // patch_size, - num_groups=1, - context_mapping_features=context_mapping_features, - use_snake=use_snake - ) - - def forward(self, x: Tensor, mapping: Optional[Tensor] = None, causal=False) -> Tensor: - # print(f"Patcher input shape: {x.shape}") - x = self.block(x, mapping, causal=causal) - x = rearrange(x, "b c (l p) -> b (c p) l", p=self.patch_size) - # print(f"Patcher output shape {x.shape}") - return x - - -class Unpatcher(nn.Module): - def __init__( - self, - in_channels: int, - out_channels: int, - patch_size: int, - context_mapping_features: Optional[int] = None, - use_snake: bool = False - ): - super().__init__() - assert_message = f"in_channels must be divisible by patch_size ({patch_size})" - assert in_channels % patch_size == 0, assert_message - self.patch_size = patch_size - - self.block = ResnetBlock1d( - in_channels=in_channels // patch_size, - out_channels=out_channels, - num_groups=1, - context_mapping_features=context_mapping_features, - use_snake=use_snake - ) - - def forward(self, x: Tensor, mapping: Optional[Tensor] = None, causal=False) -> Tensor: - # print(f"Unpatcher input shape: {x.shape}") - x = rearrange(x, " b (c p) l -> b c (l p) ", p=self.patch_size) - x = self.block(x, mapping, causal=causal) - # print(f"Unpatcher output shape: {x.shape}") - return x - - -""" -Attention Components -""" -def FeedForward(features: int, multiplier: int) -> nn.Module: - # print(f'feed forward getting multipler {multiplier}') - mid_features = features * multiplier - return nn.Sequential( - nn.Linear(in_features=features, out_features=mid_features), - nn.GELU(), - nn.Linear(in_features=mid_features, out_features=features), - ) - -def add_mask(sim: Tensor, mask: Tensor) -> Tensor: - b, ndim = sim.shape[0], mask.ndim - if ndim == 3: - mask = rearrange(mask, "b n m -> b 1 n m") - if ndim == 2: - mask = repeat(mask, "n m -> b 1 n m", b=b) - max_neg_value = -torch.finfo(sim.dtype).max - sim = sim.masked_fill(~mask, max_neg_value) - return sim - -def causal_mask(q: Tensor, k: Tensor) -> Tensor: - b, i, j, device = q.shape[0], q.shape[-2], k.shape[-2], q.device - mask = ~torch.ones((i, j), dtype=torch.bool, device=device).triu(j - i + 1) - mask = repeat(mask, "n m -> b n m", b=b) - return mask - -class AttentionBase(nn.Module): - def __init__( - self, - features: int, - *, - head_features: int, - num_heads: int, - out_features: Optional[int] = None, - ): - super().__init__() - self.scale = head_features**-0.5 - self.num_heads = num_heads - mid_features = head_features * num_heads - out_features = default(out_features, features) - - self.to_out = nn.Linear( - in_features=mid_features, out_features=out_features - ) - - self.use_flash = torch.cuda.is_available() and version.parse(torch.__version__) >= version.parse('2.0.0') - - if not self.use_flash: - return - - device_properties = torch.cuda.get_device_properties(torch.device('cuda')) - - if device_properties.major == 8 and device_properties.minor == 0: - # Use flash attention for A100 GPUs - self.sdp_kernel_config = (True, False, False) - else: - # Don't use flash attention for other GPUs - self.sdp_kernel_config = (False, True, True) - - def forward( - self, q: Tensor, k: Tensor, v: Tensor, mask: Optional[Tensor] = None, is_causal: bool = False - ) -> Tensor: - # Split heads - q, k, v = rearrange_many((q, k, v), "b n (h d) -> b h n d", h=self.num_heads) - - if not self.use_flash: - if is_causal and not mask: - # Mask out future tokens for causal attention - mask = causal_mask(q, k) - - # Compute similarity matrix and add eventual mask - sim = einsum("... n d, ... m d -> ... n m", q, k) * self.scale - sim = add_mask(sim, mask) if exists(mask) else sim - - # Get attention matrix with softmax - attn = sim.softmax(dim=-1, dtype=torch.float32) - - # Compute values - out = einsum("... n m, ... m d -> ... n d", attn, v) - else: - with sdp_kernel(*self.sdp_kernel_config): - out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, is_causal=is_causal) - - out = rearrange(out, "b h n d -> b n (h d)") - return self.to_out(out) - -class Attention(nn.Module): - def __init__( - self, - features: int, - *, - head_features: int, - num_heads: int, - out_features: Optional[int] = None, - context_features: Optional[int] = None, - causal: bool = False, - ): - super().__init__() - self.context_features = context_features - self.causal = causal - mid_features = head_features * num_heads - context_features = default(context_features, features) - - self.norm = nn.LayerNorm(features) - self.norm_context = nn.LayerNorm(context_features) - self.to_q = nn.Linear( - in_features=features, out_features=mid_features, bias=False - ) - self.to_kv = nn.Linear( - in_features=context_features, out_features=mid_features * 2, bias=False - ) - self.attention = AttentionBase( - features, - num_heads=num_heads, - head_features=head_features, - out_features=out_features, - ) - - def forward( - self, - x: Tensor, # [b, n, c] - context: Optional[Tensor] = None, # [b, m, d] - context_mask: Optional[Tensor] = None, # [b, m], false is masked, - causal: Optional[bool] = False, - ) -> Tensor: - assert_message = "You must provide a context when using context_features" - assert not self.context_features or exists(context), assert_message - # Use context if provided - context = default(context, x) - # Normalize then compute q from input and k,v from context - x, context = self.norm(x), self.norm_context(context) - # print("Shape of x:", x.shape) - # print("Shape of context:", context.shape) - # print("context_mask:", context_mask) - q, k, v = (self.to_q(x), *torch.chunk(self.to_kv(context), chunks=2, dim=-1)) - - if exists(context_mask): - # Mask out cross-attention for padding tokens - mask = repeat(context_mask, "b m -> b m d", d=v.shape[-1]) - k, v = k * mask, v * mask - - # Compute and return attention - return self.attention(q, k, v, is_causal=self.causal or causal) - - -def FeedForward(features: int, multiplier: int) -> nn.Module: - mid_features = features * multiplier - return nn.Sequential( - nn.Linear(in_features=features, out_features=mid_features), - nn.GELU(), - nn.Linear(in_features=mid_features, out_features=features), - ) - -""" -Transformer Blocks -""" - - -class TransformerBlock(nn.Module): - def __init__( - self, - features: int, - num_heads: int, - head_features: int, - multiplier: int, - context_features: Optional[int] = None, - ): - super().__init__() - - self.use_cross_attention = exists(context_features) and context_features > 0 - - self.attention = Attention( - features=features, - num_heads=num_heads, - head_features=head_features - ) - - if self.use_cross_attention: - self.cross_attention = Attention( - features=features, - num_heads=num_heads, - head_features=head_features, - context_features=context_features - ) - - self.feed_forward = FeedForward(features=features, multiplier=multiplier) - - def forward(self, x: Tensor, *, context: Optional[Tensor] = None, context_mask: Optional[Tensor] = None, causal: Optional[bool] = False) -> Tensor: - # print(f'TransformerBlock input shape: {x.shape}') - x = self.attention(x, causal=causal) + x - if self.use_cross_attention: - x = self.cross_attention(x, context=context, context_mask=context_mask) + x - x = self.feed_forward(x) + x - # print(f'TransformerBlock output shape: {x.shape}') - return x - - -""" -Transformers -""" - - -class Transformer1d(nn.Module): - def __init__( - self, - num_layers: int, - channels: int, - num_heads: int, - head_features: int, - multiplier: int, - context_features: Optional[int] = None, - ): - super().__init__() - - self.to_in = nn.Sequential( - nn.GroupNorm(num_groups=32, num_channels=channels, eps=1e-6, affine=True), - Conv1d( - in_channels=channels, - out_channels=channels, - kernel_size=1, - ), - Rearrange("b c t -> b t c"), - ) - - self.blocks = nn.ModuleList( - [ - TransformerBlock( - features=channels, - head_features=head_features, - num_heads=num_heads, - multiplier=multiplier, - context_features=context_features, - ) - for i in range(num_layers) - ] - ) - - self.to_out = nn.Sequential( - Rearrange("b t c -> b c t"), - Conv1d( - in_channels=channels, - out_channels=channels, - kernel_size=1, - ), - ) - - def forward(self, x: Tensor, *, context: Optional[Tensor] = None, context_mask: Optional[Tensor] = None, causal=False) -> Tensor: - # print(f'Transformer1d input shape: {x.shape}') - x = self.to_in(x) - for block in self.blocks: - x = block(x, context=context, context_mask=context_mask, causal=causal) - x = self.to_out(x) - # print(f'Transformer1d output shape: {x.shape}') - return x - - -""" -Time Embeddings -""" - - -class SinusoidalEmbedding(nn.Module): - def __init__(self, dim: int): - super().__init__() - self.dim = dim - - def forward(self, x: Tensor) -> Tensor: - device, half_dim = x.device, self.dim // 2 - emb = torch.tensor(log(10000) / (half_dim - 1), device=device) - emb = torch.exp(torch.arange(half_dim, device=device) * -emb) - emb = rearrange(x, "i -> i 1") * rearrange(emb, "j -> 1 j") - return torch.cat((emb.sin(), emb.cos()), dim=-1) - - -class LearnedPositionalEmbedding(nn.Module): - """Used for continuous time""" - - def __init__(self, dim: int): - super().__init__() - assert (dim % 2) == 0 - half_dim = dim // 2 - self.weights = nn.Parameter(torch.randn(half_dim)) - - def forward(self, x: Tensor) -> Tensor: - x = rearrange(x, "b -> b 1") - freqs = x * rearrange(self.weights, "d -> 1 d") * 2 * pi - fouriered = torch.cat((freqs.sin(), freqs.cos()), dim=-1) - fouriered = torch.cat((x, fouriered), dim=-1) - return fouriered - - -def TimePositionalEmbedding(dim: int, out_features: int) -> nn.Module: - return nn.Sequential( - LearnedPositionalEmbedding(dim), - nn.Linear(in_features=dim + 1, out_features=out_features), - ) - - -""" -Encoder/Decoder Components -""" - - -class DownsampleBlock1d(nn.Module): - def __init__( - self, - in_channels: int, - out_channels: int, - *, - factor: int, - num_groups: int, - num_layers: int, - kernel_multiplier: int = 2, - use_pre_downsample: bool = True, - use_skip: bool = False, - use_snake: bool = False, - extract_channels: int = 0, - context_channels: int = 0, - num_transformer_blocks: int = 0, - attention_heads: Optional[int] = None, - attention_features: Optional[int] = None, - attention_multiplier: Optional[int] = None, - context_mapping_features: Optional[int] = None, - context_embedding_features: Optional[int] = None, - ): - super().__init__() - self.use_pre_downsample = use_pre_downsample - self.use_skip = use_skip - self.use_transformer = num_transformer_blocks > 0 - self.use_extract = extract_channels > 0 - self.use_context = context_channels > 0 - - channels = out_channels if use_pre_downsample else in_channels - - self.downsample = Downsample1d( - in_channels=in_channels, - out_channels=out_channels, - factor=factor, - kernel_multiplier=kernel_multiplier, - ) - - self.blocks = nn.ModuleList( - [ - ResnetBlock1d( - in_channels=channels + context_channels if i == 0 else channels, - out_channels=channels, - num_groups=num_groups, - context_mapping_features=context_mapping_features, - use_snake=use_snake - ) - for i in range(num_layers) - ] - ) - - if self.use_transformer: - assert ( - (exists(attention_heads) or exists(attention_features)) - and exists(attention_multiplier) - ) - - if attention_features is None and attention_heads is not None: - attention_features = channels // attention_heads - - if attention_heads is None and attention_features is not None: - attention_heads = channels // attention_features - - self.transformer = Transformer1d( - num_layers=num_transformer_blocks, - channels=channels, - num_heads=attention_heads, - head_features=attention_features, - multiplier=attention_multiplier, - context_features=context_embedding_features - ) - - if self.use_extract: - num_extract_groups = min(num_groups, extract_channels) - self.to_extracted = ResnetBlock1d( - in_channels=out_channels, - out_channels=extract_channels, - num_groups=num_extract_groups, - use_snake=use_snake - ) - - def forward( - self, - x: Tensor, - *, - mapping: Optional[Tensor] = None, - channels: Optional[Tensor] = None, - embedding: Optional[Tensor] = None, - embedding_mask: Optional[Tensor] = None, - causal: Optional[bool] = False - ) -> Union[Tuple[Tensor, List[Tensor]], Tensor]: - # print(f'DownsampleBlock1d input shape: {x.shape}') - if self.use_pre_downsample: - x = self.downsample(x) - - if self.use_context and exists(channels): - x = torch.cat([x, channels], dim=1) - - skips = [] - for block in self.blocks: - x = block(x, mapping=mapping, causal=causal) - skips += [x] if self.use_skip else [] - - if self.use_transformer: - x = self.transformer(x, context=embedding, context_mask=embedding_mask, causal=causal) - skips += [x] if self.use_skip else [] - - if not self.use_pre_downsample: - x = self.downsample(x) - - if self.use_extract: - extracted = self.to_extracted(x) - return x, extracted - # print(f'DownsampleBlock1d output shape: {x.shape}') - return (x, skips) if self.use_skip else x - - -class UpsampleBlock1d(nn.Module): - def __init__( - self, - in_channels: int, - out_channels: int, - *, - factor: int, - num_layers: int, - num_groups: int, - use_nearest: bool = False, - use_pre_upsample: bool = False, - use_skip: bool = False, - use_snake: bool = False, - skip_channels: int = 0, - use_skip_scale: bool = False, - extract_channels: int = 0, - num_transformer_blocks: int = 0, - attention_heads: Optional[int] = None, - attention_features: Optional[int] = None, - attention_multiplier: Optional[int] = None, - context_mapping_features: Optional[int] = None, - context_embedding_features: Optional[int] = None, - ): - super().__init__() - - self.use_extract = extract_channels > 0 - self.use_pre_upsample = use_pre_upsample - self.use_transformer = num_transformer_blocks > 0 - self.use_skip = use_skip - self.skip_scale = 2 ** -0.5 if use_skip_scale else 1.0 - - channels = out_channels if use_pre_upsample else in_channels - - self.blocks = nn.ModuleList( - [ - ResnetBlock1d( - in_channels=channels + skip_channels, - out_channels=channels, - num_groups=num_groups, - context_mapping_features=context_mapping_features, - use_snake=use_snake - ) - for _ in range(num_layers) - ] - ) - - if self.use_transformer: - assert ( - (exists(attention_heads) or exists(attention_features)) - and exists(attention_multiplier) - ) - - if attention_features is None and attention_heads is not None: - attention_features = channels // attention_heads - - if attention_heads is None and attention_features is not None: - attention_heads = channels // attention_features - - self.transformer = Transformer1d( - num_layers=num_transformer_blocks, - channels=channels, - num_heads=attention_heads, - head_features=attention_features, - multiplier=attention_multiplier, - context_features=context_embedding_features, - ) - - self.upsample = Upsample1d( - in_channels=in_channels, - out_channels=out_channels, - factor=factor, - use_nearest=use_nearest, - ) - - if self.use_extract: - num_extract_groups = min(num_groups, extract_channels) - self.to_extracted = ResnetBlock1d( - in_channels=out_channels, - out_channels=extract_channels, - num_groups=num_extract_groups, - use_snake=use_snake - ) - - def add_skip(self, x: Tensor, skip: Tensor) -> Tensor: - return torch.cat([x, skip * self.skip_scale], dim=1) - - def forward( - self, - x: Tensor, - *, - skips: Optional[List[Tensor]] = None, - mapping: Optional[Tensor] = None, - embedding: Optional[Tensor] = None, - embedding_mask: Optional[Tensor] = None, - causal: Optional[bool] = False - ) -> Union[Tuple[Tensor, Tensor], Tensor]: - # print(f'UpsampleBlock1d input shape: {x.shape}') - if self.use_pre_upsample: - x = self.upsample(x) - - for block in self.blocks: - x = self.add_skip(x, skip=skips.pop()) if exists(skips) else x - x = block(x, mapping=mapping, causal=causal) - - if self.use_transformer: - x = self.transformer(x, context=embedding, context_mask=embedding_mask, causal=causal) - - if not self.use_pre_upsample: - x = self.upsample(x) - - if self.use_extract: - extracted = self.to_extracted(x) - return x, extracted - # print(f'UpsampleBlock1d output shape: {x.shape}') - return x - - -class BottleneckBlock1d(nn.Module): - def __init__( - self, - channels: int, - *, - num_groups: int, - num_transformer_blocks: int = 0, - attention_heads: Optional[int] = None, - attention_features: Optional[int] = None, - attention_multiplier: Optional[int] = None, - context_mapping_features: Optional[int] = None, - context_embedding_features: Optional[int] = None, - use_snake: bool = False, - ): - super().__init__() - self.use_transformer = num_transformer_blocks > 0 - - self.pre_block = ResnetBlock1d( - in_channels=channels, - out_channels=channels, - num_groups=num_groups, - context_mapping_features=context_mapping_features, - use_snake=use_snake - ) - - if self.use_transformer: - assert ( - (exists(attention_heads) or exists(attention_features)) - and exists(attention_multiplier) - ) - - if attention_features is None and attention_heads is not None: - attention_features = channels // attention_heads - - if attention_heads is None and attention_features is not None: - attention_heads = channels // attention_features - - self.transformer = Transformer1d( - num_layers=num_transformer_blocks, - channels=channels, - num_heads=attention_heads, - head_features=attention_features, - multiplier=attention_multiplier, - context_features=context_embedding_features, - ) - - self.post_block = ResnetBlock1d( - in_channels=channels, - out_channels=channels, - num_groups=num_groups, - context_mapping_features=context_mapping_features, - use_snake=use_snake - ) - - def forward( - self, - x: Tensor, - *, - mapping: Optional[Tensor] = None, - embedding: Optional[Tensor] = None, - embedding_mask: Optional[Tensor] = None, - causal: Optional[bool] = False - ) -> Tensor: - # print(f'BottleneckBlock1d input shape: {x.shape}') - x = self.pre_block(x, mapping=mapping, causal=causal) - if self.use_transformer: - x = self.transformer(x, context=embedding, context_mask=embedding_mask, causal=causal) - x = self.post_block(x, mapping=mapping, causal=causal) - # print(f'BottleneckBlock1d output shape: {x.shape}') - return x - - -""" -UNet -""" - - -class UNet1d(nn.Module): - def __init__( - self, - in_channels: int, - channels: int, - multipliers: Sequence[int], - factors: Sequence[int], - num_blocks: Sequence[int], - attentions: Sequence[int], - patch_size: int = 1, - resnet_groups: int = 8, - use_context_time: bool = True, - kernel_multiplier_downsample: int = 2, - use_nearest_upsample: bool = False, - use_skip_scale: bool = True, - use_snake: bool = False, - use_stft: bool = False, - use_stft_context: bool = False, - out_channels: Optional[int] = None, - context_features: Optional[int] = None, - context_features_multiplier: int = 4, - context_channels: Optional[Sequence[int]] = None, - context_embedding_features: Optional[int] = None, - **kwargs, - ): - super().__init__() - out_channels = default(out_channels, in_channels) - context_channels = list(default(context_channels, [])) - num_layers = len(multipliers) - 1 - use_context_features = exists(context_features) - use_context_channels = len(context_channels) > 0 - context_mapping_features = None - - attention_kwargs, kwargs = groupby("attention_", kwargs, keep_prefix=True) - - self.num_layers = num_layers - self.use_context_time = use_context_time - self.use_context_features = use_context_features - self.use_context_channels = use_context_channels - self.use_stft = use_stft - self.use_stft_context = use_stft_context - - self.context_features = context_features - context_channels_pad_length = num_layers + 1 - len(context_channels) - context_channels = context_channels + [0] * context_channels_pad_length - self.context_channels = context_channels - self.context_embedding_features = context_embedding_features - - if use_context_channels: - has_context = [c > 0 for c in context_channels] - self.has_context = has_context - self.channels_ids = [sum(has_context[:i]) for i in range(len(has_context))] - - assert ( - len(factors) == num_layers - and len(attentions) >= num_layers - and len(num_blocks) == num_layers - ) - - if use_context_time or use_context_features: - context_mapping_features = channels * context_features_multiplier - - self.to_mapping = nn.Sequential( - nn.Linear(context_mapping_features, context_mapping_features), - nn.GELU(), - nn.Linear(context_mapping_features, context_mapping_features), - nn.GELU(), - ) - - if use_context_time: - assert exists(context_mapping_features) - self.to_time = nn.Sequential( - TimePositionalEmbedding( - dim=channels, out_features=context_mapping_features - ), - nn.GELU(), - ) - - if use_context_features: - assert exists(context_features) and exists(context_mapping_features) - self.to_features = nn.Sequential( - nn.Linear( - in_features=context_features, out_features=context_mapping_features - ), - nn.GELU(), - ) - - if use_stft: - stft_kwargs, kwargs = groupby("stft_", kwargs) - assert "num_fft" in stft_kwargs, "stft_num_fft required if use_stft=True" - stft_channels = (stft_kwargs["num_fft"] // 2 + 1) * 2 - in_channels *= stft_channels - out_channels *= stft_channels - context_channels[0] *= stft_channels if use_stft_context else 1 - assert exists(in_channels) and exists(out_channels) - self.stft = STFT(**stft_kwargs) - - assert not kwargs, f"Unknown arguments: {', '.join(list(kwargs.keys()))}" - - self.to_in = Patcher( - in_channels=in_channels + context_channels[0], - out_channels=channels * multipliers[0], - patch_size=patch_size, - context_mapping_features=context_mapping_features, - use_snake=use_snake - ) - - self.downsamples = nn.ModuleList( - [ - DownsampleBlock1d( - in_channels=channels * multipliers[i], - out_channels=channels * multipliers[i + 1], - context_mapping_features=context_mapping_features, - context_channels=context_channels[i + 1], - context_embedding_features=context_embedding_features, - num_layers=num_blocks[i], - factor=factors[i], - kernel_multiplier=kernel_multiplier_downsample, - num_groups=resnet_groups, - use_pre_downsample=True, - use_skip=True, - use_snake=use_snake, - num_transformer_blocks=attentions[i], - **attention_kwargs, - ) - for i in range(num_layers) - ] - ) - - self.bottleneck = BottleneckBlock1d( - channels=channels * multipliers[-1], - context_mapping_features=context_mapping_features, - context_embedding_features=context_embedding_features, - num_groups=resnet_groups, - num_transformer_blocks=attentions[-1], - use_snake=use_snake, - **attention_kwargs, - ) - - self.upsamples = nn.ModuleList( - [ - UpsampleBlock1d( - in_channels=channels * multipliers[i + 1], - out_channels=channels * multipliers[i], - context_mapping_features=context_mapping_features, - context_embedding_features=context_embedding_features, - num_layers=num_blocks[i] + (1 if attentions[i] else 0), - factor=factors[i], - use_nearest=use_nearest_upsample, - num_groups=resnet_groups, - use_skip_scale=use_skip_scale, - use_pre_upsample=False, - use_skip=True, - use_snake=use_snake, - skip_channels=channels * multipliers[i + 1], - num_transformer_blocks=attentions[i], - **attention_kwargs, - ) - for i in reversed(range(num_layers)) - ] - ) - - self.to_out = Unpatcher( - in_channels=channels * multipliers[0], - out_channels=out_channels, - patch_size=patch_size, - context_mapping_features=context_mapping_features, - use_snake=use_snake - ) - - def get_channels( - self, channels_list: Optional[Sequence[Tensor]] = None, layer: int = 0 - ) -> Optional[Tensor]: - """Gets context channels at `layer` and checks that shape is correct""" - use_context_channels = self.use_context_channels and self.has_context[layer] - if not use_context_channels: - return None - assert exists(channels_list), "Missing context" - # Get channels index (skipping zero channel contexts) - channels_id = self.channels_ids[layer] - # Get channels - channels = channels_list[channels_id] - message = f"Missing context for layer {layer} at index {channels_id}" - assert exists(channels), message - # Check channels - num_channels = self.context_channels[layer] - message = f"Expected context with {num_channels} channels at idx {channels_id}" - assert channels.shape[1] == num_channels, message - # STFT channels if requested - channels = self.stft.encode1d(channels) if self.use_stft_context else channels # type: ignore # noqa - return channels - - def get_mapping( - self, time: Optional[Tensor] = None, features: Optional[Tensor] = None - ) -> Optional[Tensor]: - """Combines context time features and features into mapping""" - items, mapping = [], None - # Compute time features - if self.use_context_time: - assert_message = "use_context_time=True but no time features provided" - assert exists(time), assert_message - items += [self.to_time(time)] - # Compute features - if self.use_context_features: - assert_message = "context_features exists but no features provided" - assert exists(features), assert_message - items += [self.to_features(features)] - # Compute joint mapping - if self.use_context_time or self.use_context_features: - mapping = reduce(torch.stack(items), "n b m -> b m", "sum") - mapping = self.to_mapping(mapping) - return mapping - - def forward( - self, - x: Tensor, - time: Optional[Tensor] = None, - *, - features: Optional[Tensor] = None, - channels_list: Optional[Sequence[Tensor]] = None, - embedding: Optional[Tensor] = None, - embedding_mask: Optional[Tensor] = None, - causal: Optional[bool] = False, - ) -> Tensor: - # print(f'Unet1d input shape: {x.shape}') - channels = self.get_channels(channels_list, layer=0) - # Apply stft if required - x = self.stft.encode1d(x) if self.use_stft else x # type: ignore - # Concat context channels at layer 0 if provided - x = torch.cat([x, channels], dim=1) if exists(channels) else x - # Compute mapping from time and features - mapping = self.get_mapping(time, features) - x = self.to_in(x, mapping, causal=causal) - skips_list = [x] - - for i, downsample in enumerate(self.downsamples): - channels = self.get_channels(channels_list, layer=i + 1) - x, skips = downsample( - x, mapping=mapping, channels=channels, embedding=embedding, embedding_mask=embedding_mask, causal=causal - ) - skips_list += [skips] - - x = self.bottleneck(x, mapping=mapping, embedding=embedding, embedding_mask=embedding_mask, causal=causal) - - for i, upsample in enumerate(self.upsamples): - skips = skips_list.pop() - x = upsample(x, skips=skips, mapping=mapping, embedding=embedding, embedding_mask=embedding_mask, causal=causal) - - x += skips_list.pop() - x = self.to_out(x, mapping, causal=causal) - x = self.stft.decode1d(x) if self.use_stft else x - # print(f'Unet1d output shape: {x.shape}') - return x - - -""" Conditioning Modules """ - - -class FixedEmbedding(nn.Module): - def __init__(self, max_length: int, features: int): - super().__init__() - self.max_length = max_length - self.embedding = nn.Embedding(max_length, features) - - def forward(self, x: Tensor) -> Tensor: - # print(f'FixedEmbedding input shape: {x.shape}') - batch_size, length, device = *x.shape[0:2], x.device - # print(f'FixedEmbedding length: {length}, self.max length: {self.max_length}') - assert_message = "Input sequence length must be <= max_length" - assert length <= self.max_length, assert_message - position = torch.arange(length, device=device) - fixed_embedding = self.embedding(position) - fixed_embedding = repeat(fixed_embedding, "n d -> b n d", b=batch_size) - # print(f'FixedEmbedding output shape: {fixed_embedding.shape}') - return fixed_embedding - - -def rand_bool(shape: Any, proba: float, device: Any = None) -> Tensor: - if proba == 1: - return torch.ones(shape, device=device, dtype=torch.bool) - elif proba == 0: - return torch.zeros(shape, device=device, dtype=torch.bool) - else: - return torch.bernoulli(torch.full(shape, proba, device=device)).to(torch.bool) - - -class UNetCFG1d(UNet1d): - - """UNet1d with Classifier-Free Guidance""" - - def __init__( - self, - context_embedding_max_length: int, - context_embedding_features: int, - use_xattn_time: bool = False, - **kwargs, - ): - super().__init__( - context_embedding_features=context_embedding_features, **kwargs - ) - - self.use_xattn_time = use_xattn_time - - if use_xattn_time: - assert exists(context_embedding_features) - self.to_time_embedding = nn.Sequential( - TimePositionalEmbedding( - dim=kwargs["channels"], out_features=context_embedding_features - ), - nn.GELU(), - ) - - context_embedding_max_length += 1 # Add one for time embedding - - self.fixed_embedding = FixedEmbedding( - max_length=context_embedding_max_length, features=context_embedding_features - ) - - def forward( # type: ignore - self, - x: Tensor, - time: Tensor, - *, - embedding: Tensor, - embedding_mask: Optional[Tensor] = None, - embedding_scale: float = 1.0, - embedding_mask_proba: float = 0.0, - batch_cfg: bool = False, - rescale_cfg: bool = False, - scale_phi: float = 0.4, - negative_embedding: Optional[Tensor] = None, - negative_embedding_mask: Optional[Tensor] = None, - **kwargs, - ) -> Tensor: - # print("Debugging UNetCFG1d forward method") - # print(f"Input x shape: {x.shape}, type: {type(x)}") - # print(f"Time embedding shape: {time.shape}, type: {type(time)}") - # print(f"Cross-attention embedding shape: {embedding.shape}, type: {type(embedding)}") - # print(f"Cross-attention embedding mask shape: {embedding_mask.shape if embedding_mask is not None else 'None'}, type: {type(embedding_mask)}") - # print(f"Embedding scale: {embedding_scale}, type: {type(embedding_scale)}") - # print(f"Embedding mask probability: {embedding_mask_proba}, type: {type(embedding_mask_proba)}") - # print(f"Batch CFG: {batch_cfg}, type: {type(batch_cfg)}") - # print(f"Rescale CFG: {rescale_cfg}, type: {type(rescale_cfg)}") - # print(f"Scale Phi: {scale_phi}, type: {type(scale_phi)}") - # if negative_embedding is not None: - # print(f"Negative embedding shape: {negative_embedding.shape}, type: {type(negative_embedding)}") - # if negative_embedding_mask is not None: - # print(f"Negative embedding mask shape: {negative_embedding_mask.shape}, type: {type(negative_embedding_mask)}") - b, device = embedding.shape[0], embedding.device - - if self.use_xattn_time: - embedding = torch.cat([embedding, self.to_time_embedding(time).unsqueeze(1)], dim=1) - - if embedding_mask is not None: - embedding_mask = torch.cat([embedding_mask, torch.ones((b, 1), device=device)], dim=1) - - fixed_embedding = self.fixed_embedding(embedding) - # print(f'Fixed Embedding.shape {fixed_embedding.shape}') - assert fixed_embedding.shape == embedding.shape, f"Shape mismatch: {fixed_embedding.shape} vs {embedding.shape}" - if embedding_mask_proba > 0.0: - # Randomly mask embedding - batch_mask = rand_bool( - shape=(b, 1, 1), proba=embedding_mask_proba, device=device - ) - embedding = torch.where(batch_mask, fixed_embedding, embedding) - - if embedding_scale != 1.0: - if batch_cfg: - batch_x = torch.cat([x, x], dim=0) - batch_time = torch.cat([time, time], dim=0) - - if negative_embedding is not None: - if negative_embedding_mask is not None: - negative_embedding_mask = negative_embedding_mask.to(torch.bool).unsqueeze(2) - - negative_embedding = torch.where(negative_embedding_mask, negative_embedding, fixed_embedding) - - batch_embed = torch.cat([embedding, negative_embedding], dim=0) - - else: - batch_embed = torch.cat([embedding, fixed_embedding], dim=0) - - batch_mask = None - if embedding_mask is not None: - batch_mask = torch.cat([embedding_mask, embedding_mask], dim=0) - - batch_features = None - features = kwargs.pop("features", None) - if self.use_context_features: - batch_features = torch.cat([features, features], dim=0) - - batch_channels = None - channels_list = kwargs.pop("channels_list", None) - if self.use_context_channels: - batch_channels = [] - for channels in channels_list: - batch_channels += [torch.cat([channels, channels], dim=0)] - - # Compute both normal and fixed embedding outputs - batch_out = super().forward(batch_x, batch_time, embedding=batch_embed, embedding_mask=batch_mask, features=batch_features, channels_list=batch_channels, **kwargs) - out, out_masked = batch_out.chunk(2, dim=0) - - else: - # Compute both normal and fixed embedding outputs - out = super().forward(x, time, embedding=embedding, embedding_mask=embedding_mask, **kwargs) - out_masked = super().forward(x, time, embedding=fixed_embedding, embedding_mask=embedding_mask, **kwargs) - - out_cfg = out_masked + (out - out_masked) * embedding_scale - - if rescale_cfg: - - out_std = out.std(dim=1, keepdim=True) - out_cfg_std = out_cfg.std(dim=1, keepdim=True) - - return scale_phi * (out_cfg * (out_std/out_cfg_std)) + (1-scale_phi) * out_cfg - - else: - - return out_cfg - - else: - return super().forward(x, time, embedding=embedding, embedding_mask=embedding_mask, **kwargs) - - -class UNetNCCA1d(UNet1d): - - """UNet1d with Noise Channel Conditioning Augmentation""" - - def __init__(self, context_features: int, **kwargs): - super().__init__(context_features=context_features, **kwargs) - self.embedder = NumberEmbedder(features=context_features) - - def expand(self, x: Any, shape: Tuple[int, ...]) -> Tensor: - x = x if torch.is_tensor(x) else torch.tensor(x) - return x.expand(shape) - - def forward( # type: ignore - self, - x: Tensor, - time: Tensor, - *, - channels_list: Sequence[Tensor], - channels_augmentation: Union[ - bool, Sequence[bool], Sequence[Sequence[bool]], Tensor - ] = False, - channels_scale: Union[ - float, Sequence[float], Sequence[Sequence[float]], Tensor - ] = 0, - **kwargs, - ) -> Tensor: - b, n = x.shape[0], len(channels_list) - channels_augmentation = self.expand(channels_augmentation, shape=(b, n)).to(x) - channels_scale = self.expand(channels_scale, shape=(b, n)).to(x) - - # Augmentation (for each channel list item) - for i in range(n): - scale = channels_scale[:, i] * channels_augmentation[:, i] - scale = rearrange(scale, "b -> b 1 1") - item = channels_list[i] - channels_list[i] = torch.randn_like(item) * scale + item * (1 - scale) # type: ignore # noqa - - # Scale embedding (sum reduction if more than one channel list item) - channels_scale_emb = self.embedder(channels_scale) - channels_scale_emb = reduce(channels_scale_emb, "b n d -> b d", "sum") - - return super().forward( - x=x, - time=time, - channels_list=channels_list, - features=channels_scale_emb, - **kwargs, - ) - - -class UNetAll1d(UNetCFG1d, UNetNCCA1d): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def forward(self, *args, **kwargs): # type: ignore - return UNetCFG1d.forward(self, *args, **kwargs) - - -def XUNet1d(type: str = "base", **kwargs) -> UNet1d: - if type == "base": - return UNet1d(**kwargs) - elif type == "all": - return UNetAll1d(**kwargs) - elif type == "cfg": - return UNetCFG1d(**kwargs) - elif type == "ncca": - return UNetNCCA1d(**kwargs) - else: - raise ValueError(f"Unknown XUNet1d type: {type}") - -class NumberEmbedder(nn.Module): - def __init__( - self, - features: int, - dim: int = 256, - ): - super().__init__() - self.features = features - self.embedding = TimePositionalEmbedding(dim=dim, out_features=features) - - def forward(self, x: Union[List[float], Tensor]) -> Tensor: - if not torch.is_tensor(x): - device = next(self.embedding.parameters()).device - x = torch.tensor(x, device=device) - assert isinstance(x, Tensor) - shape = x.shape - x = rearrange(x, "... -> (...)") - embedding = self.embedding(x) - x = embedding.view(*shape, self.features) - return x # type: ignore - - -""" -Audio Transforms -""" - - -class STFT(nn.Module): - """Helper for torch stft and istft""" - - def __init__( - self, - num_fft: int = 1023, - hop_length: int = 256, - window_length: Optional[int] = None, - length: Optional[int] = None, - use_complex: bool = False, - ): - super().__init__() - self.num_fft = num_fft - self.hop_length = default(hop_length, floor(num_fft // 4)) - self.window_length = default(window_length, num_fft) - self.length = length - self.register_buffer("window", torch.hann_window(self.window_length)) - self.use_complex = use_complex - - def encode(self, wave: Tensor) -> Tuple[Tensor, Tensor]: - b = wave.shape[0] - wave = rearrange(wave, "b c t -> (b c) t") - - stft = torch.stft( - wave, - n_fft=self.num_fft, - hop_length=self.hop_length, - win_length=self.window_length, - window=self.window, # type: ignore - return_complex=True, - normalized=True, - ) - - if self.use_complex: - # Returns real and imaginary - stft_a, stft_b = stft.real, stft.imag - else: - # Returns magnitude and phase matrices - magnitude, phase = torch.abs(stft), torch.angle(stft) - stft_a, stft_b = magnitude, phase - - return rearrange_many((stft_a, stft_b), "(b c) f l -> b c f l", b=b) - - def decode(self, stft_a: Tensor, stft_b: Tensor) -> Tensor: - b, l = stft_a.shape[0], stft_a.shape[-1] # noqa - length = closest_power_2(l * self.hop_length) - - stft_a, stft_b = rearrange_many((stft_a, stft_b), "b c f l -> (b c) f l") - - if self.use_complex: - real, imag = stft_a, stft_b - else: - magnitude, phase = stft_a, stft_b - real, imag = magnitude * torch.cos(phase), magnitude * torch.sin(phase) - - stft = torch.stack([real, imag], dim=-1) - - wave = torch.istft( - stft, - n_fft=self.num_fft, - hop_length=self.hop_length, - win_length=self.window_length, - window=self.window, # type: ignore - length=default(self.length, length), - normalized=True, - ) - - return rearrange(wave, "(b c) t -> b c t", b=b) - - def encode1d( - self, wave: Tensor, stacked: bool = True - ) -> Union[Tensor, Tuple[Tensor, Tensor]]: - stft_a, stft_b = self.encode(wave) - stft_a, stft_b = rearrange_many((stft_a, stft_b), "b c f l -> b (c f) l") - return torch.cat((stft_a, stft_b), dim=1) if stacked else (stft_a, stft_b) - - def decode1d(self, stft_pair: Tensor) -> Tensor: - f = self.num_fft // 2 + 1 - stft_a, stft_b = stft_pair.chunk(chunks=2, dim=1) - stft_a, stft_b = rearrange_many((stft_a, stft_b), "b (c f) l -> b c f l", f=f) - return self.decode(stft_a, stft_b) diff --git a/sonique/stable_audio_tools/models/autoencoders.py b/sonique/stable_audio_tools/models/autoencoders.py deleted file mode 100644 index dd4d25564d02eaaf5846231c42abdf05766ecc07..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/models/autoencoders.py +++ /dev/null @@ -1,660 +0,0 @@ -import torch -import math -import numpy as np - -from torch import nn, sin, pow -from torch.nn import functional as F -from torch.nn import Parameter -from torchaudio import transforms as T -from alias_free_torch import Activation1d -from dac.nn.layers import WNConv1d, WNConvTranspose1d -from typing import List, Literal, Dict, Any, Callable -from einops import rearrange - -from ...inference.sampling import sample -from ...inference.utils import prepare_audio -from .bottleneck import Bottleneck -from .diffusion import ConditionedDiffusionModel, DAU1DCondWrapper, UNet1DCondWrapper, DiTWrapper -from .factory import create_pretransform_from_config, create_bottleneck_from_config -from .pretransforms import Pretransform, AutoencoderPretransform - -def snake_beta(x, alpha, beta): - return x + (1.0 / (beta + 0.000000001)) * pow(sin(x * alpha), 2) - -try: - snake_beta = torch.compile(snake_beta) -except RuntimeError: - pass - -# Adapted from https://github.com/NVIDIA/BigVGAN/blob/main/activations.py under MIT license -# License available in LICENSES/LICENSE_NVIDIA.txt -class SnakeBeta(nn.Module): - - def __init__(self, in_features, alpha=1.0, alpha_trainable=True, alpha_logscale=True): - super(SnakeBeta, self).__init__() - self.in_features = in_features - - # initialize alpha - self.alpha_logscale = alpha_logscale - if self.alpha_logscale: # log scale alphas initialized to zeros - self.alpha = Parameter(torch.zeros(in_features) * alpha) - self.beta = Parameter(torch.zeros(in_features) * alpha) - else: # linear scale alphas initialized to ones - self.alpha = Parameter(torch.ones(in_features) * alpha) - self.beta = Parameter(torch.ones(in_features) * alpha) - - self.alpha.requires_grad = alpha_trainable - self.beta.requires_grad = alpha_trainable - - self.no_div_by_zero = 0.000000001 - - def forward(self, x): - alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # line up with x to [B, C, T] - beta = self.beta.unsqueeze(0).unsqueeze(-1) - if self.alpha_logscale: - alpha = torch.exp(alpha) - beta = torch.exp(beta) - x = snake_beta(x, alpha, beta) - - return x - -def get_activation(activation: Literal["elu", "snake", "none"], antialias=False, channels=None) -> nn.Module: - if activation == "elu": - act = nn.ELU() - elif activation == "snake": - act = SnakeBeta(channels) - elif activation == "none": - act = nn.Identity() - else: - raise ValueError(f"Unknown activation {activation}") - - if antialias: - act = Activation1d(act) - - return act - -class ResidualUnit(nn.Module): - def __init__(self, in_channels, out_channels, dilation, use_snake=False, antialias_activation=False): - super().__init__() - - self.dilation = dilation - - act = get_activation("snake" if use_snake else "elu", antialias=antialias_activation, channels=out_channels) - - padding = (dilation * (7-1)) // 2 - - self.layers = nn.Sequential( - act, - WNConv1d(in_channels=in_channels, out_channels=out_channels, - kernel_size=7, dilation=dilation, padding=padding), - act, - WNConv1d(in_channels=out_channels, out_channels=out_channels, - kernel_size=1) - ) - - def forward(self, x): - return x + self.layers(x) - -class EncoderBlock(nn.Module): - def __init__(self, in_channels, out_channels, stride, use_snake=False, antialias_activation=False): - super().__init__() - - act = get_activation("snake" if use_snake else "elu", antialias=antialias_activation, channels=in_channels) - - self.layers = nn.Sequential( - ResidualUnit(in_channels=in_channels, - out_channels=in_channels, dilation=1, use_snake=use_snake), - ResidualUnit(in_channels=in_channels, - out_channels=in_channels, dilation=3, use_snake=use_snake), - ResidualUnit(in_channels=in_channels, - out_channels=in_channels, dilation=9, use_snake=use_snake), - act, - WNConv1d(in_channels=in_channels, out_channels=out_channels, - kernel_size=2*stride, stride=stride, padding=math.ceil(stride/2)), - ) - - def forward(self, x): - return self.layers(x) - -class DecoderBlock(nn.Module): - def __init__(self, in_channels, out_channels, stride, use_snake=False, antialias_activation=False, use_nearest_upsample=False): - super().__init__() - - if use_nearest_upsample: - upsample_layer = nn.Sequential( - nn.Upsample(scale_factor=stride, mode="nearest"), - WNConv1d(in_channels=in_channels, - out_channels=out_channels, - kernel_size=2*stride, - stride=1, - bias=False, - padding='same') - ) - else: - upsample_layer = WNConvTranspose1d(in_channels=in_channels, - out_channels=out_channels, - kernel_size=2*stride, stride=stride, padding=math.ceil(stride/2)) - - act = get_activation("snake" if use_snake else "elu", antialias=antialias_activation, channels=in_channels) - - self.layers = nn.Sequential( - act, - upsample_layer, - ResidualUnit(in_channels=out_channels, out_channels=out_channels, - dilation=1, use_snake=use_snake), - ResidualUnit(in_channels=out_channels, out_channels=out_channels, - dilation=3, use_snake=use_snake), - ResidualUnit(in_channels=out_channels, out_channels=out_channels, - dilation=9, use_snake=use_snake), - ) - - def forward(self, x): - return self.layers(x) - -class OobleckEncoder(nn.Module): - def __init__(self, - in_channels=2, - channels=128, - latent_dim=32, - c_mults = [1, 2, 4, 8], - strides = [2, 4, 8, 8], - use_snake=False, - antialias_activation=False - ): - super().__init__() - - c_mults = [1] + c_mults - - self.depth = len(c_mults) - - layers = [ - WNConv1d(in_channels=in_channels, out_channels=c_mults[0] * channels, kernel_size=7, padding=3) - ] - - for i in range(self.depth-1): - layers += [EncoderBlock(in_channels=c_mults[i]*channels, out_channels=c_mults[i+1]*channels, stride=strides[i], use_snake=use_snake)] - - layers += [ - get_activation("snake" if use_snake else "elu", antialias=antialias_activation, channels=c_mults[-1] * channels), - WNConv1d(in_channels=c_mults[-1]*channels, out_channels=latent_dim, kernel_size=3, padding=1) - ] - - self.layers = nn.Sequential(*layers) - - def forward(self, x): - return self.layers(x) - - -class OobleckDecoder(nn.Module): - def __init__(self, - out_channels=2, - channels=128, - latent_dim=32, - c_mults = [1, 2, 4, 8], - strides = [2, 4, 8, 8], - use_snake=False, - antialias_activation=False, - use_nearest_upsample=False, - final_tanh=True): - super().__init__() - - c_mults = [1] + c_mults - - self.depth = len(c_mults) - - layers = [ - WNConv1d(in_channels=latent_dim, out_channels=c_mults[-1]*channels, kernel_size=7, padding=3), - ] - - for i in range(self.depth-1, 0, -1): - layers += [DecoderBlock( - in_channels=c_mults[i]*channels, - out_channels=c_mults[i-1]*channels, - stride=strides[i-1], - use_snake=use_snake, - antialias_activation=antialias_activation, - use_nearest_upsample=use_nearest_upsample - ) - ] - - layers += [ - get_activation("snake" if use_snake else "elu", antialias=antialias_activation, channels=c_mults[0] * channels), - WNConv1d(in_channels=c_mults[0] * channels, out_channels=out_channels, kernel_size=7, padding=3, bias=False), - nn.Tanh() if final_tanh else nn.Identity() - ] - - self.layers = nn.Sequential(*layers) - - def forward(self, x): - return self.layers(x) - -class DACEncoderWrapper(nn.Module): - def __init__(self, in_channels=1, **kwargs): - super().__init__() - - from dac.model.dac import Encoder as DACEncoder - - latent_dim = kwargs.pop("latent_dim", None) - - encoder_out_dim = kwargs["d_model"] * (2 ** len(kwargs["strides"])) - self.encoder = DACEncoder(d_latent=encoder_out_dim, **kwargs) - self.latent_dim = latent_dim - - # Latent-dim support was added to DAC after this was first written, and implemented differently, so this is for backwards compatibility - self.proj_out = nn.Conv1d(self.encoder.enc_dim, latent_dim, kernel_size=1) if latent_dim is not None else nn.Identity() - - if in_channels != 1: - self.encoder.block[0] = WNConv1d(in_channels, kwargs.get("d_model", 64), kernel_size=7, padding=3) - - def forward(self, x): - x = self.encoder(x) - x = self.proj_out(x) - return x - -class DACDecoderWrapper(nn.Module): - def __init__(self, latent_dim, out_channels=1, **kwargs): - super().__init__() - - from dac.model.dac import Decoder as DACDecoder - - self.decoder = DACDecoder(**kwargs, input_channel = latent_dim, d_out=out_channels) - - self.latent_dim = latent_dim - - def forward(self, x): - return self.decoder(x) - -class AudioAutoencoder(nn.Module): - def __init__( - self, - encoder, - decoder, - latent_dim, - downsampling_ratio, - sample_rate, - io_channels=2, - bottleneck: Bottleneck = None, - pretransform: Pretransform = None, - in_channels = None, - out_channels = None, - soft_clip = False - ): - super().__init__() - - self.downsampling_ratio = downsampling_ratio - self.sample_rate = sample_rate - - self.latent_dim = latent_dim - self.io_channels = io_channels - self.in_channels = io_channels - self.out_channels = io_channels - - self.min_length = self.downsampling_ratio - - if in_channels is not None: - self.in_channels = in_channels - - if out_channels is not None: - self.out_channels = out_channels - - self.bottleneck = bottleneck - - self.encoder = encoder - - self.decoder = decoder - - self.pretransform = pretransform - - self.soft_clip = soft_clip - - def encode(self, audio, return_info=False, skip_pretransform=False, iterate_batch=False, **kwargs): - - info = {} - - if self.pretransform is not None and not skip_pretransform: - if self.pretransform.enable_grad: - if iterate_batch: - audios = [] - for i in range(audio.shape[0]): - audios.append(self.pretransform.encode(audio[i:i+1])) - audio = torch.cat(audios, dim=0) - else: - audio = self.pretransform.encode(audio) - else: - with torch.no_grad(): - if iterate_batch: - audios = [] - for i in range(audio.shape[0]): - audios.append(self.pretransform.encode(audio[i:i+1])) - audio = torch.cat(audios, dim=0) - else: - audio = self.pretransform.encode(audio) - - if self.encoder is not None: - if iterate_batch: - latents = [] - for i in range(audio.shape[0]): - latents.append(self.encoder(audio[i:i+1])) - latents = torch.cat(latents, dim=0) - else: - latents = self.encoder(audio) - else: - latents = audio - - if self.bottleneck is not None: - # TODO: Add iterate batch logic, needs to merge the info dicts - latents, bottleneck_info = self.bottleneck.encode(latents, return_info=True, **kwargs) - - info.update(bottleneck_info) - - if return_info: - return latents, info - - return latents - - def decode(self, latents, iterate_batch=False, **kwargs): - - if self.bottleneck is not None: - if iterate_batch: - decoded = [] - for i in range(latents.shape[0]): - decoded.append(self.bottleneck.decode(latents[i:i+1])) - decoded = torch.cat(decoded, dim=0) - else: - latents = self.bottleneck.decode(latents) - - if iterate_batch: - decoded = [] - for i in range(latents.shape[0]): - decoded.append(self.decoder(latents[i:i+1])) - decoded = torch.cat(decoded, dim=0) - else: - decoded = self.decoder(latents, **kwargs) - - if self.pretransform is not None: - if self.pretransform.enable_grad: - if iterate_batch: - decodeds = [] - for i in range(decoded.shape[0]): - decodeds.append(self.pretransform.decode(decoded[i:i+1])) - decoded = torch.cat(decodeds, dim=0) - else: - decoded = self.pretransform.decode(decoded) - else: - with torch.no_grad(): - if iterate_batch: - decodeds = [] - for i in range(latents.shape[0]): - decodeds.append(self.pretransform.decode(decoded[i:i+1])) - decoded = torch.cat(decodeds, dim=0) - else: - decoded = self.pretransform.decode(decoded) - - if self.soft_clip: - decoded = torch.tanh(decoded) - - return decoded - - def encode_audio(self, audio, in_sr, **kwargs): - ''' - Encode single audio tensor to latents, including preprocessing the audio to be compatible with the model - ''' - - if in_sr != self.sample_rate: - resample_tf = T.Resample(in_sr, self.sample_rate).to(audio.device) - audio = resample_tf(audio) - - audio_length = audio.shape[-1] - - pad_length = (self.min_length - (audio_length % self.min_length)) % self.min_length - - # Pad with zeros to multiple of model's downsampling ratio - audio = F.pad(audio, (0, pad_length)) - - audio = prepare_audio(audio, in_sr=self.sample_rate, target_sr=self.sample_rate, target_length=audio.shape[1], target_channels=self.in_channels, device=audio.device) - - # TODO: Add chunking logic - - return self.encode(audio, **kwargs) - - def decode_audio(self, latents, **kwargs): - ''' - Decode latents to audio - ''' - - # TODO: Add chunking logic - - return self.decode(latents, **kwargs) - -class DiffusionAutoencoder(AudioAutoencoder): - def __init__( - self, - diffusion: ConditionedDiffusionModel, - diffusion_downsampling_ratio, - *args, - **kwargs - ): - super().__init__(*args, **kwargs) - - self.diffusion = diffusion - - self.min_length = self.downsampling_ratio * diffusion_downsampling_ratio - - if self.encoder is not None: - # Shrink the initial encoder parameters to avoid saturated latents - with torch.no_grad(): - for param in self.encoder.parameters(): - param *= 0.5 - - def decode(self, latents, steps=100): - - upsampled_length = latents.shape[2] * self.downsampling_ratio - - if self.bottleneck is not None: - latents = self.bottleneck.decode(latents) - - if self.decoder is not None: - latents = self.decode(latents) - - # Upsample latents to match diffusion length - if latents.shape[2] != upsampled_length: - latents = F.interpolate(latents, size=upsampled_length, mode='nearest') - - noise = torch.randn(latents.shape[0], self.io_channels, upsampled_length, device=latents.device) - decoded = sample(self.diffusion, noise, steps, 0, input_concat_cond=latents) - - if self.pretransform is not None: - if self.pretransform.enable_grad: - decoded = self.pretransform.decode(decoded) - else: - with torch.no_grad(): - decoded = self.pretransform.decode(decoded) - - return decoded - -# AE factories - -def create_encoder_from_config(encoder_config: Dict[str, Any]): - encoder_type = encoder_config.get("type", None) - assert encoder_type is not None, "Encoder type must be specified" - - if encoder_type == "oobleck": - encoder = OobleckEncoder( - **encoder_config["config"] - ) - - elif encoder_type == "seanet": - from encodec.modules import SEANetEncoder - seanet_encoder_config = encoder_config["config"] - - #SEANet encoder expects strides in reverse order - seanet_encoder_config["ratios"] = list(reversed(seanet_encoder_config.get("ratios", [2, 2, 2, 2, 2]))) - encoder = SEANetEncoder( - **seanet_encoder_config - ) - elif encoder_type == "dac": - dac_config = encoder_config["config"] - - encoder = DACEncoderWrapper(**dac_config) - elif encoder_type == "local_attn": - from .local_attention import TransformerEncoder1D - - local_attn_config = encoder_config["config"] - - encoder = TransformerEncoder1D( - **local_attn_config - ) - else: - raise ValueError(f"Unknown encoder type {encoder_type}") - - requires_grad = encoder_config.get("requires_grad", True) - if not requires_grad: - for param in encoder.parameters(): - param.requires_grad = False - - return encoder - -def create_decoder_from_config(decoder_config: Dict[str, Any]): - decoder_type = decoder_config.get("type", None) - assert decoder_type is not None, "Decoder type must be specified" - - if decoder_type == "oobleck": - decoder = OobleckDecoder( - **decoder_config["config"] - ) - elif decoder_type == "seanet": - from encodec.modules import SEANetDecoder - - decoder = SEANetDecoder( - **decoder_config["config"] - ) - elif decoder_type == "dac": - dac_config = decoder_config["config"] - - decoder = DACDecoderWrapper(**dac_config) - elif decoder_type == "local_attn": - from .local_attention import TransformerDecoder1D - - local_attn_config = decoder_config["config"] - - decoder = TransformerDecoder1D( - **local_attn_config - ) - else: - raise ValueError(f"Unknown decoder type {decoder_type}") - - requires_grad = decoder_config.get("requires_grad", True) - if not requires_grad: - for param in decoder.parameters(): - param.requires_grad = False - - return decoder - -def create_autoencoder_from_config(config: Dict[str, Any]): - - ae_config = config["model"] - - encoder = create_encoder_from_config(ae_config["encoder"]) - decoder = create_decoder_from_config(ae_config["decoder"]) - - bottleneck = ae_config.get("bottleneck", None) - - latent_dim = ae_config.get("latent_dim", None) - assert latent_dim is not None, "latent_dim must be specified in model config" - downsampling_ratio = ae_config.get("downsampling_ratio", None) - assert downsampling_ratio is not None, "downsampling_ratio must be specified in model config" - io_channels = ae_config.get("io_channels", None) - assert io_channels is not None, "io_channels must be specified in model config" - sample_rate = config.get("sample_rate", None) - assert sample_rate is not None, "sample_rate must be specified in model config" - - in_channels = ae_config.get("in_channels", None) - out_channels = ae_config.get("out_channels", None) - - pretransform = ae_config.get("pretransform", None) - - if pretransform is not None: - pretransform = create_pretransform_from_config(pretransform, sample_rate) - - if bottleneck is not None: - bottleneck = create_bottleneck_from_config(bottleneck) - - soft_clip = ae_config["decoder"].get("soft_clip", False) - - return AudioAutoencoder( - encoder, - decoder, - io_channels=io_channels, - latent_dim=latent_dim, - downsampling_ratio=downsampling_ratio, - sample_rate=sample_rate, - bottleneck=bottleneck, - pretransform=pretransform, - in_channels=in_channels, - out_channels=out_channels, - soft_clip=soft_clip - ) - -def create_diffAE_from_config(config: Dict[str, Any]): - - diffae_config = config["model"] - - if "encoder" in diffae_config: - encoder = create_encoder_from_config(diffae_config["encoder"]) - else: - encoder = None - - if "decoder" in diffae_config: - decoder = create_decoder_from_config(diffae_config["decoder"]) - else: - decoder = None - - diffusion_model_type = diffae_config["diffusion"]["type"] - - if diffusion_model_type == "DAU1d": - diffusion = DAU1DCondWrapper(**diffae_config["diffusion"]["config"]) - elif diffusion_model_type == "adp_1d": - diffusion = UNet1DCondWrapper(**diffae_config["diffusion"]["config"]) - elif diffusion_model_type == "dit": - diffusion = DiTWrapper(**diffae_config["diffusion"]["config"]) - - latent_dim = diffae_config.get("latent_dim", None) - assert latent_dim is not None, "latent_dim must be specified in model config" - downsampling_ratio = diffae_config.get("downsampling_ratio", None) - assert downsampling_ratio is not None, "downsampling_ratio must be specified in model config" - io_channels = diffae_config.get("io_channels", None) - assert io_channels is not None, "io_channels must be specified in model config" - sample_rate = config.get("sample_rate", None) - assert sample_rate is not None, "sample_rate must be specified in model config" - - bottleneck = diffae_config.get("bottleneck", None) - - pretransform = diffae_config.get("pretransform", None) - - if pretransform is not None: - pretransform = create_pretransform_from_config(pretransform, sample_rate) - - if bottleneck is not None: - bottleneck = create_bottleneck_from_config(bottleneck) - - diffusion_downsampling_ratio = None, - - if diffusion_model_type == "DAU1d": - diffusion_downsampling_ratio = np.prod(diffae_config["diffusion"]["config"]["strides"]) - elif diffusion_model_type == "adp_1d": - diffusion_downsampling_ratio = np.prod(diffae_config["diffusion"]["config"]["factors"]) - elif diffusion_model_type == "dit": - diffusion_downsampling_ratio = 1 - - return DiffusionAutoencoder( - encoder=encoder, - decoder=decoder, - diffusion=diffusion, - io_channels=io_channels, - sample_rate=sample_rate, - latent_dim=latent_dim, - downsampling_ratio=downsampling_ratio, - diffusion_downsampling_ratio=diffusion_downsampling_ratio, - bottleneck=bottleneck, - pretransform=pretransform - ) \ No newline at end of file diff --git a/sonique/stable_audio_tools/models/blocks.py b/sonique/stable_audio_tools/models/blocks.py deleted file mode 100644 index bc1d4c1fe732d8773f7d9db53f5671a813f83ee1..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/models/blocks.py +++ /dev/null @@ -1,206 +0,0 @@ -from functools import reduce -import math -import torch -from torch import nn -from torch.nn import functional as F - -from torch.backends.cuda import sdp_kernel -from packaging import version - -from dac.nn.layers import Snake1d - -class ResidualBlock(nn.Module): - def __init__(self, main, skip=None): - super().__init__() - self.main = nn.Sequential(*main) - self.skip = skip if skip else nn.Identity() - - def forward(self, input): - return self.main(input) + self.skip(input) - -class ResConvBlock(ResidualBlock): - def __init__(self, c_in, c_mid, c_out, is_last=False, kernel_size=5, conv_bias=True, use_snake=False): - skip = None if c_in == c_out else nn.Conv1d(c_in, c_out, 1, bias=False) - super().__init__([ - nn.Conv1d(c_in, c_mid, kernel_size, padding=kernel_size//2, bias=conv_bias), - nn.GroupNorm(1, c_mid), - Snake1d(c_mid) if use_snake else nn.GELU(), - nn.Conv1d(c_mid, c_out, kernel_size, padding=kernel_size//2, bias=conv_bias), - nn.GroupNorm(1, c_out) if not is_last else nn.Identity(), - (Snake1d(c_out) if use_snake else nn.GELU()) if not is_last else nn.Identity(), - ], skip) - -class SelfAttention1d(nn.Module): - def __init__(self, c_in, n_head=1, dropout_rate=0.): - super().__init__() - assert c_in % n_head == 0 - self.norm = nn.GroupNorm(1, c_in) - self.n_head = n_head - self.qkv_proj = nn.Conv1d(c_in, c_in * 3, 1) - self.out_proj = nn.Conv1d(c_in, c_in, 1) - self.dropout = nn.Dropout(dropout_rate, inplace=True) - - self.use_flash = torch.cuda.is_available() and version.parse(torch.__version__) >= version.parse('2.0.0') - - if not self.use_flash: - return - - device_properties = torch.cuda.get_device_properties(torch.device('cuda')) - - if device_properties.major == 8 and device_properties.minor == 0: - # Use flash attention for A100 GPUs - self.sdp_kernel_config = (True, False, False) - else: - # Don't use flash attention for other GPUs - self.sdp_kernel_config = (False, True, True) - - def forward(self, input): - n, c, s = input.shape - qkv = self.qkv_proj(self.norm(input)) - qkv = qkv.view( - [n, self.n_head * 3, c // self.n_head, s]).transpose(2, 3) - q, k, v = qkv.chunk(3, dim=1) - scale = k.shape[3]**-0.25 - - if self.use_flash: - with sdp_kernel(*self.sdp_kernel_config): - y = F.scaled_dot_product_attention(q, k, v, is_causal=False).contiguous().view([n, c, s]) - else: - att = ((q * scale) @ (k.transpose(2, 3) * scale)).softmax(3) - y = (att @ v).transpose(2, 3).contiguous().view([n, c, s]) - - - return input + self.dropout(self.out_proj(y)) - -class SkipBlock(nn.Module): - def __init__(self, *main): - super().__init__() - self.main = nn.Sequential(*main) - - def forward(self, input): - return torch.cat([self.main(input), input], dim=1) - -class FourierFeatures(nn.Module): - def __init__(self, in_features, out_features, std=1.): - super().__init__() - assert out_features % 2 == 0 - self.weight = nn.Parameter(torch.randn( - [out_features // 2, in_features]) * std) - - def forward(self, input): - f = 2 * math.pi * input @ self.weight.T - return torch.cat([f.cos(), f.sin()], dim=-1) - -def expand_to_planes(input, shape): - return input[..., None].repeat([1, 1, shape[2]]) - -_kernels = { - 'linear': - [1 / 8, 3 / 8, 3 / 8, 1 / 8], - 'cubic': - [-0.01171875, -0.03515625, 0.11328125, 0.43359375, - 0.43359375, 0.11328125, -0.03515625, -0.01171875], - 'lanczos3': - [0.003689131001010537, 0.015056144446134567, -0.03399861603975296, - -0.066637322306633, 0.13550527393817902, 0.44638532400131226, - 0.44638532400131226, 0.13550527393817902, -0.066637322306633, - -0.03399861603975296, 0.015056144446134567, 0.003689131001010537] -} - -class Downsample1d(nn.Module): - def __init__(self, kernel='linear', pad_mode='reflect'): - super().__init__() - self.pad_mode = pad_mode - kernel_1d = torch.tensor(_kernels[kernel]) - self.pad = kernel_1d.shape[0] // 2 - 1 - self.register_buffer('kernel', kernel_1d) - - def forward(self, x): - x = F.pad(x, (self.pad,) * 2, self.pad_mode) - weight = x.new_zeros([x.shape[1], x.shape[1], self.kernel.shape[0]]) - indices = torch.arange(x.shape[1], device=x.device) - weight[indices, indices] = self.kernel.to(weight) - return F.conv1d(x, weight, stride=2) - - -class Upsample1d(nn.Module): - def __init__(self, kernel='linear', pad_mode='reflect'): - super().__init__() - self.pad_mode = pad_mode - kernel_1d = torch.tensor(_kernels[kernel]) * 2 - self.pad = kernel_1d.shape[0] // 2 - 1 - self.register_buffer('kernel', kernel_1d) - - def forward(self, x): - x = F.pad(x, ((self.pad + 1) // 2,) * 2, self.pad_mode) - weight = x.new_zeros([x.shape[1], x.shape[1], self.kernel.shape[0]]) - indices = torch.arange(x.shape[1], device=x.device) - weight[indices, indices] = self.kernel.to(weight) - return F.conv_transpose1d(x, weight, stride=2, padding=self.pad * 2 + 1) - -def Downsample1d_2( - in_channels: int, out_channels: int, factor: int, kernel_multiplier: int = 2 -) -> nn.Module: - assert kernel_multiplier % 2 == 0, "Kernel multiplier must be even" - - return nn.Conv1d( - in_channels=in_channels, - out_channels=out_channels, - kernel_size=factor * kernel_multiplier + 1, - stride=factor, - padding=factor * (kernel_multiplier // 2), - ) - - -def Upsample1d_2( - in_channels: int, out_channels: int, factor: int, use_nearest: bool = False -) -> nn.Module: - - if factor == 1: - return nn.Conv1d( - in_channels=in_channels, out_channels=out_channels, kernel_size=3, padding=1 - ) - - if use_nearest: - return nn.Sequential( - nn.Upsample(scale_factor=factor, mode="nearest"), - nn.Conv1d( - in_channels=in_channels, - out_channels=out_channels, - kernel_size=3, - padding=1, - ), - ) - else: - return nn.ConvTranspose1d( - in_channels=in_channels, - out_channels=out_channels, - kernel_size=factor * 2, - stride=factor, - padding=factor // 2 + factor % 2, - output_padding=factor % 2, - ) - -def zero_init(layer): - nn.init.zeros_(layer.weight) - if layer.bias is not None: - nn.init.zeros_(layer.bias) - return layer - -def rms_norm(x, scale, eps): - dtype = reduce(torch.promote_types, (x.dtype, scale.dtype, torch.float32)) - mean_sq = torch.mean(x.to(dtype)**2, dim=-1, keepdim=True) - scale = scale.to(dtype) * torch.rsqrt(mean_sq + eps) - return x * scale.to(x.dtype) - -class AdaRMSNorm(nn.Module): - def __init__(self, features, cond_features, eps=1e-6): - super().__init__() - self.eps = eps - self.linear = zero_init(nn.Linear(cond_features, features, bias=False)) - - def extra_repr(self): - return f"eps={self.eps}," - - def forward(self, x, cond): - return rms_norm(x, self.linear(cond)[:, None, :] + 1, self.eps) \ No newline at end of file diff --git a/sonique/stable_audio_tools/models/bottleneck.py b/sonique/stable_audio_tools/models/bottleneck.py deleted file mode 100644 index dec4996d8a5fd4af94f385fc21a32465303c7ef3..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/models/bottleneck.py +++ /dev/null @@ -1,288 +0,0 @@ -import torch -from torch import nn -from torch.nn import functional as F - -from einops import rearrange -from vector_quantize_pytorch import ResidualVQ, FSQ -from dac.nn.quantize import ResidualVectorQuantize as DACResidualVQ - -class Bottleneck(nn.Module): - def __init__(self): - super().__init__() - - def encode(self, x, return_info=False, **kwargs): - raise NotImplementedError - - def decode(self, x): - raise NotImplementedError - -class TanhBottleneck(Bottleneck): - def __init__(self): - super().__init__() - self.tanh = nn.Tanh() - - def encode(self, x, return_info=False): - info = {} - - x = torch.tanh(x) - - if return_info: - return x, info - else: - return x - - def decode(self, x): - return x - -def vae_sample(mean, scale): - stdev = nn.functional.softplus(scale) + 1e-4 - var = stdev * stdev - logvar = torch.log(var) - latents = torch.randn_like(mean) * stdev + mean - - kl = (mean * mean + var - logvar - 1).sum(1).mean() - - return latents, kl - -class VAEBottleneck(Bottleneck): - def __init__(self): - super().__init__() - - def encode(self, x, return_info=False, **kwargs): - info = {} - - mean, scale = x.chunk(2, dim=1) - - x, kl = vae_sample(mean, scale) - - info["kl"] = kl - - if return_info: - return x, info - else: - return x - - def decode(self, x): - return x - -def compute_mean_kernel(x, y): - kernel_input = (x[:, None] - y[None]).pow(2).mean(2) / x.shape[-1] - return torch.exp(-kernel_input).mean() - -def compute_mmd(latents): - latents_reshaped = latents.permute(0, 2, 1).reshape(-1, latents.shape[1]) - noise = torch.randn_like(latents_reshaped) - - latents_kernel = compute_mean_kernel(latents_reshaped, latents_reshaped) - noise_kernel = compute_mean_kernel(noise, noise) - latents_noise_kernel = compute_mean_kernel(latents_reshaped, noise) - - mmd = latents_kernel + noise_kernel - 2 * latents_noise_kernel - return mmd.mean() - -class WassersteinBottleneck(Bottleneck): - def __init__(self, noise_augment_dim: int = 0): - super().__init__() - - self.noise_augment_dim = noise_augment_dim - - def encode(self, x, return_info=False): - info = {} - - if self.training and return_info: - mmd = compute_mmd(x) - info["mmd"] = mmd - - if return_info: - return x, info - - return x - - def decode(self, x): - - if self.noise_augment_dim > 0: - noise = torch.randn(x.shape[0], self.noise_augment_dim, - x.shape[-1]).type_as(x) - x = torch.cat([x, noise], dim=1) - - return x - -class L2Bottleneck(Bottleneck): - def __init__(self): - super().__init__() - - def encode(self, x, return_info=False): - info = {} - - x = F.normalize(x, dim=1) - - if return_info: - return x, info - else: - return x - - def decode(self, x): - return F.normalize(x, dim=1) - -class RVQBottleneck(Bottleneck): - def __init__(self, **quantizer_kwargs): - super().__init__() - self.quantizer = ResidualVQ(**quantizer_kwargs) - self.num_quantizers = quantizer_kwargs["num_quantizers"] - - def encode(self, x, return_info=False, **kwargs): - info = {} - - x = rearrange(x, "b c n -> b n c") - x, indices, loss = self.quantizer(x) - x = rearrange(x, "b n c -> b c n") - - info["quantizer_indices"] = indices - info["quantizer_loss"] = loss.mean() - - if return_info: - return x, info - else: - return x - - def decode(self, x): - return x - -class RVQVAEBottleneck(Bottleneck): - def __init__(self, **quantizer_kwargs): - super().__init__() - self.quantizer = ResidualVQ(**quantizer_kwargs) - self.num_quantizers = quantizer_kwargs["num_quantizers"] - - def encode(self, x, return_info=False): - info = {} - - x, kl = vae_sample(*x.chunk(2, dim=1)) - - info["kl"] = kl - - x = rearrange(x, "b c n -> b n c") - x, indices, loss = self.quantizer(x) - x = rearrange(x, "b n c -> b c n") - - info["quantizer_indices"] = indices - info["quantizer_loss"] = loss.mean() - - if return_info: - return x, info - else: - return x - - def decode(self, x): - return x - -class DACRVQBottleneck(Bottleneck): - def __init__(self, quantize_on_decode=False, **quantizer_kwargs): - super().__init__() - self.quantizer = DACResidualVQ(**quantizer_kwargs) - self.num_quantizers = quantizer_kwargs["n_codebooks"] - self.quantize_on_decode = quantize_on_decode - - def encode(self, x, return_info=False, **kwargs): - info = {} - - info["pre_quantizer"] = x - - if self.quantize_on_decode: - return x, info if return_info else x - - z, codes, latents, commitment_loss, codebook_loss = self.quantizer(x, **kwargs) - - output = { - "z": z, - "codes": codes, - "latents": latents, - "vq/commitment_loss": commitment_loss, - "vq/codebook_loss": codebook_loss, - } - - output["vq/commitment_loss"] /= self.num_quantizers - output["vq/codebook_loss"] /= self.num_quantizers - - info.update(output) - - if return_info: - return output["z"], info - - return output["z"] - - def decode(self, x): - - if self.quantize_on_decode: - x = self.quantizer(x)[0] - - return x - -class DACRVQVAEBottleneck(Bottleneck): - def __init__(self, quantize_on_decode=False, **quantizer_kwargs): - super().__init__() - self.quantizer = DACResidualVQ(**quantizer_kwargs) - self.num_quantizers = quantizer_kwargs["n_codebooks"] - self.quantize_on_decode = quantize_on_decode - - def encode(self, x, return_info=False, n_quantizers: int = None): - info = {} - - mean, scale = x.chunk(2, dim=1) - - x, kl = vae_sample(mean, scale) - - info["pre_quantizer"] = x - info["kl"] = kl - - if self.quantize_on_decode: - return x, info if return_info else x - - z, codes, latents, commitment_loss, codebook_loss = self.quantizer(x, n_quantizers=n_quantizers) - - output = { - "z": z, - "codes": codes, - "latents": latents, - "vq/commitment_loss": commitment_loss, - "vq/codebook_loss": codebook_loss, - } - - output["vq/commitment_loss"] /= self.num_quantizers - output["vq/codebook_loss"] /= self.num_quantizers - - info.update(output) - - if return_info: - return output["z"], info - - return output["z"] - - def decode(self, x): - - if self.quantize_on_decode: - x = self.quantizer(x)[0] - - return x - -class FSQBottleneck(Bottleneck): - def __init__(self, dim, levels): - super().__init__() - self.quantizer = FSQ(levels=[levels] * dim) - - def encode(self, x, return_info=False): - info = {} - - x = rearrange(x, "b c n -> b n c") - x, indices = self.quantizer(x) - x = rearrange(x, "b n c -> b c n") - - info["quantizer_indices"] = indices - - if return_info: - return x, info - else: - return x - - def decode(self, x): - return x \ No newline at end of file diff --git a/sonique/stable_audio_tools/models/conditioners.py b/sonique/stable_audio_tools/models/conditioners.py deleted file mode 100644 index 9cae65fbf47179a87a3a4b7c18966051e64b5774..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/models/conditioners.py +++ /dev/null @@ -1,554 +0,0 @@ -#Heavily influenced by https://github.com/facebookresearch/audiocraft/blob/main/audiocraft/modules/conditioners.py - -import torch -import logging, warnings -import string -import typing as tp -import gc - -from .adp import NumberEmbedder -from ...inference.utils import set_audio_channels -from .factory import create_pretransform_from_config -from .pretransforms import Pretransform -from ..training.utils import copy_state_dict -from .utils import load_ckpt_state_dict - -from torch import nn - -class Conditioner(nn.Module): - def __init__( - self, - dim: int, - output_dim: int, - project_out: bool = False, - ): - - super().__init__() - - self.dim = dim - self.output_dim = output_dim - self.proj_out = nn.Linear(dim, output_dim) if (dim != output_dim or project_out) else nn.Identity() - - def forward(self, x: tp.Any) -> tp.Any: - raise NotImplementedError() - -class IntConditioner(Conditioner): - def __init__(self, - output_dim: int, - min_val: int=0, - max_val: int=512 - ): - super().__init__(output_dim, output_dim) - - self.min_val = min_val - self.max_val = max_val - self.int_embedder = nn.Embedding(max_val - min_val + 1, output_dim).requires_grad_(True) - - def forward(self, ints: tp.List[int], device=None) -> tp.Any: - - #self.int_embedder.to(device) - - ints = torch.tensor(ints).to(device) - ints = ints.clamp(self.min_val, self.max_val) - - int_embeds = self.int_embedder(ints).unsqueeze(1) - - return [int_embeds, torch.ones(int_embeds.shape[0], 1).to(device)] - -class NumberConditioner(Conditioner): - ''' - Conditioner that takes a list of floats, normalizes them for a given range, and returns a list of embeddings - ''' - def __init__(self, - output_dim: int, - min_val: float=0, - max_val: float=1 - ): - super().__init__(output_dim, output_dim) - - self.min_val = min_val - self.max_val = max_val - - self.embedder = NumberEmbedder(features=output_dim) - - def forward(self, floats: tp.List[float], device=None) -> tp.Any: - - # Cast the inputs to floats - floats = [float(x) for x in floats] - - floats = torch.tensor(floats).to(device) - - floats = floats.clamp(self.min_val, self.max_val) - - normalized_floats = (floats - self.min_val) / (self.max_val - self.min_val) - - float_embeds = self.embedder(normalized_floats).unsqueeze(1) - - return [float_embeds, torch.ones(float_embeds.shape[0], 1).to(device)] - -class CLAPTextConditioner(Conditioner): - def __init__(self, - output_dim: int, - clap_ckpt_path, - use_text_features = False, - feature_layer_ix: int = -1, - audio_model_type="HTSAT-base", - enable_fusion=True, - project_out: bool = False, - finetune: bool = False): - super().__init__(768 if use_text_features else 512, output_dim, project_out=project_out) - - self.use_text_features = use_text_features - self.feature_layer_ix = feature_layer_ix - self.finetune = finetune - - # Suppress logging from transformers - previous_level = logging.root.manager.disable - logging.disable(logging.ERROR) - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - try: - import laion_clap - from laion_clap.clap_module.factory import load_state_dict as clap_load_state_dict - - model = laion_clap.CLAP_Module(enable_fusion=enable_fusion, amodel=audio_model_type, device='cpu') - - if self.finetune: - self.model = model - else: - self.__dict__["model"] = model - - state_dict = clap_load_state_dict(clap_ckpt_path) - self.model.model.load_state_dict(state_dict, strict=False) - - if self.finetune: - self.model.model.text_branch.requires_grad_(True) - self.model.model.text_branch.train() - else: - self.model.model.text_branch.requires_grad_(False) - self.model.model.text_branch.eval() - - finally: - logging.disable(previous_level) - - del self.model.model.audio_branch - - gc.collect() - torch.cuda.empty_cache() - - def get_clap_features(self, prompts, layer_ix=-2, device: tp.Any = "cuda"): - prompt_tokens = self.model.tokenizer(prompts) - attention_mask = prompt_tokens["attention_mask"].to(device=device, non_blocking=True) - prompt_features = self.model.model.text_branch( - input_ids=prompt_tokens["input_ids"].to(device=device, non_blocking=True), - attention_mask=attention_mask, - output_hidden_states=True - )["hidden_states"][layer_ix] - - return prompt_features, attention_mask - - def forward(self, texts: tp.List[str], device: tp.Any = "cuda") -> tp.Any: - self.model.to(device) - - if self.use_text_features: - if len(texts) == 1: - text_features, text_attention_mask = self.get_clap_features([texts[0], ""], layer_ix=self.feature_layer_ix, device=device) - text_features = text_features[:1, ...] - text_attention_mask = text_attention_mask[:1, ...] - else: - text_features, text_attention_mask = self.get_clap_features(texts, layer_ix=self.feature_layer_ix, device=device) - return [self.proj_out(text_features), text_attention_mask] - - # Fix for CLAP bug when only one text is passed - if len(texts) == 1: - text_embedding = self.model.get_text_embedding([texts[0], ""], use_tensor=True)[:1, ...] - else: - text_embedding = self.model.get_text_embedding(texts, use_tensor=True) - - text_embedding = text_embedding.unsqueeze(1).to(device) - - return [self.proj_out(text_embedding), torch.ones(text_embedding.shape[0], 1).to(device)] - -class CLAPAudioConditioner(Conditioner): - def __init__(self, - output_dim: int, - clap_ckpt_path, - audio_model_type="HTSAT-base", - enable_fusion=True, - project_out: bool = False): - super().__init__(512, output_dim, project_out=project_out) - - device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') - - # Suppress logging from transformers - previous_level = logging.root.manager.disable - logging.disable(logging.ERROR) - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - try: - import laion_clap - from laion_clap.clap_module.factory import load_state_dict as clap_load_state_dict - - model = laion_clap.CLAP_Module(enable_fusion=enable_fusion, amodel=audio_model_type, device='cpu') - - if self.finetune: - self.model = model - else: - self.__dict__["model"] = model - - state_dict = clap_load_state_dict(clap_ckpt_path) - self.model.model.load_state_dict(state_dict, strict=False) - - if self.finetune: - self.model.model.audio_branch.requires_grad_(True) - self.model.model.audio_branch.train() - else: - self.model.model.audio_branch.requires_grad_(False) - self.model.model.audio_branch.eval() - - finally: - logging.disable(previous_level) - - del self.model.model.text_branch - - gc.collect() - torch.cuda.empty_cache() - - def forward(self, audios: tp.Union[torch.Tensor, tp.List[torch.Tensor], tp.Tuple[torch.Tensor]] , device: tp.Any = "cuda") -> tp.Any: - - self.model.to(device) - - if isinstance(audios, list) or isinstance(audios, tuple): - audios = torch.cat(audios, dim=0) - - # Convert to mono - mono_audios = audios.mean(dim=1) - - with torch.cuda.amp.autocast(enabled=False): - audio_embedding = self.model.get_audio_embedding_from_data(mono_audios.float(), use_tensor=True) - - audio_embedding = audio_embedding.unsqueeze(1).to(device) - - return [self.proj_out(audio_embedding), torch.ones(audio_embedding.shape[0], 1).to(device)] - -class T5Conditioner(Conditioner): - - T5_MODELS = ["t5-small", "t5-base", "t5-large", "t5-3b", "t5-11b", - "google/flan-t5-small", "google/flan-t5-base", "google/flan-t5-large", - "google/flan-t5-xl", "google/flan-t5-xxl"] - - T5_MODEL_DIMS = { - "t5-small": 512, - "t5-base": 768, - "t5-large": 1024, - "t5-3b": 1024, - "t5-11b": 1024, - "t5-xl": 2048, - "t5-xxl": 4096, - "google/flan-t5-small": 512, - "google/flan-t5-base": 768, - "google/flan-t5-large": 1024, - "google/flan-t5-3b": 1024, - "google/flan-t5-11b": 1024, - "google/flan-t5-xl": 2048, - "google/flan-t5-xxl": 4096, - } - - def __init__( - self, - output_dim: int, - t5_model_name: str = "t5-base", - max_length: str = 128, - enable_grad: bool = False, - project_out: bool = False, - ): - assert t5_model_name in self.T5_MODELS, f"Unknown T5 model name: {t5_model_name}" - super().__init__(self.T5_MODEL_DIMS[t5_model_name], output_dim, project_out=project_out) - - from transformers import T5EncoderModel, AutoTokenizer - - self.max_length = max_length - self.enable_grad = enable_grad - - # Suppress logging from transformers - previous_level = logging.root.manager.disable - logging.disable(logging.ERROR) - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - try: - # self.tokenizer = T5Tokenizer.from_pretrained(t5_model_name, model_max_length = max_length) - # model = T5EncoderModel.from_pretrained(t5_model_name, max_length=max_length).train(enable_grad).requires_grad_(enable_grad) - self.tokenizer = AutoTokenizer.from_pretrained(t5_model_name) - model = T5EncoderModel.from_pretrained(t5_model_name).train(enable_grad).requires_grad_(enable_grad).to(torch.float16) - finally: - logging.disable(previous_level) - - if self.enable_grad: - self.model = model - else: - self.__dict__["model"] = model - - - def forward(self, texts: tp.List[str], device: tp.Union[torch.device, str]) -> tp.Tuple[torch.Tensor, torch.Tensor]: - - self.model.to(device) - self.proj_out.to(device) - - encoded = self.tokenizer( - texts, - truncation=True, - max_length=self.max_length, - padding="max_length", - return_tensors="pt", - ) - - input_ids = encoded["input_ids"].to(device) - attention_mask = encoded["attention_mask"].to(device).to(torch.bool) - - self.model.eval() - - with torch.cuda.amp.autocast(dtype=torch.float16) and torch.set_grad_enabled(self.enable_grad): - embeddings = self.model( - input_ids=input_ids, attention_mask=attention_mask - )["last_hidden_state"] - - embeddings = self.proj_out(embeddings.float()) - - embeddings = embeddings * attention_mask.unsqueeze(-1).float() - - return embeddings, attention_mask - -class PhonemeConditioner(Conditioner): - """ - A conditioner that turns text into phonemes and embeds them using a lookup table - Only works for English text - - Args: - output_dim: the dimension of the output embeddings - max_length: the maximum number of phonemes to embed - project_out: whether to add another linear projection to the output embeddings - """ - - def __init__( - self, - output_dim: int, - max_length: int = 1024, - project_out: bool = False, - ): - super().__init__(output_dim, output_dim, project_out=project_out) - - from g2p_en import G2p - - self.max_length = max_length - - self.g2p = G2p() - - # Reserving 0 for padding, 1 for ignored - self.phoneme_embedder = nn.Embedding(len(self.g2p.phonemes) + 2, output_dim) - - def forward(self, texts: tp.List[str], device: tp.Union[torch.device, str]) -> tp.Tuple[torch.Tensor, torch.Tensor]: - - self.phoneme_embedder.to(device) - self.proj_out.to(device) - - batch_phonemes = [self.g2p(text) for text in texts] # shape [batch_size, length] - - phoneme_ignore = [" ", *string.punctuation] - - # Remove ignored phonemes and cut to max length - batch_phonemes = [[p if p not in phoneme_ignore else "_" for p in phonemes] for phonemes in batch_phonemes] - - # Convert to ids - phoneme_ids = [[self.g2p.p2idx[p] + 2 if p in self.g2p.p2idx else 1 for p in phonemes] for phonemes in batch_phonemes] - - #Pad to match longest and make a mask tensor for the padding - longest = max([len(ids) for ids in phoneme_ids]) - phoneme_ids = [ids + [0] * (longest - len(ids)) for ids in phoneme_ids] - - phoneme_ids = torch.tensor(phoneme_ids).to(device) - - # Convert to embeddings - phoneme_embeds = self.phoneme_embedder(phoneme_ids) - - phoneme_embeds = self.proj_out(phoneme_embeds) - - return phoneme_embeds, torch.ones(phoneme_embeds.shape[0], phoneme_embeds.shape[1]).to(device) - -class TokenizerLUTConditioner(Conditioner): - """ - A conditioner that embeds text using a lookup table on a pretrained tokenizer's vocabulary - - Args: - tokenizer_name: the name of the tokenizer from the Hugging Face transformers library - output_dim: the dimension of the output embeddings - max_length: the maximum length of the text to embed - project_out: whether to add another linear projection to the output embeddings - """ - - def __init__( - self, - tokenizer_name: str, # Name of a tokenizer from the Hugging Face transformers library - output_dim: int, - max_length: int = 1024, - project_out: bool = False, - ): - super().__init__(output_dim, output_dim, project_out=project_out) - - from transformers import AutoTokenizer - - # Suppress logging from transformers - previous_level = logging.root.manager.disable - logging.disable(logging.ERROR) - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - try: - self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) - finally: - logging.disable(previous_level) - - self.max_length = max_length - - self.token_embedder = nn.Embedding(len(self.tokenizer), output_dim) - - def forward(self, texts: tp.List[str], device: tp.Union[torch.device, str]) -> tp.Tuple[torch.Tensor, torch.Tensor]: - self.proj_out.to(device) - - encoded = self.tokenizer( - texts, - truncation=True, - max_length=self.max_length, - padding="max_length", - return_tensors="pt", - ) - - input_ids = encoded["input_ids"].to(device) - attention_mask = encoded["attention_mask"].to(device).to(torch.bool) - - embeddings = self.token_embedder(input_ids) - - embeddings = self.proj_out(embeddings) - - embeddings = embeddings * attention_mask.unsqueeze(-1).float() - - return embeddings, attention_mask - -class PretransformConditioner(Conditioner): - """ - A conditioner that uses a pretransform's encoder for conditioning - - Args: - pretransform: an instantiated pretransform to use for conditioning - output_dim: the dimension of the output embeddings - """ - def __init__(self, pretransform: Pretransform, output_dim: int): - super().__init__(pretransform.encoded_channels, output_dim) - - self.pretransform = pretransform - - def forward(self, audio: tp.Union[torch.Tensor, tp.List[torch.Tensor], tp.Tuple[torch.Tensor]], device: tp.Union[torch.device, str]) -> tp.Tuple[torch.Tensor, torch.Tensor]: - - self.pretransform.to(device) - self.proj_out.to(device) - - if isinstance(audio, list) or isinstance(audio, tuple): - audio = torch.cat(audio, dim=0) - - # Convert audio to pretransform input channels - audio = set_audio_channels(audio, self.pretransform.io_channels) - - latents = self.pretransform.encode(audio) - - latents = self.proj_out(latents) - - return [latents, torch.ones(latents.shape[0], latents.shape[2]).to(latents.device)] - -class MultiConditioner(nn.Module): - """ - A module that applies multiple conditioners to an input dictionary based on the keys - - Args: - conditioners: a dictionary of conditioners with keys corresponding to the keys of the conditioning input dictionary (e.g. "prompt") - default_keys: a dictionary of default keys to use if the key is not in the input dictionary (e.g. {"prompt_t5": "prompt"}) - """ - def __init__(self, conditioners: tp.Dict[str, Conditioner], default_keys: tp.Dict[str, str] = {}): - super().__init__() - - self.conditioners = nn.ModuleDict(conditioners) - self.default_keys = default_keys - - def forward(self, batch_metadata: tp.List[tp.Dict[str, tp.Any]], device: tp.Union[torch.device, str]) -> tp.Dict[str, tp.Any]: - output = {} - - for key, conditioner in self.conditioners.items(): - condition_key = key - - conditioner_inputs = [] - - for x in batch_metadata: - - if condition_key not in x: - if condition_key in self.default_keys: - condition_key = self.default_keys[condition_key] - else: - raise ValueError(f"Conditioner key {condition_key} not found in batch metadata") - - #Unwrap the condition info if it's a single-element list or tuple, this is to support collation functions that wrap everything in a list - if isinstance(x[condition_key], list) or isinstance(x[condition_key], tuple) and len(x[condition_key]) == 1: - conditioner_inputs.append(x[condition_key][0]) - else: - conditioner_inputs.append(x[condition_key]) - - output[key] = conditioner(conditioner_inputs, device) - - return output - -def create_multi_conditioner_from_conditioning_config(config: tp.Dict[str, tp.Any]) -> MultiConditioner: - """ - Create a MultiConditioner from a conditioning config dictionary - - Args: - config: the conditioning config dictionary - device: the device to put the conditioners on - """ - conditioners = {} - cond_dim = config["cond_dim"] - - default_keys = config.get("default_keys", {}) - - for conditioner_info in config["configs"]: - id = conditioner_info["id"] - - conditioner_type = conditioner_info["type"] - - conditioner_config = {"output_dim": cond_dim} - - conditioner_config.update(conditioner_info["config"]) - - if conditioner_type == "t5": - conditioners[id] = T5Conditioner(**conditioner_config) - elif conditioner_type == "clap_text": - conditioners[id] = CLAPTextConditioner(**conditioner_config) - elif conditioner_type == "clap_audio": - conditioners[id] = CLAPAudioConditioner(**conditioner_config) - elif conditioner_type == "int": - conditioners[id] = IntConditioner(**conditioner_config) - elif conditioner_type == "number": - conditioners[id] = NumberConditioner(**conditioner_config) - elif conditioner_type == "phoneme": - conditioners[id] = PhonemeConditioner(**conditioner_config) - elif conditioner_type == "lut": - conditioners[id] = TokenizerLUTConditioner(**conditioner_config) - elif conditioner_type == "pretransform": - sample_rate = conditioner_config.pop("sample_rate", None) - assert sample_rate is not None, "Sample rate must be specified for pretransform conditioners" - - pretransform = create_pretransform_from_config(conditioner_config.pop("pretransform_config"), sample_rate=sample_rate) - - if conditioner_config.get("pretransform_ckpt_path", None) is not None: - pretransform.load_state_dict(load_ckpt_state_dict(conditioner_config.pop("pretransform_ckpt_path"))) - - conditioners[id] = PretransformConditioner(pretransform, **conditioner_config) - else: - raise ValueError(f"Unknown conditioner type: {conditioner_type}") - - return MultiConditioner(conditioners, default_keys=default_keys) \ No newline at end of file diff --git a/sonique/stable_audio_tools/models/diffusion.py b/sonique/stable_audio_tools/models/diffusion.py deleted file mode 100644 index 07eeb4906d35e7c024ae636ae3a808b60f0903d4..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/models/diffusion.py +++ /dev/null @@ -1,985 +0,0 @@ -import torch -from torch import nn -from torch.nn import functional as F -from functools import partial, reduce -import numpy as np -import typing as tp - -import x_transformers -from x_transformers import ContinuousTransformerWrapper, Encoder -from einops import rearrange - -from .blocks import ResConvBlock, FourierFeatures, Upsample1d, Upsample1d_2, Downsample1d, Downsample1d_2, SelfAttention1d, SkipBlock, expand_to_planes -from .conditioners import MultiConditioner, create_multi_conditioner_from_conditioning_config -from .factory import create_pretransform_from_config -from .local_attention import ContinuousLocalTransformer -from .pretransforms import Pretransform -from ...inference.generation import generate_diffusion_cond - -from .adp import UNetCFG1d, UNet1d - -from time import time - -class Profiler: - - def __init__(self): - self.ticks = [[time(), None]] - - def tick(self, msg): - self.ticks.append([time(), msg]) - - def __repr__(self): - rep = 80 * "=" + "\n" - for i in range(1, len(self.ticks)): - msg = self.ticks[i][1] - ellapsed = self.ticks[i][0] - self.ticks[i - 1][0] - rep += msg + f": {ellapsed*1000:.2f}ms\n" - rep += 80 * "=" + "\n\n\n" - return rep - -class DiffusionModel(nn.Module): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def forward(self, x, t, **kwargs): - raise NotImplementedError() - -class DiffusionModelWrapper(nn.Module): - def __init__( - self, - model: DiffusionModel, - io_channels, - sample_size, - sample_rate, - min_input_length, - pretransform: tp.Optional[Pretransform] = None, - ): - super().__init__() - self.io_channels = io_channels - self.sample_size = sample_size - self.sample_rate = sample_rate - self.min_input_length = min_input_length - - self.model = model - - if pretransform is not None: - self.pretransform = pretransform - else: - self.pretransform = None - - def forward(self, x, t, **kwargs): - return self.model(x, t, **kwargs) - -class ConditionedDiffusionModel(nn.Module): - def __init__(self, - *args, - supports_cross_attention: bool = False, - supports_input_concat: bool = False, - supports_global_cond: bool = False, - supports_prepend_cond: bool = False, - **kwargs): - super().__init__(*args, **kwargs) - self.supports_cross_attention = supports_cross_attention - self.supports_input_concat = supports_input_concat - self.supports_global_cond = supports_global_cond - self.supports_prepend_cond = supports_prepend_cond - - def forward(self, - x: torch.Tensor, - t: torch.Tensor, - cross_attn_cond: torch.Tensor = None, - cross_attn_mask: torch.Tensor = None, - input_concat_cond: torch.Tensor = None, - global_embed: torch.Tensor = None, - prepend_cond: torch.Tensor = None, - prepend_cond_mask: torch.Tensor = None, - cfg_scale: float = 1.0, - cfg_dropout_prob: float = 0.0, - batch_cfg: bool = False, - rescale_cfg: bool = False, - **kwargs): - raise NotImplementedError() - -class ConditionedDiffusionModelWrapper(nn.Module): - """ - A diffusion model that takes in conditioning - """ - def __init__( - self, - model: ConditionedDiffusionModel, - conditioner: MultiConditioner, - io_channels, - sample_rate, - min_input_length: int, - pretransform: tp.Optional[Pretransform] = None, - cross_attn_cond_ids: tp.List[str] = [], - global_cond_ids: tp.List[str] = [], - input_concat_ids: tp.List[str] = [], - prepend_cond_ids: tp.List[str] = [], - ): - super().__init__() - - # if "audio" not in cross_attn_cond_ids: - # cross_attn_cond_ids.append("audio") - - self.model = model - self.conditioner = conditioner - self.io_channels = io_channels - self.sample_rate = sample_rate - self.pretransform = pretransform - self.cross_attn_cond_ids = cross_attn_cond_ids - self.global_cond_ids = global_cond_ids - self.input_concat_ids = input_concat_ids - self.prepend_cond_ids = prepend_cond_ids - self.min_input_length = min_input_length - - def get_conditioning_inputs(self, cond: tp.Dict[str, tp.Any], negative=False): - # print("cross_attn_cond_ids:", self.cross_attn_cond_ids) - # print("global_cond_ids:", self.global_cond_ids) - # print("input_concat_ids:", self.input_concat_ids) - # print("cond keys:", cond.keys()) - cross_attention_input = None - cross_attention_masks = None - global_cond = None - input_concat_cond = None - prepend_cond = None - prepend_cond_mask = None - - if len(self.cross_attn_cond_ids) > 0: - # Concatenate all cross-attention inputs over the sequence dimension - # Assumes that the cross-attention inputs are of shape (batch, seq, channels) - # for key in self.cross_attn_cond_ids: - # if key in cond: - # print(f"Key '{key}' found. Shape: {cond[key][0].shape if cond[key][0] is not None else 'None'}, Type: {type(cond[key][0])}") - # if key == "prompt": - # print(f"Prompt tensor content: {cond[key][0]}") # Print the content of the prompt tensor - # else: - # print(f"Key '{key}' not found in cond.") - cross_attention_input = torch.cat([cond[key][0] for key in self.cross_attn_cond_ids], dim=1) - cross_attention_masks = torch.cat([cond[key][1] for key in self.cross_attn_cond_ids], dim=1) - - if len(self.global_cond_ids) > 0: - # Concatenate all global conditioning inputs over the channel dimension - # Assumes that the global conditioning inputs are of shape (batch, channels) - global_cond = torch.cat([cond[key][0] for key in self.global_cond_ids], dim=-1) - if len(global_cond.shape) == 3: - global_cond = global_cond.squeeze(1) - - if len(self.input_concat_ids) > 0: - # Concatenate all input concat conditioning inputs over the channel dimension - # Assumes that the input concat conditioning inputs are of shape (batch, channels, seq) - input_concat_cond = torch.cat([cond[key][0] for key in self.input_concat_ids], dim=1) - - if len(self.prepend_cond_ids) > 0: - # Concatenate all prepend conditioning inputs over the sequence dimension - # Assumes that the prepend conditioning inputs are of shape (batch, seq, channels) - prepend_cond = torch.cat([cond[key][0] for key in self.prepend_cond_ids], dim=1) - prepend_cond_mask = torch.cat([cond[key][1] for key in self.prepend_cond_ids], dim=1) - - if negative: - return { - "negative_cross_attn_cond": cross_attention_input, - "negative_cross_attn_mask": cross_attention_masks, - "negative_global_cond": global_cond, - "negative_input_concat_cond": input_concat_cond - } - else: - return { - "cross_attn_cond": cross_attention_input, - "cross_attn_mask": cross_attention_masks, - "global_cond": global_cond, - "input_concat_cond": input_concat_cond, - "prepend_cond": prepend_cond, - "prepend_cond_mask": prepend_cond_mask - } - - def forward(self, x: torch.Tensor, t: torch.Tensor, cond: tp.Dict[str, tp.Any], **kwargs): - # print("Shape of input to model (x):", x.shape) - # print("Shape of time tensor (t):", t.shape) - # print("Shapes of conditioning tensor inputs:", {k: v.shape for k, v in cond.items() if isinstance(v, torch.Tensor)}) - - return self.model(x, t, **self.get_conditioning_inputs(cond), **kwargs) - - def generate(self, *args, **kwargs): - return generate_diffusion_cond(self, *args, **kwargs) - -class UNetCFG1DWrapper(ConditionedDiffusionModel): - def __init__( - self, - *args, - **kwargs - ): - super().__init__(supports_cross_attention=True, supports_global_cond=True, supports_input_concat=True) - - self.model = UNetCFG1d(*args, **kwargs) - - with torch.no_grad(): - for param in self.model.parameters(): - param *= 0.5 - - def forward(self, - x, - t, - cross_attn_cond=None, - cross_attn_mask=None, - input_concat_cond=None, - global_cond=None, - cfg_scale=1.0, - cfg_dropout_prob: float = 0.0, - batch_cfg: bool = False, - rescale_cfg: bool = False, - negative_cross_attn_cond=None, - negative_cross_attn_mask=None, - negative_global_cond=None, - negative_input_concat_cond=None, - prepend_cond=None, - prepend_cond_mask=None, - **kwargs): - p = Profiler() - p.tick("start") - - channels_list = None - if input_concat_cond is not None: - channels_list = [input_concat_cond] - - outputs = self.model( - x, - t, - embedding=cross_attn_cond, - embedding_mask=cross_attn_mask, - features=global_cond, - channels_list=channels_list, - embedding_scale=cfg_scale, - embedding_mask_proba=cfg_dropout_prob, - batch_cfg=batch_cfg, - rescale_cfg=rescale_cfg, - negative_embedding=negative_cross_attn_cond, - negative_embedding_mask=negative_cross_attn_mask, - **kwargs) - - p.tick("UNetCFG1D forward") - #print(f"Profiler: {p}") - return outputs - -class UNet1DCondWrapper(ConditionedDiffusionModel): - def __init__( - self, - *args, - **kwargs - ): - super().__init__(supports_cross_attention=False, supports_global_cond=True, supports_input_concat=True) - - self.model = UNet1d(*args, **kwargs) - - with torch.no_grad(): - for param in self.model.parameters(): - param *= 0.5 - - def forward(self, - x, - t, - input_concat_cond=None, - global_cond=None, - cross_attn_cond=None, - cross_attn_mask=None, - prepend_cond=None, - prepend_cond_mask=None, - cfg_scale=1.0, - cfg_dropout_prob: float = 0.0, - batch_cfg: bool = False, - rescale_cfg: bool = False, - negative_cross_attn_cond=None, - negative_cross_attn_mask=None, - negative_global_cond=None, - negative_input_concat_cond=None, - **kwargs): - - channels_list = None - if input_concat_cond is not None: - - # Interpolate input_concat_cond to the same length as x - if input_concat_cond.shape[2] != x.shape[2]: - input_concat_cond = F.interpolate(input_concat_cond, (x.shape[2], ), mode='nearest') - - channels_list = [input_concat_cond] - - outputs = self.model( - x, - t, - features=global_cond, - channels_list=channels_list, - **kwargs) - - return outputs - -class UNet1DUncondWrapper(DiffusionModel): - def __init__( - self, - in_channels, - *args, - **kwargs - ): - super().__init__() - - self.model = UNet1d(in_channels=in_channels, *args, **kwargs) - - self.io_channels = in_channels - - with torch.no_grad(): - for param in self.model.parameters(): - param *= 0.5 - - def forward(self, x, t, **kwargs): - return self.model(x, t, **kwargs) - -class DAU1DCondWrapper(ConditionedDiffusionModel): - def __init__( - self, - *args, - **kwargs - ): - super().__init__(supports_cross_attention=False, supports_global_cond=False, supports_input_concat=True) - - self.model = DiffusionAttnUnet1D(*args, **kwargs) - - with torch.no_grad(): - for param in self.model.parameters(): - param *= 0.5 - - def forward(self, - x, - t, - input_concat_cond=None, - cross_attn_cond=None, - cross_attn_mask=None, - global_cond=None, - cfg_scale=1.0, - cfg_dropout_prob: float = 0.0, - batch_cfg: bool = False, - rescale_cfg: bool = False, - negative_cross_attn_cond=None, - negative_cross_attn_mask=None, - negative_global_cond=None, - negative_input_concat_cond=None, - prepend_cond=None, - **kwargs): - - return self.model(x, t, cond = input_concat_cond) - -class DiffusionAttnUnet1D(nn.Module): - def __init__( - self, - io_channels = 2, - depth=14, - n_attn_layers = 6, - channels = [128, 128, 256, 256] + [512] * 10, - cond_dim = 0, - cond_noise_aug = False, - kernel_size = 5, - learned_resample = False, - strides = [2] * 13, - conv_bias = True, - use_snake = False - ): - super().__init__() - - self.cond_noise_aug = cond_noise_aug - - self.io_channels = io_channels - - if self.cond_noise_aug: - self.rng = torch.quasirandom.SobolEngine(1, scramble=True) - - self.timestep_embed = FourierFeatures(1, 16) - - attn_layer = depth - n_attn_layers - - strides = [1] + strides - - block = nn.Identity() - - conv_block = partial(ResConvBlock, kernel_size=kernel_size, conv_bias = conv_bias, use_snake=use_snake) - - for i in range(depth, 0, -1): - c = channels[i - 1] - stride = strides[i-1] - if stride > 2 and not learned_resample: - raise ValueError("Must have stride 2 without learned resampling") - - if i > 1: - c_prev = channels[i - 2] - add_attn = i >= attn_layer and n_attn_layers > 0 - block = SkipBlock( - Downsample1d_2(c_prev, c_prev, stride) if (learned_resample or stride == 1) else Downsample1d("cubic"), - conv_block(c_prev, c, c), - SelfAttention1d( - c, c // 32) if add_attn else nn.Identity(), - conv_block(c, c, c), - SelfAttention1d( - c, c // 32) if add_attn else nn.Identity(), - conv_block(c, c, c), - SelfAttention1d( - c, c // 32) if add_attn else nn.Identity(), - block, - conv_block(c * 2 if i != depth else c, c, c), - SelfAttention1d( - c, c // 32) if add_attn else nn.Identity(), - conv_block(c, c, c), - SelfAttention1d( - c, c // 32) if add_attn else nn.Identity(), - conv_block(c, c, c_prev), - SelfAttention1d(c_prev, c_prev // - 32) if add_attn else nn.Identity(), - Upsample1d_2(c_prev, c_prev, stride) if learned_resample else Upsample1d(kernel="cubic") - ) - else: - cond_embed_dim = 16 if not self.cond_noise_aug else 32 - block = nn.Sequential( - conv_block((io_channels + cond_dim) + cond_embed_dim, c, c), - conv_block(c, c, c), - conv_block(c, c, c), - block, - conv_block(c * 2, c, c), - conv_block(c, c, c), - conv_block(c, c, io_channels, is_last=True), - ) - self.net = block - - with torch.no_grad(): - for param in self.net.parameters(): - param *= 0.5 - - def forward(self, x, t, cond=None, cond_aug_scale=None): - - timestep_embed = expand_to_planes(self.timestep_embed(t[:, None]), x.shape) - - inputs = [x, timestep_embed] - - if cond is not None: - if cond.shape[2] != x.shape[2]: - cond = F.interpolate(cond, (x.shape[2], ), mode='linear', align_corners=False) - - if self.cond_noise_aug: - # Get a random number between 0 and 1, uniformly sampled - if cond_aug_scale is None: - aug_level = self.rng.draw(cond.shape[0])[:, 0].to(cond) - else: - aug_level = torch.tensor([cond_aug_scale]).repeat([cond.shape[0]]).to(cond) - - # Add noise to the conditioning signal - cond = cond + torch.randn_like(cond) * aug_level[:, None, None] - - # Get embedding for noise cond level, reusing timestamp_embed - aug_level_embed = expand_to_planes(self.timestep_embed(aug_level[:, None]), x.shape) - - inputs.append(aug_level_embed) - - inputs.append(cond) - - outputs = self.net(torch.cat(inputs, dim=1)) - - return outputs - -class DiTWrapper(ConditionedDiffusionModel): - def __init__( - self, - *args, - **kwargs - ): - super().__init__(supports_cross_attention=True, supports_global_cond=False, supports_input_concat=False) - - self.model = DiffusionTransformer(*args, **kwargs) - - with torch.no_grad(): - for param in self.model.parameters(): - param *= 0.5 - - def forward(self, - x, - t, - cross_attn_cond=None, - cross_attn_mask=None, - negative_cross_attn_cond=None, - negative_cross_attn_mask=None, - input_concat_cond=None, - negative_input_concat_cond=None, - global_cond=None, - negative_global_cond=None, - prepend_cond=None, - prepend_cond_mask=None, - cfg_scale=1.0, - cfg_dropout_prob: float = 0.0, - batch_cfg: bool = True, - rescale_cfg: bool = False, - scale_phi: float = 0.0, - **kwargs): - - assert batch_cfg, "batch_cfg must be True for DiTWrapper" - assert negative_input_concat_cond is None, "negative_input_concat_cond is not supported for DiTWrapper" - assert global_cond is None, "global_cond is not supported for DiTWrapper" - assert negative_global_cond is None, "negative_global_cond is not supported for DiTWrapper" - - return self.model( - x, - t, - cross_attn_cond=cross_attn_cond, - cross_attn_cond_mask=cross_attn_mask, - negative_cross_attn_cond=negative_cross_attn_cond, - negative_cross_attn_mask=negative_cross_attn_mask, - input_concat_cond=input_concat_cond, - prepend_cond=prepend_cond, - prepend_cond_mask=prepend_cond_mask, - cfg_scale=cfg_scale, - cfg_dropout_prob=cfg_dropout_prob, - scale_phi=scale_phi, - **kwargs) - -class DiTUncondWrapper(DiffusionModel): - def __init__( - self, - in_channels, - *args, - **kwargs - ): - super().__init__() - - self.model = DiffusionTransformer(io_channels=in_channels, *args, **kwargs) - - self.io_channels = in_channels - - with torch.no_grad(): - for param in self.model.parameters(): - param *= 0.5 - - def forward(self, x, t, **kwargs): - return self.model(x, t, **kwargs) - -class DiffusionTransformer(nn.Module): - def __init__(self, - io_channels=32, - input_length=512, - embed_dim=768, - cond_token_dim=0, - global_cond_dim=0, - input_concat_dim=0, - prepend_cond_dim=0, - depth=12, - num_heads=8, - transformer_type: tp.Literal["local_attn", "x-transformers"] = "x-transformers", - **kwargs): - - super().__init__() - - self.cond_token_dim = cond_token_dim - - # Timestep embeddings - timestep_features_dim = 256 - - self.timestep_features = FourierFeatures(1, timestep_features_dim) - - self.to_timestep_embed = nn.Sequential( - nn.Linear(timestep_features_dim, embed_dim, bias=True), - nn.SiLU(), - nn.Linear(embed_dim, embed_dim, bias=True), - ) - - if cond_token_dim > 0: - # Conditioning tokens - self.to_cond_embed = nn.Sequential( - nn.Linear(cond_token_dim, embed_dim, bias=False), - nn.SiLU(), - nn.Linear(embed_dim, embed_dim, bias=False) - ) - - if global_cond_dim > 0: - # Global conditioning - self.to_global_embed = nn.Sequential( - nn.Linear(global_cond_dim, embed_dim, bias=False), - nn.SiLU(), - nn.Linear(embed_dim, embed_dim, bias=False) - ) - - if prepend_cond_dim > 0: - # Prepend conditioning - self.to_prepend_embed = nn.Sequential( - nn.Linear(prepend_cond_dim, embed_dim, bias=False), - nn.SiLU(), - nn.Linear(embed_dim, embed_dim, bias=False) - ) - - self.input_concat_dim = input_concat_dim - - dim_in = io_channels + self.input_concat_dim - - # Transformer - - self.transformer_type = transformer_type - - if self.transformer_type == "local_attn": - self.transformer = ContinuousLocalTransformer( - dim=embed_dim, - dim_in=dim_in, - dim_out=io_channels, - depth=depth, - heads=num_heads, - cond_dim=embed_dim if global_cond_dim > 0 else 0, - cross_attn_cond_dim=embed_dim if cond_token_dim > 0 else 0, - **kwargs - ) - - elif self.transformer_type == "x-transformers": - self.transformer = ContinuousTransformerWrapper( - dim_in=dim_in, - dim_out=io_channels, - max_seq_len=0, #Not relevant without absolute positional embeds - attn_layers = Encoder( - dim=embed_dim, - depth=depth, - heads=num_heads, - attn_flash = True, - cross_attend = cond_token_dim > 0, - zero_init_branch_output=True, - use_abs_pos_emb = False, - rotary_pos_emb=True, - ff_swish = True, - ff_glu = True, - **kwargs - ) - ) - else: - raise ValueError(f"Unknown transformer type: {self.transformer_type}") - - self.preprocess_conv = nn.Conv1d(dim_in, dim_in, 1, bias=False) - nn.init.zeros_(self.preprocess_conv.weight) - self.postprocess_conv = nn.Conv1d(io_channels, io_channels, 1, bias=False) - nn.init.zeros_(self.postprocess_conv.weight) - - def _forward( - self, - x, - t, - mask=None, - cross_attn_cond=None, - cross_attn_cond_mask=None, - input_concat_cond=None, - global_embed=None, - prepend_cond=None, - prepend_cond_mask=None, - **kwargs): - - if cross_attn_cond is not None: - cross_attn_cond = self.to_cond_embed(cross_attn_cond) - - # Get the batch of timestep embeddings - timestep_embed = self.to_timestep_embed(self.timestep_features(t[:, None])) # (b, embed_dim) - - # Add a sequence dimension to the timestep embeddings - timestep_embed = timestep_embed.unsqueeze(1) - - prepend_inputs = timestep_embed - - prepend_mask = torch.ones((x.shape[0], 1), device=x.device, dtype=torch.bool) - - if global_embed is not None: - # Project the global conditioning to the embedding dimension - global_embed = self.to_global_embed(global_embed) - - # Add the global conditioning to the timestep embeddings - prepend_inputs = torch.cat([prepend_inputs, global_embed.unsqueeze(2)], dim=2) - - prepend_mask = torch.cat([prepend_mask, torch.ones((x.shape[0], 1), device=x.device, dtype=torch.bool)], dim=1) - - if prepend_cond is not None: - # Project the prepend conditioning to the embedding dimension - prepend_cond = self.to_prepend_embed(prepend_cond) - - # Set up inputs to prepend to transformer inputs - prepend_inputs = torch.cat([prepend_inputs, prepend_cond], dim=1) - - if prepend_cond_mask is not None: - prepend_mask = torch.cat([prepend_mask, prepend_cond_mask], dim=1) - else: - prepend_mask = torch.cat([prepend_mask, torch.ones((x.shape[0], prepend_cond.shape[1]), device=x.device, dtype=torch.bool)], dim=1) - - prepend_length = prepend_inputs.shape[1] - - if input_concat_cond is not None: - - # Interpolate input_concat_cond to the same length as x - if input_concat_cond.shape[2] != x.shape[2]: - input_concat_cond = F.interpolate(input_concat_cond, (x.shape[2], ), mode='nearest') - - x = torch.cat([x, input_concat_cond], dim=1) - - x = self.preprocess_conv(x) + x - - x = rearrange(x, "b c t -> b t c") - - if self.transformer_type == "local_attn": - if mask is not None: - mask = torch.cat([prepend_mask, mask], dim=1) - output = self.transformer(x, prepend_cond=prepend_inputs, cross_attn_cond=cross_attn_cond, cross_attn_cond_mask=cross_attn_cond_mask, mask=mask, **kwargs) - else: - output = self.transformer(x, prepend_embeds=prepend_inputs, context=cross_attn_cond, context_mask=cross_attn_cond_mask, mask=mask, prepend_mask=prepend_mask, **kwargs) - - output = rearrange(output, "b t c -> b c t")[:,:,prepend_length:] - - output = self.postprocess_conv(output) + output - - return output - - def forward( - self, - x, - t, - cross_attn_cond=None, - cross_attn_cond_mask=None, - negative_cross_attn_cond=None, - negative_cross_attn_mask=None, - input_concat_cond=None, - global_embed=None, - prepend_cond=None, - prepend_cond_mask=None, - cfg_scale=1.0, - cfg_dropout_prob=0.0, - causal=False, - scale_phi=0.0, - mask=None, - **kwargs): - - assert causal == False, "Causal mode is not supported for DiffusionTransformer" - - if cross_attn_cond_mask is not None: - cross_attn_cond_mask = cross_attn_cond_mask.bool() - - cross_attn_cond_mask = None # Temporarily disabling conditioning masks due to kernel issue for flash attention - - if prepend_cond_mask is not None: - prepend_cond_mask = prepend_cond_mask.bool() - - # CFG dropout - if cfg_dropout_prob > 0.0: - if cross_attn_cond is not None: - null_embed = torch.zeros_like(cross_attn_cond, device=cross_attn_cond.device) - dropout_mask = torch.bernoulli(torch.full((cross_attn_cond.shape[0], 1, 1), cfg_dropout_prob, device=cross_attn_cond.device)).to(torch.bool) - cross_attn_cond = torch.where(dropout_mask, null_embed, cross_attn_cond) - - if prepend_cond is not None: - null_embed = torch.zeros_like(prepend_cond, device=prepend_cond.device) - dropout_mask = torch.bernoulli(torch.full((prepend_cond.shape[0], 1, 1), cfg_dropout_prob, device=prepend_cond.device)).to(torch.bool) - prepend_cond = torch.where(dropout_mask, null_embed, prepend_cond) - - - if cfg_scale != 1.0 and (cross_attn_cond is not None or prepend_cond is not None): - # Classifier-free guidance - # Concatenate conditioned and unconditioned inputs on the batch dimension - batch_inputs = torch.cat([x, x], dim=0) - batch_timestep = torch.cat([t, t], dim=0) - - if global_embed is not None: - batch_global_cond = torch.cat([global_embed, global_embed], dim=0) - else: - batch_global_cond = None - - if input_concat_cond is not None: - batch_input_concat_cond = torch.cat([input_concat_cond, input_concat_cond], dim=0) - else: - batch_input_concat_cond = None - - batch_cond = None - batch_cond_masks = None - - # Handle CFG for cross-attention conditioning - if cross_attn_cond is not None: - - null_embed = torch.zeros_like(cross_attn_cond, device=cross_attn_cond.device) - - # For negative cross-attention conditioning, replace the null embed with the negative cross-attention conditioning - if negative_cross_attn_cond is not None: - - # If there's a negative cross-attention mask, set the masked tokens to the null embed - if negative_cross_attn_mask is not None: - negative_cross_attn_mask = negative_cross_attn_mask.to(torch.bool).unsqueeze(2) - - negative_cross_attn_cond = torch.where(negative_cross_attn_mask, negative_cross_attn_cond, null_embed) - - batch_cond = torch.cat([cross_attn_cond, negative_cross_attn_cond], dim=0) - - else: - batch_cond = torch.cat([cross_attn_cond, null_embed], dim=0) - - if cross_attn_cond_mask is not None: - batch_cond_masks = torch.cat([cross_attn_cond_mask, cross_attn_cond_mask], dim=0) - - batch_prepend_cond = None - batch_prepend_cond_mask = None - - if prepend_cond is not None: - - null_embed = torch.zeros_like(prepend_cond, device=prepend_cond.device) - - batch_prepend_cond = torch.cat([prepend_cond, null_embed], dim=0) - - if prepend_cond_mask is not None: - batch_prepend_cond_mask = torch.cat([prepend_cond_mask, prepend_cond_mask], dim=0) - - - if mask is not None: - batch_masks = torch.cat([mask, mask], dim=0) - else: - batch_masks = None - - batch_output = self._forward( - batch_inputs, - batch_timestep, - cross_attn_cond=batch_cond, - cross_attn_cond_mask=batch_cond_masks, - mask = batch_masks, - input_concat_cond=batch_input_concat_cond, - global_embed = batch_global_cond, - prepend_cond = batch_prepend_cond, - prepend_cond_mask = batch_prepend_cond_mask, - **kwargs) - - cond_output, uncond_output = torch.chunk(batch_output, 2, dim=0) - cfg_output = uncond_output + (cond_output - uncond_output) * cfg_scale - - if scale_phi != 0.0: - - cond_out_std = cond_output.std(dim=1, keepdim=True) - out_cfg_std = cfg_output.std(dim=1, keepdim=True) - - return scale_phi * (cfg_output * (cond_out_std/out_cfg_std)) + (1-scale_phi) * cfg_output - - else: - - return cfg_output - - else: - return self._forward( - x, - t, - cross_attn_cond=cross_attn_cond, - cross_attn_cond_mask=cross_attn_cond_mask, - input_concat_cond=input_concat_cond, - global_embed=global_embed, - prepend_cond=prepend_cond, - prepend_cond_mask=prepend_cond_mask, - mask=mask, - **kwargs - ) - -def create_diffusion_uncond_from_config(config: tp.Dict[str, tp.Any]): - diffusion_uncond_config = config["model"] - - model_type = diffusion_uncond_config.get('type', None) - - diffusion_config = diffusion_uncond_config.get('config', {}) - - assert model_type is not None, "Must specify model type in config" - - pretransform = diffusion_uncond_config.get("pretransform", None) - - sample_size = config.get("sample_size", None) - assert sample_size is not None, "Must specify sample size in config" - - sample_rate = config.get("sample_rate", None) - assert sample_rate is not None, "Must specify sample rate in config" - - if pretransform is not None: - pretransform = create_pretransform_from_config(pretransform, sample_rate) - min_input_length = pretransform.downsampling_ratio - else: - min_input_length = 1 - - if model_type == 'DAU1d': - - model = DiffusionAttnUnet1D( - **diffusion_config - ) - - - - elif model_type == "adp_uncond_1d": - - model = UNet1DUncondWrapper( - **diffusion_config - ) - - elif model_type == "dit": - model = DiTUncondWrapper( - **diffusion_config - ) - - else: - raise NotImplementedError(f'Unknown model type: {model_type}') - - return DiffusionModelWrapper(model, - io_channels=model.io_channels, - sample_size=sample_size, - sample_rate=sample_rate, - pretransform=pretransform, - min_input_length=min_input_length) - -def create_diffusion_cond_from_config(config: tp.Dict[str, tp.Any]): - - model_config = config["model"] - - diffusion_config = model_config.get('diffusion', None) - assert diffusion_config is not None, "Must specify diffusion config" - - diffusion_model_type = diffusion_config.get('type', None) - assert diffusion_model_type is not None, "Must specify diffusion model type" - - diffusion_model_config = diffusion_config.get('config', None) - assert diffusion_model_config is not None, "Must specify diffusion model config" - - if diffusion_model_type == 'adp_cfg_1d': - diffusion_model = UNetCFG1DWrapper(**diffusion_model_config) - elif diffusion_model_type == 'adp_1d': - diffusion_model = UNet1DCondWrapper(**diffusion_model_config) - elif diffusion_model_type == 'dit': - diffusion_model = DiTWrapper(**diffusion_model_config) - - io_channels = model_config.get('io_channels', None) - assert io_channels is not None, "Must specify io_channels in model config" - - sample_rate = config.get('sample_rate', None) - assert sample_rate is not None, "Must specify sample_rate in config" - - conditioning_config = model_config.get('conditioning', None) - - conditioner = None - if conditioning_config is not None: - conditioner = create_multi_conditioner_from_conditioning_config(conditioning_config) - - cross_attention_ids = diffusion_config.get('cross_attention_cond_ids', []) - global_cond_ids = diffusion_config.get('global_cond_ids', []) - input_concat_ids = diffusion_config.get('input_concat_ids', []) - prepend_cond_ids = diffusion_config.get('prepend_cond_ids', []) - - pretransform = model_config.get("pretransform", None) - - if pretransform is not None: - pretransform = create_pretransform_from_config(pretransform, sample_rate) - min_input_length = pretransform.downsampling_ratio - else: - min_input_length = 1 - - if diffusion_model_type == "adp_cfg_1d" or diffusion_model_type == "adp_1d": - min_input_length *= np.prod(diffusion_model_config["factors"]) - elif diffusion_model_type == "dit": - min_input_length = min_input_length # There's no downsampling in DiT - - return ConditionedDiffusionModelWrapper( - diffusion_model, - conditioner, - min_input_length=min_input_length, - sample_rate=sample_rate, - cross_attn_cond_ids=cross_attention_ids, - global_cond_ids=global_cond_ids, - input_concat_ids=input_concat_ids, - prepend_cond_ids=prepend_cond_ids, - pretransform=pretransform, - io_channels=io_channels - ) \ No newline at end of file diff --git a/sonique/stable_audio_tools/models/discriminators.py b/sonique/stable_audio_tools/models/discriminators.py deleted file mode 100644 index b593168df965bb1f57881ea79edbc2f66478c6c2..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/models/discriminators.py +++ /dev/null @@ -1,546 +0,0 @@ -import torch -import torch.nn as nn -import torch.nn.functional as F -import numpy as np -from functools import reduce -import typing as tp -from einops import rearrange -from audiotools import AudioSignal, STFTParams -from dac.model.discriminator import WNConv1d, WNConv2d - -def get_hinge_losses(score_real, score_fake): - gen_loss = -score_fake.mean() - dis_loss = torch.relu(1 - score_real).mean() + torch.relu(1 + score_fake).mean() - return dis_loss, gen_loss - -class EncodecDiscriminator(nn.Module): - - def __init__(self, *args, **kwargs): - super().__init__() - - from encodec.msstftd import MultiScaleSTFTDiscriminator - - self.discriminators = MultiScaleSTFTDiscriminator(*args, **kwargs) - - def forward(self, x): - logits, features = self.discriminators(x) - return logits, features - - def loss(self, x, y): - feature_matching_distance = 0. - logits_true, feature_true = self.forward(x) - logits_fake, feature_fake = self.forward(y) - - dis_loss = torch.tensor(0.) - adv_loss = torch.tensor(0.) - - for i, (scale_true, scale_fake) in enumerate(zip(feature_true, feature_fake)): - - feature_matching_distance = feature_matching_distance + sum( - map( - lambda x, y: abs(x - y).mean(), - scale_true, - scale_fake, - )) / len(scale_true) - - _dis, _adv = get_hinge_losses( - logits_true[i], - logits_fake[i], - ) - - dis_loss = dis_loss + _dis - adv_loss = adv_loss + _adv - - return dis_loss, adv_loss, feature_matching_distance - -# Discriminators from oobleck - -IndividualDiscriminatorOut = tp.Tuple[torch.Tensor, tp.Sequence[torch.Tensor]] - -TensorDict = tp.Dict[str, torch.Tensor] - -class SharedDiscriminatorConvNet(nn.Module): - - def __init__( - self, - in_size: int, - convolution: tp.Union[nn.Conv1d, nn.Conv2d], - out_size: int = 1, - capacity: int = 32, - n_layers: int = 4, - kernel_size: int = 15, - stride: int = 4, - activation: tp.Callable[[], nn.Module] = lambda: nn.SiLU(), - normalization: tp.Callable[[nn.Module], nn.Module] = torch.nn.utils.weight_norm, - ) -> None: - super().__init__() - channels = [in_size] - channels += list(capacity * 2**np.arange(n_layers)) - - if isinstance(stride, int): - stride = n_layers * [stride] - - net = [] - for i in range(n_layers): - if isinstance(kernel_size, int): - pad = kernel_size // 2 - s = stride[i] - else: - pad = kernel_size[0] // 2 - s = (stride[i], 1) - - net.append( - normalization( - convolution( - channels[i], - channels[i + 1], - kernel_size, - stride=s, - padding=pad, - ))) - net.append(activation()) - - net.append(convolution(channels[-1], out_size, 1)) - - self.net = nn.ModuleList(net) - - def forward(self, x) -> IndividualDiscriminatorOut: - features = [] - for layer in self.net: - x = layer(x) - if isinstance(layer, nn.modules.conv._ConvNd): - features.append(x) - score = x.reshape(x.shape[0], -1).mean(-1) - return score, features - - -class MultiScaleDiscriminator(nn.Module): - - def __init__(self, - in_channels: int, - n_scales: int, - **conv_kwargs) -> None: - super().__init__() - layers = [] - for _ in range(n_scales): - layers.append(SharedDiscriminatorConvNet(in_channels, nn.Conv1d, **conv_kwargs)) - self.layers = nn.ModuleList(layers) - - def forward(self, x: torch.Tensor) -> IndividualDiscriminatorOut: - score = 0 - features = [] - for layer in self.layers: - s, f = layer(x) - score = score + s - features.extend(f) - x = nn.functional.avg_pool1d(x, 2) - return score, features - -class MultiPeriodDiscriminator(nn.Module): - - def __init__(self, - in_channels: int, - periods: tp.Sequence[int], - **conv_kwargs) -> None: - super().__init__() - layers = [] - self.periods = periods - - for _ in periods: - layers.append(SharedDiscriminatorConvNet(in_channels, nn.Conv2d, **conv_kwargs)) - - self.layers = nn.ModuleList(layers) - - def forward(self, x: torch.Tensor) -> IndividualDiscriminatorOut: - score = 0 - features = [] - for layer, n in zip(self.layers, self.periods): - s, f = layer(self.fold(x, n)) - score = score + s - features.extend(f) - return score, features - - def fold(self, x: torch.Tensor, n: int) -> torch.Tensor: - pad = (n - (x.shape[-1] % n)) % n - x = nn.functional.pad(x, (0, pad)) - return x.reshape(*x.shape[:2], -1, n) - - -class MultiDiscriminator(nn.Module): - """ - Individual discriminators should take a single tensor as input (NxB C T) and - return a tuple composed of a score tensor (NxB) and a Sequence of Features - Sequence[NxB C' T']. - """ - - def __init__(self, discriminator_list: tp.Sequence[nn.Module], - keys: tp.Sequence[str]) -> None: - super().__init__() - self.discriminators = nn.ModuleList(discriminator_list) - self.keys = keys - - def unpack_tensor_to_dict(self, features: torch.Tensor) -> TensorDict: - features = features.chunk(len(self.keys), 0) - return {k: features[i] for i, k in enumerate(self.keys)} - - @staticmethod - def concat_dicts(dict_a, dict_b): - out_dict = {} - keys = set(list(dict_a.keys()) + list(dict_b.keys())) - for k in keys: - out_dict[k] = [] - if k in dict_a: - if isinstance(dict_a[k], list): - out_dict[k].extend(dict_a[k]) - else: - out_dict[k].append(dict_a[k]) - if k in dict_b: - if isinstance(dict_b[k], list): - out_dict[k].extend(dict_b[k]) - else: - out_dict[k].append(dict_b[k]) - return out_dict - - @staticmethod - def sum_dicts(dict_a, dict_b): - out_dict = {} - keys = set(list(dict_a.keys()) + list(dict_b.keys())) - for k in keys: - out_dict[k] = 0. - if k in dict_a: - out_dict[k] = out_dict[k] + dict_a[k] - if k in dict_b: - out_dict[k] = out_dict[k] + dict_b[k] - return out_dict - - def forward(self, inputs: TensorDict) -> TensorDict: - discriminator_input = torch.cat([inputs[k] for k in self.keys], 0) - all_scores = [] - all_features = [] - - for discriminator in self.discriminators: - score, features = discriminator(discriminator_input) - scores = self.unpack_tensor_to_dict(score) - scores = {f"score_{k}": scores[k] for k in scores.keys()} - all_scores.append(scores) - - features = map(self.unpack_tensor_to_dict, features) - features = reduce(self.concat_dicts, features) - features = {f"features_{k}": features[k] for k in features.keys()} - all_features.append(features) - - all_scores = reduce(self.sum_dicts, all_scores) - all_features = reduce(self.concat_dicts, all_features) - - inputs.update(all_scores) - inputs.update(all_features) - - return inputs - -class OobleckDiscriminator(nn.Module): - - def __init__( - self, - in_channels=1, - ): - super().__init__() - - multi_scale_discriminator = MultiScaleDiscriminator( - in_channels=in_channels, - n_scales=3, - ) - - multi_period_discriminator = MultiPeriodDiscriminator( - in_channels=in_channels, - periods=[2, 3, 5, 7, 11] - ) - - # multi_resolution_discriminator = MultiScaleSTFTDiscriminator( - # filters=32, - # in_channels = in_channels, - # out_channels = 1, - # n_ffts = [2048, 1024, 512, 256, 128], - # hop_lengths = [512, 256, 128, 64, 32], - # win_lengths = [2048, 1024, 512, 256, 128] - # ) - - self.multi_discriminator = MultiDiscriminator( - [multi_scale_discriminator, multi_period_discriminator], #, multi_resolution_discriminator], - ["reals", "fakes"] - ) - - def loss(self, reals, fakes): - inputs = { - "reals": reals, - "fakes": fakes, - } - - inputs = self.multi_discriminator(inputs) - - scores_real = inputs["score_reals"] - scores_fake = inputs["score_fakes"] - - features_real = inputs["features_reals"] - features_fake = inputs["features_fakes"] - - dis_loss, gen_loss = get_hinge_losses(scores_real, scores_fake) - - feature_matching_distance = torch.tensor(0.) - - for _, (scale_real, scale_fake) in enumerate(zip(features_real, features_fake)): - - feature_matching_distance = feature_matching_distance + sum( - map( - lambda real, fake: abs(real - fake).mean(), - scale_real, - scale_fake, - )) / len(scale_real) - - return dis_loss, gen_loss, feature_matching_distance - - -## Discriminators from Descript Audio Codec repo -## Copied and modified under MIT license, see LICENSES/LICENSE_DESCRIPT.txt -class MPD(nn.Module): - def __init__(self, period, channels=1): - super().__init__() - - self.period = period - self.convs = nn.ModuleList( - [ - WNConv2d(channels, 32, (5, 1), (3, 1), padding=(2, 0)), - WNConv2d(32, 128, (5, 1), (3, 1), padding=(2, 0)), - WNConv2d(128, 512, (5, 1), (3, 1), padding=(2, 0)), - WNConv2d(512, 1024, (5, 1), (3, 1), padding=(2, 0)), - WNConv2d(1024, 1024, (5, 1), 1, padding=(2, 0)), - ] - ) - self.conv_post = WNConv2d( - 1024, 1, kernel_size=(3, 1), padding=(1, 0), act=False - ) - - def pad_to_period(self, x): - t = x.shape[-1] - x = F.pad(x, (0, self.period - t % self.period), mode="reflect") - return x - - def forward(self, x): - fmap = [] - - x = self.pad_to_period(x) - x = rearrange(x, "b c (l p) -> b c l p", p=self.period) - - for layer in self.convs: - x = layer(x) - fmap.append(x) - - x = self.conv_post(x) - fmap.append(x) - - return fmap - - -class MSD(nn.Module): - def __init__(self, rate: int = 1, sample_rate: int = 44100, channels=1): - super().__init__() - - self.convs = nn.ModuleList( - [ - WNConv1d(channels, 16, 15, 1, padding=7), - WNConv1d(16, 64, 41, 4, groups=4, padding=20), - WNConv1d(64, 256, 41, 4, groups=16, padding=20), - WNConv1d(256, 1024, 41, 4, groups=64, padding=20), - WNConv1d(1024, 1024, 41, 4, groups=256, padding=20), - WNConv1d(1024, 1024, 5, 1, padding=2), - ] - ) - self.conv_post = WNConv1d(1024, 1, 3, 1, padding=1, act=False) - self.sample_rate = sample_rate - self.rate = rate - - def forward(self, x): - x = AudioSignal(x, self.sample_rate) - x.resample(self.sample_rate // self.rate) - x = x.audio_data - - fmap = [] - - for l in self.convs: - x = l(x) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - - return fmap - - -BANDS = [(0.0, 0.1), (0.1, 0.25), (0.25, 0.5), (0.5, 0.75), (0.75, 1.0)] - - -class MRD(nn.Module): - def __init__( - self, - window_length: int, - hop_factor: float = 0.25, - sample_rate: int = 44100, - bands: list = BANDS, - channels: int = 1 - ): - """Complex multi-band spectrogram discriminator. - Parameters - ---------- - window_length : int - Window length of STFT. - hop_factor : float, optional - Hop factor of the STFT, defaults to ``0.25 * window_length``. - sample_rate : int, optional - Sampling rate of audio in Hz, by default 44100 - bands : list, optional - Bands to run discriminator over. - """ - super().__init__() - - self.window_length = window_length - self.hop_factor = hop_factor - self.sample_rate = sample_rate - self.stft_params = STFTParams( - window_length=window_length, - hop_length=int(window_length * hop_factor), - match_stride=True, - ) - - self.channels = channels - - n_fft = window_length // 2 + 1 - bands = [(int(b[0] * n_fft), int(b[1] * n_fft)) for b in bands] - self.bands = bands - - ch = 32 - convs = lambda: nn.ModuleList( - [ - WNConv2d(2, ch, (3, 9), (1, 1), padding=(1, 4)), - WNConv2d(ch, ch, (3, 9), (1, 2), padding=(1, 4)), - WNConv2d(ch, ch, (3, 9), (1, 2), padding=(1, 4)), - WNConv2d(ch, ch, (3, 9), (1, 2), padding=(1, 4)), - WNConv2d(ch, ch, (3, 3), (1, 1), padding=(1, 1)), - ] - ) - self.band_convs = nn.ModuleList([convs() for _ in range(len(self.bands))]) - self.conv_post = WNConv2d(ch, 1, (3, 3), (1, 1), padding=(1, 1), act=False) - - def spectrogram(self, x): - x = AudioSignal(x, self.sample_rate, stft_params=self.stft_params) - x = torch.view_as_real(x.stft()) - x = rearrange(x, "b ch f t c -> (b ch) c t f", ch=self.channels) - # Split into bands - x_bands = [x[..., b[0] : b[1]] for b in self.bands] - return x_bands - - def forward(self, x): - x_bands = self.spectrogram(x) - fmap = [] - - x = [] - for band, stack in zip(x_bands, self.band_convs): - for layer in stack: - band = layer(band) - fmap.append(band) - x.append(band) - - x = torch.cat(x, dim=-1) - x = self.conv_post(x) - fmap.append(x) - - return fmap - - -class DACDiscriminator(nn.Module): - def __init__( - self, - channels: int = 1, - rates: list = [], - periods: list = [2, 3, 5, 7, 11], - fft_sizes: list = [2048, 1024, 512], - sample_rate: int = 44100, - bands: list = BANDS, - ): - """Discriminator that combines multiple discriminators. - - Parameters - ---------- - rates : list, optional - sampling rates (in Hz) to run MSD at, by default [] - If empty, MSD is not used. - periods : list, optional - periods (of samples) to run MPD at, by default [2, 3, 5, 7, 11] - fft_sizes : list, optional - Window sizes of the FFT to run MRD at, by default [2048, 1024, 512] - sample_rate : int, optional - Sampling rate of audio in Hz, by default 44100 - bands : list, optional - Bands to run MRD at, by default `BANDS` - """ - super().__init__() - discs = [] - discs += [MPD(p, channels=channels) for p in periods] - discs += [MSD(r, sample_rate=sample_rate, channels=channels) for r in rates] - discs += [MRD(f, sample_rate=sample_rate, bands=bands, channels=channels) for f in fft_sizes] - self.discriminators = nn.ModuleList(discs) - - def preprocess(self, y): - # Remove DC offset - y = y - y.mean(dim=-1, keepdims=True) - # Peak normalize the volume of input audio - y = 0.8 * y / (y.abs().max(dim=-1, keepdim=True)[0] + 1e-9) - return y - - def forward(self, x): - x = self.preprocess(x) - fmaps = [d(x) for d in self.discriminators] - return fmaps - -class DACGANLoss(nn.Module): - """ - Computes a discriminator loss, given a discriminator on - generated waveforms/spectrograms compared to ground truth - waveforms/spectrograms. Computes the loss for both the - discriminator and the generator in separate functions. - """ - - def __init__(self, **discriminator_kwargs): - super().__init__() - self.discriminator = DACDiscriminator(**discriminator_kwargs) - - def forward(self, fake, real): - d_fake = self.discriminator(fake) - d_real = self.discriminator(real) - return d_fake, d_real - - def discriminator_loss(self, fake, real): - d_fake, d_real = self.forward(fake.clone().detach(), real) - - loss_d = 0 - for x_fake, x_real in zip(d_fake, d_real): - loss_d += torch.mean(x_fake[-1] ** 2) - loss_d += torch.mean((1 - x_real[-1]) ** 2) - return loss_d - - def generator_loss(self, fake, real): - d_fake, d_real = self.forward(fake, real) - - loss_g = 0 - for x_fake in d_fake: - loss_g += torch.mean((1 - x_fake[-1]) ** 2) - - loss_feature = 0 - - for i in range(len(d_fake)): - for j in range(len(d_fake[i]) - 1): - loss_feature += F.l1_loss(d_fake[i][j], d_real[i][j].detach()) - return loss_g, loss_feature - - def loss(self, fake, real): - gen_loss, feature_distance = self.generator_loss(fake, real) - dis_loss = self.discriminator_loss(fake, real) - - return dis_loss, gen_loss, feature_distance \ No newline at end of file diff --git a/sonique/stable_audio_tools/models/factory.py b/sonique/stable_audio_tools/models/factory.py deleted file mode 100644 index 36db64d6acae94648c6e0e17ebc278a3d7742b22..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/models/factory.py +++ /dev/null @@ -1,141 +0,0 @@ -import json - -def create_model_from_config(model_config): - model_type = model_config.get('model_type', None) - - assert model_type is not None, 'model_type must be specified in model config' - - if model_type == 'autoencoder': - from .autoencoders import create_autoencoder_from_config - return create_autoencoder_from_config(model_config) - elif model_type == 'diffusion_uncond': - from .diffusion import create_diffusion_uncond_from_config - return create_diffusion_uncond_from_config(model_config) - elif model_type == 'diffusion_cond' or model_type == 'diffusion_cond_inpaint' or model_type == "diffusion_prior": - from .diffusion import create_diffusion_cond_from_config - return create_diffusion_cond_from_config(model_config) - elif model_type == 'diffusion_autoencoder': - from .autoencoders import create_diffAE_from_config - return create_diffAE_from_config(model_config) - elif model_type == 'musicgen': - from .musicgen import create_musicgen_from_config - return create_musicgen_from_config(model_config) - else: - raise NotImplementedError(f'Unknown model type: {model_type}') - -def create_model_from_config_path(model_config_path): - with open(model_config_path) as f: - model_config = json.load(f) - - return create_model_from_config(model_config) - -def create_pretransform_from_config(pretransform_config, sample_rate): - pretransform_type = pretransform_config.get('type', None) - - assert pretransform_type is not None, 'type must be specified in pretransform config' - - if pretransform_type == 'autoencoder': - from .autoencoders import create_autoencoder_from_config - from .pretransforms import AutoencoderPretransform - - # Create fake top-level config to pass sample rate to autoencoder constructor - # This is a bit of a hack but it keeps us from re-defining the sample rate in the config - autoencoder_config = {"sample_rate": sample_rate, "model": pretransform_config["config"]} - # print(f'autoencoder build with config: {autoencoder_config}') - autoencoder = create_autoencoder_from_config(autoencoder_config) - - scale = pretransform_config.get("scale", 1.0) - model_half = pretransform_config.get("model_half", False) - iterate_batch = pretransform_config.get("iterate_batch", False) - - pretransform = AutoencoderPretransform(autoencoder, scale=scale, model_half=model_half, iterate_batch=iterate_batch) - elif pretransform_type == 'wavelet': - from .pretransforms import WaveletPretransform - - wavelet_config = pretransform_config["config"] - channels = wavelet_config["channels"] - levels = wavelet_config["levels"] - wavelet = wavelet_config["wavelet"] - - pretransform = WaveletPretransform(channels, levels, wavelet) - elif pretransform_type == 'pqmf': - from .pretransforms import PQMFPretransform - pqmf_config = pretransform_config["config"] - pretransform = PQMFPretransform(**pqmf_config) - elif pretransform_type == 'dac_pretrained': - from .pretransforms import PretrainedDACPretransform - pretrained_dac_config = pretransform_config["config"] - pretransform = PretrainedDACPretransform(**pretrained_dac_config) - else: - raise NotImplementedError(f'Unknown pretransform type: {pretransform_type}') - - enable_grad = pretransform_config.get('enable_grad', False) - pretransform.enable_grad = enable_grad - - pretransform.eval().requires_grad_(pretransform.enable_grad) - - return pretransform - -def create_bottleneck_from_config(bottleneck_config): - bottleneck_type = bottleneck_config.get('type', None) - - assert bottleneck_type is not None, 'type must be specified in bottleneck config' - - if bottleneck_type == 'tanh': - from .bottleneck import TanhBottleneck - return TanhBottleneck() - elif bottleneck_type == 'vae': - from .bottleneck import VAEBottleneck - return VAEBottleneck() - elif bottleneck_type == 'rvq': - from .bottleneck import RVQBottleneck - - quantizer_params = { - "dim": 128, - "codebook_size": 1024, - "num_quantizers": 8, - "decay": 0.99, - "kmeans_init": True, - "kmeans_iters": 50, - "threshold_ema_dead_code": 2, - } - - quantizer_params.update(bottleneck_config["config"]) - - return RVQBottleneck(**quantizer_params) - elif bottleneck_type == "dac_rvq": - from .bottleneck import DACRVQBottleneck - - return DACRVQBottleneck(**bottleneck_config["config"]) - - elif bottleneck_type == 'rvq_vae': - from .bottleneck import RVQVAEBottleneck - - quantizer_params = { - "dim": 128, - "codebook_size": 1024, - "num_quantizers": 8, - "decay": 0.99, - "kmeans_init": True, - "kmeans_iters": 50, - "threshold_ema_dead_code": 2, - } - - quantizer_params.update(bottleneck_config["config"]) - - return RVQVAEBottleneck(**quantizer_params) - - elif bottleneck_type == 'dac_rvq_vae': - from .bottleneck import DACRVQVAEBottleneck - return DACRVQVAEBottleneck(**bottleneck_config["config"]) - elif bottleneck_type == 'l2_norm': - from .bottleneck import L2Bottleneck - return L2Bottleneck() - elif bottleneck_type == "wasserstein": - from .bottleneck import WassersteinBottleneck - return WassersteinBottleneck(**bottleneck_config.get("config", {})) - elif bottleneck_type == "fsq": - from .bottleneck import FSQBottleneck - return FSQBottleneck(**bottleneck_config["config"]) - else: - raise NotImplementedError(f'Unknown bottleneck type: {bottleneck_type}') diff --git a/sonique/stable_audio_tools/models/local_attention.py b/sonique/stable_audio_tools/models/local_attention.py deleted file mode 100644 index db6a07db5fa5f82e237408a6abf9dc95138fe8b2..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/models/local_attention.py +++ /dev/null @@ -1,292 +0,0 @@ -import torch - -from einops import rearrange -from torch import nn -from local_attention.transformer import LocalMHA, FeedForward - -from .adp import Attention -from .blocks import AdaRMSNorm - -# Adapted from https://github.com/lucidrains/local-attention/blob/master/local_attention/transformer.py -class ContinuousLocalTransformer(nn.Module): - def __init__( - self, - *, - dim, - depth, - dim_in = None, - dim_out = None, - causal = False, - local_attn_window_size = 64, - heads = 8, - ff_mult = 4, - attn_dropout = 0., - ff_dropout = 0., - use_conv = True, - cond_dim = 0, - cross_attn_cond_dim = 0, - use_rotary_pos_emb = False, - **kwargs - ): - super().__init__() - - dim_head = dim//heads - - qk_scale = dim_head ** 0.5 - - self.layers = nn.ModuleList([]) - - self.project_in = nn.Linear(dim_in, dim) if dim_in is not None else nn.Identity() - - self.project_out = nn.Linear(dim, dim_out) if dim_out is not None else nn.Identity() - - self.local_attn_window_size = local_attn_window_size - - self.use_conv = use_conv - - self.cond_dim = cond_dim - - self.cross_attn_cond_dim = cross_attn_cond_dim - - for _ in range(depth): - - self.layers.append(nn.ModuleList([ - AdaRMSNorm(dim, cond_dim, eps=1e-8) if cond_dim > 0 else nn.LayerNorm(dim, eps=1e-8), - LocalMHA( - dim = dim, - dim_head = dim_head, - heads = heads, - qk_scale=qk_scale, - dropout = attn_dropout, - causal = causal, - window_size = local_attn_window_size, - prenorm = False, - use_rotary_pos_emb = use_rotary_pos_emb, - **kwargs), - Attention(features=dim, num_heads=heads, head_features=dim_head, context_features=self.cross_attn_cond_dim) if self.cross_attn_cond_dim > 0 else nn.Identity(), - nn.Conv1d(dim, dim, kernel_size=3, padding=1) if use_conv else nn.Identity(), - FeedForward(dim = dim, mult = ff_mult, dropout = ff_dropout) - ])) - - def forward(self, x, mask = None, cond = None, cross_attn_cond = None, cross_attn_cond_mask = None, prepend_cond = None): - - x = self.project_in(x) - - if prepend_cond is not None: - x = torch.cat([prepend_cond, x], dim=1) - - for norm, attn, xattn, conv, ff in self.layers: - - if cond is not None: - x = norm(x, cond) - else: - x = norm(x) - - x = attn(x, mask = mask) + x - - if cross_attn_cond is not None: - x = xattn(x, context=cross_attn_cond, context_mask=cross_attn_cond_mask) + x - - if self.use_conv: - x = rearrange(x, "b n c -> b c n") - x = conv(x) + x - x = rearrange(x, "b c n -> b n c") - - x = ff(x) + x - - return self.project_out(x) - - -class TransformerDownsampleBlock1D(nn.Module): - def __init__( - self, - in_channels, - embed_dim = 768, - depth = 3, - heads = 12, - downsample_ratio = 2, - local_attn_window_size = 64, - use_conv = True, - **kwargs - ): - super().__init__() - - self.downsample_ratio = downsample_ratio - - self.transformer = ContinuousLocalTransformer( - dim=embed_dim, - depth=depth, - heads=heads, - local_attn_window_size=local_attn_window_size, - use_conv=use_conv, - **kwargs - ) - - self.project_in = nn.Linear(in_channels, embed_dim) if in_channels != embed_dim else nn.Identity() - - self.project_down = nn.Sequential( - nn.Linear(embed_dim * self.downsample_ratio, embed_dim, bias=False), - nn.SiLU(), - nn.Linear(embed_dim, embed_dim, bias=False) - ) - - def forward(self, x): - - x = self.project_in(x) - - # Compute - x = self.transformer(x) - - # Trade sequence length for channels - x = rearrange(x, "b (n r) c -> b n (c r)", r=self.downsample_ratio) - - # Project back to embed dim - x = self.project_down(x) - - return x - -class TransformerUpsampleBlock1D(nn.Module): - def __init__( - self, - in_channels, - embed_dim, - depth = 3, - heads = 12, - upsample_ratio = 2, - local_attn_window_size = 64, - use_conv = True, - **kwargs - ): - super().__init__() - - self.upsample_ratio = upsample_ratio - - self.transformer = ContinuousLocalTransformer( - dim=embed_dim, - depth=depth, - heads=heads, - local_attn_window_size = local_attn_window_size, - use_conv=use_conv, - **kwargs - ) - - self.project_in = nn.Linear(in_channels, embed_dim) if in_channels != embed_dim else nn.Identity() - - self.project_up = nn.Sequential( - nn.Linear(embed_dim, embed_dim * self.upsample_ratio, bias=False), - nn.SiLU(), - nn.Linear(embed_dim * self.upsample_ratio, embed_dim * self.upsample_ratio, bias=False) - ) - - - def forward(self, x): - - # Project to embed dim - x = self.project_in(x) - - # Project to increase channel dim - x = self.project_up(x) - - # Trade channels for sequence length - x = rearrange(x, "b n (c r) -> b (n r) c", r=self.upsample_ratio) - - # Compute - x = self.transformer(x) - - return x - - -class TransformerEncoder1D(nn.Module): - def __init__( - self, - in_channels, - out_channels, - embed_dims = [96, 192, 384, 768], - heads = [12, 12, 12, 12], - depths = [3, 3, 3, 3], - ratios = [2, 2, 2, 2], - local_attn_window_size = 64, - use_conv = True, - **kwargs - ): - super().__init__() - - layers = [] - - for layer in range(len(depths)): - prev_dim = embed_dims[layer - 1] if layer > 0 else embed_dims[0] - - layers.append( - TransformerDownsampleBlock1D( - in_channels = prev_dim, - embed_dim = embed_dims[layer], - heads = heads[layer], - depth = depths[layer], - downsample_ratio = ratios[layer], - local_attn_window_size = local_attn_window_size, - use_conv = use_conv, - **kwargs - ) - ) - - self.layers = nn.Sequential(*layers) - - self.project_in = nn.Linear(in_channels, embed_dims[0]) - self.project_out = nn.Linear(embed_dims[-1], out_channels) - - def forward(self, x): - x = rearrange(x, "b c n -> b n c") - x = self.project_in(x) - x = self.layers(x) - x = self.project_out(x) - x = rearrange(x, "b n c -> b c n") - - return x - - -class TransformerDecoder1D(nn.Module): - def __init__( - self, - in_channels, - out_channels, - embed_dims = [768, 384, 192, 96], - heads = [12, 12, 12, 12], - depths = [3, 3, 3, 3], - ratios = [2, 2, 2, 2], - local_attn_window_size = 64, - use_conv = True, - **kwargs - ): - - super().__init__() - - layers = [] - - for layer in range(len(depths)): - prev_dim = embed_dims[layer - 1] if layer > 0 else embed_dims[0] - - layers.append( - TransformerUpsampleBlock1D( - in_channels = prev_dim, - embed_dim = embed_dims[layer], - heads = heads[layer], - depth = depths[layer], - upsample_ratio = ratios[layer], - local_attn_window_size = local_attn_window_size, - use_conv = use_conv, - **kwargs - ) - ) - - self.layers = nn.Sequential(*layers) - - self.project_in = nn.Linear(in_channels, embed_dims[0]) - self.project_out = nn.Linear(embed_dims[-1], out_channels) - - def forward(self, x): - x = rearrange(x, "b c n -> b n c") - x = self.project_in(x) - x = self.layers(x) - x = self.project_out(x) - x = rearrange(x, "b n c -> b c n") - return x \ No newline at end of file diff --git a/sonique/stable_audio_tools/models/musicgen.py b/sonique/stable_audio_tools/models/musicgen.py deleted file mode 100644 index 0454fe2de4e09e670b636294cb3502ec6400a678..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/models/musicgen.py +++ /dev/null @@ -1,161 +0,0 @@ -import torch -import typing as tp -from audiocraft.models import MusicGen, CompressionModel, LMModel -import audiocraft.quantization as qt -from .autoencoders import AudioAutoencoder -from .bottleneck import DACRVQBottleneck, DACRVQVAEBottleneck - -from audiocraft.modules.codebooks_patterns import ( - DelayedPatternProvider, - MusicLMPattern, - ParallelPatternProvider, - UnrolledPatternProvider, - VALLEPattern, -) - -from audiocraft.modules.conditioners import ( - ConditionFuser, - ConditioningProvider, - T5Conditioner, -) - -def create_musicgen_from_config(config): - model_config = config.get('model', None) - assert model_config is not None, 'model config must be specified in config' - - if model_config.get("pretrained", False): - model = MusicGen.get_pretrained(model_config["pretrained"], device="cpu") - - if model_config.get("reinit_lm", False): - model.lm._init_weights("gaussian", "current", True) - - return model - - # Create MusicGen model from scratch - compression_config = model_config.get('compression', None) - assert compression_config is not None, 'compression config must be specified in model config' - - compression_type = compression_config.get('type', None) - assert compression_type is not None, 'type must be specified in compression config' - - if compression_type == 'pretrained': - compression_model = CompressionModel.get_pretrained(compression_config["config"]["name"]) - elif compression_type == "dac_rvq_ae": - from .autoencoders import create_autoencoder_from_config - autoencoder = create_autoencoder_from_config({"model": compression_config["config"], "sample_rate": config["sample_rate"]}) - autoencoder.load_state_dict(torch.load(compression_config["ckpt_path"], map_location="cpu")["state_dict"]) - compression_model = DACRVQCompressionModel(autoencoder) - - lm_config = model_config.get('lm', None) - assert lm_config is not None, 'lm config must be specified in model config' - - codebook_pattern = lm_config.pop("codebook_pattern", "delay") - - pattern_providers = { - 'parallel': ParallelPatternProvider, - 'delay': DelayedPatternProvider, - 'unroll': UnrolledPatternProvider, - 'valle': VALLEPattern, - 'musiclm': MusicLMPattern, - } - - pattern_provider = pattern_providers[codebook_pattern](n_q=compression_model.num_codebooks) - - conditioning_config = model_config.get("conditioning", {}) - - condition_output_dim = conditioning_config.get("output_dim", 768) - - condition_provider = ConditioningProvider( - conditioners = { - "description": T5Conditioner( - name="t5-base", - output_dim=condition_output_dim, - word_dropout=0.3, - normalize_text=False, - finetune=False, - device="cpu" - ) - } - ) - - condition_fuser = ConditionFuser(fuse2cond={ - "cross": ["description"], - "prepend": [], - "sum": [] - }) - - lm = LMModel( - pattern_provider = pattern_provider, - condition_provider = condition_provider, - fuser = condition_fuser, - n_q = compression_model.num_codebooks, - card = compression_model.cardinality, - **lm_config - ) - - - model = MusicGen( - name = model_config.get("name", "musicgen-scratch"), - compression_model = compression_model, - lm = lm, - max_duration=30 - ) - - return model - -class DACRVQCompressionModel(CompressionModel): - def __init__(self, autoencoder: AudioAutoencoder): - super().__init__() - self.model = autoencoder.eval() - - assert isinstance(self.model.bottleneck, DACRVQBottleneck) or isinstance(self.model.bottleneck, DACRVQVAEBottleneck), "Autoencoder must have a DACRVQBottleneck or DACRVQVAEBottleneck" - - self.n_quantizers = self.model.bottleneck.num_quantizers - - def forward(self, x: torch.Tensor) -> qt.QuantizedResult: - raise NotImplementedError("Forward and training with DAC RVQ not supported") - - def encode(self, x: torch.Tensor) -> tp.Tuple[torch.Tensor, tp.Optional[torch.Tensor]]: - _, info = self.model.encode(x, return_info=True, n_quantizers=self.n_quantizers) - codes = info["codes"] - return codes, None - - def decode(self, codes: torch.Tensor, scale: tp.Optional[torch.Tensor] = None): - assert scale is None - z_q = self.decode_latent(codes) - return self.model.decode(z_q) - - def decode_latent(self, codes: torch.Tensor): - """Decode from the discrete codes to continuous latent space.""" - return self.model.bottleneck.quantizer.from_codes(codes)[0] - - @property - def channels(self) -> int: - return self.model.io_channels - - @property - def frame_rate(self) -> float: - return self.model.sample_rate / self.model.downsampling_ratio - - @property - def sample_rate(self) -> int: - return self.model.sample_rate - - @property - def cardinality(self) -> int: - return self.model.bottleneck.quantizer.codebook_size - - @property - def num_codebooks(self) -> int: - return self.n_quantizers - - @property - def total_codebooks(self) -> int: - self.model.bottleneck.num_quantizers - - def set_num_codebooks(self, n: int): - """Set the active number of codebooks used by the quantizer. - """ - assert n >= 1 - assert n <= self.total_codebooks - self.n_quantizers = n \ No newline at end of file diff --git a/sonique/stable_audio_tools/models/pqmf.py b/sonique/stable_audio_tools/models/pqmf.py deleted file mode 100644 index 007fdb51ec797554c1cdd4d9363894d743d970bf..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/models/pqmf.py +++ /dev/null @@ -1,393 +0,0 @@ -import math -import numpy as np -import torch -import torch.nn as nn -from einops import rearrange -from scipy.optimize import fmin -from scipy.signal import firwin, kaiser, kaiser_beta, kaiserord - -class PQMF(nn.Module): - """ - Pseudo Quadrature Mirror Filter (PQMF) for multiband signal decomposition and reconstruction. - Uses polyphase representation which is computationally more efficient for real-time. - - Parameters: - - attenuation (int): Desired attenuation of the rejected frequency bands, usually between 80 and 120 dB. - - num_bands (int): Number of desired frequency bands. It must be a power of 2. - """ - - def __init__(self, attenuation, num_bands): - super(PQMF, self).__init__() - - # Ensure num_bands is a power of 2 - is_power_of_2 = (math.log2(num_bands) == int(math.log2(num_bands))) - assert is_power_of_2, "'num_bands' must be a power of 2." - - # Create the prototype filter - prototype_filter = design_prototype_filter(attenuation, num_bands) - filter_bank = generate_modulated_filter_bank(prototype_filter, num_bands) - padded_filter_bank = pad_to_nearest_power_of_two(filter_bank) - - # Register filters and settings - self.register_buffer("filter_bank", padded_filter_bank) - self.register_buffer("prototype", prototype_filter) - self.num_bands = num_bands - - def forward(self, signal): - """Decompose the signal into multiple frequency bands.""" - # If signal is not a pytorch tensor of Batch x Channels x Length, convert it - signal = prepare_signal_dimensions(signal) - # The signal length must be a multiple of num_bands. Pad it with zeros. - signal = pad_signal(signal, self.num_bands) - # run it - signal = polyphase_analysis(signal, self.filter_bank) - return apply_alias_cancellation(signal) - - def inverse(self, bands): - """Reconstruct the original signal from the frequency bands.""" - bands = apply_alias_cancellation(bands) - return polyphase_synthesis(bands, self.filter_bank) - - -def prepare_signal_dimensions(signal): - """ - Rearrange signal into Batch x Channels x Length. - - Parameters - ---------- - signal : torch.Tensor or numpy.ndarray - The input signal. - - Returns - ------- - torch.Tensor - Preprocessed signal tensor. - """ - # Convert numpy to torch tensor - if isinstance(signal, np.ndarray): - signal = torch.from_numpy(signal) - - # Ensure tensor - if not isinstance(signal, torch.Tensor): - raise ValueError("Input should be either a numpy array or a PyTorch tensor.") - - # Modify dimension of signal to Batch x Channels x Length - if signal.dim() == 1: - # This is just a mono signal. Unsqueeze to 1 x 1 x Length - signal = signal.unsqueeze(0).unsqueeze(0) - elif signal.dim() == 2: - # This is a multi-channel signal (e.g. stereo) - # Rearrange so that larger dimension (Length) is last - if signal.shape[0] > signal.shape[1]: - signal = signal.T - # Unsqueeze to 1 x Channels x Length - signal = signal.unsqueeze(0) - return signal - -def pad_signal(signal, num_bands): - """ - Pads the signal to make its length divisible by the given number of bands. - - Parameters - ---------- - signal : torch.Tensor - The input signal tensor, where the last dimension represents the signal length. - - num_bands : int - The number of bands by which the signal length should be divisible. - - Returns - ------- - torch.Tensor - The padded signal tensor. If the original signal length was already divisible - by num_bands, returns the original signal unchanged. - """ - remainder = signal.shape[-1] % num_bands - if remainder > 0: - padding_size = num_bands - remainder - signal = nn.functional.pad(signal, (0, padding_size)) - return signal - -def generate_modulated_filter_bank(prototype_filter, num_bands): - """ - Generate a QMF bank of cosine modulated filters based on a given prototype filter. - - Parameters - ---------- - prototype_filter : torch.Tensor - The prototype filter used as the basis for modulation. - num_bands : int - The number of desired subbands or filters. - - Returns - ------- - torch.Tensor - A bank of cosine modulated filters. - """ - - # Initialize indices for modulation. - subband_indices = torch.arange(num_bands).reshape(-1, 1) - - # Calculate the length of the prototype filter. - filter_length = prototype_filter.shape[-1] - - # Generate symmetric time indices centered around zero. - time_indices = torch.arange(-(filter_length // 2), (filter_length // 2) + 1) - - # Calculate phase offsets to ensure orthogonality between subbands. - phase_offsets = (-1)**subband_indices * np.pi / 4 - - # Compute the cosine modulation function. - modulation = torch.cos( - (2 * subband_indices + 1) * np.pi / (2 * num_bands) * time_indices + phase_offsets - ) - - # Apply modulation to the prototype filter. - modulated_filters = 2 * prototype_filter * modulation - - return modulated_filters - - -def design_kaiser_lowpass(angular_cutoff, attenuation, filter_length=None): - """ - Design a lowpass filter using the Kaiser window. - - Parameters - ---------- - angular_cutoff : float - The angular frequency cutoff of the filter. - attenuation : float - The desired stopband attenuation in decibels (dB). - filter_length : int, optional - Desired length of the filter. If not provided, it's computed based on the given specs. - - Returns - ------- - ndarray - The designed lowpass filter coefficients. - """ - - estimated_length, beta = kaiserord(attenuation, angular_cutoff / np.pi) - - # Ensure the estimated length is odd. - estimated_length = 2 * (estimated_length // 2) + 1 - - if filter_length is None: - filter_length = estimated_length - - return firwin(filter_length, angular_cutoff, window=('kaiser', beta), scale=False, nyq=np.pi) - - -def evaluate_filter_objective(angular_cutoff, attenuation, num_bands, filter_length): - """ - Evaluate the filter's objective value based on the criteria from https://ieeexplore.ieee.org/document/681427 - - Parameters - ---------- - angular_cutoff : float - Angular frequency cutoff of the filter. - attenuation : float - Desired stopband attenuation in dB. - num_bands : int - Number of bands for the multiband filter system. - filter_length : int, optional - Desired length of the filter. - - Returns - ------- - float - The computed objective (loss) value for the given filter specs. - """ - - filter_coeffs = design_kaiser_lowpass(angular_cutoff, attenuation, filter_length) - convolved_filter = np.convolve(filter_coeffs, filter_coeffs[::-1], "full") - - return np.max(np.abs(convolved_filter[convolved_filter.shape[-1] // 2::2 * num_bands][1:])) - - -def design_prototype_filter(attenuation, num_bands, filter_length=None): - """ - Design the optimal prototype filter for a multiband system given the desired specs. - - Parameters - ---------- - attenuation : float - The desired stopband attenuation in dB. - num_bands : int - Number of bands for the multiband filter system. - filter_length : int, optional - Desired length of the filter. If not provided, it's computed based on the given specs. - - Returns - ------- - ndarray - The optimal prototype filter coefficients. - """ - - optimal_angular_cutoff = fmin(lambda angular_cutoff: evaluate_filter_objective(angular_cutoff, attenuation, num_bands, filter_length), - 1 / num_bands, disp=0)[0] - - prototype_filter = design_kaiser_lowpass(optimal_angular_cutoff, attenuation, filter_length) - return torch.tensor(prototype_filter, dtype=torch.float32) - -def pad_to_nearest_power_of_two(x): - """ - Pads the input tensor 'x' on both sides such that its last dimension - becomes the nearest larger power of two. - - Parameters: - ----------- - x : torch.Tensor - The input tensor to be padded. - - Returns: - -------- - torch.Tensor - The padded tensor. - """ - current_length = x.shape[-1] - target_length = 2**math.ceil(math.log2(current_length)) - - total_padding = target_length - current_length - left_padding = total_padding // 2 - right_padding = total_padding - left_padding - - return nn.functional.pad(x, (left_padding, right_padding)) - -def apply_alias_cancellation(x): - """ - Applies alias cancellation by inverting the sign of every - second element of every second row, starting from the second - row's first element in a tensor. - - This operation helps ensure that the aliasing introduced in - each band during the decomposition will be counteracted during - the reconstruction. - - Parameters: - ----------- - x : torch.Tensor - The input tensor. - - Returns: - -------- - torch.Tensor - Tensor with specific elements' sign inverted for alias cancellation. - """ - - # Create a mask of the same shape as 'x', initialized with all ones - mask = torch.ones_like(x) - - # Update specific elements in the mask to -1 to perform inversion - mask[..., 1::2, ::2] = -1 - - # Apply the mask to the input tensor 'x' - return x * mask - -def ensure_odd_length(tensor): - """ - Pads the last dimension of a tensor to ensure its size is odd. - - Parameters: - ----------- - tensor : torch.Tensor - Input tensor whose last dimension might need padding. - - Returns: - -------- - torch.Tensor - The original tensor if its last dimension was already odd, - or the padded tensor with an odd-sized last dimension. - """ - - last_dim_size = tensor.shape[-1] - - if last_dim_size % 2 == 0: - tensor = nn.functional.pad(tensor, (0, 1)) - - return tensor - -def polyphase_analysis(signal, filter_bank): - """ - Applies the polyphase method to efficiently analyze the signal using a filter bank. - - Parameters: - ----------- - signal : torch.Tensor - Input signal tensor with shape (Batch x Channels x Length). - - filter_bank : torch.Tensor - Filter bank tensor with shape (Bands x Length). - - Returns: - -------- - torch.Tensor - Signal split into sub-bands. (Batch x Channels x Bands x Length) - """ - - num_bands = filter_bank.shape[0] - num_channels = signal.shape[1] - - # Rearrange signal for polyphase processing. - # Also combine Batch x Channel into one dimension for now. - #signal = rearrange(signal, "b c (t n) -> b (c n) t", n=num_bands) - signal = rearrange(signal, "b c (t n) -> (b c) n t", n=num_bands) - - # Rearrange the filter bank for matching signal shape - filter_bank = rearrange(filter_bank, "c (t n) -> c n t", n=num_bands) - - # Apply convolution with appropriate padding to maintain spatial dimensions - padding = filter_bank.shape[-1] // 2 - filtered_signal = nn.functional.conv1d(signal, filter_bank, padding=padding) - - # Truncate the last dimension post-convolution to adjust the output shape - filtered_signal = filtered_signal[..., :-1] - # Rearrange the first dimension back into Batch x Channels - filtered_signal = rearrange(filtered_signal, "(b c) n t -> b c n t", c=num_channels) - - return filtered_signal - -def polyphase_synthesis(signal, filter_bank): - """ - Polyphase Inverse: Apply polyphase filter bank synthesis to reconstruct a signal. - - Parameters - ---------- - signal : torch.Tensor - Decomposed signal to be reconstructed (shape: Batch x Channels x Bands x Length). - - filter_bank : torch.Tensor - Analysis filter bank (shape: Bands x Length). - - should_rearrange : bool, optional - Flag to determine if the filters should be rearranged for polyphase synthesis. Default is True. - - Returns - ------- - torch.Tensor - Reconstructed signal (shape: Batch x Channels X Length) - """ - - num_bands = filter_bank.shape[0] - num_channels = signal.shape[1] - - # Rearrange the filter bank - filter_bank = filter_bank.flip(-1) - filter_bank = rearrange(filter_bank, "c (t n) -> n c t", n=num_bands) - - # Combine Batch x Channels into one dimension for now. - signal = rearrange(signal, "b c n t -> (b c) n t") - - # Apply convolution with appropriate padding - padding_amount = filter_bank.shape[-1] // 2 + 1 - reconstructed_signal = nn.functional.conv1d(signal, filter_bank, padding=int(padding_amount)) - - # Scale the result - reconstructed_signal = reconstructed_signal[..., :-1] * num_bands - - # Reorganize the output and truncate - reconstructed_signal = reconstructed_signal.flip(1) - reconstructed_signal = rearrange(reconstructed_signal, "(b c) n t -> b c (t n)", c=num_channels, n=num_bands) - reconstructed_signal = reconstructed_signal[..., 2 * filter_bank.shape[1]:] - - return reconstructed_signal \ No newline at end of file diff --git a/sonique/stable_audio_tools/models/pretrained.py b/sonique/stable_audio_tools/models/pretrained.py deleted file mode 100644 index e83af343587da91af92218f309c969c5a975b5ed..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/models/pretrained.py +++ /dev/null @@ -1,25 +0,0 @@ -import json - -from .factory import create_model_from_config -from .utils import load_ckpt_state_dict - -from huggingface_hub import hf_hub_download - -def get_pretrained_model(name: str): - - model_config_path = hf_hub_download(name, filename="model_config.json", repo_type='model') - - with open(model_config_path) as f: - model_config = json.load(f) - - model = create_model_from_config(model_config) - - # Try to download the model.safetensors file first, if it doesn't exist, download the model.ckpt file - try: - model_ckpt_path = hf_hub_download(name, filename="model.safetensors", repo_type='model') - except Exception as e: - model_ckpt_path = hf_hub_download(name, filename="model.ckpt", repo_type='model') - - model.load_state_dict(load_ckpt_state_dict(model_ckpt_path)) - - return model, model_config \ No newline at end of file diff --git a/sonique/stable_audio_tools/models/pretransforms.py b/sonique/stable_audio_tools/models/pretransforms.py deleted file mode 100644 index a661acbb6bc1371b50cd5742d0a6becbb5775bb3..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/models/pretransforms.py +++ /dev/null @@ -1,160 +0,0 @@ -from einops import rearrange -from torch import nn - -class Pretransform(nn.Module): - def __init__(self, enable_grad=False, io_channels=2, ): - super().__init__() - - self.io_channels = io_channels - self.encoded_channels = None - self.downsampling_ratio = None - - self.enable_grad = enable_grad - - def encode(self, x): - return x - - def decode(self, z): - return z - -class AutoencoderPretransform(Pretransform): - def __init__(self, model, scale=1.0, model_half=False, iterate_batch=False): - super().__init__() - self.model = model - self.model.requires_grad_(False).eval() - self.scale=scale - self.downsampling_ratio = model.downsampling_ratio - self.io_channels = model.io_channels - self.sample_rate = model.sample_rate - - self.model_half = model_half - self.iterate_batch = iterate_batch - - self.encoded_channels = model.latent_dim - - if self.model_half: - self.model.half() - - def encode(self, x, **kwargs): - # print(f'encoder takes input {x.shape}') - if self.model_half: - x = x.half() - - encoded = self.model.encode(x, iterate_batch=self.iterate_batch, **kwargs) - - if self.model_half: - encoded = encoded.float() - - out = encoded / self.scale - # print(f'encoder out: {out.shape}') - return encoded / self.scale - - def decode(self, z, **kwargs): - z = z * self.scale - - if self.model_half: - z = z.half() - - decoded = self.model.decode(z, iterate_batch=self.iterate_batch, **kwargs) - - if self.model_half: - decoded = decoded.float() - - return decoded - - def load_state_dict(self, state_dict, strict=True): - # print(f'load state dict {state_dict}') - self.model.load_state_dict(state_dict, strict=strict) - -class WaveletPretransform(Pretransform): - def __init__(self, channels, levels, wavelet): - super().__init__() - - from .wavelets import WaveletEncode1d, WaveletDecode1d - - self.encoder = WaveletEncode1d(channels, levels, wavelet) - self.decoder = WaveletDecode1d(channels, levels, wavelet) - - self.downsampling_ratio = 2 ** levels - self.io_channels = channels - self.encoded_channels = channels * self.downsampling_ratio - - def encode(self, x): - return self.encoder(x) - - def decode(self, z): - return self.decoder(z) - -class PQMFPretransform(Pretransform): - def __init__(self, attenuation=100, num_bands=16): - super().__init__() - from .pqmf import PQMF - self.pqmf = PQMF(attenuation, num_bands) - - def encode(self, x): - # x is (Batch x Channels x Time) - x = self.pqmf.forward(x) - # pqmf.forward returns (Batch x Channels x Bands x Time) - # but Pretransform needs Batch x Channels x Time - # so concatenate channels and bands into one axis - return rearrange(x, "b c n t -> b (c n) t") - - def decode(self, x): - # x is (Batch x (Channels Bands) x Time), convert back to (Batch x Channels x Bands x Time) - x = rearrange(x, "b (c n) t -> b c n t", n=self.pqmf.num_bands) - # returns (Batch x Channels x Time) - return self.pqmf.inverse(x) - -class PretrainedDACPretransform(Pretransform): - def __init__(self, model_type="44khz", model_bitrate="8kbps", scale=1.0, quantize_on_decode: bool = True, chunked=True): - super().__init__() - - import dac - - model_path = dac.utils.download(model_type=model_type, model_bitrate=model_bitrate) - - self.model = dac.DAC.load(model_path) - - self.quantize_on_decode = quantize_on_decode - - if model_type == "44khz": - self.downsampling_ratio = 512 - else: - self.downsampling_ratio = 320 - - self.io_channels = 1 - - self.scale = scale - - self.chunked = chunked - - self.encoded_channels = self.model.latent_dim - - def encode(self, x): - # print(f"Input to DAC encoder shape: {x.shape}, type: {x.dtype}") - latents = self.model.encoder(x) - # print(f"Latents shape after DAC encoder: {latents.shape}") - - if self.quantize_on_decode: - output = latents - else: - z, _, _, _, _ = self.model.quantizer(latents, n_quantizers=self.model.n_codebooks) - output = z - - if self.scale != 1.0: - output = output / self.scale - # print(f'output from DAC encoder: {x.shape}') - return output - - def decode(self, z): - - if self.scale != 1.0: - z = z * self.scale - - if self.quantize_on_decode: - z, _, _, _, _ = self.model.quantizer(z, n_quantizers=self.model.n_codebooks) - - return self.model.decode(z) - - - diff --git a/sonique/stable_audio_tools/models/utils.py b/sonique/stable_audio_tools/models/utils.py deleted file mode 100644 index 50c389398aa78cbe33f080f0368bfedb93f8f6da..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/models/utils.py +++ /dev/null @@ -1,10 +0,0 @@ -import torch -from safetensors.torch import load_file - -def load_ckpt_state_dict(ckpt_path): - if ckpt_path.endswith(".safetensors"): - state_dict = load_file(ckpt_path) - else: - state_dict = torch.load(ckpt_path, map_location="cpu")["state_dict"] - - return state_dict diff --git a/sonique/stable_audio_tools/models/wavelets.py b/sonique/stable_audio_tools/models/wavelets.py deleted file mode 100644 index a359e39110c168aab960d3f79262b464a660e55e..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/models/wavelets.py +++ /dev/null @@ -1,82 +0,0 @@ -"""The 1D discrete wavelet transform for PyTorch.""" - -from einops import rearrange -import pywt -import torch -from torch import nn -from torch.nn import functional as F -from typing import Literal - - -def get_filter_bank(wavelet): - filt = torch.tensor(pywt.Wavelet(wavelet).filter_bank) - if wavelet.startswith("bior") and torch.all(filt[:, 0] == 0): - filt = filt[:, 1:] - return filt - -class WaveletEncode1d(nn.Module): - def __init__(self, - channels, - levels, - wavelet: Literal["bior2.2", "bior2.4", "bior2.6", "bior2.8", "bior4.4", "bior6.8"] = "bior4.4"): - super().__init__() - self.wavelet = wavelet - self.channels = channels - self.levels = levels - filt = get_filter_bank(wavelet) - assert filt.shape[-1] % 2 == 1 - kernel = filt[:2, None] - kernel = torch.flip(kernel, dims=(-1,)) - index_i = torch.repeat_interleave(torch.arange(2), channels) - index_j = torch.tile(torch.arange(channels), (2,)) - kernel_final = torch.zeros(channels * 2, channels, filt.shape[-1]) - kernel_final[index_i * channels + index_j, index_j] = kernel[index_i, 0] - self.register_buffer("kernel", kernel_final) - - def forward(self, x): - for i in range(self.levels): - low, rest = x[:, : self.channels], x[:, self.channels :] - pad = self.kernel.shape[-1] // 2 - low = F.pad(low, (pad, pad), "reflect") - low = F.conv1d(low, self.kernel, stride=2) - rest = rearrange( - rest, "n (c c2) (l l2) -> n (c l2 c2) l", l2=2, c2=self.channels - ) - x = torch.cat([low, rest], dim=1) - return x - - -class WaveletDecode1d(nn.Module): - def __init__(self, - channels, - levels, - wavelet: Literal["bior2.2", "bior2.4", "bior2.6", "bior2.8", "bior4.4", "bior6.8"] = "bior4.4"): - super().__init__() - self.wavelet = wavelet - self.channels = channels - self.levels = levels - filt = get_filter_bank(wavelet) - assert filt.shape[-1] % 2 == 1 - kernel = filt[2:, None] - index_i = torch.repeat_interleave(torch.arange(2), channels) - index_j = torch.tile(torch.arange(channels), (2,)) - kernel_final = torch.zeros(channels * 2, channels, filt.shape[-1]) - kernel_final[index_i * channels + index_j, index_j] = kernel[index_i, 0] - self.register_buffer("kernel", kernel_final) - - def forward(self, x): - for i in range(self.levels): - low, rest = x[:, : self.channels * 2], x[:, self.channels * 2 :] - pad = self.kernel.shape[-1] // 2 + 2 - low = rearrange(low, "n (l2 c) l -> n c (l l2)", l2=2) - low = F.pad(low, (pad, pad), "reflect") - low = rearrange(low, "n c (l l2) -> n (l2 c) l", l2=2) - low = F.conv_transpose1d( - low, self.kernel, stride=2, padding=self.kernel.shape[-1] // 2 - ) - low = low[..., pad - 1 : -pad] - rest = rearrange( - rest, "n (c l2 c2) l -> n (c c2) (l l2)", l2=2, c2=self.channels - ) - x = torch.cat([low, rest], dim=1) - return x \ No newline at end of file diff --git a/sonique/stable_audio_tools/training/__init__.py b/sonique/stable_audio_tools/training/__init__.py deleted file mode 100644 index f77486b07a478bc88359bf2ece8b9c860df1b054..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/training/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .factory import create_training_wrapper_from_config, create_demo_callback_from_config diff --git a/sonique/stable_audio_tools/training/autoencoders.py b/sonique/stable_audio_tools/training/autoencoders.py deleted file mode 100644 index b729a5d1c6d7da45ca9d0333dd4ea201d0ec1e0a..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/training/autoencoders.py +++ /dev/null @@ -1,480 +0,0 @@ -import torch -import torchaudio -import wandb -from einops import rearrange -from safetensors.torch import save_file, save_model -from torch import nn, optim -from torch.nn import functional as F -from torch.nn.parameter import Parameter -from ema_pytorch import EMA -import auraloss -import pytorch_lightning as pl -from ..models.autoencoders import AudioAutoencoder -from ..models.discriminators import EncodecDiscriminator, OobleckDiscriminator, DACGANLoss -from ..models.bottleneck import VAEBottleneck, RVQBottleneck, DACRVQBottleneck, DACRVQVAEBottleneck, RVQVAEBottleneck, WassersteinBottleneck -from .losses import MultiLoss, AuralossLoss, ValueLoss, L1Loss -from .utils import create_optimizer_from_config, create_scheduler_from_config - - -from pytorch_lightning.utilities.rank_zero import rank_zero_only -from aeiou.viz import pca_point_cloud, audio_spectrogram_image, tokens_spectrogram_image - -class AutoencoderTrainingWrapper(pl.LightningModule): - def __init__( - self, - autoencoder: AudioAutoencoder, - lr: float = 1e-4, - warmup_steps: int = 0, - encoder_freeze_on_warmup: bool = False, - sample_rate=48000, - loss_config: dict = None, - optimizer_configs: dict = None, - use_ema: bool = True, - ema_copy = None, - force_input_mono = False, - latent_mask_ratio = 0.0, - teacher_model: AudioAutoencoder = None - ): - super().__init__() - - self.automatic_optimization = False - - self.autoencoder = autoencoder - - self.warmed_up = False - self.warmup_steps = warmup_steps - self.encoder_freeze_on_warmup = encoder_freeze_on_warmup - self.lr = lr - - self.force_input_mono = force_input_mono - - self.teacher_model = teacher_model - - if optimizer_configs is None: - optimizer_configs ={ - "autoencoder": { - "optimizer": { - "type": "AdamW", - "config": { - "lr": lr, - "betas": (.8, .99) - } - } - }, - "discriminator": { - "optimizer": { - "type": "AdamW", - "config": { - "lr": lr, - "betas": (.8, .99) - } - } - } - - } - - self.optimizer_configs = optimizer_configs - - if loss_config is None: - scales = [2048, 1024, 512, 256, 128, 64, 32] - hop_sizes = [] - win_lengths = [] - overlap = 0.75 - for s in scales: - hop_sizes.append(int(s * (1 - overlap))) - win_lengths.append(s) - - loss_config = { - "discriminator": { - "type": "encodec", - "config": { - "n_ffts": scales, - "hop_lengths": hop_sizes, - "win_lengths": win_lengths, - "filters": 32 - }, - "weights": { - "adversarial": 0.1, - "feature_matching": 5.0, - } - }, - "spectral": { - "type": "mrstft", - "config": { - "fft_sizes": scales, - "hop_sizes": hop_sizes, - "win_lengths": win_lengths, - "perceptual_weighting": True - }, - "weights": { - "mrstft": 1.0, - } - }, - "time": { - "type": "l1", - "config": {}, - "weights": { - "l1": 0.0, - } - } - } - - self.loss_config = loss_config - - # Spectral reconstruction loss - - stft_loss_args = loss_config['spectral']['config'] - - if self.autoencoder.out_channels == 2: - self.sdstft = auraloss.freq.SumAndDifferenceSTFTLoss(sample_rate=sample_rate, **stft_loss_args) - self.lrstft = auraloss.freq.MultiResolutionSTFTLoss(sample_rate=sample_rate, **stft_loss_args) - else: - self.sdstft = auraloss.freq.MultiResolutionSTFTLoss(sample_rate=sample_rate, **stft_loss_args) - - # Discriminator - - if loss_config['discriminator']['type'] == 'oobleck': - self.discriminator = OobleckDiscriminator(**loss_config['discriminator']['config']) - elif loss_config['discriminator']['type'] == 'encodec': - self.discriminator = EncodecDiscriminator(in_channels=self.autoencoder.out_channels, **loss_config['discriminator']['config']) - elif loss_config['discriminator']['type'] == 'dac': - self.discriminator = DACGANLoss(channels=self.autoencoder.out_channels, sample_rate=sample_rate, **loss_config['discriminator']['config']) - - self.gen_loss_modules = [] - - # Adversarial and feature matching losses - self.gen_loss_modules += [ - ValueLoss(key='loss_adv', weight=self.loss_config['discriminator']['weights']['adversarial'], name='loss_adv'), - ValueLoss(key='feature_matching_distance', weight=self.loss_config['discriminator']['weights']['feature_matching'], name='feature_matching'), - ] - - if self.teacher_model is not None: - # Distillation losses - - stft_loss_weight = self.loss_config['spectral']['weights']['mrstft'] * 0.25 - self.gen_loss_modules += [ - AuralossLoss(self.sdstft, 'reals', 'decoded', name='mrstft_loss', weight=stft_loss_weight), # Reconstruction loss - AuralossLoss(self.sdstft, 'decoded', 'teacher_decoded', name='mrstft_loss_distill', weight=stft_loss_weight), # Distilled model's decoder is compatible with teacher's decoder - AuralossLoss(self.sdstft, 'reals', 'own_latents_teacher_decoded', name='mrstft_loss_own_latents_teacher', weight=stft_loss_weight), # Distilled model's encoder is compatible with teacher's decoder - AuralossLoss(self.sdstft, 'reals', 'teacher_latents_own_decoded', name='mrstft_loss_teacher_latents_own', weight=stft_loss_weight) # Teacher's encoder is compatible with distilled model's decoder - ] - - else: - - # Reconstruction loss - self.gen_loss_modules += [ - AuralossLoss(self.sdstft, 'reals', 'decoded', name='mrstft_loss', weight=self.loss_config['spectral']['weights']['mrstft']), - ] - - if self.autoencoder.out_channels == 2: - - # Add left and right channel reconstruction losses in addition to the sum and difference - self.gen_loss_modules += [ - AuralossLoss(self.lrstft, 'reals_left', 'decoded_left', name='stft_loss_left', weight=self.loss_config['spectral']['weights']['mrstft']/2), - AuralossLoss(self.lrstft, 'reals_right', 'decoded_right', name='stft_loss_right', weight=self.loss_config['spectral']['weights']['mrstft']/2), - ] - - self.gen_loss_modules += [ - AuralossLoss(self.sdstft, 'reals', 'decoded', name='mrstft_loss', weight=self.loss_config['spectral']['weights']['mrstft']), - ] - - if self.loss_config['time']['weights']['l1'] > 0.0: - self.gen_loss_modules.append(L1Loss(key_a='reals', key_b='decoded', weight=self.loss_config['time']['weights']['l1'], name='l1_time_loss')) - - if self.autoencoder.bottleneck is not None: - self.gen_loss_modules += create_loss_modules_from_bottleneck(self.autoencoder.bottleneck, self.loss_config) - - self.losses_gen = MultiLoss(self.gen_loss_modules) - - self.disc_loss_modules = [ - ValueLoss(key='loss_dis', weight=1.0, name='discriminator_loss'), - ] - - self.losses_disc = MultiLoss(self.disc_loss_modules) - - # Set up EMA for model weights - self.autoencoder_ema = None - - self.use_ema = use_ema - - if self.use_ema: - self.autoencoder_ema = EMA( - self.autoencoder, - ema_model=ema_copy, - beta=0.9999, - power=3/4, - update_every=1, - update_after_step=1 - ) - - self.latent_mask_ratio = latent_mask_ratio - - def configure_optimizers(self): - - opt_gen = create_optimizer_from_config(self.optimizer_configs['autoencoder']['optimizer'], self.autoencoder.parameters()) - opt_disc = create_optimizer_from_config(self.optimizer_configs['discriminator']['optimizer'], self.discriminator.parameters()) - - if "scheduler" in self.optimizer_configs['autoencoder'] and "scheduler" in self.optimizer_configs['discriminator']: - sched_gen = create_scheduler_from_config(self.optimizer_configs['autoencoder']['scheduler'], opt_gen) - sched_disc = create_scheduler_from_config(self.optimizer_configs['discriminator']['scheduler'], opt_disc) - return [opt_gen, opt_disc], [sched_gen, sched_disc] - - return [opt_gen, opt_disc] - - def training_step(self, batch, batch_idx): - reals, _ = batch - - # Remove extra dimension added by WebDataset - if reals.ndim == 4 and reals.shape[0] == 1: - reals = reals[0] - - if self.global_step >= self.warmup_steps: - self.warmed_up = True - - loss_info = {} - - loss_info["reals"] = reals - - encoder_input = reals - - if self.force_input_mono and encoder_input.shape[1] > 1: - encoder_input = encoder_input.mean(dim=1, keepdim=True) - - loss_info["encoder_input"] = encoder_input - - data_std = encoder_input.std() - - if self.warmed_up and self.encoder_freeze_on_warmup: - with torch.no_grad(): - latents, encoder_info = self.autoencoder.encode(encoder_input, return_info=True) - else: - latents, encoder_info = self.autoencoder.encode(encoder_input, return_info=True) - - loss_info["latents"] = latents - - loss_info.update(encoder_info) - - # Encode with teacher model for distillation - if self.teacher_model is not None: - with torch.no_grad(): - teacher_latents = self.teacher_model.encode(encoder_input, return_info=False) - loss_info['teacher_latents'] = teacher_latents - - # Optionally mask out some latents for noise resistance - if self.latent_mask_ratio > 0.0: - mask = torch.rand_like(latents) < self.latent_mask_ratio - latents = torch.where(mask, torch.zeros_like(latents), latents) - - decoded = self.autoencoder.decode(latents) - - loss_info["decoded"] = decoded - - if self.autoencoder.out_channels == 2: - loss_info["decoded_left"] = decoded[:, 0:1, :] - loss_info["decoded_right"] = decoded[:, 1:2, :] - loss_info["reals_left"] = reals[:, 0:1, :] - loss_info["reals_right"] = reals[:, 1:2, :] - - # Distillation - if self.teacher_model is not None: - with torch.no_grad(): - teacher_decoded = self.teacher_model.decode(teacher_latents) - own_latents_teacher_decoded = self.teacher_model.decode(latents) #Distilled model's latents decoded by teacher - teacher_latents_own_decoded = self.autoencoder.decode(teacher_latents) #Teacher's latents decoded by distilled model - - loss_info['teacher_decoded'] = teacher_decoded - loss_info['own_latents_teacher_decoded'] = own_latents_teacher_decoded - loss_info['teacher_latents_own_decoded'] = teacher_latents_own_decoded - - - if self.warmed_up: - loss_dis, loss_adv, feature_matching_distance = self.discriminator.loss(reals, decoded) - else: - loss_dis = torch.tensor(0.).to(reals) - loss_adv = torch.tensor(0.).to(reals) - feature_matching_distance = torch.tensor(0.).to(reals) - - loss_info["loss_dis"] = loss_dis - loss_info["loss_adv"] = loss_adv - loss_info["feature_matching_distance"] = feature_matching_distance - - opt_gen, opt_disc = self.optimizers() - - lr_schedulers = self.lr_schedulers() - - sched_gen = None - sched_disc = None - - if lr_schedulers is not None: - sched_gen, sched_disc = lr_schedulers - - # Train the discriminator - if self.global_step % 2 and self.warmed_up: - loss, losses = self.losses_disc(loss_info) - - log_dict = { - 'train/disc_lr': opt_disc.param_groups[0]['lr'] - } - - opt_disc.zero_grad() - self.manual_backward(loss) - opt_disc.step() - - if sched_disc is not None: - # sched step every step - sched_disc.step() - - # Train the generator - else: - - loss, losses = self.losses_gen(loss_info) - - if self.use_ema: - self.autoencoder_ema.update() - - opt_gen.zero_grad() - self.manual_backward(loss) - opt_gen.step() - - if sched_gen is not None: - # scheduler step every step - sched_gen.step() - - log_dict = { - 'train/loss': loss.detach(), - 'train/latent_std': latents.std().detach(), - 'train/data_std': data_std.detach(), - 'train/gen_lr': opt_gen.param_groups[0]['lr'] - } - - for loss_name, loss_value in losses.items(): - log_dict[f'train/{loss_name}'] = loss_value.detach() - - self.log_dict(log_dict, prog_bar=True, on_step=True) - - return loss - - def export_model(self, path, use_safetensors=False): - if self.autoencoder_ema is not None: - model = self.autoencoder_ema.ema_model - else: - model = self.autoencoder - - if use_safetensors: - save_model(model, path) - else: - torch.save({"state_dict": model.state_dict()}, path) - - -class AutoencoderDemoCallback(pl.Callback): - def __init__( - self, - demo_dl, - demo_every=2000, - sample_size=65536, - sample_rate=48000 - ): - super().__init__() - self.demo_every = demo_every - self.demo_samples = sample_size - self.demo_dl = iter(demo_dl) - self.sample_rate = sample_rate - self.last_demo_step = -1 - - @rank_zero_only - @torch.no_grad() - def on_train_batch_end(self, trainer, module, outputs, batch, batch_idx): - if (trainer.global_step - 1) % self.demo_every != 0 or self.last_demo_step == trainer.global_step: - return - - self.last_demo_step = trainer.global_step - - module.eval() - - try: - demo_reals, _ = next(self.demo_dl) - - # Remove extra dimension added by WebDataset - if demo_reals.ndim == 4 and demo_reals.shape[0] == 1: - demo_reals = demo_reals[0] - - encoder_input = demo_reals - - encoder_input = encoder_input.to(module.device) - - if module.force_input_mono: - encoder_input = encoder_input.mean(dim=1, keepdim=True) - - demo_reals = demo_reals.to(module.device) - - with torch.no_grad(): - if module.use_ema: - - latents = module.autoencoder_ema.ema_model.encode(encoder_input) - - fakes = module.autoencoder_ema.ema_model.decode(latents) - else: - latents = module.autoencoder.encode(encoder_input) - - fakes = module.autoencoder.decode(latents) - - #Interleave reals and fakes - reals_fakes = rearrange([demo_reals, fakes], 'i b d n -> (b i) d n') - - # Put the demos together - reals_fakes = rearrange(reals_fakes, 'b d n -> d (b n)') - - log_dict = {} - - filename = f'recon_{trainer.global_step:08}.wav' - reals_fakes = reals_fakes.clamp(-1, 1).mul(32767).to(torch.int16).cpu() - torchaudio.save(filename, reals_fakes, self.sample_rate) - - log_dict[f'recon'] = wandb.Audio(filename, - sample_rate=self.sample_rate, - caption=f'Reconstructed') - - log_dict[f'embeddings_3dpca'] = pca_point_cloud(latents) - log_dict[f'embeddings_spec'] = wandb.Image(tokens_spectrogram_image(latents)) - - log_dict[f'recon_melspec_left'] = wandb.Image(audio_spectrogram_image(reals_fakes)) - - trainer.logger.experiment.log(log_dict) - except Exception as e: - print(f'{type(e).__name__}: {e}') - raise e - finally: - module.train() - -def create_loss_modules_from_bottleneck(bottleneck, loss_config): - losses = [] - - if isinstance(bottleneck, VAEBottleneck) or isinstance(bottleneck, DACRVQVAEBottleneck) or isinstance(bottleneck, RVQVAEBottleneck): - try: - kl_weight = loss_config['bottleneck']['weights']['kl'] - except: - kl_weight = 1e-6 - - kl_loss = ValueLoss(key='kl', weight=kl_weight, name='kl_loss') - losses.append(kl_loss) - - if isinstance(bottleneck, RVQBottleneck) or isinstance(bottleneck, RVQVAEBottleneck): - quantizer_loss = ValueLoss(key='quantizer_loss', weight=1.0, name='quantizer_loss') - losses.append(quantizer_loss) - - if isinstance(bottleneck, DACRVQBottleneck) or isinstance(bottleneck, DACRVQVAEBottleneck): - codebook_loss = ValueLoss(key='vq/codebook_loss', weight=1.0, name='codebook_loss') - commitment_loss = ValueLoss(key='vq/commitment_loss', weight=0.25, name='commitment_loss') - losses.append(codebook_loss) - losses.append(commitment_loss) - - if isinstance(bottleneck, WassersteinBottleneck): - try: - mmd_weight = loss_config['bottleneck']['weights']['mmd'] - except: - mmd_weight = 100 - - mmd_loss = ValueLoss(key='mmd', weight=mmd_weight, name='mmd_loss') - losses.append(mmd_loss) - - return losses \ No newline at end of file diff --git a/sonique/stable_audio_tools/training/diffusion.py b/sonique/stable_audio_tools/training/diffusion.py deleted file mode 100644 index d60c341c394edb6c198dbdb63cc8b5a1e912a77d..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/training/diffusion.py +++ /dev/null @@ -1,1157 +0,0 @@ -import pytorch_lightning as pl -import sys, gc -import random -import torch -import torchaudio -import typing as tp -import wandb - -from aeiou.viz import pca_point_cloud, audio_spectrogram_image, tokens_spectrogram_image -import auraloss -from ema_pytorch import EMA -from einops import rearrange -from safetensors.torch import save_file -from torch import optim -from torch.nn import functional as F -from pytorch_lightning.utilities.rank_zero import rank_zero_only - -from ...inference.sampling import get_alphas_sigmas, sample -from ..models.diffusion import DiffusionModelWrapper, ConditionedDiffusionModelWrapper -from ..models.autoencoders import DiffusionAutoencoder -from .losses import AuralossLoss, MSELoss, MultiLoss - -from time import time - -class Profiler: - - def __init__(self): - self.ticks = [[time(), None]] - - def tick(self, msg): - self.ticks.append([time(), msg]) - - def __repr__(self): - rep = 80 * "=" + "\n" - for i in range(1, len(self.ticks)): - msg = self.ticks[i][1] - ellapsed = self.ticks[i][0] - self.ticks[i - 1][0] - rep += msg + f": {ellapsed*1000:.2f}ms\n" - rep += 80 * "=" + "\n\n\n" - return rep - -class DiffusionUncondTrainingWrapper(pl.LightningModule): - ''' - Wrapper for training an unconditional audio diffusion model (like Dance Diffusion). - ''' - def __init__( - self, - model: DiffusionModelWrapper, - lr: float = 1e-4 - ): - super().__init__() - - self.diffusion = model - - self.diffusion_ema = EMA( - self.diffusion.model, - beta=0.9999, - power=3/4, - update_every=1, - update_after_step=1 - ) - - self.lr = lr - - self.rng = torch.quasirandom.SobolEngine(1, scramble=True) - - loss_modules = [ - MSELoss("v", - "targets", - weight=1.0, - name="mse_loss" - ) - ] - - self.losses = MultiLoss(loss_modules) - - def configure_optimizers(self): - return optim.Adam([*self.diffusion.parameters()], lr=self.lr) - - def training_step(self, batch, batch_idx): - reals = batch[0] - - if reals.ndim == 4 and reals.shape[0] == 1: - reals = reals[0] - - # Draw uniformly distributed continuous timesteps - t = self.rng.draw(reals.shape[0])[:, 0].to(self.device) - - # Calculate the noise schedule parameters for those timesteps - alphas, sigmas = get_alphas_sigmas(t) - - diffusion_input = reals - - loss_info = {} - - loss_info["audio_reals"] = diffusion_input - - if self.diffusion.pretransform is not None: - with torch.set_grad_enabled(self.diffusion.pretransform.enable_grad): - diffusion_input = self.diffusion.pretransform.encode(diffusion_input) - loss_info["reals"] = diffusion_input - - # Combine the ground truth data and the noise - alphas = alphas[:, None, None] - sigmas = sigmas[:, None, None] - noise = torch.randn_like(diffusion_input) - noised_inputs = diffusion_input * alphas + noise * sigmas - targets = noise * alphas - diffusion_input * sigmas - - with torch.cuda.amp.autocast(): - v = self.diffusion(noised_inputs, t) - - loss_info.update({ - "v": v, - "targets": targets - }) - - loss, losses = self.losses(loss_info) - - log_dict = { - 'train/loss': loss.detach(), - 'train/std_data': diffusion_input.std(), - } - - for loss_name, loss_value in losses.items(): - log_dict[f"train/{loss_name}"] = loss_value.detach() - - self.log_dict(log_dict, prog_bar=True, on_step=True) - return loss - - def on_before_zero_grad(self, *args, **kwargs): - self.diffusion_ema.update() - - def export_model(self, path, use_safetensors=False): - - self.diffusion.model = self.diffusion_ema.ema_model - - if use_safetensors: - save_file(self.diffusion.state_dict(), path) - else: - torch.save({"state_dict": self.diffusion.state_dict()}, path) - -class DiffusionUncondDemoCallback(pl.Callback): - def __init__(self, - demo_every=2000, - num_demos=8, - demo_steps=250, - sample_rate=48000 - ): - super().__init__() - - self.demo_every = demo_every - self.num_demos = num_demos - self.demo_steps = demo_steps - self.sample_rate = sample_rate - self.last_demo_step = -1 - - @rank_zero_only - @torch.no_grad() - def on_train_batch_end(self, trainer, module, outputs, batch, batch_idx): - - if (trainer.global_step - 1) % self.demo_every != 0 or self.last_demo_step == trainer.global_step: - return - - self.last_demo_step = trainer.global_step - - demo_samples = module.diffusion.sample_size - - if module.diffusion.pretransform is not None: - demo_samples = demo_samples // module.diffusion.pretransform.downsampling_ratio - - noise = torch.randn([self.num_demos, module.diffusion.io_channels, demo_samples]).to(module.device) - - try: - with torch.cuda.amp.autocast(): - fakes = sample(module.diffusion_ema, noise, self.demo_steps, 0) - - if module.diffusion.pretransform is not None: - fakes = module.diffusion.pretransform.decode(fakes) - - # Put the demos together - fakes = rearrange(fakes, 'b d n -> d (b n)') - - log_dict = {} - - filename = f'demo_{trainer.global_step:08}.wav' - fakes = fakes.clamp(-1, 1).mul(32767).to(torch.int16).cpu() - torchaudio.save(filename, fakes, self.sample_rate) - - log_dict[f'demo'] = wandb.Audio(filename, - sample_rate=self.sample_rate, - caption=f'Reconstructed') - - log_dict[f'demo_melspec_left'] = wandb.Image(audio_spectrogram_image(fakes)) - - trainer.logger.experiment.log(log_dict) - - del fakes - - except Exception as e: - print(f'{type(e).__name__}: {e}') - finally: - gc.collect() - torch.cuda.empty_cache() - -class DiffusionCondTrainingWrapper(pl.LightningModule): - ''' - Wrapper for training a conditional audio diffusion model. - ''' - def __init__( - self, - model: ConditionedDiffusionModelWrapper, - lr: float = 1e-4, - causal_dropout: float = 0.0, - mask_padding: bool = False, - mask_padding_dropout: float = 0.2, - use_ema: bool = True - ): - super().__init__() - - self.diffusion = model - - if use_ema: - self.diffusion_ema = EMA( - self.diffusion.model, - beta=0.9999, - power=3/4, - update_every=1, - update_after_step=1, - include_online_model=False - ) - else: - self.diffusion_ema = None - - self.mask_padding = mask_padding - self.mask_padding_dropout = mask_padding_dropout - - self.lr = lr - - self.rng = torch.quasirandom.SobolEngine(1, scramble=True) - - self.causal_dropout = causal_dropout - - self.loss_modules = [ - MSELoss("v", - "targets", - weight=1.0, - mask_key="padding_mask" if self.mask_padding else None, - name="mse_loss" - ) - ] - - self.losses = MultiLoss(self.loss_modules) - - def configure_optimizers(self): - return optim.Adam([*self.diffusion.parameters()], lr=self.lr) - - def training_step(self, batch, batch_idx): - reals, metadata = batch - - p = Profiler() - - if reals.ndim == 4 and reals.shape[0] == 1: - reals = reals[0] - - # Draw uniformly distributed continuous timesteps - t = self.rng.draw(reals.shape[0])[:, 0].to(self.device) - - # Replace 1% of t with ones to ensure training on terminal SNR - t = torch.where(torch.rand_like(t) < 0.01, torch.ones_like(t), t) - - # Calculate the noise schedule parameters for those timesteps - alphas, sigmas = get_alphas_sigmas(t) - - diffusion_input = reals - - p.tick("setup") - - with torch.cuda.amp.autocast(): - conditioning = self.diffusion.conditioner(metadata, self.device) - - # If mask_padding is on, randomly drop the padding masks to allow for learning silence padding - use_padding_mask = self.mask_padding and random.random() > self.mask_padding_dropout - - # Create batch tensor of attention masks from the "mask" field of the metadata array - if use_padding_mask: - padding_masks = torch.stack([md["padding_mask"][0] for md in metadata], dim=0).to(self.device) # Shape (batch_size, sequence_length) - - p.tick("conditioning") - - if self.diffusion.pretransform is not None: - self.diffusion.pretransform.to(self.device) - - with torch.cuda.amp.autocast() and torch.set_grad_enabled(self.diffusion.pretransform.enable_grad): - diffusion_input = self.diffusion.pretransform.encode(diffusion_input) - p.tick("pretransform") - - # If mask_padding is on, interpolate the padding masks to the size of the pretransformed input - if use_padding_mask: - padding_masks = F.interpolate(padding_masks.unsqueeze(1).float(), size=diffusion_input.shape[2], mode="nearest").squeeze(1).bool() - - - # Combine the ground truth data and the noise - alphas = alphas[:, None, None] - sigmas = sigmas[:, None, None] - noise = torch.randn_like(diffusion_input) - noised_inputs = diffusion_input * alphas + noise * sigmas - targets = noise * alphas - diffusion_input * sigmas - - p.tick("noise") - - extra_args = {} - - if self.causal_dropout > 0.0: - extra_args["causal"] = random.random() < self.causal_dropout - - if use_padding_mask: - extra_args["mask"] = padding_masks - - with torch.cuda.amp.autocast(): - p.tick("amp") - v = self.diffusion(noised_inputs, t, cond=conditioning, cfg_dropout_prob = 0.1, **extra_args) - p.tick("diffusion") - - loss_info = { - "v": v, - "targets": targets, - "padding_mask": padding_masks if use_padding_mask else None, - } - - loss, losses = self.losses(loss_info) - - log_dict = { - 'train/loss': loss.detach(), - 'train/std_data': diffusion_input.std(), - } - - for loss_name, loss_value in losses.items(): - log_dict[f"train/{loss_name}"] = loss_value.detach() - - self.log_dict(log_dict, prog_bar=True, on_step=True) - p.tick("log") - #print(f"Profiler: {p}") - return loss - - def on_before_zero_grad(self, *args, **kwargs): - if self.diffusion_ema is not None: - self.diffusion_ema.update() - - def export_model(self, path, use_safetensors=False): - if self.diffusion_ema is not None: - self.diffusion.model = self.diffusion_ema.ema_model - - if use_safetensors: - save_file(self.diffusion.state_dict(), path) - else: - torch.save({"state_dict": self.diffusion.state_dict()}, path) - -class DiffusionCondDemoCallback(pl.Callback): - def __init__(self, - demo_every=2000, - num_demos=8, - sample_size=65536, - demo_steps=250, - sample_rate=48000, - demo_conditioning: tp.Optional[tp.Dict[str, tp.Any]] = {}, - demo_cfg_scales: tp.Optional[tp.List[int]] = [3, 5, 7], - demo_cond_from_batch: bool = False, - display_audio_cond: bool = False - ): - super().__init__() - - self.demo_every = demo_every - self.num_demos = num_demos - self.demo_samples = sample_size - self.demo_steps = demo_steps - self.sample_rate = sample_rate - self.last_demo_step = -1 - self.demo_conditioning = demo_conditioning - self.demo_cfg_scales = demo_cfg_scales - - # If true, the callback will use the metadata from the batch to generate the demo conditioning - self.demo_cond_from_batch = demo_cond_from_batch - - # If true, the callback will display the audio conditioning - self.display_audio_cond = display_audio_cond - - @rank_zero_only - @torch.no_grad() - def on_train_batch_end(self, trainer, module: DiffusionCondTrainingWrapper, outputs, batch, batch_idx): - - if (trainer.global_step - 1) % self.demo_every != 0 or self.last_demo_step == trainer.global_step: - return - - module.eval() - - print(f"Generating demo") - self.last_demo_step = trainer.global_step - - demo_samples = self.demo_samples - - demo_cond = self.demo_conditioning - - if self.demo_cond_from_batch: - # Get metadata from the batch - demo_cond = batch[1][:self.num_demos] - - if module.diffusion.pretransform is not None: - demo_samples = demo_samples // module.diffusion.pretransform.downsampling_ratio - - noise = torch.randn([self.num_demos, module.diffusion.io_channels, demo_samples]).to(module.device) - - try: - print("Getting conditioning") - with torch.cuda.amp.autocast(): - conditioning = module.diffusion.conditioner(demo_cond, module.device) - - cond_inputs = module.diffusion.get_conditioning_inputs(conditioning) - - log_dict = {} - - if self.display_audio_cond: - audio_inputs = torch.cat([cond["audio"] for cond in demo_cond], dim=0) - audio_inputs = rearrange(audio_inputs, 'b d n -> d (b n)') - - filename = f'demo_audio_cond_{trainer.global_step:08}.wav' - audio_inputs = audio_inputs.clamp(-1, 1).mul(32767).to(torch.int16).cpu() - torchaudio.save(filename, audio_inputs, self.sample_rate) - log_dict[f'demo_audio_cond'] = wandb.Audio(filename, sample_rate=self.sample_rate, caption="Audio conditioning") - log_dict[f"demo_audio_cond_melspec_left"] = wandb.Image(audio_spectrogram_image(audio_inputs)) - trainer.logger.experiment.log(log_dict) - - for cfg_scale in self.demo_cfg_scales: - - print(f"Generating demo for cfg scale {cfg_scale}") - - with torch.cuda.amp.autocast(): - model = module.diffusion_ema.model if module.diffusion_ema is not None else module.diffusion.model - - fakes = sample(model, noise, self.demo_steps, 0, **cond_inputs, cfg_scale=cfg_scale, batch_cfg=True) - if module.diffusion.pretransform is not None: - fakes = module.diffusion.pretransform.decode(fakes) - - # Put the demos together - fakes = rearrange(fakes, 'b d n -> d (b n)') - - log_dict = {} - - filename = f'demo_cfg_{cfg_scale}_{trainer.global_step:08}.wav' - fakes = fakes.clamp(-1, 1).mul(32767).to(torch.int16).cpu() - torchaudio.save(filename, fakes, self.sample_rate) - - log_dict[f'demo_cfg_{cfg_scale}'] = wandb.Audio(filename, - sample_rate=self.sample_rate, - caption=f'Reconstructed') - - log_dict[f'demo_melspec_left_cfg_{cfg_scale}'] = wandb.Image(audio_spectrogram_image(fakes)) - - trainer.logger.experiment.log(log_dict) - - del fakes - - except Exception as e: - raise e - finally: - gc.collect() - torch.cuda.empty_cache() - module.train() - -class DiffusionCondInpaintTrainingWrapper(pl.LightningModule): - ''' - Wrapper for training a conditional audio diffusion model. - ''' - def __init__( - self, - model: ConditionedDiffusionModelWrapper, - lr: float = 1e-4, - max_mask_segments = 10 - ): - super().__init__() - - self.diffusion = model - - self.diffusion_ema = EMA( - self.diffusion.model, - beta=0.9999, - power=3/4, - update_every=1, - update_after_step=1, - include_online_model=False - ) - - self.lr = lr - self.max_mask_segments = max_mask_segments - - self.rng = torch.quasirandom.SobolEngine(1, scramble=True) - - self.loss_modules = [ - MSELoss("v", - "targets", - weight=1.0, - name="mse_loss" - ) - ] - - self.losses = MultiLoss(self.loss_modules) - - def configure_optimizers(self): - return optim.Adam([*self.diffusion.parameters()], lr=self.lr) - - def random_mask(self, sequence, max_mask_length): - b, _, sequence_length = sequence.size() - - # Create a mask tensor for each batch element - masks = [] - - for i in range(b): - mask_type = random.randint(0, 2) - - if mask_type == 0: # Random mask with multiple segments - num_segments = random.randint(1, self.max_mask_segments) - max_segment_length = max_mask_length // num_segments - - segment_lengths = random.sample(range(1, max_segment_length + 1), num_segments) - - mask = torch.ones((1, 1, sequence_length)) - for length in segment_lengths: - mask_start = random.randint(0, sequence_length - length) - mask[:, :, mask_start:mask_start + length] = 0 - - elif mask_type == 1: # Full mask - mask = torch.zeros((1, 1, sequence_length)) - - elif mask_type == 2: # Causal mask - mask = torch.ones((1, 1, sequence_length)) - mask_length = random.randint(1, max_mask_length) - mask[:, :, -mask_length:] = 0 - - mask = mask.to(sequence.device) - masks.append(mask) - - # Concatenate the mask tensors into a single tensor - mask = torch.cat(masks, dim=0).to(sequence.device) - - # Apply the mask to the sequence tensor for each batch element - masked_sequence = sequence * mask - - return masked_sequence, mask - - def training_step(self, batch, batch_idx): - reals, metadata = batch - - p = Profiler() - - if reals.ndim == 4 and reals.shape[0] == 1: - reals = reals[0] - - # Draw uniformly distributed continuous timesteps - t = self.rng.draw(reals.shape[0])[:, 0].to(self.device) - - # Calculate the noise schedule parameters for those timesteps - alphas, sigmas = get_alphas_sigmas(t) - - diffusion_input = reals - - p.tick("setup") - - with torch.cuda.amp.autocast(): - conditioning = self.diffusion.conditioner(metadata, self.device) - - p.tick("conditioning") - - if self.diffusion.pretransform is not None: - self.diffusion.pretransform.to(self.device) - with torch.cuda.amp.autocast() and torch.set_grad_enabled(self.diffusion.pretransform.enable_grad): - diffusion_input = self.diffusion.pretransform.encode(diffusion_input) - p.tick("pretransform") - - # Max mask size is the full sequence length - max_mask_length = diffusion_input.shape[2] - - # Create a mask of random length for a random slice of the input - masked_input, mask = self.random_mask(diffusion_input, max_mask_length) - - conditioning['inpaint_mask'] = [mask] - conditioning['inpaint_masked_input'] = [masked_input] - - # Combine the ground truth data and the noise - alphas = alphas[:, None, None] - sigmas = sigmas[:, None, None] - noise = torch.randn_like(diffusion_input) - noised_inputs = diffusion_input * alphas + noise * sigmas - targets = noise * alphas - diffusion_input * sigmas - - p.tick("noise") - - with torch.cuda.amp.autocast(): - p.tick("amp") - v = self.diffusion(noised_inputs, t, cond=conditioning, cfg_dropout_prob = 0.1) - p.tick("diffusion") - - loss_info = { - "v": v, - "targets": targets - } - - loss, losses = self.losses(loss_info) - - log_dict = { - 'train/loss': loss.detach(), - 'train/std_data': diffusion_input.std(), - } - - for loss_name, loss_value in losses.items(): - log_dict[f"train/{loss_name}"] = loss_value.detach() - - self.log_dict(log_dict, prog_bar=True, on_step=True) - p.tick("log") - #print(f"Profiler: {p}") - return loss - - def on_before_zero_grad(self, *args, **kwargs): - self.diffusion_ema.update() - - def export_model(self, path): - self.diffusion.model = self.diffusion_ema.ema_model - - save_file(self.diffusion.state_dict(), path) - -class DiffusionCondInpaintDemoCallback(pl.Callback): - def __init__( - self, - demo_dl, - demo_every=2000, - demo_steps=250, - sample_size=65536, - sample_rate=48000, - demo_cfg_scales: tp.Optional[tp.List[int]] = [3, 5, 7] - ): - super().__init__() - self.demo_every = demo_every - self.demo_steps = demo_steps - self.demo_samples = sample_size - self.demo_dl = iter(demo_dl) - self.sample_rate = sample_rate - self.demo_cfg_scales = demo_cfg_scales - self.last_demo_step = -1 - - @rank_zero_only - @torch.no_grad() - def on_train_batch_end(self, trainer, module: DiffusionCondTrainingWrapper, outputs, batch, batch_idx): - if (trainer.global_step - 1) % self.demo_every != 0 or self.last_demo_step == trainer.global_step: - return - - self.last_demo_step = trainer.global_step - - try: - log_dict = {} - - demo_reals, metadata = next(self.demo_dl) - - # Remove extra dimension added by WebDataset - if demo_reals.ndim == 4 and demo_reals.shape[0] == 1: - demo_reals = demo_reals[0] - - demo_reals = demo_reals.to(module.device) - - - # Log the real audio - log_dict[f'demo_reals_melspec_left'] = wandb.Image(audio_spectrogram_image(rearrange(demo_reals, "b d n -> d (b n)").mul(32767).to(torch.int16).cpu())) - # log_dict[f'demo_reals'] = wandb.Audio(rearrange(demo_reals, "b d n -> d (b n)").mul(32767).to(torch.int16).cpu(), sample_rate=self.sample_rate, caption="demo reals") - - if module.diffusion.pretransform is not None: - module.diffusion.pretransform.to(module.device) - with torch.cuda.amp.autocast(): - demo_reals = module.diffusion.pretransform.encode(demo_reals) - - demo_samples = demo_reals.shape[2] - - # Get conditioning - conditioning = module.diffusion.conditioner(metadata, module.device) - - masked_input, mask = module.random_mask(demo_reals, demo_reals.shape[2]) - - conditioning['inpaint_mask'] = [mask] - conditioning['inpaint_masked_input'] = [masked_input] - - if module.diffusion.pretransform is not None: - log_dict[f'demo_masked_input'] = wandb.Image(tokens_spectrogram_image(masked_input.cpu())) - else: - log_dict[f'demo_masked_input'] = wandb.Image(audio_spectrogram_image(rearrange(masked_input, "b c t -> c (b t)").mul(32767).to(torch.int16).cpu())) - - cond_inputs = module.diffusion.get_conditioning_inputs(conditioning) - - noise = torch.randn([demo_reals.shape[0], module.diffusion.io_channels, demo_samples]).to(module.device) - - trainer.logger.experiment.log(log_dict) - - for cfg_scale in self.demo_cfg_scales: - - print(f"Generating demo for cfg scale {cfg_scale}") - fakes = sample(module.diffusion_ema.model, noise, self.demo_steps, 0, **cond_inputs, cfg_scale=cfg_scale, batch_cfg=True) - - if module.diffusion.pretransform is not None: - with torch.cuda.amp.autocast(): - fakes = module.diffusion.pretransform.decode(fakes) - - # Put the demos together - fakes = rearrange(fakes, 'b d n -> d (b n)') - - log_dict = {} - - filename = f'demo_cfg_{cfg_scale}_{trainer.global_step:08}.wav' - fakes = fakes.clamp(-1, 1).mul(32767).to(torch.int16).cpu() - torchaudio.save(filename, fakes, self.sample_rate) - - log_dict[f'demo_cfg_{cfg_scale}'] = wandb.Audio(filename, - sample_rate=self.sample_rate, - caption=f'Reconstructed') - - log_dict[f'demo_melspec_left_cfg_{cfg_scale}'] = wandb.Image(audio_spectrogram_image(fakes)) - - trainer.logger.experiment.log(log_dict) - except Exception as e: - print(f'{type(e).__name__}: {e}') - raise e - -class DiffusionAutoencoderTrainingWrapper(pl.LightningModule): - ''' - Wrapper for training a diffusion autoencoder - ''' - def __init__( - self, - model: DiffusionAutoencoder, - lr: float = 1e-4, - ema_copy = None, - use_reconstruction_loss: bool = False - ): - super().__init__() - - self.diffae = model - - self.diffae_ema = EMA( - self.diffae, - ema_model=ema_copy, - beta=0.9999, - power=3/4, - update_every=1, - update_after_step=1, - include_online_model=False - ) - - self.lr = lr - - self.rng = torch.quasirandom.SobolEngine(1, scramble=True) - - loss_modules = [ - MSELoss("v", - "targets", - weight=1.0, - name="mse_loss" - ) - ] - - self.use_reconstruction_loss = use_reconstruction_loss - - if use_reconstruction_loss: - scales = [2048, 1024, 512, 256, 128, 64, 32] - hop_sizes = [] - win_lengths = [] - overlap = 0.75 - for s in scales: - hop_sizes.append(int(s * (1 - overlap))) - win_lengths.append(s) - - sample_rate = model.sample_rate - - stft_loss_args = { - "fft_sizes": scales, - "hop_sizes": hop_sizes, - "win_lengths": win_lengths, - "perceptual_weighting": True - } - - out_channels = model.out_channels - - if model.pretransform is not None: - out_channels = model.pretransform.io_channels - - if out_channels == 2: - self.sdstft = auraloss.freq.SumAndDifferenceSTFTLoss(sample_rate=sample_rate, **stft_loss_args) - else: - self.sdstft = auraloss.freq.MultiResolutionSTFTLoss(sample_rate=sample_rate, **stft_loss_args) - - loss_modules.append( - AuralossLoss(self.sdstft, 'audio_reals', 'audio_pred', name='mrstft_loss', weight=0.1), # Reconstruction loss - ) - - self.losses = MultiLoss(loss_modules) - - def configure_optimizers(self): - return optim.Adam([*self.diffae.parameters()], lr=self.lr) - - def training_step(self, batch, batch_idx): - reals = batch[0] - - if reals.ndim == 4 and reals.shape[0] == 1: - reals = reals[0] - - loss_info = {} - - loss_info["audio_reals"] = reals - - if self.diffae.pretransform is not None: - with torch.no_grad(): - reals = self.diffae.pretransform.encode(reals) - - loss_info["reals"] = reals - - #Encode reals, skipping the pretransform since it was already applied - latents, encoder_info = self.diffae.encode(reals, return_info=True, skip_pretransform=True) - - loss_info["latents"] = latents - loss_info.update(encoder_info) - - if self.diffae.decoder is not None: - latents = self.diffae.decoder(latents) - - # Upsample latents to match diffusion length - if latents.shape[2] != reals.shape[2]: - latents = F.interpolate(latents, size=reals.shape[2], mode='nearest') - - loss_info["latents_upsampled"] = latents - - # Draw uniformly distributed continuous timesteps - t = self.rng.draw(reals.shape[0])[:, 0].to(self.device) - - # Calculate the noise schedule parameters for those timesteps - alphas, sigmas = get_alphas_sigmas(t) - - # Combine the ground truth data and the noise - alphas = alphas[:, None, None] - sigmas = sigmas[:, None, None] - noise = torch.randn_like(reals) - noised_reals = reals * alphas + noise * sigmas - targets = noise * alphas - reals * sigmas - - with torch.cuda.amp.autocast(): - v = self.diffae.diffusion(noised_reals, t, input_concat_cond=latents) - - loss_info.update({ - "v": v, - "targets": targets - }) - - if self.use_reconstruction_loss: - pred = noised_reals * alphas - v * sigmas - - loss_info["pred"] = pred - - if self.diffae.pretransform is not None: - pred = self.diffae.pretransform.decode(pred) - loss_info["audio_pred"] = pred - - loss, losses = self.losses(loss_info) - - log_dict = { - 'train/loss': loss.detach(), - 'train/std_data': reals.std(), - 'train/latent_std': latents.std(), - } - - for loss_name, loss_value in losses.items(): - log_dict[f"train/{loss_name}"] = loss_value.detach() - - self.log_dict(log_dict, prog_bar=True, on_step=True) - return loss - - def on_before_zero_grad(self, *args, **kwargs): - self.diffae_ema.update() - - def export_model(self, path, use_safetensors=False): - - model = self.diffae_ema.ema_model - - if use_safetensors: - save_file(model.state_dict(), path) - else: - torch.save({"state_dict": model.state_dict()}, path) - -class DiffusionAutoencoderDemoCallback(pl.Callback): - def __init__( - self, - demo_dl, - demo_every=2000, - demo_steps=250, - sample_size=65536, - sample_rate=48000 - ): - super().__init__() - self.demo_every = demo_every - self.demo_steps = demo_steps - self.demo_samples = sample_size - self.demo_dl = iter(demo_dl) - self.sample_rate = sample_rate - self.last_demo_step = -1 - - @rank_zero_only - @torch.no_grad() - def on_train_batch_end(self, trainer, module: DiffusionAutoencoderTrainingWrapper, outputs, batch, batch_idx): - if (trainer.global_step - 1) % self.demo_every != 0 or self.last_demo_step == trainer.global_step: - return - - self.last_demo_step = trainer.global_step - - demo_reals, _ = next(self.demo_dl) - - # Remove extra dimension added by WebDataset - if demo_reals.ndim == 4 and demo_reals.shape[0] == 1: - demo_reals = demo_reals[0] - - encoder_input = demo_reals - - encoder_input = encoder_input.to(module.device) - - demo_reals = demo_reals.to(module.device) - - with torch.no_grad() and torch.cuda.amp.autocast(): - latents = module.diffae_ema.ema_model.encode(encoder_input).float() - fakes = module.diffae_ema.ema_model.decode(latents, steps=self.demo_steps) - - #Interleave reals and fakes - reals_fakes = rearrange([demo_reals, fakes], 'i b d n -> (b i) d n') - - # Put the demos together - reals_fakes = rearrange(reals_fakes, 'b d n -> d (b n)') - - log_dict = {} - - filename = f'recon_{trainer.global_step:08}.wav' - reals_fakes = reals_fakes.clamp(-1, 1).mul(32767).to(torch.int16).cpu() - torchaudio.save(filename, reals_fakes, self.sample_rate) - - log_dict[f'recon'] = wandb.Audio(filename, - sample_rate=self.sample_rate, - caption=f'Reconstructed') - - log_dict[f'embeddings_3dpca'] = pca_point_cloud(latents) - log_dict[f'embeddings_spec'] = wandb.Image(tokens_spectrogram_image(latents)) - - log_dict[f'recon_melspec_left'] = wandb.Image(audio_spectrogram_image(reals_fakes)) - - if module.diffae_ema.ema_model.pretransform is not None: - with torch.no_grad() and torch.cuda.amp.autocast(): - initial_latents = module.diffae_ema.ema_model.pretransform.encode(encoder_input) - first_stage_fakes = module.diffae_ema.ema_model.pretransform.decode(initial_latents) - first_stage_fakes = rearrange(first_stage_fakes, 'b d n -> d (b n)') - first_stage_fakes = first_stage_fakes.clamp(-1, 1).mul(32767).to(torch.int16).cpu() - first_stage_filename = f'first_stage_{trainer.global_step:08}.wav' - torchaudio.save(first_stage_filename, first_stage_fakes, self.sample_rate) - - log_dict[f'first_stage_latents'] = wandb.Image(tokens_spectrogram_image(initial_latents)) - - log_dict[f'first_stage'] = wandb.Audio(first_stage_filename, - sample_rate=self.sample_rate, - caption=f'First Stage Reconstructed') - - log_dict[f'first_stage_melspec_left'] = wandb.Image(audio_spectrogram_image(first_stage_fakes)) - - - trainer.logger.experiment.log(log_dict) - - -class DiffusionPriorTrainingWrapper(pl.LightningModule): - ''' - Wrapper for training a diffusion prior for inverse problems - Prior types: - mono_stereo: The prior is conditioned on a mono version of the audio to generate a stereo version - ''' - def __init__( - self, - model: ConditionedDiffusionModelWrapper, - lr: float = 1e-4, - ema_copy = None, - prior_type: tp.Literal["mono_stereo"] = "mono_stereo" - ): - super().__init__() - - self.diffusion = model - - self.diffusion_ema = EMA( - self.diffusion, - ema_model=ema_copy, - beta=0.9999, - power=3/4, - update_every=1, - update_after_step=1, - include_online_model=False - ) - - self.lr = lr - - self.rng = torch.quasirandom.SobolEngine(1, scramble=True) - - loss_modules = [ - MSELoss("v", - "targets", - weight=1.0, - name="mse_loss" - ) - ] - - self.losses = MultiLoss(loss_modules) - - def configure_optimizers(self): - return optim.Adam([*self.diffusion.parameters()], lr=self.lr) - - def training_step(self, batch, batch_idx): - reals = batch[0] - - if reals.ndim == 4 and reals.shape[0] == 1: - reals = reals[0] - - loss_info = {} - - loss_info["audio_reals"] = reals - - if self.prior_type == "mono_stereo": - source = reals.mean(dim=1, keepdim=True).repeat(1, reals.shape[1], 1).to(self.device) - loss_info["audio_reals_mono"] = source - - if self.diffusion.pretransform is not None: - with torch.no_grad(): - reals = self.diffusion.pretransform.encode(reals) - - if self.prior_type == "mono_stereo": - source = self.diffusion.pretransform.encode(source) - - loss_info["reals"] = reals - - # Draw uniformly distributed continuous timesteps - t = self.rng.draw(reals.shape[0])[:, 0].to(self.device) - - # Calculate the noise schedule parameters for those timesteps - alphas, sigmas = get_alphas_sigmas(t) - - # Combine the ground truth data and the noise - alphas = alphas[:, None, None] - sigmas = sigmas[:, None, None] - noise = torch.randn_like(reals) - noised_reals = reals * alphas + noise * sigmas - targets = noise * alphas - reals * sigmas - - with torch.cuda.amp.autocast(): - - v = self.diffusion(noised_reals, t, cond={"source": [source]}) - - loss_info.update({ - "v": v, - "targets": targets - }) - - loss, losses = self.losses(loss_info) - - log_dict = { - 'train/loss': loss.detach(), - 'train/std_data': reals.std() - } - - for loss_name, loss_value in losses.items(): - log_dict[f"train/{loss_name}"] = loss_value.detach() - - self.log_dict(log_dict, prog_bar=True, on_step=True) - return loss - - def on_before_zero_grad(self, *args, **kwargs): - self.diffusion_ema.update() - - def export_model(self, path, use_safetensors=False): - - #model = self.diffusion_ema.ema_model - model = self.diffusion - - if use_safetensors: - save_file(model.state_dict(), path) - else: - torch.save({"state_dict": model.state_dict()}, path) - -class DiffusionPriorDemoCallback(pl.Callback): - def __init__( - self, - demo_dl, - demo_every=2000, - demo_steps=250, - sample_size=65536, - sample_rate=48000 - ): - super().__init__() - self.demo_every = demo_every - self.demo_steps = demo_steps - self.demo_samples = sample_size - self.demo_dl = iter(demo_dl) - self.sample_rate = sample_rate - self.last_demo_step = -1 - - @rank_zero_only - @torch.no_grad() - def on_train_batch_end(self, trainer, module: DiffusionAutoencoderTrainingWrapper, outputs, batch, batch_idx): - if (trainer.global_step - 1) % self.demo_every != 0 or self.last_demo_step == trainer.global_step: - return - - self.last_demo_step = trainer.global_step - - demo_reals, _ = next(self.demo_dl) - - # Remove extra dimension added by WebDataset - if demo_reals.ndim == 4 and demo_reals.shape[0] == 1: - demo_reals = demo_reals[0] - - demo_reals = demo_reals.to(module.device) - - encoder_input = demo_reals - - with torch.no_grad() and torch.cuda.amp.autocast(): - if module.prior_type == "mono_stereo" and encoder_input.shape[1] > 1: - source = encoder_input.mean(dim=1, keepdim=True).repeat(1, encoder_input.shape[1], 1).to(module.device) - - if module.diffusion.pretransform is not None: - source = module.diffusion.pretransform.encode(source) - - if module.diffusion.pretransform is not None: - encoder_input = module.diffusion.pretransform.encode(encoder_input) - - fakes = sample(module.diffusion_ema.model, torch.randn_like(encoder_input), self.demo_steps, 0, cond={"source": [source]}) - - if module.diffusion.pretransform is not None: - fakes = module.diffusion.pretransform.decode(fakes) - - #Interleave reals and fakes - reals_fakes = rearrange([demo_reals, fakes], 'i b d n -> (b i) d n') - - # Put the demos together - reals_fakes = rearrange(reals_fakes, 'b d n -> d (b n)') - - log_dict = {} - - filename = f'recon_{trainer.global_step:08}.wav' - reals_fakes = reals_fakes.clamp(-1, 1).mul(32767).to(torch.int16).cpu() - torchaudio.save(filename, reals_fakes, self.sample_rate) - - log_dict[f'recon'] = wandb.Audio(filename, - sample_rate=self.sample_rate, - caption=f'Reconstructed') - - log_dict[f'recon_melspec_left'] = wandb.Image(audio_spectrogram_image(reals_fakes)) - - trainer.logger.experiment.log(log_dict) \ No newline at end of file diff --git a/sonique/stable_audio_tools/training/factory.py b/sonique/stable_audio_tools/training/factory.py deleted file mode 100644 index 7de70075c751db3af400a585d106738df8c810e9..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/training/factory.py +++ /dev/null @@ -1,213 +0,0 @@ -import torch -from torch.nn import Parameter -from ..models.factory import create_model_from_config - -def create_training_wrapper_from_config(model_config, model): - model_type = model_config.get('model_type', None) - assert model_type is not None, 'model_type must be specified in model config' - - training_config = model_config.get('training', None) - assert training_config is not None, 'training config must be specified in model config' - - if model_type == 'autoencoder': - from .autoencoders import AutoencoderTrainingWrapper - - ema_copy = None - - if training_config.get("use_ema", False): - ema_copy = create_model_from_config(model_config) - ema_copy = create_model_from_config(model_config) # I don't know why this needs to be called twice but it broke when I called it once - # Copy each weight to the ema copy - for name, param in model.state_dict().items(): - if isinstance(param, Parameter): - # backwards compatibility for serialized parameters - param = param.data - ema_copy.state_dict()[name].copy_(param) - - use_ema = training_config.get("use_ema", False) - - latent_mask_ratio = training_config.get("latent_mask_ratio", 0.0) - - teacher_model = training_config.get("teacher_model", None) - if teacher_model is not None: - teacher_model = create_model_from_config(teacher_model) - teacher_model = teacher_model.eval().requires_grad_(False) - - teacher_model_ckpt = training_config.get("teacher_model_ckpt", None) - if teacher_model_ckpt is not None: - teacher_model.load_state_dict(torch.load(teacher_model_ckpt)["state_dict"]) - else: - raise ValueError("teacher_model_ckpt must be specified if teacher_model is specified") - - return AutoencoderTrainingWrapper( - model, - lr=training_config["learning_rate"], - warmup_steps=training_config.get("warmup_steps", 0), - encoder_freeze_on_warmup=training_config.get("encoder_freeze_on_warmup", False), - sample_rate=model_config["sample_rate"], - loss_config=training_config.get("loss_configs", None), - optimizer_configs=training_config.get("optimizer_configs", None), - use_ema=use_ema, - ema_copy=ema_copy if use_ema else None, - force_input_mono=training_config.get("force_input_mono", False), - latent_mask_ratio=latent_mask_ratio, - teacher_model=teacher_model - ) - elif model_type == 'diffusion_uncond': - from .diffusion import DiffusionUncondTrainingWrapper - return DiffusionUncondTrainingWrapper( - model, - lr=training_config["learning_rate"], - ) - elif model_type == 'diffusion_cond': - from .diffusion import DiffusionCondTrainingWrapper - return DiffusionCondTrainingWrapper( - model, - lr=training_config["learning_rate"], - causal_dropout=training_config.get("causal_dropout", 0.0), - mask_padding=training_config.get("mask_padding", False), - use_ema = training_config.get("use_ema", True), - ) - elif model_type == 'diffusion_prior': - from .diffusion import DiffusionPriorTrainingWrapper - - ema_copy = create_model_from_config(model_config) - - # Copy each weight to the ema copy - for name, param in model.state_dict().items(): - if isinstance(param, Parameter): - # backwards compatibility for serialized parameters - param = param.data - ema_copy.state_dict()[name].copy_(param) - - prior_type = training_config.get("prior_type", "mono_stereo") - - return DiffusionPriorTrainingWrapper( - model, - lr=training_config["learning_rate"], - ema_copy=ema_copy, - prior_type=prior_type - ) - elif model_type == 'diffusion_cond_inpaint': - from .diffusion import DiffusionCondInpaintTrainingWrapper - return DiffusionCondInpaintTrainingWrapper( - model, - lr=training_config["learning_rate"] - ) - elif model_type == 'diffusion_autoencoder': - from .diffusion import DiffusionAutoencoderTrainingWrapper - - ema_copy = create_model_from_config(model_config) - - # Copy each weight to the ema copy - for name, param in model.state_dict().items(): - if isinstance(param, Parameter): - # backwards compatibility for serialized parameters - param = param.data - ema_copy.state_dict()[name].copy_(param) - - return DiffusionAutoencoderTrainingWrapper( - model, - ema_copy=ema_copy, - lr=training_config["learning_rate"], - use_reconstruction_loss=training_config.get("use_reconstruction_loss", False) - ) - elif model_type == 'musicgen': - from .musicgen import MusicGenTrainingWrapper - - ema_copy = create_model_from_config(model_config).lm - - for name, param in model.lm.state_dict().items(): - if isinstance(param, Parameter): - # backwards compatibility for serialized parameters - param = param.data - ema_copy.state_dict()[name].copy_(param) - - return MusicGenTrainingWrapper( - model, - ema_copy=ema_copy, - lr=training_config["learning_rate"] - ) - else: - raise NotImplementedError(f'Unknown model type: {model_type}') - -def create_demo_callback_from_config(model_config, **kwargs): - model_type = model_config.get('model_type', None) - assert model_type is not None, 'model_type must be specified in model config' - - training_config = model_config.get('training', None) - assert training_config is not None, 'training config must be specified in model config' - - demo_config = training_config.get("demo", {}) - - if model_type == 'autoencoder': - from .autoencoders import AutoencoderDemoCallback - return AutoencoderDemoCallback( - demo_every=demo_config.get("demo_every", 2000), - sample_size=model_config["sample_size"], - sample_rate=model_config["sample_rate"], - **kwargs - ) - elif model_type == 'diffusion_uncond': - from .diffusion import DiffusionUncondDemoCallback - return DiffusionUncondDemoCallback( - demo_every=demo_config.get("demo_every", 2000), - demo_steps=demo_config.get("demo_steps", 250), - sample_rate=model_config["sample_rate"] - ) - elif model_type == "diffusion_autoencoder": - from .diffusion import DiffusionAutoencoderDemoCallback - return DiffusionAutoencoderDemoCallback( - demo_every=demo_config.get("demo_every", 2000), - demo_steps=demo_config.get("demo_steps", 250), - sample_size=model_config["sample_size"], - sample_rate=model_config["sample_rate"], - **kwargs - ) - elif model_type == "diffusion_prior": - from .diffusion import DiffusionPriorDemoCallback - return DiffusionPriorDemoCallback( - demo_every=demo_config.get("demo_every", 2000), - demo_steps=demo_config.get("demo_steps", 250), - sample_size=model_config["sample_size"], - sample_rate=model_config["sample_rate"], - **kwargs - ) - elif model_type == "diffusion_cond": - from .diffusion import DiffusionCondDemoCallback - - return DiffusionCondDemoCallback( - demo_every=demo_config.get("demo_every", 2000), - sample_size=model_config["sample_size"], - sample_rate=model_config["sample_rate"], - demo_steps=demo_config.get("demo_steps", 250), - num_demos=demo_config["num_demos"], - demo_cfg_scales=demo_config["demo_cfg_scales"], - demo_conditioning=demo_config.get("demo_cond", {}), - demo_cond_from_batch=demo_config.get("demo_cond_from_batch", False), - display_audio_cond=demo_config.get("display_audio_cond", False), - ) - elif model_type == "diffusion_cond_inpaint": - from .diffusion import DiffusionCondInpaintDemoCallback - - return DiffusionCondInpaintDemoCallback( - demo_every=demo_config.get("demo_every", 2000), - sample_size=model_config["sample_size"], - sample_rate=model_config["sample_rate"], - demo_steps=demo_config.get("demo_steps", 250), - demo_cfg_scales=demo_config["demo_cfg_scales"], - **kwargs - ) - elif model_type == "musicgen": - from .musicgen import MusicGenDemoCallback - - return MusicGenDemoCallback( - demo_every=demo_config.get("demo_every", 2000), - sample_size=model_config["sample_size"], - sample_rate=model_config["sample_rate"], - demo_cfg_scales=demo_config["demo_cfg_scales"], - demo_conditioning=demo_config["demo_cond"], - **kwargs - ) - else: - raise NotImplementedError(f'Unknown model type: {model_type}') \ No newline at end of file diff --git a/sonique/stable_audio_tools/training/losses.py b/sonique/stable_audio_tools/training/losses.py deleted file mode 100644 index 55b154615d833f68ecc7283a7f78d6a4ab9def31..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/training/losses.py +++ /dev/null @@ -1,101 +0,0 @@ -import typing as tp - -from torch.nn import functional as F -from torch import nn - -class LossModule(nn.Module): - def __init__(self, name: str, weight: float = 1.0): - super().__init__() - - self.name = name - self.weight = weight - - def forward(self, info, *args, **kwargs): - raise NotImplementedError - -class ValueLoss(LossModule): - def __init__(self, key: str, name, weight: float = 1.0): - super().__init__(name=name, weight=weight) - - self.key = key - - def forward(self, info): - return self.weight * info[self.key] - -class L1Loss(LossModule): - def __init__(self, key_a: str, key_b: str, weight: float = 1.0, mask_key: str = None, name: str = 'l1_loss'): - super().__init__(name=name, weight=weight) - - self.key_a = key_a - self.key_b = key_b - - self.mask_key = mask_key - - def forward(self, info): - mse_loss = F.l1_loss(info[self.key_a], info[self.key_b], reduction='none') - - if self.mask_key is not None and self.mask_key in info: - mse_loss = mse_loss[info[self.mask_key]] - - mse_loss = mse_loss.mean() - - return self.weight * mse_loss - -class MSELoss(LossModule): - def __init__(self, key_a: str, key_b: str, weight: float = 1.0, mask_key: str = None, name: str = 'mse_loss'): - super().__init__(name=name, weight=weight) - - self.key_a = key_a - self.key_b = key_b - - self.mask_key = mask_key - - def forward(self, info): - mse_loss = F.mse_loss(info[self.key_a], info[self.key_b], reduction='none') - - if self.mask_key is not None and self.mask_key in info and info[self.mask_key] is not None: - mask = info[self.mask_key] - - if mask.ndim == 2 and mse_loss.ndim == 3: - mask = mask.unsqueeze(1) - - if mask.shape[1] != mse_loss.shape[1]: - mask = mask.repeat(1, mse_loss.shape[1], 1) - - mse_loss = mse_loss[mask] - - mse_loss = mse_loss.mean() - - return self.weight * mse_loss - -class AuralossLoss(LossModule): - def __init__(self, auraloss_module, input_key: str, target_key: str, name: str, weight: float = 1): - super().__init__(name, weight) - - self.auraloss_module = auraloss_module - - self.input_key = input_key - self.target_key = target_key - - def forward(self, info): - loss = self.auraloss_module(info[self.input_key], info[self.target_key]) - - return self.weight * loss - -class MultiLoss(nn.Module): - def __init__(self, losses: tp.List[LossModule]): - super().__init__() - - self.losses = nn.ModuleList(losses) - - def forward(self, info): - total_loss = 0 - - losses = {} - - for loss_module in self.losses: - module_loss = loss_module(info) - total_loss += module_loss - losses[loss_module.name] = module_loss - - return total_loss, losses \ No newline at end of file diff --git a/sonique/stable_audio_tools/training/musicgen.py b/sonique/stable_audio_tools/training/musicgen.py deleted file mode 100644 index 9893a7478bdf2e06f0ac1c2c2921609070299b7a..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/training/musicgen.py +++ /dev/null @@ -1,231 +0,0 @@ -import pytorch_lightning as pl -import sys, gc -import random -import torch -import torchaudio -import typing as tp -import wandb - -from aeiou.viz import pca_point_cloud, audio_spectrogram_image, tokens_spectrogram_image -from ema_pytorch import EMA -from einops import rearrange -from torch import optim -from torch.nn import functional as F -from pytorch_lightning.utilities.rank_zero import rank_zero_only - -from audiocraft.models import MusicGen -from audiocraft.modules.conditioners import ClassifierFreeGuidanceDropout, ConditioningAttributes - -from time import time - -class Profiler: - - def __init__(self): - self.ticks = [[time(), None]] - - def tick(self, msg): - self.ticks.append([time(), msg]) - - def __repr__(self): - rep = 80 * "=" + "\n" - for i in range(1, len(self.ticks)): - msg = self.ticks[i][1] - ellapsed = self.ticks[i][0] - self.ticks[i - 1][0] - rep += msg + f": {ellapsed*1000:.2f}ms\n" - rep += 80 * "=" + "\n\n\n" - return rep - - -class MusicGenTrainingWrapper(pl.LightningModule): - def __init__(self, musicgen_model, lr = 1e-4, ema_copy=None): - super().__init__() - - self.musicgen_model: MusicGen = musicgen_model - - self.musicgen_model.compression_model.requires_grad_(False) - - self.lm = self.musicgen_model.lm - - self.lm.to(torch.float32).train().requires_grad_(True) - - self.lm_ema = EMA(self.lm, ema_model=ema_copy, beta=0.99, update_every=10) - - self.cfg_dropout = ClassifierFreeGuidanceDropout(0.1) - - self.lr = lr - - def configure_optimizers(self): - optimizer = optim.AdamW([*self.lm.parameters()], lr=self.lr, betas=(0.9, 0.95), weight_decay=0.1) - - return optimizer - - # Copied and modified from https://github.com/facebookresearch/audiocraft/blob/main/audiocraft/solvers/musicgen.py under MIT license - # License can be found in LICENSES/LICENSE_META.txt - - def _compute_cross_entropy( - self, logits: torch.Tensor, targets: torch.Tensor, mask: torch.Tensor - ) -> tp.Tuple[torch.Tensor, tp.List[torch.Tensor]]: - """Compute cross entropy between multi-codebook targets and model's logits. - The cross entropy is computed per codebook to provide codebook-level cross entropy. - Valid timesteps for each of the codebook are pulled from the mask, where invalid - timesteps are set to 0. - - Args: - logits (torch.Tensor): Model's logits of shape [B, K, T, card]. - targets (torch.Tensor): Target codes, of shape [B, K, T]. - mask (torch.Tensor): Mask for valid target codes, of shape [B, K, T]. - Returns: - ce (torch.Tensor): Cross entropy averaged over the codebooks - ce_per_codebook (list of torch.Tensor): Cross entropy per codebook (detached). - """ - B, K, T = targets.shape - assert logits.shape[:-1] == targets.shape - assert mask.shape == targets.shape - ce = torch.zeros([], device=targets.device) - ce_per_codebook: tp.List[torch.Tensor] = [] - for k in range(K): - logits_k = logits[:, k, ...].contiguous().view(-1, logits.size(-1)) # [B x T, card] - targets_k = targets[:, k, ...].contiguous().view(-1) # [B x T] - mask_k = mask[:, k, ...].contiguous().view(-1) # [B x T] - ce_targets = targets_k[mask_k] - ce_logits = logits_k[mask_k] - q_ce = F.cross_entropy(ce_logits, ce_targets) - ce += q_ce - ce_per_codebook.append(q_ce.detach()) - # average cross entropy across codebooks - ce = ce / K - return ce, ce_per_codebook - - def training_step(self, batch, batch_idx): - reals, metadata = batch - - if reals.ndim == 4 and reals.shape[0] == 1: - reals = reals[0] - - # Convert reals to mono if necessary - if self.musicgen_model.audio_channels == 1: - reals = reals.mean(dim=1, keepdim=True) - - self.musicgen_model.compression_model.to(self.device).eval() - self.lm.to(self.device).train() - self.lm.condition_provider.to(self.device).eval() - - self.lm.condition_provider.conditioners["description"].device = self.device - self.lm.condition_provider.conditioners["description"].t5.to(self.device).eval() - - with torch.cuda.amp.autocast(): - - codes, _ = self.musicgen_model.compression_model.encode(reals) # [b, k, t] - - attributes = [ConditioningAttributes(text={'description': md["prompt"][0][:512]}) for md in metadata] - attributes = self.lm.cfg_dropout(attributes) - attributes = self.lm.att_dropout(attributes) - tokenized = self.lm.condition_provider.tokenize(attributes) - - with torch.cuda.amp.autocast(enabled=False): - condition_tensors = self.lm.condition_provider(tokenized) - - lm_output = self.lm.compute_predictions( - codes=codes, - conditions = [], - condition_tensors = condition_tensors, - ) - - logits = lm_output.logits # [b, k, t, c] - logits_mask = lm_output.mask # [b, k, t] - - cross_entropy, cross_entropy_per_codebook = self._compute_cross_entropy(logits, codes, logits_mask) - - loss = cross_entropy - - log_dict = { - 'train/loss': loss.detach(), - 'train/cross_entropy': cross_entropy.detach(), - 'train/perplexity': torch.exp(cross_entropy).detach(), - } - - for k, ce_q in enumerate(cross_entropy_per_codebook): - log_dict[f'cross_entropy_q{k + 1}'] = ce_q - log_dict[f'perplexity_q{k + 1}'] = torch.exp(ce_q) - - self.log_dict(log_dict, prog_bar=True, on_step=True) - return loss - - def on_before_zero_grad(self, *args, **kwargs): - self.lm_ema.update() - - def export_model(self, path): - self.musicgen_model.lm = self.lm_ema.ema_model - export_state_dict = {"state_dict": self.musicgen_model.state_dict()} - - torch.save(export_state_dict, path) - -class MusicGenDemoCallback(pl.Callback): - def __init__(self, - demo_every=2000, - num_demos=8, - sample_size=65536, - sample_rate=48000, - demo_conditioning: tp.Optional[tp.Dict[str, tp.Any]] = None, - demo_cfg_scales: tp.Optional[tp.List[int]] = [3, 5, 7], - **kwargs - ): - super().__init__() - - self.demo_every = demo_every - self.num_demos = num_demos - self.demo_samples = sample_size - self.sample_rate = sample_rate - self.last_demo_step = -1 - self.demo_conditioning = demo_conditioning - self.demo_cfg_scales = demo_cfg_scales - - @rank_zero_only - @torch.no_grad() - def on_train_batch_end(self, trainer, module: MusicGenTrainingWrapper, outputs, batch, batch_idx): - - if (trainer.global_step - 1) % self.demo_every != 0 or self.last_demo_step == trainer.global_step: - return - - module.eval() - - print(f"Generating demo") - self.last_demo_step = trainer.global_step - - demo_length_sec = self.demo_samples // self.sample_rate - - try: - print("Getting conditioning") - - prompts = [md["prompt"][:512] for md in self.demo_conditioning] - - for cfg_scale in self.demo_cfg_scales: - - module.musicgen_model.set_generation_params(duration=demo_length_sec, cfg_coef=cfg_scale) - - print(f"Generating demo for cfg scale {cfg_scale}") - fakes = module.musicgen_model.generate(prompts, progress=True) - - # Put the demos together - fakes = rearrange(fakes, 'b d n -> d (b n)') - - log_dict = {} - - filename = f'demo_cfg_{cfg_scale}_{trainer.global_step:08}.wav' - fakes = fakes.clamp(-1, 1).mul(32767).to(torch.int16).cpu() - torchaudio.save(filename, fakes, self.sample_rate) - - log_dict[f'demo_cfg_{cfg_scale}'] = wandb.Audio(filename, - sample_rate=self.sample_rate, - caption=f'Reconstructed') - - log_dict[f'demo_melspec_left_cfg_{cfg_scale}'] = wandb.Image(audio_spectrogram_image(fakes)) - - trainer.logger.experiment.log(log_dict) - - except Exception as e: - raise e - finally: - gc.collect() - torch.cuda.empty_cache() - module.train() \ No newline at end of file diff --git a/sonique/stable_audio_tools/training/utils.py b/sonique/stable_audio_tools/training/utils.py deleted file mode 100644 index 66bc5b16c880913b2bc69288cd29f3a137fe9a8f..0000000000000000000000000000000000000000 --- a/sonique/stable_audio_tools/training/utils.py +++ /dev/null @@ -1,104 +0,0 @@ -import torch -import os - -def get_rank(): - """Get rank of current process.""" - - print(os.environ.keys()) - - if "SLURM_PROCID" in os.environ: - return int(os.environ["SLURM_PROCID"]) - - if not torch.distributed.is_available() or not torch.distributed.is_initialized(): - return 0 - - return torch.distributed.get_rank() - -class InverseLR(torch.optim.lr_scheduler._LRScheduler): - """Implements an inverse decay learning rate schedule with an optional exponential - warmup. When last_epoch=-1, sets initial lr as lr. - inv_gamma is the number of steps/epochs required for the learning rate to decay to - (1 / 2)**power of its original value. - Args: - optimizer (Optimizer): Wrapped optimizer. - inv_gamma (float): Inverse multiplicative factor of learning rate decay. Default: 1. - power (float): Exponential factor of learning rate decay. Default: 1. - warmup (float): Exponential warmup factor (0 <= warmup < 1, 0 to disable) - Default: 0. - final_lr (float): The final learning rate. Default: 0. - last_epoch (int): The index of last epoch. Default: -1. - verbose (bool): If ``True``, prints a message to stdout for - each update. Default: ``False``. - """ - - def __init__(self, optimizer, inv_gamma=1., power=1., warmup=0., final_lr=0., - last_epoch=-1, verbose=False): - self.inv_gamma = inv_gamma - self.power = power - if not 0. <= warmup < 1: - raise ValueError('Invalid value for warmup') - self.warmup = warmup - self.final_lr = final_lr - super().__init__(optimizer, last_epoch, verbose) - - def get_lr(self): - if not self._get_lr_called_within_step: - import warnings - warnings.warn("To get the last learning rate computed by the scheduler, " - "please use `get_last_lr()`.") - - return self._get_closed_form_lr() - - def _get_closed_form_lr(self): - warmup = 1 - self.warmup ** (self.last_epoch + 1) - lr_mult = (1 + self.last_epoch / self.inv_gamma) ** -self.power - return [warmup * max(self.final_lr, base_lr * lr_mult) - for base_lr in self.base_lrs] - -def copy_state_dict(model, state_dict): - """Load state_dict to model, but only for keys that match exactly. - - Args: - model (nn.Module): model to load state_dict. - state_dict (OrderedDict): state_dict to load. - """ - model_state_dict = model.state_dict() - for key in state_dict: - if key in model_state_dict and state_dict[key].shape == model_state_dict[key].shape: - if isinstance(state_dict[key], torch.nn.Parameter): - # backwards compatibility for serialized parameters - state_dict[key] = state_dict[key].data - model_state_dict[key] = state_dict[key] - - model.load_state_dict(model_state_dict, strict=False) - -def create_optimizer_from_config(optimizer_config, parameters): - """Create optimizer from config. - - Args: - parameters (iterable): parameters to optimize. - optimizer_config (dict): optimizer config. - - Returns: - torch.optim.Optimizer: optimizer. - """ - optimizer_fn = getattr(torch.optim, optimizer_config["type"]) - optimizer = optimizer_fn(parameters, **optimizer_config["config"]) - return optimizer - -def create_scheduler_from_config(scheduler_config, optimizer): - """Create scheduler from config. - - Args: - scheduler_config (dict): scheduler config. - optimizer (torch.optim.Optimizer): optimizer. - - Returns: - torch.optim.lr_scheduler._LRScheduler: scheduler. - """ - if scheduler_config["type"] == "InverseLR": - scheduler_fn = InverseLR - else: - scheduler_fn = getattr(torch.optim.lr_scheduler, scheduler_config["type"]) - scheduler = scheduler_fn(optimizer, **scheduler_config["config"]) - return scheduler \ No newline at end of file