Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- sjdtree/data/prompts/T2I-CompBench_val.jsonAdded
- sjdtree/data/prompts/captions_train2017_extracted.jsonAdded
- sjdtree/data/prompts/captions_val2017.jsonAdded
- sjdtree/data/prompts/captions_val2017_longest.jsonAdded
- sjdtree/data/prompts/captions_val_2014.jsonAdded
- sjdtree/data/prompts/combined_data.jsonAdded
- sjdtree/data/prompts/preprocess.pyAdded+22
- sjdtree/dataset_tools/dataset_templates.pyAdded+320
- sjdtree/dataset_tools/multi_gpu_dataframe_split.pyAdded+93
- sjdtree/dataset_tools/multi_gpu_infer_with_prompt.pyAdded+196
- sjdtree/emu3/__init__.pyAdded
- sjdtree/emu3/__pycache__/__init__.cpython-310.pycAdded
- sjdtree/emu3/mllm/__init__.pyAdded+61
- sjdtree/emu3/mllm/__pycache__/__init__.cpython-310.pycAdded
- sjdtree/emu3/mllm/__pycache__/processing_emu3.cpython-310.pycAdded
- sjdtree/emu3/mllm/__pycache__/utils_emu3.cpython-310.pycAdded
- sjdtree/emu3/mllm/configuration_emu3.pyAdded+213
- sjdtree/emu3/mllm/modeling_emu3.pyAdded+1343
- sjdtree/emu3/mllm/processing_emu3.pyAdded+299
- sjdtree/emu3/mllm/tokenization_emu3.pyAdded+294
- sjdtree/emu3/mllm/utils_emu3.pyAdded+62
- sjdtree/emu3/tokenizer/__init__.pyAdded+70
- sjdtree/emu3/tokenizer/configuration_emu3visionvq.pyAdded+106
- sjdtree/emu3/tokenizer/image_processing_emu3visionvq.pyAdded+442
- sjdtree/emu3/tokenizer/modeling_emu3visionvq.pyAdded+822
- sjdtree/llamagen/__init__.pyAdded
- sjdtree/llamagen/language/README.mdAdded+14
- sjdtree/llamagen/language/extract_t5_feature.pyAdded+129
- sjdtree/llamagen/language/t5.pyAdded+205
- sjdtree/llamagen/llamagen.pyAdded+504
- sjdtree/llamagen/llamagen_solver.pyAdded+476
- sjdtree/llamagen/tokenizer/consistencydecoder/README.mdAdded+14
- sjdtree/llamagen/tokenizer/consistencydecoder/cd_demo.pyAdded+57
- sjdtree/llamagen/tokenizer/consistencydecoder/reconstruction_cd_ddp.pyAdded+208
- sjdtree/llamagen/tokenizer/tokenizer_image/discriminator.pyAdded+255
- sjdtree/llamagen/tokenizer/tokenizer_image/discriminator_patchgan.pyAdded+152
- sjdtree/llamagen/tokenizer/tokenizer_image/discriminator_stylegan.pyAdded+101
- sjdtree/llamagen/tokenizer/tokenizer_image/lpips.pyAdded+164
- sjdtree/llamagen/tokenizer/tokenizer_image/reconstruction_vq_ddp.pyAdded+197
- sjdtree/llamagen/tokenizer/tokenizer_image/vq_demo.pyAdded+84
- sjdtree/llamagen/tokenizer/tokenizer_image/vq_loss.pyAdded+168
- sjdtree/llamagen/tokenizer/tokenizer_image/vq_model.pyAdded+424
- sjdtree/llamagen/tokenizer/tokenizer_image/vq_model_hf.pyAdded+17
- sjdtree/llamagen/tokenizer/tokenizer_image/vq_train.pyAdded+316
- sjdtree/llamagen/tokenizer/vae/README.mdAdded+14
- sjdtree/llamagen/tokenizer/vae/reconstruction_vae_ddp.pyAdded+210
- sjdtree/llamagen/tokenizer/vae/sd_vae_demo.pyAdded+57
- sjdtree/llamagen/tokenizer/validation/val_ddp.pyAdded+165
- sjdtree/llamagen/tokenizer/vqgan/README.mdAdded+21
- sjdtree/llamagen/tokenizer/vqgan/configs/vqgan_imagenet_f16_1024.yamlAdded+32
12345678910111213141516171819202122import jsonimport csv
with open('captions_val2017.json', 'r') as f: captions_data = json.load(f)
captions_by_image_id = {}for item in captions_data['annotations']: image_id = item['image_id'] if image_id not in captions_by_image_id: captions_by_image_id[image_id] = item['caption'] else: if len(captions_by_image_id[image_id]) < len(item['caption']): captions_by_image_id[image_id] = item['caption'] else: continue
captions = list(captions_by_image_id.values())print(len(captions))
with open('captions_val2017_longest.json', 'w') as f_out: json.dump(captions, f_out, indent=4)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320import osimport randomfrom datetime import datetime
import pandas as pdfrom torch.utils.data import Datasetimport torchvision.transforms as Timport torchimport numpy as np
import einopsfrom PIL import Image
from .multi_gpu_dataframe_split import split_dataframe_for_gpu, split_dataframe_for_node, split_datalist_for_gpu
def center_crop(width, height, img): resample = {'box': Image.BOX, 'lanczos': Image.LANCZOS}['lanczos'] crop = np.min(img.shape[:2]) img = img[(img.shape[0] - crop) // 2: (img.shape[0] + crop) // 2, (img.shape[1] - crop) // 2: (img.shape[1] + crop) // 2] try: img = Image.fromarray(img, 'RGB') except: img = Image.fromarray(img) img = img.resize((width, height), resample) return np.array(img).astype(np.uint8)
class PartiPromptsMultiGPUBench(Dataset):
def __init__( self, annFile, gpu_id, gpu_ids, node_id, node_ids, output_dir=None, data_len=0, ): csv_file = annFile print(f"Loading PartiPrompts from {csv_file} for GPU {gpu_id}, Node {node_id}") if data_len != 0: self.df = pd.read_csv(csv_file, sep='\t', nrows=data_len) else: self.df = pd.read_csv(csv_file, sep='\t') self.csv_file_base_name = os.path.basename(csv_file)
self.not_name_char = [ '\"', "'", "(", ")", ":", ";", ",", ".", "!", "?", ">", "<", "[", "]", "{", "}", "|", "\\", "/", "@", "#", "$", "%", "^", "&", "*", "~", "`", "=", "+", "-", "_", ]
self.prompt_dict = self.check_all_prompts()
self.df = split_dataframe_for_gpu(self.df, gpu_id, gpu_ids, node_id, node_ids) def __len__(self): return len(self.df) def __getitem__(self, idx): prompt = self.df.iloc[idx]['Prompt'] # prompt = self.clean_prompt(prompt) prompt_idx = self.prompt_dict[ prompt ]
return prompt, prompt_idx
def clean_prompt(self, prompt): prompt = prompt.replace("\n", " ") prompt = prompt.replace("\t", " ") prompt = prompt.replace("\r", " ") prompt = prompt.replace(" ", " ") prompt = prompt.strip() prompt = prompt.lower() for char in self.not_name_char: prompt = prompt.replace(char, " ") return prompt def check_all_prompts(self): prompt_dict = dict() max_len = 0 for idx in range(len(self.df)): prompt = self.df.iloc[idx]['Prompt'] # prompt = self.clean_prompt(prompt) prompt_dict[prompt] = idx max_len = max(max_len, len(prompt)) print(f"Number of unique prompts: {len(prompt_dict)} | Max prompt length: {max_len}") return prompt_dict
class PartiPromptsMultiGPUBenchCOCOFormat(PartiPromptsMultiGPUBench): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.anno = dict() self.anno["annotations"] = [] for idx in range(len(self.df)): self.anno["annotations"].append({ "id": idx, "caption": self.df.iloc[idx]['Prompt'], })
class MSCOCODatabase(Dataset): def __init__( self, root='data/coco/val2017', annFile='data/coco/annotations/captions_val2017.json', size=None, **kwargs, ): from pycocotools.coco import COCO self.root = root self.height = self.width = size self.coco = COCO(annFile) self.keys = list(sorted(self.coco.imgs.keys()))
def _load_image(self, key: int): path = self.coco.loadImgs(key)[0]["file_name"] return Image.open(os.path.join(self.root, path)).convert("RGB")
def _load_target(self, key: int): return self.coco.loadAnns(self.coco.getAnnIds(key))
def __len__(self): return len(self.keys)
def __getitem__(self, index): key = self.keys[index] image = self._load_image(key) image = np.array(image).astype(np.uint8) image = center_crop(self.width, self.height, image).astype(np.float32) image = (image / 127.5 - 1.0).astype(np.float32) image = einops.rearrange(image, 'h w c -> c h w') anns = self._load_target(key) target = [] for ann in anns: target.append(ann['caption'])
return image, target
class MSCOCOPromptBench(MSCOCODatabase): def __init__( self, gpu_id, gpu_ids, node_id, node_ids, *args, output_dir=None, **kwargs, ): super().__init__(*args, **kwargs) self._init_coco_dataset_dict(gpu_id, gpu_ids, node_id, node_ids) def _init_coco_dataset_dict(self, gpu_id, gpu_ids, node_id, node_ids): keys = self.keys
max_relative_id = 0 max_prompt_len = 0 self.anno = dict() self.anno["annotations"] = [] for key in keys: target = [] ids = [] for i, ann in enumerate(self._load_target(key)): if max_prompt_len < len(ann['caption']): max_prompt_len = len(ann['caption']) max_relative_id = i target.append(ann['caption']) ids.append(ann['id']) prompt = target[max_relative_id] prompt_idx = ids[max_relative_id]
self.anno["annotations"].append({ "id": prompt_idx, "caption": prompt, }) self.anno_dict_keys = list(range(len(self.anno["annotations"]))) self.anno_dict_keys = split_datalist_for_gpu( self.anno_dict_keys, gpu_id, gpu_ids, node_id, node_ids ) def __len__(self): return len(self.anno_dict_keys) def __getitem__(self, index): key = self.anno_dict_keys[index]
prompt_dict = self.anno["annotations"][key] prompt = prompt_dict["caption"] prompt_idx = prompt_dict["id"]
return prompt, prompt_idx
class MSCOCODatabase_DIY(Dataset): def __init__( self, root='data/coco/val2017', annFile='data/coco/annotations/captions_val2017.json', size=None, **kwargs, ): from pycocotools.coco import COCO self.root = root self.height = self.width = size self.coco = COCO(annFile) self.keys = self.coco.getImgIds() #list(sorted(self.coco.imgs.keys()))
def _load_image(self, key: int):# 获取图片文件名 path = self.coco.loadImgs(key)[0]["file_name"] return Image.open(os.path.join(self.root, path)).convert("RGB")
def _load_target(self, key: int): return self.coco.loadAnns(self.coco.getAnnIds(imgIds=key))
def __len__(self): return len(self.keys)
def __getitem__(self, index): key = self.keys[index] image = self._load_image(key) # 获取图片文件名 image = np.array(image).astype(np.uint8) image = center_crop(self.width, self.height, image).astype(np.float32) image = (image / 127.5 - 1.0).astype(np.float32) image = einops.rearrange(image, 'h w c -> c h w') anns = self._load_target(key) target = [] for ann in anns: target.append(ann['caption'])
return image, target
class MSCOCOPromptBench_DIY(MSCOCODatabase_DIY): def __init__( self, gpu_id, gpu_ids, node_id, node_ids, *args, output_dir=None, id_set=None, **kwargs, ): super().__init__(*args, **kwargs) self.id_set = id_set self._init_coco_dataset_dict(gpu_id, gpu_ids, node_id, node_ids) def _init_coco_dataset_dict(self, gpu_id, gpu_ids, node_id, node_ids): keys = self.keys
max_relative_id = 0 max_prompt_len = 0 self.anno = dict() self.anno["annotations"] = [] for key in keys:#key这里的key是一组的key, 一对多 for i, ann in enumerate(self._load_target(key)): # 可能有多个caption if max_relative_id >= i: image_id = ann['image_id'] img_info = self.coco.loadImgs(image_id)[0]# 加载图片信息 self.anno["annotations"].append({ "id": ann['id'], "caption": ann['caption'], "img_name": img_info['file_name'], }) self.anno_dict_keys = list(range(len(self.anno["annotations"]))) self.anno_dict_keys = split_datalist_for_gpu( self.anno_dict_keys, gpu_id, gpu_ids, node_id, node_ids )
def __len__(self): return len(self.anno_dict_keys) def __getitem__(self, index): key = self.anno_dict_keys[index]
prompt_dict = self.anno["annotations"][key] prompt = prompt_dict["caption"] prompt_idx = prompt_dict["id"] # img_name = prompt_dict["img_name"]
return prompt, prompt_idx
def create_dataset( name, ds_type='eval', **kwargs,): # train/test split datasets if ds_type == 'eval': if name == "coco": # ds = MSCOCOPromptBench(**kwargs) ds = MSCOCOPromptBench_DIY(**kwargs) return ds elif name == "parti_cocoformat": return PartiPromptsMultiGPUBenchCOCOFormat(**kwargs) elif name == "parti": return PartiPromptsMultiGPUBench(**kwargs) else: raise NotImplementedError else: if name == "coco": ds = MSCOCODatabase(**kwargs) return ds else: raise NotImplementedError if __name__ == "__main__": ds = create_dataset( name="mscoco", root='data/coco/train2017', annFile='data/coco/annotations/captions_val2017.json', ) print(len(ds.anno["annotations"]))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293import osimport randomfrom datetime import datetime
import pandas as pdfrom torch.utils.data import Datasetimport torchvision.transforms as Timport torchimport numpy as np
def split_datalist_for_gpu(df, gpu_id, gpu_ids, node_id, node_ids): node_index = node_ids.index(node_id) # Position of the current node in the node list gpu_index = gpu_ids.index(gpu_id) # Position of the current GPU in the GPU list
# first split the dataframe for different nodes total_nodes = len(node_ids) rows_per_split = len(df) // total_nodes start_index = node_index * rows_per_split end_index = start_index + rows_per_split if node_index < total_nodes - 1 else len(df)
df = df[start_index:end_index]
# then split the dataframe for different gpus total_gpus = len(gpu_ids) rows_per_split = len(df) // total_gpus start_index = gpu_index * rows_per_split end_index = start_index + rows_per_split if gpu_index < total_gpus - 1 else len(df)
return df[start_index:end_index]
def split_dataframe_for_gpu(df, gpu_id, gpu_ids, node_id, node_ids): """ Splits the dataframe for a specific GPU on a specific node, supporting arbitrary GPU and node identifiers. Args: df (pd.DataFrame): The dataframe to split. gpu_id (int): The identifier of the GPU for which the split is intended. gpu_ids (list): List of all GPU IDs across all nodes, which can be non-sequential. node_id (int): The identifier of the node on which the GPU is located. node_ids (list): List of all node IDs, which can be non-sequential. Returns: pd.DataFrame: A subset of the original dataframe intended for the specific GPU on a specific node. """ # Calculate the unique index for this GPU on this node by finding its position in the global list of GPUs node_index = node_ids.index(node_id) # Position of the current node in the node list gpu_index = gpu_ids.index(gpu_id) # Position of the current GPU in the GPU list
# first split the dataframe for different nodes total_nodes = len(node_ids) rows_per_split = len(df) // total_nodes start_index = node_index * rows_per_split end_index = start_index + rows_per_split if node_index < total_nodes - 1 else len(df)
df = df.iloc[start_index:end_index]
# then split the dataframe for different gpus total_gpus = len(gpu_ids) rows_per_split = len(df) // total_gpus start_index = gpu_index * rows_per_split end_index = start_index + rows_per_split if gpu_index < total_gpus - 1 else len(df)
return df.iloc[start_index:end_index]
def split_dataframe_for_node(df, node_id, node_ids): """ Splits the dataframe for a specific node, supporting arbitrary node identifiers. Args: df (pd.DataFrame): The dataframe to split. node_id (int): The identifier of the node node_ids (list): List of all node IDs, which can be non-sequential. Returns: pd.DataFrame: A subset of the original dataframe intended for the specific node. """ # Calculate the unique index for this GPU on this node by finding its position in the global list of GPUs node_index = node_ids.index(node_id) # Position of the current node in the node list global_index = node_index # Unique index across all GPUs on all nodes
# Calculate the total number of splits needed total_nodes = len(node_ids) # Calculate the number of rows per split rows_per_split = len(df) // total_nodes # Calculate the start and end indices of the rows for this particular split start_index = global_index * rows_per_split end_index = start_index + rows_per_split if global_index < total_nodes - 1 else len(df) # Get the subset of the dataframe return df.iloc[start_index:end_index]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196import osimport mathfrom argparse import ArgumentParserimport timeimport multiprocessing
import numpy as npimport torchfrom torch.utils.data import DataLoaderimport torchfrom PIL import Imageimport pandas as pdfrom tqdm import tqdm
from typing import List, Optional, Union, Dictfrom copy import copy
from utils import set_logger
import jsonclass PromptWrapper: def __init__( self, eval_data: DataLoader, gpu_id, node_id, model_name = "Alpha-VLLM/Lumina-mGPT-7B-768", output_dir = "./workdir", seed = None, return_accl = False ) -> None:
self.gpu_id = gpu_id self.node_id = node_id self.device = torch.device(f"cuda:{self.gpu_id}") print(f"GPU {self.gpu_id} is initialized") self.eval_data = eval_data
self.seed = seed # self.max_num_new_tokens = max_num_new_tokens self.model_name = model_name.split("/")[-1] self.output_dir = output_dir if not os.path.exists(self.output_dir): os.makedirs(self.output_dir) self.return_accl = return_accl def run(self, sample_fn): json_file_name = f"out_put_json_{self.gpu_id}_{self.node_id}.json" json_file_path = self.output_dir + "/" + json_file_name global_statistics = {} for i, data_item in enumerate(tqdm( self.eval_data, desc=f"Generating captions on GPU {self.gpu_id}, Node {self.node_id}" )): prompt, prompt_idx = data_item
prompt = prompt[0] prompt_idx = prompt_idx[0].item()
output_file_name = str(prompt_idx) + ".png" output_file_path = self.output_dir + "/" + output_file_name if not os.path.exists(output_file_path): if not self.return_accl: result_image = sample_fn(prompt) else: result_image, result = sample_fn(prompt) # Result(input_ids=input_ids, loop_num=gen_loop_num, token_gen_len = cur_len - init_len,time_forward=t) token_gen_len = result.token_gen_len loop_num = result.loop_num acceptance_length = token_gen_len / loop_num statistics = { "prompt": prompt, "time": result.time_forward, "acceptance_length": acceptance_length, "loop_num": loop_num, } global_statistics[f"prompt_{i}"] = statistics if isinstance(result_image, torch.Tensor): output_file_path = output_file_path.replace(".png", ".pt") torch.save(result_image, output_file_path) elif isinstance(result_image, Image.Image): result_image.save(output_file_path, format="PNG") else: raise ValueError(f"Invalid image type: {type(result_image)}") with open(f"{json_file_path}", "w") as f: json.dump(global_statistics, f, indent=4)
from .dataset_templates import create_datasetfrom model_wrappers.model_loader import load_pretrained_model, get_forward_funcdef run_caption_gen( gpu_id, node_id, gpu_ids, node_ids, dataset_params = dict( name = 'parti', annFile = './data/PartiPrompts.tsv', ), seed = None, model_name = "Alpha-VLLM/Lumina-mGPT-7B-768", output_dir = "./workdir", **kwargs,): return_accl = kwargs.get("return_accl",False) dataset = create_dataset( gpu_id=gpu_id, gpu_ids=gpu_ids, node_id=node_id, node_ids=node_ids, output_dir=output_dir, **dataset_params, )
dataloader = DataLoader( dataset, batch_size=1, shuffle=False, pin_memory=True, num_workers=12, ) device = torch.device(f"cuda:{gpu_id}") print(f"device {device}, GPU {gpu_id} is initialized, running on Node {node_id}.") model = load_pretrained_model( model_name, device = device, seed = seed, **kwargs, )
forward_func = get_forward_func( model_name, model, **kwargs, )
prompt_gen = PromptWrapper( eval_data=dataloader, gpu_id=gpu_id, node_id=node_id, seed = seed, model_name = model_name, output_dir = output_dir, return_accl = return_accl ) set_logger(log_level='info', fname=os.path.join(output_dir, 'gen_img_output.log')) with torch.no_grad(): prompt_gen.run(forward_func)
def _run_on_gpu( gpu_id, gpu_ids, node_id, node_ids, kwargs): """ Function that calls run caption gen with the specified arguments. """ # Set the GPU ID for the process if needed (optional) # os.environ['CUDA_VISIBLE_DEVICES'] = str(gpu_id) run_caption_gen( gpu_id=gpu_id, node_id=node_id, gpu_ids=gpu_ids, node_ids=node_ids, **kwargs)
def _run_on_multiple_gpus( gpu_ids, node_ids, node_id, **kwargs): """ Launches run caption gen on multiple GPUs without using multiprocessing.Pool, ensuring subprocesses are not daemonic and can have their CUDA context. Args: - num_gpus (int): Number of GPUs to use. - **kwargs: Arguments for the run caption gen function, excluding gpu_id. """ to_iterate = gpu_ids
processes = [] for gpu_id in to_iterate: # Prepare the arguments for each GPU p = multiprocessing.Process(target=_run_on_gpu, args=(gpu_id, gpu_ids, node_id, node_ids, kwargs), daemon=False) p.start() processes.append(p) for p in processes: p.join() # Wait for all processes to complete12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061# Copyright 2024 BAAI and the HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.from typing import TYPE_CHECKING
from transformers.utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available,)
_import_structure = { "configuration_emu3": ["Emu3Config"], "tokenization_emu3": ["Emu3Tokenizer"], "processing_emu3": ["Emu3Processor"],}
try: if not is_torch_available(): raise OptionalDependencyNotAvailable()except OptionalDependencyNotAvailable: passelse: _import_structure["modeling_emu3"] = [ "Emu3Model", "Emu3PretrainedModel", "Emu3ForCausalLM", ]
if TYPE_CHECKING: from .configuration_emu3 import Emu3Config from .tokenization_emu3 import Emu3Tokenizer from .processing_emu3 import Emu3Processor
try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_emu3 import ( Emu3Model, Emu3PretrainedModel, Emu3ForCausalLM, )
else: import sys
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213# coding=utf-8# Copyright 2024 The Emu team, BAAI and The HuggingFace Inc. team. All rights reserved.## This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX# and OPT implementations in this library. It has been modified from its# original forms to accommodate minor architectural differences compared# to GPT-NeoX and OPT used by the Meta AI team that trained the model.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.""" Emu3 model configuration"""
from typing import Optional
from transformers.configuration_utils import PretrainedConfigfrom transformers.utils import logging
logger = logging.get_logger(__name__)
EMU3_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
class Emu3Config(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Emu3Model`]. It is used to instantiate an Emu3 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Emu3-8B.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
Args: vocab_size (`int`, *optional*, defaults to 184622): Vocabulary size of the Emu3 model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`Emu3Model`] hidden_size (`int`, *optional*, defaults to 4096): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 14336): Dimension of the MLP representations. num_hidden_layers (`int`, *optional*, defaults to 32): Number of hidden layers in the Transformer decoder. num_attention_heads (`int`, *optional*, defaults to 32): Number of attention heads for each attention layer in the Transformer decoder. num_key_value_heads (`int`, *optional*, defaults to 8): This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details checkout [this paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `num_attention_heads`. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in the decoder. max_position_embeddings (`int`, *optional*, defaults to 9216): The maximum sequence length that this model might ever be used with. Emu supports up to 9216 tokens, initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. rms_norm_eps (`float`, *optional*, defaults to 1e-05): The epsilon used by the rms normalization layers. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. pad_token_id (`int`, *optional*, 151643): Padding token id. bos_token_id (`int`, *optional*, defaults to 151849): Beginning of stream token id. eos_token_id (`int`, *optional*, defaults to 151850): End of stream token id. img_token_id (`int`, *optional*, defaults to 151851): image token id. boi_token_id (`int`, *optional*, defaults to 151852): Beginning of image token id. eoi_token_id (`int`, *optional*, defaults to 151853): End of image token id. eol_token_id (`int`, *optional*, defaults to 151846): End of line token id. eof_token_id (`int`, *optional*, defaults to 151847): End of line token id. image_area (`int`, *optional*, defaults to 720 * 720) generated image area (image area used in training) pretraining_tp (`int`, *optional*, defaults to 1): Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is necessary to ensure exact reproducibility of the pretraining results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232). tie_word_embeddings (`bool`, *optional*, defaults to `False`): Whether to tie weight embeddings rope_theta (`float`, *optional*, defaults to 1_000_000.0): The base period of the RoPE embeddings. rope_scaling (`Dict`, *optional*): Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update `max_position_embeddings` to the expected new maximum. See the following thread for more information on how these scaling strategies behave: https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an experimental feature, subject to breaking API changes in future versions. attention_dropout (`float`, *optional*, defaults to 0.1): The dropout ratio for the attention probabilities.
```python >>> from transformers import Emu3Model, Emu3Config
>>> # Initializing a Emu3-8b style configuration >>> configuration = Emu3Config()
>>> # Initializing a model from the Emu3-8b style configuration >>> model = Emu3Model(configuration)
>>> # Accessing the model configuration >>> configuration = model.config ```"""
model_type = "Emu3" keys_to_ignore_at_inference = ["past_key_values"]
def __init__( self, vocab_size: int = 184622, hidden_size: int = 4096, intermediate_size: int = 14336, num_hidden_layers: int = 32, num_attention_heads: int = 32, num_key_value_heads: Optional[int] = 8, hidden_act: str = "silu", max_position_embeddings: int = 9216, initializer_range: float = 0.02, rms_norm_eps: float = 1e-5, use_cache: bool = True, pad_token_id: int = 151643, bos_token_id: int = 151849, eos_token_id: int = 151850, img_token_id: int = 151851, boi_token_id: int = 151852, eoi_token_id: int = 151853, eol_token_id: int = 151846, eof_token_id: int = 151847, image_area: int = 720 * 720, pretraining_tp: int = 1, tie_word_embeddings: bool = False, rope_theta: float = 1000000.0, rope_scaling: Optional = None, attention_dropout: float = 0.1, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads
# for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.pretraining_tp = pretraining_tp self.use_cache = use_cache self.rope_theta = rope_theta self.rope_scaling = rope_scaling self._rope_scaling_validation() self.attention_dropout = attention_dropout
self.img_token_id = img_token_id self.boi_token_id = boi_token_id self.eoi_token_id = eoi_token_id self.eol_token_id = eol_token_id self.eof_token_id = eof_token_id self.image_area = image_area
super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, )
def _rope_scaling_validation(self): """ Validate the `rope_scaling` configuration. """ if self.rope_scaling is None: return
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2: raise ValueError( "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, " f"got {self.rope_scaling}" ) rope_scaling_type = self.rope_scaling.get("type", None) rope_scaling_factor = self.rope_scaling.get("factor", None) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}" ) if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0: raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343# coding=utf-8# Copyright 2024 The Emu team, BAAI and The HuggingFace Inc. team. All rights reserved.## This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX# and OPT implementations in this library. It has been modified from its# original forms to accommodate minor architectural differences compared# to GPT-NeoX and OPT used by the Meta AI team that trained the model.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.## Adapted from https://github.com/huggingface/transformers/blob/52daf4ec768fb9ffe84a0c373834172a7c54aecc/src/transformers/models/llama/modeling_llama.py#""" PyTorch Emu3 model."""import mathimport warningsfrom typing import List, Optional, Tuple, Union
import torchimport torch.nn.functional as Fimport torch.utils.checkpointfrom torch import nnfrom torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from transformers.activations import ACT2FNfrom transformers.cache_utils import Cache, DynamicCachefrom transformers.modeling_attn_mask_utils import ( AttentionMaskConverter, _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa,)from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPastfrom transformers.modeling_utils import PreTrainedModelfrom transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13from transformers.utils import ( add_start_docstrings, add_start_docstrings_to_model_forward, is_flash_attn_2_available, is_flash_attn_greater_or_equal_2_10, logging, replace_return_docstrings,)from transformers.utils.import_utils import is_torch_fx_availablefrom .configuration_emu3 import Emu3Config
if is_flash_attn_2_available(): from flash_attn import flash_attn_func, flash_attn_varlen_func from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
# This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.# It means that the function will not be traced through and simply appear as a node in the graph.if is_torch_fx_available(): if not is_torch_greater_or_equal_than_1_13: import torch.fx
_prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
logger = logging.get_logger(__name__)
_CONFIG_FOR_DOC = "Emu3Config"
def _get_unpad_data(attention_mask): seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten() max_seqlen_in_batch = seqlens_in_batch.max().item() cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)) return ( indices, cu_seqlens, max_seqlen_in_batch, )
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): warnings.warn( "Calling `transformers.models.emu3.modeling_emu3._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask" ) return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
def _make_causal_mask( input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0): warnings.warn( "Calling `transformers.models.emu3.modeling_emu3._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.emu3.modeling_emu3.AttentionMaskConverter._make_causal_mask" ) return AttentionMaskConverter._make_causal_mask( input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length )
class Emu3RMSNorm(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ Emu3RMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps
def forward(self, hidden_states): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return self.weight * hidden_states.to(input_dtype)
ALL_LAYERNORM_LAYERS.append(Emu3RMSNorm)
class Emu3RotaryEmbedding(nn.Module): def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None): super().__init__()
self.dim = dim self.max_position_embeddings = max_position_embeddings self.base = base inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)) self.register_buffer("inv_freq", inv_freq, persistent=False)
# Build here to make `torch.jit.trace` work. self._set_cos_sin_cache( seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype() )
def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
freqs = torch.outer(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().to(dtype), persistent=False) self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
def forward(self, x, seq_len=None): # x: [bs, num_attention_heads, seq_len, head_size] if seq_len > self.max_seq_len_cached: self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
return ( self.cos_cached[:seq_len].to(dtype=x.dtype), self.sin_cached[:seq_len].to(dtype=x.dtype), )
class Emu3LinearScalingRotaryEmbedding(Emu3RotaryEmbedding): """Emu3RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0): self.scaling_factor = scaling_factor super().__init__(dim, max_position_embeddings, base, device)
def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) t = t / self.scaling_factor
freqs = torch.outer(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().to(dtype), persistent=False) self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
class Emu3DynamicNTKScalingRotaryEmbedding(Emu3RotaryEmbedding): """Emu3RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0): self.scaling_factor = scaling_factor super().__init__(dim, max_position_embeddings, base, device)
def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len
if seq_len > self.max_position_embeddings: base = self.base * ( (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1) ) ** (self.dim / (self.dim - 2)) inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)) self.register_buffer("inv_freq", inv_freq, persistent=False)
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
freqs = torch.outer(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().to(dtype), persistent=False) self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
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, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors.
Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. position_ids (`torch.Tensor`): The position indices of the tokens corresponding to the query and key tensors. For example, this can be used to pass offsetted position ids when working with a KV-cache. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ cos = cos[position_ids].unsqueeze(unsqueeze_dim) sin = sin[position_ids].unsqueeze(unsqueeze_dim) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed
class Emu3MLP(nn.Module): def __init__(self, config): super().__init__() self.config = config self.hidden_size = config.hidden_size self.intermediate_size = config.intermediate_size self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) self.act_fn = ACT2FN[config.hidden_act]
def forward(self, x): if self.config.pretraining_tp > 1: slice = self.intermediate_size // self.config.pretraining_tp gate_proj_slices = self.gate_proj.weight.split(slice, dim=0) up_proj_slices = self.up_proj.weight.split(slice, dim=0) down_proj_slices = self.down_proj.weight.split(slice, dim=1)
gate_proj = torch.cat( [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1 ) up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2) down_proj = [ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp) ] down_proj = sum(down_proj) else: down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
return down_proj
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
class Emu3Attention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: Emu3Config, layer_idx: Optional[int] = None): super().__init__() self.config = config self.layer_idx = layer_idx if layer_idx is None: logger.warning_once( f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will " "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` " "when creating this class." )
self.attention_dropout = config.attention_dropout self.hidden_size = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = self.hidden_size // self.num_heads self.num_key_value_heads = config.num_key_value_heads self.num_key_value_groups = self.num_heads // self.num_key_value_heads self.max_position_embeddings = config.max_position_embeddings self.rope_theta = config.rope_theta self.is_causal = True
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_key_value_heads * self.head_dim, bias=False) self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False) self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False) self._init_rope()
def _init_rope(self): if self.config.rope_scaling is None: self.rotary_emb = Emu3RotaryEmbedding( self.head_dim, max_position_embeddings=self.max_position_embeddings, base=self.rope_theta, ) else: scaling_type = self.config.rope_scaling["type"] scaling_factor = self.config.rope_scaling["factor"] if scaling_type == "linear": self.rotary_emb = Emu3LinearScalingRotaryEmbedding( self.head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor, base=self.rope_theta, ) elif scaling_type == "dynamic": self.rotary_emb = Emu3DynamicNTKScalingRotaryEmbedding( self.head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor, base=self.rope_theta, ) else: raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
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[Cache] = None, output_attentions: bool = False, use_cache: bool = False, **kwargs, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: if "padding_mask" in kwargs: warnings.warn( "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" )
bsz, q_len, _ = hidden_states.size()
if self.config.pretraining_tp > 1: key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp query_slices = self.q_proj.weight.split( (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0 ) key_slices = self.k_proj.weight.split(key_value_slicing, dim=0) value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)] query_states = torch.cat(query_states, dim=-1)
key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)] key_states = torch.cat(key_states, dim=-1)
value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)] value_states = torch.cat(value_states, dim=-1)
else: query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states)
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
kv_seq_len = key_states.shape[-2] if past_key_value is not None: if self.layer_idx is None: raise ValueError( f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} " "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class " "with a layer index." ) kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) 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)
if past_key_value is not None: cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
key_states = repeat_kv(key_states, self.num_key_value_groups) value_states = repeat_kv(value_states, self.num_key_value_groups)
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
# upcast attention to fp32 attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training) 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).contiguous()
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
if self.config.pretraining_tp > 1: attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2) o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1) attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)]) else: attn_output = self.o_proj(attn_output)
if not output_attentions: attn_weights = None
return attn_output, attn_weights, past_key_value
class Emu3FlashAttention2(Emu3Attention): """ Emu3 flash attention module. This module inherits from `Emu3Attention` as the weights of the module stays untouched. The only required change would be on the forward pass where it needs to correctly call the public API of flash attention and deal with padding tokens in case the input contains any of them. """
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1. # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0. # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left). self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Cache] = None, output_attentions: bool = False, use_cache: bool = False, **kwargs, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: # Emu3FlashAttention2 attention does not support output_attentions if "padding_mask" in kwargs: warnings.warn( "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" )
# overwrite attention_mask with padding_mask attention_mask = kwargs.pop("padding_mask")
output_attentions = False
bsz, q_len, _ = hidden_states.size()
query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states)
# Flash attention requires the input to have the shape # batch_size x seq_length x head_dim x hidden_dim # therefore we just need to keep the original shape query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, self.num_key_value_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.get_usable_length(kv_seq_len, self.layer_idx) 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)
if past_key_value is not None: cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache # to be able to avoid many of these transpose/reshape/view. query_states = query_states.transpose(1, 2) key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2)
dropout_rate = self.attention_dropout if self.training else 0.0
# In PEFT, usually we cast the layer norms in float32 for training stability reasons # therefore the input hidden states gets silently casted in float32. Hence, we need # cast them back in the correct dtype just to be sure everything works as expected. # This might slowdown training & inference so it is recommended to not cast the LayerNorms # in fp32. (Emu3RMSNorm handles it correctly)
input_dtype = query_states.dtype if input_dtype == torch.float32: # Handle the case where the model is quantized if hasattr(self.config, "_pre_quantization_dtype"): target_dtype = self.config._pre_quantization_dtype else: target_dtype = self.q_proj.weight.dtype
logger.warning_once( f"The input hidden states seems to be silently casted in float32, this might be related to" f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in" f" {target_dtype}." )
query_states = query_states.to(target_dtype) key_states = key_states.to(target_dtype) value_states = value_states.to(target_dtype)
attn_output = self._flash_attention_forward( query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate )
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous() attn_output = self.o_proj(attn_output)
if not output_attentions: attn_weights = None
return attn_output, attn_weights, past_key_value
def _flash_attention_forward( self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None ): """ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token first unpad the input, then computes the attention scores and pad the final attention scores.
Args: query_states (`torch.Tensor`): Input query states to be passed to Flash Attention API key_states (`torch.Tensor`): Input key states to be passed to Flash Attention API value_states (`torch.Tensor`): Input value states to be passed to Flash Attention API attention_mask (`torch.Tensor`): The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the position of padding tokens and 1 for the position of non-padding tokens. dropout (`int`, *optional*): Attention dropout softmax_scale (`float`, *optional*): The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim) """ if not self._flash_attn_uses_top_left_mask: causal = self.is_causal else: # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in Emu3FlashAttention2 __init__. causal = self.is_causal and query_length != 1
# Contains at least one padding token in the sequence if attention_mask is not None: batch_size = query_states.shape[0] query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input( query_states, key_states, value_states, attention_mask, query_length )
cu_seqlens_q, cu_seqlens_k = cu_seq_lens max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
attn_output_unpad = flash_attn_varlen_func( query_states, key_states, value_states, cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=cu_seqlens_k, max_seqlen_q=max_seqlen_in_batch_q, max_seqlen_k=max_seqlen_in_batch_k, dropout_p=dropout, softmax_scale=softmax_scale, causal=causal, )
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length) else: attn_output = flash_attn_func( query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal )
return attn_output
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length): indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask) batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
key_layer = index_first_axis( key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k ) value_layer = index_first_axis( value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k ) if query_length == kv_seq_len: query_layer = index_first_axis( query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k ) cu_seqlens_q = cu_seqlens_k max_seqlen_in_batch_q = max_seqlen_in_batch_k indices_q = indices_k elif query_length == 1: max_seqlen_in_batch_q = 1 cu_seqlens_q = torch.arange( batch_size + 1, dtype=torch.int32, device=query_layer.device ) # There is a memcpy here, that is very bad. indices_q = cu_seqlens_q[:-1] query_layer = query_layer.squeeze(1) else: # The -q_len: slice assumes left padding. attention_mask = attention_mask[:, -query_length:] query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
return ( query_layer, key_layer, value_layer, indices_q, (cu_seqlens_q, cu_seqlens_k), (max_seqlen_in_batch_q, max_seqlen_in_batch_k), )
class Emu3SdpaAttention(Emu3Attention): """ Emu3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from `Emu3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to SDPA API. """
# Adapted from Emu3Attention.forward def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Cache] = None, output_attentions: bool = False, use_cache: bool = False, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: if output_attentions: # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented. logger.warning_once( "Emu3Model is using Emu3SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, " 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.' ) return super().forward( 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, )
bsz, q_len, _ = hidden_states.size()
query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states)
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, self.num_key_value_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.get_usable_length(kv_seq_len, self.layer_idx) 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)
if past_key_value is not None: cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
key_states = repeat_kv(key_states, self.num_key_value_groups) value_states = repeat_kv(value_states, self.num_key_value_groups)
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()}" )
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask, # Reference: https://github.com/pytorch/pytorch/issues/112577. if query_states.device.type == "cuda" and attention_mask is not None: query_states = query_states.contiguous() key_states = key_states.contiguous() value_states = value_states.contiguous()
attn_output = torch.nn.functional.scaled_dot_product_attention( query_states, key_states, value_states, attn_mask=attention_mask, dropout_p=self.attention_dropout if self.training else 0.0, # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1. is_causal=self.is_causal and attention_mask is None and q_len > 1, )
attn_output = attn_output.transpose(1, 2).contiguous() attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
attn_output = self.o_proj(attn_output)
return attn_output, None, past_key_value
EMU3_ATTENTION_CLASSES = { "eager": Emu3Attention, "flash_attention_2": Emu3FlashAttention2, "sdpa": Emu3SdpaAttention,}
class Emu3DecoderLayer(nn.Module): def __init__(self, config: Emu3Config, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.dropout = nn.Dropout(config.attention_dropout) self.self_attn = EMU3_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
self.mlp = Emu3MLP(config) self.input_layernorm = Emu3RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = Emu3RMSNorm(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, **kwargs, ) -> 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_size, sequence_length)` if flash attention is used or `(batch_size, 1, query_sequence_length, key_sequence_length)` if default attention is used. 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 """ if "padding_mask" in kwargs: warnings.warn( "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" )
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, **kwargs, ) hidden_states = residual + self.dropout(hidden_states)
# Fully Connected residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + self.dropout(hidden_states)
outputs = (hidden_states,)
if output_attentions: outputs += (self_attn_weights,)
if use_cache: outputs += (present_key_value,)
return outputs
EMU3_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 ([`Emu3Config`]): 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 Emu3 Model outputting raw hidden-states without any specific head on top.", EMU3_START_DOCSTRING,)class Emu3PreTrainedModel(PreTrainedModel): config_class = Emu3Config base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["Emu3DecoderLayer"] _skip_keys_device_placement = "past_key_values" _supports_flash_attn_2 = True _supports_sdpa = True _supports_cache_class = True
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_()
EMU3_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 `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 (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*): Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
Two formats are allowed: - a [`~cache_utils.Cache`] instance; - 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)`). This is also known as the legacy cache format.
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the legacy cache format will be returned.
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `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 Emu3 Model outputting raw hidden-states without any specific head on top.", EMU3_START_DOCSTRING,)class Emu3Model(Emu3PreTrainedModel): """ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Emu3DecoderLayer`]
Args: config: Emu3Config """
def __init__(self, config: Emu3Config): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size
self.dropout = nn.Dropout(config.attention_dropout) self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.layers = nn.ModuleList( [Emu3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self._use_sdpa = config._attn_implementation == "sdpa" self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2" self.norm = Emu3RMSNorm(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
@add_start_docstrings_to_model_forward(EMU3_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, 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 input_ids and inputs_embeds at the same time") elif input_ids is not None: batch_size, seq_length = input_ids.shape[:2] elif inputs_embeds is not None: batch_size, seq_length = inputs_embeds.shape[:2] else: raise ValueError("You have to specify either input_ids or 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
past_key_values_length = 0 if use_cache: use_legacy_cache = not isinstance(past_key_values, Cache) if use_legacy_cache: past_key_values = DynamicCache.from_legacy_cache(past_key_values) past_key_values_length = past_key_values.get_usable_length(seq_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)
if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids)
if self._use_flash_attention_2: # 2d mask is passed through the layers attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None elif self._use_sdpa and not output_attentions: # output_attentions=True can not be supported when using SDPA, and we fall back on # the manual implementation that requires a 4D causal mask in all cases. attention_mask = _prepare_4d_causal_attention_mask_for_sdpa( attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length, ) else: # 4d mask is passed through the layers attention_mask = _prepare_4d_causal_attention_mask( attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length )
# embed positions hidden_states = self.dropout(inputs_embeds)
# decoder layers all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None next_decoder_cache = None
for decoder_layer in self.layers: if output_hidden_states: all_hidden_states += (hidden_states,)
if self.gradient_checkpointing and self.training: layer_outputs = self._gradient_checkpointing_func( decoder_layer.__call__, hidden_states, attention_mask, position_ids, past_key_values, output_attentions, use_cache, ) else: layer_outputs = decoder_layer( hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_values, 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 = None if use_cache: next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache 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 Emu3ForCausalLM(Emu3PreTrainedModel): _tied_weights_keys = ["lm_head.weight"]
def __init__(self, config): super().__init__(config) self.model = Emu3Model(config) self.vocab_size = config.vocab_size 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(EMU3_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, 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, AutoModel, AutoImageProcessor, AutoModelForCausalLM >>> from transformers.generation.configuration_utils import GenerationConfig >>> from transformers.generation import LogitsProcessorList, PrefixConstrainedLogitsProcessor, UnbatchedClassifierFreeGuidanceLogitsProcessor >>> from transformers import Emu3Processor >>> from PIL import Image
>>> model = AutoModelForCausalLM.from_pretrained(PATH_TO_CONVERTED_EMU3_WEIGHTS) >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER) >>> image_processor = AutoImageProcessor.from_pretrained(PATH_TO_CONVERTED_IMAGE_PROCESSER) >>> image_tokenizer = AutoModel.from_pretrained(PATH_TO_CONVERTED_TOKENIZER_WEIGHTS).eval() >>> processor = Emu3Processor(image_processor, image_tokenizer, tokenizer)
>>> # Generation >>> prompt = "An Emu in cartoon style, it is wearing sunglasses."
>>> pos_inputs = processor(text=prompt, mode='G', ratio="4:3", image_area=model.config.image_area, return_tensors="pt") >>> neg_inputs = processor(text="", mode='G', ratio="4:3", image_area=model.config.image_area, return_tensors="pt")
>>> GENERATION_CONFIG = GenerationConfig( >>> use_cache=True, >>> eos_token_id=model.config.eos_token_id, >>> pad_token_id=model.config.pad_token_id, >>> max_new_tokens=40960, >>> do_sample=True, >>> top_k=2048, >>> )
>>> h, w = pos_inputs.image_size[0] >>> constrained_fn = processor.build_prefix_constrained_fn(h, w) >>> logits_processor = LogitsProcessorList([ >>> UnbatchedClassifierFreeGuidanceLogitsProcessor( >>> classifier_free_guidance, >>> model, >>> unconditional_ids=neg_inputs.input_ids.to("cuda:0"), >>> ), >>> PrefixConstrainedLogitsProcessor( >>> constrained_fn, >>> num_beams=1, >>> ), >>> ])
>>> outputs = model.generate(pos_inputs.input_ids.to("cuda:0"), GENERATION_CONFIG, logits_processor=logits_processor) >>> 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] >>> mm_list = processor.decode(outputs[0])
>>> # Understanding >>> prompt = "Provide a one-sentence caption for the provided image." >>> image = Image.open(TEST_IMAGE_PATH)
>>> inputs = processor(text=text, image=image, mode='U', padding_side="left", padding="longest", return_tensors="pt") >>> input_ids = inputs.input_ids.to("cuda:0") >>> GENERATION_CONFIG = GenerationConfig( >>> pad_token_id=tokenizer.pad_token_id, >>> bos_token_id=tokenizer.bos_token_id, >>> eos_token_id=tokenizer.eos_token_id, >>> )
>>> outputs = model.generate(input_ids, GENERATION_CONFIG, max_new_tokens=100) >>> outputs = outputs[:, input_ids.shape[-1]:] >>> answer = processor.batch_decode(outputs, skip_special_tokens=True) ```""" 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, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, )
hidden_states = outputs[0] if self.config.pretraining_tp > 1: lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0) logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)] logits = torch.cat(logits, dim=-1) else: logits = self.lm_head(hidden_states) logits = logits.float()
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, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs ): if past_key_values is not None: if isinstance(past_key_values, Cache): cache_length = past_key_values.get_seq_length() past_length = past_key_values.seen_tokens max_cache_length = past_key_values.get_max_length() else: cache_length = past_length = past_key_values[0][0].shape[2] max_cache_length = None
# Keep only the unprocessed tokens: # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as # input) if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]: input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :] # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard # input_ids based on the past_length. elif past_length < input_ids.shape[1]: input_ids = input_ids[:, past_length:] # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask. if ( max_cache_length is not None and attention_mask is not None and cache_length + input_ids.shape[1] > max_cache_length ): attention_mask = attention_mask[:, -max_cache_length:]
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[:, -input_ids.shape[1] :]
# 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, "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.to(past_state.device)) for past_state in layer_past), ) return reordered_past123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299# coding=utf-8# Copyright 2024 The Emu team, BAAI and The HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.""" Processor class for Emu3. """
import refrom typing import List, Optional, Sequence, Unionfrom functools import partial
from PIL import Imageimport torchfrom transformers.feature_extraction_utils import BatchFeaturefrom transformers.image_utils import ImageInput, get_image_size, to_numpy_arrayfrom transformers.processing_utils import ProcessingKwargs, ProcessorMixinfrom transformers.tokenization_utils_base import TextInput, PreTokenizedInputfrom transformers.utils import logging
from .utils_emu3 import Emu3PrefixConstrainedLogitsHelper
logger = logging.get_logger(__name__)
class Emu3Processor(ProcessorMixin): r""" Constructs an Emu3 processor which wraps an Emu3 image processor and an Emu3 vision vq model and an Emu3 tokenizer into a single processor.
[`Emu3Processor`] offers all the functionalities of [`Emu3VisionVQModel`] and [`Emu3Tokenizer`]. See the [`~Emu3Processor.__call__`], [`~Emu3Processor.decode`], [`~Emu3Processor.vision_encode`], [`~Emu3Processor.vision_decode`] for more information.
Args: image_processor ([`Emu3VisionVQImageProcessor`]): The image processor is a required input. vision_tokenizer ([`Emu3VisionVQModel`]): The vision tokenizer is a required input. tokenizer ([`Emu3Tokenizer`]): The tokenizer is a required input. prefix_template(`str`, *optional*): The prefix template for image tokens visual_template(`Tuple[str, ...]`, *optional*): The visual token template for image tokens """
attributes = ["image_processor", "tokenizer"] valid_kwargs = ["vision_tokenizer", "prefix_template", "visual_template"] image_processor_class = "AutoImageProcessor" tokenizer_class = "AutoTokenizer"
def __init__( self, image_processor=None, vision_tokenizer=None, tokenizer=None, chat_template="You are a helpful assistant. USER: {image_prompt}{text_prompt}. ASSISTANT:", prefix_template="{H}*{W}", visual_template=("<|visual token {token_id:0>6d}|>", r"<\|visual token (\d+)\|>"), **kwargs, ): assert vision_tokenizer is not None, "image tokenizer can not be None"
self.vision_tokenizer = vision_tokenizer self.prefix_template = prefix_template self.visual_template = visual_template
super().__init__(image_processor, tokenizer, chat_template=chat_template) self.const_helper = self.build_const_helper()
@torch.no_grad() def __call__( self, text = None, image = None, *, mode: str = "G", ratio: str = "1:1", image_area: int = 518400, frame_number: int = 1, **kwargs, ) -> BatchFeature: """ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text` and `kwargs` arguments to Emu3Tokenizer's [`~Emu3Tokenizer.__call__`] to encode the text. To prepare the image(s), this method forwards the `image` argument to Emu3VisionVQImageProcessor's [`~Emu3VisionVQImageProcessor.__call__`] and Emu3VisionVQModel's [`~EmuVideoVQModel.encode`] if `image` is not `None`. Please refer to the doctsring of the above two methods for more information.
Args: text (`str` or `List[str]`): The sequence or a batch of sequence to be encoded. A sequence is a string. image (`PIL.Image.Image` or `List[PIL.Image.Image]`, *optional*): The image or a batch of images to be prepared. An image is a PIL image. mode (`str`, *optional*, in `G` or `U`): task mode, `G` for generation and `U` for understanding ratio (`str`, *optional*): the image width-height ratio for generation image_area (`int`, *optional*): image area used to calcualte the generated image height and width return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors of a particular framework. Acceptable values are: - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects.
Returns: [`BatchFeature`]: A [`BatchFeature`] with the following fields:
- **input_ids** -- List of token ids to be fed to a model. - **image_size** -- List of image size of input images or generated images. """ assert mode in ('G', 'U', 'VG'), "mode must be 'G', 'VG' or 'U'." if isinstance(text, str): text = [text]
if not isinstance(text[0], str): raise ValueError("`text` must be string or list of string")
image_inputs = None if mode == 'G' or mode == 'VG': if image is not None: raise ValueError("You have to specify only `text` in generation mode")
if len(text) > 1: raise ValueError("`text` can only be `str` in generation mode") else: if image is None: raise ValueError("Invalid input image. Please provide exactly one PIL.Image.Image per text.")
if not isinstance(image, Sequence) and not isinstance(image, Image.Image): raise ValueError("Invalid input image. Please provide PIL.Image.Image or List[PIL.Image.Image].")
if isinstance(image, Sequence) and not isinstance(image[0], Image.Image): raise ValueError("Invalid input image. Please provide PIL.Image.Image or List[PIL.Image.Image].")
image_inputs = self.image_processor(image, return_tensors="pt")["pixel_values"] print(image_inputs.shape) image_inputs = image_inputs.to(self.vision_tokenizer.device, self.vision_tokenizer.dtype) image_tokens = self.vision_tokenizer.encode(image_inputs)
if len(text) != len(image_tokens): raise ValueError("number of image must match number of text prompt")
prompt_list, size_list = [], [] for idx, text_prompt in enumerate(text): prompt = self.tokenizer.bos_token if mode == 'U': h, w = image_tokens[idx].shape imgstr = self.to_imgstr(image_tokens[idx]) image_prompt = ( self.tokenizer.boi_token + self.prefix_template.format(H=h, W=w) + self.tokenizer.img_token + imgstr + self.tokenizer.eol_token + self.tokenizer.eof_token + self.tokenizer.eoi_token ) prompt += self.chat_template.format(image_prompt=image_prompt, text_prompt=text_prompt) if mode == 'VG': h, w = self.calculate_generate_size(ratio, image_area, self.vision_tokenizer.spatial_scale_factor) image_prompt = ( self.tokenizer.boi_token + self.prefix_template.format(H=h, W=w, F=frame_number) + self.tokenizer.img_token ) prompt += (text_prompt + image_prompt) else: h, w = self.calculate_generate_size(ratio, image_area, self.vision_tokenizer.spatial_scale_factor) image_prompt = ( self.tokenizer.boi_token + self.prefix_template.format(H=h, W=w) + self.tokenizer.img_token ) prompt += (text_prompt + image_prompt)
prompt_list.append(prompt) size_list.append([h, w])
text_inputs = self.tokenizer(prompt_list, **kwargs) return BatchFeature(data={**text_inputs, "image_size": size_list}, tensor_type=kwargs.get("return_tensors"))
@torch.no_grad() def batch_decode(self, *args, **kwargs): docs = self.tokenizer.batch_decode(*args, **kwargs) return [self.multimodal_decode(d) for d in docs]
@torch.no_grad() def decode(self, *args, **kwargs): doc = self.tokenizer.decode(*args, **kwargs) return self.multimodal_decode(doc)
@torch.no_grad() def vision_encode(self, *args, **kwargs): return self.vision_tokenizer.encode(*args, **kwargs)
@torch.no_grad() def vision_decode(self, *args, **kwargs): return self.vision_tokenizer.decode(*args, **kwargs)
@torch.no_grad() def multimodal_decode(self, doc): multimodal_output = [] pattern = rf'({re.escape(self.tokenizer.boi_token)}.*?{re.escape(self.tokenizer.eoi_token)})' chunks = re.split(pattern, doc) for c in chunks: if len(c) == 0: continue
if self.tokenizer.boi_token in c: image = [] image_rows = re.split(re.escape(self.tokenizer.eol_token), c) for r in image_rows: token_ids = re.findall(self.visual_template[1], r) if len(token_ids) > 0: row_token = [int(m) for m in token_ids] image.append(row_token) image = torch.tensor(image, dtype=torch.long, device=self.vision_tokenizer.device) image = self.vision_tokenizer.decode(image[None]).float() image = self.image_processor.postprocess(image)["pixel_values"][0] multimodal_output.append(image) else: multimodal_output.append(c)
return multimodal_output if len(multimodal_output) > 1 else multimodal_output[0]
@property def model_input_names(self): tokenizer_input_names = self.tokenizer.model_input_names image_processor_input_names = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
def to_imgstr(self, image_tokens): image_tokens = image_tokens.cpu().numpy().tolist() image_token_str = [ [ self.visual_template[0].format(token_id=token_id) for token_id in token_row ] for token_row in image_tokens ] image_row_str = ["".join(token_row) for token_row in image_token_str] imgstr = self.tokenizer.eol_token.join(image_row_str) return imgstr
def calculate_generate_size(self, ratio, image_area, spatial_scale_factor): w, h = map(int, ratio.split(":")) current_area = h * w target_ratio = (image_area / current_area) ** 0.5
th = int(round(h * target_ratio / spatial_scale_factor)) tw = int(round(w * target_ratio / spatial_scale_factor)) return th, tw
def build_const_helper(self): ( img_token, eoi_token, eos_token, eol_token, eof_token, pad_token, vis_start, vis_end, ) = self.tokenizer.encode([ self.tokenizer.img_token, self.tokenizer.eoi_token, self.tokenizer.eos_token, self.tokenizer.eol_token, self.tokenizer.eof_token, self.tokenizer.pad_token, self.visual_template[0].format(token_id=0), self.visual_template[0].format(token_id=self.vision_tokenizer.config.codebook_size - 1), ])
const_helper = partial( Emu3PrefixConstrainedLogitsHelper, img_token=img_token, eoi_token=eoi_token, eos_token=eos_token, eol_token=eol_token, eof_token=eof_token, pad_token=pad_token, visual_tokens=list(range(vis_start, vis_end + 1)), ) return const_helper
def build_prefix_constrained_fn(self, height, width): helper = self.const_helper(height=height, width=width) return helper123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294# coding=utf-8# Copyright 2024 The Emu team, BAAI and The HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Tokenization classes for Emu3."""
import base64import loggingimport osimport unicodedatafrom typing import Collection, Dict, List, Optional, Set, Tuple, Union
import tiktokenfrom transformers import PreTrainedTokenizer, AddedToken
logger = logging.getLogger(__name__)
VOCAB_FILES_NAMES = { "vocab_file": "emu3.tiktoken", "special_tokens_file": "emu3_vision_tokens.txt",}
PAT_STR = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""ENDOFTEXT = "<|endoftext|>"IMSTART = "<|im_start|>"IMEND = "<|im_end|>"# as the default behavior is changed to allow special tokens in# regular texts, the surface forms of special tokens need to be# as different as possible to minimize the impactEXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))# changed to use actual index to avoid misconfiguration with vocabulary expansionSPECIAL_START_ID = 151643
def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]: with open(tiktoken_bpe_file, "rb") as f: contents = f.read() return { base64.b64decode(token): int(rank) for token, rank in (line.split() for line in contents.splitlines() if line) }
class Emu3Tokenizer(PreTrainedTokenizer): """Emu3 tokenizer."""
vocab_files_names = VOCAB_FILES_NAMES
def __init__( self, vocab_file, special_tokens_file, errors="replace", bos_token = "<|extra_203|>", eos_token = "<|extra_204|>", pad_token = "<|endoftext|>", img_token = "<|image token|>", boi_token = "<|image start|>", eoi_token = "<|image end|>", eol_token = "<|extra_200|>", eof_token = "<|extra_201|>", **kwargs, ): super().__init__(**kwargs)
# how to handle errors in decoding UTF-8 byte sequences # use ignore if you are in streaming inference self.errors = errors
self.mergeable_ranks = _load_tiktoken_bpe(vocab_file)
vision_tokens = [t.strip() for t in open(special_tokens_file).readlines() if len(t.strip()) > 0] SPECIAL_TOKENS = tuple( enumerate( ( ( ENDOFTEXT, IMSTART, IMEND, ) + EXTRAS + tuple(vision_tokens) ), start=SPECIAL_START_ID, ) ) self.special_tokens = {token: index for index, token in SPECIAL_TOKENS} self.special_tokens_set = set(t for _, t in SPECIAL_TOKENS)
enc = tiktoken.Encoding( "Emu3", pat_str=PAT_STR, mergeable_ranks=self.mergeable_ranks, special_tokens=self.special_tokens, )
assert ( len(self.mergeable_ranks) + len(self.special_tokens) == enc.n_vocab ), f"{len(self.mergeable_ranks) + len(self.special_tokens)} != {enc.n_vocab} in encoding"
self.decoder = { v: k for k, v in self.mergeable_ranks.items() } self.decoder.update({v: k for k, v in self.special_tokens.items()})
self.tokenizer = enc
self.eod_id = self.tokenizer.eot_token self.bos_token = bos_token self.eos_token = eos_token self.pad_token = pad_token self.img_token = img_token self.boi_token = boi_token self.eoi_token = eoi_token self.eol_token = eol_token self.eof_token = eof_token
def __getstate__(self): # for pickle lovers state = self.__dict__.copy() del state["tokenizer"] return state
def __setstate__(self, state): # tokenizer is not python native; don't pass it; rebuild it self.__dict__.update(state) enc = tiktoken.Encoding( "Emu3", pat_str=PAT_STR, mergeable_ranks=self.mergeable_ranks, special_tokens=self.special_tokens, ) self.tokenizer = enc
def __len__(self) -> int: return self.tokenizer.n_vocab
def get_vocab(self) -> Dict[bytes, int]: return self.mergeable_ranks
def convert_tokens_to_ids( self, tokens: Union[bytes, str, List[Union[bytes, str]]] ) -> List[int]: if isinstance(tokens, (str, bytes)): if tokens in self.special_tokens: return self.special_tokens[tokens] else: return self.mergeable_ranks.get(tokens)
ids = [] for token in tokens: if token in self.special_tokens: ids.append(self.special_tokens[token]) else: ids.append(self.mergeable_ranks.get(token)) return ids
def _add_tokens( self, new_tokens: Union[List[str], List[AddedToken]], special_tokens: bool = False, ) -> int: if not special_tokens and new_tokens: raise ValueError("Adding regular tokens is not supported")
for token in new_tokens: surface_form = token.content if isinstance(token, AddedToken) else token if surface_form not in self.special_tokens_set: raise ValueError("Adding unknown special tokens is not supported")
return 0
def save_vocabulary(self, save_directory: str, **kwargs) -> Tuple[str]: """ Save only the vocabulary of the tokenizer (vocabulary).
Returns: `Tuple(str)`: Paths to the files saved. """ regular_file_path = os.path.join(save_directory, self.vocab_files_names["vocab_file"]) with open(regular_file_path,'w', encoding="utf8") as w: for k, v in self.mergeable_ranks.items(): line = base64.b64encode(k).decode("utf8") + " " + str(v) + "\n" w.write(line)
excluded_special_tokens = set((ENDOFTEXT, IMSTART, IMEND,) + EXTRAS) special_file_path = os.path.join(save_directory, self.vocab_files_names["special_tokens_file"]) with open(special_file_path, 'w', encoding="utf8") as w: for k in self.special_tokens: if k not in excluded_special_tokens: print(k, file=w)
return (regular_file_path, special_file_path)
def tokenize( self, text: str, allowed_special: Union[Set, str] = "all", disallowed_special: Union[Collection, str] = (), **kwargs, ) -> List[Union[bytes, str]]: """ Converts a string in a sequence of tokens.
Args: text (`str`): The sequence to be encoded. allowed_special (`Literal["all"]` or `set`): The surface forms of the tokens to be encoded as special tokens in regular texts. Default to "all". disallowed_special (`Literal["all"]` or `Collection`): The surface forms of the tokens that should not be in regular texts and trigger errors. Default to an empty tuple.
kwargs (additional keyword arguments, *optional*): Will be passed to the underlying model specific encode method.
Returns: `List[bytes|str]`: The list of tokens. """ tokens = [] text = unicodedata.normalize("NFC", text)
# this implementation takes a detour: text -> token id -> token surface forms for t in self.tokenizer.encode( text, allowed_special=allowed_special, disallowed_special=disallowed_special ): tokens.append(self.decoder[t])
return tokens
def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str: """ Converts a sequence of tokens in a single string. """ text = "" temp = b"" for t in tokens: if isinstance(t, str): if temp: text += temp.decode("utf-8", errors=self.errors) temp = b"" text += t elif isinstance(t, bytes): temp += t else: raise TypeError("token should only be of type types or str") if temp: text += temp.decode("utf-8", errors=self.errors) return text
@property def vocab_size(self): return self.tokenizer.n_vocab
def _convert_id_to_token(self, index: int) -> Union[bytes, str]: """Converts an id to a token, special tokens included""" if index in self.decoder: return self.decoder[index] raise ValueError("unknown ids")
def _convert_token_to_id(self, token: Union[bytes, str]) -> int: """Converts a token to an id using the vocab, special tokens included""" if token in self.special_tokens: return self.special_tokens[token] if token in self.mergeable_ranks: return self.mergeable_ranks[token] raise ValueError("unknown token")
def _decode( self, token_ids: Union[int, List[int]], skip_special_tokens: bool = False, errors: Optional[str] = None, **kwargs, ) -> str: if isinstance(token_ids, int): token_ids = [token_ids]
if skip_special_tokens: token_ids = [i for i in token_ids if i < self.eod_id]
return self.tokenizer.decode(token_ids, errors=errors or self.errors)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162# coding=utf-8# Copyright 2024 The Emu team, BAAI and The HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.""" Logits Processor Helper class for Emu3. """
import torch
class Emu3PrefixConstrainedLogitsHelper:
def __init__( self, height, width, img_token, eoi_token, eos_token, eol_token, eof_token, pad_token, visual_tokens, ): self.height = height self.width = width self.img_token = img_token self.eoi_token = eoi_token self.eos_token = eos_token self.eol_token = eol_token self.eof_token = eof_token self.pad_token = pad_token self.visual_tokens = visual_tokens
self.offset_cache = {}
def __call__(self, batch_id, input_ids): if batch_id not in self.offset_cache: position = torch.nonzero(input_ids == self.img_token, as_tuple=True)[0][0] self.offset_cache[batch_id] = position
offset = input_ids.shape[0] - self.offset_cache[batch_id] if offset % (self.width + 1) == 0: return (self.eol_token, ) elif offset == (self.width + 1) * self.height + 1: return (self.eof_token, ) elif offset == (self.width + 1) * self.height + 2: return (self.eoi_token, ) elif offset == (self.width + 1) * self.height + 3: return (self.eos_token, ) elif offset > (self.width + 1) * self.height + 3: return (self.pad_token, ) else: return self.visual_tokens12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970# Copyright 2024 BAAI and the HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.from typing import TYPE_CHECKING
from transformers.utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available,)
_import_structure = {"configuration_emu3visionvq": ["Emu3VisionVQConfig"]}
try: if not is_torch_available(): raise OptionalDependencyNotAvailable()except OptionalDependencyNotAvailable: passelse: _import_structure["modeling_emu3visionvq"] = [ "Emu3VisionVQModel", "Emu3VisionVQPretrainedModel", ]
try: if not is_vision_available(): raise OptionalDependencyNotAvailable()except OptionalDependencyNotAvailable: passelse: _import_structure["image_processing_emu3visionvq"] = ["Emu3VisionVQImageProcessor"]
if TYPE_CHECKING: from .configuration_emu3visionvq import Emu3VisionVQConfig
try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_emu3visionvq import ( Emu3VisionVQModel, Emu3VisionVQPretrainedModel, )
try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_emu3visionvq import Emu3VisionVQImageProcessor
else: import sys
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106# coding=utf-8# Copyright 2024 The Emu team, BAAI and The HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.""" Emu3VisionVQ model configuration """
from typing import List
from transformers.configuration_utils import PretrainedConfigfrom transformers.utils import logging
logger = logging.get_logger(__name__)
class Emu3VisionVQConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Emu3VisionVQ`]. It is used to instantiate an video movq model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a configuration to the VQ model presented in Emu3 paper.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
Args: codebook_size (`int`, *optional*, defaults to 32768): Codebook size of the VQ model. embed_dim (`int`, *optional*, defaults to 4): Dimension of the quantized vector in codebook. z_channels (`int`, *optional*, defaults to 4): Dimension of the output channel of encoder and the input channel of decoder double_z (`bool`, *optional*, defaults to False): Whether double the output dim of the encoder. in_channels (`int`, *optional*, defaults to 3): Input channel of encoder. out_channels (`int`, *optional*, defaults to 3): Output channel of decoder. temporal_downsample_factor (`int`, *optional*, defaults to 4): Temporal downsample factor. ch (`int`, *optional*, defaults to 256): Basic channel number of the intermediate blocks. ch_mult (`List[int]`, *optional*, defaults to `[1, 2, 2, 4]`): Channel scaling factor of the intermediate blocks. num_res_blocks (`int`, *optional*, defaults to 2): Residual block number in each stage. attn_resolutions (`List[int]`, *optional*, defaults to 3): Stage indices to apply attention. dropout (`float`, *optional*, defaults to 0.0): Dropout probability.
```python >>> from transformers import Emu3VisionVQ, Emu3VisionVQConfig
>>> # Initializing a video VQ model of Emu3 configuration >>> configuration = Emu3VisionVQConfig()
>>> # Initializing a model from the Emu3 VQ model style configuration >>> model = Emu3VisionVQModel(configuration)
>>> # Accessing the model configuration >>> configuration = model.config ```"""
model_type = "Emu3VisionVQ"
def __init__( self, codebook_size: int = 32768, embed_dim: int = 4, z_channels: int = 4, double_z: bool = False, in_channels: int = 3, out_channels: int = 3, temporal_downsample_factor: int = 4, ch: int = 256, ch_mult: List[int] = [1, 2, 2, 4], num_res_blocks: int = 2, attn_resolutions: List[int] = [3], dropout: float = 0.0, **kwargs, ): super().__init__(**kwargs)
self.codebook_size = codebook_size self.embed_dim = embed_dim self.z_channels = z_channels self.double_z = double_z self.in_channels = in_channels self.out_channels = out_channels self.temporal_downsample_factor = temporal_downsample_factor self.ch = ch self.ch_mult = ch_mult self.num_res_blocks = num_res_blocks self.attn_resolutions = attn_resolutions self.dropout = dropout123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442# coding=utf-8# Copyright 2024 The Emu team, BAAI and The HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Image processor class for Emu3VisionVQ."""
import mathfrom typing import Dict, List, Optional, Union
import numpy as np
from transformers.image_processing_utils import BaseImageProcessor, BatchFeaturefrom transformers.image_transforms import ( convert_to_rgb, resize, to_channel_dimension_format,)from transformers.image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, infer_channel_dimension_format, is_scaled_image, make_list_of_images, to_numpy_array, valid_images, validate_preprocess_arguments,)from transformers.utils import TensorType, is_vision_available, logging
logger = logging.get_logger(__name__)
if is_vision_available(): from PIL import Image
def smart_resize( height: int, width: int, factor: int = 8, min_pixels: int = 512 * 512, max_pixels: int = 1024 * 1024): """Rescales the image so that the following conditions are met:
1. Both dimensions (height and width) are divisible by 'factor'.
2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
3. The aspect ratio of the image is maintained as closely as possible.
""" if height < factor or width < factor: raise ValueError(f"height:{height} or width:{width} must be larger than factor:{factor}") elif max(height, width) / min(height, width) > 5: raise ValueError( f"absolute aspect ratio must be smaller than 5, got {max(height, width) / min(height, width)}" )
h_bar = round(height / factor) * factor w_bar = round(width / factor) * factor if h_bar * w_bar > max_pixels: beta = math.sqrt((height * width) / max_pixels) h_bar = math.floor(height / beta / factor) * factor w_bar = math.floor(width / beta / factor) * factor elif h_bar * w_bar < min_pixels: beta = math.sqrt(min_pixels / (height * width)) h_bar = math.ceil(height * beta / factor) * factor w_bar = math.ceil(width * beta / factor) * factor
return h_bar, w_bar
class Emu3VisionVQImageProcessor(BaseImageProcessor): r""" Constructs a Emu3VisionVQ image processor that dynamically resizes images based on the original images.
Args: do_resize (`bool`, *optional*, defaults to `True`): Whether to resize the image's (height, width) dimensions. resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`): Resampling filter to use when resizing the image. do_rescale (`bool`, *optional*, defaults to `True`): Whether to rescale the image by the specified scale `rescale_factor`. rescale_factor (`int` or `float`, *optional*, defaults to `1/255`): Scale factor to use if rescaling the image. do_normalize (`bool`, *optional*, defaults to `True`): Whether to normalize the image. image_mean (`float` or `List[float]`, *optional*, defaults to `[0.5, 0.5, 0.5]`): Mean to use if normalizing the image. This is a float or list of floats for each channel in the image. image_std (`float` or `List[float]`, *optional*, defaults to `[0.5, 0.5, 0.5]`): Standard deviation to use if normalizing the image. This is a float or list of floats for each channel in the image. do_convert_rgb (`bool`, *optional*, defaults to `True`): Whether to convert the image to RGB. min_pixels (`int`, *optional*, defaults to `512 * 512`): The min pixels of the image to resize the image. max_pixels (`int`, *optional*, defaults to `1024 * 1024`): The max pixels of the image to resize the image. spatial_factor (`int`, *optional*, defautls to 8): The spatial downsample factor the image will be downsampled in feature extracting phase """
model_input_names = ["pixel_values"]
def __init__( self, do_resize: bool = True, resample: PILImageResampling = PILImageResampling.BICUBIC, do_rescale: bool = True, rescale_factor: Union[int, float] = 1 / 255, do_normalize: bool = True, image_mean: Optional[Union[float, List[float]]] = None, image_std: Optional[Union[float, List[float]]] = None, do_convert_rgb: bool = True, min_pixels: int = 512 * 512, max_pixels: int = 1024 * 1024, spatial_factor: int = 8, **kwargs, ) -> None: super().__init__(**kwargs) self.do_resize = do_resize self.resample = resample self.do_rescale = do_rescale self.rescale_factor = rescale_factor self.do_normalize = do_normalize self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD self.min_pixels = min_pixels self.max_pixels = max_pixels self.size = {"min_pixels": min_pixels, "max_pixels": max_pixels} self.do_convert_rgb = do_convert_rgb self.spatial_factor = spatial_factor
def _preprocess( self, images: ImageInput, do_resize: Optional[bool] = None, resample: PILImageResampling = None, do_rescale: Optional[bool] = None, rescale_factor: Optional[float] = None, do_normalize: Optional[bool] = None, image_mean: Optional[Union[float, List[float]]] = None, image_std: Optional[Union[float, List[float]]] = None, do_convert_rgb: Optional[bool] = None, spatial_factor: Optional[int] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, output_data_format: Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST, ): """ Preprocess an image or batch of images. Copy of the `preprocess` method from `CLIPImageProcessor`.
Args: images (`ImageInput`): Image or batch of images to preprocess. Expects pixel values ranging from 0 to 255. If pixel values range from 0 to 1, set `do_rescale=False`. do_resize (`bool`, *optional*, defaults to `self.do_resize`): Whether to resize the image. resample (`PILImageResampling`, *optional*, defaults to `self.resample`): Resampling filter to use if resizing the image. This can be one of the `PILImageResampling` enums. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`): Whether to rescale the image. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`): Scale factor to use if rescaling the image. do_normalize (`bool`, *optional*, defaults to `self.do_normalize`): Whether to normalize the image. image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`): Mean to use if normalizing the image. Can be a float or a list of floats corresponding to the number of channels in the image. image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`): Standard deviation to use if normalizing the image. Can be a float or a list of floats corresponding to the number of channels in the image. do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`): Whether to convert the image to RGB. spatial_factor (`int`, *optional*, defaults to `self.spatial_factor`): The spatial downsample factor the image will be downsampled in feature extracting phase input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format for the input image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format. output_data_format (`ChannelDimension`, *optional*, defaults to `ChannelDimension.FIRST`): The channel dimension format for the output image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. - Unset: Use the channel dimension format of the input image. """ spatial_factor = spatial_factor if spatial_factor is not None else self.spatial_factor
images = make_list_of_images(images) if do_convert_rgb: images = [convert_to_rgb(image) for image in images]
# All transformations expect numpy arrays. images = [to_numpy_array(image) for image in images]
if is_scaled_image(images[0]) and do_rescale: logger.warning_once( "It looks like you are trying to rescale already rescaled images. If the input" "pixel_values.append()images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again." )
if input_data_format is None: # We assume that all images have the same channel dimension format. input_data_format = infer_channel_dimension_format(images[0])
height, width = get_image_size(images[0], channel_dim=input_data_format) resized_height, resized_width = height, width processed_images = [] for image in images: if do_resize: resized_height, resized_width = smart_resize( height, width, factor=spatial_factor, min_pixels=self.min_pixels, max_pixels=self.max_pixels, ) image = resize( image, size=(resized_height, resized_width), resample=resample, input_data_format=input_data_format )
if do_rescale: image = self.rescale(image, scale=rescale_factor, input_data_format=input_data_format)
if do_normalize: image = self.normalize( image=image, mean=image_mean, std=image_std, input_data_format=input_data_format )
image = to_channel_dimension_format(image, output_data_format, input_channel_dim=input_data_format) processed_images.append(image)
image = np.array(processed_images) return image
def preprocess( self, images: ImageInput, do_resize: Optional[bool] = None, resample: PILImageResampling = None, do_rescale: Optional[bool] = None, rescale_factor: Optional[float] = None, do_normalize: Optional[bool] = None, image_mean: Optional[Union[float, List[float]]] = None, image_std: Optional[Union[float, List[float]]] = None, do_convert_rgb: Optional[bool] = None, spatial_factor: Optional[int] = None, return_tensors: Optional[Union[str, TensorType]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, output_data_format: Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST, ): """ Args: images (`ImageInput`): Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`. do_resize (`bool`, *optional*, defaults to `self.do_resize`): Whether to resize the image. resample (`int`, *optional*, defaults to `self.resample`): Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only has an effect if `do_resize` is set to `True`. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`): Whether to rescale the image. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`): Rescale factor to rescale the image by if `do_rescale` is set to `True`. do_normalize (`bool`, *optional*, defaults to `self.do_normalize`): Whether to normalize the image. image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`): Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`. image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`): Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to `True`. do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`): Whether to convert the image to RGB. spatial_factor (`int`, *optional*, defaults to `self.spatial_factor`): The spatial downsample factor the image will be downsampled in feature extracting phase return_tensors (`str` or `TensorType`, *optional*): The type of tensors to return. Can be one of: - Unset: Return a list of `np.ndarray`. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`. input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format. output_data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`): The channel dimension format for the output image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. - Unset: Use the channel dimension format of the input image. """ do_resize = do_resize if do_resize is not None else self.do_resize resample = resample if resample is not None else self.resample do_rescale = do_rescale if do_rescale is not None else self.do_rescale rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor do_normalize = do_normalize if do_normalize is not None else self.do_normalize image_mean = image_mean if image_mean is not None else self.image_mean image_std = image_std if image_std is not None else self.image_std do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb spatial_factor = spatial_factor if spatial_factor is not None else self.spatial_factor
images = make_list_of_images(images) if images is None or not valid_images(images): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." )
validate_preprocess_arguments( rescale_factor=rescale_factor, do_normalize=do_normalize, image_mean=image_mean, image_std=image_std, do_resize=do_resize, size=self.size, resample=resample, )
pixel_values = [] for image in images: norm_image = self._preprocess( image, do_resize=do_resize, resample=resample, do_rescale=do_rescale, rescale_factor=rescale_factor, do_normalize=do_normalize, image_mean=image_mean, image_std=image_std, do_convert_rgb=do_convert_rgb, spatial_factor=spatial_factor, input_data_format=input_data_format, output_data_format=output_data_format, ) pixel_values.extend(norm_image) pixel_values = np.array(pixel_values) data = {"pixel_values": pixel_values}
return BatchFeature(data=data, tensor_type=return_tensors)
def postprocess( self, images: ImageInput, do_rescale: Optional[bool] = None, rescale_factor: Optional[float] = None, do_normalize: Optional[bool] = None, image_mean: Optional[Union[float, List[float]]] = None, image_std: Optional[Union[float, List[float]]] = None, return_tensors = "PIL.Image.Image", input_data_format: Optional[Union[str, ChannelDimension]] = None, ): """ Postprocess an image or batch of images tensor. Postprocess is the reverse process of preprocess. The parameters should be same as in preprocess.
Args: images (`ImageInput`): Image to postprocess. Expects a single or batch of images with pixel values ranging from -1 to 1. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`): Whether to rescale the image. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`): Rescale factor to rescale the image by if `do_rescale` is set to `True`. do_normalize (`bool`, *optional*, defaults to `self.do_normalize`): Whether to normalize the image. image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`): Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`. image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`): Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to `True`. return_tensors (`str` or `TensorType`, *optional*): The type of tensors to return. Can be one of: - Unset: Return a list of `np.ndarray`. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`. input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format. """ do_rescale = do_rescale if do_rescale is not None else self.do_rescale rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor rescale_factor = 1 / rescale_factor
do_normalize = do_normalize if do_normalize is not None else self.do_normalize image_mean = image_mean if image_mean is not None else self.image_mean image_std = image_std if image_std is not None else self.image_std image_mean, image_std = self.inverse_meanstd(image_mean, image_std)
images = make_list_of_images(images) if isinstance(images[0], Image.Image): return images if len(images) > 1 else images[0]
if input_data_format is None: # We assume that all images have the same channel dimension format. input_data_format = infer_channel_dimension_format(images[0])
pixel_values = [] for image in images: image = to_numpy_array(image) if do_normalize: image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
if do_rescale: image = self.rescale(image, scale=rescale_factor, input_data_format=input_data_format) image = image.clip(0, 255).astype(np.uint8)
if do_normalize and do_rescale and return_tensors == "PIL.Image.Image": image = to_channel_dimension_format(image, ChannelDimension.LAST, input_channel_dim=input_data_format) pixel_values.append(Image.fromarray(image)) else: pixel_values.extend(image)
data = {"pixel_values": pixel_values} return_tensors = return_tensors if return_tensors != "PIL.Image.Image" else None
return BatchFeature(data=data, tensor_type=return_tensors)
def inverse_meanstd(self, image_mean, image_std): image_mean = self.to_tuple(image_mean) image_std = self.to_tuple(image_std)
rev_image_mean = tuple(-m / s for m, s in zip(image_mean, image_std)) rev_image_std = tuple(1 / s for s in image_std)
return rev_image_mean, rev_image_std
def to_tuple(self, value, dim=3): if isinstance(value, int | float): return (value,) * dim
return tuple(value)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822# coding=utf-8# Copyright 2024 The Emu team, BAAI and The HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.""" Emu3VisionVQ model """
import mathfrom typing import Optional, Tuple, Union
import torchfrom torch import nnfrom torch.nn import functional as Ffrom transformers.modeling_utils import PreTrainedModel
from .configuration_emu3visionvq import Emu3VisionVQConfig
class Emu3VisionVQActivation(nn.Module):
def __init__(self): super().__init__()
def __call__(self, x: torch.Tensor): return x * torch.sigmoid(x)
class Emu3VisionVQUpsample(nn.Module):
def __init__(self, in_channels: int): super().__init__() self.conv = nn.Conv2d( in_channels, in_channels, kernel_size=3, stride=1, padding=1, )
def forward(self, x: torch.Tensor): x = F.interpolate(x, scale_factor=2.0, mode="nearest") x = self.conv(x) return x
class Emu3VisionVQDownsample(nn.Module):
def __init__(self, in_channels: int): super().__init__() self.conv = nn.Conv2d( in_channels, in_channels, kernel_size=3, stride=2, padding=0, )
def forward(self, x: torch.Tensor): pad = (0, 1, 0, 1) x = F.pad(x, pad, mode="constant", value=0) x = self.conv(x) return x
class Emu3VisionVQCausalConv3d(nn.Module):
def __init__( self, in_channel: int, out_channel: int, kernel_size: Union[int, Tuple[int, ...]] = (3, 1, 1), stride: Union[int, Tuple[int, ...]] = (1, 1, 1), ): super().__init__()
if isinstance(kernel_size, int): kernel_size = (kernel_size,) * 3 if isinstance(stride, int): stride = (stride,) * 3 hw_pad = [k - s for k, s in zip(kernel_size[1:], stride[1:])] self.padding = tuple() for p in hw_pad[::-1]: self.padding += (p // 2 + p % 2, p // 2) self.padding += (2, 0)
self.conv = nn.Conv3d( in_channel, out_channel, kernel_size, stride=stride, )
def forward(self, x: torch.Tensor): x = F.pad(x, self.padding) x = self.conv(x) return x
class Emu3VisionVQResnetTemporalBlock(nn.Module):
def __init__( self, in_channels: int, out_channels: Optional[int] = None, conv_shortcut: bool = False, dropout: float = 0.0, ): super().__init__() self.in_channels = in_channels out_channels = in_channels if out_channels is None else out_channels self.out_channels = out_channels self.use_conv_shortcut = conv_shortcut
stride = (1, 1, 1) kernel_size = (3, 3, 3)
self.norm1 = nn.BatchNorm3d(in_channels) self.conv1 = Emu3VisionVQCausalConv3d( in_channels, out_channels, kernel_size=kernel_size, stride=stride, ) self.norm2 = nn.BatchNorm3d(out_channels) self.dropout = nn.Dropout(dropout) self.conv2 = Emu3VisionVQCausalConv3d( out_channels, out_channels, kernel_size=kernel_size, stride=stride, ) self.act = Emu3VisionVQActivation()
if self.in_channels != self.out_channels: if self.use_conv_shortcut: self.conv_shortcut = Emu3VisionVQCausalConv3d( in_channels, out_channels, kernel_size=kernel_size, stride=stride, ) else: self.nin_shortcut = nn.Conv3d( in_channels, out_channels, kernel_size=1, stride=1, padding=0, )
def forward(self, x: torch.Tensor): h = self.norm1(x) h = self.act(h) h = self.conv1(h)
h = self.norm2(h) h = self.act(h) h = self.dropout(h) h = self.conv2(h)
if self.in_channels != self.out_channels: if self.use_conv_shortcut: x = self.conv_shortcut(x) else: x = self.nin_shortcut(x)
return x + h
class Emu3VisionVQSpatialNorm(nn.Module):
def __init__( self, f_channels: int, zq_channels: int, norm_layer: nn.Module = nn.GroupNorm, add_conv: bool = False, num_groups: int = 32, eps: float = 1e-6, affine: bool = True, ): super().__init__() self.norm_layer = norm_layer( num_channels=f_channels, num_groups=num_groups, eps=eps, affine=affine, )
self.add_conv = add_conv if self.add_conv: self.conv = nn.Conv2d( zq_channels, zq_channels, kernel_size=3, stride=1, padding=1, )
self.conv_y = nn.Conv2d( zq_channels, f_channels, kernel_size=1, stride=1, padding=0, ) self.conv_b = nn.Conv2d( zq_channels, f_channels, kernel_size=1, stride=1, padding=0, )
def forward(self, x: torch.Tensor, zq: torch.Tensor): zq = F.interpolate(zq, size=x.shape[-2:], mode="nearest")
if self.add_conv: zq = self.conv(zq)
x = self.norm_layer(x) x = x * self.conv_y(zq) + self.conv_b(zq) return x
class Emu3VisionVQResnetBlock(nn.Module):
def __init__( self, in_channels: int, out_channels: Optional[int] = None, conv_shortcut: bool = False, dropout: float = 0.0, zq_ch: Optional[int] = None, add_conv: bool = False, ): super().__init__() self.in_channels = in_channels out_channels = in_channels if out_channels is None else out_channels self.out_channels = out_channels self.use_conv_shortcut = conv_shortcut self.zq_ch = zq_ch
if zq_ch is None: norm_kwargs = dict(num_groups=32, eps=1e-6, affine=True) self.norm1 = nn.GroupNorm(num_channels=in_channels, **norm_kwargs) self.norm2 = nn.GroupNorm(num_channels=out_channels, **norm_kwargs) else: self.norm1 = Emu3VisionVQSpatialNorm(in_channels, zq_ch, add_conv=add_conv) self.norm2 = Emu3VisionVQSpatialNorm(out_channels, zq_ch, add_conv=add_conv)
self.conv1 = nn.Conv2d( in_channels, out_channels, kernel_size=3, stride=1, padding=1, )
self.dropout = nn.Dropout(dropout) self.conv2 = nn.Conv2d( out_channels, out_channels, kernel_size=3, stride=1, padding=1, )
self.act = Emu3VisionVQActivation()
if self.in_channels != self.out_channels: if self.use_conv_shortcut: self.conv_shortcut = nn.Conv2d( in_channels, out_channels, kernel_size=3, stride=1, padding=1, ) else: self.nin_shortcut = nn.Conv2d( in_channels, out_channels, kernel_size=1, stride=1, padding=0, )
def forward(self, x: torch.Tensor, zq: Optional[torch.Tensor] = None): norm_args = tuple() if self.zq_ch is None else (zq, )
h = self.norm1(x, *norm_args) h = self.act(h) h = self.conv1(h)
h = self.norm2(h, *norm_args) h = self.act(h) h = self.dropout(h) h = self.conv2(h)
if self.in_channels != self.out_channels: if self.use_conv_shortcut: x = self.conv_shortcut(x) else: x = self.nin_shortcut(x)
return x + h
class Emu3VisionVQAttnBlock(nn.Module):
def __init__( self, in_channels: int, zq_ch: Optional[int] = None, add_conv: bool = False ): super().__init__() self.in_channels = in_channels self.zq_ch = zq_ch
if zq_ch is None: norm_kwargs = dict(num_groups=32, eps=1e-6, affine=True) self.norm = nn.GroupNorm(num_channels=in_channels, **norm_kwargs) else: self.norm = Emu3VisionVQSpatialNorm(in_channels, zq_ch, add_conv=add_conv)
self.q = nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0, ) self.k = nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0, ) self.v = nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0, ) self.proj_out = nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0, )
def forward(self, x: torch.Tensor, zq: Optional[torch.Tensor] = None): norm_args = tuple() if self.zq_ch is None else (zq, )
nx = self.norm(x, *norm_args) q = self.q(nx) k = self.k(nx) v = self.v(nx)
# compute attention b, c, h, w = q.shape q = q.reshape(b, c, h * w) k = k.reshape(b, c, h * w) score = torch.bmm(q.permute(0, 2, 1), k) score = score / (c ** 0.5) score = F.softmax(score, dim=2)
# attend to values v = v.reshape(b, c, h * w) v = torch.bmm(v, score.permute(0, 2, 1)) v = v.reshape(b, c, h, w)
v = self.proj_out(v)
return x + v
class Emu3VisionVQTemporalUpsample(nn.Module):
def __init__( self, in_channel: int, out_channel: int, kernel_size: Tuple[int, ...] = (3, 3, 3), stride: Tuple[int, ...] = (1, 1, 1) ): super().__init__() self.in_channel = in_channel self.out_channel = out_channel self.conv = Emu3VisionVQCausalConv3d( in_channel, out_channel, kernel_size, stride=stride, ) def forward(self, x: torch.Tensor): b, c, t, h, w = x.shape x = x.permute(0, 1, 3, 4, 2).contiguous().view(b, -1, t) x = F.interpolate(x, scale_factor=2.0, mode="nearest") x = x.view(b, c, h, w, -1).permute(0, 1, 4, 2, 3).contiguous() x = self.conv(x) return x
class Emu3VisionVQTemporalDownsample(nn.Module):
def __init__( self, in_channel: int, out_channel: int, kernel_size: Tuple[int, ...] = (4, 3, 3), stride: Tuple[int, ...] = (2, 1, 1), ): super().__init__() self.in_channel = in_channel self.out_channel = out_channel self.kernel_size = kernel_size
self.conv = Emu3VisionVQCausalConv3d( in_channel, out_channel, kernel_size=kernel_size, stride=stride, ) def forward(self, x: torch.Tensor): x = self.conv(x) return x
class Emu3VisionVQVectorQuantizer(nn.Module):
def __init__(self, config: Emu3VisionVQConfig): super().__init__() self.embedding = nn.Embedding(config.codebook_size, config.embed_dim) self.embedding.weight.data.uniform_(-1.0 / config.codebook_size, 1.0 / config.codebook_size)
def forward(self, x: torch.Tensor): # b t c h w -> b t h w c b, t, c, h, w = x.shape x = x.permute(0, 1, 3, 4, 2).contiguous() x_flattened = x.view(-1, c)
codebook = self.embedding.weight
d = torch.sum(x_flattened ** 2, dim=1, keepdim=True) + \ torch.sum(codebook ** 2, dim=1) - 2 * \ torch.einsum('bd,dn->bn', x_flattened, codebook.permute(1, 0))
indices = torch.argmin(d, dim=1) indices = indices.view(b, t, h, w) return indices
class Emu3VisionVQEncoder(nn.Module):
def __init__(self, config: Emu3VisionVQConfig): super().__init__() self.ch = config.ch self.num_resolutions = len(config.ch_mult) self.num_res_blocks = config.num_res_blocks self.in_channels = config.in_channels
# downsampling self.conv_in = nn.Conv2d( self.in_channels, self.ch, kernel_size=3, stride=1, padding=1 )
in_ch_mult = (1,) + tuple(config.ch_mult) self.down = nn.ModuleList() for i_level in range(self.num_resolutions): block = nn.ModuleList() attn = nn.ModuleList() block_in = config.ch * in_ch_mult[i_level] block_out = config.ch * config.ch_mult[i_level] for i_block in range(self.num_res_blocks): block.append( Emu3VisionVQResnetBlock( in_channels=block_in, out_channels=block_out, dropout=config.dropout, ) ) block_in = block_out if i_level in config.attn_resolutions: attn.append(Emu3VisionVQAttnBlock(block_in))
down = nn.Module() down.block = block down.attn = attn if i_level != self.num_resolutions - 1: down.downsample = Emu3VisionVQDownsample(block_in)
self.down.append(down)
# middle self.mid = nn.Module() self.mid.block_1 = Emu3VisionVQResnetBlock( in_channels=block_in, out_channels=block_in, dropout=config.dropout, ) self.mid.attn_1 = Emu3VisionVQAttnBlock(block_in) self.mid.block_2 = Emu3VisionVQResnetBlock( in_channels=block_in, out_channels=block_in, dropout=config.dropout, )
# end self.norm_out = nn.GroupNorm(num_channels=block_in, num_groups=32, eps=1e-6, affine=True)
out_z_channels = 2 * config.z_channels if config.double_z else config.z_channels self.conv_out = nn.Conv2d( block_in, out_z_channels, kernel_size=3, stride=1, padding=1, ) temporal_down_blocks = int(math.log2(config.temporal_downsample_factor)) self.time_conv = nn.ModuleList()
for i in range(temporal_down_blocks): conv = Emu3VisionVQTemporalDownsample(out_z_channels, out_z_channels) self.time_conv.append(conv)
self.time_res_stack = nn.Sequential(*[ Emu3VisionVQResnetTemporalBlock( in_channels=out_z_channels, out_channels=out_z_channels, dropout=config.dropout, ) for _ in range(self.num_res_blocks) ])
self.act = Emu3VisionVQActivation()
def forward(self, x: torch.Tensor): t = x.shape[1] x = x.reshape(-1, *x.shape[2:])
# downsampling h = self.conv_in(x) for i_level in range(self.num_resolutions): for i_block in range(self.num_res_blocks): h = self.down[i_level].block[i_block](h) if len(self.down[i_level].attn) > 0: h = self.down[i_level].attn[i_block](h)
if i_level != self.num_resolutions - 1: h = self.down[i_level].downsample(h)
h = self.mid.block_1(h) h = self.mid.attn_1(h) h = self.mid.block_2(h) # end h = self.norm_out(h) h = self.act(h)
h = self.conv_out(h)
h = h.reshape(-1, t, *h.shape[1:]) h = h.permute(0, 2, 1, 3, 4)
for conv in self.time_conv: h = self.act(conv(h))
h = self.time_res_stack(h) h = h.permute(0, 2, 1, 3, 4)
return h
class Emu3VisionVQDecoder(nn.Module):
def __init__(self, config: Emu3VisionVQConfig): super().__init__() self.ch = config.ch self.num_resolutions = len(config.ch_mult) self.num_res_blocks = config.num_res_blocks
in_ch_mult = (1,) + tuple(config.ch_mult) zq_ch = config.embed_dim
block_in = config.ch * config.ch_mult[-1] self.time_res_stack = nn.Sequential(*[ Emu3VisionVQResnetTemporalBlock( in_channels=config.z_channels, out_channels=config.z_channels, dropout=config.dropout, ) for _ in range(config.num_res_blocks) ])
tempo_upsample_block_num = int(math.log2(config.temporal_downsample_factor)) self.time_conv = nn.ModuleList() for i in range(tempo_upsample_block_num): conv = Emu3VisionVQTemporalUpsample(config.z_channels, config.z_channels) self.time_conv.append(conv) self.conv_in = nn.Conv2d( config.z_channels, block_in, kernel_size=3, stride=1, padding=1, )
# middle self.mid = nn.Module() self.mid.block_1 = Emu3VisionVQResnetBlock( in_channels=block_in, out_channels=block_in, dropout=config.dropout, zq_ch=zq_ch, ) self.mid.attn_1 = Emu3VisionVQAttnBlock(block_in, zq_ch) self.mid.block_2 = Emu3VisionVQResnetBlock( in_channels=block_in, out_channels=block_in, dropout=config.dropout, zq_ch=zq_ch, )
# upsampling self.up = nn.ModuleList() for i_level in reversed(range(self.num_resolutions)): block = nn.ModuleList() attn = nn.ModuleList() block_out = config.ch * config.ch_mult[i_level] for i_block in range(self.num_res_blocks + 1): block.append( Emu3VisionVQResnetBlock( in_channels=block_in, out_channels=block_out, dropout=config.dropout, zq_ch=zq_ch, ) ) block_in = block_out if i_level in config.attn_resolutions: attn.append(Emu3VisionVQAttnBlock(block_in, zq_ch))
up = nn.Module() up.block = block up.attn = attn if i_level != 0: up.upsample = Emu3VisionVQUpsample(block_in)
self.up.insert(0, up)
self.act = Emu3VisionVQActivation()
self.norm_out = Emu3VisionVQSpatialNorm(block_in, zq_ch) self.conv_out = nn.Conv2d( block_in, config.out_channels, kernel_size=3, stride=1, padding=1, )
def forward(self, z: torch.Tensor, zq: torch.Tensor): z_zq = torch.cat((z, zq), dim=0) z_zq = z_zq.permute(0, 2, 1, 3, 4) z_zq = self.time_res_stack(z_zq)
for conv in self.time_conv: z_zq = self.act(conv(z_zq))
z_zq = z_zq.permute(0, 2, 1, 3, 4)
h, zq = torch.chunk(z_zq, 2, dim=0)
h = h.reshape(-1, *h.shape[2:]) zq = zq.reshape(-1, *zq.shape[2:]) h = self.conv_in(h) # middle h = self.mid.block_1(h, zq) h = self.mid.attn_1(h, zq) h = self.mid.block_2(h, zq)
# upsampling for i_level in reversed(range(self.num_resolutions)): for i_block in range(self.num_res_blocks+1): h = self.up[i_level].block[i_block](h, zq) if len(self.up[i_level].attn) > 0: h = self.up[i_level].attn[i_block](h, zq)
if i_level != 0: h = self.up[i_level].upsample(h)
h = self.norm_out(h, zq) h = self.act(h) h = self.conv_out(h)
return h
class Emu3VisionVQPretrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """
config_class = Emu3VisionVQConfig base_model_prefix = "emuvideovq" main_input_name = "pixel_values" _no_split_modules = ["Emu3VisionVQResnetBlock", "Emu3VisionVQAttnBlock", "Emu3VisionVQResnetTemporalBlock"]
def _init_weights(self, module): if isinstance(module, (nn.Conv2d, nn.Conv3d)): nn.init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu") # copied from the `reset_parameters` method of `class Linear(Module)` in `torch`. elif isinstance(module, nn.Linear): nn.init.kaiming_uniform_(module.weight, a=math.sqrt(5)) if module.bias is not None: fan_in, _ = nn.init._calculate_fan_in_and_fan_out(module.weight) bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0 nn.init.uniform_(module.bias, -bound, bound) elif isinstance(module, (nn.BatchNorm2d, nn.BatchNorm3d, nn.GroupNorm)): nn.init.constant_(module.weight, 1) nn.init.constant_(module.bias, 0)
class Emu3VisionVQModel(Emu3VisionVQPretrainedModel):
def __init__(self, config): super().__init__(config) self.config = config
self.encoder = Emu3VisionVQEncoder(config) self.decoder = Emu3VisionVQDecoder(config) self.quantize = Emu3VisionVQVectorQuantizer(config)
self.quant_conv = Emu3VisionVQCausalConv3d(config.z_channels, config.embed_dim) self.post_quant_conv = Emu3VisionVQCausalConv3d(config.embed_dim, config.z_channels)
self.spatial_scale_factor = 2 ** (len(config.ch_mult) - 1)
self.post_init()
def encode(self, x: torch.Tensor): ndim = x.ndim if ndim == 4: t = self.config.temporal_downsample_factor b, c, h, w = x.shape x = x.unsqueeze(1).repeat(1, t, 1, 1, 1) elif ndim == 5: b, t, c, h, w = x.shape
h = self.encoder(x)
# b t c h w -> b c t h w h = h.permute(0, 2, 1, 3, 4) h = self.quant_conv(h) # b c t h w -> b t c h w h = h.permute(0, 2, 1, 3, 4)
codes = self.quantize(h)
if ndim == 4: codes = codes.squeeze(1)
return codes
def decode(self, x: torch.Tensor): ndim = x.ndim if ndim == 3: x = x.unsqueeze(1)
b, t, h, w = x.shape quant = self.quantize.embedding(x.flatten()) c = quant.shape[-1] quant = quant.view(b, t, h, w, c).permute(0, 4, 1, 2, 3).contiguous() quant2 = self.post_quant_conv(quant)
quant = quant.permute(0, 2, 1, 3, 4) quant2 = quant2.permute(0, 2, 1, 3, 4)
video = self.decoder(quant2, quant) video = video.reshape( b, t * self.config.temporal_downsample_factor, self.config.out_channels, h * self.spatial_scale_factor, w * self.spatial_scale_factor, ) if ndim == 3: return video[:, 0] return video
@property def device(self): return next(self.parameters()).device
@property def dtype(self): return next(self.parameters()).dtype1234567891011121314## Language models for text-conditional image generation
### Requirements```pip install ftfypip install transformerspip install acceleratepip install sentencepiecepip install pandaspip install bs4```
### Language ModelsDownload flan-t5-xl models from [flan-t5-xl](https://huggingface.co/google/flan-t5-xl) and put into the folder of `./pretrained_models/t5-ckpt/`123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129import torchtorch.backends.cuda.matmul.allow_tf32 = Truetorch.backends.cudnn.allow_tf32 = Trueimport torch.distributed as distfrom torch.utils.data import Dataset, DataLoaderfrom torch.utils.data.distributed import DistributedSamplerimport numpy as npimport argparseimport osimport json
from utils.distributed import init_distributed_modefrom language.t5 import T5Embedder
CAPTION_KEY = { 'blip': 0, 'llava': 1, 'llava_first': 2,}################################################################################## Training Helper Functions ##################################################################################class CustomDataset(Dataset): def __init__(self, lst_dir, start, end, caption_key, trunc_caption=False): img_path_list = [] for lst_name in sorted(os.listdir(lst_dir))[start: end+1]: if not lst_name.endswith('.jsonl'): continue file_path = os.path.join(lst_dir, lst_name) with open(file_path, 'r') as file: for line_idx, line in enumerate(file): data = json.loads(line) # caption = data[caption_key] caption = data['text'][CAPTION_KEY[caption_key]] code_dir = file_path.split('/')[-1].split('.')[0] if trunc_caption: caption = caption.split('.')[0] img_path_list.append((caption, code_dir, line_idx)) self.img_path_list = img_path_list
def __len__(self): return len(self.img_path_list)
def __getitem__(self, index): caption, code_dir, code_name = self.img_path_list[index] return caption, code_dir, code_name
################################################################################## Training Loop ##################################################################################def main(args): """ Trains a new DiT model. """ assert torch.cuda.is_available(), "Training currently requires at least one GPU."
# Setup DDP: # dist.init_process_group("nccl") init_distributed_mode(args) rank = dist.get_rank() device = rank % torch.cuda.device_count() seed = args.global_seed * dist.get_world_size() + rank torch.manual_seed(seed) torch.cuda.set_device(device) print(f"Starting rank={rank}, seed={seed}, world_size={dist.get_world_size()}.")
# Setup a feature folder: if rank == 0: os.makedirs(args.t5_path, exist_ok=True)
# Setup data: print(f"Dataset is preparing...") dataset = CustomDataset(args.data_path, args.data_start, args.data_end, args.caption_key, args.trunc_caption) sampler = DistributedSampler( dataset, num_replicas=dist.get_world_size(), rank=rank, shuffle=False, seed=args.global_seed ) loader = DataLoader( dataset, batch_size=1, # important! shuffle=False, sampler=sampler, num_workers=args.num_workers, pin_memory=True, drop_last=False ) print(f"Dataset contains {len(dataset):,} images")
precision = {'none': torch.float32, 'bf16': torch.bfloat16, 'fp16': torch.float16}[args.precision] assert os.path.exists(args.t5_model_path) t5_xxl = T5Embedder( device=device, local_cache=True, cache_dir=args.t5_model_path, dir_or_name=args.t5_model_type, torch_dtype=precision )
for caption, code_dir, code_name in loader: caption_embs, emb_masks = t5_xxl.get_text_embeddings(caption) valid_caption_embs = caption_embs[:, :emb_masks.sum()] x = valid_caption_embs.to(torch.float32).detach().cpu().numpy() os.makedirs(os.path.join(args.t5_path, code_dir[0]), exist_ok=True) np.save(os.path.join(args.t5_path, code_dir[0], '{}.npy'.format(code_name.item())), x) print(code_name.item())
dist.destroy_process_group()
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--data-path", type=str, required=True) parser.add_argument("--t5-path", type=str, required=True) parser.add_argument("--data-start", type=int, required=True) parser.add_argument("--data-end", type=int, required=True) parser.add_argument("--caption-key", type=str, default='blip', choices=list(CAPTION_KEY.keys())) parser.add_argument("--trunc-caption", action='store_true', default=False) parser.add_argument("--t5-model-path", type=str, default='./pretrained_models/t5-ckpt') parser.add_argument("--t5-model-type", type=str, default='flan-t5-xl') parser.add_argument("--precision", type=str, default='bf16', choices=["none", "fp16", "bf16"]) parser.add_argument("--global-seed", type=int, default=0) parser.add_argument("--num-workers", type=int, default=24) args = parser.parse_args() main(args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205# Modified from:# PixArt: https://github.com/PixArt-alpha/PixArt-alpha/blob/master/diffusion/model/t5.pyimport osimport reimport htmlimport urllib.parse as ul
import ftfyimport torchfrom bs4 import BeautifulSoupfrom transformers import T5EncoderModel, AutoTokenizerfrom huggingface_hub import hf_hub_download
class T5Embedder: available_models = ['t5-v1_1-xxl', 't5-v1_1-xl', 'flan-t5-xl'] bad_punct_regex = re.compile(r'['+'#®•©™&@·º½¾¿¡§~'+'\)'+'\('+'\]'+'\['+'\}'+'\{'+'\|'+'\\'+'\/'+'\*' + r']{1,}') # noqa
def __init__(self, device, dir_or_name='t5-v1_1-xxl', *, local_cache=False, cache_dir=None, hf_token=None, use_text_preprocessing=True, t5_model_kwargs=None, torch_dtype=None, use_offload_folder=None, model_max_length=120): self.device = torch.device(device) self.torch_dtype = torch_dtype or torch.bfloat16 if t5_model_kwargs is None: t5_model_kwargs = {'low_cpu_mem_usage': True, 'torch_dtype': self.torch_dtype} t5_model_kwargs['device_map'] = {'shared': self.device, 'encoder': self.device}
self.use_text_preprocessing = use_text_preprocessing self.hf_token = hf_token self.cache_dir = cache_dir or os.path.expanduser('~/.cache/IF_') self.dir_or_name = dir_or_name tokenizer_path, path = dir_or_name, dir_or_name if local_cache: cache_dir = os.path.join(self.cache_dir, dir_or_name) tokenizer_path, path = cache_dir, cache_dir elif dir_or_name in self.available_models: cache_dir = os.path.join(self.cache_dir, dir_or_name) for filename in [ 'config.json', 'special_tokens_map.json', 'spiece.model', 'tokenizer_config.json', 'pytorch_model.bin.index.json', 'pytorch_model-00001-of-00002.bin', 'pytorch_model-00002-of-00002.bin' ]: hf_hub_download(repo_id=f'DeepFloyd/{dir_or_name}', filename=filename, cache_dir=cache_dir, force_filename=filename, token=self.hf_token) tokenizer_path, path = cache_dir, cache_dir else: cache_dir = os.path.join(self.cache_dir, 't5-v1_1-xxl') for filename in [ 'config.json', 'special_tokens_map.json', 'spiece.model', 'tokenizer_config.json', ]: hf_hub_download(repo_id='DeepFloyd/t5-v1_1-xxl', filename=filename, cache_dir=cache_dir, force_filename=filename, token=self.hf_token) tokenizer_path = cache_dir
print(tokenizer_path) # self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_path) self.tokenizer = AutoTokenizer.from_pretrained( "google/flan-t5-xl", cache_dir=cache_dir, ) # self.model = T5EncoderModel.from_pretrained(path, **t5_model_kwargs).eval() self.model = T5EncoderModel.from_pretrained("google/flan-t5-xl", **t5_model_kwargs).eval() self.model_max_length = model_max_length
def get_text_embeddings(self, texts): texts = [self.text_preprocessing(text) for text in texts]
text_tokens_and_mask = self.tokenizer( texts, max_length=self.model_max_length, padding='max_length', truncation=True, return_attention_mask=True, add_special_tokens=True, return_tensors='pt' )
text_tokens_and_mask['input_ids'] = text_tokens_and_mask['input_ids'] text_tokens_and_mask['attention_mask'] = text_tokens_and_mask['attention_mask']
with torch.no_grad(): text_encoder_embs = self.model( input_ids=text_tokens_and_mask['input_ids'].to(self.device), attention_mask=text_tokens_and_mask['attention_mask'].to(self.device), )['last_hidden_state'].detach() return text_encoder_embs, text_tokens_and_mask['attention_mask'].to(self.device)
def text_preprocessing(self, text): if self.use_text_preprocessing: # The exact text cleaning as was in the training stage: text = self.clean_caption(text) text = self.clean_caption(text) return text else: return text.lower().strip()
@staticmethod def basic_clean(text): text = ftfy.fix_text(text) text = html.unescape(html.unescape(text)) return text.strip()
def clean_caption(self, caption): caption = str(caption) caption = ul.unquote_plus(caption) caption = caption.strip().lower() caption = re.sub('<person>', 'person', caption) # urls: caption = re.sub( r'\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))', # noqa '', caption) # regex for urls caption = re.sub( r'\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))', # noqa '', caption) # regex for urls # html: caption = BeautifulSoup(caption, features='html.parser').text
# @<nickname> caption = re.sub(r'@[\w\d]+\b', '', caption)
# 31C0—31EF CJK Strokes # 31F0—31FF Katakana Phonetic Extensions # 3200—32FF Enclosed CJK Letters and Months # 3300—33FF CJK Compatibility # 3400—4DBF CJK Unified Ideographs Extension A # 4DC0—4DFF Yijing Hexagram Symbols # 4E00—9FFF CJK Unified Ideographs caption = re.sub(r'[\u31c0-\u31ef]+', '', caption) caption = re.sub(r'[\u31f0-\u31ff]+', '', caption) caption = re.sub(r'[\u3200-\u32ff]+', '', caption) caption = re.sub(r'[\u3300-\u33ff]+', '', caption) caption = re.sub(r'[\u3400-\u4dbf]+', '', caption) caption = re.sub(r'[\u4dc0-\u4dff]+', '', caption) caption = re.sub(r'[\u4e00-\u9fff]+', '', caption) #######################################################
# все виды тире / all types of dash --> "-" caption = re.sub( r'[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+', # noqa '-', caption)
# кавычки к одному стандарту caption = re.sub(r'[`´«»“”¨]', '"', caption) caption = re.sub(r'[‘’]', "'", caption)
# " caption = re.sub(r'"?', '', caption) # & caption = re.sub(r'&', '', caption)
# ip adresses: caption = re.sub(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', ' ', caption)
# article ids: caption = re.sub(r'\d:\d\d\s+$', '', caption)
# \n caption = re.sub(r'\\n', ' ', caption)
# "#123" caption = re.sub(r'#\d{1,3}\b', '', caption) # "#12345.." caption = re.sub(r'#\d{5,}\b', '', caption) # "123456.." caption = re.sub(r'\b\d{6,}\b', '', caption) # filenames: caption = re.sub(r'[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)', '', caption)
# caption = re.sub(r'[\"\']{2,}', r'"', caption) # """AUSVERKAUFT""" caption = re.sub(r'[\.]{2,}', r' ', caption) # """AUSVERKAUFT"""
caption = re.sub(self.bad_punct_regex, r' ', caption) # ***AUSVERKAUFT***, #AUSVERKAUFT caption = re.sub(r'\s+\.\s+', r' ', caption) # " . "
# this-is-my-cute-cat / this_is_my_cute_cat regex2 = re.compile(r'(?:\-|\_)') if len(re.findall(regex2, caption)) > 3: caption = re.sub(regex2, ' ', caption)
caption = self.basic_clean(caption)
caption = re.sub(r'\b[a-zA-Z]{1,3}\d{3,15}\b', '', caption) # jc6640 caption = re.sub(r'\b[a-zA-Z]+\d+[a-zA-Z]+\b', '', caption) # jc6640vc caption = re.sub(r'\b\d+[a-zA-Z]+\d+\b', '', caption) # 6640vc231
caption = re.sub(r'(worldwide\s+)?(free\s+)?shipping', '', caption) caption = re.sub(r'(free\s)?download(\sfree)?', '', caption) caption = re.sub(r'\bclick\b\s(?:for|on)\s\w+', '', caption) caption = re.sub(r'\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?', '', caption) caption = re.sub(r'\bpage\s+\d+\b', '', caption)
caption = re.sub(r'\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\b', r' ', caption) # j2d1a2a...
caption = re.sub(r'\b\d+\.?\d*[xх×]\d+\.?\d*\b', '', caption)
caption = re.sub(r'\b\s+\:\s+', r': ', caption) caption = re.sub(r'(\D[,\./])\b', r'\1 ', caption) caption = re.sub(r'\s+', ' ', caption)
caption.strip()
caption = re.sub(r'^[\"\']([\w\W]+)[\"\']$', r'\1', caption) caption = re.sub(r'^[\'\_,\-\:;]', r'', caption) caption = re.sub(r'[\'\_,\-\:\-\+]$', r'', caption) caption = re.sub(r'^\.\S+$', '', caption)
return caption.strip()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504# Modified from:# VQGAN: https://github.com/CompVis/taming-transformers/blob/master/taming/modules/transformer/mingpt.py# DiT: https://github.com/facebookresearch/DiT/blob/main/models.py # nanoGPT: https://github.com/karpathy/nanoGPT/blob/master/model.py# llama: https://github.com/facebookresearch/llama/blob/main/llama/model.py# gpt-fast: https://github.com/pytorch-labs/gpt-fast/blob/main/model.py# PixArt: https://github.com/PixArt-alpha/PixArt-alpha/blob/master/diffusion/model/nets/PixArt_blocks.pyfrom dataclasses import dataclassfrom typing import Optional, List
import torchimport torch.nn as nnfrom torch.nn import functional as F
def drop_path(x, drop_prob: float = 0., training: bool = False, scale_by_keep: bool = True): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument.
""" if drop_prob == 0. or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets random_tensor = x.new_empty(shape).bernoulli_(keep_prob) if keep_prob > 0.0 and scale_by_keep: random_tensor.div_(keep_prob) return x * random_tensor
class DropPath(torch.nn.Module): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). """ def __init__(self, drop_prob: float = 0., scale_by_keep: bool = True): super(DropPath, self).__init__() self.drop_prob = drop_prob self.scale_by_keep = scale_by_keep
def forward(self, x): return drop_path(x, self.drop_prob, self.training, self.scale_by_keep)
def extra_repr(self): return f'drop_prob={round(self.drop_prob,3):0.3f}'
def find_multiple(n: int, k: int): if n % k == 0: return n return n + k - (n % k)
@dataclassclass ModelArgs: dim: int = 4096 n_layer: int = 32 n_head: int = 32 n_kv_head: Optional[int] = None multiple_of: int = 256 # make SwiGLU hidden layer size multiple of large power of 2 ffn_dim_multiplier: Optional[float] = None rope_base: float = 10000 norm_eps: float = 1e-5 initializer_range: float = 0.02 token_dropout_p: float = 0.1 attn_dropout_p: float = 0.0 resid_dropout_p: float = 0.1 ffn_dropout_p: float = 0.1 drop_path_rate: float = 0.0
num_classes: int = 1000 caption_dim: int = 2048 class_dropout_prob: float = 0.1 model_type: str = 'c2i'
vocab_size: int = 16384 cls_token_num: int = 1 block_size: int = 256 max_batch_size: int = 32 max_seq_len: int = 2048
################################################################################## Embedding Layers for Class Labels ##################################################################################class LabelEmbedder(nn.Module): """ Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance. """ def __init__(self, num_classes, hidden_size, dropout_prob): super().__init__() use_cfg_embedding = dropout_prob > 0 self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size) self.num_classes = num_classes self.dropout_prob = dropout_prob
def token_drop(self, labels, force_drop_ids=None): """ Drops labels to enable classifier-free guidance. """ if force_drop_ids is None: drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob else: drop_ids = force_drop_ids == 1 labels = torch.where(drop_ids, self.num_classes, labels) return labels
def forward(self, labels, train, force_drop_ids=None): use_dropout = self.dropout_prob > 0 if (train and use_dropout) or (force_drop_ids is not None): labels = self.token_drop(labels, force_drop_ids) embeddings = self.embedding_table(labels).unsqueeze(1) return embeddings
################################################################################## Embedding Layers for Text Feature ##################################################################################class CaptionEmbedder(nn.Module): """ Embeds text caption into vector representations. Also handles label dropout for classifier-free guidance. """ def __init__(self, in_channels, hidden_size, uncond_prob, token_num=120): super().__init__() self.cap_proj = MLP(in_features=in_channels, hidden_features=hidden_size, out_features=hidden_size) self.register_buffer("uncond_embedding", nn.Parameter(torch.randn(token_num, in_channels) / in_channels ** 0.5)) self.uncond_prob = uncond_prob
def token_drop(self, caption, force_drop_ids=None): """ Drops labels to enable classifier-free guidance. """ if force_drop_ids is None: drop_ids = torch.rand(caption.shape[0], device=caption.device) < self.uncond_prob else: drop_ids = force_drop_ids == 1 caption = torch.where(drop_ids[:, None, None], self.uncond_embedding, caption) return caption
def forward(self, caption, train, force_drop_ids=None): use_dropout = self.uncond_prob > 0 if (train and use_dropout) or (force_drop_ids is not None): caption = self.token_drop(caption, force_drop_ids) embeddings = self.cap_proj(caption) return embeddings
class MLP(nn.Module): def __init__(self, in_features, hidden_features, out_features): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features, bias=False) self.act = nn.GELU(approximate='tanh') self.fc2 = nn.Linear(hidden_features, out_features, bias=False)
def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.fc2(x) return x
################################################################################## GPT Model ##################################################################################class RMSNorm(torch.nn.Module): def __init__(self, dim: int, eps: float = 1e-5): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(dim))
def _norm(self, x): return x * torch.rsqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps)
def forward(self, x): output = self._norm(x.float()).type_as(x) return output * self.weight
class FeedForward(nn.Module): def __init__(self, config: ModelArgs): super().__init__() hidden_dim = 4 * config.dim hidden_dim = int(2 * hidden_dim / 3) # custom dim factor multiplier if config.ffn_dim_multiplier is not None: hidden_dim = int(config.ffn_dim_multiplier * hidden_dim) hidden_dim = find_multiple(hidden_dim, config.multiple_of)
self.w1 = nn.Linear(config.dim, hidden_dim, bias=False) self.w3 = nn.Linear(config.dim, hidden_dim, bias=False) self.w2 = nn.Linear(hidden_dim, config.dim, bias=False) self.ffn_dropout = nn.Dropout(config.ffn_dropout_p)
def forward(self, x): return self.ffn_dropout(self.w2(F.silu(self.w1(x)) * self.w3(x)))
class KVCache(nn.Module): def __init__(self, max_batch_size, max_seq_length, n_head, head_dim, dtype): super().__init__() cache_shape = (max_batch_size, n_head, max_seq_length, head_dim) self.register_buffer('k_cache', torch.zeros(cache_shape, dtype=dtype)) self.register_buffer('v_cache', torch.zeros(cache_shape, dtype=dtype))
def update(self, input_pos, k_val, v_val): # input_pos: [S], k_val: [B, H, S, D] # print('input_pos kv', input_pos.shape, input_pos) assert input_pos.shape[0] == k_val.shape[2] k_out = self.k_cache v_out = self.v_cache k_out[:, :, input_pos] = k_val v_out[:, :, input_pos] = v_val
return k_out, v_out
class Attention(nn.Module): def __init__(self, config: ModelArgs): super().__init__() assert config.dim % config.n_head == 0 self.dim = config.dim self.head_dim = config.dim // config.n_head self.n_head = config.n_head self.n_kv_head = config.n_kv_head if config.n_kv_head is not None else config.n_head total_kv_dim = (self.n_head + 2 * self.n_kv_head) * self.head_dim
# key, query, value projections for all heads, but in a batch self.wqkv = nn.Linear(config.dim, total_kv_dim, bias=False) self.wo = nn.Linear(config.dim, config.dim, bias=False) self.kv_cache = None
# regularization self.attn_dropout_p = config.attn_dropout_p self.resid_dropout = nn.Dropout(config.resid_dropout_p)
def forward( self, x: torch.Tensor, freqs_cis: torch.Tensor = None, input_pos: Optional[torch.Tensor] = None, mask: Optional[torch.Tensor] = None ): bsz, seqlen, _ = x.shape kv_size = self.n_kv_head * self.head_dim xq, xk, xv = self.wqkv(x).split([self.dim, kv_size, kv_size], dim=-1)
xq = xq.view(bsz, seqlen, self.n_head, self.head_dim) xk = xk.view(bsz, seqlen, self.n_kv_head, self.head_dim) xv = xv.view(bsz, seqlen, self.n_kv_head, self.head_dim) xq = apply_rotary_emb(xq, freqs_cis) xk = apply_rotary_emb(xk, freqs_cis)
xq, xk, xv = map(lambda x: x.transpose(1, 2), (xq, xk, xv))
if self.kv_cache is not None: keys, values = self.kv_cache.update(input_pos, xk, xv) # print('sdf', keys.shape, values.shape) else: keys, values = xk, xv keys = keys.repeat_interleave(self.n_head // self.n_kv_head, dim=1) values = values.repeat_interleave(self.n_head // self.n_kv_head, dim=1)
# print(xq.shape, keys.shape, values.shape, mask.shape, self.n_kv_head, self.n_head, seqlen)
output = F.scaled_dot_product_attention( xq, keys, values, attn_mask=mask, is_causal=True if mask is None else False, # is_causal=False is for KV cache dropout_p=self.attn_dropout_p if self.training else 0) output = output.transpose(1, 2).contiguous().view(bsz, seqlen, self.dim)
output = self.resid_dropout(self.wo(output)) return output
class TransformerBlock(nn.Module): def __init__(self, config: ModelArgs, drop_path: float): super().__init__() self.attention = Attention(config) self.feed_forward = FeedForward(config) self.attention_norm = RMSNorm(config.dim, eps=config.norm_eps) self.ffn_norm = RMSNorm(config.dim, eps=config.norm_eps) self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
def forward( self, x: torch.Tensor, freqs_cis: torch.Tensor, start_pos: int, mask: Optional[torch.Tensor] = None): h = x + self.drop_path(self.attention(self.attention_norm(x), freqs_cis, start_pos, mask)) out = h + self.drop_path(self.feed_forward(self.ffn_norm(h))) return out
class Transformer(nn.Module): def __init__(self, config: ModelArgs): super().__init__() self.config = config self.vocab_size = config.vocab_size self.n_layer = config.n_layer self.block_size = config.block_size self.num_classes = config.num_classes self.model_type = config.model_type self.cls_token_num = config.cls_token_num if self.model_type == 'c2i': self.cls_embedding = LabelEmbedder(config.num_classes, config.dim, config.class_dropout_prob) elif self.model_type == 't2i': self.cls_embedding = CaptionEmbedder(config.caption_dim, config.dim, config.class_dropout_prob) else: raise Exception("please check model type") self.tok_embeddings = nn.Embedding(config.vocab_size, config.dim) self.tok_dropout = nn.Dropout(config.token_dropout_p)
# transformer blocks dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.n_layer)] self.layers = torch.nn.ModuleList() for layer_id in range(config.n_layer): self.layers.append(TransformerBlock(config, dpr[layer_id]))
# output layer self.norm = RMSNorm(config.dim, eps=config.norm_eps) self.output = nn.Linear(config.dim, config.vocab_size, bias=False)
# 2d rotary pos embedding grid_size = int(self.block_size ** 0.5) assert grid_size * grid_size == self.block_size self.freqs_cis = precompute_freqs_cis_2d(grid_size, self.config.dim // self.config.n_head, self.config.rope_base, self.cls_token_num) # KVCache self.max_batch_size = -1 self.max_seq_length = -1
self.initialize_weights()
def initialize_weights(self): # Initialize nn.Linear and nn.Embedding self.apply(self._init_weights)
# Zero-out output layers: nn.init.constant_(self.output.weight, 0)
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)
def setup_caches(self, max_batch_size, max_seq_length, dtype): # if self.max_seq_length >= max_seq_length and self.max_batch_size >= max_batch_size: # return head_dim = self.config.dim // self.config.n_head max_seq_length = find_multiple(max_seq_length, 8) self.max_seq_length = max_seq_length self.max_batch_size = max_batch_size for b in self.layers: b.attention.kv_cache = KVCache(max_batch_size, max_seq_length, self.config.n_head, head_dim, dtype)
causal_mask = torch.tril(torch.ones(self.max_seq_length, self.max_seq_length, dtype=torch.bool)) self.causal_mask = causal_mask.unsqueeze(0).repeat(self.max_batch_size, 1, 1) grid_size = int(self.config.block_size ** 0.5) assert grid_size * grid_size == self.block_size self.freqs_cis = precompute_freqs_cis_2d(grid_size, self.config.dim // self.config.n_head, self.config.rope_base, self.cls_token_num)
def forward( self, idx: torch.Tensor, cond_idx: torch.Tensor, # cond_idx_or_embed input_pos: Optional[torch.Tensor] = None, targets: Optional[torch.Tensor] = None, mask: Optional[torch.Tensor] = None, valid: Optional[torch.Tensor] = None, ): if idx is not None and cond_idx is not None: # training or naive inference cond_embeddings = self.cls_embedding(cond_idx, train=self.training)[:,:self.cls_token_num] token_embeddings = self.tok_embeddings(idx) token_embeddings = torch.cat((cond_embeddings, token_embeddings), dim=1) h = self.tok_dropout(token_embeddings) self.freqs_cis = self.freqs_cis.to(h.device) else: if cond_idx is not None: # prefill in inference token_embeddings = self.cls_embedding(cond_idx, train=self.training)[:,:self.cls_token_num] else: # decode_n_tokens(kv cache) in inference token_embeddings = self.tok_embeddings(idx) bs = token_embeddings.shape[0] mask = self.causal_mask[:bs, None, input_pos] h = self.tok_dropout(token_embeddings) self.freqs_cis = self.freqs_cis if self.training: freqs_cis = self.freqs_cis[:token_embeddings.shape[1]] else: freqs_cis = self.freqs_cis[input_pos] # transformer blocks for layer in self.layers: h = layer(h, freqs_cis, input_pos, mask) # output layers h = self.norm(h) logits = self.output(h).float() if self.training: logits = logits[:, self.cls_token_num - 1:].contiguous()
# if we are given some desired targets also calculate the loss loss = None if valid is not None: loss_all = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), reduction='none') valid_all = valid[:,None].repeat(1, targets.shape[1]).view(-1) loss = (loss_all * valid_all).sum() / max(valid_all.sum(), 1) elif targets is not None: loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
return logits, loss
def get_fsdp_wrap_module_list(self) -> List[nn.Module]: return list(self.layers)
################################################################################## Rotary Positional Embedding Functions ################################################################################### https://github.com/pytorch-labs/gpt-fast/blob/main/model.py def precompute_freqs_cis(seq_len: int, n_elem: int, base: int = 10000, cls_token_num=120): freqs = 1.0 / (base ** (torch.arange(0, n_elem, 2)[: (n_elem // 2)].float() / n_elem)) t = torch.arange(seq_len, device=freqs.device) freqs = torch.outer(t, freqs) # (seq_len, head_dim // 2) freqs_cis = torch.polar(torch.ones_like(freqs), freqs) cache = torch.stack([freqs_cis.real, freqs_cis.imag], dim=-1) # (cls_token_num+seq_len, head_dim // 2, 2) cond_cache = torch.cat([torch.zeros(cls_token_num, n_elem // 2, 2), cache]) # (cls_token_num+seq_len, head_dim // 2, 2) return cond_cache
def precompute_freqs_cis_2d(grid_size: int, n_elem: int, base: int = 10000, cls_token_num=120): # split the dimension into half, one for x and one for y half_dim = n_elem // 2 freqs = 1.0 / (base ** (torch.arange(0, half_dim, 2)[: (half_dim // 2)].float() / half_dim)) t = torch.arange(grid_size, device=freqs.device) freqs = torch.outer(t, freqs) # (grid_size, head_dim // 2) freqs_grid = torch.concat([ freqs[:, None, :].expand(-1, grid_size, -1), freqs[None, :, :].expand(grid_size, -1, -1), ], dim=-1) # (grid_size, grid_size, head_dim // 2) cache_grid = torch.stack([torch.cos(freqs_grid), torch.sin(freqs_grid)], dim=-1) # (grid_size, grid_size, head_dim // 2, 2) cache = cache_grid.flatten(0, 1) cond_cache = torch.cat([torch.zeros(cls_token_num, n_elem // 2, 2), cache]) # (cls_token_num+grid_size**2, head_dim // 2, 2) return cond_cache
def apply_rotary_emb(x: torch.Tensor, freqs_cis: torch.Tensor): # x: (bs, seq_len, n_head, head_dim) # freqs_cis (seq_len, head_dim // 2, 2) xshaped = x.float().reshape(*x.shape[:-1], -1, 2) # (bs, seq_len, n_head, head_dim//2, 2) freqs_cis = freqs_cis.view(1, xshaped.size(1), 1, xshaped.size(3), 2) # (1, seq_len, 1, head_dim//2, 2) x_out2 = torch.stack([ xshaped[..., 0] * freqs_cis[..., 0] - xshaped[..., 1] * freqs_cis[..., 1], xshaped[..., 1] * freqs_cis[..., 0] + xshaped[..., 0] * freqs_cis[..., 1], ], dim=-1) x_out2 = x_out2.flatten(3) return x_out2.type_as(x)
################################################################################## GPT Configs ##################################################################################### text-conditionaldef GPT_7B(**kwargs): return Transformer(ModelArgs(n_layer=32, n_head=32, dim=4096, **kwargs)) # 6.6B
def GPT_3B(**kwargs): return Transformer(ModelArgs(n_layer=24, n_head=32, dim=3200, **kwargs)) # 3.1B
def GPT_1B(**kwargs): return Transformer(ModelArgs(n_layer=22, n_head=32, dim=2048, **kwargs)) # 1.2B
### class-conditionaldef GPT_XXXL(**kwargs): return Transformer(ModelArgs(n_layer=48, n_head=40, dim=2560, **kwargs)) # 3.9B
def GPT_XXL(**kwargs): return Transformer(ModelArgs(n_layer=48, n_head=24, dim=1536, **kwargs)) # 1.4B
def GPT_XL(**kwargs): return Transformer(ModelArgs(n_layer=36, n_head=20, dim=1280, **kwargs)) # 775M
def GPT_L(**kwargs): return Transformer(ModelArgs(n_layer=24, n_head=16, dim=1024, **kwargs)) # 343M
def GPT_B(**kwargs): return Transformer(ModelArgs(n_layer=12, n_head=12, dim=768, **kwargs)) # 111M
GPT_models = { 'GPT-B': GPT_B, 'GPT-L': GPT_L, 'GPT-XL': GPT_XL, 'GPT-XXL': GPT_XXL, 'GPT-XXXL': GPT_XXXL, 'GPT-1B': GPT_1B, 'GPT-3B': GPT_3B, 'GPT-7B': GPT_7B, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476import torchfrom torch import nnfrom torch.nn import functional as Fimport numpy as npimport os
import torch._dynamo.configimport torch._inductor.configimport copy
from typing import Optional, Tuple
import transformersfrom transformers.generation.utils import GenerationMixin
from transformers.generation.logits_process import LogitsProcessor, LogitsProcessorList, LogitsWarperfrom transformers.generation.logits_process import TopKLogitsWarperfrom transformers import GenerationConfig
from transformers.utils import ModelOutputfrom dataclasses import dataclass
from transformers import StoppingCriteria, StoppingCriteriaList
from transformers.cache_utils import Cache, DynamicCache
from scheduler.logit_processor_3dim import TopPLogitsWarper3d
@dataclassclass BackboneOutput(ModelOutput): logits: torch.Tensor = None past_key_values: Cache = None
def top_k_top_p_filtering( logits, top_k: int = 0, top_p: float = 1.0, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1,): """Filter a distribution of logits using top-k and/or nucleus (top-p) filtering Args: logits: logits distribution shape (batch size, vocabulary size) if top_k > 0: keep only top k tokens with highest probability (top-k filtering). if top_p < 1.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering). Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751) Make sure we keep at least min_tokens_to_keep per batch example in the output From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317 """ if top_k > 0: top_k = min(max(top_k, min_tokens_to_keep), logits.size(-1)) # Safety check # Remove all tokens with a probability less than the last token of the top-k indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None] logits[indices_to_remove] = filter_value
if top_p < 1.0: sorted_logits, sorted_indices = torch.sort(logits, descending=True) cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
# Remove tokens with cumulative probability above the threshold (token with 0 are kept) sorted_indices_to_remove = cumulative_probs > top_p if min_tokens_to_keep > 1: # Keep at least min_tokens_to_keep (set to min_tokens_to_keep-1 because we add the first one below) sorted_indices_to_remove[..., :min_tokens_to_keep] = 0 # Shift the indices to the right to keep also the first token above the threshold sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone() sorted_indices_to_remove[..., 0] = 0
# scatter sorted tensors to original indexing indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove) logits[indices_to_remove] = filter_value return logits
def sample(logits, temperature: float=1.0, top_k: int=0, top_p: float=1.0, sample_logits=True): logits = logits[:, -1, :] / max(temperature, 1e-5) if top_k > 0 or top_p < 1.0: logits = top_k_top_p_filtering(logits, top_k=top_k, top_p=top_p) probs = F.softmax(logits, dim=-1) if sample_logits: idx = torch.multinomial(probs, num_samples=1) else: _, idx = torch.topk(probs, k=1, dim=-1) return idx, probs
def logits_to_probs(logits, temperature: float = 1.0, top_p: float=1.0, top_k: int = None, **kwargs): logits = logits / max(temperature, 1e-5) if top_k > 0 or top_p < 1.0: logits = top_k_top_p_filtering(logits, top_k=top_k, top_p=top_p) probs = torch.nn.functional.softmax(logits, dim=-1) return probs
def prefill(model, cond_idx: torch.Tensor, input_pos: torch.Tensor, cfg_scale: float, **sampling_kwargs): if cfg_scale > 1.0: logits = model.inference(None, cond_idx, input_pos) logits_combined = logits cond_logits, uncond_logits = torch.split(logits_combined, len(logits_combined) // 2, dim=0) logits = uncond_logits + (cond_logits - uncond_logits) * cfg_scale else: logits = model.inference(None, cond_idx, input_pos)
return sample(logits, **sampling_kwargs)[0]
def decode_one_token(model, x: torch.Tensor, input_pos: torch.Tensor, cfg_scale: float, cfg_flag: bool, **sampling_kwargs): assert input_pos.shape[-1] == 1 if cfg_scale > 1.0: x_combined = torch.cat([x, x]) logits = model.inference(x_combined, cond_idx=None, input_pos=input_pos) logits_combined = logits cond_logits, uncond_logits = torch.split(logits_combined, len(logits_combined) // 2, dim=0) if cfg_flag: logits = uncond_logits + (cond_logits - uncond_logits) * cfg_scale else: logits = cond_logits else: logits = model.inference(x, cond_idx=None, input_pos=input_pos) return sample(logits, **sampling_kwargs)
def decode_n_tokens( model, cur_token: torch.Tensor, input_pos: torch.Tensor, num_new_tokens: int, cfg_scale: float, cfg_interval: int, **sampling_kwargs,): new_tokens, new_probs = [], [] cfg_flag = True for i in range(num_new_tokens): with torch.backends.cuda.sdp_kernel(enable_flash=False, enable_mem_efficient=False, enable_math=True): # Actually better for Inductor to codegen attention here if cfg_interval > -1 and i > cfg_interval: cfg_flag = False next_token, next_prob = decode_one_token( model, cur_token, input_pos, cfg_scale, cfg_flag, **sampling_kwargs ) input_pos += 1 new_tokens.append(next_token.clone()) new_probs.append(next_prob.clone()) cur_token = next_token.view(-1, 1) return new_tokens, new_probs
@torch.no_grad()def generate(model, cond, max_new_tokens, emb_masks=None, cfg_scale=1.0, cfg_interval=-1, **sampling_kwargs): if model.model_type == 'c2i': if cfg_scale > 1.0: cond_null = torch.ones_like(cond) * model.num_classes cond_combined = torch.cat([cond, cond_null]) else: cond_combined = cond T = 1 elif model.model_type == 't2i': if cfg_scale > 1.0: cond_null = torch.zeros_like(cond) + model.cls_embedding.uncond_embedding cond_combined = torch.cat([cond, cond_null]) else: cond_combined = cond T = cond.shape[1] else: raise Exception("please check model type")
T_new = T + max_new_tokens max_seq_length = T_new max_batch_size = cond.shape[0]
device = cond.device with torch.device(device): max_batch_size_cfg = max_batch_size * 2 if cfg_scale > 1.0 else max_batch_size model.setup_caches(max_batch_size=max_batch_size_cfg, max_seq_length=max_seq_length, dtype=model.tok_embeddings.weight.dtype) if emb_masks is not None: assert emb_masks.shape[0] == max_batch_size assert emb_masks.shape[-1] == T if cfg_scale > 1.0: model.causal_mask[:, :, :T] = model.causal_mask[:, :, :T] * torch.cat([emb_masks, emb_masks]).unsqueeze(1) else: model.causal_mask[:, :, :T] = model.causal_mask[:, :, :T] * emb_masks.unsqueeze(1)
eye_matrix = torch.eye(model.causal_mask.size(1), model.causal_mask.size(2), device=device) model.causal_mask[:] = model.causal_mask * (1 - eye_matrix) + eye_matrix # create an empty tensor of the expected final shape and fill in the current tokens seq = torch.empty((max_batch_size, T_new), dtype=torch.int, device=device)
input_pos = torch.arange(0, T, device=device) next_token = prefill(model, cond_combined, input_pos, cfg_scale, **sampling_kwargs) seq[:, T:T+1] = next_token
input_pos = torch.tensor([T], device=device, dtype=torch.int) generated_tokens, _ = decode_n_tokens(model, next_token, input_pos, max_new_tokens-1, cfg_scale, cfg_interval, **sampling_kwargs) seq[:, T+1:] = torch.cat(generated_tokens, dim=1)
return seq[:, T:]
def renew_llamagen( model_class,): class WrappedLLamaGen(model_class, GenerationMixin): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _init_new_params(self, *args, **kwargs): self.config.is_encoder_decoder = False def clear_kvcache(self): for layer_idx, b in enumerate(self.layers): b.attention.kv_cache.k_cache[..., :, :] = 0 b.attention.kv_cache.v_cache[..., :, :] = 0 def assign_kvcache(self, past_key_values): for layer_idx, b in enumerate(self.layers): used_len = past_key_values.key_cache[layer_idx].shape[-2] b.attention.kv_cache.k_cache[..., :used_len, :] = past_key_values.key_cache[layer_idx] b.attention.kv_cache.v_cache[..., :used_len, :] = past_key_values.value_cache[layer_idx] def get_max_kvcache_len(self): max_kvcache_len = 0 for b in self.layers: max_kvcache_len = max(max_kvcache_len, b.attention.kv_cache.k_cache.shape[-2]) return max_kvcache_len def assign_past_key_values(self, past_key_values, used_len): for layer_idx, b in enumerate(self.layers): if layer_idx < len(past_key_values.key_cache): past_key_values.key_cache[layer_idx] = b.attention.kv_cache.k_cache[..., :used_len, :] past_key_values.value_cache[layer_idx] = b.attention.kv_cache.v_cache[..., :used_len, :] else: past_key_values.key_cache.append(b.attention.kv_cache.k_cache[..., :used_len, :]) past_key_values.value_cache.append(b.attention.kv_cache.v_cache[..., :used_len, :])
return past_key_values
def forward( self, input_ids, position_ids, cache_position, past_key_values, use_cache, attention_mask, **kwargs, ): dtype = self.tok_embeddings.weight.dtype
input_pos = position_ids[0][-input_ids.shape[1]:] while attention_mask.dim() < 4: attention_mask = attention_mask.unsqueeze(1) max_kvcache_len = self.get_max_kvcache_len() if attention_mask.shape[-1] < max_kvcache_len: attention_mask = torch.cat([ attention_mask, torch.zeros( *attention_mask.shape[:-1], max_kvcache_len - attention_mask.shape[-1], dtype=attention_mask.dtype, device=attention_mask.device ) ], dim=-1) causal_mask = self.causal_mask while causal_mask.dim() < 4: causal_mask = causal_mask.unsqueeze(1) causal_mask = causal_mask[:, :, input_pos, :].to(attention_mask.dtype) attention_mask = torch.minimum(attention_mask, causal_mask) min_dtype = torch.finfo(dtype).min attention_mask = ((attention_mask == 0).to(dtype) * min_dtype).to(dtype) mask = attention_mask
is_kvcache_not_empty = (past_key_values.get_seq_length() > 0)
# idx = input_ids if is_kvcache_not_empty else None # cond_idx = None if is_kvcache_not_empty else input_ids idx = input_ids
if is_kvcache_not_empty: self.assign_kvcache(past_key_values) logits = self.inference( idx = idx, cond_idx = None, input_pos=input_pos, mask=None, #mask, ) used_len = position_ids[0][-1:] + 1 past_key_values = self.assign_past_key_values(past_key_values, used_len) outputs = BackboneOutput( logits = logits, past_key_values = past_key_values, ) return outputs def inference( self, idx: torch.Tensor, cond_idx: torch.Tensor, # cond_idx_or_embed input_pos: Optional[torch.Tensor] = None, mask: Optional[torch.Tensor] = None, ): if idx is not None and cond_idx is not None: # training or naive inference cond_embeddings = self.cls_embedding(cond_idx, train=self.training)[:,:self.cls_token_num] token_embeddings = self.tok_embeddings(idx) token_embeddings = torch.cat((cond_embeddings, token_embeddings), dim=1) h = self.tok_dropout(token_embeddings) self.freqs_cis = self.freqs_cis.to(h.device) else: if cond_idx is not None: # pre fill in inference token_embeddings = self.cls_embedding(cond_idx, train=self.training)[:,:self.cls_token_num] else: # decode_n_tokens(kv cache) in inference token_embeddings = self.tok_embeddings(idx) bs = token_embeddings.shape[0] if mask is None: mask = self.causal_mask[:bs, None, input_pos, :] h = self.tok_dropout(token_embeddings) self.freqs_cis = self.freqs_cis if self.training: freqs_cis = self.freqs_cis[:token_embeddings.shape[1]] else: freqs_cis = self.freqs_cis[input_pos] # transformer blocks for layer in self.layers: h = layer(h, freqs_cis, input_pos, mask) # output layers h = self.norm(h) logits = self.output(h).float() if self.training: logits = logits[:, self.cls_token_num - 1:].contiguous()
return logits return WrappedLLamaGen
class MaxlenCriteria(StoppingCriteria): def __init__(self, max_seq_length): super().__init__() self.max_seq_length = max_seq_length def __call__(self, input_ids, scores, **kwargs): return input_ids.shape[-1] >= self.max_seq_length
class LlamaGenSolver: def __init__(self, model, image_top_k, image_top_p): self.model = model self.image_top_k = image_top_k self.image_top_p = image_top_p def _sample(self, *args, **kwargs): raise NotImplementedError def _init_model_kwargs(self, prefill_num, mask=None, device='cuda', *args, **kwargs): # print('mas22k', mask[0, :50, :50], mask.shape) model_kwargs = dict( use_cache = True, attention_mask = mask[0, -1:, :prefill_num] if mask is not None else torch.ones( (1, prefill_num), device=device ), past_key_values = transformers.DynamicCache(), cache_position=prefill_num, ) return model_kwargs @torch.no_grad() def generate(self, cond, max_new_tokens, emb_masks=None, cfg_scale=1.0, cfg_interval=-1, return_accl=False,**sampling_kwargs): model = self.model if model.model_type == 'c2i': if cfg_scale > 1.0: cond_null = torch.ones_like(cond) * model.num_classes cond_combined = torch.cat([cond, cond_null]) else: cond_combined = cond T = 1 elif model.model_type == 't2i': if cfg_scale > 1.0: cond_null = torch.zeros_like(cond) + model.cls_embedding.uncond_embedding cond_combined = torch.cat([cond, cond_null]) else: cond_combined = cond T = cond.shape[1] else: raise Exception("please check model type")
T_new = T + max_new_tokens max_seq_length = T_new max_batch_size = cond.shape[0]
device = cond.device with torch.device(device): max_batch_size_cfg = max_batch_size * 2 if cfg_scale > 1.0 else max_batch_size model.setup_caches( max_batch_size=max_batch_size_cfg, max_seq_length=max_seq_length , dtype=model.tok_embeddings.weight.dtype ) if emb_masks is not None: assert emb_masks.shape[0] == max_batch_size assert emb_masks.shape[-1] == T if cfg_scale > 1.0: model.causal_mask[:, :, :T] = model.causal_mask[:, :, :T] * torch.cat([emb_masks, emb_masks]).unsqueeze(1) else: model.causal_mask[:, :, :T] = model.causal_mask[:, :, :T] * emb_masks.unsqueeze(1)
eye_matrix = torch.eye(model.causal_mask.size(1), model.causal_mask.size(2), device=device) model.causal_mask[:] = model.causal_mask * (1 - eye_matrix) + eye_matrix
mask = model.causal_mask
input_pos = torch.arange(0, T, device=device) next_token = prefill(model, cond_combined, input_pos, cfg_scale, **sampling_kwargs)
input_ids = next_token
max_gen_len = max_seq_length # max_new_tokens temperature = 1.0 synced_gpus = False stopping_criteria = StoppingCriteriaList([ MaxlenCriteria(max_new_tokens) # As llamagen has T5 ]) generation_config = GenerationConfig( max_new_tokens=max_gen_len, max_length=max_gen_len, temperature=temperature, top_k=None, do_sample=True, # eos_token_id= [8710], _pad_token_tensor=None, return_dict_in_generate = False, return_accl = return_accl ) model_kwargs = self._init_model_kwargs( prefill_num = T+1, # existing `next_token`, an already decoded image token mask = None, # this mask only used for generating the positional indexes device = device, ) logits_processor = self.create_logits_processor()
result = model._sample( input_ids=input_ids, logits_processor=logits_processor, stopping_criteria = stopping_criteria, generation_config=generation_config, synced_gpus=synced_gpus, streamer=None, logits_warper=None, **model_kwargs, ) outputs = result.input_ids generated_tokens = outputs if isinstance(outputs, torch.Tensor) else outputs.sequences generated_tokens = generated_tokens[:, -max_new_tokens:] model.clear_kvcache() if return_accl: result.input_ids = generated_tokens return result else: return generated_tokens def create_logits_processor(self, ): image_top_k = self.image_top_k image_top_p = self.image_top_p
logits_processor = LogitsProcessorList()
topk_logits_warper = TopKLogitsWarper(top_k=image_top_k) topp_logits_warper = TopPLogitsWarper3d(top_p=image_top_p)
logits_processor.append(topk_logits_warper) logits_processor.append(topp_logits_warper)
return logits_processor1234567891011121314## Consistency Decoder from OpenAI
### install```pip install diffuserspip install accelerate```
### demo```cd ${THIS_REPO_ROOT}python3 tokenizer/consistencydecoder/cd_demo.py```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import argparseimport torchimport torch.nn.functional as Fimport numpy as npfrom PIL import Imagefrom diffusers import ConsistencyDecoderVAE
def main(args): # Setup PyTorch: torch.manual_seed(args.seed) torch.set_grad_enabled(False) device = "cuda" if torch.cuda.is_available() else "cpu"
# create and load model vae = ConsistencyDecoderVAE.from_pretrained("openai/consistency-decoder", torch_dtype=torch.float16).to(device)
# load image img_path = args.image_path out_path = args.image_path.replace('.jpg', '_cd.jpg').replace('.jpeg', '_cd.jpeg').replace('.png', '_cd.png') input_size = args.image_size img = Image.open(img_path).convert("RGB")
# preprocess size_org = img.size img = img.resize((input_size, input_size)) img = np.array(img) / 255. x = 2.0 * img - 1.0 # x value is between [-1, 1] x = torch.tensor(x) x = x.unsqueeze(dim=0) x = torch.einsum('nhwc->nchw', x) x_input = x.half().to(device)
# inference with torch.no_grad(): # Map input images to latent space + normalize latents: latent = vae.encode(x_input).latent_dist.sample().mul_(0.18215) # reconstruct: output = vae.decode(latent / 0.18215).sample # output value is between [-1, 1]
# postprocess output = F.interpolate(output, size=[size_org[1], size_org[0]], mode='bilinear').permute(0, 2, 3, 1)[0] sample = torch.clamp(127.5 * output + 128.0, 0, 255).to("cpu", dtype=torch.uint8).numpy()
# save Image.fromarray(sample).save(out_path) print("Reconstructed image is saved to {}".format(out_path))
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--image-path", type=str, default="assets/example.jpg") parser.add_argument("--image-size", type=int, choices=[256, 512, 1024], default=512) parser.add_argument("--seed", type=int, default=0) args = parser.parse_args() main(args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208import torchtorch.backends.cuda.matmul.allow_tf32 = Truetorch.backends.cudnn.allow_tf32 = Trueimport torch.distributed as distfrom torch.utils.data import Dataset, DataLoaderfrom torch.utils.data.distributed import DistributedSamplerfrom torchvision.datasets import ImageFolderfrom torchvision import transformsfrom tqdm import tqdmimport osimport itertoolsfrom PIL import Imageimport numpy as npimport argparseimport random
from skimage.metrics import peak_signal_noise_ratio as psnr_lossfrom skimage.metrics import structural_similarity as ssim_lossfrom diffusers.models import ConsistencyDecoderVAE
class SingleFolderDataset(Dataset): def __init__(self, directory, transform=None): super().__init__() self.directory = directory self.transform = transform self.image_paths = [os.path.join(directory, file_name) for file_name in os.listdir(directory) if os.path.isfile(os.path.join(directory, file_name))]
def __len__(self): return len(self.image_paths)
def __getitem__(self, idx): image_path = self.image_paths[idx] image = Image.open(image_path).convert('RGB') if self.transform: image = self.transform(image) return image, torch.tensor(0)
def create_npz_from_sample_folder(sample_dir, num=50_000): """ Builds a single .npz file from a folder of .png samples. """ samples = [] for i in tqdm(range(num), desc="Building .npz file from samples"): sample_pil = Image.open(f"{sample_dir}/{i:06d}.png") sample_np = np.asarray(sample_pil).astype(np.uint8) samples.append(sample_np)
random.shuffle(samples) # This is very important for IS(Inception Score) !!! samples = np.stack(samples) assert samples.shape == (num, samples.shape[1], samples.shape[2], 3) npz_path = f"{sample_dir}.npz" np.savez(npz_path, arr_0=samples) print(f"Saved .npz file to {npz_path} [shape={samples.shape}].") return npz_path
def center_crop_arr(pil_image, image_size): """ Center cropping implementation from ADM. https://github.com/openai/guided-diffusion/blob/8fb3ad9197f16bbc40620447b2742e13458d2831/guided_diffusion/image_datasets.py#L126 """ while min(*pil_image.size) >= 2 * image_size: pil_image = pil_image.resize( tuple(x // 2 for x in pil_image.size), resample=Image.BOX )
scale = image_size / min(*pil_image.size) pil_image = pil_image.resize( tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC )
arr = np.array(pil_image) crop_y = (arr.shape[0] - image_size) // 2 crop_x = (arr.shape[1] - image_size) // 2 return Image.fromarray(arr[crop_y: crop_y + image_size, crop_x: crop_x + image_size])
def main(args): # Setup PyTorch: assert torch.cuda.is_available(), "Sampling with DDP requires at least one GPU. sample.py supports CPU-only usage" torch.set_grad_enabled(False)
# Setup env dist.init_process_group("nccl") rank = dist.get_rank() device = rank % torch.cuda.device_count() seed = args.global_seed * dist.get_world_size() + rank torch.manual_seed(seed) torch.cuda.set_device(device) print(f"Starting rank={rank}, seed={seed}, world_size={dist.get_world_size()}.")
# create and load model vae = ConsistencyDecoderVAE.from_pretrained("openai/consistency-decoder", torch_dtype=torch.float16).to("cuda:{}".format(device))
# Create folder to save samples: folder_name = f"openai-consistencydecoder-{args.dataset}-size-{args.image_size}-seed-{args.global_seed}" sample_folder_dir = f"{args.sample_dir}/{folder_name}" if rank == 0: os.makedirs(sample_folder_dir, exist_ok=True) print(f"Saving .png samples at {sample_folder_dir}") dist.barrier()
# Setup data: transform = transforms.Compose([ transforms.Lambda(lambda pil_image: center_crop_arr(pil_image, args.image_size)), transforms.ToTensor(), transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True) ]) if args.dataset == 'imagenet': dataset = ImageFolder(args.data_path, transform=transform) num_fid_samples = 50000 elif args.dataset == 'coco': dataset = SingleFolderDataset(args.data_path, transform=transform) num_fid_samples = 5000 else: raise Exception("please check dataset") sampler = DistributedSampler( dataset, num_replicas=dist.get_world_size(), rank=rank, shuffle=False, seed=args.global_seed ) loader = DataLoader( dataset, batch_size=args.per_proc_batch_size, shuffle=False, sampler=sampler, num_workers=args.num_workers, pin_memory=True, drop_last=False )
# Figure out how many samples we need to generate on each GPU and how many iterations we need to run: n = args.per_proc_batch_size global_batch_size = n * dist.get_world_size() psnr_val_rgb = [] ssim_val_rgb = []
loader = tqdm(loader) if rank == 0 else loader total = 0 for x, _ in loader: rgb_gts = x rgb_gts = (rgb_gts.permute(0, 2, 3, 1).to("cpu").numpy() + 1.0) / 2.0 # rgb_gt value is between [0, 1] x = x.half().to("cuda:{}".format(device)) with torch.no_grad(): # Map input images to latent space + normalize latents: latent = vae.encode(x).latent_dist.sample().mul_(0.18215) # reconstruct: samples = vae.decode(latent / 0.18215).sample # output value is between [-1, 1] samples = torch.clamp(127.5 * samples + 128.0, 0, 255).permute(0, 2, 3, 1).to("cpu", dtype=torch.uint8).numpy() # Save samples to disk as individual .png files for i, (sample, rgb_gt) in enumerate(zip(samples, rgb_gts)): index = i * dist.get_world_size() + rank + total Image.fromarray(sample).save(f"{sample_folder_dir}/{index:06d}.png") # metric rgb_restored = sample.astype(np.float32) / 255. # rgb_restored value is between [0, 1] psnr = psnr_loss(rgb_restored, rgb_gt) ssim = ssim_loss(rgb_restored, rgb_gt, multichannel=True, data_range=2.0, channel_axis=-1) psnr_val_rgb.append(psnr) ssim_val_rgb.append(ssim) total += global_batch_size
# ------------------------------------ # Summary # ------------------------------------ # Make sure all processes have finished saving their samples dist.barrier() world_size = dist.get_world_size() gather_psnr_val = [None for _ in range(world_size)] gather_ssim_val = [None for _ in range(world_size)] dist.all_gather_object(gather_psnr_val, psnr_val_rgb) dist.all_gather_object(gather_ssim_val, ssim_val_rgb)
if rank == 0: gather_psnr_val = list(itertools.chain(*gather_psnr_val)) gather_ssim_val = list(itertools.chain(*gather_ssim_val)) psnr_val_rgb = sum(gather_psnr_val) / len(gather_psnr_val) ssim_val_rgb = sum(gather_ssim_val) / len(gather_ssim_val) print("PSNR: %f, SSIM: %f " % (psnr_val_rgb, ssim_val_rgb))
result_file = f"{sample_folder_dir}_results.txt" print("writing results to {}".format(result_file)) with open(result_file, 'w') as f: print("PSNR: %f, SSIM: %f " % (psnr_val_rgb, ssim_val_rgb), file=f)
create_npz_from_sample_folder(sample_folder_dir, num_fid_samples) print("Done.") dist.barrier() dist.destroy_process_group()
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--data-path", type=str, required=True) parser.add_argument("--dataset", type=str, choices=['imagenet', 'coco'], default='imagenet') parser.add_argument("--image-size", type=int, choices=[256, 512], default=256) parser.add_argument("--sample-dir", type=str, default="reconstructions") parser.add_argument("--per-proc-batch-size", type=int, default=32) parser.add_argument("--global-seed", type=int, default=0) parser.add_argument("--num-workers", type=int, default=4) args = parser.parse_args() main(args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255# Modified from:# taming-transformers: https://github.com/CompVis/taming-transformers# stylegan2-pytorch: https://github.com/rosinality/stylegan2-pytorch/blob/master/model.py# maskgit: https://github.com/google-research/maskgit/blob/main/maskgit/nets/discriminator.pyimport functoolsimport mathimport torchimport torch.nn as nntry: from kornia.filters import filter2dexcept: pass
################################################################################## PatchGAN ##################################################################################class PatchGANDiscriminator(nn.Module): """Defines a PatchGAN discriminator as in Pix2Pix --> see https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/networks.py """ def __init__(self, input_nc=3, ndf=64, n_layers=3, use_actnorm=False): """Construct a PatchGAN discriminator Parameters: input_nc (int) -- the number of channels in input images ndf (int) -- the number of filters in the last conv layer n_layers (int) -- the number of conv layers in the discriminator norm_layer -- normalization layer """ super(PatchGANDiscriminator, self).__init__() if not use_actnorm: norm_layer = nn.BatchNorm2d else: norm_layer = ActNorm if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters use_bias = norm_layer.func != nn.BatchNorm2d else: use_bias = norm_layer != nn.BatchNorm2d
kw = 4 padw = 1 sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)] nf_mult = 1 nf_mult_prev = 1 for n in range(1, n_layers): # gradually increase the number of filters nf_mult_prev = nf_mult nf_mult = min(2 ** n, 8) sequence += [ nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias), norm_layer(ndf * nf_mult), nn.LeakyReLU(0.2, True) ]
nf_mult_prev = nf_mult nf_mult = min(2 ** n_layers, 8) sequence += [ nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias), norm_layer(ndf * nf_mult), nn.LeakyReLU(0.2, True) ]
sequence += [ nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # output 1 channel prediction map self.main = nn.Sequential(*sequence)
self.apply(self._init_weights) def _init_weights(self, module): if isinstance(module, nn.Conv2d): nn.init.normal_(module.weight.data, 0.0, 0.02) elif isinstance(module, nn.BatchNorm2d): nn.init.normal_(module.weight.data, 1.0, 0.02) nn.init.constant_(module.bias.data, 0)
def forward(self, input): """Standard forward.""" return self.main(input)
class ActNorm(nn.Module): def __init__(self, num_features, logdet=False, affine=True, allow_reverse_init=False): assert affine super().__init__() self.logdet = logdet self.loc = nn.Parameter(torch.zeros(1, num_features, 1, 1)) self.scale = nn.Parameter(torch.ones(1, num_features, 1, 1)) self.allow_reverse_init = allow_reverse_init
self.register_buffer('initialized', torch.tensor(0, dtype=torch.uint8))
def initialize(self, input): with torch.no_grad(): flatten = input.permute(1, 0, 2, 3).contiguous().view(input.shape[1], -1) mean = ( flatten.mean(1) .unsqueeze(1) .unsqueeze(2) .unsqueeze(3) .permute(1, 0, 2, 3) ) std = ( flatten.std(1) .unsqueeze(1) .unsqueeze(2) .unsqueeze(3) .permute(1, 0, 2, 3) )
self.loc.data.copy_(-mean) self.scale.data.copy_(1 / (std + 1e-6))
def forward(self, input, reverse=False): if reverse: return self.reverse(input) if len(input.shape) == 2: input = input[:,:,None,None] squeeze = True else: squeeze = False
_, _, height, width = input.shape
if self.training and self.initialized.item() == 0: self.initialize(input) self.initialized.fill_(1)
h = self.scale * (input + self.loc)
if squeeze: h = h.squeeze(-1).squeeze(-1)
if self.logdet: log_abs = torch.log(torch.abs(self.scale)) logdet = height*width*torch.sum(log_abs) logdet = logdet * torch.ones(input.shape[0]).to(input) return h, logdet
return h
def reverse(self, output): if self.training and self.initialized.item() == 0: if not self.allow_reverse_init: raise RuntimeError( "Initializing ActNorm in reverse direction is " "disabled by default. Use allow_reverse_init=True to enable." ) else: self.initialize(output) self.initialized.fill_(1)
if len(output.shape) == 2: output = output[:,:,None,None] squeeze = True else: squeeze = False
h = output / self.scale - self.loc
if squeeze: h = h.squeeze(-1).squeeze(-1) return h
################################################################################## StyleGAN ##################################################################################class StyleGANDiscriminator(nn.Module): def __init__(self, input_nc=3, ndf=64, n_layers=3, channel_multiplier=1, image_size=256): super().__init__() channels = { 4: 512, 8: 512, 16: 512, 32: 512, 64: 256 * channel_multiplier, 128: 128 * channel_multiplier, 256: 64 * channel_multiplier, 512: 32 * channel_multiplier, 1024: 16 * channel_multiplier, } log_size = int(math.log(image_size, 2)) in_channel = channels[image_size]
blocks = [nn.Conv2d(input_nc, in_channel, 3, padding=1), leaky_relu()] for i in range(log_size, 2, -1): out_channel = channels[2 ** (i - 1)] blocks.append(DiscriminatorBlock(in_channel, out_channel)) in_channel = out_channel self.blocks = nn.ModuleList(blocks)
self.final_conv = nn.Sequential( nn.Conv2d(in_channel, channels[4], 3, padding=1), leaky_relu(), ) self.final_linear = nn.Sequential( nn.Linear(channels[4] * 4 * 4, channels[4]), leaky_relu(), nn.Linear(channels[4], 1) ) def forward(self, x): for block in self.blocks: x = block(x) x = self.final_conv(x) x = x.view(x.shape[0], -1) x = self.final_linear(x) return x
class DiscriminatorBlock(nn.Module): def __init__(self, input_channels, filters, downsample=True): super().__init__() self.conv_res = nn.Conv2d(input_channels, filters, 1, stride = (2 if downsample else 1))
self.net = nn.Sequential( nn.Conv2d(input_channels, filters, 3, padding=1), leaky_relu(), nn.Conv2d(filters, filters, 3, padding=1), leaky_relu() )
self.downsample = nn.Sequential( Blur(), nn.Conv2d(filters, filters, 3, padding = 1, stride = 2) ) if downsample else None
def forward(self, x): res = self.conv_res(x) x = self.net(x) if exists(self.downsample): x = self.downsample(x) x = (x + res) * (1 / math.sqrt(2)) return x
class Blur(nn.Module): def __init__(self): super().__init__() f = torch.Tensor([1, 2, 1]) self.register_buffer('f', f) def forward(self, x): f = self.f f = f[None, None, :] * f [None, :, None] return filter2d(x, f, normalized=True)
def leaky_relu(p=0.2): return nn.LeakyReLU(p, inplace=True)
def exists(val): return val is not None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152# Modified from:# taming-transformers: https://github.com/CompVis/taming-transformersimport functoolsimport torchimport torch.nn as nn
class NLayerDiscriminator(nn.Module): """Defines a PatchGAN discriminator as in Pix2Pix --> see https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/networks.py """ def __init__(self, input_nc=3, ndf=64, n_layers=3, use_actnorm=False): """Construct a PatchGAN discriminator Parameters: input_nc (int) -- the number of channels in input images ndf (int) -- the number of filters in the last conv layer n_layers (int) -- the number of conv layers in the discriminator norm_layer -- normalization layer """ super(NLayerDiscriminator, self).__init__() if not use_actnorm: norm_layer = nn.BatchNorm2d else: norm_layer = ActNorm if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters use_bias = norm_layer.func != nn.BatchNorm2d else: use_bias = norm_layer != nn.BatchNorm2d
kw = 4 padw = 1 sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)] nf_mult = 1 nf_mult_prev = 1 for n in range(1, n_layers): # gradually increase the number of filters nf_mult_prev = nf_mult nf_mult = min(2 ** n, 8) sequence += [ nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias), norm_layer(ndf * nf_mult), nn.LeakyReLU(0.2, True) ]
nf_mult_prev = nf_mult nf_mult = min(2 ** n_layers, 8) sequence += [ nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias), norm_layer(ndf * nf_mult), nn.LeakyReLU(0.2, True) ]
sequence += [ nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # output 1 channel prediction map self.main = nn.Sequential(*sequence)
self.apply(self._init_weights) def _init_weights(self, module): if isinstance(module, nn.Conv2d): nn.init.normal_(module.weight.data, 0.0, 0.02) elif isinstance(module, nn.BatchNorm2d): nn.init.normal_(module.weight.data, 1.0, 0.02) nn.init.constant_(module.bias.data, 0)
def forward(self, input): """Standard forward.""" return self.main(input)
class ActNorm(nn.Module): def __init__(self, num_features, logdet=False, affine=True, allow_reverse_init=False): assert affine super().__init__() self.logdet = logdet self.loc = nn.Parameter(torch.zeros(1, num_features, 1, 1)) self.scale = nn.Parameter(torch.ones(1, num_features, 1, 1)) self.allow_reverse_init = allow_reverse_init
self.register_buffer('initialized', torch.tensor(0, dtype=torch.uint8))
def initialize(self, input): with torch.no_grad(): flatten = input.permute(1, 0, 2, 3).contiguous().view(input.shape[1], -1) mean = ( flatten.mean(1) .unsqueeze(1) .unsqueeze(2) .unsqueeze(3) .permute(1, 0, 2, 3) ) std = ( flatten.std(1) .unsqueeze(1) .unsqueeze(2) .unsqueeze(3) .permute(1, 0, 2, 3) )
self.loc.data.copy_(-mean) self.scale.data.copy_(1 / (std + 1e-6))
def forward(self, input, reverse=False): if reverse: return self.reverse(input) if len(input.shape) == 2: input = input[:,:,None,None] squeeze = True else: squeeze = False
_, _, height, width = input.shape
if self.training and self.initialized.item() == 0: self.initialize(input) self.initialized.fill_(1)
h = self.scale * (input + self.loc)
if squeeze: h = h.squeeze(-1).squeeze(-1)
if self.logdet: log_abs = torch.log(torch.abs(self.scale)) logdet = height*width*torch.sum(log_abs) logdet = logdet * torch.ones(input.shape[0]).to(input) return h, logdet
return h
def reverse(self, output): if self.training and self.initialized.item() == 0: if not self.allow_reverse_init: raise RuntimeError( "Initializing ActNorm in reverse direction is " "disabled by default. Use allow_reverse_init=True to enable." ) else: self.initialize(output) self.initialized.fill_(1)
if len(output.shape) == 2: output = output[:,:,None,None] squeeze = True else: squeeze = False
h = output / self.scale - self.loc
if squeeze: h = h.squeeze(-1).squeeze(-1) return h123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101# Modified from:# stylegan2-pytorch: https://github.com/lucidrains/stylegan2-pytorch/blob/master/stylegan2_pytorch/stylegan2_pytorch.py# stylegan2-pytorch: https://github.com/rosinality/stylegan2-pytorch/blob/master/model.py# maskgit: https://github.com/google-research/maskgit/blob/main/maskgit/nets/discriminator.pyimport mathimport torchimport torch.nn as nntry: from kornia.filters import filter2dexcept: pass
class Discriminator(nn.Module): def __init__(self, input_nc=3, ndf=64, n_layers=3, channel_multiplier=1, image_size=256): super().__init__() channels = { 4: 512, 8: 512, 16: 512, 32: 512, 64: 256 * channel_multiplier, 128: 128 * channel_multiplier, 256: 64 * channel_multiplier, 512: 32 * channel_multiplier, 1024: 16 * channel_multiplier, } log_size = int(math.log(image_size, 2)) in_channel = channels[image_size]
blocks = [nn.Conv2d(input_nc, in_channel, 3, padding=1), leaky_relu()] for i in range(log_size, 2, -1): out_channel = channels[2 ** (i - 1)] blocks.append(DiscriminatorBlock(in_channel, out_channel)) in_channel = out_channel self.blocks = nn.ModuleList(blocks)
self.final_conv = nn.Sequential( nn.Conv2d(in_channel, channels[4], 3, padding=1), leaky_relu(), ) self.final_linear = nn.Sequential( nn.Linear(channels[4] * 4 * 4, channels[4]), leaky_relu(), nn.Linear(channels[4], 1) ) def forward(self, x): for block in self.blocks: x = block(x) x = self.final_conv(x) x = x.view(x.shape[0], -1) x = self.final_linear(x) return x
class DiscriminatorBlock(nn.Module): def __init__(self, input_channels, filters, downsample=True): super().__init__() self.conv_res = nn.Conv2d(input_channels, filters, 1, stride = (2 if downsample else 1))
self.net = nn.Sequential( nn.Conv2d(input_channels, filters, 3, padding=1), leaky_relu(), nn.Conv2d(filters, filters, 3, padding=1), leaky_relu() )
self.downsample = nn.Sequential( Blur(), nn.Conv2d(filters, filters, 3, padding = 1, stride = 2) ) if downsample else None
def forward(self, x): res = self.conv_res(x) x = self.net(x) if exists(self.downsample): x = self.downsample(x) x = (x + res) * (1 / math.sqrt(2)) return x
class Blur(nn.Module): def __init__(self): super().__init__() f = torch.Tensor([1, 2, 1]) self.register_buffer('f', f) def forward(self, x): f = self.f f = f[None, None, :] * f [None, :, None] return filter2d(x, f, normalized=True)
def leaky_relu(p=0.2): return nn.LeakyReLU(p, inplace=True)
def exists(val): return val is not None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164"""Stripped version of https://github.com/richzhang/PerceptualSimilarity/tree/master/models"""
import os, hashlibimport requestsfrom tqdm import tqdm
import torchimport torch.nn as nnfrom torchvision import modelsfrom collections import namedtuple
URL_MAP = { "vgg_lpips": "https://heibox.uni-heidelberg.de/f/607503859c864bc1b30b/?dl=1"}
CKPT_MAP = { "vgg_lpips": "vgg.pth"}
MD5_MAP = { "vgg_lpips": "d507d7349b931f0638a25a48a722f98a"}
def download(url, local_path, chunk_size=1024): os.makedirs(os.path.split(local_path)[0], exist_ok=True) with requests.get(url, stream=True) as r: total_size = int(r.headers.get("content-length", 0)) with tqdm(total=total_size, unit="B", unit_scale=True) as pbar: with open(local_path, "wb") as f: for data in r.iter_content(chunk_size=chunk_size): if data: f.write(data) pbar.update(chunk_size)
def md5_hash(path): with open(path, "rb") as f: content = f.read() return hashlib.md5(content).hexdigest()
def get_ckpt_path(name, root, check=False): assert name in URL_MAP path = os.path.join(root, CKPT_MAP[name]) if not os.path.exists(path) or (check and not md5_hash(path) == MD5_MAP[name]): print("Downloading {} model from {} to {}".format(name, URL_MAP[name], path)) download(URL_MAP[name], path) md5 = md5_hash(path) assert md5 == MD5_MAP[name], md5 return path
class LPIPS(nn.Module): # Learned perceptual metric def __init__(self, use_dropout=True): super().__init__() self.scaling_layer = ScalingLayer() self.chns = [64, 128, 256, 512, 512] # vg16 features self.net = vgg16(pretrained=True, requires_grad=False) self.lin0 = NetLinLayer(self.chns[0], use_dropout=use_dropout) self.lin1 = NetLinLayer(self.chns[1], use_dropout=use_dropout) self.lin2 = NetLinLayer(self.chns[2], use_dropout=use_dropout) self.lin3 = NetLinLayer(self.chns[3], use_dropout=use_dropout) self.lin4 = NetLinLayer(self.chns[4], use_dropout=use_dropout) self.load_from_pretrained() for param in self.parameters(): param.requires_grad = False
def load_from_pretrained(self, name="vgg_lpips"): ckpt = get_ckpt_path(name, os.path.join(os.path.dirname(os.path.abspath(__file__)), "cache")) self.load_state_dict(torch.load(ckpt, map_location=torch.device("cpu")), strict=False) print("loaded pretrained LPIPS loss from {}".format(ckpt))
@classmethod def from_pretrained(cls, name="vgg_lpips"): if name != "vgg_lpips": raise NotImplementedError model = cls() ckpt = get_ckpt_path(name, os.path.join(os.path.dirname(os.path.abspath(__file__)), "cache")) model.load_state_dict(torch.load(ckpt, map_location=torch.device("cpu")), strict=False) return model
def forward(self, input, target): in0_input, in1_input = (self.scaling_layer(input), self.scaling_layer(target)) outs0, outs1 = self.net(in0_input), self.net(in1_input) feats0, feats1, diffs = {}, {}, {} lins = [self.lin0, self.lin1, self.lin2, self.lin3, self.lin4] for kk in range(len(self.chns)): feats0[kk], feats1[kk] = normalize_tensor(outs0[kk]), normalize_tensor(outs1[kk]) diffs[kk] = (feats0[kk] - feats1[kk]) ** 2
res = [spatial_average(lins[kk].model(diffs[kk]), keepdim=True) for kk in range(len(self.chns))] val = res[0] for l in range(1, len(self.chns)): val += res[l] return val
class ScalingLayer(nn.Module): def __init__(self): super(ScalingLayer, self).__init__() self.register_buffer('shift', torch.Tensor([-.030, -.088, -.188])[None, :, None, None]) self.register_buffer('scale', torch.Tensor([.458, .448, .450])[None, :, None, None])
def forward(self, inp): return (inp - self.shift) / self.scale
class NetLinLayer(nn.Module): """ A single linear layer which does a 1x1 conv """ def __init__(self, chn_in, chn_out=1, use_dropout=False): super(NetLinLayer, self).__init__() layers = [nn.Dropout(), ] if (use_dropout) else [] layers += [nn.Conv2d(chn_in, chn_out, 1, stride=1, padding=0, bias=False), ] self.model = nn.Sequential(*layers)
class vgg16(torch.nn.Module): def __init__(self, requires_grad=False, pretrained=True): super(vgg16, self).__init__() vgg_pretrained_features = models.vgg16(pretrained=pretrained).features self.slice1 = torch.nn.Sequential() self.slice2 = torch.nn.Sequential() self.slice3 = torch.nn.Sequential() self.slice4 = torch.nn.Sequential() self.slice5 = torch.nn.Sequential() self.N_slices = 5 for x in range(4): self.slice1.add_module(str(x), vgg_pretrained_features[x]) for x in range(4, 9): self.slice2.add_module(str(x), vgg_pretrained_features[x]) for x in range(9, 16): self.slice3.add_module(str(x), vgg_pretrained_features[x]) for x in range(16, 23): self.slice4.add_module(str(x), vgg_pretrained_features[x]) for x in range(23, 30): self.slice5.add_module(str(x), vgg_pretrained_features[x]) if not requires_grad: for param in self.parameters(): param.requires_grad = False
def forward(self, X): h = self.slice1(X) h_relu1_2 = h h = self.slice2(h) h_relu2_2 = h h = self.slice3(h) h_relu3_3 = h h = self.slice4(h) h_relu4_3 = h h = self.slice5(h) h_relu5_3 = h vgg_outputs = namedtuple("VggOutputs", ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3', 'relu5_3']) out = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3, h_relu5_3) return out
def normalize_tensor(x,eps=1e-10): norm_factor = torch.sqrt(torch.sum(x**2,dim=1,keepdim=True)) return x/(norm_factor+eps)
def spatial_average(x, keepdim=True): return x.mean([2,3],keepdim=keepdim)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197import torchtorch.backends.cuda.matmul.allow_tf32 = Truetorch.backends.cudnn.allow_tf32 = Trueimport torch.nn.functional as Fimport torch.distributed as distfrom torch.utils.data import DataLoaderfrom torch.utils.data.distributed import DistributedSamplerfrom torchvision import transformsfrom tqdm import tqdmimport osfrom PIL import Imageimport numpy as npimport argparseimport itertools
from skimage.metrics import peak_signal_noise_ratio as psnr_lossfrom skimage.metrics import structural_similarity as ssim_loss
from dataset.augmentation import center_crop_arrfrom dataset.build import build_datasetfrom tokenizer.tokenizer_image.vq_model import VQ_models
def create_npz_from_sample_folder(sample_dir, num=50000): """ Builds a single .npz file from a folder of .png samples. """ samples = [] for i in tqdm(range(num), desc="Building .npz file from samples"): sample_pil = Image.open(f"{sample_dir}/{i:06d}.png") sample_np = np.asarray(sample_pil).astype(np.uint8) samples.append(sample_np) samples = np.stack(samples) assert samples.shape == (num, samples.shape[1], samples.shape[2], 3) npz_path = f"{sample_dir}.npz" np.savez(npz_path, arr_0=samples) print(f"Saved .npz file to {npz_path} [shape={samples.shape}].") return npz_path
def main(args): # Setup PyTorch: assert torch.cuda.is_available(), "Sampling with DDP requires at least one GPU. sample.py supports CPU-only usage" torch.set_grad_enabled(False)
# Setup DDP: dist.init_process_group("nccl") rank = dist.get_rank() device = rank % torch.cuda.device_count() seed = args.global_seed * dist.get_world_size() + rank torch.manual_seed(seed) torch.cuda.set_device(device) print(f"Starting rank={rank}, seed={seed}, world_size={dist.get_world_size()}.")
# create and load model vq_model = VQ_models[args.vq_model]( codebook_size=args.codebook_size, codebook_embed_dim=args.codebook_embed_dim) vq_model.to(device) vq_model.eval() checkpoint = torch.load(args.vq_ckpt, map_location="cpu") if "ema" in checkpoint: # ema model_weight = checkpoint["ema"] elif "model" in checkpoint: # ddp model_weight = checkpoint["model"] elif "state_dict" in checkpoint: model_weight = checkpoint["state_dict"] else: raise Exception("please check model weight") vq_model.load_state_dict(model_weight) del checkpoint
# Create folder to save samples: folder_name = (f"{args.vq_model}-{args.dataset}-size-{args.image_size}-size-{args.image_size_eval}" f"-codebook-size-{args.codebook_size}-dim-{args.codebook_embed_dim}-seed-{args.global_seed}") sample_folder_dir = f"{args.sample_dir}/{folder_name}" if rank == 0: os.makedirs(sample_folder_dir, exist_ok=True) print(f"Saving .png samples at {sample_folder_dir}") dist.barrier()
# Setup data: transform = transforms.Compose([ transforms.Lambda(lambda pil_image: center_crop_arr(pil_image, args.image_size)), transforms.ToTensor(), transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True) ])
if args.dataset == 'imagenet': dataset = build_dataset(args, transform=transform) num_fid_samples = 50000 elif args.dataset == 'coco': dataset = build_dataset(args, transform=transform) num_fid_samples = 5000 else: raise Exception("please check dataset") sampler = DistributedSampler( dataset, num_replicas=dist.get_world_size(), rank=rank, shuffle=False, seed=args.global_seed ) loader = DataLoader( dataset, batch_size=args.per_proc_batch_size, shuffle=False, sampler=sampler, num_workers=args.num_workers, pin_memory=True, drop_last=False )
# Figure out how many samples we need to generate on each GPU and how many iterations we need to run: n = args.per_proc_batch_size global_batch_size = n * dist.get_world_size() psnr_val_rgb = [] ssim_val_rgb = [] loader = tqdm(loader) if rank == 0 else loader total = 0 for x, _ in loader: if args.image_size_eval != args.image_size: rgb_gts = F.interpolate(x, size=(args.image_size_eval, args.image_size_eval), mode='bicubic') else: rgb_gts = x rgb_gts = (rgb_gts.permute(0, 2, 3, 1).to("cpu").numpy() + 1.0) / 2.0 # rgb_gt value is between [0, 1] x = x.to(device, non_blocking=True) with torch.no_grad(): latent, _, [_, _, indices] = vq_model.encode(x) samples = vq_model.decode_code(indices, latent.shape) # output value is between [-1, 1] if args.image_size_eval != args.image_size: samples = F.interpolate(samples, size=(args.image_size_eval, args.image_size_eval), mode='bicubic') samples = torch.clamp(127.5 * samples + 128.0, 0, 255).permute(0, 2, 3, 1).to("cpu", dtype=torch.uint8).numpy()
# Save samples to disk as individual .png files for i, (sample, rgb_gt) in enumerate(zip(samples, rgb_gts)): index = i * dist.get_world_size() + rank + total Image.fromarray(sample).save(f"{sample_folder_dir}/{index:06d}.png") # metric rgb_restored = sample.astype(np.float32) / 255. # rgb_restored value is between [0, 1] psnr = psnr_loss(rgb_restored, rgb_gt) ssim = ssim_loss(rgb_restored, rgb_gt, multichannel=True, data_range=2.0, channel_axis=-1) psnr_val_rgb.append(psnr) ssim_val_rgb.append(ssim) total += global_batch_size
# ------------------------------------ # Summary # ------------------------------------ # Make sure all processes have finished saving their samples dist.barrier() world_size = dist.get_world_size() gather_psnr_val = [None for _ in range(world_size)] gather_ssim_val = [None for _ in range(world_size)] dist.all_gather_object(gather_psnr_val, psnr_val_rgb) dist.all_gather_object(gather_ssim_val, ssim_val_rgb)
if rank == 0: gather_psnr_val = list(itertools.chain(*gather_psnr_val)) gather_ssim_val = list(itertools.chain(*gather_ssim_val)) psnr_val_rgb = sum(gather_psnr_val) / len(gather_psnr_val) ssim_val_rgb = sum(gather_ssim_val) / len(gather_ssim_val) print("PSNR: %f, SSIM: %f " % (psnr_val_rgb, ssim_val_rgb))
result_file = f"{sample_folder_dir}_results.txt" print("writing results to {}".format(result_file)) with open(result_file, 'w') as f: print("PSNR: %f, SSIM: %f " % (psnr_val_rgb, ssim_val_rgb), file=f)
create_npz_from_sample_folder(sample_folder_dir, num_fid_samples) print("Done.") dist.barrier() dist.destroy_process_group()
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--data-path", type=str, required=True) parser.add_argument("--dataset", type=str, choices=['imagenet', 'coco'], default='imagenet') parser.add_argument("--vq-model", type=str, choices=list(VQ_models.keys()), default="VQ-16") parser.add_argument("--vq-ckpt", type=str, default=None, help="ckpt path for vq model") parser.add_argument("--codebook-size", type=int, default=16384, help="codebook size for vector quantization") parser.add_argument("--codebook-embed-dim", type=int, default=8, help="codebook dimension for vector quantization") parser.add_argument("--image-size", type=int, choices=[256, 384, 512], default=256) parser.add_argument("--image-size-eval", type=int, choices=[256, 384, 512], default=256) parser.add_argument("--sample-dir", type=str, default="reconstructions") parser.add_argument("--per-proc-batch-size", type=int, default=32) parser.add_argument("--global-seed", type=int, default=0) parser.add_argument("--num-workers", type=int, default=4) args = parser.parse_args() main(args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384import torchimport torch.nn.functional as F
import osimport argparseimport numpy as npfrom PIL import Image
from tokenizer.tokenizer_image.vq_model import VQ_modelsfrom dataset.augmentation import center_crop_arr
def main(args): # Setup PyTorch: torch.manual_seed(args.seed) torch.set_grad_enabled(False) device = "cuda" if torch.cuda.is_available() else "cpu" # create and load model model = VQ_models[args.vq_model]( codebook_size=args.codebook_size, codebook_embed_dim=args.codebook_embed_dim) model.to(device) model.eval() checkpoint = torch.load(args.vq_ckpt, map_location="cpu") if "ema" in checkpoint: # ema model_weight = checkpoint["ema"] elif "model" in checkpoint: # ddp model_weight = checkpoint["model"] elif "state_dict" in checkpoint: model_weight = checkpoint["state_dict"] else: raise Exception("please check model weight") model.load_state_dict(model_weight) del checkpoint
# output dir os.makedirs(args.output_dir, exist_ok=True) out_path = args.image_path.replace('.jpg', '_{}.jpg'.format(args.suffix)) out_path = out_path.replace('.jpeg', '_{}.jpeg'.format(args.suffix)) out_path = out_path.replace('.png', '_{}.png'.format(args.suffix)) out_filename = out_path.split('/')[-1] out_path = os.path.join(args.output_dir, out_filename) # load image pil_image = Image.open(args.image_path).convert("RGB") img = center_crop_arr(pil_image, args.image_size) # # preprocess # size_org = img.size # img = img.resize((input_size, input_size)) img = np.array(img) / 255. x = 2.0 * img - 1.0 # x value is between [-1, 1] x = torch.tensor(x) x = x.unsqueeze(dim=0) x = torch.einsum('nhwc->nchw', x) x_input = x.float().to("cuda")
# inference with torch.no_grad(): latent, _, [_, _, indices] = model.encode(x_input) output = model.decode_code(indices, latent.shape) # output value is between [-1, 1]
# postprocess output = F.interpolate(output, size=[args.image_size, args.image_size], mode='bicubic').permute(0, 2, 3, 1)[0] sample = torch.clamp(127.5 * output + 128.0, 0, 255).to("cpu", dtype=torch.uint8).numpy()
# save Image.fromarray(sample).save(out_path) print("Reconstructed image is saved to {}".format(out_path))
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--image-path", type=str, default="assets/example.jpg") parser.add_argument("--output-dir", type=str, default="output_vq_demo") parser.add_argument("--suffix", type=str, default="tokenizer_image") parser.add_argument("--vq-model", type=str, choices=list(VQ_models.keys()), default="VQ-16") parser.add_argument("--vq-ckpt", type=str, default=None, help="ckpt path for vq model") parser.add_argument("--codebook-size", type=int, default=16384, help="codebook size for vector quantization") parser.add_argument("--codebook-embed-dim", type=int, default=8, help="codebook dimension for vector quantization") parser.add_argument("--image-size", type=int, choices=[256, 384, 448, 512, 1024], default=512) parser.add_argument("--seed", type=int, default=0) args = parser.parse_args() main(args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168# Modified from:# taming-transformers: https://github.com/CompVis/taming-transformers# muse-maskgit-pytorch: https://github.com/lucidrains/muse-maskgit-pytorch/blob/main/muse_maskgit_pytorch/vqgan_vae.pyimport torchimport torch.nn as nnimport torch.nn.functional as F
from tokenizer.tokenizer_image.lpips import LPIPSfrom tokenizer.tokenizer_image.discriminator_patchgan import NLayerDiscriminator as PatchGANDiscriminatorfrom tokenizer.tokenizer_image.discriminator_stylegan import Discriminator as StyleGANDiscriminator
def hinge_d_loss(logits_real, logits_fake): loss_real = torch.mean(F.relu(1. - logits_real)) loss_fake = torch.mean(F.relu(1. + logits_fake)) d_loss = 0.5 * (loss_real + loss_fake) return d_loss
def vanilla_d_loss(logits_real, logits_fake): loss_real = torch.mean(F.softplus(-logits_real)) loss_fake = torch.mean(F.softplus(logits_fake)) d_loss = 0.5 * (loss_real + loss_fake) return d_loss
def non_saturating_d_loss(logits_real, logits_fake): loss_real = torch.mean(F.binary_cross_entropy_with_logits(torch.ones_like(logits_real), logits_real)) loss_fake = torch.mean(F.binary_cross_entropy_with_logits(torch.zeros_like(logits_fake), logits_fake)) d_loss = 0.5 * (loss_real + loss_fake) return d_loss
def hinge_gen_loss(logit_fake): return -torch.mean(logit_fake)
def non_saturating_gen_loss(logit_fake): return torch.mean(F.binary_cross_entropy_with_logits(torch.ones_like(logit_fake), logit_fake))
def adopt_weight(weight, global_step, threshold=0, value=0.): if global_step < threshold: weight = value return weight
class VQLoss(nn.Module): def __init__(self, disc_start, disc_loss="hinge", disc_dim=64, disc_type='patchgan', image_size=256, disc_num_layers=3, disc_in_channels=3, disc_weight=1.0, disc_adaptive_weight = False, gen_adv_loss='hinge', reconstruction_loss='l2', reconstruction_weight=1.0, codebook_weight=1.0, perceptual_weight=1.0, ): super().__init__() # discriminator loss assert disc_type in ["patchgan", "stylegan"] assert disc_loss in ["hinge", "vanilla", "non-saturating"] if disc_type == "patchgan": self.discriminator = PatchGANDiscriminator( input_nc=disc_in_channels, n_layers=disc_num_layers, ndf=disc_dim, ) elif disc_type == "stylegan": self.discriminator = StyleGANDiscriminator( input_nc=disc_in_channels, image_size=image_size, ) else: raise ValueError(f"Unknown GAN discriminator type '{disc_type}'.") if disc_loss == "hinge": self.disc_loss = hinge_d_loss elif disc_loss == "vanilla": self.disc_loss = vanilla_d_loss elif disc_loss == "non-saturating": self.disc_loss = non_saturating_d_loss else: raise ValueError(f"Unknown GAN discriminator loss '{disc_loss}'.") self.discriminator_iter_start = disc_start self.disc_weight = disc_weight self.disc_adaptive_weight = disc_adaptive_weight
assert gen_adv_loss in ["hinge", "non-saturating"] # gen_adv_loss if gen_adv_loss == "hinge": self.gen_adv_loss = hinge_gen_loss elif gen_adv_loss == "non-saturating": self.gen_adv_loss = non_saturating_gen_loss else: raise ValueError(f"Unknown GAN generator loss '{gen_adv_loss}'.")
# perceptual loss self.perceptual_loss = LPIPS().eval() self.perceptual_weight = perceptual_weight
# reconstruction loss if reconstruction_loss == "l1": self.rec_loss = F.l1_loss elif reconstruction_loss == "l2": self.rec_loss = F.mse_loss else: raise ValueError(f"Unknown rec loss '{reconstruction_loss}'.") self.rec_weight = reconstruction_weight
# codebook loss self.codebook_weight = codebook_weight
def calculate_adaptive_weight(self, nll_loss, g_loss, last_layer): nll_grads = torch.autograd.grad(nll_loss, last_layer, retain_graph=True)[0] g_grads = torch.autograd.grad(g_loss, last_layer, retain_graph=True)[0]
d_weight = torch.norm(nll_grads) / (torch.norm(g_grads) + 1e-4) d_weight = torch.clamp(d_weight, 0.0, 1e4).detach() return d_weight.detach()
def forward(self, codebook_loss, inputs, reconstructions, optimizer_idx, global_step, last_layer=None, logger=None, log_every=100): # generator update if optimizer_idx == 0: # reconstruction loss rec_loss = self.rec_loss(inputs.contiguous(), reconstructions.contiguous())
# perceptual loss p_loss = self.perceptual_loss(inputs.contiguous(), reconstructions.contiguous()) p_loss = torch.mean(p_loss)
# discriminator loss logits_fake = self.discriminator(reconstructions.contiguous()) generator_adv_loss = self.gen_adv_loss(logits_fake) if self.disc_adaptive_weight: null_loss = self.rec_weight * rec_loss + self.perceptual_weight * p_loss disc_adaptive_weight = self.calculate_adaptive_weight(null_loss, generator_adv_loss, last_layer=last_layer) else: disc_adaptive_weight = 1 disc_weight = adopt_weight(self.disc_weight, global_step, threshold=self.discriminator_iter_start) loss = self.rec_weight * rec_loss + \ self.perceptual_weight * p_loss + \ disc_adaptive_weight * disc_weight * generator_adv_loss + \ codebook_loss[0] + codebook_loss[1] + codebook_loss[2] if global_step % log_every == 0: rec_loss = self.rec_weight * rec_loss p_loss = self.perceptual_weight * p_loss generator_adv_loss = disc_adaptive_weight * disc_weight * generator_adv_loss logger.info(f"(Generator) rec_loss: {rec_loss:.4f}, perceptual_loss: {p_loss:.4f}, " f"vq_loss: {codebook_loss[0]:.4f}, commit_loss: {codebook_loss[1]:.4f}, entropy_loss: {codebook_loss[2]:.4f}, " f"codebook_usage: {codebook_loss[3]:.4f}, generator_adv_loss: {generator_adv_loss:.4f}, " f"disc_adaptive_weight: {disc_adaptive_weight:.4f}, disc_weight: {disc_weight:.4f}") return loss
# discriminator update if optimizer_idx == 1: logits_real = self.discriminator(inputs.contiguous().detach()) logits_fake = self.discriminator(reconstructions.contiguous().detach())
disc_weight = adopt_weight(self.disc_weight, global_step, threshold=self.discriminator_iter_start) d_adversarial_loss = disc_weight * self.disc_loss(logits_real, logits_fake) if global_step % log_every == 0: logits_real = logits_real.detach().mean() logits_fake = logits_fake.detach().mean() logger.info(f"(Discriminator) " f"discriminator_adv_loss: {d_adversarial_loss:.4f}, disc_weight: {disc_weight:.4f}, " f"logits_real: {logits_real:.4f}, logits_fake: {logits_fake:.4f}") return d_adversarial_loss123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424# Modified from:# taming-transformers: https://github.com/CompVis/taming-transformers# maskgit: https://github.com/google-research/maskgitfrom dataclasses import dataclass, fieldfrom typing import List
import torchimport torch.nn as nnimport torch.nn.functional as F
@dataclassclass ModelArgs: codebook_size: int = 16384 codebook_embed_dim: int = 8 codebook_l2_norm: bool = True codebook_show_usage: bool = True commit_loss_beta: float = 0.25 entropy_loss_ratio: float = 0.0 encoder_ch_mult: List[int] = field(default_factory=lambda: [1, 1, 2, 2, 4]) decoder_ch_mult: List[int] = field(default_factory=lambda: [1, 1, 2, 2, 4]) z_channels: int = 256 dropout_p: float = 0.0
class VQModel(nn.Module): def __init__(self, config: ModelArgs): super().__init__() self.config = config self.encoder = Encoder(ch_mult=config.encoder_ch_mult, z_channels=config.z_channels, dropout=config.dropout_p) self.decoder = Decoder(ch_mult=config.decoder_ch_mult, z_channels=config.z_channels, dropout=config.dropout_p)
self.quantize = VectorQuantizer(config.codebook_size, config.codebook_embed_dim, config.commit_loss_beta, config.entropy_loss_ratio, config.codebook_l2_norm, config.codebook_show_usage) self.quant_conv = nn.Conv2d(config.z_channels, config.codebook_embed_dim, 1) self.post_quant_conv = nn.Conv2d(config.codebook_embed_dim, config.z_channels, 1)
def encode(self, x): h = self.encoder(x) h = self.quant_conv(h) quant, emb_loss, info = self.quantize(h) return quant, emb_loss, info
def decode(self, quant): quant = self.post_quant_conv(quant) dec = self.decoder(quant) return dec
def decode_code(self, code_b, shape=None, channel_first=True): quant_b = self.quantize.get_codebook_entry(code_b, shape, channel_first) dec = self.decode(quant_b) return dec
def forward(self, input): quant, diff, _ = self.encode(input) dec = self.decode(quant) return dec, diff
class Encoder(nn.Module): def __init__(self, in_channels=3, ch=128, ch_mult=(1,1,2,2,4), num_res_blocks=2, norm_type='group', dropout=0.0, resamp_with_conv=True, z_channels=256): super().__init__() self.num_resolutions = len(ch_mult) self.num_res_blocks = num_res_blocks self.conv_in = nn.Conv2d(in_channels, ch, kernel_size=3, stride=1, padding=1)
# downsampling in_ch_mult = (1,) + tuple(ch_mult) self.conv_blocks = nn.ModuleList() for i_level in range(self.num_resolutions): conv_block = nn.Module() # res & attn res_block = nn.ModuleList() attn_block = nn.ModuleList() block_in = ch*in_ch_mult[i_level] block_out = ch*ch_mult[i_level] for _ in range(self.num_res_blocks): res_block.append(ResnetBlock(block_in, block_out, dropout=dropout, norm_type=norm_type)) block_in = block_out if i_level == self.num_resolutions - 1: attn_block.append(AttnBlock(block_in, norm_type)) conv_block.res = res_block conv_block.attn = attn_block # downsample if i_level != self.num_resolutions-1: conv_block.downsample = Downsample(block_in, resamp_with_conv) self.conv_blocks.append(conv_block)
# middle self.mid = nn.ModuleList() self.mid.append(ResnetBlock(block_in, block_in, dropout=dropout, norm_type=norm_type)) self.mid.append(AttnBlock(block_in, norm_type=norm_type)) self.mid.append(ResnetBlock(block_in, block_in, dropout=dropout, norm_type=norm_type))
# end self.norm_out = Normalize(block_in, norm_type) self.conv_out = nn.Conv2d(block_in, z_channels, kernel_size=3, stride=1, padding=1)
def forward(self, x): h = self.conv_in(x) # downsampling for i_level, block in enumerate(self.conv_blocks): for i_block in range(self.num_res_blocks): h = block.res[i_block](h) if len(block.attn) > 0: h = block.attn[i_block](h) if i_level != self.num_resolutions - 1: h = block.downsample(h) # middle for mid_block in self.mid: h = mid_block(h) # end h = self.norm_out(h) h = nonlinearity(h) h = self.conv_out(h) return h
class Decoder(nn.Module): def __init__(self, z_channels=256, ch=128, ch_mult=(1,1,2,2,4), num_res_blocks=2, norm_type="group", dropout=0.0, resamp_with_conv=True, out_channels=3): super().__init__() self.num_resolutions = len(ch_mult) self.num_res_blocks = num_res_blocks
block_in = ch*ch_mult[self.num_resolutions-1] # z to block_in self.conv_in = nn.Conv2d(z_channels, block_in, kernel_size=3, stride=1, padding=1)
# middle self.mid = nn.ModuleList() self.mid.append(ResnetBlock(block_in, block_in, dropout=dropout, norm_type=norm_type)) self.mid.append(AttnBlock(block_in, norm_type=norm_type)) self.mid.append(ResnetBlock(block_in, block_in, dropout=dropout, norm_type=norm_type))
# upsampling self.conv_blocks = nn.ModuleList() for i_level in reversed(range(self.num_resolutions)): conv_block = nn.Module() # res & attn res_block = nn.ModuleList() attn_block = nn.ModuleList() block_out = ch*ch_mult[i_level] for _ in range(self.num_res_blocks + 1): res_block.append(ResnetBlock(block_in, block_out, dropout=dropout, norm_type=norm_type)) block_in = block_out if i_level == self.num_resolutions - 1: attn_block.append(AttnBlock(block_in, norm_type)) conv_block.res = res_block conv_block.attn = attn_block # downsample if i_level != 0: conv_block.upsample = Upsample(block_in, resamp_with_conv) self.conv_blocks.append(conv_block)
# end self.norm_out = Normalize(block_in, norm_type) self.conv_out = nn.Conv2d(block_in, out_channels, kernel_size=3, stride=1, padding=1)
@property def last_layer(self): return self.conv_out.weight def forward(self, z): # z to block_in h = self.conv_in(z)
# middle for mid_block in self.mid: h = mid_block(h) # upsampling for i_level, block in enumerate(self.conv_blocks): for i_block in range(self.num_res_blocks + 1): h = block.res[i_block](h) if len(block.attn) > 0: h = block.attn[i_block](h) if i_level != self.num_resolutions - 1: h = block.upsample(h)
# end h = self.norm_out(h) h = nonlinearity(h) h = self.conv_out(h) return h
class VectorQuantizer(nn.Module): def __init__(self, n_e, e_dim, beta, entropy_loss_ratio, l2_norm, show_usage): super().__init__() self.n_e = n_e self.e_dim = e_dim self.beta = beta self.entropy_loss_ratio = entropy_loss_ratio self.l2_norm = l2_norm self.show_usage = show_usage
self.embedding = nn.Embedding(self.n_e, self.e_dim) self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e) if self.l2_norm: self.embedding.weight.data = F.normalize(self.embedding.weight.data, p=2, dim=-1) if self.show_usage: self.register_buffer("codebook_used", nn.Parameter(torch.zeros(65536)))
def forward(self, z): # reshape z -> (batch, height, width, channel) and flatten z = torch.einsum('b c h w -> b h w c', z).contiguous() z_flattened = z.view(-1, self.e_dim) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
if self.l2_norm: z = F.normalize(z, p=2, dim=-1) z_flattened = F.normalize(z_flattened, p=2, dim=-1) embedding = F.normalize(self.embedding.weight, p=2, dim=-1) else: embedding = self.embedding.weight
d = torch.sum(z_flattened ** 2, dim=1, keepdim=True) + \ torch.sum(embedding**2, dim=1) - 2 * \ torch.einsum('bd,dn->bn', z_flattened, torch.einsum('n d -> d n', embedding))
min_encoding_indices = torch.argmin(d, dim=1) z_q = embedding[min_encoding_indices].view(z.shape) perplexity = None min_encodings = None vq_loss = None commit_loss = None entropy_loss = None codebook_usage = 0
if self.show_usage and self.training: cur_len = min_encoding_indices.shape[0] self.codebook_used[:-cur_len] = self.codebook_used[cur_len:].clone() self.codebook_used[-cur_len:] = min_encoding_indices codebook_usage = len(torch.unique(self.codebook_used)) / self.n_e
# compute loss for embedding if self.training: vq_loss = torch.mean((z_q - z.detach()) ** 2) commit_loss = self.beta * torch.mean((z_q.detach() - z) ** 2) entropy_loss = self.entropy_loss_ratio * compute_entropy_loss(-d)
# preserve gradients z_q = z + (z_q - z).detach()
# reshape back to match original input shape z_q = torch.einsum('b h w c -> b c h w', z_q)
return z_q, (vq_loss, commit_loss, entropy_loss, codebook_usage), (perplexity, min_encodings, min_encoding_indices)
def get_codebook_entry(self, indices, shape=None, channel_first=True): # shape = (batch, channel, height, width) if channel_first else (batch, height, width, channel) if self.l2_norm: embedding = F.normalize(self.embedding.weight, p=2, dim=-1) else: embedding = self.embedding.weight z_q = embedding[indices] # (b*h*w, c)
if shape is not None: if channel_first: z_q = z_q.reshape(shape[0], shape[2], shape[3], shape[1]) # reshape back to match original input shape z_q = z_q.permute(0, 3, 1, 2).contiguous() else: z_q = z_q.view(shape) return z_q
class ResnetBlock(nn.Module): def __init__(self, in_channels, out_channels=None, conv_shortcut=False, dropout=0.0, norm_type='group'): super().__init__() self.in_channels = in_channels out_channels = in_channels if out_channels is None else out_channels self.out_channels = out_channels self.use_conv_shortcut = conv_shortcut
self.norm1 = Normalize(in_channels, norm_type) self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1) self.norm2 = Normalize(out_channels, norm_type) self.dropout = nn.Dropout(dropout) self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
if self.in_channels != self.out_channels: if self.use_conv_shortcut: self.conv_shortcut = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1) else: self.nin_shortcut = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
def forward(self, x): h = x h = self.norm1(h) h = nonlinearity(h) h = self.conv1(h) h = self.norm2(h) h = nonlinearity(h) h = self.dropout(h) h = self.conv2(h)
if self.in_channels != self.out_channels: if self.use_conv_shortcut: x = self.conv_shortcut(x) else: x = self.nin_shortcut(x) return x+h
class AttnBlock(nn.Module): def __init__(self, in_channels, norm_type='group'): super().__init__() self.norm = Normalize(in_channels, norm_type) self.q = nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) self.k = nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) self.v = nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) self.proj_out = nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
def forward(self, x): h_ = x h_ = self.norm(h_) q = self.q(h_) k = self.k(h_) v = self.v(h_)
# compute attention b,c,h,w = q.shape q = q.reshape(b,c,h*w) q = q.permute(0,2,1) # b,hw,c k = k.reshape(b,c,h*w) # b,c,hw w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j] w_ = w_ * (int(c)**(-0.5)) w_ = F.softmax(w_, dim=2)
# attend to values v = v.reshape(b,c,h*w) w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q) h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j] h_ = h_.reshape(b,c,h,w)
h_ = self.proj_out(h_)
return x+h_
def nonlinearity(x): # swish return x*torch.sigmoid(x)
def Normalize(in_channels, norm_type='group'): assert norm_type in ['group', 'batch'] if norm_type == 'group': return nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True) elif norm_type == 'batch': return nn.SyncBatchNorm(in_channels)
class Upsample(nn.Module): def __init__(self, in_channels, with_conv): super().__init__() self.with_conv = with_conv if self.with_conv: self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)
def forward(self, x): x = F.interpolate(x, scale_factor=2.0, mode="nearest") if self.with_conv: x = self.conv(x) return x
class Downsample(nn.Module): def __init__(self, in_channels, with_conv): super().__init__() self.with_conv = with_conv if self.with_conv: # no asymmetric padding in torch conv, must do it ourselves self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=0)
def forward(self, x): if self.with_conv: pad = (0,1,0,1) x = F.pad(x, pad, mode="constant", value=0) x = self.conv(x) else: x = F.avg_pool2d(x, kernel_size=2, stride=2) return x
def compute_entropy_loss(affinity, loss_type="softmax", temperature=0.01): flat_affinity = affinity.reshape(-1, affinity.shape[-1]) flat_affinity /= temperature probs = F.softmax(flat_affinity, dim=-1) log_probs = F.log_softmax(flat_affinity + 1e-5, dim=-1) if loss_type == "softmax": target_probs = probs else: raise ValueError("Entropy loss {} not supported".format(loss_type)) avg_probs = torch.mean(target_probs, dim=0) avg_entropy = - torch.sum(avg_probs * torch.log(avg_probs + 1e-5)) sample_entropy = - torch.mean(torch.sum(target_probs * log_probs, dim=-1)) loss = sample_entropy - avg_entropy return loss
################################################################################## VQ Model Configs ##################################################################################def VQ_8(**kwargs): return VQModel(ModelArgs(encoder_ch_mult=[1, 2, 2, 4], decoder_ch_mult=[1, 2, 2, 4], **kwargs))
def VQ_16(**kwargs): return VQModel(ModelArgs(encoder_ch_mult=[1, 1, 2, 2, 4], decoder_ch_mult=[1, 1, 2, 2, 4], **kwargs))
VQ_models = {'VQ-16': VQ_16, 'VQ-8': VQ_8}1234567891011121314151617from huggingface_hub import PyTorchModelHubMixin
from tokenizer.tokenizer_image.vq_model import ModelArgs, VQModel
class VQModelHF(VQModel, PyTorchModelHubMixin, repo_url="https://github.com/FoundationVision/LlamaGen", license="mit", tags=["llamagen", "text-to-image"]): pass
################################################################################## VQ Model Configs ##################################################################################def VQ_8(**kwargs): return VQModelHF(ModelArgs(encoder_ch_mult=[1, 2, 2, 4], decoder_ch_mult=[1, 2, 2, 4], **kwargs))
def VQ_16(**kwargs): return VQModelHF(ModelArgs(encoder_ch_mult=[1, 1, 2, 2, 4], decoder_ch_mult=[1, 1, 2, 2, 4], **kwargs))
VQ_models_HF = {'VQ-16': VQ_16, 'VQ-8': VQ_8}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316# Modified from:# fast-DiT: https://github.com/chuanyangjin/fast-DiT/blob/main/train.py# nanoGPT: https://github.com/karpathy/nanoGPT/blob/master/model.pyimport torch# the first flag below was False when we tested this script but True makes A100 training a lot faster:torch.backends.cuda.matmul.allow_tf32 = Truetorch.backends.cudnn.allow_tf32 = Trueimport torch.distributed as distfrom torch.nn.parallel import DistributedDataParallel as DDPfrom torch.utils.data import Dataset, DataLoaderfrom torch.utils.data.distributed import DistributedSamplerfrom torchvision.datasets import ImageFolderfrom torchvision import transforms
import osimport timeimport argparsefrom glob import globfrom copy import deepcopy
from utils.logger import create_loggerfrom utils.distributed import init_distributed_modefrom utils.ema import update_ema, requires_gradfrom dataset.augmentation import random_crop_arrfrom dataset.build import build_datasetfrom tokenizer.tokenizer_image.vq_model import VQ_modelsfrom tokenizer.tokenizer_image.vq_loss import VQLoss
import warningswarnings.filterwarnings('ignore')
################################################################################## Training Loop ##################################################################################
def main(args): """ Trains a new model. """ assert torch.cuda.is_available(), "Training currently requires at least one GPU." # Setup DDP: init_distributed_mode(args) assert args.global_batch_size % dist.get_world_size() == 0, f"Batch size must be divisible by world size." rank = dist.get_rank() device = rank % torch.cuda.device_count() seed = args.global_seed * dist.get_world_size() + rank torch.manual_seed(seed) torch.cuda.set_device(device)
# Setup an experiment folder: if rank == 0: os.makedirs(args.results_dir, exist_ok=True) # Make results folder (holds all experiment subfolders) experiment_index = len(glob(f"{args.results_dir}/*")) model_string_name = args.vq_model.replace("/", "-") experiment_dir = f"{args.results_dir}/{experiment_index:03d}-{model_string_name}" # Create an experiment folder checkpoint_dir = f"{experiment_dir}/checkpoints" # Stores saved model checkpoints os.makedirs(checkpoint_dir, exist_ok=True) logger = create_logger(experiment_dir) logger.info(f"Experiment directory created at {experiment_dir}")
time_record = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) cloud_results_dir = f"{args.cloud_save_path}/{time_record}" cloud_checkpoint_dir = f"{cloud_results_dir}/{experiment_index:03d}-{model_string_name}/checkpoints" os.makedirs(cloud_checkpoint_dir, exist_ok=True) logger.info(f"Experiment directory created in cloud at {cloud_checkpoint_dir}") else: logger = create_logger(None)
# training args logger.info(f"{args}")
# training env logger.info(f"Starting rank={rank}, seed={seed}, world_size={dist.get_world_size()}.")
# create and load model vq_model = VQ_models[args.vq_model]( codebook_size=args.codebook_size, codebook_embed_dim=args.codebook_embed_dim, commit_loss_beta=args.commit_loss_beta, entropy_loss_ratio=args.entropy_loss_ratio, dropout_p=args.dropout_p, ) logger.info(f"VQ Model Parameters: {sum(p.numel() for p in vq_model.parameters()):,}") if args.ema: ema = deepcopy(vq_model).to(device) # Create an EMA of the model for use after training requires_grad(ema, False) logger.info(f"VQ Model EMA Parameters: {sum(p.numel() for p in ema.parameters()):,}") vq_model = vq_model.to(device)
vq_loss = VQLoss( disc_start=args.disc_start, disc_weight=args.disc_weight, disc_type=args.disc_type, disc_loss=args.disc_loss, gen_adv_loss=args.gen_loss, image_size=args.image_size, perceptual_weight=args.perceptual_weight, reconstruction_weight=args.reconstruction_weight, reconstruction_loss=args.reconstruction_loss, codebook_weight=args.codebook_weight, ).to(device) logger.info(f"Discriminator Parameters: {sum(p.numel() for p in vq_loss.discriminator.parameters()):,}")
# initialize a GradScaler. If enabled=False scaler is a no-op scaler = torch.cuda.amp.GradScaler(enabled=(args.mixed_precision =='fp16')) scaler_disc = torch.cuda.amp.GradScaler(enabled=(args.mixed_precision =='fp16')) # Setup optimizer optimizer = torch.optim.Adam(vq_model.parameters(), lr=args.lr, betas=(args.beta1, args.beta2)) optimizer_disc = torch.optim.Adam(vq_loss.discriminator.parameters(), lr=args.lr, betas=(args.beta1, args.beta2))
# Setup data: transform = transforms.Compose([ transforms.Lambda(lambda pil_image: random_crop_arr(pil_image, args.image_size)), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True) ]) dataset = build_dataset(args, transform=transform) sampler = DistributedSampler( dataset, num_replicas=dist.get_world_size(), rank=rank, shuffle=True, seed=args.global_seed ) loader = DataLoader( dataset, batch_size=int(args.global_batch_size // dist.get_world_size()), shuffle=False, sampler=sampler, num_workers=args.num_workers, pin_memory=True, drop_last=True ) logger.info(f"Dataset contains {len(dataset):,} images ({args.data_path})")
# Prepare models for training: if args.vq_ckpt: checkpoint = torch.load(args.vq_ckpt, map_location="cpu") vq_model.load_state_dict(checkpoint["model"]) if args.ema: ema.load_state_dict(checkpoint["ema"]) optimizer.load_state_dict(checkpoint["optimizer"]) vq_loss.discriminator.load_state_dict(checkpoint["discriminator"]) optimizer_disc.load_state_dict(checkpoint["optimizer_disc"]) if not args.finetune: train_steps = checkpoint["steps"] if "steps" in checkpoint else int(args.vq_ckpt.split('/')[-1].split('.')[0]) start_epoch = int(train_steps / int(len(dataset) / args.global_batch_size)) train_steps = int(start_epoch * int(len(dataset) / args.global_batch_size)) else: train_steps = 0 start_epoch = 0 del checkpoint logger.info(f"Resume training from checkpoint: {args.vq_ckpt}") logger.info(f"Initial state: steps={train_steps}, epochs={start_epoch}") else: train_steps = 0 start_epoch = 0 if args.ema: update_ema(ema, vq_model, decay=0) # Ensure EMA is initialized with synced weights if args.compile: logger.info("compiling the model... (may take several minutes)") vq_model = torch.compile(vq_model) # requires PyTorch 2.0 vq_model = DDP(vq_model.to(device), device_ids=[args.gpu]) vq_model.train() if args.ema: ema.eval() # EMA model should always be in eval mode vq_loss = DDP(vq_loss.to(device), device_ids=[args.gpu]) vq_loss.train()
ptdtype = {'none': torch.float32, 'bf16': torch.bfloat16, 'fp16': torch.float16}[args.mixed_precision]
# Variables for monitoring/logging purposes: log_steps = 0 running_loss = 0 start_time = time.time()
logger.info(f"Training for {args.epochs} epochs...") for epoch in range(start_epoch, args.epochs): sampler.set_epoch(epoch) logger.info(f"Beginning epoch {epoch}...") for x, y in loader: imgs = x.to(device, non_blocking=True)
# generator training optimizer.zero_grad() with torch.cuda.amp.autocast(dtype=ptdtype): recons_imgs, codebook_loss = vq_model(imgs) loss_gen = vq_loss(codebook_loss, imgs, recons_imgs, optimizer_idx=0, global_step=train_steps+1, last_layer=vq_model.module.decoder.last_layer, logger=logger, log_every=args.log_every) scaler.scale(loss_gen).backward() if args.max_grad_norm != 0.0: scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(vq_model.parameters(), args.max_grad_norm) scaler.step(optimizer) scaler.update() if args.ema: update_ema(ema, vq_model.module._orig_mod if args.compile else vq_model.module)
# discriminator training optimizer_disc.zero_grad() with torch.cuda.amp.autocast(dtype=ptdtype): loss_disc = vq_loss(codebook_loss, imgs, recons_imgs, optimizer_idx=1, global_step=train_steps+1, logger=logger, log_every=args.log_every) scaler_disc.scale(loss_disc).backward() if args.max_grad_norm != 0.0: scaler_disc.unscale_(optimizer_disc) torch.nn.utils.clip_grad_norm_(vq_loss.module.discriminator.parameters(), args.max_grad_norm) scaler_disc.step(optimizer_disc) scaler_disc.update() # # Log loss values: running_loss += loss_gen.item() + loss_disc.item() log_steps += 1 train_steps += 1 if train_steps % args.log_every == 0: # Measure training speed: torch.cuda.synchronize() end_time = time.time() steps_per_sec = log_steps / (end_time - start_time) # Reduce loss history over all processes: avg_loss = torch.tensor(running_loss / log_steps, device=device) dist.all_reduce(avg_loss, op=dist.ReduceOp.SUM) avg_loss = avg_loss.item() / dist.get_world_size() logger.info(f"(step={train_steps:07d}) Train Loss: {avg_loss:.4f}, Train Steps/Sec: {steps_per_sec:.2f}") # Reset monitoring variables: running_loss = 0 log_steps = 0 start_time = time.time()
# Save checkpoint: if train_steps % args.ckpt_every == 0 and train_steps > 0: if rank == 0: if args.compile: model_weight = vq_model.module._orig_mod.state_dict() else: model_weight = vq_model.module.state_dict() checkpoint = { "model": model_weight, "optimizer": optimizer.state_dict(), "discriminator": vq_loss.module.discriminator.state_dict(), "optimizer_disc": optimizer_disc.state_dict(), "steps": train_steps, "args": args } if args.ema: checkpoint["ema"] = ema.state_dict() if not args.no_local_save: checkpoint_path = f"{checkpoint_dir}/{train_steps:07d}.pt" torch.save(checkpoint, checkpoint_path) logger.info(f"Saved checkpoint to {checkpoint_path}") cloud_checkpoint_path = f"{cloud_checkpoint_dir}/{train_steps:07d}.pt" torch.save(checkpoint, cloud_checkpoint_path) logger.info(f"Saved checkpoint in cloud to {cloud_checkpoint_path}") dist.barrier()
vq_model.eval() # important! This disables randomized embedding dropout # do any sampling/FID calculation/etc. with ema (or model) in eval mode ...
logger.info("Done!") dist.destroy_process_group()
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--data-path", type=str, required=True) parser.add_argument("--data-face-path", type=str, default=None, help="face datasets to improve vq model") parser.add_argument("--cloud-save-path", type=str, required=True, help='please specify a cloud disk path, if not, local path') parser.add_argument("--no-local-save", action='store_true', help='no save checkpoints to local path for limited disk volume') parser.add_argument("--vq-model", type=str, choices=list(VQ_models.keys()), default="VQ-16") parser.add_argument("--vq-ckpt", type=str, default=None, help="ckpt path for resume training") parser.add_argument("--finetune", action='store_true', help="finetune a pre-trained vq model") parser.add_argument("--ema", action='store_true', help="whether using ema training") parser.add_argument("--codebook-size", type=int, default=16384, help="codebook size for vector quantization") parser.add_argument("--codebook-embed-dim", type=int, default=8, help="codebook dimension for vector quantization") parser.add_argument("--codebook-l2-norm", action='store_true', default=True, help="l2 norm codebook") parser.add_argument("--codebook-weight", type=float, default=1.0, help="codebook loss weight for vector quantization") parser.add_argument("--entropy-loss-ratio", type=float, default=0.0, help="entropy loss ratio in codebook loss") parser.add_argument("--commit-loss-beta", type=float, default=0.25, help="commit loss beta in codebook loss") parser.add_argument("--reconstruction-weight", type=float, default=1.0, help="reconstruction loss weight of image pixel") parser.add_argument("--reconstruction-loss", type=str, default='l2', help="reconstruction loss type of image pixel") parser.add_argument("--perceptual-weight", type=float, default=1.0, help="perceptual loss weight of LPIPS") parser.add_argument("--disc-weight", type=float, default=0.5, help="discriminator loss weight for gan training") parser.add_argument("--disc-start", type=int, default=20000, help="iteration to start discriminator training and loss") parser.add_argument("--disc-type", type=str, choices=['patchgan', 'stylegan'], default='patchgan', help="discriminator type") parser.add_argument("--disc-loss", type=str, choices=['hinge', 'vanilla', 'non-saturating'], default='hinge', help="discriminator loss") parser.add_argument("--gen-loss", type=str, choices=['hinge', 'non-saturating'], default='hinge', help="generator loss for gan training") parser.add_argument("--compile", action='store_true', default=False) parser.add_argument("--dropout-p", type=float, default=0.0, help="dropout_p") parser.add_argument("--results-dir", type=str, default="results_tokenizer_image") parser.add_argument("--dataset", type=str, default='imagenet') parser.add_argument("--image-size", type=int, choices=[256, 512], default=256) parser.add_argument("--epochs", type=int, default=40) parser.add_argument("--lr", type=float, default=1e-4) parser.add_argument("--weight-decay", type=float, default=5e-2, help="Weight decay to use.") parser.add_argument("--beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.") parser.add_argument("--beta2", type=float, default=0.95, help="The beta2 parameter for the Adam optimizer.") parser.add_argument("--max-grad-norm", default=1.0, type=float, help="Max gradient norm.") parser.add_argument("--global-batch-size", type=int, default=128) parser.add_argument("--global-seed", type=int, default=0) parser.add_argument("--num-workers", type=int, default=16) parser.add_argument("--log-every", type=int, default=100) parser.add_argument("--ckpt-every", type=int, default=5000) parser.add_argument("--gradient-accumulation-steps", type=int, default=1) parser.add_argument("--mixed-precision", type=str, default='bf16', choices=["none", "fp16", "bf16"]) args = parser.parse_args() main(args)1234567891011121314## VAE Models from Stable Diffusion
### install```pip install diffuserspip install accelerate```
### demo```cd ${THIS_REPO_ROOT}python3 tokenizer/vae/sd_vae_demo.py```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210import torchtorch.backends.cuda.matmul.allow_tf32 = Truetorch.backends.cudnn.allow_tf32 = Trueimport torch.distributed as distfrom torch.utils.data import Dataset, DataLoaderfrom torch.utils.data.distributed import DistributedSamplerfrom torchvision.datasets import ImageFolderfrom torchvision import transformsfrom tqdm import tqdmimport osimport itertoolsfrom PIL import Imageimport numpy as npimport argparseimport random
from skimage.metrics import peak_signal_noise_ratio as psnr_lossfrom skimage.metrics import structural_similarity as ssim_lossfrom diffusers.models import AutoencoderKL
class SingleFolderDataset(Dataset): def __init__(self, directory, transform=None): super().__init__() self.directory = directory self.transform = transform self.image_paths = [os.path.join(directory, file_name) for file_name in os.listdir(directory) if os.path.isfile(os.path.join(directory, file_name))]
def __len__(self): return len(self.image_paths)
def __getitem__(self, idx): image_path = self.image_paths[idx] image = Image.open(image_path).convert('RGB') if self.transform: image = self.transform(image) return image, torch.tensor(0)
def create_npz_from_sample_folder(sample_dir, num=50_000): """ Builds a single .npz file from a folder of .png samples. """ samples = [] for i in tqdm(range(num), desc="Building .npz file from samples"): sample_pil = Image.open(f"{sample_dir}/{i:06d}.png") sample_np = np.asarray(sample_pil).astype(np.uint8) samples.append(sample_np) random.shuffle(samples) # This is very important for IS(Inception Score) !!! samples = np.stack(samples) assert samples.shape == (num, samples.shape[1], samples.shape[2], 3) npz_path = f"{sample_dir}.npz" np.savez(npz_path, arr_0=samples) print(f"Saved .npz file to {npz_path} [shape={samples.shape}].") return npz_path
def center_crop_arr(pil_image, image_size): """ Center cropping implementation from ADM. https://github.com/openai/guided-diffusion/blob/8fb3ad9197f16bbc40620447b2742e13458d2831/guided_diffusion/image_datasets.py#L126 """ while min(*pil_image.size) >= 2 * image_size: pil_image = pil_image.resize( tuple(x // 2 for x in pil_image.size), resample=Image.BOX )
scale = image_size / min(*pil_image.size) pil_image = pil_image.resize( tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC )
arr = np.array(pil_image) crop_y = (arr.shape[0] - image_size) // 2 crop_x = (arr.shape[1] - image_size) // 2 return Image.fromarray(arr[crop_y: crop_y + image_size, crop_x: crop_x + image_size])
def main(args): # Setup PyTorch: assert torch.cuda.is_available(), "Sampling with DDP requires at least one GPU. sample.py supports CPU-only usage" torch.set_grad_enabled(False)
# Setup DDP: dist.init_process_group("nccl") rank = dist.get_rank() device = rank % torch.cuda.device_count() seed = args.global_seed * dist.get_world_size() + rank torch.manual_seed(seed) torch.cuda.set_device(device) print(f"Starting rank={rank}, seed={seed}, world_size={dist.get_world_size()}.")
# load vae vae = AutoencoderKL.from_pretrained(f"stabilityai/{args.vae}").to(device)
# Create folder to save samples: folder_name = f"stabilityai-{args.vae}-{args.dataset}-size-{args.image_size}-seed-{args.global_seed}" sample_folder_dir = f"{args.sample_dir}/{folder_name}" if rank == 0: os.makedirs(sample_folder_dir, exist_ok=True) print(f"Saving .png samples at {sample_folder_dir}") dist.barrier()
# Setup data: transform = transforms.Compose([ transforms.Lambda(lambda pil_image: center_crop_arr(pil_image, args.image_size)), transforms.ToTensor(), transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True) ]) if args.dataset == 'imagenet': dataset = ImageFolder(args.data_path, transform=transform) num_fid_samples = 50000 elif args.dataset == 'coco': dataset = SingleFolderDataset(args.data_path, transform=transform) num_fid_samples = 5000 else: raise Exception("please check dataset") sampler = DistributedSampler( dataset, num_replicas=dist.get_world_size(), rank=rank, shuffle=False, seed=args.global_seed ) loader = DataLoader( dataset, batch_size=args.per_proc_batch_size, shuffle=False, sampler=sampler, num_workers=args.num_workers, pin_memory=True, drop_last=False )
# Figure out how many samples we need to generate on each GPU and how many iterations we need to run: n = args.per_proc_batch_size global_batch_size = n * dist.get_world_size() psnr_val_rgb = [] ssim_val_rgb = [] loader = tqdm(loader) if rank == 0 else loader total = 0 for x, _ in loader: rgb_gts = x rgb_gts = (rgb_gts.permute(0, 2, 3, 1).to("cpu").numpy() + 1.0) / 2.0 # rgb_gt value is between [0, 1] x = x.to(device) with torch.no_grad(): # Map input images to latent space + normalize latents: latent = vae.encode(x).latent_dist.sample().mul_(0.18215) # reconstruct: samples = vae.decode(latent / 0.18215).sample # output value is between [-1, 1] samples = torch.clamp(127.5 * samples + 128.0, 0, 255).permute(0, 2, 3, 1).to("cpu", dtype=torch.uint8).numpy() # Save samples to disk as individual .png files for i, (sample, rgb_gt) in enumerate(zip(samples, rgb_gts)): index = i * dist.get_world_size() + rank + total Image.fromarray(sample).save(f"{sample_folder_dir}/{index:06d}.png") # metric rgb_restored = sample.astype(np.float32) / 255. # rgb_restored value is between [0, 1] psnr = psnr_loss(rgb_restored, rgb_gt) ssim = ssim_loss(rgb_restored, rgb_gt, multichannel=True, data_range=2.0, channel_axis=-1) psnr_val_rgb.append(psnr) ssim_val_rgb.append(ssim) total += global_batch_size
# ------------------------------------ # Summary # ------------------------------------ # Make sure all processes have finished saving their samples dist.barrier() world_size = dist.get_world_size() gather_psnr_val = [None for _ in range(world_size)] gather_ssim_val = [None for _ in range(world_size)] dist.all_gather_object(gather_psnr_val, psnr_val_rgb) dist.all_gather_object(gather_ssim_val, ssim_val_rgb)
if rank == 0: gather_psnr_val = list(itertools.chain(*gather_psnr_val)) gather_ssim_val = list(itertools.chain(*gather_ssim_val)) psnr_val_rgb = sum(gather_psnr_val) / len(gather_psnr_val) ssim_val_rgb = sum(gather_ssim_val) / len(gather_ssim_val) print("PSNR: %f, SSIM: %f " % (psnr_val_rgb, ssim_val_rgb))
result_file = f"{sample_folder_dir}_results.txt" print("writing results to {}".format(result_file)) with open(result_file, 'w') as f: print("PSNR: %f, SSIM: %f " % (psnr_val_rgb, ssim_val_rgb), file=f)
create_npz_from_sample_folder(sample_folder_dir, num_fid_samples) print("Done.") dist.barrier() dist.destroy_process_group()
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--data-path", type=str, required=True) parser.add_argument("--dataset", type=str, choices=['imagenet', 'coco'], default='imagenet') parser.add_argument("--vae", type=str, choices=["sdxl-vae", "sd-vae-ft-mse"], default="sd-vae-ft-mse") parser.add_argument("--image-size", type=int, choices=[256, 512], default=256) parser.add_argument("--sample-dir", type=str, default="reconstructions") parser.add_argument("--per-proc-batch-size", type=int, default=32) parser.add_argument("--global-seed", type=int, default=0) parser.add_argument("--num-workers", type=int, default=4) args = parser.parse_args() main(args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import argparseimport torchimport torch.nn.functional as Fimport numpy as npfrom PIL import Imagefrom diffusers.models import AutoencoderKL
def main(args): # Setup PyTorch: torch.manual_seed(args.seed) torch.set_grad_enabled(False) device = "cuda" if torch.cuda.is_available() else "cpu"
# create and load model vae = AutoencoderKL.from_pretrained(f"stabilityai/{args.vae}").to(device)
# load image img_path = args.image_path out_path = args.image_path.replace('.jpg', '_vae.jpg').replace('.jpeg', '_vae.jpeg').replace('.png', '_vae.png') input_size = args.image_size img = Image.open(img_path).convert("RGB")
# preprocess size_org = img.size img = img.resize((input_size, input_size)) img = np.array(img) / 255. x = 2.0 * img - 1.0 # x value is between [-1, 1] x = torch.tensor(x) x = x.unsqueeze(dim=0) x = torch.einsum('nhwc->nchw', x) x_input = x.float().to("cuda")
# inference with torch.no_grad(): # Map input images to latent space + normalize latents: latent = vae.encode(x_input).latent_dist.sample().mul_(0.18215) # reconstruct: output = vae.decode(latent / 0.18215).sample # output value is between [-1, 1]
# postprocess output = F.interpolate(output, size=[size_org[1], size_org[0]], mode='bilinear').permute(0, 2, 3, 1)[0] sample = torch.clamp(127.5 * output + 128.0, 0, 255).to("cpu", dtype=torch.uint8).numpy()
# save Image.fromarray(sample).save(out_path) print("Reconstructed image is saved to {}".format(out_path))
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--image-path", type=str, default="assets/example.jpg") parser.add_argument("--vae", type=str, choices=["sdxl-vae", "sd-vae-ft-mse"], default="sd-vae-ft-mse") parser.add_argument("--image-size", type=int, choices=[256, 512, 1024], default=512) parser.add_argument("--seed", type=int, default=0) args = parser.parse_args() main(args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165import torchtorch.backends.cuda.matmul.allow_tf32 = Truetorch.backends.cudnn.allow_tf32 = Trueimport torch.distributed as distfrom torch.utils.data import Dataset, DataLoaderfrom torch.utils.data.distributed import DistributedSamplerfrom torchvision.datasets import ImageFolderfrom torchvision import transformsfrom tqdm import tqdmimport osfrom PIL import Imageimport numpy as npimport argparseimport random
class SingleFolderDataset(Dataset): def __init__(self, directory, transform=None): super().__init__() self.directory = directory self.transform = transform self.image_paths = [os.path.join(directory, file_name) for file_name in os.listdir(directory) if os.path.isfile(os.path.join(directory, file_name))]
def __len__(self): return len(self.image_paths)
def __getitem__(self, idx): image_path = self.image_paths[idx] image = Image.open(image_path).convert('RGB') if self.transform: image = self.transform(image) return image, torch.tensor(0)
def create_npz_from_sample_folder(sample_dir, num=50_000): """ Builds a single .npz file from a folder of .png samples. """ samples = [] for i in tqdm(range(num), desc="Building .npz file from samples"): sample_pil = Image.open(f"{sample_dir}/{i:06d}.png") sample_np = np.asarray(sample_pil).astype(np.uint8) samples.append(sample_np)
random.shuffle(samples) # This is very important for IS(Inception Score) !!! samples = np.stack(samples) assert samples.shape == (num, samples.shape[1], samples.shape[2], 3) npz_path = f"{sample_dir}.npz" np.savez(npz_path, arr_0=samples) print(f"Saved .npz file to {npz_path} [shape={samples.shape}].") return npz_path
def center_crop_arr(pil_image, image_size): """ Center cropping implementation from ADM. https://github.com/openai/guided-diffusion/blob/8fb3ad9197f16bbc40620447b2742e13458d2831/guided_diffusion/image_datasets.py#L126 """ while min(*pil_image.size) >= 2 * image_size: pil_image = pil_image.resize( tuple(x // 2 for x in pil_image.size), resample=Image.BOX )
scale = image_size / min(*pil_image.size) pil_image = pil_image.resize( tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC )
arr = np.array(pil_image) crop_y = (arr.shape[0] - image_size) // 2 crop_x = (arr.shape[1] - image_size) // 2 return Image.fromarray(arr[crop_y: crop_y + image_size, crop_x: crop_x + image_size])
def main(args): # Setup PyTorch: assert torch.cuda.is_available(), "Sampling with DDP requires at least one GPU. sample.py supports CPU-only usage" torch.set_grad_enabled(False)
# Setup env dist.init_process_group("nccl") rank = dist.get_rank() device = rank % torch.cuda.device_count() seed = args.global_seed * dist.get_world_size() + rank torch.manual_seed(seed) torch.cuda.set_device(device) print(f"Starting rank={rank}, seed={seed}, world_size={dist.get_world_size()}.")
# Create folder to save samples: folder_name = f"val_{args.dataset}" sample_folder_dir = f"{args.sample_dir}/{folder_name}" if rank == 0: os.makedirs(sample_folder_dir, exist_ok=True) print(f"Saving .png samples at {sample_folder_dir}") dist.barrier()
# Setup data: transform = transforms.Compose([ transforms.Lambda(lambda pil_image: center_crop_arr(pil_image, args.image_size)), transforms.ToTensor(), transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True) ])
if args.dataset == 'imagenet': dataset = ImageFolder(args.data_path, transform=transform) num_fid_samples = 50000 elif args.dataset == 'coco': dataset = SingleFolderDataset(args.data_path, transform=transform) num_fid_samples = 5000 else: raise Exception("please check dataset") sampler = DistributedSampler( dataset, num_replicas=dist.get_world_size(), rank=rank, shuffle=False, seed=args.global_seed ) loader = DataLoader( dataset, batch_size=args.per_proc_batch_size, shuffle=False, sampler=sampler, num_workers=args.num_workers, pin_memory=True, drop_last=False )
# Figure out how many samples we need to generate on each GPU and how many iterations we need to run: n = args.per_proc_batch_size global_batch_size = n * dist.get_world_size()
loader = tqdm(loader) if rank == 0 else loader total = 0 for x, _ in loader: samples = torch.clamp(127.5 * x + 128.0, 0, 255).permute(0, 2, 3, 1).to("cpu", dtype=torch.uint8).numpy() # Save samples to disk as individual .png files for i, sample in enumerate(samples): index = i * dist.get_world_size() + rank + total Image.fromarray(sample).save(f"{sample_folder_dir}/{index:06d}.png")
total += global_batch_size
# Make sure all processes have finished saving their samples before attempting to convert to .npz dist.barrier() if rank == 0: create_npz_from_sample_folder(sample_folder_dir, num_fid_samples) print("Done.") dist.barrier() dist.destroy_process_group()
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--data-path", type=str, required=True) parser.add_argument("--dataset", type=str, choices=['imagenet', 'coco'], default='imagenet') parser.add_argument("--image-size", type=int, choices=[256, 512], default=256) parser.add_argument("--sample-dir", type=str, default="reconstructions") parser.add_argument("--per-proc-batch-size", type=int, default=32) parser.add_argument("--global-seed", type=int, default=0) parser.add_argument("--num-workers", type=int, default=4) args = parser.parse_args() main(args)123456789101112131415161718192021## Pretrained VQVAE Models
### install```pip install omegaconfpip install einops```* download all needed models from https://github.com/CompVis/taming-transformers and put in pretrained_models/* pip install pytorch_lightning* python3 tools/convert_pytorch_lightning_to_torch.py* pip uninstall pytorch_lightning
### demo```cd ${THIS_REPO_ROOT}python3 tokenizer/vqgan/taming_vqgan_demo.py```
### acknowledgeCodes in this folder are modified from from https://github.com/CompVis/taming-transformers
1234567891011121314151617181920212223242526272829303132model: base_learning_rate: 4.5e-06 target: taming.models.vqgan.VQModel params: embed_dim: 256 n_embed: 1024 ddconfig: double_z: false z_channels: 256 resolution: 256 in_channels: 3 out_ch: 3 ch: 128 ch_mult: - 1 - 1 - 2 - 2 - 4 num_res_blocks: 2 attn_resolutions: - 16 dropout: 0.0 lossconfig: target: taming.modules.losses.vqperceptual.VQLPIPSWithDiscriminator params: disc_conditional: false disc_in_channels: 3 disc_start: 0 disc_weight: 0.8 codebook_weight: 1.0 sjdtree/data/prompts/T2I-CompBench_val.jsonAdded
sjdtree/data/prompts/captions_train2017_extracted.jsonAdded
sjdtree/data/prompts/captions_val2017.jsonAdded
sjdtree/data/prompts/captions_val2017_longest.jsonAdded
sjdtree/data/prompts/captions_val_2014.jsonAdded
sjdtree/data/prompts/combined_data.jsonAdded
sjdtree/data/prompts/preprocess.pyAdded+22
sjdtree/dataset_tools/dataset_templates.pyAdded+320
sjdtree/dataset_tools/multi_gpu_dataframe_split.pyAdded+93
sjdtree/dataset_tools/multi_gpu_infer_with_prompt.pyAdded+196
sjdtree/emu3/__init__.pyAdded
sjdtree/emu3/__pycache__/__init__.cpython-310.pycAdded
sjdtree/emu3/mllm/__init__.pyAdded+61
sjdtree/emu3/mllm/__pycache__/__init__.cpython-310.pycAdded
sjdtree/emu3/mllm/__pycache__/processing_emu3.cpython-310.pycAdded
sjdtree/emu3/mllm/__pycache__/utils_emu3.cpython-310.pycAdded
sjdtree/emu3/mllm/configuration_emu3.pyAdded+213
sjdtree/emu3/mllm/modeling_emu3.pyAdded+1343
sjdtree/emu3/mllm/processing_emu3.pyAdded+299
sjdtree/emu3/mllm/tokenization_emu3.pyAdded+294
sjdtree/emu3/mllm/utils_emu3.pyAdded+62
sjdtree/emu3/tokenizer/__init__.pyAdded+70
sjdtree/emu3/tokenizer/configuration_emu3visionvq.pyAdded+106
sjdtree/emu3/tokenizer/image_processing_emu3visionvq.pyAdded+442
sjdtree/emu3/tokenizer/modeling_emu3visionvq.pyAdded+822
sjdtree/llamagen/__init__.pyAdded
sjdtree/llamagen/language/README.mdAdded+14
sjdtree/llamagen/language/extract_t5_feature.pyAdded+129
sjdtree/llamagen/language/t5.pyAdded+205
sjdtree/llamagen/llamagen.pyAdded+504
sjdtree/llamagen/llamagen_solver.pyAdded+476
sjdtree/llamagen/tokenizer/consistencydecoder/README.mdAdded+14
sjdtree/llamagen/tokenizer/consistencydecoder/cd_demo.pyAdded+57
sjdtree/llamagen/tokenizer/consistencydecoder/reconstruction_cd_ddp.pyAdded+208
sjdtree/llamagen/tokenizer/tokenizer_image/discriminator.pyAdded+255
sjdtree/llamagen/tokenizer/tokenizer_image/discriminator_patchgan.pyAdded+152
sjdtree/llamagen/tokenizer/tokenizer_image/discriminator_stylegan.pyAdded+101
sjdtree/llamagen/tokenizer/tokenizer_image/lpips.pyAdded+164
sjdtree/llamagen/tokenizer/tokenizer_image/reconstruction_vq_ddp.pyAdded+197
sjdtree/llamagen/tokenizer/tokenizer_image/vq_demo.pyAdded+84
sjdtree/llamagen/tokenizer/tokenizer_image/vq_loss.pyAdded+168
sjdtree/llamagen/tokenizer/tokenizer_image/vq_model.pyAdded+424
sjdtree/llamagen/tokenizer/tokenizer_image/vq_model_hf.pyAdded+17
sjdtree/llamagen/tokenizer/tokenizer_image/vq_train.pyAdded+316
sjdtree/llamagen/tokenizer/vae/README.mdAdded+14
sjdtree/llamagen/tokenizer/vae/reconstruction_vae_ddp.pyAdded+210
sjdtree/llamagen/tokenizer/vae/sd_vae_demo.pyAdded+57
sjdtree/llamagen/tokenizer/validation/val_ddp.pyAdded+165
sjdtree/llamagen/tokenizer/vqgan/README.mdAdded+21
sjdtree/llamagen/tokenizer/vqgan/configs/vqgan_imagenet_f16_1024.yamlAdded+32