Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- sjdtree/data/prompts/T2I-CompBench_val.json +0 -0
- sjdtree/data/prompts/captions_train2017_extracted.json +0 -0
- sjdtree/data/prompts/captions_val2017.json +0 -0
- sjdtree/data/prompts/captions_val2017_longest.json +0 -0
- sjdtree/data/prompts/captions_val_2014.json +0 -0
- sjdtree/data/prompts/combined_data.json +0 -0
- sjdtree/data/prompts/preprocess.py +22 -0
- sjdtree/dataset_tools/dataset_templates.py +320 -0
- sjdtree/dataset_tools/multi_gpu_dataframe_split.py +93 -0
- sjdtree/dataset_tools/multi_gpu_infer_with_prompt.py +196 -0
- sjdtree/emu3/__init__.py +0 -0
- sjdtree/emu3/__pycache__/__init__.cpython-310.pyc +0 -0
- sjdtree/emu3/mllm/__init__.py +61 -0
- sjdtree/emu3/mllm/__pycache__/__init__.cpython-310.pyc +0 -0
- sjdtree/emu3/mllm/__pycache__/processing_emu3.cpython-310.pyc +0 -0
- sjdtree/emu3/mllm/__pycache__/utils_emu3.cpython-310.pyc +0 -0
- sjdtree/emu3/mllm/configuration_emu3.py +213 -0
- sjdtree/emu3/mllm/modeling_emu3.py +1343 -0
- sjdtree/emu3/mllm/processing_emu3.py +299 -0
- sjdtree/emu3/mllm/tokenization_emu3.py +294 -0
- sjdtree/emu3/mllm/utils_emu3.py +62 -0
- sjdtree/emu3/tokenizer/__init__.py +70 -0
- sjdtree/emu3/tokenizer/configuration_emu3visionvq.py +106 -0
- sjdtree/emu3/tokenizer/image_processing_emu3visionvq.py +442 -0
- sjdtree/emu3/tokenizer/modeling_emu3visionvq.py +822 -0
- sjdtree/llamagen/__init__.py +0 -0
- sjdtree/llamagen/language/README.md +14 -0
- sjdtree/llamagen/language/extract_t5_feature.py +129 -0
- sjdtree/llamagen/language/t5.py +205 -0
- sjdtree/llamagen/llamagen.py +504 -0
- sjdtree/llamagen/llamagen_solver.py +476 -0
- sjdtree/llamagen/tokenizer/consistencydecoder/README.md +14 -0
- sjdtree/llamagen/tokenizer/consistencydecoder/cd_demo.py +57 -0
- sjdtree/llamagen/tokenizer/consistencydecoder/reconstruction_cd_ddp.py +208 -0
- sjdtree/llamagen/tokenizer/tokenizer_image/discriminator.py +255 -0
- sjdtree/llamagen/tokenizer/tokenizer_image/discriminator_patchgan.py +152 -0
- sjdtree/llamagen/tokenizer/tokenizer_image/discriminator_stylegan.py +101 -0
- sjdtree/llamagen/tokenizer/tokenizer_image/lpips.py +164 -0
- sjdtree/llamagen/tokenizer/tokenizer_image/reconstruction_vq_ddp.py +197 -0
- sjdtree/llamagen/tokenizer/tokenizer_image/vq_demo.py +84 -0
- sjdtree/llamagen/tokenizer/tokenizer_image/vq_loss.py +168 -0
- sjdtree/llamagen/tokenizer/tokenizer_image/vq_model.py +424 -0
- sjdtree/llamagen/tokenizer/tokenizer_image/vq_model_hf.py +17 -0
- sjdtree/llamagen/tokenizer/tokenizer_image/vq_train.py +316 -0
- sjdtree/llamagen/tokenizer/vae/README.md +14 -0
- sjdtree/llamagen/tokenizer/vae/reconstruction_vae_ddp.py +210 -0
- sjdtree/llamagen/tokenizer/vae/sd_vae_demo.py +57 -0
- sjdtree/llamagen/tokenizer/validation/val_ddp.py +165 -0
- sjdtree/llamagen/tokenizer/vqgan/README.md +21 -0
- sjdtree/llamagen/tokenizer/vqgan/configs/vqgan_imagenet_f16_1024.yaml +32 -0
sjdtree/data/prompts/T2I-CompBench_val.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
sjdtree/data/prompts/captions_train2017_extracted.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
sjdtree/data/prompts/captions_val2017.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
sjdtree/data/prompts/captions_val2017_longest.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
sjdtree/data/prompts/captions_val_2014.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
sjdtree/data/prompts/combined_data.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
sjdtree/data/prompts/preprocess.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import csv
|
| 3 |
+
|
| 4 |
+
with open('captions_val2017.json', 'r') as f:
|
| 5 |
+
captions_data = json.load(f)
|
| 6 |
+
|
| 7 |
+
captions_by_image_id = {}
|
| 8 |
+
for item in captions_data['annotations']:
|
| 9 |
+
image_id = item['image_id']
|
| 10 |
+
if image_id not in captions_by_image_id:
|
| 11 |
+
captions_by_image_id[image_id] = item['caption']
|
| 12 |
+
else:
|
| 13 |
+
if len(captions_by_image_id[image_id]) < len(item['caption']):
|
| 14 |
+
captions_by_image_id[image_id] = item['caption']
|
| 15 |
+
else:
|
| 16 |
+
continue
|
| 17 |
+
|
| 18 |
+
captions = list(captions_by_image_id.values())
|
| 19 |
+
print(len(captions))
|
| 20 |
+
|
| 21 |
+
with open('captions_val2017_longest.json', 'w') as f_out:
|
| 22 |
+
json.dump(captions, f_out, indent=4)
|
sjdtree/dataset_tools/dataset_templates.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import random
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from torch.utils.data import Dataset
|
| 7 |
+
import torchvision.transforms as T
|
| 8 |
+
import torch
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
import einops
|
| 12 |
+
from PIL import Image
|
| 13 |
+
|
| 14 |
+
from .multi_gpu_dataframe_split import split_dataframe_for_gpu, split_dataframe_for_node, split_datalist_for_gpu
|
| 15 |
+
|
| 16 |
+
def center_crop(width, height, img):
|
| 17 |
+
resample = {'box': Image.BOX, 'lanczos': Image.LANCZOS}['lanczos']
|
| 18 |
+
crop = np.min(img.shape[:2])
|
| 19 |
+
img = img[(img.shape[0] - crop) // 2: (img.shape[0] + crop) // 2,
|
| 20 |
+
(img.shape[1] - crop) // 2: (img.shape[1] + crop) // 2]
|
| 21 |
+
try:
|
| 22 |
+
img = Image.fromarray(img, 'RGB')
|
| 23 |
+
except:
|
| 24 |
+
img = Image.fromarray(img)
|
| 25 |
+
img = img.resize((width, height), resample)
|
| 26 |
+
return np.array(img).astype(np.uint8)
|
| 27 |
+
|
| 28 |
+
class PartiPromptsMultiGPUBench(Dataset):
|
| 29 |
+
|
| 30 |
+
def __init__(
|
| 31 |
+
self,
|
| 32 |
+
annFile,
|
| 33 |
+
gpu_id,
|
| 34 |
+
gpu_ids,
|
| 35 |
+
node_id,
|
| 36 |
+
node_ids,
|
| 37 |
+
output_dir=None,
|
| 38 |
+
data_len=0,
|
| 39 |
+
):
|
| 40 |
+
csv_file = annFile
|
| 41 |
+
print(f"Loading PartiPrompts from {csv_file} for GPU {gpu_id}, Node {node_id}")
|
| 42 |
+
if data_len != 0:
|
| 43 |
+
self.df = pd.read_csv(csv_file, sep='\t', nrows=data_len)
|
| 44 |
+
else:
|
| 45 |
+
self.df = pd.read_csv(csv_file, sep='\t')
|
| 46 |
+
self.csv_file_base_name = os.path.basename(csv_file)
|
| 47 |
+
|
| 48 |
+
self.not_name_char = [
|
| 49 |
+
'\"', "'", "(", ")", ":", ";", ",", ".",
|
| 50 |
+
"!", "?", ">", "<", "[", "]", "{", "}",
|
| 51 |
+
"|", "\\", "/", "@", "#", "$", "%", "^",
|
| 52 |
+
"&", "*", "~", "`", "=", "+", "-", "_",
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
self.prompt_dict = self.check_all_prompts()
|
| 56 |
+
|
| 57 |
+
self.df = split_dataframe_for_gpu(self.df, gpu_id, gpu_ids, node_id, node_ids)
|
| 58 |
+
|
| 59 |
+
def __len__(self):
|
| 60 |
+
return len(self.df)
|
| 61 |
+
|
| 62 |
+
def __getitem__(self, idx):
|
| 63 |
+
prompt = self.df.iloc[idx]['Prompt']
|
| 64 |
+
# prompt = self.clean_prompt(prompt)
|
| 65 |
+
prompt_idx = self.prompt_dict[ prompt ]
|
| 66 |
+
|
| 67 |
+
return prompt, prompt_idx
|
| 68 |
+
|
| 69 |
+
def clean_prompt(self, prompt):
|
| 70 |
+
prompt = prompt.replace("\n", " ")
|
| 71 |
+
prompt = prompt.replace("\t", " ")
|
| 72 |
+
prompt = prompt.replace("\r", " ")
|
| 73 |
+
prompt = prompt.replace(" ", " ")
|
| 74 |
+
prompt = prompt.strip()
|
| 75 |
+
prompt = prompt.lower()
|
| 76 |
+
for char in self.not_name_char:
|
| 77 |
+
prompt = prompt.replace(char, " ")
|
| 78 |
+
return prompt
|
| 79 |
+
|
| 80 |
+
def check_all_prompts(self):
|
| 81 |
+
prompt_dict = dict()
|
| 82 |
+
max_len = 0
|
| 83 |
+
for idx in range(len(self.df)):
|
| 84 |
+
prompt = self.df.iloc[idx]['Prompt']
|
| 85 |
+
# prompt = self.clean_prompt(prompt)
|
| 86 |
+
prompt_dict[prompt] = idx
|
| 87 |
+
max_len = max(max_len, len(prompt))
|
| 88 |
+
|
| 89 |
+
print(f"Number of unique prompts: {len(prompt_dict)} | Max prompt length: {max_len}")
|
| 90 |
+
return prompt_dict
|
| 91 |
+
|
| 92 |
+
class PartiPromptsMultiGPUBenchCOCOFormat(PartiPromptsMultiGPUBench):
|
| 93 |
+
def __init__(self, *args, **kwargs):
|
| 94 |
+
super().__init__(*args, **kwargs)
|
| 95 |
+
self.anno = dict()
|
| 96 |
+
self.anno["annotations"] = []
|
| 97 |
+
for idx in range(len(self.df)):
|
| 98 |
+
self.anno["annotations"].append({
|
| 99 |
+
"id": idx,
|
| 100 |
+
"caption": self.df.iloc[idx]['Prompt'],
|
| 101 |
+
})
|
| 102 |
+
|
| 103 |
+
class MSCOCODatabase(Dataset):
|
| 104 |
+
def __init__(
|
| 105 |
+
self,
|
| 106 |
+
root='data/coco/val2017',
|
| 107 |
+
annFile='data/coco/annotations/captions_val2017.json',
|
| 108 |
+
size=None,
|
| 109 |
+
**kwargs,
|
| 110 |
+
):
|
| 111 |
+
from pycocotools.coco import COCO
|
| 112 |
+
self.root = root
|
| 113 |
+
self.height = self.width = size
|
| 114 |
+
self.coco = COCO(annFile)
|
| 115 |
+
self.keys = list(sorted(self.coco.imgs.keys()))
|
| 116 |
+
|
| 117 |
+
def _load_image(self, key: int):
|
| 118 |
+
path = self.coco.loadImgs(key)[0]["file_name"]
|
| 119 |
+
return Image.open(os.path.join(self.root, path)).convert("RGB")
|
| 120 |
+
|
| 121 |
+
def _load_target(self, key: int):
|
| 122 |
+
return self.coco.loadAnns(self.coco.getAnnIds(key))
|
| 123 |
+
|
| 124 |
+
def __len__(self):
|
| 125 |
+
return len(self.keys)
|
| 126 |
+
|
| 127 |
+
def __getitem__(self, index):
|
| 128 |
+
key = self.keys[index]
|
| 129 |
+
image = self._load_image(key)
|
| 130 |
+
image = np.array(image).astype(np.uint8)
|
| 131 |
+
image = center_crop(self.width, self.height, image).astype(np.float32)
|
| 132 |
+
image = (image / 127.5 - 1.0).astype(np.float32)
|
| 133 |
+
image = einops.rearrange(image, 'h w c -> c h w')
|
| 134 |
+
anns = self._load_target(key)
|
| 135 |
+
target = []
|
| 136 |
+
for ann in anns:
|
| 137 |
+
target.append(ann['caption'])
|
| 138 |
+
|
| 139 |
+
return image, target
|
| 140 |
+
|
| 141 |
+
class MSCOCOPromptBench(MSCOCODatabase):
|
| 142 |
+
def __init__(
|
| 143 |
+
self,
|
| 144 |
+
gpu_id,
|
| 145 |
+
gpu_ids,
|
| 146 |
+
node_id,
|
| 147 |
+
node_ids,
|
| 148 |
+
*args,
|
| 149 |
+
output_dir=None,
|
| 150 |
+
**kwargs,
|
| 151 |
+
):
|
| 152 |
+
super().__init__(*args, **kwargs)
|
| 153 |
+
self._init_coco_dataset_dict(gpu_id, gpu_ids, node_id, node_ids)
|
| 154 |
+
|
| 155 |
+
def _init_coco_dataset_dict(self, gpu_id, gpu_ids, node_id, node_ids):
|
| 156 |
+
keys = self.keys
|
| 157 |
+
|
| 158 |
+
max_relative_id = 0
|
| 159 |
+
max_prompt_len = 0
|
| 160 |
+
self.anno = dict()
|
| 161 |
+
self.anno["annotations"] = []
|
| 162 |
+
for key in keys:
|
| 163 |
+
target = []
|
| 164 |
+
ids = []
|
| 165 |
+
for i, ann in enumerate(self._load_target(key)):
|
| 166 |
+
if max_prompt_len < len(ann['caption']):
|
| 167 |
+
max_prompt_len = len(ann['caption'])
|
| 168 |
+
max_relative_id = i
|
| 169 |
+
|
| 170 |
+
target.append(ann['caption'])
|
| 171 |
+
ids.append(ann['id'])
|
| 172 |
+
|
| 173 |
+
prompt = target[max_relative_id]
|
| 174 |
+
prompt_idx = ids[max_relative_id]
|
| 175 |
+
|
| 176 |
+
self.anno["annotations"].append({
|
| 177 |
+
"id": prompt_idx,
|
| 178 |
+
"caption": prompt,
|
| 179 |
+
})
|
| 180 |
+
|
| 181 |
+
self.anno_dict_keys = list(range(len(self.anno["annotations"])))
|
| 182 |
+
|
| 183 |
+
self.anno_dict_keys = split_datalist_for_gpu(
|
| 184 |
+
self.anno_dict_keys, gpu_id, gpu_ids, node_id, node_ids
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
def __len__(self):
|
| 188 |
+
return len(self.anno_dict_keys)
|
| 189 |
+
|
| 190 |
+
def __getitem__(self, index):
|
| 191 |
+
key = self.anno_dict_keys[index]
|
| 192 |
+
|
| 193 |
+
prompt_dict = self.anno["annotations"][key]
|
| 194 |
+
prompt = prompt_dict["caption"]
|
| 195 |
+
prompt_idx = prompt_dict["id"]
|
| 196 |
+
|
| 197 |
+
return prompt, prompt_idx
|
| 198 |
+
|
| 199 |
+
class MSCOCODatabase_DIY(Dataset):
|
| 200 |
+
def __init__(
|
| 201 |
+
self,
|
| 202 |
+
root='data/coco/val2017',
|
| 203 |
+
annFile='data/coco/annotations/captions_val2017.json',
|
| 204 |
+
size=None,
|
| 205 |
+
**kwargs,
|
| 206 |
+
):
|
| 207 |
+
from pycocotools.coco import COCO
|
| 208 |
+
self.root = root
|
| 209 |
+
self.height = self.width = size
|
| 210 |
+
self.coco = COCO(annFile)
|
| 211 |
+
self.keys = self.coco.getImgIds() #list(sorted(self.coco.imgs.keys()))
|
| 212 |
+
|
| 213 |
+
def _load_image(self, key: int):# 获取图片文件名
|
| 214 |
+
path = self.coco.loadImgs(key)[0]["file_name"]
|
| 215 |
+
return Image.open(os.path.join(self.root, path)).convert("RGB")
|
| 216 |
+
|
| 217 |
+
def _load_target(self, key: int):
|
| 218 |
+
return self.coco.loadAnns(self.coco.getAnnIds(imgIds=key))
|
| 219 |
+
|
| 220 |
+
def __len__(self):
|
| 221 |
+
return len(self.keys)
|
| 222 |
+
|
| 223 |
+
def __getitem__(self, index):
|
| 224 |
+
key = self.keys[index]
|
| 225 |
+
image = self._load_image(key) # 获取图片文件名
|
| 226 |
+
image = np.array(image).astype(np.uint8)
|
| 227 |
+
image = center_crop(self.width, self.height, image).astype(np.float32)
|
| 228 |
+
image = (image / 127.5 - 1.0).astype(np.float32)
|
| 229 |
+
image = einops.rearrange(image, 'h w c -> c h w')
|
| 230 |
+
anns = self._load_target(key)
|
| 231 |
+
target = []
|
| 232 |
+
for ann in anns:
|
| 233 |
+
target.append(ann['caption'])
|
| 234 |
+
|
| 235 |
+
return image, target
|
| 236 |
+
|
| 237 |
+
class MSCOCOPromptBench_DIY(MSCOCODatabase_DIY):
|
| 238 |
+
def __init__(
|
| 239 |
+
self,
|
| 240 |
+
gpu_id,
|
| 241 |
+
gpu_ids,
|
| 242 |
+
node_id,
|
| 243 |
+
node_ids,
|
| 244 |
+
*args,
|
| 245 |
+
output_dir=None,
|
| 246 |
+
id_set=None,
|
| 247 |
+
**kwargs,
|
| 248 |
+
):
|
| 249 |
+
super().__init__(*args, **kwargs)
|
| 250 |
+
self.id_set = id_set
|
| 251 |
+
self._init_coco_dataset_dict(gpu_id, gpu_ids, node_id, node_ids)
|
| 252 |
+
|
| 253 |
+
def _init_coco_dataset_dict(self, gpu_id, gpu_ids, node_id, node_ids):
|
| 254 |
+
keys = self.keys
|
| 255 |
+
|
| 256 |
+
max_relative_id = 0
|
| 257 |
+
max_prompt_len = 0
|
| 258 |
+
self.anno = dict()
|
| 259 |
+
self.anno["annotations"] = []
|
| 260 |
+
for key in keys:#key这里的key是一组的key, 一对多
|
| 261 |
+
for i, ann in enumerate(self._load_target(key)): # 可能有多个caption
|
| 262 |
+
if max_relative_id >= i:
|
| 263 |
+
image_id = ann['image_id']
|
| 264 |
+
img_info = self.coco.loadImgs(image_id)[0]# 加载图片信息
|
| 265 |
+
|
| 266 |
+
self.anno["annotations"].append({
|
| 267 |
+
"id": ann['id'],
|
| 268 |
+
"caption": ann['caption'],
|
| 269 |
+
"img_name": img_info['file_name'],
|
| 270 |
+
})
|
| 271 |
+
self.anno_dict_keys = list(range(len(self.anno["annotations"])))
|
| 272 |
+
|
| 273 |
+
self.anno_dict_keys = split_datalist_for_gpu(
|
| 274 |
+
self.anno_dict_keys, gpu_id, gpu_ids, node_id, node_ids
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
def __len__(self):
|
| 278 |
+
return len(self.anno_dict_keys)
|
| 279 |
+
|
| 280 |
+
def __getitem__(self, index):
|
| 281 |
+
key = self.anno_dict_keys[index]
|
| 282 |
+
|
| 283 |
+
prompt_dict = self.anno["annotations"][key]
|
| 284 |
+
prompt = prompt_dict["caption"]
|
| 285 |
+
prompt_idx = prompt_dict["id"]
|
| 286 |
+
# img_name = prompt_dict["img_name"]
|
| 287 |
+
|
| 288 |
+
return prompt, prompt_idx
|
| 289 |
+
|
| 290 |
+
def create_dataset(
|
| 291 |
+
name,
|
| 292 |
+
ds_type='eval',
|
| 293 |
+
**kwargs,
|
| 294 |
+
):
|
| 295 |
+
# train/test split datasets
|
| 296 |
+
if ds_type == 'eval':
|
| 297 |
+
if name == "coco":
|
| 298 |
+
# ds = MSCOCOPromptBench(**kwargs)
|
| 299 |
+
ds = MSCOCOPromptBench_DIY(**kwargs)
|
| 300 |
+
return ds
|
| 301 |
+
elif name == "parti_cocoformat":
|
| 302 |
+
return PartiPromptsMultiGPUBenchCOCOFormat(**kwargs)
|
| 303 |
+
elif name == "parti":
|
| 304 |
+
return PartiPromptsMultiGPUBench(**kwargs)
|
| 305 |
+
else:
|
| 306 |
+
raise NotImplementedError
|
| 307 |
+
else:
|
| 308 |
+
if name == "coco":
|
| 309 |
+
ds = MSCOCODatabase(**kwargs)
|
| 310 |
+
return ds
|
| 311 |
+
else:
|
| 312 |
+
raise NotImplementedError
|
| 313 |
+
|
| 314 |
+
if __name__ == "__main__":
|
| 315 |
+
ds = create_dataset(
|
| 316 |
+
name="mscoco",
|
| 317 |
+
root='data/coco/train2017',
|
| 318 |
+
annFile='data/coco/annotations/captions_val2017.json',
|
| 319 |
+
)
|
| 320 |
+
print(len(ds.anno["annotations"]))
|
sjdtree/dataset_tools/multi_gpu_dataframe_split.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import random
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from torch.utils.data import Dataset
|
| 7 |
+
import torchvision.transforms as T
|
| 8 |
+
import torch
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
def split_datalist_for_gpu(df, gpu_id, gpu_ids, node_id, node_ids):
|
| 12 |
+
node_index = node_ids.index(node_id) # Position of the current node in the node list
|
| 13 |
+
gpu_index = gpu_ids.index(gpu_id) # Position of the current GPU in the GPU list
|
| 14 |
+
|
| 15 |
+
# first split the dataframe for different nodes
|
| 16 |
+
total_nodes = len(node_ids)
|
| 17 |
+
rows_per_split = len(df) // total_nodes
|
| 18 |
+
start_index = node_index * rows_per_split
|
| 19 |
+
end_index = start_index + rows_per_split if node_index < total_nodes - 1 else len(df)
|
| 20 |
+
|
| 21 |
+
df = df[start_index:end_index]
|
| 22 |
+
|
| 23 |
+
# then split the dataframe for different gpus
|
| 24 |
+
total_gpus = len(gpu_ids)
|
| 25 |
+
rows_per_split = len(df) // total_gpus
|
| 26 |
+
start_index = gpu_index * rows_per_split
|
| 27 |
+
end_index = start_index + rows_per_split if gpu_index < total_gpus - 1 else len(df)
|
| 28 |
+
|
| 29 |
+
return df[start_index:end_index]
|
| 30 |
+
|
| 31 |
+
def split_dataframe_for_gpu(df, gpu_id, gpu_ids, node_id, node_ids):
|
| 32 |
+
"""
|
| 33 |
+
Splits the dataframe for a specific GPU on a specific node, supporting arbitrary GPU and node identifiers.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
df (pd.DataFrame): The dataframe to split.
|
| 37 |
+
gpu_id (int): The identifier of the GPU for which the split is intended.
|
| 38 |
+
gpu_ids (list): List of all GPU IDs across all nodes, which can be non-sequential.
|
| 39 |
+
node_id (int): The identifier of the node on which the GPU is located.
|
| 40 |
+
node_ids (list): List of all node IDs, which can be non-sequential.
|
| 41 |
+
|
| 42 |
+
Returns:
|
| 43 |
+
pd.DataFrame: A subset of the original dataframe intended for the specific GPU on a specific node.
|
| 44 |
+
"""
|
| 45 |
+
# Calculate the unique index for this GPU on this node by finding its position in the global list of GPUs
|
| 46 |
+
node_index = node_ids.index(node_id) # Position of the current node in the node list
|
| 47 |
+
gpu_index = gpu_ids.index(gpu_id) # Position of the current GPU in the GPU list
|
| 48 |
+
|
| 49 |
+
# first split the dataframe for different nodes
|
| 50 |
+
total_nodes = len(node_ids)
|
| 51 |
+
rows_per_split = len(df) // total_nodes
|
| 52 |
+
start_index = node_index * rows_per_split
|
| 53 |
+
end_index = start_index + rows_per_split if node_index < total_nodes - 1 else len(df)
|
| 54 |
+
|
| 55 |
+
df = df.iloc[start_index:end_index]
|
| 56 |
+
|
| 57 |
+
# then split the dataframe for different gpus
|
| 58 |
+
total_gpus = len(gpu_ids)
|
| 59 |
+
rows_per_split = len(df) // total_gpus
|
| 60 |
+
start_index = gpu_index * rows_per_split
|
| 61 |
+
end_index = start_index + rows_per_split if gpu_index < total_gpus - 1 else len(df)
|
| 62 |
+
|
| 63 |
+
return df.iloc[start_index:end_index]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def split_dataframe_for_node(df, node_id, node_ids):
|
| 67 |
+
"""
|
| 68 |
+
Splits the dataframe for a specific node, supporting arbitrary node identifiers.
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
df (pd.DataFrame): The dataframe to split.
|
| 72 |
+
node_id (int): The identifier of the node
|
| 73 |
+
node_ids (list): List of all node IDs, which can be non-sequential.
|
| 74 |
+
|
| 75 |
+
Returns:
|
| 76 |
+
pd.DataFrame: A subset of the original dataframe intended for the specific node.
|
| 77 |
+
"""
|
| 78 |
+
# Calculate the unique index for this GPU on this node by finding its position in the global list of GPUs
|
| 79 |
+
node_index = node_ids.index(node_id) # Position of the current node in the node list
|
| 80 |
+
global_index = node_index # Unique index across all GPUs on all nodes
|
| 81 |
+
|
| 82 |
+
# Calculate the total number of splits needed
|
| 83 |
+
total_nodes = len(node_ids)
|
| 84 |
+
|
| 85 |
+
# Calculate the number of rows per split
|
| 86 |
+
rows_per_split = len(df) // total_nodes
|
| 87 |
+
|
| 88 |
+
# Calculate the start and end indices of the rows for this particular split
|
| 89 |
+
start_index = global_index * rows_per_split
|
| 90 |
+
end_index = start_index + rows_per_split if global_index < total_nodes - 1 else len(df)
|
| 91 |
+
|
| 92 |
+
# Get the subset of the dataframe
|
| 93 |
+
return df.iloc[start_index:end_index]
|
sjdtree/dataset_tools/multi_gpu_infer_with_prompt.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import math
|
| 3 |
+
from argparse import ArgumentParser
|
| 4 |
+
import time
|
| 5 |
+
import multiprocessing
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
from torch.utils.data import DataLoader
|
| 10 |
+
import torch
|
| 11 |
+
from PIL import Image
|
| 12 |
+
import pandas as pd
|
| 13 |
+
from tqdm import tqdm
|
| 14 |
+
|
| 15 |
+
from typing import List, Optional, Union, Dict
|
| 16 |
+
from copy import copy
|
| 17 |
+
|
| 18 |
+
from utils import set_logger
|
| 19 |
+
|
| 20 |
+
import json
|
| 21 |
+
class PromptWrapper:
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
eval_data: DataLoader,
|
| 25 |
+
gpu_id,
|
| 26 |
+
node_id,
|
| 27 |
+
model_name = "Alpha-VLLM/Lumina-mGPT-7B-768",
|
| 28 |
+
output_dir = "./workdir",
|
| 29 |
+
seed = None,
|
| 30 |
+
return_accl = False
|
| 31 |
+
) -> None:
|
| 32 |
+
|
| 33 |
+
self.gpu_id = gpu_id
|
| 34 |
+
self.node_id = node_id
|
| 35 |
+
self.device = torch.device(f"cuda:{self.gpu_id}")
|
| 36 |
+
print(f"GPU {self.gpu_id} is initialized")
|
| 37 |
+
self.eval_data = eval_data
|
| 38 |
+
|
| 39 |
+
self.seed = seed
|
| 40 |
+
# self.max_num_new_tokens = max_num_new_tokens
|
| 41 |
+
self.model_name = model_name.split("/")[-1]
|
| 42 |
+
|
| 43 |
+
self.output_dir = output_dir
|
| 44 |
+
if not os.path.exists(self.output_dir):
|
| 45 |
+
os.makedirs(self.output_dir)
|
| 46 |
+
self.return_accl = return_accl
|
| 47 |
+
|
| 48 |
+
def run(self, sample_fn):
|
| 49 |
+
json_file_name = f"out_put_json_{self.gpu_id}_{self.node_id}.json"
|
| 50 |
+
json_file_path = self.output_dir + "/" + json_file_name
|
| 51 |
+
global_statistics = {}
|
| 52 |
+
for i, data_item in enumerate(tqdm(
|
| 53 |
+
self.eval_data, desc=f"Generating captions on GPU {self.gpu_id}, Node {self.node_id}"
|
| 54 |
+
)):
|
| 55 |
+
prompt, prompt_idx = data_item
|
| 56 |
+
|
| 57 |
+
prompt = prompt[0]
|
| 58 |
+
prompt_idx = prompt_idx[0].item()
|
| 59 |
+
|
| 60 |
+
output_file_name = str(prompt_idx) + ".png"
|
| 61 |
+
output_file_path = self.output_dir + "/" + output_file_name
|
| 62 |
+
if not os.path.exists(output_file_path):
|
| 63 |
+
if not self.return_accl:
|
| 64 |
+
result_image = sample_fn(prompt)
|
| 65 |
+
else:
|
| 66 |
+
result_image, result = sample_fn(prompt)
|
| 67 |
+
# Result(input_ids=input_ids, loop_num=gen_loop_num, token_gen_len = cur_len - init_len,time_forward=t)
|
| 68 |
+
token_gen_len = result.token_gen_len
|
| 69 |
+
loop_num = result.loop_num
|
| 70 |
+
acceptance_length = token_gen_len / loop_num
|
| 71 |
+
statistics = {
|
| 72 |
+
"prompt": prompt,
|
| 73 |
+
"time": result.time_forward,
|
| 74 |
+
"acceptance_length": acceptance_length,
|
| 75 |
+
"loop_num": loop_num,
|
| 76 |
+
}
|
| 77 |
+
global_statistics[f"prompt_{i}"] = statistics
|
| 78 |
+
if isinstance(result_image, torch.Tensor):
|
| 79 |
+
output_file_path = output_file_path.replace(".png", ".pt")
|
| 80 |
+
torch.save(result_image, output_file_path)
|
| 81 |
+
elif isinstance(result_image, Image.Image):
|
| 82 |
+
result_image.save(output_file_path, format="PNG")
|
| 83 |
+
else:
|
| 84 |
+
raise ValueError(f"Invalid image type: {type(result_image)}")
|
| 85 |
+
|
| 86 |
+
with open(f"{json_file_path}", "w") as f:
|
| 87 |
+
json.dump(global_statistics, f, indent=4)
|
| 88 |
+
|
| 89 |
+
from .dataset_templates import create_dataset
|
| 90 |
+
from model_wrappers.model_loader import load_pretrained_model, get_forward_func
|
| 91 |
+
def run_caption_gen(
|
| 92 |
+
gpu_id,
|
| 93 |
+
node_id,
|
| 94 |
+
gpu_ids,
|
| 95 |
+
node_ids,
|
| 96 |
+
dataset_params = dict(
|
| 97 |
+
name = 'parti',
|
| 98 |
+
annFile = './data/PartiPrompts.tsv',
|
| 99 |
+
),
|
| 100 |
+
seed = None,
|
| 101 |
+
model_name = "Alpha-VLLM/Lumina-mGPT-7B-768",
|
| 102 |
+
output_dir = "./workdir",
|
| 103 |
+
**kwargs,
|
| 104 |
+
):
|
| 105 |
+
return_accl = kwargs.get("return_accl",False)
|
| 106 |
+
dataset = create_dataset(
|
| 107 |
+
gpu_id=gpu_id,
|
| 108 |
+
gpu_ids=gpu_ids,
|
| 109 |
+
node_id=node_id,
|
| 110 |
+
node_ids=node_ids,
|
| 111 |
+
output_dir=output_dir,
|
| 112 |
+
**dataset_params,
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
dataloader = DataLoader(
|
| 116 |
+
dataset,
|
| 117 |
+
batch_size=1,
|
| 118 |
+
shuffle=False,
|
| 119 |
+
pin_memory=True,
|
| 120 |
+
num_workers=12,
|
| 121 |
+
)
|
| 122 |
+
device = torch.device(f"cuda:{gpu_id}")
|
| 123 |
+
print(f"device {device}, GPU {gpu_id} is initialized, running on Node {node_id}.")
|
| 124 |
+
|
| 125 |
+
model = load_pretrained_model(
|
| 126 |
+
model_name,
|
| 127 |
+
device = device,
|
| 128 |
+
seed = seed,
|
| 129 |
+
**kwargs,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
forward_func = get_forward_func(
|
| 133 |
+
model_name,
|
| 134 |
+
model,
|
| 135 |
+
**kwargs,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
prompt_gen = PromptWrapper(
|
| 139 |
+
eval_data=dataloader,
|
| 140 |
+
gpu_id=gpu_id,
|
| 141 |
+
node_id=node_id,
|
| 142 |
+
seed = seed,
|
| 143 |
+
model_name = model_name,
|
| 144 |
+
output_dir = output_dir,
|
| 145 |
+
return_accl = return_accl
|
| 146 |
+
)
|
| 147 |
+
set_logger(log_level='info', fname=os.path.join(output_dir, 'gen_img_output.log'))
|
| 148 |
+
with torch.no_grad():
|
| 149 |
+
prompt_gen.run(forward_func)
|
| 150 |
+
|
| 151 |
+
def _run_on_gpu(
|
| 152 |
+
gpu_id,
|
| 153 |
+
gpu_ids,
|
| 154 |
+
node_id,
|
| 155 |
+
node_ids,
|
| 156 |
+
kwargs):
|
| 157 |
+
"""
|
| 158 |
+
Function that calls run caption gen with the specified arguments.
|
| 159 |
+
"""
|
| 160 |
+
# Set the GPU ID for the process if needed (optional)
|
| 161 |
+
# os.environ['CUDA_VISIBLE_DEVICES'] = str(gpu_id)
|
| 162 |
+
run_caption_gen(
|
| 163 |
+
gpu_id=gpu_id,
|
| 164 |
+
node_id=node_id,
|
| 165 |
+
gpu_ids=gpu_ids,
|
| 166 |
+
node_ids=node_ids,
|
| 167 |
+
**kwargs)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _run_on_multiple_gpus(
|
| 171 |
+
gpu_ids,
|
| 172 |
+
node_ids,
|
| 173 |
+
node_id,
|
| 174 |
+
**kwargs):
|
| 175 |
+
"""
|
| 176 |
+
Launches run caption gen on multiple GPUs without using multiprocessing.Pool,
|
| 177 |
+
ensuring subprocesses are not daemonic and can have their CUDA context.
|
| 178 |
+
|
| 179 |
+
Args:
|
| 180 |
+
- num_gpus (int): Number of GPUs to use.
|
| 181 |
+
- **kwargs: Arguments for the run caption gen function, excluding gpu_id.
|
| 182 |
+
"""
|
| 183 |
+
to_iterate = gpu_ids
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
processes = []
|
| 187 |
+
for gpu_id in to_iterate:
|
| 188 |
+
# Prepare the arguments for each GPU
|
| 189 |
+
p = multiprocessing.Process(target=_run_on_gpu,
|
| 190 |
+
args=(gpu_id, gpu_ids, node_id, node_ids, kwargs),
|
| 191 |
+
daemon=False)
|
| 192 |
+
p.start()
|
| 193 |
+
processes.append(p)
|
| 194 |
+
|
| 195 |
+
for p in processes:
|
| 196 |
+
p.join() # Wait for all processes to complete
|
sjdtree/emu3/__init__.py
ADDED
|
File without changes
|
sjdtree/emu3/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (149 Bytes). View file
|
|
|
sjdtree/emu3/mllm/__init__.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 BAAI and the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from transformers.utils import (
|
| 17 |
+
OptionalDependencyNotAvailable,
|
| 18 |
+
_LazyModule,
|
| 19 |
+
is_torch_available,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
_import_structure = {
|
| 24 |
+
"configuration_emu3": ["Emu3Config"],
|
| 25 |
+
"tokenization_emu3": ["Emu3Tokenizer"],
|
| 26 |
+
"processing_emu3": ["Emu3Processor"],
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
if not is_torch_available():
|
| 31 |
+
raise OptionalDependencyNotAvailable()
|
| 32 |
+
except OptionalDependencyNotAvailable:
|
| 33 |
+
pass
|
| 34 |
+
else:
|
| 35 |
+
_import_structure["modeling_emu3"] = [
|
| 36 |
+
"Emu3Model",
|
| 37 |
+
"Emu3PretrainedModel",
|
| 38 |
+
"Emu3ForCausalLM",
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
if TYPE_CHECKING:
|
| 42 |
+
from .configuration_emu3 import Emu3Config
|
| 43 |
+
from .tokenization_emu3 import Emu3Tokenizer
|
| 44 |
+
from .processing_emu3 import Emu3Processor
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
if not is_torch_available():
|
| 48 |
+
raise OptionalDependencyNotAvailable()
|
| 49 |
+
except OptionalDependencyNotAvailable:
|
| 50 |
+
pass
|
| 51 |
+
else:
|
| 52 |
+
from .modeling_emu3 import (
|
| 53 |
+
Emu3Model,
|
| 54 |
+
Emu3PretrainedModel,
|
| 55 |
+
Emu3ForCausalLM,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
else:
|
| 59 |
+
import sys
|
| 60 |
+
|
| 61 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure)
|
sjdtree/emu3/mllm/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (878 Bytes). View file
|
|
|
sjdtree/emu3/mllm/__pycache__/processing_emu3.cpython-310.pyc
ADDED
|
Binary file (10.5 kB). View file
|
|
|
sjdtree/emu3/mllm/__pycache__/utils_emu3.cpython-310.pyc
ADDED
|
Binary file (1.32 kB). View file
|
|
|
sjdtree/emu3/mllm/configuration_emu3.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The Emu team, BAAI and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 5 |
+
# and OPT implementations in this library. It has been modified from its
|
| 6 |
+
# original forms to accommodate minor architectural differences compared
|
| 7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
""" Emu3 model configuration"""
|
| 21 |
+
|
| 22 |
+
from typing import Optional
|
| 23 |
+
|
| 24 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 25 |
+
from transformers.utils import logging
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
EMU3_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Emu3Config(PretrainedConfig):
|
| 34 |
+
r"""
|
| 35 |
+
This is the configuration class to store the configuration of a [`Emu3Model`]. It is used to instantiate an Emu3
|
| 36 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 37 |
+
defaults will yield a similar configuration to that of the Emu3-8B.
|
| 38 |
+
|
| 39 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 40 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
vocab_size (`int`, *optional*, defaults to 184622):
|
| 45 |
+
Vocabulary size of the Emu3 model. Defines the number of different tokens that can be represented by the
|
| 46 |
+
`inputs_ids` passed when calling [`Emu3Model`]
|
| 47 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
| 48 |
+
Dimension of the hidden representations.
|
| 49 |
+
intermediate_size (`int`, *optional*, defaults to 14336):
|
| 50 |
+
Dimension of the MLP representations.
|
| 51 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
| 52 |
+
Number of hidden layers in the Transformer decoder.
|
| 53 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
| 54 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 55 |
+
num_key_value_heads (`int`, *optional*, defaults to 8):
|
| 56 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 57 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 58 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 59 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 60 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
| 61 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
| 62 |
+
`num_attention_heads`.
|
| 63 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 64 |
+
The non-linear activation function (function or string) in the decoder.
|
| 65 |
+
max_position_embeddings (`int`, *optional*, defaults to 9216):
|
| 66 |
+
The maximum sequence length that this model might ever be used with. Emu supports up to 9216 tokens,
|
| 67 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 68 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 69 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 70 |
+
The epsilon used by the rms normalization layers.
|
| 71 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 72 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 73 |
+
relevant if `config.is_decoder=True`.
|
| 74 |
+
pad_token_id (`int`, *optional*, 151643):
|
| 75 |
+
Padding token id.
|
| 76 |
+
bos_token_id (`int`, *optional*, defaults to 151849):
|
| 77 |
+
Beginning of stream token id.
|
| 78 |
+
eos_token_id (`int`, *optional*, defaults to 151850):
|
| 79 |
+
End of stream token id.
|
| 80 |
+
img_token_id (`int`, *optional*, defaults to 151851):
|
| 81 |
+
image token id.
|
| 82 |
+
boi_token_id (`int`, *optional*, defaults to 151852):
|
| 83 |
+
Beginning of image token id.
|
| 84 |
+
eoi_token_id (`int`, *optional*, defaults to 151853):
|
| 85 |
+
End of image token id.
|
| 86 |
+
eol_token_id (`int`, *optional*, defaults to 151846):
|
| 87 |
+
End of line token id.
|
| 88 |
+
eof_token_id (`int`, *optional*, defaults to 151847):
|
| 89 |
+
End of line token id.
|
| 90 |
+
image_area (`int`, *optional*, defaults to 720 * 720)
|
| 91 |
+
generated image area (image area used in training)
|
| 92 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
| 93 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
| 94 |
+
document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
|
| 95 |
+
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
| 96 |
+
issue](https://github.com/pytorch/pytorch/issues/76232).
|
| 97 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 98 |
+
Whether to tie weight embeddings
|
| 99 |
+
rope_theta (`float`, *optional*, defaults to 1_000_000.0):
|
| 100 |
+
The base period of the RoPE embeddings.
|
| 101 |
+
rope_scaling (`Dict`, *optional*):
|
| 102 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
| 103 |
+
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
|
| 104 |
+
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
| 105 |
+
`max_position_embeddings` to the expected new maximum. See the following thread for more information on how
|
| 106 |
+
these scaling strategies behave:
|
| 107 |
+
https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
|
| 108 |
+
experimental feature, subject to breaking API changes in future versions.
|
| 109 |
+
attention_dropout (`float`, *optional*, defaults to 0.1):
|
| 110 |
+
The dropout ratio for the attention probabilities.
|
| 111 |
+
|
| 112 |
+
```python
|
| 113 |
+
>>> from transformers import Emu3Model, Emu3Config
|
| 114 |
+
|
| 115 |
+
>>> # Initializing a Emu3-8b style configuration
|
| 116 |
+
>>> configuration = Emu3Config()
|
| 117 |
+
|
| 118 |
+
>>> # Initializing a model from the Emu3-8b style configuration
|
| 119 |
+
>>> model = Emu3Model(configuration)
|
| 120 |
+
|
| 121 |
+
>>> # Accessing the model configuration
|
| 122 |
+
>>> configuration = model.config
|
| 123 |
+
```"""
|
| 124 |
+
|
| 125 |
+
model_type = "Emu3"
|
| 126 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 127 |
+
|
| 128 |
+
def __init__(
|
| 129 |
+
self,
|
| 130 |
+
vocab_size: int = 184622,
|
| 131 |
+
hidden_size: int = 4096,
|
| 132 |
+
intermediate_size: int = 14336,
|
| 133 |
+
num_hidden_layers: int = 32,
|
| 134 |
+
num_attention_heads: int = 32,
|
| 135 |
+
num_key_value_heads: Optional[int] = 8,
|
| 136 |
+
hidden_act: str = "silu",
|
| 137 |
+
max_position_embeddings: int = 9216,
|
| 138 |
+
initializer_range: float = 0.02,
|
| 139 |
+
rms_norm_eps: float = 1e-5,
|
| 140 |
+
use_cache: bool = True,
|
| 141 |
+
pad_token_id: int = 151643,
|
| 142 |
+
bos_token_id: int = 151849,
|
| 143 |
+
eos_token_id: int = 151850,
|
| 144 |
+
img_token_id: int = 151851,
|
| 145 |
+
boi_token_id: int = 151852,
|
| 146 |
+
eoi_token_id: int = 151853,
|
| 147 |
+
eol_token_id: int = 151846,
|
| 148 |
+
eof_token_id: int = 151847,
|
| 149 |
+
image_area: int = 720 * 720,
|
| 150 |
+
pretraining_tp: int = 1,
|
| 151 |
+
tie_word_embeddings: bool = False,
|
| 152 |
+
rope_theta: float = 1000000.0,
|
| 153 |
+
rope_scaling: Optional = None,
|
| 154 |
+
attention_dropout: float = 0.1,
|
| 155 |
+
**kwargs,
|
| 156 |
+
):
|
| 157 |
+
self.vocab_size = vocab_size
|
| 158 |
+
self.max_position_embeddings = max_position_embeddings
|
| 159 |
+
self.hidden_size = hidden_size
|
| 160 |
+
self.intermediate_size = intermediate_size
|
| 161 |
+
self.num_hidden_layers = num_hidden_layers
|
| 162 |
+
self.num_attention_heads = num_attention_heads
|
| 163 |
+
|
| 164 |
+
# for backward compatibility
|
| 165 |
+
if num_key_value_heads is None:
|
| 166 |
+
num_key_value_heads = num_attention_heads
|
| 167 |
+
|
| 168 |
+
self.num_key_value_heads = num_key_value_heads
|
| 169 |
+
self.hidden_act = hidden_act
|
| 170 |
+
self.initializer_range = initializer_range
|
| 171 |
+
self.rms_norm_eps = rms_norm_eps
|
| 172 |
+
self.pretraining_tp = pretraining_tp
|
| 173 |
+
self.use_cache = use_cache
|
| 174 |
+
self.rope_theta = rope_theta
|
| 175 |
+
self.rope_scaling = rope_scaling
|
| 176 |
+
self._rope_scaling_validation()
|
| 177 |
+
self.attention_dropout = attention_dropout
|
| 178 |
+
|
| 179 |
+
self.img_token_id = img_token_id
|
| 180 |
+
self.boi_token_id = boi_token_id
|
| 181 |
+
self.eoi_token_id = eoi_token_id
|
| 182 |
+
self.eol_token_id = eol_token_id
|
| 183 |
+
self.eof_token_id = eof_token_id
|
| 184 |
+
self.image_area = image_area
|
| 185 |
+
|
| 186 |
+
super().__init__(
|
| 187 |
+
pad_token_id=pad_token_id,
|
| 188 |
+
bos_token_id=bos_token_id,
|
| 189 |
+
eos_token_id=eos_token_id,
|
| 190 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 191 |
+
**kwargs,
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
def _rope_scaling_validation(self):
|
| 195 |
+
"""
|
| 196 |
+
Validate the `rope_scaling` configuration.
|
| 197 |
+
"""
|
| 198 |
+
if self.rope_scaling is None:
|
| 199 |
+
return
|
| 200 |
+
|
| 201 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
| 202 |
+
raise ValueError(
|
| 203 |
+
"`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
|
| 204 |
+
f"got {self.rope_scaling}"
|
| 205 |
+
)
|
| 206 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
| 207 |
+
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
| 208 |
+
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
| 209 |
+
raise ValueError(
|
| 210 |
+
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
| 211 |
+
)
|
| 212 |
+
if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
|
| 213 |
+
raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
|
sjdtree/emu3/mllm/modeling_emu3.py
ADDED
|
@@ -0,0 +1,1343 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The Emu team, BAAI and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 5 |
+
# and OPT implementations in this library. It has been modified from its
|
| 6 |
+
# original forms to accommodate minor architectural differences compared
|
| 7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
#
|
| 21 |
+
# Adapted from https://github.com/huggingface/transformers/blob/52daf4ec768fb9ffe84a0c373834172a7c54aecc/src/transformers/models/llama/modeling_llama.py
|
| 22 |
+
#
|
| 23 |
+
""" PyTorch Emu3 model."""
|
| 24 |
+
import math
|
| 25 |
+
import warnings
|
| 26 |
+
from typing import List, Optional, Tuple, Union
|
| 27 |
+
|
| 28 |
+
import torch
|
| 29 |
+
import torch.nn.functional as F
|
| 30 |
+
import torch.utils.checkpoint
|
| 31 |
+
from torch import nn
|
| 32 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 33 |
+
|
| 34 |
+
from transformers.activations import ACT2FN
|
| 35 |
+
from transformers.cache_utils import Cache, DynamicCache
|
| 36 |
+
from transformers.modeling_attn_mask_utils import (
|
| 37 |
+
AttentionMaskConverter,
|
| 38 |
+
_prepare_4d_attention_mask,
|
| 39 |
+
_prepare_4d_causal_attention_mask,
|
| 40 |
+
_prepare_4d_causal_attention_mask_for_sdpa,
|
| 41 |
+
)
|
| 42 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
|
| 43 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 44 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
|
| 45 |
+
from transformers.utils import (
|
| 46 |
+
add_start_docstrings,
|
| 47 |
+
add_start_docstrings_to_model_forward,
|
| 48 |
+
is_flash_attn_2_available,
|
| 49 |
+
is_flash_attn_greater_or_equal_2_10,
|
| 50 |
+
logging,
|
| 51 |
+
replace_return_docstrings,
|
| 52 |
+
)
|
| 53 |
+
from transformers.utils.import_utils import is_torch_fx_available
|
| 54 |
+
from .configuration_emu3 import Emu3Config
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
if is_flash_attn_2_available():
|
| 58 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
| 59 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
|
| 63 |
+
# It means that the function will not be traced through and simply appear as a node in the graph.
|
| 64 |
+
if is_torch_fx_available():
|
| 65 |
+
if not is_torch_greater_or_equal_than_1_13:
|
| 66 |
+
import torch.fx
|
| 67 |
+
|
| 68 |
+
_prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
logger = logging.get_logger(__name__)
|
| 72 |
+
|
| 73 |
+
_CONFIG_FOR_DOC = "Emu3Config"
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _get_unpad_data(attention_mask):
|
| 77 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
| 78 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
| 79 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
| 80 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
|
| 81 |
+
return (
|
| 82 |
+
indices,
|
| 83 |
+
cu_seqlens,
|
| 84 |
+
max_seqlen_in_batch,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
| 89 |
+
warnings.warn(
|
| 90 |
+
"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"
|
| 91 |
+
)
|
| 92 |
+
return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _make_causal_mask(
|
| 96 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
| 97 |
+
):
|
| 98 |
+
warnings.warn(
|
| 99 |
+
"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"
|
| 100 |
+
)
|
| 101 |
+
return AttentionMaskConverter._make_causal_mask(
|
| 102 |
+
input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class Emu3RMSNorm(nn.Module):
|
| 107 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 108 |
+
"""
|
| 109 |
+
Emu3RMSNorm is equivalent to T5LayerNorm
|
| 110 |
+
"""
|
| 111 |
+
super().__init__()
|
| 112 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 113 |
+
self.variance_epsilon = eps
|
| 114 |
+
|
| 115 |
+
def forward(self, hidden_states):
|
| 116 |
+
input_dtype = hidden_states.dtype
|
| 117 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 118 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 119 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 120 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
ALL_LAYERNORM_LAYERS.append(Emu3RMSNorm)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class Emu3RotaryEmbedding(nn.Module):
|
| 127 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
| 128 |
+
super().__init__()
|
| 129 |
+
|
| 130 |
+
self.dim = dim
|
| 131 |
+
self.max_position_embeddings = max_position_embeddings
|
| 132 |
+
self.base = base
|
| 133 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
| 134 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 135 |
+
|
| 136 |
+
# Build here to make `torch.jit.trace` work.
|
| 137 |
+
self._set_cos_sin_cache(
|
| 138 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
| 142 |
+
self.max_seq_len_cached = seq_len
|
| 143 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
| 144 |
+
|
| 145 |
+
freqs = torch.outer(t, self.inv_freq)
|
| 146 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 147 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 148 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
| 149 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
| 150 |
+
|
| 151 |
+
def forward(self, x, seq_len=None):
|
| 152 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
| 153 |
+
if seq_len > self.max_seq_len_cached:
|
| 154 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
| 155 |
+
|
| 156 |
+
return (
|
| 157 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
| 158 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class Emu3LinearScalingRotaryEmbedding(Emu3RotaryEmbedding):
|
| 163 |
+
"""Emu3RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
| 164 |
+
|
| 165 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
| 166 |
+
self.scaling_factor = scaling_factor
|
| 167 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
| 168 |
+
|
| 169 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
| 170 |
+
self.max_seq_len_cached = seq_len
|
| 171 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
| 172 |
+
t = t / self.scaling_factor
|
| 173 |
+
|
| 174 |
+
freqs = torch.outer(t, self.inv_freq)
|
| 175 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 176 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 177 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
| 178 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class Emu3DynamicNTKScalingRotaryEmbedding(Emu3RotaryEmbedding):
|
| 182 |
+
"""Emu3RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
| 183 |
+
|
| 184 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
| 185 |
+
self.scaling_factor = scaling_factor
|
| 186 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
| 187 |
+
|
| 188 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
| 189 |
+
self.max_seq_len_cached = seq_len
|
| 190 |
+
|
| 191 |
+
if seq_len > self.max_position_embeddings:
|
| 192 |
+
base = self.base * (
|
| 193 |
+
(self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
|
| 194 |
+
) ** (self.dim / (self.dim - 2))
|
| 195 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
| 196 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 197 |
+
|
| 198 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
| 199 |
+
|
| 200 |
+
freqs = torch.outer(t, self.inv_freq)
|
| 201 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 202 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 203 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
| 204 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def rotate_half(x):
|
| 208 |
+
"""Rotates half the hidden dims of the input."""
|
| 209 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 210 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 211 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
| 215 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 216 |
+
|
| 217 |
+
Args:
|
| 218 |
+
q (`torch.Tensor`): The query tensor.
|
| 219 |
+
k (`torch.Tensor`): The key tensor.
|
| 220 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 221 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 222 |
+
position_ids (`torch.Tensor`):
|
| 223 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
| 224 |
+
used to pass offsetted position ids when working with a KV-cache.
|
| 225 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 226 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 227 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 228 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 229 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 230 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 231 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 232 |
+
Returns:
|
| 233 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 234 |
+
"""
|
| 235 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
| 236 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
| 237 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 238 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 239 |
+
return q_embed, k_embed
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class Emu3MLP(nn.Module):
|
| 243 |
+
def __init__(self, config):
|
| 244 |
+
super().__init__()
|
| 245 |
+
self.config = config
|
| 246 |
+
self.hidden_size = config.hidden_size
|
| 247 |
+
self.intermediate_size = config.intermediate_size
|
| 248 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 249 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 250 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 251 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 252 |
+
|
| 253 |
+
def forward(self, x):
|
| 254 |
+
if self.config.pretraining_tp > 1:
|
| 255 |
+
slice = self.intermediate_size // self.config.pretraining_tp
|
| 256 |
+
gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
|
| 257 |
+
up_proj_slices = self.up_proj.weight.split(slice, dim=0)
|
| 258 |
+
down_proj_slices = self.down_proj.weight.split(slice, dim=1)
|
| 259 |
+
|
| 260 |
+
gate_proj = torch.cat(
|
| 261 |
+
[F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
|
| 262 |
+
)
|
| 263 |
+
up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
|
| 264 |
+
|
| 265 |
+
intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
|
| 266 |
+
down_proj = [
|
| 267 |
+
F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
|
| 268 |
+
]
|
| 269 |
+
down_proj = sum(down_proj)
|
| 270 |
+
else:
|
| 271 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 272 |
+
|
| 273 |
+
return down_proj
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 277 |
+
"""
|
| 278 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 279 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 280 |
+
"""
|
| 281 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 282 |
+
if n_rep == 1:
|
| 283 |
+
return hidden_states
|
| 284 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 285 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
class Emu3Attention(nn.Module):
|
| 289 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 290 |
+
|
| 291 |
+
def __init__(self, config: Emu3Config, layer_idx: Optional[int] = None):
|
| 292 |
+
super().__init__()
|
| 293 |
+
self.config = config
|
| 294 |
+
self.layer_idx = layer_idx
|
| 295 |
+
if layer_idx is None:
|
| 296 |
+
logger.warning_once(
|
| 297 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
| 298 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
| 299 |
+
"when creating this class."
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
self.attention_dropout = config.attention_dropout
|
| 303 |
+
self.hidden_size = config.hidden_size
|
| 304 |
+
self.num_heads = config.num_attention_heads
|
| 305 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 306 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 307 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 308 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 309 |
+
self.rope_theta = config.rope_theta
|
| 310 |
+
self.is_causal = True
|
| 311 |
+
|
| 312 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
| 313 |
+
raise ValueError(
|
| 314 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
| 315 |
+
f" and `num_heads`: {self.num_heads})."
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
| 319 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
| 320 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
| 321 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
| 322 |
+
self._init_rope()
|
| 323 |
+
|
| 324 |
+
def _init_rope(self):
|
| 325 |
+
if self.config.rope_scaling is None:
|
| 326 |
+
self.rotary_emb = Emu3RotaryEmbedding(
|
| 327 |
+
self.head_dim,
|
| 328 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 329 |
+
base=self.rope_theta,
|
| 330 |
+
)
|
| 331 |
+
else:
|
| 332 |
+
scaling_type = self.config.rope_scaling["type"]
|
| 333 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
| 334 |
+
if scaling_type == "linear":
|
| 335 |
+
self.rotary_emb = Emu3LinearScalingRotaryEmbedding(
|
| 336 |
+
self.head_dim,
|
| 337 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 338 |
+
scaling_factor=scaling_factor,
|
| 339 |
+
base=self.rope_theta,
|
| 340 |
+
)
|
| 341 |
+
elif scaling_type == "dynamic":
|
| 342 |
+
self.rotary_emb = Emu3DynamicNTKScalingRotaryEmbedding(
|
| 343 |
+
self.head_dim,
|
| 344 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 345 |
+
scaling_factor=scaling_factor,
|
| 346 |
+
base=self.rope_theta,
|
| 347 |
+
)
|
| 348 |
+
else:
|
| 349 |
+
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
| 350 |
+
|
| 351 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 352 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 353 |
+
|
| 354 |
+
def forward(
|
| 355 |
+
self,
|
| 356 |
+
hidden_states: torch.Tensor,
|
| 357 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 358 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 359 |
+
past_key_value: Optional[Cache] = None,
|
| 360 |
+
output_attentions: bool = False,
|
| 361 |
+
use_cache: bool = False,
|
| 362 |
+
**kwargs,
|
| 363 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 364 |
+
if "padding_mask" in kwargs:
|
| 365 |
+
warnings.warn(
|
| 366 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
bsz, q_len, _ = hidden_states.size()
|
| 370 |
+
|
| 371 |
+
if self.config.pretraining_tp > 1:
|
| 372 |
+
key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
|
| 373 |
+
query_slices = self.q_proj.weight.split(
|
| 374 |
+
(self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
|
| 375 |
+
)
|
| 376 |
+
key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
|
| 377 |
+
value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
|
| 378 |
+
|
| 379 |
+
query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 380 |
+
query_states = torch.cat(query_states, dim=-1)
|
| 381 |
+
|
| 382 |
+
key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 383 |
+
key_states = torch.cat(key_states, dim=-1)
|
| 384 |
+
|
| 385 |
+
value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 386 |
+
value_states = torch.cat(value_states, dim=-1)
|
| 387 |
+
|
| 388 |
+
else:
|
| 389 |
+
query_states = self.q_proj(hidden_states)
|
| 390 |
+
key_states = self.k_proj(hidden_states)
|
| 391 |
+
value_states = self.v_proj(hidden_states)
|
| 392 |
+
|
| 393 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 394 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 395 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 396 |
+
|
| 397 |
+
kv_seq_len = key_states.shape[-2]
|
| 398 |
+
if past_key_value is not None:
|
| 399 |
+
if self.layer_idx is None:
|
| 400 |
+
raise ValueError(
|
| 401 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
| 402 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
| 403 |
+
"with a layer index."
|
| 404 |
+
)
|
| 405 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
| 406 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
| 407 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
| 408 |
+
|
| 409 |
+
if past_key_value is not None:
|
| 410 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
| 411 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 412 |
+
|
| 413 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 414 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 415 |
+
|
| 416 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
| 417 |
+
|
| 418 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
| 419 |
+
raise ValueError(
|
| 420 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
| 421 |
+
f" {attn_weights.size()}"
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
if attention_mask is not None:
|
| 425 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
| 426 |
+
raise ValueError(
|
| 427 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
| 428 |
+
)
|
| 429 |
+
attn_weights = attn_weights + attention_mask
|
| 430 |
+
|
| 431 |
+
# upcast attention to fp32
|
| 432 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 433 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
| 434 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 435 |
+
|
| 436 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
| 437 |
+
raise ValueError(
|
| 438 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
| 439 |
+
f" {attn_output.size()}"
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 443 |
+
|
| 444 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 445 |
+
|
| 446 |
+
if self.config.pretraining_tp > 1:
|
| 447 |
+
attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
|
| 448 |
+
o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
|
| 449 |
+
attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
|
| 450 |
+
else:
|
| 451 |
+
attn_output = self.o_proj(attn_output)
|
| 452 |
+
|
| 453 |
+
if not output_attentions:
|
| 454 |
+
attn_weights = None
|
| 455 |
+
|
| 456 |
+
return attn_output, attn_weights, past_key_value
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
class Emu3FlashAttention2(Emu3Attention):
|
| 460 |
+
"""
|
| 461 |
+
Emu3 flash attention module. This module inherits from `Emu3Attention` as the weights of the module stays
|
| 462 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
| 463 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
| 464 |
+
"""
|
| 465 |
+
|
| 466 |
+
def __init__(self, *args, **kwargs):
|
| 467 |
+
super().__init__(*args, **kwargs)
|
| 468 |
+
|
| 469 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
| 470 |
+
# 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.
|
| 471 |
+
# 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).
|
| 472 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
| 473 |
+
|
| 474 |
+
def forward(
|
| 475 |
+
self,
|
| 476 |
+
hidden_states: torch.Tensor,
|
| 477 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 478 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 479 |
+
past_key_value: Optional[Cache] = None,
|
| 480 |
+
output_attentions: bool = False,
|
| 481 |
+
use_cache: bool = False,
|
| 482 |
+
**kwargs,
|
| 483 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 484 |
+
# Emu3FlashAttention2 attention does not support output_attentions
|
| 485 |
+
if "padding_mask" in kwargs:
|
| 486 |
+
warnings.warn(
|
| 487 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
# overwrite attention_mask with padding_mask
|
| 491 |
+
attention_mask = kwargs.pop("padding_mask")
|
| 492 |
+
|
| 493 |
+
output_attentions = False
|
| 494 |
+
|
| 495 |
+
bsz, q_len, _ = hidden_states.size()
|
| 496 |
+
|
| 497 |
+
query_states = self.q_proj(hidden_states)
|
| 498 |
+
key_states = self.k_proj(hidden_states)
|
| 499 |
+
value_states = self.v_proj(hidden_states)
|
| 500 |
+
|
| 501 |
+
# Flash attention requires the input to have the shape
|
| 502 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
| 503 |
+
# therefore we just need to keep the original shape
|
| 504 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 505 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 506 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 507 |
+
|
| 508 |
+
kv_seq_len = key_states.shape[-2]
|
| 509 |
+
if past_key_value is not None:
|
| 510 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
| 511 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
| 512 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
| 513 |
+
|
| 514 |
+
if past_key_value is not None:
|
| 515 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
| 516 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 517 |
+
|
| 518 |
+
# 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
|
| 519 |
+
# to be able to avoid many of these transpose/reshape/view.
|
| 520 |
+
query_states = query_states.transpose(1, 2)
|
| 521 |
+
key_states = key_states.transpose(1, 2)
|
| 522 |
+
value_states = value_states.transpose(1, 2)
|
| 523 |
+
|
| 524 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
| 525 |
+
|
| 526 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
| 527 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
| 528 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
| 529 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
| 530 |
+
# in fp32. (Emu3RMSNorm handles it correctly)
|
| 531 |
+
|
| 532 |
+
input_dtype = query_states.dtype
|
| 533 |
+
if input_dtype == torch.float32:
|
| 534 |
+
# Handle the case where the model is quantized
|
| 535 |
+
if hasattr(self.config, "_pre_quantization_dtype"):
|
| 536 |
+
target_dtype = self.config._pre_quantization_dtype
|
| 537 |
+
else:
|
| 538 |
+
target_dtype = self.q_proj.weight.dtype
|
| 539 |
+
|
| 540 |
+
logger.warning_once(
|
| 541 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
| 542 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
| 543 |
+
f" {target_dtype}."
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
query_states = query_states.to(target_dtype)
|
| 547 |
+
key_states = key_states.to(target_dtype)
|
| 548 |
+
value_states = value_states.to(target_dtype)
|
| 549 |
+
|
| 550 |
+
attn_output = self._flash_attention_forward(
|
| 551 |
+
query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
|
| 552 |
+
)
|
| 553 |
+
|
| 554 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
| 555 |
+
attn_output = self.o_proj(attn_output)
|
| 556 |
+
|
| 557 |
+
if not output_attentions:
|
| 558 |
+
attn_weights = None
|
| 559 |
+
|
| 560 |
+
return attn_output, attn_weights, past_key_value
|
| 561 |
+
|
| 562 |
+
def _flash_attention_forward(
|
| 563 |
+
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
|
| 564 |
+
):
|
| 565 |
+
"""
|
| 566 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
| 567 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
| 568 |
+
|
| 569 |
+
Args:
|
| 570 |
+
query_states (`torch.Tensor`):
|
| 571 |
+
Input query states to be passed to Flash Attention API
|
| 572 |
+
key_states (`torch.Tensor`):
|
| 573 |
+
Input key states to be passed to Flash Attention API
|
| 574 |
+
value_states (`torch.Tensor`):
|
| 575 |
+
Input value states to be passed to Flash Attention API
|
| 576 |
+
attention_mask (`torch.Tensor`):
|
| 577 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
| 578 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
| 579 |
+
dropout (`int`, *optional*):
|
| 580 |
+
Attention dropout
|
| 581 |
+
softmax_scale (`float`, *optional*):
|
| 582 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
| 583 |
+
"""
|
| 584 |
+
if not self._flash_attn_uses_top_left_mask:
|
| 585 |
+
causal = self.is_causal
|
| 586 |
+
else:
|
| 587 |
+
# 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__.
|
| 588 |
+
causal = self.is_causal and query_length != 1
|
| 589 |
+
|
| 590 |
+
# Contains at least one padding token in the sequence
|
| 591 |
+
if attention_mask is not None:
|
| 592 |
+
batch_size = query_states.shape[0]
|
| 593 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
| 594 |
+
query_states, key_states, value_states, attention_mask, query_length
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
| 598 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
| 599 |
+
|
| 600 |
+
attn_output_unpad = flash_attn_varlen_func(
|
| 601 |
+
query_states,
|
| 602 |
+
key_states,
|
| 603 |
+
value_states,
|
| 604 |
+
cu_seqlens_q=cu_seqlens_q,
|
| 605 |
+
cu_seqlens_k=cu_seqlens_k,
|
| 606 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
| 607 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
| 608 |
+
dropout_p=dropout,
|
| 609 |
+
softmax_scale=softmax_scale,
|
| 610 |
+
causal=causal,
|
| 611 |
+
)
|
| 612 |
+
|
| 613 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
| 614 |
+
else:
|
| 615 |
+
attn_output = flash_attn_func(
|
| 616 |
+
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
|
| 617 |
+
)
|
| 618 |
+
|
| 619 |
+
return attn_output
|
| 620 |
+
|
| 621 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
| 622 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
| 623 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
| 624 |
+
|
| 625 |
+
key_layer = index_first_axis(
|
| 626 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
| 627 |
+
)
|
| 628 |
+
value_layer = index_first_axis(
|
| 629 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
| 630 |
+
)
|
| 631 |
+
if query_length == kv_seq_len:
|
| 632 |
+
query_layer = index_first_axis(
|
| 633 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
| 634 |
+
)
|
| 635 |
+
cu_seqlens_q = cu_seqlens_k
|
| 636 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
| 637 |
+
indices_q = indices_k
|
| 638 |
+
elif query_length == 1:
|
| 639 |
+
max_seqlen_in_batch_q = 1
|
| 640 |
+
cu_seqlens_q = torch.arange(
|
| 641 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
| 642 |
+
) # There is a memcpy here, that is very bad.
|
| 643 |
+
indices_q = cu_seqlens_q[:-1]
|
| 644 |
+
query_layer = query_layer.squeeze(1)
|
| 645 |
+
else:
|
| 646 |
+
# The -q_len: slice assumes left padding.
|
| 647 |
+
attention_mask = attention_mask[:, -query_length:]
|
| 648 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
| 649 |
+
|
| 650 |
+
return (
|
| 651 |
+
query_layer,
|
| 652 |
+
key_layer,
|
| 653 |
+
value_layer,
|
| 654 |
+
indices_q,
|
| 655 |
+
(cu_seqlens_q, cu_seqlens_k),
|
| 656 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
| 657 |
+
)
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
class Emu3SdpaAttention(Emu3Attention):
|
| 661 |
+
"""
|
| 662 |
+
Emu3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
| 663 |
+
`Emu3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
| 664 |
+
SDPA API.
|
| 665 |
+
"""
|
| 666 |
+
|
| 667 |
+
# Adapted from Emu3Attention.forward
|
| 668 |
+
def forward(
|
| 669 |
+
self,
|
| 670 |
+
hidden_states: torch.Tensor,
|
| 671 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 672 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 673 |
+
past_key_value: Optional[Cache] = None,
|
| 674 |
+
output_attentions: bool = False,
|
| 675 |
+
use_cache: bool = False,
|
| 676 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 677 |
+
if output_attentions:
|
| 678 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
| 679 |
+
logger.warning_once(
|
| 680 |
+
"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, "
|
| 681 |
+
'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.'
|
| 682 |
+
)
|
| 683 |
+
return super().forward(
|
| 684 |
+
hidden_states=hidden_states,
|
| 685 |
+
attention_mask=attention_mask,
|
| 686 |
+
position_ids=position_ids,
|
| 687 |
+
past_key_value=past_key_value,
|
| 688 |
+
output_attentions=output_attentions,
|
| 689 |
+
use_cache=use_cache,
|
| 690 |
+
)
|
| 691 |
+
|
| 692 |
+
bsz, q_len, _ = hidden_states.size()
|
| 693 |
+
|
| 694 |
+
query_states = self.q_proj(hidden_states)
|
| 695 |
+
key_states = self.k_proj(hidden_states)
|
| 696 |
+
value_states = self.v_proj(hidden_states)
|
| 697 |
+
|
| 698 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 699 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 700 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 701 |
+
|
| 702 |
+
kv_seq_len = key_states.shape[-2]
|
| 703 |
+
if past_key_value is not None:
|
| 704 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
| 705 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
| 706 |
+
|
| 707 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
| 708 |
+
|
| 709 |
+
if past_key_value is not None:
|
| 710 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
| 711 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 712 |
+
|
| 713 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 714 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 715 |
+
|
| 716 |
+
if attention_mask is not None:
|
| 717 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
| 718 |
+
raise ValueError(
|
| 719 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
| 720 |
+
)
|
| 721 |
+
|
| 722 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
| 723 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
| 724 |
+
if query_states.device.type == "cuda" and attention_mask is not None:
|
| 725 |
+
query_states = query_states.contiguous()
|
| 726 |
+
key_states = key_states.contiguous()
|
| 727 |
+
value_states = value_states.contiguous()
|
| 728 |
+
|
| 729 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
| 730 |
+
query_states,
|
| 731 |
+
key_states,
|
| 732 |
+
value_states,
|
| 733 |
+
attn_mask=attention_mask,
|
| 734 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
| 735 |
+
# 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.
|
| 736 |
+
is_causal=self.is_causal and attention_mask is None and q_len > 1,
|
| 737 |
+
)
|
| 738 |
+
|
| 739 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 740 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 741 |
+
|
| 742 |
+
attn_output = self.o_proj(attn_output)
|
| 743 |
+
|
| 744 |
+
return attn_output, None, past_key_value
|
| 745 |
+
|
| 746 |
+
|
| 747 |
+
EMU3_ATTENTION_CLASSES = {
|
| 748 |
+
"eager": Emu3Attention,
|
| 749 |
+
"flash_attention_2": Emu3FlashAttention2,
|
| 750 |
+
"sdpa": Emu3SdpaAttention,
|
| 751 |
+
}
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
class Emu3DecoderLayer(nn.Module):
|
| 755 |
+
def __init__(self, config: Emu3Config, layer_idx: int):
|
| 756 |
+
super().__init__()
|
| 757 |
+
self.hidden_size = config.hidden_size
|
| 758 |
+
self.dropout = nn.Dropout(config.attention_dropout)
|
| 759 |
+
self.self_attn = EMU3_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
|
| 760 |
+
|
| 761 |
+
self.mlp = Emu3MLP(config)
|
| 762 |
+
self.input_layernorm = Emu3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 763 |
+
self.post_attention_layernorm = Emu3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 764 |
+
|
| 765 |
+
def forward(
|
| 766 |
+
self,
|
| 767 |
+
hidden_states: torch.Tensor,
|
| 768 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 769 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 770 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 771 |
+
output_attentions: Optional[bool] = False,
|
| 772 |
+
use_cache: Optional[bool] = False,
|
| 773 |
+
**kwargs,
|
| 774 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 775 |
+
"""
|
| 776 |
+
Args:
|
| 777 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 778 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
| 779 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
| 780 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
| 781 |
+
output_attentions (`bool`, *optional*):
|
| 782 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 783 |
+
returned tensors for more detail.
|
| 784 |
+
use_cache (`bool`, *optional*):
|
| 785 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 786 |
+
(see `past_key_values`).
|
| 787 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
| 788 |
+
"""
|
| 789 |
+
if "padding_mask" in kwargs:
|
| 790 |
+
warnings.warn(
|
| 791 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
| 792 |
+
)
|
| 793 |
+
|
| 794 |
+
residual = hidden_states
|
| 795 |
+
|
| 796 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 797 |
+
|
| 798 |
+
# Self Attention
|
| 799 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 800 |
+
hidden_states=hidden_states,
|
| 801 |
+
attention_mask=attention_mask,
|
| 802 |
+
position_ids=position_ids,
|
| 803 |
+
past_key_value=past_key_value,
|
| 804 |
+
output_attentions=output_attentions,
|
| 805 |
+
use_cache=use_cache,
|
| 806 |
+
**kwargs,
|
| 807 |
+
)
|
| 808 |
+
hidden_states = residual + self.dropout(hidden_states)
|
| 809 |
+
|
| 810 |
+
# Fully Connected
|
| 811 |
+
residual = hidden_states
|
| 812 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 813 |
+
hidden_states = self.mlp(hidden_states)
|
| 814 |
+
hidden_states = residual + self.dropout(hidden_states)
|
| 815 |
+
|
| 816 |
+
outputs = (hidden_states,)
|
| 817 |
+
|
| 818 |
+
if output_attentions:
|
| 819 |
+
outputs += (self_attn_weights,)
|
| 820 |
+
|
| 821 |
+
if use_cache:
|
| 822 |
+
outputs += (present_key_value,)
|
| 823 |
+
|
| 824 |
+
return outputs
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
EMU3_START_DOCSTRING = r"""
|
| 828 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 829 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 830 |
+
etc.)
|
| 831 |
+
|
| 832 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 833 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 834 |
+
and behavior.
|
| 835 |
+
|
| 836 |
+
Parameters:
|
| 837 |
+
config ([`Emu3Config`]):
|
| 838 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 839 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 840 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 841 |
+
"""
|
| 842 |
+
|
| 843 |
+
|
| 844 |
+
@add_start_docstrings(
|
| 845 |
+
"The bare Emu3 Model outputting raw hidden-states without any specific head on top.",
|
| 846 |
+
EMU3_START_DOCSTRING,
|
| 847 |
+
)
|
| 848 |
+
class Emu3PreTrainedModel(PreTrainedModel):
|
| 849 |
+
config_class = Emu3Config
|
| 850 |
+
base_model_prefix = "model"
|
| 851 |
+
supports_gradient_checkpointing = True
|
| 852 |
+
_no_split_modules = ["Emu3DecoderLayer"]
|
| 853 |
+
_skip_keys_device_placement = "past_key_values"
|
| 854 |
+
_supports_flash_attn_2 = True
|
| 855 |
+
_supports_sdpa = True
|
| 856 |
+
_supports_cache_class = True
|
| 857 |
+
|
| 858 |
+
def _init_weights(self, module):
|
| 859 |
+
std = self.config.initializer_range
|
| 860 |
+
if isinstance(module, nn.Linear):
|
| 861 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 862 |
+
if module.bias is not None:
|
| 863 |
+
module.bias.data.zero_()
|
| 864 |
+
elif isinstance(module, nn.Embedding):
|
| 865 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 866 |
+
if module.padding_idx is not None:
|
| 867 |
+
module.weight.data[module.padding_idx].zero_()
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
EMU3_INPUTS_DOCSTRING = r"""
|
| 871 |
+
Args:
|
| 872 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 873 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 874 |
+
it.
|
| 875 |
+
|
| 876 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 877 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 878 |
+
|
| 879 |
+
[What are input IDs?](../glossary#input-ids)
|
| 880 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 881 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 882 |
+
|
| 883 |
+
- 1 for tokens that are **not masked**,
|
| 884 |
+
- 0 for tokens that are **masked**.
|
| 885 |
+
|
| 886 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 887 |
+
|
| 888 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 889 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 890 |
+
|
| 891 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
| 892 |
+
`past_key_values`).
|
| 893 |
+
|
| 894 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
| 895 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
| 896 |
+
information on the default strategy.
|
| 897 |
+
|
| 898 |
+
- 1 indicates the head is **not masked**,
|
| 899 |
+
- 0 indicates the head is **masked**.
|
| 900 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 901 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 902 |
+
config.n_positions - 1]`.
|
| 903 |
+
|
| 904 |
+
[What are position IDs?](../glossary#position-ids)
|
| 905 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
| 906 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
| 907 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
| 908 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
| 909 |
+
|
| 910 |
+
Two formats are allowed:
|
| 911 |
+
- a [`~cache_utils.Cache`] instance;
|
| 912 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 913 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
| 914 |
+
cache format.
|
| 915 |
+
|
| 916 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
| 917 |
+
legacy cache format will be returned.
|
| 918 |
+
|
| 919 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
| 920 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
| 921 |
+
of shape `(batch_size, sequence_length)`.
|
| 922 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 923 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 924 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 925 |
+
model's internal embedding lookup matrix.
|
| 926 |
+
use_cache (`bool`, *optional*):
|
| 927 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 928 |
+
`past_key_values`).
|
| 929 |
+
output_attentions (`bool`, *optional*):
|
| 930 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 931 |
+
tensors for more detail.
|
| 932 |
+
output_hidden_states (`bool`, *optional*):
|
| 933 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 934 |
+
more detail.
|
| 935 |
+
return_dict (`bool`, *optional*):
|
| 936 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 937 |
+
"""
|
| 938 |
+
|
| 939 |
+
|
| 940 |
+
@add_start_docstrings(
|
| 941 |
+
"The bare Emu3 Model outputting raw hidden-states without any specific head on top.",
|
| 942 |
+
EMU3_START_DOCSTRING,
|
| 943 |
+
)
|
| 944 |
+
class Emu3Model(Emu3PreTrainedModel):
|
| 945 |
+
"""
|
| 946 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Emu3DecoderLayer`]
|
| 947 |
+
|
| 948 |
+
Args:
|
| 949 |
+
config: Emu3Config
|
| 950 |
+
"""
|
| 951 |
+
|
| 952 |
+
def __init__(self, config: Emu3Config):
|
| 953 |
+
super().__init__(config)
|
| 954 |
+
self.padding_idx = config.pad_token_id
|
| 955 |
+
self.vocab_size = config.vocab_size
|
| 956 |
+
|
| 957 |
+
self.dropout = nn.Dropout(config.attention_dropout)
|
| 958 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 959 |
+
self.layers = nn.ModuleList(
|
| 960 |
+
[Emu3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 961 |
+
)
|
| 962 |
+
self._use_sdpa = config._attn_implementation == "sdpa"
|
| 963 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
| 964 |
+
self.norm = Emu3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 965 |
+
|
| 966 |
+
self.gradient_checkpointing = False
|
| 967 |
+
# Initialize weights and apply final processing
|
| 968 |
+
self.post_init()
|
| 969 |
+
|
| 970 |
+
def get_input_embeddings(self):
|
| 971 |
+
return self.embed_tokens
|
| 972 |
+
|
| 973 |
+
def set_input_embeddings(self, value):
|
| 974 |
+
self.embed_tokens = value
|
| 975 |
+
|
| 976 |
+
@add_start_docstrings_to_model_forward(EMU3_INPUTS_DOCSTRING)
|
| 977 |
+
def forward(
|
| 978 |
+
self,
|
| 979 |
+
input_ids: torch.LongTensor = None,
|
| 980 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 981 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 982 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 983 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 984 |
+
use_cache: Optional[bool] = None,
|
| 985 |
+
output_attentions: Optional[bool] = None,
|
| 986 |
+
output_hidden_states: Optional[bool] = None,
|
| 987 |
+
return_dict: Optional[bool] = None,
|
| 988 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 989 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 990 |
+
output_hidden_states = (
|
| 991 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 992 |
+
)
|
| 993 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 994 |
+
|
| 995 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 996 |
+
|
| 997 |
+
# retrieve input_ids and inputs_embeds
|
| 998 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 999 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 1000 |
+
elif input_ids is not None:
|
| 1001 |
+
batch_size, seq_length = input_ids.shape[:2]
|
| 1002 |
+
elif inputs_embeds is not None:
|
| 1003 |
+
batch_size, seq_length = inputs_embeds.shape[:2]
|
| 1004 |
+
else:
|
| 1005 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 1006 |
+
|
| 1007 |
+
if self.gradient_checkpointing and self.training:
|
| 1008 |
+
if use_cache:
|
| 1009 |
+
logger.warning_once(
|
| 1010 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 1011 |
+
)
|
| 1012 |
+
use_cache = False
|
| 1013 |
+
|
| 1014 |
+
past_key_values_length = 0
|
| 1015 |
+
if use_cache:
|
| 1016 |
+
use_legacy_cache = not isinstance(past_key_values, Cache)
|
| 1017 |
+
if use_legacy_cache:
|
| 1018 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
| 1019 |
+
past_key_values_length = past_key_values.get_usable_length(seq_length)
|
| 1020 |
+
|
| 1021 |
+
if position_ids is None:
|
| 1022 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 1023 |
+
position_ids = torch.arange(
|
| 1024 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
| 1025 |
+
)
|
| 1026 |
+
position_ids = position_ids.unsqueeze(0)
|
| 1027 |
+
|
| 1028 |
+
if inputs_embeds is None:
|
| 1029 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 1030 |
+
|
| 1031 |
+
if self._use_flash_attention_2:
|
| 1032 |
+
# 2d mask is passed through the layers
|
| 1033 |
+
attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
|
| 1034 |
+
elif self._use_sdpa and not output_attentions:
|
| 1035 |
+
# output_attentions=True can not be supported when using SDPA, and we fall back on
|
| 1036 |
+
# the manual implementation that requires a 4D causal mask in all cases.
|
| 1037 |
+
attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
|
| 1038 |
+
attention_mask,
|
| 1039 |
+
(batch_size, seq_length),
|
| 1040 |
+
inputs_embeds,
|
| 1041 |
+
past_key_values_length,
|
| 1042 |
+
)
|
| 1043 |
+
else:
|
| 1044 |
+
# 4d mask is passed through the layers
|
| 1045 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
| 1046 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
| 1047 |
+
)
|
| 1048 |
+
|
| 1049 |
+
# embed positions
|
| 1050 |
+
hidden_states = self.dropout(inputs_embeds)
|
| 1051 |
+
|
| 1052 |
+
# decoder layers
|
| 1053 |
+
all_hidden_states = () if output_hidden_states else None
|
| 1054 |
+
all_self_attns = () if output_attentions else None
|
| 1055 |
+
next_decoder_cache = None
|
| 1056 |
+
|
| 1057 |
+
for decoder_layer in self.layers:
|
| 1058 |
+
if output_hidden_states:
|
| 1059 |
+
all_hidden_states += (hidden_states,)
|
| 1060 |
+
|
| 1061 |
+
if self.gradient_checkpointing and self.training:
|
| 1062 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 1063 |
+
decoder_layer.__call__,
|
| 1064 |
+
hidden_states,
|
| 1065 |
+
attention_mask,
|
| 1066 |
+
position_ids,
|
| 1067 |
+
past_key_values,
|
| 1068 |
+
output_attentions,
|
| 1069 |
+
use_cache,
|
| 1070 |
+
)
|
| 1071 |
+
else:
|
| 1072 |
+
layer_outputs = decoder_layer(
|
| 1073 |
+
hidden_states,
|
| 1074 |
+
attention_mask=attention_mask,
|
| 1075 |
+
position_ids=position_ids,
|
| 1076 |
+
past_key_value=past_key_values,
|
| 1077 |
+
output_attentions=output_attentions,
|
| 1078 |
+
use_cache=use_cache,
|
| 1079 |
+
)
|
| 1080 |
+
|
| 1081 |
+
hidden_states = layer_outputs[0]
|
| 1082 |
+
|
| 1083 |
+
if use_cache:
|
| 1084 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
| 1085 |
+
|
| 1086 |
+
if output_attentions:
|
| 1087 |
+
all_self_attns += (layer_outputs[1],)
|
| 1088 |
+
|
| 1089 |
+
hidden_states = self.norm(hidden_states)
|
| 1090 |
+
|
| 1091 |
+
# add hidden states from the last decoder layer
|
| 1092 |
+
if output_hidden_states:
|
| 1093 |
+
all_hidden_states += (hidden_states,)
|
| 1094 |
+
|
| 1095 |
+
next_cache = None
|
| 1096 |
+
if use_cache:
|
| 1097 |
+
next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
|
| 1098 |
+
if not return_dict:
|
| 1099 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
| 1100 |
+
return BaseModelOutputWithPast(
|
| 1101 |
+
last_hidden_state=hidden_states,
|
| 1102 |
+
past_key_values=next_cache,
|
| 1103 |
+
hidden_states=all_hidden_states,
|
| 1104 |
+
attentions=all_self_attns,
|
| 1105 |
+
)
|
| 1106 |
+
|
| 1107 |
+
|
| 1108 |
+
class Emu3ForCausalLM(Emu3PreTrainedModel):
|
| 1109 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 1110 |
+
|
| 1111 |
+
def __init__(self, config):
|
| 1112 |
+
super().__init__(config)
|
| 1113 |
+
self.model = Emu3Model(config)
|
| 1114 |
+
self.vocab_size = config.vocab_size
|
| 1115 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1116 |
+
|
| 1117 |
+
# Initialize weights and apply final processing
|
| 1118 |
+
self.post_init()
|
| 1119 |
+
|
| 1120 |
+
def get_input_embeddings(self):
|
| 1121 |
+
return self.model.embed_tokens
|
| 1122 |
+
|
| 1123 |
+
def set_input_embeddings(self, value):
|
| 1124 |
+
self.model.embed_tokens = value
|
| 1125 |
+
|
| 1126 |
+
def get_output_embeddings(self):
|
| 1127 |
+
return self.lm_head
|
| 1128 |
+
|
| 1129 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1130 |
+
self.lm_head = new_embeddings
|
| 1131 |
+
|
| 1132 |
+
def set_decoder(self, decoder):
|
| 1133 |
+
self.model = decoder
|
| 1134 |
+
|
| 1135 |
+
def get_decoder(self):
|
| 1136 |
+
return self.model
|
| 1137 |
+
|
| 1138 |
+
@add_start_docstrings_to_model_forward(EMU3_INPUTS_DOCSTRING)
|
| 1139 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
| 1140 |
+
def forward(
|
| 1141 |
+
self,
|
| 1142 |
+
input_ids: torch.LongTensor = None,
|
| 1143 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1144 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1145 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1146 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1147 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1148 |
+
use_cache: Optional[bool] = None,
|
| 1149 |
+
output_attentions: Optional[bool] = None,
|
| 1150 |
+
output_hidden_states: Optional[bool] = None,
|
| 1151 |
+
return_dict: Optional[bool] = None,
|
| 1152 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 1153 |
+
r"""
|
| 1154 |
+
Args:
|
| 1155 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1156 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1157 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1158 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1159 |
+
|
| 1160 |
+
Returns:
|
| 1161 |
+
|
| 1162 |
+
Example:
|
| 1163 |
+
|
| 1164 |
+
```python
|
| 1165 |
+
>>> from transformers import AutoTokenizer, AutoModel, AutoImageProcessor, AutoModelForCausalLM
|
| 1166 |
+
>>> from transformers.generation.configuration_utils import GenerationConfig
|
| 1167 |
+
>>> from transformers.generation import LogitsProcessorList, PrefixConstrainedLogitsProcessor, UnbatchedClassifierFreeGuidanceLogitsProcessor
|
| 1168 |
+
>>> from transformers import Emu3Processor
|
| 1169 |
+
>>> from PIL import Image
|
| 1170 |
+
|
| 1171 |
+
>>> model = AutoModelForCausalLM.from_pretrained(PATH_TO_CONVERTED_EMU3_WEIGHTS)
|
| 1172 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
| 1173 |
+
>>> image_processor = AutoImageProcessor.from_pretrained(PATH_TO_CONVERTED_IMAGE_PROCESSER)
|
| 1174 |
+
>>> image_tokenizer = AutoModel.from_pretrained(PATH_TO_CONVERTED_TOKENIZER_WEIGHTS).eval()
|
| 1175 |
+
>>> processor = Emu3Processor(image_processor, image_tokenizer, tokenizer)
|
| 1176 |
+
|
| 1177 |
+
>>> # Generation
|
| 1178 |
+
>>> prompt = "An Emu in cartoon style, it is wearing sunglasses."
|
| 1179 |
+
|
| 1180 |
+
>>> pos_inputs = processor(text=prompt, mode='G', ratio="4:3", image_area=model.config.image_area, return_tensors="pt")
|
| 1181 |
+
>>> neg_inputs = processor(text="", mode='G', ratio="4:3", image_area=model.config.image_area, return_tensors="pt")
|
| 1182 |
+
|
| 1183 |
+
>>> GENERATION_CONFIG = GenerationConfig(
|
| 1184 |
+
>>> use_cache=True,
|
| 1185 |
+
>>> eos_token_id=model.config.eos_token_id,
|
| 1186 |
+
>>> pad_token_id=model.config.pad_token_id,
|
| 1187 |
+
>>> max_new_tokens=40960,
|
| 1188 |
+
>>> do_sample=True,
|
| 1189 |
+
>>> top_k=2048,
|
| 1190 |
+
>>> )
|
| 1191 |
+
|
| 1192 |
+
>>> h, w = pos_inputs.image_size[0]
|
| 1193 |
+
>>> constrained_fn = processor.build_prefix_constrained_fn(h, w)
|
| 1194 |
+
>>> logits_processor = LogitsProcessorList([
|
| 1195 |
+
>>> UnbatchedClassifierFreeGuidanceLogitsProcessor(
|
| 1196 |
+
>>> classifier_free_guidance,
|
| 1197 |
+
>>> model,
|
| 1198 |
+
>>> unconditional_ids=neg_inputs.input_ids.to("cuda:0"),
|
| 1199 |
+
>>> ),
|
| 1200 |
+
>>> PrefixConstrainedLogitsProcessor(
|
| 1201 |
+
>>> constrained_fn,
|
| 1202 |
+
>>> num_beams=1,
|
| 1203 |
+
>>> ),
|
| 1204 |
+
>>> ])
|
| 1205 |
+
|
| 1206 |
+
>>> outputs = model.generate(pos_inputs.input_ids.to("cuda:0"), GENERATION_CONFIG, logits_processor=logits_processor)
|
| 1207 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 1208 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 1209 |
+
>>> mm_list = processor.decode(outputs[0])
|
| 1210 |
+
|
| 1211 |
+
>>> # Understanding
|
| 1212 |
+
>>> prompt = "Provide a one-sentence caption for the provided image."
|
| 1213 |
+
>>> image = Image.open(TEST_IMAGE_PATH)
|
| 1214 |
+
|
| 1215 |
+
>>> inputs = processor(text=text, image=image, mode='U', padding_side="left", padding="longest", return_tensors="pt")
|
| 1216 |
+
>>> input_ids = inputs.input_ids.to("cuda:0")
|
| 1217 |
+
>>> GENERATION_CONFIG = GenerationConfig(
|
| 1218 |
+
>>> pad_token_id=tokenizer.pad_token_id,
|
| 1219 |
+
>>> bos_token_id=tokenizer.bos_token_id,
|
| 1220 |
+
>>> eos_token_id=tokenizer.eos_token_id,
|
| 1221 |
+
>>> )
|
| 1222 |
+
|
| 1223 |
+
>>> outputs = model.generate(input_ids, GENERATION_CONFIG, max_new_tokens=100)
|
| 1224 |
+
>>> outputs = outputs[:, input_ids.shape[-1]:]
|
| 1225 |
+
>>> answer = processor.batch_decode(outputs, skip_special_tokens=True)
|
| 1226 |
+
```"""
|
| 1227 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1228 |
+
output_hidden_states = (
|
| 1229 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1230 |
+
)
|
| 1231 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1232 |
+
|
| 1233 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 1234 |
+
outputs = self.model(
|
| 1235 |
+
input_ids=input_ids,
|
| 1236 |
+
attention_mask=attention_mask,
|
| 1237 |
+
position_ids=position_ids,
|
| 1238 |
+
past_key_values=past_key_values,
|
| 1239 |
+
inputs_embeds=inputs_embeds,
|
| 1240 |
+
use_cache=use_cache,
|
| 1241 |
+
output_attentions=output_attentions,
|
| 1242 |
+
output_hidden_states=output_hidden_states,
|
| 1243 |
+
return_dict=return_dict,
|
| 1244 |
+
)
|
| 1245 |
+
|
| 1246 |
+
hidden_states = outputs[0]
|
| 1247 |
+
if self.config.pretraining_tp > 1:
|
| 1248 |
+
lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
|
| 1249 |
+
logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 1250 |
+
logits = torch.cat(logits, dim=-1)
|
| 1251 |
+
else:
|
| 1252 |
+
logits = self.lm_head(hidden_states)
|
| 1253 |
+
logits = logits.float()
|
| 1254 |
+
|
| 1255 |
+
loss = None
|
| 1256 |
+
if labels is not None:
|
| 1257 |
+
# Shift so that tokens < n predict n
|
| 1258 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 1259 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 1260 |
+
# Flatten the tokens
|
| 1261 |
+
loss_fct = CrossEntropyLoss()
|
| 1262 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
| 1263 |
+
shift_labels = shift_labels.view(-1)
|
| 1264 |
+
# Enable model parallelism
|
| 1265 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
| 1266 |
+
loss = loss_fct(shift_logits, shift_labels)
|
| 1267 |
+
|
| 1268 |
+
if not return_dict:
|
| 1269 |
+
output = (logits,) + outputs[1:]
|
| 1270 |
+
return (loss,) + output if loss is not None else output
|
| 1271 |
+
|
| 1272 |
+
return CausalLMOutputWithPast(
|
| 1273 |
+
loss=loss,
|
| 1274 |
+
logits=logits,
|
| 1275 |
+
past_key_values=outputs.past_key_values,
|
| 1276 |
+
hidden_states=outputs.hidden_states,
|
| 1277 |
+
attentions=outputs.attentions,
|
| 1278 |
+
)
|
| 1279 |
+
|
| 1280 |
+
def prepare_inputs_for_generation(
|
| 1281 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
| 1282 |
+
):
|
| 1283 |
+
if past_key_values is not None:
|
| 1284 |
+
if isinstance(past_key_values, Cache):
|
| 1285 |
+
cache_length = past_key_values.get_seq_length()
|
| 1286 |
+
past_length = past_key_values.seen_tokens
|
| 1287 |
+
max_cache_length = past_key_values.get_max_length()
|
| 1288 |
+
else:
|
| 1289 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
| 1290 |
+
max_cache_length = None
|
| 1291 |
+
|
| 1292 |
+
# Keep only the unprocessed tokens:
|
| 1293 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
| 1294 |
+
# some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
|
| 1295 |
+
# input)
|
| 1296 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
| 1297 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
|
| 1298 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
| 1299 |
+
# input_ids based on the past_length.
|
| 1300 |
+
elif past_length < input_ids.shape[1]:
|
| 1301 |
+
input_ids = input_ids[:, past_length:]
|
| 1302 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
| 1303 |
+
|
| 1304 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
| 1305 |
+
if (
|
| 1306 |
+
max_cache_length is not None
|
| 1307 |
+
and attention_mask is not None
|
| 1308 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
| 1309 |
+
):
|
| 1310 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
| 1311 |
+
|
| 1312 |
+
position_ids = kwargs.get("position_ids", None)
|
| 1313 |
+
if attention_mask is not None and position_ids is None:
|
| 1314 |
+
# create position_ids on the fly for batch generation
|
| 1315 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 1316 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 1317 |
+
if past_key_values:
|
| 1318 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
| 1319 |
+
|
| 1320 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
| 1321 |
+
if inputs_embeds is not None and past_key_values is None:
|
| 1322 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
| 1323 |
+
else:
|
| 1324 |
+
model_inputs = {"input_ids": input_ids}
|
| 1325 |
+
|
| 1326 |
+
model_inputs.update(
|
| 1327 |
+
{
|
| 1328 |
+
"position_ids": position_ids,
|
| 1329 |
+
"past_key_values": past_key_values,
|
| 1330 |
+
"use_cache": kwargs.get("use_cache"),
|
| 1331 |
+
"attention_mask": attention_mask,
|
| 1332 |
+
}
|
| 1333 |
+
)
|
| 1334 |
+
return model_inputs
|
| 1335 |
+
|
| 1336 |
+
@staticmethod
|
| 1337 |
+
def _reorder_cache(past_key_values, beam_idx):
|
| 1338 |
+
reordered_past = ()
|
| 1339 |
+
for layer_past in past_key_values:
|
| 1340 |
+
reordered_past += (
|
| 1341 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
| 1342 |
+
)
|
| 1343 |
+
return reordered_past
|
sjdtree/emu3/m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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The Emu team, BAAI and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Processor class for Emu3. """
|
| 16 |
+
|
| 17 |
+
import re
|
| 18 |
+
from typing import List, Optional, Sequence, Union
|
| 19 |
+
from functools import partial
|
| 20 |
+
|
| 21 |
+
from PIL import Image
|
| 22 |
+
import torch
|
| 23 |
+
from transformers.feature_extraction_utils import BatchFeature
|
| 24 |
+
from transformers.image_utils import ImageInput, get_image_size, to_numpy_array
|
| 25 |
+
from transformers.processing_utils import ProcessingKwargs, ProcessorMixin
|
| 26 |
+
from transformers.tokenization_utils_base import TextInput, PreTokenizedInput
|
| 27 |
+
from transformers.utils import logging
|
| 28 |
+
|
| 29 |
+
from .utils_emu3 import Emu3PrefixConstrainedLogitsHelper
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class Emu3Processor(ProcessorMixin):
|
| 36 |
+
r"""
|
| 37 |
+
Constructs an Emu3 processor which wraps an Emu3 image processor and an Emu3 vision vq model and an Emu3 tokenizer into a single processor.
|
| 38 |
+
|
| 39 |
+
[`Emu3Processor`] offers all the functionalities of [`Emu3VisionVQModel`] and [`Emu3Tokenizer`]. See the
|
| 40 |
+
[`~Emu3Processor.__call__`], [`~Emu3Processor.decode`], [`~Emu3Processor.vision_encode`], [`~Emu3Processor.vision_decode`]
|
| 41 |
+
for more information.
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
image_processor ([`Emu3VisionVQImageProcessor`]):
|
| 45 |
+
The image processor is a required input.
|
| 46 |
+
vision_tokenizer ([`Emu3VisionVQModel`]):
|
| 47 |
+
The vision tokenizer is a required input.
|
| 48 |
+
tokenizer ([`Emu3Tokenizer`]):
|
| 49 |
+
The tokenizer is a required input.
|
| 50 |
+
prefix_template(`str`, *optional*):
|
| 51 |
+
The prefix template for image tokens
|
| 52 |
+
visual_template(`Tuple[str, ...]`, *optional*):
|
| 53 |
+
The visual token template for image tokens
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
attributes = ["image_processor", "tokenizer"]
|
| 57 |
+
valid_kwargs = ["vision_tokenizer", "prefix_template", "visual_template"]
|
| 58 |
+
image_processor_class = "AutoImageProcessor"
|
| 59 |
+
tokenizer_class = "AutoTokenizer"
|
| 60 |
+
|
| 61 |
+
def __init__(
|
| 62 |
+
self,
|
| 63 |
+
image_processor=None,
|
| 64 |
+
vision_tokenizer=None,
|
| 65 |
+
tokenizer=None,
|
| 66 |
+
chat_template="You are a helpful assistant. USER: {image_prompt}{text_prompt}. ASSISTANT:",
|
| 67 |
+
prefix_template="{H}*{W}",
|
| 68 |
+
visual_template=("<|visual token {token_id:0>6d}|>", r"<\|visual token (\d+)\|>"),
|
| 69 |
+
**kwargs,
|
| 70 |
+
):
|
| 71 |
+
assert vision_tokenizer is not None, "image tokenizer can not be None"
|
| 72 |
+
|
| 73 |
+
self.vision_tokenizer = vision_tokenizer
|
| 74 |
+
self.prefix_template = prefix_template
|
| 75 |
+
self.visual_template = visual_template
|
| 76 |
+
|
| 77 |
+
super().__init__(image_processor, tokenizer, chat_template=chat_template)
|
| 78 |
+
self.const_helper = self.build_const_helper()
|
| 79 |
+
|
| 80 |
+
@torch.no_grad()
|
| 81 |
+
def __call__(
|
| 82 |
+
self,
|
| 83 |
+
text = None,
|
| 84 |
+
image = None,
|
| 85 |
+
*,
|
| 86 |
+
mode: str = "G",
|
| 87 |
+
ratio: str = "1:1",
|
| 88 |
+
image_area: int = 518400,
|
| 89 |
+
frame_number: int = 1,
|
| 90 |
+
**kwargs,
|
| 91 |
+
) -> BatchFeature:
|
| 92 |
+
"""
|
| 93 |
+
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
|
| 94 |
+
and `kwargs` arguments to Emu3Tokenizer's [`~Emu3Tokenizer.__call__`] to encode the text.
|
| 95 |
+
To prepare the image(s), this method forwards the `image` argument to
|
| 96 |
+
Emu3VisionVQImageProcessor's [`~Emu3VisionVQImageProcessor.__call__`] and Emu3VisionVQModel's [`~EmuVideoVQModel.encode`]
|
| 97 |
+
if `image` is not `None`. Please refer to the doctsring of the above two methods for more information.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
text (`str` or `List[str]`):
|
| 101 |
+
The sequence or a batch of sequence to be encoded. A sequence is a string.
|
| 102 |
+
image (`PIL.Image.Image` or `List[PIL.Image.Image]`, *optional*):
|
| 103 |
+
The image or a batch of images to be prepared. An image is a PIL image.
|
| 104 |
+
mode (`str`, *optional*, in `G` or `U`):
|
| 105 |
+
task mode, `G` for generation and `U` for understanding
|
| 106 |
+
ratio (`str`, *optional*):
|
| 107 |
+
the image width-height ratio for generation
|
| 108 |
+
image_area (`int`, *optional*):
|
| 109 |
+
image area used to calcualte the generated image height and width
|
| 110 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 111 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 112 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 113 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 114 |
+
|
| 115 |
+
Returns:
|
| 116 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 117 |
+
|
| 118 |
+
- **input_ids** -- List of token ids to be fed to a model.
|
| 119 |
+
- **image_size** -- List of image size of input images or generated images.
|
| 120 |
+
"""
|
| 121 |
+
assert mode in ('G', 'U', 'VG'), "mode must be 'G', 'VG' or 'U'."
|
| 122 |
+
if isinstance(text, str):
|
| 123 |
+
text = [text]
|
| 124 |
+
|
| 125 |
+
if not isinstance(text[0], str):
|
| 126 |
+
raise ValueError("`text` must be string or list of string")
|
| 127 |
+
|
| 128 |
+
image_inputs = None
|
| 129 |
+
if mode == 'G' or mode == 'VG':
|
| 130 |
+
if image is not None:
|
| 131 |
+
raise ValueError("You have to specify only `text` in generation mode")
|
| 132 |
+
|
| 133 |
+
if len(text) > 1:
|
| 134 |
+
raise ValueError("`text` can only be `str` in generation mode")
|
| 135 |
+
else:
|
| 136 |
+
if image is None:
|
| 137 |
+
raise ValueError("Invalid input image. Please provide exactly one PIL.Image.Image per text.")
|
| 138 |
+
|
| 139 |
+
if not isinstance(image, Sequence) and not isinstance(image, Image.Image):
|
| 140 |
+
raise ValueError("Invalid input image. Please provide PIL.Image.Image or List[PIL.Image.Image].")
|
| 141 |
+
|
| 142 |
+
if isinstance(image, Sequence) and not isinstance(image[0], Image.Image):
|
| 143 |
+
raise ValueError("Invalid input image. Please provide PIL.Image.Image or List[PIL.Image.Image].")
|
| 144 |
+
|
| 145 |
+
image_inputs = self.image_processor(image, return_tensors="pt")["pixel_values"]
|
| 146 |
+
print(image_inputs.shape)
|
| 147 |
+
image_inputs = image_inputs.to(self.vision_tokenizer.device, self.vision_tokenizer.dtype)
|
| 148 |
+
image_tokens = self.vision_tokenizer.encode(image_inputs)
|
| 149 |
+
|
| 150 |
+
if len(text) != len(image_tokens):
|
| 151 |
+
raise ValueError("number of image must match number of text prompt")
|
| 152 |
+
|
| 153 |
+
prompt_list, size_list = [], []
|
| 154 |
+
for idx, text_prompt in enumerate(text):
|
| 155 |
+
prompt = self.tokenizer.bos_token
|
| 156 |
+
if mode == 'U':
|
| 157 |
+
h, w = image_tokens[idx].shape
|
| 158 |
+
imgstr = self.to_imgstr(image_tokens[idx])
|
| 159 |
+
image_prompt = (
|
| 160 |
+
self.tokenizer.boi_token +
|
| 161 |
+
self.prefix_template.format(H=h, W=w) +
|
| 162 |
+
self.tokenizer.img_token +
|
| 163 |
+
imgstr +
|
| 164 |
+
self.tokenizer.eol_token +
|
| 165 |
+
self.tokenizer.eof_token +
|
| 166 |
+
self.tokenizer.eoi_token
|
| 167 |
+
)
|
| 168 |
+
prompt += self.chat_template.format(image_prompt=image_prompt, text_prompt=text_prompt)
|
| 169 |
+
if mode == 'VG':
|
| 170 |
+
h, w = self.calculate_generate_size(ratio, image_area, self.vision_tokenizer.spatial_scale_factor)
|
| 171 |
+
image_prompt = (
|
| 172 |
+
self.tokenizer.boi_token +
|
| 173 |
+
self.prefix_template.format(H=h, W=w, F=frame_number) +
|
| 174 |
+
self.tokenizer.img_token
|
| 175 |
+
)
|
| 176 |
+
prompt += (text_prompt + image_prompt)
|
| 177 |
+
else:
|
| 178 |
+
h, w = self.calculate_generate_size(ratio, image_area, self.vision_tokenizer.spatial_scale_factor)
|
| 179 |
+
image_prompt = (
|
| 180 |
+
self.tokenizer.boi_token +
|
| 181 |
+
self.prefix_template.format(H=h, W=w) +
|
| 182 |
+
self.tokenizer.img_token
|
| 183 |
+
)
|
| 184 |
+
prompt += (text_prompt + image_prompt)
|
| 185 |
+
|
| 186 |
+
prompt_list.append(prompt)
|
| 187 |
+
size_list.append([h, w])
|
| 188 |
+
|
| 189 |
+
text_inputs = self.tokenizer(prompt_list, **kwargs)
|
| 190 |
+
return BatchFeature(data={**text_inputs, "image_size": size_list}, tensor_type=kwargs.get("return_tensors"))
|
| 191 |
+
|
| 192 |
+
@torch.no_grad()
|
| 193 |
+
def batch_decode(self, *args, **kwargs):
|
| 194 |
+
docs = self.tokenizer.batch_decode(*args, **kwargs)
|
| 195 |
+
return [self.multimodal_decode(d) for d in docs]
|
| 196 |
+
|
| 197 |
+
@torch.no_grad()
|
| 198 |
+
def decode(self, *args, **kwargs):
|
| 199 |
+
doc = self.tokenizer.decode(*args, **kwargs)
|
| 200 |
+
return self.multimodal_decode(doc)
|
| 201 |
+
|
| 202 |
+
@torch.no_grad()
|
| 203 |
+
def vision_encode(self, *args, **kwargs):
|
| 204 |
+
return self.vision_tokenizer.encode(*args, **kwargs)
|
| 205 |
+
|
| 206 |
+
@torch.no_grad()
|
| 207 |
+
def vision_decode(self, *args, **kwargs):
|
| 208 |
+
return self.vision_tokenizer.decode(*args, **kwargs)
|
| 209 |
+
|
| 210 |
+
@torch.no_grad()
|
| 211 |
+
def multimodal_decode(self, doc):
|
| 212 |
+
multimodal_output = []
|
| 213 |
+
pattern = rf'({re.escape(self.tokenizer.boi_token)}.*?{re.escape(self.tokenizer.eoi_token)})'
|
| 214 |
+
chunks = re.split(pattern, doc)
|
| 215 |
+
for c in chunks:
|
| 216 |
+
if len(c) == 0:
|
| 217 |
+
continue
|
| 218 |
+
|
| 219 |
+
if self.tokenizer.boi_token in c:
|
| 220 |
+
image = []
|
| 221 |
+
image_rows = re.split(re.escape(self.tokenizer.eol_token), c)
|
| 222 |
+
for r in image_rows:
|
| 223 |
+
token_ids = re.findall(self.visual_template[1], r)
|
| 224 |
+
if len(token_ids) > 0:
|
| 225 |
+
row_token = [int(m) for m in token_ids]
|
| 226 |
+
image.append(row_token)
|
| 227 |
+
image = torch.tensor(image, dtype=torch.long, device=self.vision_tokenizer.device)
|
| 228 |
+
image = self.vision_tokenizer.decode(image[None]).float()
|
| 229 |
+
image = self.image_processor.postprocess(image)["pixel_values"][0]
|
| 230 |
+
multimodal_output.append(image)
|
| 231 |
+
else:
|
| 232 |
+
multimodal_output.append(c)
|
| 233 |
+
|
| 234 |
+
return multimodal_output if len(multimodal_output) > 1 else multimodal_output[0]
|
| 235 |
+
|
| 236 |
+
@property
|
| 237 |
+
def model_input_names(self):
|
| 238 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
| 239 |
+
image_processor_input_names = self.image_processor.model_input_names
|
| 240 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
| 241 |
+
|
| 242 |
+
def to_imgstr(self, image_tokens):
|
| 243 |
+
image_tokens = image_tokens.cpu().numpy().tolist()
|
| 244 |
+
image_token_str = [
|
| 245 |
+
[
|
| 246 |
+
self.visual_template[0].format(token_id=token_id)
|
| 247 |
+
for token_id in token_row
|
| 248 |
+
]
|
| 249 |
+
for token_row in image_tokens
|
| 250 |
+
]
|
| 251 |
+
image_row_str = ["".join(token_row) for token_row in image_token_str]
|
| 252 |
+
imgstr = self.tokenizer.eol_token.join(image_row_str)
|
| 253 |
+
return imgstr
|
| 254 |
+
|
| 255 |
+
def calculate_generate_size(self, ratio, image_area, spatial_scale_factor):
|
| 256 |
+
w, h = map(int, ratio.split(":"))
|
| 257 |
+
current_area = h * w
|
| 258 |
+
target_ratio = (image_area / current_area) ** 0.5
|
| 259 |
+
|
| 260 |
+
th = int(round(h * target_ratio / spatial_scale_factor))
|
| 261 |
+
tw = int(round(w * target_ratio / spatial_scale_factor))
|
| 262 |
+
return th, tw
|
| 263 |
+
|
| 264 |
+
def build_const_helper(self):
|
| 265 |
+
(
|
| 266 |
+
img_token,
|
| 267 |
+
eoi_token,
|
| 268 |
+
eos_token,
|
| 269 |
+
eol_token,
|
| 270 |
+
eof_token,
|
| 271 |
+
pad_token,
|
| 272 |
+
vis_start,
|
| 273 |
+
vis_end,
|
| 274 |
+
) = self.tokenizer.encode([
|
| 275 |
+
self.tokenizer.img_token,
|
| 276 |
+
self.tokenizer.eoi_token,
|
| 277 |
+
self.tokenizer.eos_token,
|
| 278 |
+
self.tokenizer.eol_token,
|
| 279 |
+
self.tokenizer.eof_token,
|
| 280 |
+
self.tokenizer.pad_token,
|
| 281 |
+
self.visual_template[0].format(token_id=0),
|
| 282 |
+
self.visual_template[0].format(token_id=self.vision_tokenizer.config.codebook_size - 1),
|
| 283 |
+
])
|
| 284 |
+
|
| 285 |
+
const_helper = partial(
|
| 286 |
+
Emu3PrefixConstrainedLogitsHelper,
|
| 287 |
+
img_token=img_token,
|
| 288 |
+
eoi_token=eoi_token,
|
| 289 |
+
eos_token=eos_token,
|
| 290 |
+
eol_token=eol_token,
|
| 291 |
+
eof_token=eof_token,
|
| 292 |
+
pad_token=pad_token,
|
| 293 |
+
visual_tokens=list(range(vis_start, vis_end + 1)),
|
| 294 |
+
)
|
| 295 |
+
return const_helper
|
| 296 |
+
|
| 297 |
+
def build_prefix_constrained_fn(self, height,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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The Emu team, BAAI and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization classes for Emu3."""
|
| 16 |
+
|
| 17 |
+
import base64
|
| 18 |
+
import logging
|
| 19 |
+
import os
|
| 20 |
+
import unicodedata
|
| 21 |
+
from typing import Collection, Dict, List, Optional, Set, Tuple, Union
|
| 22 |
+
|
| 23 |
+
import tiktoken
|
| 24 |
+
from transformers import PreTrainedTokenizer, AddedToken
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
VOCAB_FILES_NAMES = {
|
| 30 |
+
"vocab_file": "emu3.tiktoken",
|
| 31 |
+
"special_tokens_file": "emu3_vision_tokens.txt",
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
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+"""
|
| 35 |
+
ENDOFTEXT = "<|endoftext|>"
|
| 36 |
+
IMSTART = "<|im_start|>"
|
| 37 |
+
IMEND = "<|im_end|>"
|
| 38 |
+
# as the default behavior is changed to allow special tokens in
|
| 39 |
+
# regular texts, the surface forms of special tokens need to be
|
| 40 |
+
# as different as possible to minimize the impact
|
| 41 |
+
EXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))
|
| 42 |
+
# changed to use actual index to avoid misconfiguration with vocabulary expansion
|
| 43 |
+
SPECIAL_START_ID = 151643
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]:
|
| 47 |
+
with open(tiktoken_bpe_file, "rb") as f:
|
| 48 |
+
contents = f.read()
|
| 49 |
+
return {
|
| 50 |
+
base64.b64decode(token): int(rank)
|
| 51 |
+
for token, rank in (line.split() for line in contents.splitlines() if line)
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class Emu3Tokenizer(PreTrainedTokenizer):
|
| 56 |
+
"""Emu3 tokenizer."""
|
| 57 |
+
|
| 58 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 59 |
+
|
| 60 |
+
def __init__(
|
| 61 |
+
self,
|
| 62 |
+
vocab_file,
|
| 63 |
+
special_tokens_file,
|
| 64 |
+
errors="replace",
|
| 65 |
+
bos_token = "<|extra_203|>",
|
| 66 |
+
eos_token = "<|extra_204|>",
|
| 67 |
+
pad_token = "<|endoftext|>",
|
| 68 |
+
img_token = "<|image token|>",
|
| 69 |
+
boi_token = "<|image start|>",
|
| 70 |
+
eoi_token = "<|image end|>",
|
| 71 |
+
eol_token = "<|extra_200|>",
|
| 72 |
+
eof_token = "<|extra_201|>",
|
| 73 |
+
**kwargs,
|
| 74 |
+
):
|
| 75 |
+
super().__init__(**kwargs)
|
| 76 |
+
|
| 77 |
+
# how to handle errors in decoding UTF-8 byte sequences
|
| 78 |
+
# use ignore if you are in streaming inference
|
| 79 |
+
self.errors = errors
|
| 80 |
+
|
| 81 |
+
self.mergeable_ranks = _load_tiktoken_bpe(vocab_file)
|
| 82 |
+
|
| 83 |
+
vision_tokens = [t.strip() for t in open(special_tokens_file).readlines() if len(t.strip()) > 0]
|
| 84 |
+
SPECIAL_TOKENS = tuple(
|
| 85 |
+
enumerate(
|
| 86 |
+
(
|
| 87 |
+
(
|
| 88 |
+
ENDOFTEXT,
|
| 89 |
+
IMSTART,
|
| 90 |
+
IMEND,
|
| 91 |
+
)
|
| 92 |
+
+ EXTRAS
|
| 93 |
+
+ tuple(vision_tokens)
|
| 94 |
+
),
|
| 95 |
+
start=SPECIAL_START_ID,
|
| 96 |
+
)
|
| 97 |
+
)
|
| 98 |
+
self.special_tokens = {token: index for index, token in SPECIAL_TOKENS}
|
| 99 |
+
self.special_tokens_set = set(t for _, t in SPECIAL_TOKENS)
|
| 100 |
+
|
| 101 |
+
enc = tiktoken.Encoding(
|
| 102 |
+
"Emu3",
|
| 103 |
+
pat_str=PAT_STR,
|
| 104 |
+
mergeable_ranks=self.mergeable_ranks,
|
| 105 |
+
special_tokens=self.special_tokens,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
assert (
|
| 109 |
+
len(self.mergeable_ranks) + len(self.special_tokens) == enc.n_vocab
|
| 110 |
+
), f"{len(self.mergeable_ranks) + len(self.special_tokens)} != {enc.n_vocab} in encoding"
|
| 111 |
+
|
| 112 |
+
self.decoder = {
|
| 113 |
+
v: k for k, v in self.mergeable_ranks.items()
|
| 114 |
+
}
|
| 115 |
+
self.decoder.update({v: k for k, v in self.special_tokens.items()})
|
| 116 |
+
|
| 117 |
+
self.tokenizer = enc
|
| 118 |
+
|
| 119 |
+
self.eod_id = self.tokenizer.eot_token
|
| 120 |
+
self.bos_token = bos_token
|
| 121 |
+
self.eos_token = eos_token
|
| 122 |
+
self.pad_token = pad_token
|
| 123 |
+
self.img_token = img_token
|
| 124 |
+
self.boi_token = boi_token
|
| 125 |
+
self.eoi_token = eoi_token
|
| 126 |
+
self.eol_token = eol_token
|
| 127 |
+
self.eof_token = eof_token
|
| 128 |
+
|
| 129 |
+
def __getstate__(self):
|
| 130 |
+
# for pickle lovers
|
| 131 |
+
state = self.__dict__.copy()
|
| 132 |
+
del state["tokenizer"]
|
| 133 |
+
return state
|
| 134 |
+
|
| 135 |
+
def __setstate__(self, state):
|
| 136 |
+
# tokenizer is not python native; don't pass it; rebuild it
|
| 137 |
+
self.__dict__.update(state)
|
| 138 |
+
enc = tiktoken.Encoding(
|
| 139 |
+
"Emu3",
|
| 140 |
+
pat_str=PAT_STR,
|
| 141 |
+
mergeable_ranks=self.mergeable_ranks,
|
| 142 |
+
special_tokens=self.special_tokens,
|
| 143 |
+
)
|
| 144 |
+
self.tokenizer = enc
|
| 145 |
+
|
| 146 |
+
def __len__(self) -> int:
|
| 147 |
+
return self.tokenizer.n_vocab
|
| 148 |
+
|
| 149 |
+
def get_vocab(self) -> Dict[bytes, int]:
|
| 150 |
+
return self.mergeable_ranks
|
| 151 |
+
|
| 152 |
+
def convert_tokens_to_ids(
|
| 153 |
+
self, tokens: Union[bytes, str, List[Union[bytes, str]]]
|
| 154 |
+
) -> List[int]:
|
| 155 |
+
if isinstance(tokens, (str, bytes)):
|
| 156 |
+
if tokens in self.special_tokens:
|
| 157 |
+
return self.special_tokens[tokens]
|
| 158 |
+
else:
|
| 159 |
+
return self.mergeable_ranks.get(tokens)
|
| 160 |
+
|
| 161 |
+
ids = []
|
| 162 |
+
for token in tokens:
|
| 163 |
+
if token in self.special_tokens:
|
| 164 |
+
ids.append(self.special_tokens[token])
|
| 165 |
+
else:
|
| 166 |
+
ids.append(self.mergeable_ranks.get(token))
|
| 167 |
+
return ids
|
| 168 |
+
|
| 169 |
+
def _add_tokens(
|
| 170 |
+
self,
|
| 171 |
+
new_tokens: Union[List[str], List[AddedToken]],
|
| 172 |
+
special_tokens: bool = False,
|
| 173 |
+
) -> int:
|
| 174 |
+
if not special_tokens and new_tokens:
|
| 175 |
+
raise ValueError("Adding regular tokens is not supported")
|
| 176 |
+
|
| 177 |
+
for token in new_tokens:
|
| 178 |
+
surface_form = token.content if isinstance(token, AddedToken) else token
|
| 179 |
+
if surface_form not in self.special_tokens_set:
|
| 180 |
+
raise ValueError("Adding unknown special tokens is not supported")
|
| 181 |
+
|
| 182 |
+
return 0
|
| 183 |
+
|
| 184 |
+
def save_vocabulary(self, save_directory: str, **kwargs) -> Tuple[str]:
|
| 185 |
+
"""
|
| 186 |
+
Save only the vocabulary of the tokenizer (vocabulary).
|
| 187 |
+
|
| 188 |
+
Returns:
|
| 189 |
+
`Tuple(str)`: Paths to the files saved.
|
| 190 |
+
"""
|
| 191 |
+
regular_file_path = os.path.join(save_directory, self.vocab_files_names["vocab_file"])
|
| 192 |
+
with open(regular_file_path,'w', encoding="utf8") as w:
|
| 193 |
+
for k, v in self.mergeable_ranks.items():
|
| 194 |
+
line = base64.b64encode(k).decode("utf8") + " " + str(v) + "\n"
|
| 195 |
+
w.write(line)
|
| 196 |
+
|
| 197 |
+
excluded_special_tokens = set((ENDOFTEXT, IMSTART, IMEND,) + EXTRAS)
|
| 198 |
+
special_file_path = os.path.join(save_directory, self.vocab_files_names["special_tokens_file"])
|
| 199 |
+
with open(special_file_path, 'w', encoding="utf8") as w:
|
| 200 |
+
for k in self.special_tokens:
|
| 201 |
+
if k not in excluded_special_tokens:
|
| 202 |
+
print(k, file=w)
|
| 203 |
+
|
| 204 |
+
return (regular_file_path, special_file_path)
|
| 205 |
+
|
| 206 |
+
def tokenize(
|
| 207 |
+
self,
|
| 208 |
+
text: str,
|
| 209 |
+
allowed_special: Union[Set, str] = "all",
|
| 210 |
+
disallowed_special: Union[Collection, str] = (),
|
| 211 |
+
**kwargs,
|
| 212 |
+
) -> List[Union[bytes, str]]:
|
| 213 |
+
"""
|
| 214 |
+
Converts a string in a sequence of tokens.
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
text (`str`):
|
| 218 |
+
The sequence to be encoded.
|
| 219 |
+
allowed_special (`Literal["all"]` or `set`):
|
| 220 |
+
The surface forms of the tokens to be encoded as special tokens in regular texts.
|
| 221 |
+
Default to "all".
|
| 222 |
+
disallowed_special (`Literal["all"]` or `Collection`):
|
| 223 |
+
The surface forms of the tokens that should not be in regular texts and trigger errors.
|
| 224 |
+
Default to an empty tuple.
|
| 225 |
+
|
| 226 |
+
kwargs (additional keyword arguments, *optional*):
|
| 227 |
+
Will be passed to the underlying model specific encode method.
|
| 228 |
+
|
| 229 |
+
Returns:
|
| 230 |
+
`List[bytes|str]`: The list of tokens.
|
| 231 |
+
"""
|
| 232 |
+
tokens = []
|
| 233 |
+
text = unicodedata.normalize("NFC", text)
|
| 234 |
+
|
| 235 |
+
# this implementation takes a detour: text -> token id -> token surface forms
|
| 236 |
+
for t in self.tokenizer.encode(
|
| 237 |
+
text, allowed_special=allowed_special, disallowed_special=disallowed_special
|
| 238 |
+
):
|
| 239 |
+
tokens.append(self.decoder[t])
|
| 240 |
+
|
| 241 |
+
return tokens
|
| 242 |
+
|
| 243 |
+
def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str:
|
| 244 |
+
"""
|
| 245 |
+
Converts a sequence of tokens in a single string.
|
| 246 |
+
"""
|
| 247 |
+
text = ""
|
| 248 |
+
temp = b""
|
| 249 |
+
for t in tokens:
|
| 250 |
+
if isinstance(t, str):
|
| 251 |
+
if temp:
|
| 252 |
+
text += temp.decode("utf-8", errors=self.errors)
|
| 253 |
+
temp = b""
|
| 254 |
+
text += t
|
| 255 |
+
elif isinstance(t, bytes):
|
| 256 |
+
temp += t
|
| 257 |
+
else:
|
| 258 |
+
raise TypeError("token should only be of type types or str")
|
| 259 |
+
if temp:
|
| 260 |
+
text += temp.decode("utf-8", errors=self.errors)
|
| 261 |
+
return text
|
| 262 |
+
|
| 263 |
+
@property
|
| 264 |
+
def vocab_size(self):
|
| 265 |
+
return self.tokenizer.n_vocab
|
| 266 |
+
|
| 267 |
+
def _convert_id_to_token(self, index: int) -> Union[bytes, str]:
|
| 268 |
+
"""Converts an id to a token, special tokens included"""
|
| 269 |
+
if index in self.decoder:
|
| 270 |
+
return self.decoder[index]
|
| 271 |
+
raise ValueError("unknown ids")
|
| 272 |
+
|
| 273 |
+
def _convert_token_to_id(self, token: Union[bytes, str]) -> int:
|
| 274 |
+
"""Converts a token to an id using the vocab, special tokens included"""
|
| 275 |
+
if token in self.special_tokens:
|
| 276 |
+
return self.special_tokens[token]
|
| 277 |
+
if token in self.mergeable_ranks:
|
| 278 |
+
return self.mergeable_ranks[token]
|
| 279 |
+
raise ValueError("unknown token")
|
| 280 |
+
|
| 281 |
+
def _decode(
|
| 282 |
+
self,
|
| 283 |
+
token_ids: Union[int, List[int]],
|
| 284 |
+
skip_special_tokens: bool = False,
|
| 285 |
+
errors: Optional[str] = None,
|
| 286 |
+
**kwargs,
|
| 287 |
+
) -> str:
|
| 288 |
+
if isinstance(token_ids, int):
|
| 289 |
+
token_ids = [token_ids]
|
| 290 |
+
|
| 291 |
+
if skip_special_tokens:
|
| 292 |
+
token_ids = [i for i in token_ids if i < self.eod_id]
|
| 293 |
+
|
| 294 |
+
return self.tokenizer.decode(token_ids, errors=errors or self.errors)
|
sjdtree/emu3/mllm/utils_emu3.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The Emu team, BAAI and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Logits Processor Helper class for Emu3. """
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
class Emu3PrefixConstrainedLogitsHelper:
|
| 20 |
+
|
| 21 |
+
def __init__(
|
| 22 |
+
self,
|
| 23 |
+
height,
|
| 24 |
+
width,
|
| 25 |
+
img_token,
|
| 26 |
+
eoi_token,
|
| 27 |
+
eos_token,
|
| 28 |
+
eol_token,
|
| 29 |
+
eof_token,
|
| 30 |
+
pad_token,
|
| 31 |
+
visual_tokens,
|
| 32 |
+
):
|
| 33 |
+
self.height = height
|
| 34 |
+
self.width = width
|
| 35 |
+
self.img_token = img_token
|
| 36 |
+
self.eoi_token = eoi_token
|
| 37 |
+
self.eos_token = eos_token
|
| 38 |
+
self.eol_token = eol_token
|
| 39 |
+
self.eof_token = eof_token
|
| 40 |
+
self.pad_token = pad_token
|
| 41 |
+
self.visual_tokens = visual_tokens
|
| 42 |
+
|
| 43 |
+
self.offset_cache = {}
|
| 44 |
+
|
| 45 |
+
def __call__(self, batch_id, input_ids):
|
| 46 |
+
if batch_id not in self.offset_cache:
|
| 47 |
+
position = torch.nonzero(input_ids == self.img_token, as_tuple=True)[0][0]
|
| 48 |
+
self.offset_cache[batch_id] = position
|
| 49 |
+
|
| 50 |
+
offset = input_ids.shape[0] - self.offset_cache[batch_id]
|
| 51 |
+
if offset % (self.width + 1) == 0:
|
| 52 |
+
return (self.eol_token, )
|
| 53 |
+
elif offset == (self.width + 1) * self.height + 1:
|
| 54 |
+
return (self.eof_token, )
|
| 55 |
+
elif offset == (self.width + 1) * self.height + 2:
|
| 56 |
+
return (self.eoi_token, )
|
| 57 |
+
elif offset == (self.width + 1) * self.height + 3:
|
| 58 |
+
return (self.eos_token, )
|
| 59 |
+
elif offset > (self.width + 1) * self.height + 3:
|
| 60 |
+
return (self.pad_token, )
|
| 61 |
+
else:
|
| 62 |
+
return self.visual_tokens
|
sjdtree/emu3/tokenizer/__init__.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 BAAI and the HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from transformers.utils import (
|
| 17 |
+
OptionalDependencyNotAvailable,
|
| 18 |
+
_LazyModule,
|
| 19 |
+
is_torch_available,
|
| 20 |
+
is_vision_available,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
_import_structure = {"configuration_emu3visionvq": ["Emu3VisionVQConfig"]}
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
if not is_torch_available():
|
| 28 |
+
raise OptionalDependencyNotAvailable()
|
| 29 |
+
except OptionalDependencyNotAvailable:
|
| 30 |
+
pass
|
| 31 |
+
else:
|
| 32 |
+
_import_structure["modeling_emu3visionvq"] = [
|
| 33 |
+
"Emu3VisionVQModel",
|
| 34 |
+
"Emu3VisionVQPretrainedModel",
|
| 35 |
+
]
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
if not is_vision_available():
|
| 39 |
+
raise OptionalDependencyNotAvailable()
|
| 40 |
+
except OptionalDependencyNotAvailable:
|
| 41 |
+
pass
|
| 42 |
+
else:
|
| 43 |
+
_import_structure["image_processing_emu3visionvq"] = ["Emu3VisionVQImageProcessor"]
|
| 44 |
+
|
| 45 |
+
if TYPE_CHECKING:
|
| 46 |
+
from .configuration_emu3visionvq import Emu3VisionVQConfig
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
if not is_torch_available():
|
| 50 |
+
raise OptionalDependencyNotAvailable()
|
| 51 |
+
except OptionalDependencyNotAvailable:
|
| 52 |
+
pass
|
| 53 |
+
else:
|
| 54 |
+
from .modeling_emu3visionvq import (
|
| 55 |
+
Emu3VisionVQModel,
|
| 56 |
+
Emu3VisionVQPretrainedModel,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
try:
|
| 60 |
+
if not is_vision_available():
|
| 61 |
+
raise OptionalDependencyNotAvailable()
|
| 62 |
+
except OptionalDependencyNotAvailable:
|
| 63 |
+
pass
|
| 64 |
+
else:
|
| 65 |
+
from .image_processing_emu3visionvq import Emu3VisionVQImageProcessor
|
| 66 |
+
|
| 67 |
+
else:
|
| 68 |
+
import sys
|
| 69 |
+
|
| 70 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure)
|
sjdtree/emu3/tokenizer/configuration_emu3visionvq.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The Emu team, BAAI and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Emu3VisionVQ model configuration """
|
| 16 |
+
|
| 17 |
+
from typing import List
|
| 18 |
+
|
| 19 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 20 |
+
from transformers.utils import logging
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Emu3VisionVQConfig(PretrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
This is the configuration class to store the configuration of a [`Emu3VisionVQ`]. It is used to instantiate an video movq
|
| 29 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 30 |
+
defaults will yield a configuration to the VQ model presented in Emu3 paper.
|
| 31 |
+
|
| 32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 33 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
codebook_size (`int`, *optional*, defaults to 32768):
|
| 38 |
+
Codebook size of the VQ model.
|
| 39 |
+
embed_dim (`int`, *optional*, defaults to 4):
|
| 40 |
+
Dimension of the quantized vector in codebook.
|
| 41 |
+
z_channels (`int`, *optional*, defaults to 4):
|
| 42 |
+
Dimension of the output channel of encoder and the input channel of decoder
|
| 43 |
+
double_z (`bool`, *optional*, defaults to False):
|
| 44 |
+
Whether double the output dim of the encoder.
|
| 45 |
+
in_channels (`int`, *optional*, defaults to 3):
|
| 46 |
+
Input channel of encoder.
|
| 47 |
+
out_channels (`int`, *optional*, defaults to 3):
|
| 48 |
+
Output channel of decoder.
|
| 49 |
+
temporal_downsample_factor (`int`, *optional*, defaults to 4):
|
| 50 |
+
Temporal downsample factor.
|
| 51 |
+
ch (`int`, *optional*, defaults to 256):
|
| 52 |
+
Basic channel number of the intermediate blocks.
|
| 53 |
+
ch_mult (`List[int]`, *optional*, defaults to `[1, 2, 2, 4]`):
|
| 54 |
+
Channel scaling factor of the intermediate blocks.
|
| 55 |
+
num_res_blocks (`int`, *optional*, defaults to 2):
|
| 56 |
+
Residual block number in each stage.
|
| 57 |
+
attn_resolutions (`List[int]`, *optional*, defaults to 3):
|
| 58 |
+
Stage indices to apply attention.
|
| 59 |
+
dropout (`float`, *optional*, defaults to 0.0):
|
| 60 |
+
Dropout probability.
|
| 61 |
+
|
| 62 |
+
```python
|
| 63 |
+
>>> from transformers import Emu3VisionVQ, Emu3VisionVQConfig
|
| 64 |
+
|
| 65 |
+
>>> # Initializing a video VQ model of Emu3 configuration
|
| 66 |
+
>>> configuration = Emu3VisionVQConfig()
|
| 67 |
+
|
| 68 |
+
>>> # Initializing a model from the Emu3 VQ model style configuration
|
| 69 |
+
>>> model = Emu3VisionVQModel(configuration)
|
| 70 |
+
|
| 71 |
+
>>> # Accessing the model configuration
|
| 72 |
+
>>> configuration = model.config
|
| 73 |
+
```"""
|
| 74 |
+
|
| 75 |
+
model_type = "Emu3VisionVQ"
|
| 76 |
+
|
| 77 |
+
def __init__(
|
| 78 |
+
self,
|
| 79 |
+
codebook_size: int = 32768,
|
| 80 |
+
embed_dim: int = 4,
|
| 81 |
+
z_channels: int = 4,
|
| 82 |
+
double_z: bool = False,
|
| 83 |
+
in_channels: int = 3,
|
| 84 |
+
out_channels: int = 3,
|
| 85 |
+
temporal_downsample_factor: int = 4,
|
| 86 |
+
ch: int = 256,
|
| 87 |
+
ch_mult: List[int] = [1, 2, 2, 4],
|
| 88 |
+
num_res_blocks: int = 2,
|
| 89 |
+
attn_resolutions: List[int] = [3],
|
| 90 |
+
dropout: float = 0.0,
|
| 91 |
+
**kwargs,
|
| 92 |
+
):
|
| 93 |
+
super().__init__(**kwargs)
|
| 94 |
+
|
| 95 |
+
self.codebook_size = codebook_size
|
| 96 |
+
self.embed_dim = embed_dim
|
| 97 |
+
self.z_channels = z_channels
|
| 98 |
+
self.double_z = double_z
|
| 99 |
+
self.in_channels = in_channels
|
| 100 |
+
self.out_channels = out_channels
|
| 101 |
+
self.temporal_downsample_factor = temporal_downsample_factor
|
| 102 |
+
self.ch = ch
|
| 103 |
+
self.ch_mult = ch_mult
|
| 104 |
+
self.num_res_blocks = num_res_blocks
|
| 105 |
+
self.attn_resolutions = attn_resolutions
|
| 106 |
+
self.dropout = dropout
|
sjdtree/emu3/tokenizer/image_processing_emu3visionvq.py
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The Emu team, BAAI and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Image processor class for Emu3VisionVQ."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
from typing import Dict, List, Optional, Union
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
|
| 23 |
+
from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
|
| 24 |
+
from transformers.image_transforms import (
|
| 25 |
+
convert_to_rgb,
|
| 26 |
+
resize,
|
| 27 |
+
to_channel_dimension_format,
|
| 28 |
+
)
|
| 29 |
+
from transformers.image_utils import (
|
| 30 |
+
IMAGENET_STANDARD_MEAN,
|
| 31 |
+
IMAGENET_STANDARD_STD,
|
| 32 |
+
ChannelDimension,
|
| 33 |
+
ImageInput,
|
| 34 |
+
PILImageResampling,
|
| 35 |
+
get_image_size,
|
| 36 |
+
infer_channel_dimension_format,
|
| 37 |
+
is_scaled_image,
|
| 38 |
+
make_list_of_images,
|
| 39 |
+
to_numpy_array,
|
| 40 |
+
valid_images,
|
| 41 |
+
validate_preprocess_arguments,
|
| 42 |
+
)
|
| 43 |
+
from transformers.utils import TensorType, is_vision_available, logging
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
if is_vision_available():
|
| 50 |
+
from PIL import Image
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def smart_resize(
|
| 54 |
+
height: int, width: int, factor: int = 8, min_pixels: int = 512 * 512, max_pixels: int = 1024 * 1024
|
| 55 |
+
):
|
| 56 |
+
"""Rescales the image so that the following conditions are met:
|
| 57 |
+
|
| 58 |
+
1. Both dimensions (height and width) are divisible by 'factor'.
|
| 59 |
+
|
| 60 |
+
2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
|
| 61 |
+
|
| 62 |
+
3. The aspect ratio of the image is maintained as closely as possible.
|
| 63 |
+
|
| 64 |
+
"""
|
| 65 |
+
if height < factor or width < factor:
|
| 66 |
+
raise ValueError(f"height:{height} or width:{width} must be larger than factor:{factor}")
|
| 67 |
+
elif max(height, width) / min(height, width) > 5:
|
| 68 |
+
raise ValueError(
|
| 69 |
+
f"absolute aspect ratio must be smaller than 5, got {max(height, width) / min(height, width)}"
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
h_bar = round(height / factor) * factor
|
| 73 |
+
w_bar = round(width / factor) * factor
|
| 74 |
+
if h_bar * w_bar > max_pixels:
|
| 75 |
+
beta = math.sqrt((height * width) / max_pixels)
|
| 76 |
+
h_bar = math.floor(height / beta / factor) * factor
|
| 77 |
+
w_bar = math.floor(width / beta / factor) * factor
|
| 78 |
+
elif h_bar * w_bar < min_pixels:
|
| 79 |
+
beta = math.sqrt(min_pixels / (height * width))
|
| 80 |
+
h_bar = math.ceil(height * beta / factor) * factor
|
| 81 |
+
w_bar = math.ceil(width * beta / factor) * factor
|
| 82 |
+
|
| 83 |
+
return h_bar, w_bar
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class Emu3VisionVQImageProcessor(BaseImageProcessor):
|
| 87 |
+
r"""
|
| 88 |
+
Constructs a Emu3VisionVQ image processor that dynamically resizes images based on the original images.
|
| 89 |
+
|
| 90 |
+
Args:
|
| 91 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 92 |
+
Whether to resize the image's (height, width) dimensions.
|
| 93 |
+
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
|
| 94 |
+
Resampling filter to use when resizing the image.
|
| 95 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 96 |
+
Whether to rescale the image by the specified scale `rescale_factor`.
|
| 97 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
| 98 |
+
Scale factor to use if rescaling the image.
|
| 99 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 100 |
+
Whether to normalize the image.
|
| 101 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `[0.5, 0.5, 0.5]`):
|
| 102 |
+
Mean to use if normalizing the image. This is a float or list of floats for each channel in the image.
|
| 103 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `[0.5, 0.5, 0.5]`):
|
| 104 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats for each channel in the image.
|
| 105 |
+
do_convert_rgb (`bool`, *optional*, defaults to `True`):
|
| 106 |
+
Whether to convert the image to RGB.
|
| 107 |
+
min_pixels (`int`, *optional*, defaults to `512 * 512`):
|
| 108 |
+
The min pixels of the image to resize the image.
|
| 109 |
+
max_pixels (`int`, *optional*, defaults to `1024 * 1024`):
|
| 110 |
+
The max pixels of the image to resize the image.
|
| 111 |
+
spatial_factor (`int`, *optional*, defautls to 8):
|
| 112 |
+
The spatial downsample factor the image will be downsampled in feature extracting phase
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
model_input_names = ["pixel_values"]
|
| 116 |
+
|
| 117 |
+
def __init__(
|
| 118 |
+
self,
|
| 119 |
+
do_resize: bool = True,
|
| 120 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 121 |
+
do_rescale: bool = True,
|
| 122 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
| 123 |
+
do_normalize: bool = True,
|
| 124 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 125 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 126 |
+
do_convert_rgb: bool = True,
|
| 127 |
+
min_pixels: int = 512 * 512,
|
| 128 |
+
max_pixels: int = 1024 * 1024,
|
| 129 |
+
spatial_factor: int = 8,
|
| 130 |
+
**kwargs,
|
| 131 |
+
) -> None:
|
| 132 |
+
super().__init__(**kwargs)
|
| 133 |
+
self.do_resize = do_resize
|
| 134 |
+
self.resample = resample
|
| 135 |
+
self.do_rescale = do_rescale
|
| 136 |
+
self.rescale_factor = rescale_factor
|
| 137 |
+
self.do_normalize = do_normalize
|
| 138 |
+
self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
|
| 139 |
+
self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
|
| 140 |
+
self.min_pixels = min_pixels
|
| 141 |
+
self.max_pixels = max_pixels
|
| 142 |
+
self.size = {"min_pixels": min_pixels, "max_pixels": max_pixels}
|
| 143 |
+
self.do_convert_rgb = do_convert_rgb
|
| 144 |
+
self.spatial_factor = spatial_factor
|
| 145 |
+
|
| 146 |
+
def _preprocess(
|
| 147 |
+
self,
|
| 148 |
+
images: ImageInput,
|
| 149 |
+
do_resize: Optional[bool] = None,
|
| 150 |
+
resample: PILImageResampling = None,
|
| 151 |
+
do_rescale: Optional[bool] = None,
|
| 152 |
+
rescale_factor: Optional[float] = None,
|
| 153 |
+
do_normalize: Optional[bool] = None,
|
| 154 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 155 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 156 |
+
do_convert_rgb: Optional[bool] = None,
|
| 157 |
+
spatial_factor: Optional[int] = None,
|
| 158 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 159 |
+
output_data_format: Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST,
|
| 160 |
+
):
|
| 161 |
+
"""
|
| 162 |
+
Preprocess an image or batch of images. Copy of the `preprocess` method from `CLIPImageProcessor`.
|
| 163 |
+
|
| 164 |
+
Args:
|
| 165 |
+
images (`ImageInput`):
|
| 166 |
+
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`.
|
| 167 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 168 |
+
Whether to resize the image.
|
| 169 |
+
resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
|
| 170 |
+
Resampling filter to use if resizing the image. This can be one of the `PILImageResampling` enums.
|
| 171 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 172 |
+
Whether to rescale the image.
|
| 173 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 174 |
+
Scale factor to use if rescaling the image.
|
| 175 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 176 |
+
Whether to normalize the image.
|
| 177 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
| 178 |
+
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.
|
| 179 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
| 180 |
+
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.
|
| 181 |
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
|
| 182 |
+
Whether to convert the image to RGB.
|
| 183 |
+
spatial_factor (`int`, *optional*, defaults to `self.spatial_factor`):
|
| 184 |
+
The spatial downsample factor the image will be downsampled in feature extracting phase
|
| 185 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 186 |
+
The channel dimension format for the input image. Can be one of:
|
| 187 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 188 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 189 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 190 |
+
output_data_format (`ChannelDimension`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 191 |
+
The channel dimension format for the output image. Can be one of:
|
| 192 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 193 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 194 |
+
- Unset: Use the channel dimension format of the input image.
|
| 195 |
+
"""
|
| 196 |
+
spatial_factor = spatial_factor if spatial_factor is not None else self.spatial_factor
|
| 197 |
+
|
| 198 |
+
images = make_list_of_images(images)
|
| 199 |
+
if do_convert_rgb:
|
| 200 |
+
images = [convert_to_rgb(image) for image in images]
|
| 201 |
+
|
| 202 |
+
# All transformations expect numpy arrays.
|
| 203 |
+
images = [to_numpy_array(image) for image in images]
|
| 204 |
+
|
| 205 |
+
if is_scaled_image(images[0]) and do_rescale:
|
| 206 |
+
logger.warning_once(
|
| 207 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 208 |
+
"pixel_values.append()images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
if input_data_format is None:
|
| 212 |
+
# We assume that all images have the same channel dimension format.
|
| 213 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 214 |
+
|
| 215 |
+
height, width = get_image_size(images[0], channel_dim=input_data_format)
|
| 216 |
+
resized_height, resized_width = height, width
|
| 217 |
+
processed_images = []
|
| 218 |
+
for image in images:
|
| 219 |
+
if do_resize:
|
| 220 |
+
resized_height, resized_width = smart_resize(
|
| 221 |
+
height,
|
| 222 |
+
width,
|
| 223 |
+
factor=spatial_factor,
|
| 224 |
+
min_pixels=self.min_pixels,
|
| 225 |
+
max_pixels=self.max_pixels,
|
| 226 |
+
)
|
| 227 |
+
image = resize(
|
| 228 |
+
image, size=(resized_height, resized_width), resample=resample, input_data_format=input_data_format
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
if do_rescale:
|
| 232 |
+
image = self.rescale(image, scale=rescale_factor, input_data_format=input_data_format)
|
| 233 |
+
|
| 234 |
+
if do_normalize:
|
| 235 |
+
image = self.normalize(
|
| 236 |
+
image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
image = to_channel_dimension_format(image, output_data_format, input_channel_dim=input_data_format)
|
| 240 |
+
processed_images.append(image)
|
| 241 |
+
|
| 242 |
+
image = np.array(processed_images)
|
| 243 |
+
return image
|
| 244 |
+
|
| 245 |
+
def preprocess(
|
| 246 |
+
self,
|
| 247 |
+
images: ImageInput,
|
| 248 |
+
do_resize: Optional[bool] = None,
|
| 249 |
+
resample: PILImageResampling = None,
|
| 250 |
+
do_rescale: Optional[bool] = None,
|
| 251 |
+
rescale_factor: Optional[float] = None,
|
| 252 |
+
do_normalize: Optional[bool] = None,
|
| 253 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 254 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 255 |
+
do_convert_rgb: Optional[bool] = None,
|
| 256 |
+
spatial_factor: Optional[int] = None,
|
| 257 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 258 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 259 |
+
output_data_format: Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST,
|
| 260 |
+
):
|
| 261 |
+
"""
|
| 262 |
+
Args:
|
| 263 |
+
images (`ImageInput`):
|
| 264 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
| 265 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 266 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 267 |
+
Whether to resize the image.
|
| 268 |
+
resample (`int`, *optional*, defaults to `self.resample`):
|
| 269 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
|
| 270 |
+
has an effect if `do_resize` is set to `True`.
|
| 271 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 272 |
+
Whether to rescale the image.
|
| 273 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 274 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 275 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 276 |
+
Whether to normalize the image.
|
| 277 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
| 278 |
+
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
| 279 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
| 280 |
+
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
| 281 |
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
|
| 282 |
+
Whether to convert the image to RGB.
|
| 283 |
+
spatial_factor (`int`, *optional*, defaults to `self.spatial_factor`):
|
| 284 |
+
The spatial downsample factor the image will be downsampled in feature extracting phase
|
| 285 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 286 |
+
The type of tensors to return. Can be one of:
|
| 287 |
+
- Unset: Return a list of `np.ndarray`.
|
| 288 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 289 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 290 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 291 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 292 |
+
from the input image. Can be one of:
|
| 293 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 294 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 295 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 296 |
+
output_data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 297 |
+
The channel dimension format for the output image. Can be one of:
|
| 298 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 299 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 300 |
+
- Unset: Use the channel dimension format of the input image.
|
| 301 |
+
"""
|
| 302 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 303 |
+
resample = resample if resample is not None else self.resample
|
| 304 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 305 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 306 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 307 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 308 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 309 |
+
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
|
| 310 |
+
spatial_factor = spatial_factor if spatial_factor is not None else self.spatial_factor
|
| 311 |
+
|
| 312 |
+
images = make_list_of_images(images)
|
| 313 |
+
if images is None or not valid_images(images):
|
| 314 |
+
raise ValueError(
|
| 315 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 316 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
validate_preprocess_arguments(
|
| 320 |
+
rescale_factor=rescale_factor,
|
| 321 |
+
do_normalize=do_normalize,
|
| 322 |
+
image_mean=image_mean,
|
| 323 |
+
image_std=image_std,
|
| 324 |
+
do_resize=do_resize,
|
| 325 |
+
size=self.size,
|
| 326 |
+
resample=resample,
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
pixel_values = []
|
| 330 |
+
for image in images:
|
| 331 |
+
norm_image = self._preprocess(
|
| 332 |
+
image,
|
| 333 |
+
do_resize=do_resize,
|
| 334 |
+
resample=resample,
|
| 335 |
+
do_rescale=do_rescale,
|
| 336 |
+
rescale_factor=rescale_factor,
|
| 337 |
+
do_normalize=do_normalize,
|
| 338 |
+
image_mean=image_mean,
|
| 339 |
+
image_std=image_std,
|
| 340 |
+
do_convert_rgb=do_convert_rgb,
|
| 341 |
+
spatial_factor=spatial_factor,
|
| 342 |
+
input_data_format=input_data_format,
|
| 343 |
+
output_data_format=output_data_format,
|
| 344 |
+
)
|
| 345 |
+
pixel_values.extend(norm_image)
|
| 346 |
+
pixel_values = np.array(pixel_values)
|
| 347 |
+
data = {"pixel_values": pixel_values}
|
| 348 |
+
|
| 349 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 350 |
+
|
| 351 |
+
def postprocess(
|
| 352 |
+
self,
|
| 353 |
+
images: ImageInput,
|
| 354 |
+
do_rescale: Optional[bool] = None,
|
| 355 |
+
rescale_factor: Optional[float] = None,
|
| 356 |
+
do_normalize: Optional[bool] = None,
|
| 357 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 358 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 359 |
+
return_tensors = "PIL.Image.Image",
|
| 360 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 361 |
+
):
|
| 362 |
+
"""
|
| 363 |
+
Postprocess an image or batch of images tensor. Postprocess is the reverse process of preprocess.
|
| 364 |
+
The parameters should be same as in preprocess.
|
| 365 |
+
|
| 366 |
+
Args:
|
| 367 |
+
images (`ImageInput`):
|
| 368 |
+
Image to postprocess. Expects a single or batch of images with pixel values ranging from -1 to 1.
|
| 369 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 370 |
+
Whether to rescale the image.
|
| 371 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 372 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 373 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 374 |
+
Whether to normalize the image.
|
| 375 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
| 376 |
+
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
| 377 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
| 378 |
+
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
| 379 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 380 |
+
The type of tensors to return. Can be one of:
|
| 381 |
+
- Unset: Return a list of `np.ndarray`.
|
| 382 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 383 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 384 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 385 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 386 |
+
from the input image. Can be one of:
|
| 387 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 388 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 389 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 390 |
+
"""
|
| 391 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 392 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 393 |
+
rescale_factor = 1 / rescale_factor
|
| 394 |
+
|
| 395 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 396 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 397 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 398 |
+
image_mean, image_std = self.inverse_meanstd(image_mean, image_std)
|
| 399 |
+
|
| 400 |
+
images = make_list_of_images(images)
|
| 401 |
+
if isinstance(images[0], Image.Image):
|
| 402 |
+
return images if len(images) > 1 else images[0]
|
| 403 |
+
|
| 404 |
+
if input_data_format is None:
|
| 405 |
+
# We assume that all images have the same channel dimension format.
|
| 406 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 407 |
+
|
| 408 |
+
pixel_values = []
|
| 409 |
+
for image in images:
|
| 410 |
+
image = to_numpy_array(image)
|
| 411 |
+
if do_normalize:
|
| 412 |
+
image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
|
| 413 |
+
|
| 414 |
+
if do_rescale:
|
| 415 |
+
image = self.rescale(image, scale=rescale_factor, input_data_format=input_data_format)
|
| 416 |
+
image = image.clip(0, 255).astype(np.uint8)
|
| 417 |
+
|
| 418 |
+
if do_normalize and do_rescale and return_tensors == "PIL.Image.Image":
|
| 419 |
+
image = to_channel_dimension_format(image, ChannelDimension.LAST, input_channel_dim=input_data_format)
|
| 420 |
+
pixel_values.append(Image.fromarray(image))
|
| 421 |
+
else:
|
| 422 |
+
pixel_values.extend(image)
|
| 423 |
+
|
| 424 |
+
data = {"pixel_values": pixel_values}
|
| 425 |
+
return_tensors = return_tensors if return_tensors != "PIL.Image.Image" else None
|
| 426 |
+
|
| 427 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 428 |
+
|
| 429 |
+
def inverse_meanstd(self, image_mean, image_std):
|
| 430 |
+
image_mean = self.to_tuple(image_mean)
|
| 431 |
+
image_std = self.to_tuple(image_std)
|
| 432 |
+
|
| 433 |
+
rev_image_mean = tuple(-m / s for m, s in zip(image_mean, image_std))
|
| 434 |
+
rev_image_std = tuple(1 / s for s in image_std)
|
| 435 |
+
|
| 436 |
+
return rev_image_mean, rev_image_std
|
| 437 |
+
|
| 438 |
+
def to_tuple(self, value, dim=3):
|
| 439 |
+
if isinstance(value, int | float):
|
| 440 |
+
return (value,) * dim
|
| 441 |
+
|
| 442 |
+
return tuple(value)
|
sjdtree/emu3/tokenizer/modeling_emu3visionvq.py
ADDED
|
@@ -0,0 +1,822 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The Emu team, BAAI and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Emu3VisionVQ model """
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from typing import Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import nn
|
| 22 |
+
from torch.nn import functional as F
|
| 23 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 24 |
+
|
| 25 |
+
from .configuration_emu3visionvq import Emu3VisionVQConfig
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class Emu3VisionVQActivation(nn.Module):
|
| 29 |
+
|
| 30 |
+
def __init__(self):
|
| 31 |
+
super().__init__()
|
| 32 |
+
|
| 33 |
+
def __call__(self, x: torch.Tensor):
|
| 34 |
+
return x * torch.sigmoid(x)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class Emu3VisionVQUpsample(nn.Module):
|
| 38 |
+
|
| 39 |
+
def __init__(self, in_channels: int):
|
| 40 |
+
super().__init__()
|
| 41 |
+
self.conv = nn.Conv2d(
|
| 42 |
+
in_channels,
|
| 43 |
+
in_channels,
|
| 44 |
+
kernel_size=3,
|
| 45 |
+
stride=1,
|
| 46 |
+
padding=1,
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
def forward(self, x: torch.Tensor):
|
| 50 |
+
x = F.interpolate(x, scale_factor=2.0, mode="nearest")
|
| 51 |
+
x = self.conv(x)
|
| 52 |
+
return x
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class Emu3VisionVQDownsample(nn.Module):
|
| 56 |
+
|
| 57 |
+
def __init__(self, in_channels: int):
|
| 58 |
+
super().__init__()
|
| 59 |
+
self.conv = nn.Conv2d(
|
| 60 |
+
in_channels,
|
| 61 |
+
in_channels,
|
| 62 |
+
kernel_size=3,
|
| 63 |
+
stride=2,
|
| 64 |
+
padding=0,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
def forward(self, x: torch.Tensor):
|
| 68 |
+
pad = (0, 1, 0, 1)
|
| 69 |
+
x = F.pad(x, pad, mode="constant", value=0)
|
| 70 |
+
x = self.conv(x)
|
| 71 |
+
return x
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class Emu3VisionVQCausalConv3d(nn.Module):
|
| 75 |
+
|
| 76 |
+
def __init__(
|
| 77 |
+
self,
|
| 78 |
+
in_channel: int,
|
| 79 |
+
out_channel: int,
|
| 80 |
+
kernel_size: Union[int, Tuple[int, ...]] = (3, 1, 1),
|
| 81 |
+
stride: Union[int, Tuple[int, ...]] = (1, 1, 1),
|
| 82 |
+
):
|
| 83 |
+
super().__init__()
|
| 84 |
+
|
| 85 |
+
if isinstance(kernel_size, int):
|
| 86 |
+
kernel_size = (kernel_size,) * 3
|
| 87 |
+
if isinstance(stride, int):
|
| 88 |
+
stride = (stride,) * 3
|
| 89 |
+
|
| 90 |
+
hw_pad = [k - s for k, s in zip(kernel_size[1:], stride[1:])]
|
| 91 |
+
self.padding = tuple()
|
| 92 |
+
for p in hw_pad[::-1]:
|
| 93 |
+
self.padding += (p // 2 + p % 2, p // 2)
|
| 94 |
+
self.padding += (2, 0)
|
| 95 |
+
|
| 96 |
+
self.conv = nn.Conv3d(
|
| 97 |
+
in_channel,
|
| 98 |
+
out_channel,
|
| 99 |
+
kernel_size,
|
| 100 |
+
stride=stride,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
def forward(self, x: torch.Tensor):
|
| 104 |
+
x = F.pad(x, self.padding)
|
| 105 |
+
x = self.conv(x)
|
| 106 |
+
return x
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class Emu3VisionVQResnetTemporalBlock(nn.Module):
|
| 110 |
+
|
| 111 |
+
def __init__(
|
| 112 |
+
self,
|
| 113 |
+
in_channels: int,
|
| 114 |
+
out_channels: Optional[int] = None,
|
| 115 |
+
conv_shortcut: bool = False,
|
| 116 |
+
dropout: float = 0.0,
|
| 117 |
+
):
|
| 118 |
+
super().__init__()
|
| 119 |
+
self.in_channels = in_channels
|
| 120 |
+
out_channels = in_channels if out_channels is None else out_channels
|
| 121 |
+
self.out_channels = out_channels
|
| 122 |
+
self.use_conv_shortcut = conv_shortcut
|
| 123 |
+
|
| 124 |
+
stride = (1, 1, 1)
|
| 125 |
+
kernel_size = (3, 3, 3)
|
| 126 |
+
|
| 127 |
+
self.norm1 = nn.BatchNorm3d(in_channels)
|
| 128 |
+
self.conv1 = Emu3VisionVQCausalConv3d(
|
| 129 |
+
in_channels,
|
| 130 |
+
out_channels,
|
| 131 |
+
kernel_size=kernel_size,
|
| 132 |
+
stride=stride,
|
| 133 |
+
)
|
| 134 |
+
self.norm2 = nn.BatchNorm3d(out_channels)
|
| 135 |
+
self.dropout = nn.Dropout(dropout)
|
| 136 |
+
self.conv2 = Emu3VisionVQCausalConv3d(
|
| 137 |
+
out_channels,
|
| 138 |
+
out_channels,
|
| 139 |
+
kernel_size=kernel_size,
|
| 140 |
+
stride=stride,
|
| 141 |
+
)
|
| 142 |
+
self.act = Emu3VisionVQActivation()
|
| 143 |
+
|
| 144 |
+
if self.in_channels != self.out_channels:
|
| 145 |
+
if self.use_conv_shortcut:
|
| 146 |
+
self.conv_shortcut = Emu3VisionVQCausalConv3d(
|
| 147 |
+
in_channels,
|
| 148 |
+
out_channels,
|
| 149 |
+
kernel_size=kernel_size,
|
| 150 |
+
stride=stride,
|
| 151 |
+
)
|
| 152 |
+
else:
|
| 153 |
+
self.nin_shortcut = nn.Conv3d(
|
| 154 |
+
in_channels,
|
| 155 |
+
out_channels,
|
| 156 |
+
kernel_size=1,
|
| 157 |
+
stride=1,
|
| 158 |
+
padding=0,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
def forward(self, x: torch.Tensor):
|
| 162 |
+
h = self.norm1(x)
|
| 163 |
+
h = self.act(h)
|
| 164 |
+
h = self.conv1(h)
|
| 165 |
+
|
| 166 |
+
h = self.norm2(h)
|
| 167 |
+
h = self.act(h)
|
| 168 |
+
h = self.dropout(h)
|
| 169 |
+
h = self.conv2(h)
|
| 170 |
+
|
| 171 |
+
if self.in_channels != self.out_channels:
|
| 172 |
+
if self.use_conv_shortcut:
|
| 173 |
+
x = self.conv_shortcut(x)
|
| 174 |
+
else:
|
| 175 |
+
x = self.nin_shortcut(x)
|
| 176 |
+
|
| 177 |
+
return x + h
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class Emu3VisionVQSpatialNorm(nn.Module):
|
| 181 |
+
|
| 182 |
+
def __init__(
|
| 183 |
+
self,
|
| 184 |
+
f_channels: int,
|
| 185 |
+
zq_channels: int,
|
| 186 |
+
norm_layer: nn.Module = nn.GroupNorm,
|
| 187 |
+
add_conv: bool = False,
|
| 188 |
+
num_groups: int = 32,
|
| 189 |
+
eps: float = 1e-6,
|
| 190 |
+
affine: bool = True,
|
| 191 |
+
):
|
| 192 |
+
super().__init__()
|
| 193 |
+
self.norm_layer = norm_layer(
|
| 194 |
+
num_channels=f_channels,
|
| 195 |
+
num_groups=num_groups,
|
| 196 |
+
eps=eps,
|
| 197 |
+
affine=affine,
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
self.add_conv = add_conv
|
| 201 |
+
if self.add_conv:
|
| 202 |
+
self.conv = nn.Conv2d(
|
| 203 |
+
zq_channels,
|
| 204 |
+
zq_channels,
|
| 205 |
+
kernel_size=3,
|
| 206 |
+
stride=1,
|
| 207 |
+
padding=1,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
self.conv_y = nn.Conv2d(
|
| 211 |
+
zq_channels,
|
| 212 |
+
f_channels,
|
| 213 |
+
kernel_size=1,
|
| 214 |
+
stride=1,
|
| 215 |
+
padding=0,
|
| 216 |
+
)
|
| 217 |
+
self.conv_b = nn.Conv2d(
|
| 218 |
+
zq_channels,
|
| 219 |
+
f_channels,
|
| 220 |
+
kernel_size=1,
|
| 221 |
+
stride=1,
|
| 222 |
+
padding=0,
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
def forward(self, x: torch.Tensor, zq: torch.Tensor):
|
| 226 |
+
zq = F.interpolate(zq, size=x.shape[-2:], mode="nearest")
|
| 227 |
+
|
| 228 |
+
if self.add_conv:
|
| 229 |
+
zq = self.conv(zq)
|
| 230 |
+
|
| 231 |
+
x = self.norm_layer(x)
|
| 232 |
+
x = x * self.conv_y(zq) + self.conv_b(zq)
|
| 233 |
+
return x
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
class Emu3VisionVQResnetBlock(nn.Module):
|
| 237 |
+
|
| 238 |
+
def __init__(
|
| 239 |
+
self,
|
| 240 |
+
in_channels: int,
|
| 241 |
+
out_channels: Optional[int] = None,
|
| 242 |
+
conv_shortcut: bool = False,
|
| 243 |
+
dropout: float = 0.0,
|
| 244 |
+
zq_ch: Optional[int] = None,
|
| 245 |
+
add_conv: bool = False,
|
| 246 |
+
):
|
| 247 |
+
super().__init__()
|
| 248 |
+
self.in_channels = in_channels
|
| 249 |
+
out_channels = in_channels if out_channels is None else out_channels
|
| 250 |
+
self.out_channels = out_channels
|
| 251 |
+
self.use_conv_shortcut = conv_shortcut
|
| 252 |
+
self.zq_ch = zq_ch
|
| 253 |
+
|
| 254 |
+
if zq_ch is None:
|
| 255 |
+
norm_kwargs = dict(num_groups=32, eps=1e-6, affine=True)
|
| 256 |
+
self.norm1 = nn.GroupNorm(num_channels=in_channels, **norm_kwargs)
|
| 257 |
+
self.norm2 = nn.GroupNorm(num_channels=out_channels, **norm_kwargs)
|
| 258 |
+
else:
|
| 259 |
+
self.norm1 = Emu3VisionVQSpatialNorm(in_channels, zq_ch, add_conv=add_conv)
|
| 260 |
+
self.norm2 = Emu3VisionVQSpatialNorm(out_channels, zq_ch, add_conv=add_conv)
|
| 261 |
+
|
| 262 |
+
self.conv1 = nn.Conv2d(
|
| 263 |
+
in_channels,
|
| 264 |
+
out_channels,
|
| 265 |
+
kernel_size=3,
|
| 266 |
+
stride=1,
|
| 267 |
+
padding=1,
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
self.dropout = nn.Dropout(dropout)
|
| 271 |
+
self.conv2 = nn.Conv2d(
|
| 272 |
+
out_channels,
|
| 273 |
+
out_channels,
|
| 274 |
+
kernel_size=3,
|
| 275 |
+
stride=1,
|
| 276 |
+
padding=1,
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
self.act = Emu3VisionVQActivation()
|
| 280 |
+
|
| 281 |
+
if self.in_channels != self.out_channels:
|
| 282 |
+
if self.use_conv_shortcut:
|
| 283 |
+
self.conv_shortcut = nn.Conv2d(
|
| 284 |
+
in_channels,
|
| 285 |
+
out_channels,
|
| 286 |
+
kernel_size=3,
|
| 287 |
+
stride=1,
|
| 288 |
+
padding=1,
|
| 289 |
+
)
|
| 290 |
+
else:
|
| 291 |
+
self.nin_shortcut = nn.Conv2d(
|
| 292 |
+
in_channels,
|
| 293 |
+
out_channels,
|
| 294 |
+
kernel_size=1,
|
| 295 |
+
stride=1,
|
| 296 |
+
padding=0,
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
def forward(self, x: torch.Tensor, zq: Optional[torch.Tensor] = None):
|
| 300 |
+
norm_args = tuple() if self.zq_ch is None else (zq, )
|
| 301 |
+
|
| 302 |
+
h = self.norm1(x, *norm_args)
|
| 303 |
+
h = self.act(h)
|
| 304 |
+
h = self.conv1(h)
|
| 305 |
+
|
| 306 |
+
h = self.norm2(h, *norm_args)
|
| 307 |
+
h = self.act(h)
|
| 308 |
+
h = self.dropout(h)
|
| 309 |
+
h = self.conv2(h)
|
| 310 |
+
|
| 311 |
+
if self.in_channels != self.out_channels:
|
| 312 |
+
if self.use_conv_shortcut:
|
| 313 |
+
x = self.conv_shortcut(x)
|
| 314 |
+
else:
|
| 315 |
+
x = self.nin_shortcut(x)
|
| 316 |
+
|
| 317 |
+
return x + h
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
class Emu3VisionVQAttnBlock(nn.Module):
|
| 321 |
+
|
| 322 |
+
def __init__(
|
| 323 |
+
self,
|
| 324 |
+
in_channels: int,
|
| 325 |
+
zq_ch: Optional[int] = None,
|
| 326 |
+
add_conv: bool = False
|
| 327 |
+
):
|
| 328 |
+
super().__init__()
|
| 329 |
+
self.in_channels = in_channels
|
| 330 |
+
self.zq_ch = zq_ch
|
| 331 |
+
|
| 332 |
+
if zq_ch is None:
|
| 333 |
+
norm_kwargs = dict(num_groups=32, eps=1e-6, affine=True)
|
| 334 |
+
self.norm = nn.GroupNorm(num_channels=in_channels, **norm_kwargs)
|
| 335 |
+
else:
|
| 336 |
+
self.norm = Emu3VisionVQSpatialNorm(in_channels, zq_ch, add_conv=add_conv)
|
| 337 |
+
|
| 338 |
+
self.q = nn.Conv2d(
|
| 339 |
+
in_channels,
|
| 340 |
+
in_channels,
|
| 341 |
+
kernel_size=1,
|
| 342 |
+
stride=1,
|
| 343 |
+
padding=0,
|
| 344 |
+
)
|
| 345 |
+
self.k = nn.Conv2d(
|
| 346 |
+
in_channels,
|
| 347 |
+
in_channels,
|
| 348 |
+
kernel_size=1,
|
| 349 |
+
stride=1,
|
| 350 |
+
padding=0,
|
| 351 |
+
)
|
| 352 |
+
self.v = nn.Conv2d(
|
| 353 |
+
in_channels,
|
| 354 |
+
in_channels,
|
| 355 |
+
kernel_size=1,
|
| 356 |
+
stride=1,
|
| 357 |
+
padding=0,
|
| 358 |
+
)
|
| 359 |
+
self.proj_out = nn.Conv2d(
|
| 360 |
+
in_channels,
|
| 361 |
+
in_channels,
|
| 362 |
+
kernel_size=1,
|
| 363 |
+
stride=1,
|
| 364 |
+
padding=0,
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
def forward(self, x: torch.Tensor, zq: Optional[torch.Tensor] = None):
|
| 368 |
+
norm_args = tuple() if self.zq_ch is None else (zq, )
|
| 369 |
+
|
| 370 |
+
nx = self.norm(x, *norm_args)
|
| 371 |
+
q = self.q(nx)
|
| 372 |
+
k = self.k(nx)
|
| 373 |
+
v = self.v(nx)
|
| 374 |
+
|
| 375 |
+
# compute attention
|
| 376 |
+
b, c, h, w = q.shape
|
| 377 |
+
q = q.reshape(b, c, h * w)
|
| 378 |
+
k = k.reshape(b, c, h * w)
|
| 379 |
+
score = torch.bmm(q.permute(0, 2, 1), k)
|
| 380 |
+
score = score / (c ** 0.5)
|
| 381 |
+
score = F.softmax(score, dim=2)
|
| 382 |
+
|
| 383 |
+
# attend to values
|
| 384 |
+
v = v.reshape(b, c, h * w)
|
| 385 |
+
v = torch.bmm(v, score.permute(0, 2, 1))
|
| 386 |
+
v = v.reshape(b, c, h, w)
|
| 387 |
+
|
| 388 |
+
v = self.proj_out(v)
|
| 389 |
+
|
| 390 |
+
return x + v
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
class Emu3VisionVQTemporalUpsample(nn.Module):
|
| 394 |
+
|
| 395 |
+
def __init__(
|
| 396 |
+
self,
|
| 397 |
+
in_channel: int,
|
| 398 |
+
out_channel: int,
|
| 399 |
+
kernel_size: Tuple[int, ...] = (3, 3, 3),
|
| 400 |
+
stride: Tuple[int, ...] = (1, 1, 1)
|
| 401 |
+
):
|
| 402 |
+
super().__init__()
|
| 403 |
+
self.in_channel = in_channel
|
| 404 |
+
self.out_channel = out_channel
|
| 405 |
+
self.conv = Emu3VisionVQCausalConv3d(
|
| 406 |
+
in_channel,
|
| 407 |
+
out_channel,
|
| 408 |
+
kernel_size,
|
| 409 |
+
stride=stride,
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
def forward(self, x: torch.Tensor):
|
| 413 |
+
b, c, t, h, w = x.shape
|
| 414 |
+
x = x.permute(0, 1, 3, 4, 2).contiguous().view(b, -1, t)
|
| 415 |
+
x = F.interpolate(x, scale_factor=2.0, mode="nearest")
|
| 416 |
+
x = x.view(b, c, h, w, -1).permute(0, 1, 4, 2, 3).contiguous()
|
| 417 |
+
x = self.conv(x)
|
| 418 |
+
return x
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
class Emu3VisionVQTemporalDownsample(nn.Module):
|
| 422 |
+
|
| 423 |
+
def __init__(
|
| 424 |
+
self,
|
| 425 |
+
in_channel: int,
|
| 426 |
+
out_channel: int,
|
| 427 |
+
kernel_size: Tuple[int, ...] = (4, 3, 3),
|
| 428 |
+
stride: Tuple[int, ...] = (2, 1, 1),
|
| 429 |
+
):
|
| 430 |
+
super().__init__()
|
| 431 |
+
self.in_channel = in_channel
|
| 432 |
+
self.out_channel = out_channel
|
| 433 |
+
self.kernel_size = kernel_size
|
| 434 |
+
|
| 435 |
+
self.conv = Emu3VisionVQCausalConv3d(
|
| 436 |
+
in_channel,
|
| 437 |
+
out_channel,
|
| 438 |
+
kernel_size=kernel_size,
|
| 439 |
+
stride=stride,
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
def forward(self, x: torch.Tensor):
|
| 443 |
+
x = self.conv(x)
|
| 444 |
+
return x
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
class Emu3VisionVQVectorQuantizer(nn.Module):
|
| 448 |
+
|
| 449 |
+
def __init__(self, config: Emu3VisionVQConfig):
|
| 450 |
+
super().__init__()
|
| 451 |
+
self.embedding = nn.Embedding(config.codebook_size, config.embed_dim)
|
| 452 |
+
self.embedding.weight.data.uniform_(-1.0 / config.codebook_size, 1.0 / config.codebook_size)
|
| 453 |
+
|
| 454 |
+
def forward(self, x: torch.Tensor):
|
| 455 |
+
# b t c h w -> b t h w c
|
| 456 |
+
b, t, c, h, w = x.shape
|
| 457 |
+
x = x.permute(0, 1, 3, 4, 2).contiguous()
|
| 458 |
+
x_flattened = x.view(-1, c)
|
| 459 |
+
|
| 460 |
+
codebook = self.embedding.weight
|
| 461 |
+
|
| 462 |
+
d = torch.sum(x_flattened ** 2, dim=1, keepdim=True) + \
|
| 463 |
+
torch.sum(codebook ** 2, dim=1) - 2 * \
|
| 464 |
+
torch.einsum('bd,dn->bn', x_flattened, codebook.permute(1, 0))
|
| 465 |
+
|
| 466 |
+
indices = torch.argmin(d, dim=1)
|
| 467 |
+
indices = indices.view(b, t, h, w)
|
| 468 |
+
return indices
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
class Emu3VisionVQEncoder(nn.Module):
|
| 472 |
+
|
| 473 |
+
def __init__(self, config: Emu3VisionVQConfig):
|
| 474 |
+
super().__init__()
|
| 475 |
+
self.ch = config.ch
|
| 476 |
+
self.num_resolutions = len(config.ch_mult)
|
| 477 |
+
self.num_res_blocks = config.num_res_blocks
|
| 478 |
+
self.in_channels = config.in_channels
|
| 479 |
+
|
| 480 |
+
# downsampling
|
| 481 |
+
self.conv_in = nn.Conv2d(
|
| 482 |
+
self.in_channels,
|
| 483 |
+
self.ch,
|
| 484 |
+
kernel_size=3,
|
| 485 |
+
stride=1,
|
| 486 |
+
padding=1
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
in_ch_mult = (1,) + tuple(config.ch_mult)
|
| 490 |
+
self.down = nn.ModuleList()
|
| 491 |
+
for i_level in range(self.num_resolutions):
|
| 492 |
+
block = nn.ModuleList()
|
| 493 |
+
attn = nn.ModuleList()
|
| 494 |
+
block_in = config.ch * in_ch_mult[i_level]
|
| 495 |
+
block_out = config.ch * config.ch_mult[i_level]
|
| 496 |
+
for i_block in range(self.num_res_blocks):
|
| 497 |
+
block.append(
|
| 498 |
+
Emu3VisionVQResnetBlock(
|
| 499 |
+
in_channels=block_in,
|
| 500 |
+
out_channels=block_out,
|
| 501 |
+
dropout=config.dropout,
|
| 502 |
+
)
|
| 503 |
+
)
|
| 504 |
+
block_in = block_out
|
| 505 |
+
if i_level in config.attn_resolutions:
|
| 506 |
+
attn.append(Emu3VisionVQAttnBlock(block_in))
|
| 507 |
+
|
| 508 |
+
down = nn.Module()
|
| 509 |
+
down.block = block
|
| 510 |
+
down.attn = attn
|
| 511 |
+
if i_level != self.num_resolutions - 1:
|
| 512 |
+
down.downsample = Emu3VisionVQDownsample(block_in)
|
| 513 |
+
|
| 514 |
+
self.down.append(down)
|
| 515 |
+
|
| 516 |
+
# middle
|
| 517 |
+
self.mid = nn.Module()
|
| 518 |
+
self.mid.block_1 = Emu3VisionVQResnetBlock(
|
| 519 |
+
in_channels=block_in,
|
| 520 |
+
out_channels=block_in,
|
| 521 |
+
dropout=config.dropout,
|
| 522 |
+
)
|
| 523 |
+
self.mid.attn_1 = Emu3VisionVQAttnBlock(block_in)
|
| 524 |
+
self.mid.block_2 = Emu3VisionVQResnetBlock(
|
| 525 |
+
in_channels=block_in,
|
| 526 |
+
out_channels=block_in,
|
| 527 |
+
dropout=config.dropout,
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
# end
|
| 531 |
+
self.norm_out = nn.GroupNorm(num_channels=block_in, num_groups=32, eps=1e-6, affine=True)
|
| 532 |
+
|
| 533 |
+
out_z_channels = 2 * config.z_channels if config.double_z else config.z_channels
|
| 534 |
+
self.conv_out = nn.Conv2d(
|
| 535 |
+
block_in,
|
| 536 |
+
out_z_channels,
|
| 537 |
+
kernel_size=3,
|
| 538 |
+
stride=1,
|
| 539 |
+
padding=1,
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
temporal_down_blocks = int(math.log2(config.temporal_downsample_factor))
|
| 543 |
+
self.time_conv = nn.ModuleList()
|
| 544 |
+
|
| 545 |
+
for i in range(temporal_down_blocks):
|
| 546 |
+
conv = Emu3VisionVQTemporalDownsample(out_z_channels, out_z_channels)
|
| 547 |
+
self.time_conv.append(conv)
|
| 548 |
+
|
| 549 |
+
self.time_res_stack = nn.Sequential(*[
|
| 550 |
+
Emu3VisionVQResnetTemporalBlock(
|
| 551 |
+
in_channels=out_z_channels,
|
| 552 |
+
out_channels=out_z_channels,
|
| 553 |
+
dropout=config.dropout,
|
| 554 |
+
) for _ in range(self.num_res_blocks)
|
| 555 |
+
])
|
| 556 |
+
|
| 557 |
+
self.act = Emu3VisionVQActivation()
|
| 558 |
+
|
| 559 |
+
def forward(self, x: torch.Tensor):
|
| 560 |
+
t = x.shape[1]
|
| 561 |
+
x = x.reshape(-1, *x.shape[2:])
|
| 562 |
+
|
| 563 |
+
# downsampling
|
| 564 |
+
h = self.conv_in(x)
|
| 565 |
+
for i_level in range(self.num_resolutions):
|
| 566 |
+
for i_block in range(self.num_res_blocks):
|
| 567 |
+
h = self.down[i_level].block[i_block](h)
|
| 568 |
+
if len(self.down[i_level].attn) > 0:
|
| 569 |
+
h = self.down[i_level].attn[i_block](h)
|
| 570 |
+
|
| 571 |
+
if i_level != self.num_resolutions - 1:
|
| 572 |
+
h = self.down[i_level].downsample(h)
|
| 573 |
+
|
| 574 |
+
h = self.mid.block_1(h)
|
| 575 |
+
h = self.mid.attn_1(h)
|
| 576 |
+
h = self.mid.block_2(h)
|
| 577 |
+
|
| 578 |
+
# end
|
| 579 |
+
h = self.norm_out(h)
|
| 580 |
+
h = self.act(h)
|
| 581 |
+
|
| 582 |
+
h = self.conv_out(h)
|
| 583 |
+
|
| 584 |
+
h = h.reshape(-1, t, *h.shape[1:])
|
| 585 |
+
h = h.permute(0, 2, 1, 3, 4)
|
| 586 |
+
|
| 587 |
+
for conv in self.time_conv:
|
| 588 |
+
h = self.act(conv(h))
|
| 589 |
+
|
| 590 |
+
h = self.time_res_stack(h)
|
| 591 |
+
h = h.permute(0, 2, 1, 3, 4)
|
| 592 |
+
|
| 593 |
+
return h
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
class Emu3VisionVQDecoder(nn.Module):
|
| 597 |
+
|
| 598 |
+
def __init__(self, config: Emu3VisionVQConfig):
|
| 599 |
+
super().__init__()
|
| 600 |
+
self.ch = config.ch
|
| 601 |
+
self.num_resolutions = len(config.ch_mult)
|
| 602 |
+
self.num_res_blocks = config.num_res_blocks
|
| 603 |
+
|
| 604 |
+
in_ch_mult = (1,) + tuple(config.ch_mult)
|
| 605 |
+
zq_ch = config.embed_dim
|
| 606 |
+
|
| 607 |
+
block_in = config.ch * config.ch_mult[-1]
|
| 608 |
+
self.time_res_stack = nn.Sequential(*[
|
| 609 |
+
Emu3VisionVQResnetTemporalBlock(
|
| 610 |
+
in_channels=config.z_channels,
|
| 611 |
+
out_channels=config.z_channels,
|
| 612 |
+
dropout=config.dropout,
|
| 613 |
+
) for _ in range(config.num_res_blocks)
|
| 614 |
+
])
|
| 615 |
+
|
| 616 |
+
tempo_upsample_block_num = int(math.log2(config.temporal_downsample_factor))
|
| 617 |
+
self.time_conv = nn.ModuleList()
|
| 618 |
+
for i in range(tempo_upsample_block_num):
|
| 619 |
+
conv = Emu3VisionVQTemporalUpsample(config.z_channels, config.z_channels)
|
| 620 |
+
self.time_conv.append(conv)
|
| 621 |
+
|
| 622 |
+
self.conv_in = nn.Conv2d(
|
| 623 |
+
config.z_channels,
|
| 624 |
+
block_in,
|
| 625 |
+
kernel_size=3,
|
| 626 |
+
stride=1,
|
| 627 |
+
padding=1,
|
| 628 |
+
)
|
| 629 |
+
|
| 630 |
+
# middle
|
| 631 |
+
self.mid = nn.Module()
|
| 632 |
+
self.mid.block_1 = Emu3VisionVQResnetBlock(
|
| 633 |
+
in_channels=block_in,
|
| 634 |
+
out_channels=block_in,
|
| 635 |
+
dropout=config.dropout,
|
| 636 |
+
zq_ch=zq_ch,
|
| 637 |
+
)
|
| 638 |
+
self.mid.attn_1 = Emu3VisionVQAttnBlock(block_in, zq_ch)
|
| 639 |
+
self.mid.block_2 = Emu3VisionVQResnetBlock(
|
| 640 |
+
in_channels=block_in,
|
| 641 |
+
out_channels=block_in,
|
| 642 |
+
dropout=config.dropout,
|
| 643 |
+
zq_ch=zq_ch,
|
| 644 |
+
)
|
| 645 |
+
|
| 646 |
+
# upsampling
|
| 647 |
+
self.up = nn.ModuleList()
|
| 648 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 649 |
+
block = nn.ModuleList()
|
| 650 |
+
attn = nn.ModuleList()
|
| 651 |
+
block_out = config.ch * config.ch_mult[i_level]
|
| 652 |
+
for i_block in range(self.num_res_blocks + 1):
|
| 653 |
+
block.append(
|
| 654 |
+
Emu3VisionVQResnetBlock(
|
| 655 |
+
in_channels=block_in,
|
| 656 |
+
out_channels=block_out,
|
| 657 |
+
dropout=config.dropout,
|
| 658 |
+
zq_ch=zq_ch,
|
| 659 |
+
)
|
| 660 |
+
)
|
| 661 |
+
block_in = block_out
|
| 662 |
+
if i_level in config.attn_resolutions:
|
| 663 |
+
attn.append(Emu3VisionVQAttnBlock(block_in, zq_ch))
|
| 664 |
+
|
| 665 |
+
up = nn.Module()
|
| 666 |
+
up.block = block
|
| 667 |
+
up.attn = attn
|
| 668 |
+
if i_level != 0:
|
| 669 |
+
up.upsample = Emu3VisionVQUpsample(block_in)
|
| 670 |
+
|
| 671 |
+
self.up.insert(0, up)
|
| 672 |
+
|
| 673 |
+
self.act = Emu3VisionVQActivation()
|
| 674 |
+
|
| 675 |
+
self.norm_out = Emu3VisionVQSpatialNorm(block_in, zq_ch)
|
| 676 |
+
self.conv_out = nn.Conv2d(
|
| 677 |
+
block_in,
|
| 678 |
+
config.out_channels,
|
| 679 |
+
kernel_size=3,
|
| 680 |
+
stride=1,
|
| 681 |
+
padding=1,
|
| 682 |
+
)
|
| 683 |
+
|
| 684 |
+
def forward(self, z: torch.Tensor, zq: torch.Tensor):
|
| 685 |
+
z_zq = torch.cat((z, zq), dim=0)
|
| 686 |
+
z_zq = z_zq.permute(0, 2, 1, 3, 4)
|
| 687 |
+
z_zq = self.time_res_stack(z_zq)
|
| 688 |
+
|
| 689 |
+
for conv in self.time_conv:
|
| 690 |
+
z_zq = self.act(conv(z_zq))
|
| 691 |
+
|
| 692 |
+
z_zq = z_zq.permute(0, 2, 1, 3, 4)
|
| 693 |
+
|
| 694 |
+
h, zq = torch.chunk(z_zq, 2, dim=0)
|
| 695 |
+
|
| 696 |
+
h = h.reshape(-1, *h.shape[2:])
|
| 697 |
+
zq = zq.reshape(-1, *zq.shape[2:])
|
| 698 |
+
|
| 699 |
+
h = self.conv_in(h)
|
| 700 |
+
|
| 701 |
+
# middle
|
| 702 |
+
h = self.mid.block_1(h, zq)
|
| 703 |
+
h = self.mid.attn_1(h, zq)
|
| 704 |
+
h = self.mid.block_2(h, zq)
|
| 705 |
+
|
| 706 |
+
# upsampling
|
| 707 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 708 |
+
for i_block in range(self.num_res_blocks+1):
|
| 709 |
+
h = self.up[i_level].block[i_block](h, zq)
|
| 710 |
+
if len(self.up[i_level].attn) > 0:
|
| 711 |
+
h = self.up[i_level].attn[i_block](h, zq)
|
| 712 |
+
|
| 713 |
+
if i_level != 0:
|
| 714 |
+
h = self.up[i_level].upsample(h)
|
| 715 |
+
|
| 716 |
+
h = self.norm_out(h, zq)
|
| 717 |
+
h = self.act(h)
|
| 718 |
+
h = self.conv_out(h)
|
| 719 |
+
|
| 720 |
+
return h
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
class Emu3VisionVQPretrainedModel(PreTrainedModel):
|
| 724 |
+
"""
|
| 725 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 726 |
+
models.
|
| 727 |
+
"""
|
| 728 |
+
|
| 729 |
+
config_class = Emu3VisionVQConfig
|
| 730 |
+
base_model_prefix = "emuvideovq"
|
| 731 |
+
main_input_name = "pixel_values"
|
| 732 |
+
_no_split_modules = ["Emu3VisionVQResnetBlock", "Emu3VisionVQAttnBlock", "Emu3VisionVQResnetTemporalBlock"]
|
| 733 |
+
|
| 734 |
+
def _init_weights(self, module):
|
| 735 |
+
if isinstance(module, (nn.Conv2d, nn.Conv3d)):
|
| 736 |
+
nn.init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu")
|
| 737 |
+
# copied from the `reset_parameters` method of `class Linear(Module)` in `torch`.
|
| 738 |
+
elif isinstance(module, nn.Linear):
|
| 739 |
+
nn.init.kaiming_uniform_(module.weight, a=math.sqrt(5))
|
| 740 |
+
if module.bias is not None:
|
| 741 |
+
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(module.weight)
|
| 742 |
+
bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
|
| 743 |
+
nn.init.uniform_(module.bias, -bound, bound)
|
| 744 |
+
elif isinstance(module, (nn.BatchNorm2d, nn.BatchNorm3d, nn.GroupNorm)):
|
| 745 |
+
nn.init.constant_(module.weight, 1)
|
| 746 |
+
nn.init.constant_(module.bias, 0)
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
class Emu3VisionVQModel(Emu3VisionVQPretrainedModel):
|
| 750 |
+
|
| 751 |
+
def __init__(self, config):
|
| 752 |
+
super().__init__(config)
|
| 753 |
+
self.config = config
|
| 754 |
+
|
| 755 |
+
self.encoder = Emu3VisionVQEncoder(config)
|
| 756 |
+
self.decoder = Emu3VisionVQDecoder(config)
|
| 757 |
+
self.quantize = Emu3VisionVQVectorQuantizer(config)
|
| 758 |
+
|
| 759 |
+
self.quant_conv = Emu3VisionVQCausalConv3d(config.z_channels, config.embed_dim)
|
| 760 |
+
self.post_quant_conv = Emu3VisionVQCausalConv3d(config.embed_dim, config.z_channels)
|
| 761 |
+
|
| 762 |
+
self.spatial_scale_factor = 2 ** (len(config.ch_mult) - 1)
|
| 763 |
+
|
| 764 |
+
self.post_init()
|
| 765 |
+
|
| 766 |
+
def encode(self, x: torch.Tensor):
|
| 767 |
+
ndim = x.ndim
|
| 768 |
+
if ndim == 4:
|
| 769 |
+
t = self.config.temporal_downsample_factor
|
| 770 |
+
b, c, h, w = x.shape
|
| 771 |
+
x = x.unsqueeze(1).repeat(1, t, 1, 1, 1)
|
| 772 |
+
elif ndim == 5:
|
| 773 |
+
b, t, c, h, w = x.shape
|
| 774 |
+
|
| 775 |
+
h = self.encoder(x)
|
| 776 |
+
|
| 777 |
+
# b t c h w -> b c t h w
|
| 778 |
+
h = h.permute(0, 2, 1, 3, 4)
|
| 779 |
+
h = self.quant_conv(h)
|
| 780 |
+
# b c t h w -> b t c h w
|
| 781 |
+
h = h.permute(0, 2, 1, 3, 4)
|
| 782 |
+
|
| 783 |
+
codes = self.quantize(h)
|
| 784 |
+
|
| 785 |
+
if ndim == 4:
|
| 786 |
+
codes = codes.squeeze(1)
|
| 787 |
+
|
| 788 |
+
return codes
|
| 789 |
+
|
| 790 |
+
def decode(self, x: torch.Tensor):
|
| 791 |
+
ndim = x.ndim
|
| 792 |
+
if ndim == 3:
|
| 793 |
+
x = x.unsqueeze(1)
|
| 794 |
+
|
| 795 |
+
b, t, h, w = x.shape
|
| 796 |
+
quant = self.quantize.embedding(x.flatten())
|
| 797 |
+
c = quant.shape[-1]
|
| 798 |
+
quant = quant.view(b, t, h, w, c).permute(0, 4, 1, 2, 3).contiguous()
|
| 799 |
+
quant2 = self.post_quant_conv(quant)
|
| 800 |
+
|
| 801 |
+
quant = quant.permute(0, 2, 1, 3, 4)
|
| 802 |
+
quant2 = quant2.permute(0, 2, 1, 3, 4)
|
| 803 |
+
|
| 804 |
+
video = self.decoder(quant2, quant)
|
| 805 |
+
video = video.reshape(
|
| 806 |
+
b,
|
| 807 |
+
t * self.config.temporal_downsample_factor,
|
| 808 |
+
self.config.out_channels,
|
| 809 |
+
h * self.spatial_scale_factor,
|
| 810 |
+
w * self.spatial_scale_factor,
|
| 811 |
+
)
|
| 812 |
+
if ndim == 3:
|
| 813 |
+
return video[:, 0]
|
| 814 |
+
return video
|
| 815 |
+
|
| 816 |
+
@property
|
| 817 |
+
def device(self):
|
| 818 |
+
return next(self.parameters()).device
|
| 819 |
+
|
| 820 |
+
@property
|
| 821 |
+
def dtype(self):
|
| 822 |
+
return next(self.parameters()).dtype
|
sjdtree/llamagen/__init__.py
ADDED
|
File without changes
|
sjdtree/llamagen/language/README.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Language models for text-conditional image generation
|
| 2 |
+
|
| 3 |
+
### Requirements
|
| 4 |
+
```
|
| 5 |
+
pip install ftfy
|
| 6 |
+
pip install transformers
|
| 7 |
+
pip install accelerate
|
| 8 |
+
pip install sentencepiece
|
| 9 |
+
pip install pandas
|
| 10 |
+
pip install bs4
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
### Language Models
|
| 14 |
+
Download 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/`
|
sjdtree/llamagen/language/extract_t5_feature.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 3 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 4 |
+
import torch.distributed as dist
|
| 5 |
+
from torch.utils.data import Dataset, DataLoader
|
| 6 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 7 |
+
import numpy as np
|
| 8 |
+
import argparse
|
| 9 |
+
import os
|
| 10 |
+
import json
|
| 11 |
+
|
| 12 |
+
from utils.distributed import init_distributed_mode
|
| 13 |
+
from language.t5 import T5Embedder
|
| 14 |
+
|
| 15 |
+
CAPTION_KEY = {
|
| 16 |
+
'blip': 0,
|
| 17 |
+
'llava': 1,
|
| 18 |
+
'llava_first': 2,
|
| 19 |
+
}
|
| 20 |
+
#################################################################################
|
| 21 |
+
# Training Helper Functions #
|
| 22 |
+
#################################################################################
|
| 23 |
+
class CustomDataset(Dataset):
|
| 24 |
+
def __init__(self, lst_dir, start, end, caption_key, trunc_caption=False):
|
| 25 |
+
img_path_list = []
|
| 26 |
+
for lst_name in sorted(os.listdir(lst_dir))[start: end+1]:
|
| 27 |
+
if not lst_name.endswith('.jsonl'):
|
| 28 |
+
continue
|
| 29 |
+
file_path = os.path.join(lst_dir, lst_name)
|
| 30 |
+
with open(file_path, 'r') as file:
|
| 31 |
+
for line_idx, line in enumerate(file):
|
| 32 |
+
data = json.loads(line)
|
| 33 |
+
# caption = data[caption_key]
|
| 34 |
+
caption = data['text'][CAPTION_KEY[caption_key]]
|
| 35 |
+
code_dir = file_path.split('/')[-1].split('.')[0]
|
| 36 |
+
if trunc_caption:
|
| 37 |
+
caption = caption.split('.')[0]
|
| 38 |
+
img_path_list.append((caption, code_dir, line_idx))
|
| 39 |
+
self.img_path_list = img_path_list
|
| 40 |
+
|
| 41 |
+
def __len__(self):
|
| 42 |
+
return len(self.img_path_list)
|
| 43 |
+
|
| 44 |
+
def __getitem__(self, index):
|
| 45 |
+
caption, code_dir, code_name = self.img_path_list[index]
|
| 46 |
+
return caption, code_dir, code_name
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
#################################################################################
|
| 51 |
+
# Training Loop #
|
| 52 |
+
#################################################################################
|
| 53 |
+
def main(args):
|
| 54 |
+
"""
|
| 55 |
+
Trains a new DiT model.
|
| 56 |
+
"""
|
| 57 |
+
assert torch.cuda.is_available(), "Training currently requires at least one GPU."
|
| 58 |
+
|
| 59 |
+
# Setup DDP:
|
| 60 |
+
# dist.init_process_group("nccl")
|
| 61 |
+
init_distributed_mode(args)
|
| 62 |
+
rank = dist.get_rank()
|
| 63 |
+
device = rank % torch.cuda.device_count()
|
| 64 |
+
seed = args.global_seed * dist.get_world_size() + rank
|
| 65 |
+
torch.manual_seed(seed)
|
| 66 |
+
torch.cuda.set_device(device)
|
| 67 |
+
print(f"Starting rank={rank}, seed={seed}, world_size={dist.get_world_size()}.")
|
| 68 |
+
|
| 69 |
+
# Setup a feature folder:
|
| 70 |
+
if rank == 0:
|
| 71 |
+
os.makedirs(args.t5_path, exist_ok=True)
|
| 72 |
+
|
| 73 |
+
# Setup data:
|
| 74 |
+
print(f"Dataset is preparing...")
|
| 75 |
+
dataset = CustomDataset(args.data_path, args.data_start, args.data_end, args.caption_key, args.trunc_caption)
|
| 76 |
+
sampler = DistributedSampler(
|
| 77 |
+
dataset,
|
| 78 |
+
num_replicas=dist.get_world_size(),
|
| 79 |
+
rank=rank,
|
| 80 |
+
shuffle=False,
|
| 81 |
+
seed=args.global_seed
|
| 82 |
+
)
|
| 83 |
+
loader = DataLoader(
|
| 84 |
+
dataset,
|
| 85 |
+
batch_size=1, # important!
|
| 86 |
+
shuffle=False,
|
| 87 |
+
sampler=sampler,
|
| 88 |
+
num_workers=args.num_workers,
|
| 89 |
+
pin_memory=True,
|
| 90 |
+
drop_last=False
|
| 91 |
+
)
|
| 92 |
+
print(f"Dataset contains {len(dataset):,} images")
|
| 93 |
+
|
| 94 |
+
precision = {'none': torch.float32, 'bf16': torch.bfloat16, 'fp16': torch.float16}[args.precision]
|
| 95 |
+
assert os.path.exists(args.t5_model_path)
|
| 96 |
+
t5_xxl = T5Embedder(
|
| 97 |
+
device=device,
|
| 98 |
+
local_cache=True,
|
| 99 |
+
cache_dir=args.t5_model_path,
|
| 100 |
+
dir_or_name=args.t5_model_type,
|
| 101 |
+
torch_dtype=precision
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
for caption, code_dir, code_name in loader:
|
| 105 |
+
caption_embs, emb_masks = t5_xxl.get_text_embeddings(caption)
|
| 106 |
+
valid_caption_embs = caption_embs[:, :emb_masks.sum()]
|
| 107 |
+
x = valid_caption_embs.to(torch.float32).detach().cpu().numpy()
|
| 108 |
+
os.makedirs(os.path.join(args.t5_path, code_dir[0]), exist_ok=True)
|
| 109 |
+
np.save(os.path.join(args.t5_path, code_dir[0], '{}.npy'.format(code_name.item())), x)
|
| 110 |
+
print(code_name.item())
|
| 111 |
+
|
| 112 |
+
dist.destroy_process_group()
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
if __name__ == "__main__":
|
| 116 |
+
parser = argparse.ArgumentParser()
|
| 117 |
+
parser.add_argument("--data-path", type=str, required=True)
|
| 118 |
+
parser.add_argument("--t5-path", type=str, required=True)
|
| 119 |
+
parser.add_argument("--data-start", type=int, required=True)
|
| 120 |
+
parser.add_argument("--data-end", type=int, required=True)
|
| 121 |
+
parser.add_argument("--caption-key", type=str, default='blip', choices=list(CAPTION_KEY.keys()))
|
| 122 |
+
parser.add_argument("--trunc-caption", action='store_true', default=False)
|
| 123 |
+
parser.add_argument("--t5-model-path", type=str, default='./pretrained_models/t5-ckpt')
|
| 124 |
+
parser.add_argument("--t5-model-type", type=str, default='flan-t5-xl')
|
| 125 |
+
parser.add_argument("--precision", type=str, default='bf16', choices=["none", "fp16", "bf16"])
|
| 126 |
+
parser.add_argument("--global-seed", type=int, default=0)
|
| 127 |
+
parser.add_argument("--num-workers", type=int, default=24)
|
| 128 |
+
args = parser.parse_args()
|
| 129 |
+
main(args)
|
sjdtree/llamagen/language/t5.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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t5.py
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
import html
|
| 6 |
+
import urllib.parse as ul
|
| 7 |
+
|
| 8 |
+
import ftfy
|
| 9 |
+
import torch
|
| 10 |
+
from bs4 import BeautifulSoup
|
| 11 |
+
from transformers import T5EncoderModel, AutoTokenizer
|
| 12 |
+
from huggingface_hub import hf_hub_download
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class T5Embedder:
|
| 16 |
+
available_models = ['t5-v1_1-xxl', 't5-v1_1-xl', 'flan-t5-xl']
|
| 17 |
+
bad_punct_regex = re.compile(r'['+'#®•©™&@·º½¾¿¡§~'+'\)'+'\('+'\]'+'\['+'\}'+'\{'+'\|'+'\\'+'\/'+'\*' + r']{1,}') # noqa
|
| 18 |
+
|
| 19 |
+
def __init__(self, device, dir_or_name='t5-v1_1-xxl', *, local_cache=False, cache_dir=None, hf_token=None, use_text_preprocessing=True,
|
| 20 |
+
t5_model_kwargs=None, torch_dtype=None, use_offload_folder=None, model_max_length=120):
|
| 21 |
+
self.device = torch.device(device)
|
| 22 |
+
self.torch_dtype = torch_dtype or torch.bfloat16
|
| 23 |
+
if t5_model_kwargs is None:
|
| 24 |
+
t5_model_kwargs = {'low_cpu_mem_usage': True, 'torch_dtype': self.torch_dtype}
|
| 25 |
+
t5_model_kwargs['device_map'] = {'shared': self.device, 'encoder': self.device}
|
| 26 |
+
|
| 27 |
+
self.use_text_preprocessing = use_text_preprocessing
|
| 28 |
+
self.hf_token = hf_token
|
| 29 |
+
self.cache_dir = cache_dir or os.path.expanduser('~/.cache/IF_')
|
| 30 |
+
self.dir_or_name = dir_or_name
|
| 31 |
+
tokenizer_path, path = dir_or_name, dir_or_name
|
| 32 |
+
if local_cache:
|
| 33 |
+
cache_dir = os.path.join(self.cache_dir, dir_or_name)
|
| 34 |
+
tokenizer_path, path = cache_dir, cache_dir
|
| 35 |
+
elif dir_or_name in self.available_models:
|
| 36 |
+
cache_dir = os.path.join(self.cache_dir, dir_or_name)
|
| 37 |
+
for filename in [
|
| 38 |
+
'config.json', 'special_tokens_map.json', 'spiece.model', 'tokenizer_config.json',
|
| 39 |
+
'pytorch_model.bin.index.json', 'pytorch_model-00001-of-00002.bin', 'pytorch_model-00002-of-00002.bin'
|
| 40 |
+
]:
|
| 41 |
+
hf_hub_download(repo_id=f'DeepFloyd/{dir_or_name}', filename=filename, cache_dir=cache_dir,
|
| 42 |
+
force_filename=filename, token=self.hf_token)
|
| 43 |
+
tokenizer_path, path = cache_dir, cache_dir
|
| 44 |
+
else:
|
| 45 |
+
cache_dir = os.path.join(self.cache_dir, 't5-v1_1-xxl')
|
| 46 |
+
for filename in [
|
| 47 |
+
'config.json', 'special_tokens_map.json', 'spiece.model', 'tokenizer_config.json',
|
| 48 |
+
]:
|
| 49 |
+
hf_hub_download(repo_id='DeepFloyd/t5-v1_1-xxl', filename=filename, cache_dir=cache_dir,
|
| 50 |
+
force_filename=filename, token=self.hf_token)
|
| 51 |
+
tokenizer_path = cache_dir
|
| 52 |
+
|
| 53 |
+
print(tokenizer_path)
|
| 54 |
+
# self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
|
| 55 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 56 |
+
"google/flan-t5-xl", cache_dir=cache_dir,
|
| 57 |
+
)
|
| 58 |
+
# self.model = T5EncoderModel.from_pretrained(path, **t5_model_kwargs).eval()
|
| 59 |
+
self.model = T5EncoderModel.from_pretrained("google/flan-t5-xl", **t5_model_kwargs).eval()
|
| 60 |
+
self.model_max_length = model_max_length
|
| 61 |
+
|
| 62 |
+
def get_text_embeddings(self, texts):
|
| 63 |
+
texts = [self.text_preprocessing(text) for text in texts]
|
| 64 |
+
|
| 65 |
+
text_tokens_and_mask = self.tokenizer(
|
| 66 |
+
texts,
|
| 67 |
+
max_length=self.model_max_length,
|
| 68 |
+
padding='max_length',
|
| 69 |
+
truncation=True,
|
| 70 |
+
return_attention_mask=True,
|
| 71 |
+
add_special_tokens=True,
|
| 72 |
+
return_tensors='pt'
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
text_tokens_and_mask['input_ids'] = text_tokens_and_mask['input_ids']
|
| 76 |
+
text_tokens_and_mask['attention_mask'] = text_tokens_and_mask['attention_mask']
|
| 77 |
+
|
| 78 |
+
with torch.no_grad():
|
| 79 |
+
text_encoder_embs = self.model(
|
| 80 |
+
input_ids=text_tokens_and_mask['input_ids'].to(self.device),
|
| 81 |
+
attention_mask=text_tokens_and_mask['attention_mask'].to(self.device),
|
| 82 |
+
)['last_hidden_state'].detach()
|
| 83 |
+
return text_encoder_embs, text_tokens_and_mask['attention_mask'].to(self.device)
|
| 84 |
+
|
| 85 |
+
def text_preprocessing(self, text):
|
| 86 |
+
if self.use_text_preprocessing:
|
| 87 |
+
# The exact text cleaning as was in the training stage:
|
| 88 |
+
text = self.clean_caption(text)
|
| 89 |
+
text = self.clean_caption(text)
|
| 90 |
+
return text
|
| 91 |
+
else:
|
| 92 |
+
return text.lower().strip()
|
| 93 |
+
|
| 94 |
+
@staticmethod
|
| 95 |
+
def basic_clean(text):
|
| 96 |
+
text = ftfy.fix_text(text)
|
| 97 |
+
text = html.unescape(html.unescape(text))
|
| 98 |
+
return text.strip()
|
| 99 |
+
|
| 100 |
+
def clean_caption(self, caption):
|
| 101 |
+
caption = str(caption)
|
| 102 |
+
caption = ul.unquote_plus(caption)
|
| 103 |
+
caption = caption.strip().lower()
|
| 104 |
+
caption = re.sub('<person>', 'person', caption)
|
| 105 |
+
# urls:
|
| 106 |
+
caption = re.sub(
|
| 107 |
+
r'\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))', # noqa
|
| 108 |
+
'', caption) # regex for urls
|
| 109 |
+
caption = re.sub(
|
| 110 |
+
r'\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))', # noqa
|
| 111 |
+
'', caption) # regex for urls
|
| 112 |
+
# html:
|
| 113 |
+
caption = BeautifulSoup(caption, features='html.parser').text
|
| 114 |
+
|
| 115 |
+
# @<nickname>
|
| 116 |
+
caption = re.sub(r'@[\w\d]+\b', '', caption)
|
| 117 |
+
|
| 118 |
+
# 31C0—31EF CJK Strokes
|
| 119 |
+
# 31F0—31FF Katakana Phonetic Extensions
|
| 120 |
+
# 3200—32FF Enclosed CJK Letters and Months
|
| 121 |
+
# 3300—33FF CJK Compatibility
|
| 122 |
+
# 3400—4DBF CJK Unified Ideographs Extension A
|
| 123 |
+
# 4DC0—4DFF Yijing Hexagram Symbols
|
| 124 |
+
# 4E00—9FFF CJK Unified Ideographs
|
| 125 |
+
caption = re.sub(r'[\u31c0-\u31ef]+', '', caption)
|
| 126 |
+
caption = re.sub(r'[\u31f0-\u31ff]+', '', caption)
|
| 127 |
+
caption = re.sub(r'[\u3200-\u32ff]+', '', caption)
|
| 128 |
+
caption = re.sub(r'[\u3300-\u33ff]+', '', caption)
|
| 129 |
+
caption = re.sub(r'[\u3400-\u4dbf]+', '', caption)
|
| 130 |
+
caption = re.sub(r'[\u4dc0-\u4dff]+', '', caption)
|
| 131 |
+
caption = re.sub(r'[\u4e00-\u9fff]+', '', caption)
|
| 132 |
+
#######################################################
|
| 133 |
+
|
| 134 |
+
# все виды тире / all types of dash --> "-"
|
| 135 |
+
caption = re.sub(
|
| 136 |
+
r'[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+', # noqa
|
| 137 |
+
'-', caption)
|
| 138 |
+
|
| 139 |
+
# кавычки к одному стандарту
|
| 140 |
+
caption = re.sub(r'[`´«»“”¨]', '"', caption)
|
| 141 |
+
caption = re.sub(r'[‘’]', "'", caption)
|
| 142 |
+
|
| 143 |
+
# "
|
| 144 |
+
caption = re.sub(r'"?', '', caption)
|
| 145 |
+
# &
|
| 146 |
+
caption = re.sub(r'&', '', caption)
|
| 147 |
+
|
| 148 |
+
# ip adresses:
|
| 149 |
+
caption = re.sub(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', ' ', caption)
|
| 150 |
+
|
| 151 |
+
# article ids:
|
| 152 |
+
caption = re.sub(r'\d:\d\d\s+$', '', caption)
|
| 153 |
+
|
| 154 |
+
# \n
|
| 155 |
+
caption = re.sub(r'\\n', ' ', caption)
|
| 156 |
+
|
| 157 |
+
# "#123"
|
| 158 |
+
caption = re.sub(r'#\d{1,3}\b', '', caption)
|
| 159 |
+
# "#12345.."
|
| 160 |
+
caption = re.sub(r'#\d{5,}\b', '', caption)
|
| 161 |
+
# "123456.."
|
| 162 |
+
caption = re.sub(r'\b\d{6,}\b', '', caption)
|
| 163 |
+
# filenames:
|
| 164 |
+
caption = re.sub(r'[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)', '', caption)
|
| 165 |
+
|
| 166 |
+
#
|
| 167 |
+
caption = re.sub(r'[\"\']{2,}', r'"', caption) # """AUSVERKAUFT"""
|
| 168 |
+
caption = re.sub(r'[\.]{2,}', r' ', caption) # """AUSVERKAUFT"""
|
| 169 |
+
|
| 170 |
+
caption = re.sub(self.bad_punct_regex, r' ', caption) # ***AUSVERKAUFT***, #AUSVERKAUFT
|
| 171 |
+
caption = re.sub(r'\s+\.\s+', r' ', caption) # " . "
|
| 172 |
+
|
| 173 |
+
# this-is-my-cute-cat / this_is_my_cute_cat
|
| 174 |
+
regex2 = re.compile(r'(?:\-|\_)')
|
| 175 |
+
if len(re.findall(regex2, caption)) > 3:
|
| 176 |
+
caption = re.sub(regex2, ' ', caption)
|
| 177 |
+
|
| 178 |
+
caption = self.basic_clean(caption)
|
| 179 |
+
|
| 180 |
+
caption = re.sub(r'\b[a-zA-Z]{1,3}\d{3,15}\b', '', caption) # jc6640
|
| 181 |
+
caption = re.sub(r'\b[a-zA-Z]+\d+[a-zA-Z]+\b', '', caption) # jc6640vc
|
| 182 |
+
caption = re.sub(r'\b\d+[a-zA-Z]+\d+\b', '', caption) # 6640vc231
|
| 183 |
+
|
| 184 |
+
caption = re.sub(r'(worldwide\s+)?(free\s+)?shipping', '', caption)
|
| 185 |
+
caption = re.sub(r'(free\s)?download(\sfree)?', '', caption)
|
| 186 |
+
caption = re.sub(r'\bclick\b\s(?:for|on)\s\w+', '', caption)
|
| 187 |
+
caption = re.sub(r'\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?', '', caption)
|
| 188 |
+
caption = re.sub(r'\bpage\s+\d+\b', '', caption)
|
| 189 |
+
|
| 190 |
+
caption = re.sub(r'\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\b', r' ', caption) # j2d1a2a...
|
| 191 |
+
|
| 192 |
+
caption = re.sub(r'\b\d+\.?\d*[xх×]\d+\.?\d*\b', '', caption)
|
| 193 |
+
|
| 194 |
+
caption = re.sub(r'\b\s+\:\s+', r': ', caption)
|
| 195 |
+
caption = re.sub(r'(\D[,\./])\b', r'\1 ', caption)
|
| 196 |
+
caption = re.sub(r'\s+', ' ', caption)
|
| 197 |
+
|
| 198 |
+
caption.strip()
|
| 199 |
+
|
| 200 |
+
caption = re.sub(r'^[\"\']([\w\W]+)[\"\']$', r'\1', caption)
|
| 201 |
+
caption = re.sub(r'^[\'\_,\-\:;]', r'', caption)
|
| 202 |
+
caption = re.sub(r'[\'\_,\-\:\-\+]$', r'', caption)
|
| 203 |
+
caption = re.sub(r'^\.\S+$', '', caption)
|
| 204 |
+
|
| 205 |
+
return caption.strip()
|
sjdtree/llamagen/llamagen.py
ADDED
|
@@ -0,0 +1,504 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modified from:
|
| 2 |
+
# VQGAN: https://github.com/CompVis/taming-transformers/blob/master/taming/modules/transformer/mingpt.py
|
| 3 |
+
# DiT: https://github.com/facebookresearch/DiT/blob/main/models.py
|
| 4 |
+
# nanoGPT: https://github.com/karpathy/nanoGPT/blob/master/model.py
|
| 5 |
+
# llama: https://github.com/facebookresearch/llama/blob/main/llama/model.py
|
| 6 |
+
# gpt-fast: https://github.com/pytorch-labs/gpt-fast/blob/main/model.py
|
| 7 |
+
# PixArt: https://github.com/PixArt-alpha/PixArt-alpha/blob/master/diffusion/model/nets/PixArt_blocks.py
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from typing import Optional, List
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
from torch.nn import functional as F
|
| 15 |
+
|
| 16 |
+
def drop_path(x, drop_prob: float = 0., training: bool = False, scale_by_keep: bool = True):
|
| 17 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 18 |
+
|
| 19 |
+
This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
|
| 20 |
+
the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
|
| 21 |
+
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
|
| 22 |
+
changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
|
| 23 |
+
'survival rate' as the argument.
|
| 24 |
+
|
| 25 |
+
"""
|
| 26 |
+
if drop_prob == 0. or not training:
|
| 27 |
+
return x
|
| 28 |
+
keep_prob = 1 - drop_prob
|
| 29 |
+
shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 30 |
+
random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
|
| 31 |
+
if keep_prob > 0.0 and scale_by_keep:
|
| 32 |
+
random_tensor.div_(keep_prob)
|
| 33 |
+
return x * random_tensor
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class DropPath(torch.nn.Module):
|
| 37 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 38 |
+
"""
|
| 39 |
+
def __init__(self, drop_prob: float = 0., scale_by_keep: bool = True):
|
| 40 |
+
super(DropPath, self).__init__()
|
| 41 |
+
self.drop_prob = drop_prob
|
| 42 |
+
self.scale_by_keep = scale_by_keep
|
| 43 |
+
|
| 44 |
+
def forward(self, x):
|
| 45 |
+
return drop_path(x, self.drop_prob, self.training, self.scale_by_keep)
|
| 46 |
+
|
| 47 |
+
def extra_repr(self):
|
| 48 |
+
return f'drop_prob={round(self.drop_prob,3):0.3f}'
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def find_multiple(n: int, k: int):
|
| 52 |
+
if n % k == 0:
|
| 53 |
+
return n
|
| 54 |
+
return n + k - (n % k)
|
| 55 |
+
|
| 56 |
+
@dataclass
|
| 57 |
+
class ModelArgs:
|
| 58 |
+
dim: int = 4096
|
| 59 |
+
n_layer: int = 32
|
| 60 |
+
n_head: int = 32
|
| 61 |
+
n_kv_head: Optional[int] = None
|
| 62 |
+
multiple_of: int = 256 # make SwiGLU hidden layer size multiple of large power of 2
|
| 63 |
+
ffn_dim_multiplier: Optional[float] = None
|
| 64 |
+
rope_base: float = 10000
|
| 65 |
+
norm_eps: float = 1e-5
|
| 66 |
+
initializer_range: float = 0.02
|
| 67 |
+
|
| 68 |
+
token_dropout_p: float = 0.1
|
| 69 |
+
attn_dropout_p: float = 0.0
|
| 70 |
+
resid_dropout_p: float = 0.1
|
| 71 |
+
ffn_dropout_p: float = 0.1
|
| 72 |
+
drop_path_rate: float = 0.0
|
| 73 |
+
|
| 74 |
+
num_classes: int = 1000
|
| 75 |
+
caption_dim: int = 2048
|
| 76 |
+
class_dropout_prob: float = 0.1
|
| 77 |
+
model_type: str = 'c2i'
|
| 78 |
+
|
| 79 |
+
vocab_size: int = 16384
|
| 80 |
+
cls_token_num: int = 1
|
| 81 |
+
block_size: int = 256
|
| 82 |
+
max_batch_size: int = 32
|
| 83 |
+
max_seq_len: int = 2048
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
#################################################################################
|
| 87 |
+
# Embedding Layers for Class Labels #
|
| 88 |
+
#################################################################################
|
| 89 |
+
class LabelEmbedder(nn.Module):
|
| 90 |
+
"""
|
| 91 |
+
Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.
|
| 92 |
+
"""
|
| 93 |
+
def __init__(self, num_classes, hidden_size, dropout_prob):
|
| 94 |
+
super().__init__()
|
| 95 |
+
use_cfg_embedding = dropout_prob > 0
|
| 96 |
+
self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size)
|
| 97 |
+
self.num_classes = num_classes
|
| 98 |
+
self.dropout_prob = dropout_prob
|
| 99 |
+
|
| 100 |
+
def token_drop(self, labels, force_drop_ids=None):
|
| 101 |
+
"""
|
| 102 |
+
Drops labels to enable classifier-free guidance.
|
| 103 |
+
"""
|
| 104 |
+
if force_drop_ids is None:
|
| 105 |
+
drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob
|
| 106 |
+
else:
|
| 107 |
+
drop_ids = force_drop_ids == 1
|
| 108 |
+
labels = torch.where(drop_ids, self.num_classes, labels)
|
| 109 |
+
return labels
|
| 110 |
+
|
| 111 |
+
def forward(self, labels, train, force_drop_ids=None):
|
| 112 |
+
use_dropout = self.dropout_prob > 0
|
| 113 |
+
if (train and use_dropout) or (force_drop_ids is not None):
|
| 114 |
+
labels = self.token_drop(labels, force_drop_ids)
|
| 115 |
+
embeddings = self.embedding_table(labels).unsqueeze(1)
|
| 116 |
+
return embeddings
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
#################################################################################
|
| 120 |
+
# Embedding Layers for Text Feature #
|
| 121 |
+
#################################################################################
|
| 122 |
+
class CaptionEmbedder(nn.Module):
|
| 123 |
+
"""
|
| 124 |
+
Embeds text caption into vector representations. Also handles label dropout for classifier-free guidance.
|
| 125 |
+
"""
|
| 126 |
+
def __init__(self, in_channels, hidden_size, uncond_prob, token_num=120):
|
| 127 |
+
super().__init__()
|
| 128 |
+
self.cap_proj = MLP(in_features=in_channels, hidden_features=hidden_size, out_features=hidden_size)
|
| 129 |
+
self.register_buffer("uncond_embedding", nn.Parameter(torch.randn(token_num, in_channels) / in_channels ** 0.5))
|
| 130 |
+
self.uncond_prob = uncond_prob
|
| 131 |
+
|
| 132 |
+
def token_drop(self, caption, force_drop_ids=None):
|
| 133 |
+
"""
|
| 134 |
+
Drops labels to enable classifier-free guidance.
|
| 135 |
+
"""
|
| 136 |
+
if force_drop_ids is None:
|
| 137 |
+
drop_ids = torch.rand(caption.shape[0], device=caption.device) < self.uncond_prob
|
| 138 |
+
else:
|
| 139 |
+
drop_ids = force_drop_ids == 1
|
| 140 |
+
caption = torch.where(drop_ids[:, None, None], self.uncond_embedding, caption)
|
| 141 |
+
return caption
|
| 142 |
+
|
| 143 |
+
def forward(self, caption, train, force_drop_ids=None):
|
| 144 |
+
use_dropout = self.uncond_prob > 0
|
| 145 |
+
if (train and use_dropout) or (force_drop_ids is not None):
|
| 146 |
+
caption = self.token_drop(caption, force_drop_ids)
|
| 147 |
+
embeddings = self.cap_proj(caption)
|
| 148 |
+
return embeddings
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class MLP(nn.Module):
|
| 152 |
+
def __init__(self, in_features, hidden_features, out_features):
|
| 153 |
+
super().__init__()
|
| 154 |
+
out_features = out_features or in_features
|
| 155 |
+
hidden_features = hidden_features or in_features
|
| 156 |
+
self.fc1 = nn.Linear(in_features, hidden_features, bias=False)
|
| 157 |
+
self.act = nn.GELU(approximate='tanh')
|
| 158 |
+
self.fc2 = nn.Linear(hidden_features, out_features, bias=False)
|
| 159 |
+
|
| 160 |
+
def forward(self, x):
|
| 161 |
+
x = self.fc1(x)
|
| 162 |
+
x = self.act(x)
|
| 163 |
+
x = self.fc2(x)
|
| 164 |
+
return x
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
#################################################################################
|
| 168 |
+
# GPT Model #
|
| 169 |
+
#################################################################################
|
| 170 |
+
class RMSNorm(torch.nn.Module):
|
| 171 |
+
def __init__(self, dim: int, eps: float = 1e-5):
|
| 172 |
+
super().__init__()
|
| 173 |
+
self.eps = eps
|
| 174 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 175 |
+
|
| 176 |
+
def _norm(self, x):
|
| 177 |
+
return x * torch.rsqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps)
|
| 178 |
+
|
| 179 |
+
def forward(self, x):
|
| 180 |
+
output = self._norm(x.float()).type_as(x)
|
| 181 |
+
return output * self.weight
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class FeedForward(nn.Module):
|
| 185 |
+
def __init__(self, config: ModelArgs):
|
| 186 |
+
super().__init__()
|
| 187 |
+
hidden_dim = 4 * config.dim
|
| 188 |
+
hidden_dim = int(2 * hidden_dim / 3)
|
| 189 |
+
# custom dim factor multiplier
|
| 190 |
+
if config.ffn_dim_multiplier is not None:
|
| 191 |
+
hidden_dim = int(config.ffn_dim_multiplier * hidden_dim)
|
| 192 |
+
hidden_dim = find_multiple(hidden_dim, config.multiple_of)
|
| 193 |
+
|
| 194 |
+
self.w1 = nn.Linear(config.dim, hidden_dim, bias=False)
|
| 195 |
+
self.w3 = nn.Linear(config.dim, hidden_dim, bias=False)
|
| 196 |
+
self.w2 = nn.Linear(hidden_dim, config.dim, bias=False)
|
| 197 |
+
self.ffn_dropout = nn.Dropout(config.ffn_dropout_p)
|
| 198 |
+
|
| 199 |
+
def forward(self, x):
|
| 200 |
+
return self.ffn_dropout(self.w2(F.silu(self.w1(x)) * self.w3(x)))
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class KVCache(nn.Module):
|
| 204 |
+
def __init__(self, max_batch_size, max_seq_length, n_head, head_dim, dtype):
|
| 205 |
+
super().__init__()
|
| 206 |
+
cache_shape = (max_batch_size, n_head, max_seq_length, head_dim)
|
| 207 |
+
self.register_buffer('k_cache', torch.zeros(cache_shape, dtype=dtype))
|
| 208 |
+
self.register_buffer('v_cache', torch.zeros(cache_shape, dtype=dtype))
|
| 209 |
+
|
| 210 |
+
def update(self, input_pos, k_val, v_val):
|
| 211 |
+
# input_pos: [S], k_val: [B, H, S, D]
|
| 212 |
+
# print('input_pos kv', input_pos.shape, input_pos)
|
| 213 |
+
assert input_pos.shape[0] == k_val.shape[2]
|
| 214 |
+
k_out = self.k_cache
|
| 215 |
+
v_out = self.v_cache
|
| 216 |
+
k_out[:, :, input_pos] = k_val
|
| 217 |
+
v_out[:, :, input_pos] = v_val
|
| 218 |
+
|
| 219 |
+
return k_out, v_out
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
class Attention(nn.Module):
|
| 223 |
+
def __init__(self, config: ModelArgs):
|
| 224 |
+
super().__init__()
|
| 225 |
+
assert config.dim % config.n_head == 0
|
| 226 |
+
self.dim = config.dim
|
| 227 |
+
self.head_dim = config.dim // config.n_head
|
| 228 |
+
self.n_head = config.n_head
|
| 229 |
+
self.n_kv_head = config.n_kv_head if config.n_kv_head is not None else config.n_head
|
| 230 |
+
total_kv_dim = (self.n_head + 2 * self.n_kv_head) * self.head_dim
|
| 231 |
+
|
| 232 |
+
# key, query, value projections for all heads, but in a batch
|
| 233 |
+
self.wqkv = nn.Linear(config.dim, total_kv_dim, bias=False)
|
| 234 |
+
self.wo = nn.Linear(config.dim, config.dim, bias=False)
|
| 235 |
+
self.kv_cache = None
|
| 236 |
+
|
| 237 |
+
# regularization
|
| 238 |
+
self.attn_dropout_p = config.attn_dropout_p
|
| 239 |
+
self.resid_dropout = nn.Dropout(config.resid_dropout_p)
|
| 240 |
+
|
| 241 |
+
def forward(
|
| 242 |
+
self, x: torch.Tensor, freqs_cis: torch.Tensor = None,
|
| 243 |
+
input_pos: Optional[torch.Tensor] = None,
|
| 244 |
+
mask: Optional[torch.Tensor] = None
|
| 245 |
+
):
|
| 246 |
+
bsz, seqlen, _ = x.shape
|
| 247 |
+
kv_size = self.n_kv_head * self.head_dim
|
| 248 |
+
xq, xk, xv = self.wqkv(x).split([self.dim, kv_size, kv_size], dim=-1)
|
| 249 |
+
|
| 250 |
+
xq = xq.view(bsz, seqlen, self.n_head, self.head_dim)
|
| 251 |
+
xk = xk.view(bsz, seqlen, self.n_kv_head, self.head_dim)
|
| 252 |
+
xv = xv.view(bsz, seqlen, self.n_kv_head, self.head_dim)
|
| 253 |
+
|
| 254 |
+
xq = apply_rotary_emb(xq, freqs_cis)
|
| 255 |
+
xk = apply_rotary_emb(xk, freqs_cis)
|
| 256 |
+
|
| 257 |
+
xq, xk, xv = map(lambda x: x.transpose(1, 2), (xq, xk, xv))
|
| 258 |
+
|
| 259 |
+
if self.kv_cache is not None:
|
| 260 |
+
keys, values = self.kv_cache.update(input_pos, xk, xv)
|
| 261 |
+
# print('sdf', keys.shape, values.shape)
|
| 262 |
+
else:
|
| 263 |
+
keys, values = xk, xv
|
| 264 |
+
keys = keys.repeat_interleave(self.n_head // self.n_kv_head, dim=1)
|
| 265 |
+
values = values.repeat_interleave(self.n_head // self.n_kv_head, dim=1)
|
| 266 |
+
|
| 267 |
+
# print(xq.shape, keys.shape, values.shape, mask.shape, self.n_kv_head, self.n_head, seqlen)
|
| 268 |
+
|
| 269 |
+
output = F.scaled_dot_product_attention(
|
| 270 |
+
xq, keys, values,
|
| 271 |
+
attn_mask=mask,
|
| 272 |
+
is_causal=True if mask is None else False, # is_causal=False is for KV cache
|
| 273 |
+
dropout_p=self.attn_dropout_p if self.training else 0)
|
| 274 |
+
|
| 275 |
+
output = output.transpose(1, 2).contiguous().view(bsz, seqlen, self.dim)
|
| 276 |
+
|
| 277 |
+
output = self.resid_dropout(self.wo(output))
|
| 278 |
+
return output
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
class TransformerBlock(nn.Module):
|
| 282 |
+
def __init__(self, config: ModelArgs, drop_path: float):
|
| 283 |
+
super().__init__()
|
| 284 |
+
self.attention = Attention(config)
|
| 285 |
+
self.feed_forward = FeedForward(config)
|
| 286 |
+
self.attention_norm = RMSNorm(config.dim, eps=config.norm_eps)
|
| 287 |
+
self.ffn_norm = RMSNorm(config.dim, eps=config.norm_eps)
|
| 288 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
| 289 |
+
|
| 290 |
+
def forward(
|
| 291 |
+
self, x: torch.Tensor, freqs_cis: torch.Tensor, start_pos: int, mask: Optional[torch.Tensor] = None):
|
| 292 |
+
h = x + self.drop_path(self.attention(self.attention_norm(x), freqs_cis, start_pos, mask))
|
| 293 |
+
out = h + self.drop_path(self.feed_forward(self.ffn_norm(h)))
|
| 294 |
+
return out
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
class Transformer(nn.Module):
|
| 298 |
+
def __init__(self, config: ModelArgs):
|
| 299 |
+
super().__init__()
|
| 300 |
+
self.config = config
|
| 301 |
+
self.vocab_size = config.vocab_size
|
| 302 |
+
self.n_layer = config.n_layer
|
| 303 |
+
self.block_size = config.block_size
|
| 304 |
+
self.num_classes = config.num_classes
|
| 305 |
+
self.model_type = config.model_type
|
| 306 |
+
self.cls_token_num = config.cls_token_num
|
| 307 |
+
if self.model_type == 'c2i':
|
| 308 |
+
self.cls_embedding = LabelEmbedder(config.num_classes, config.dim, config.class_dropout_prob)
|
| 309 |
+
elif self.model_type == 't2i':
|
| 310 |
+
self.cls_embedding = CaptionEmbedder(config.caption_dim, config.dim, config.class_dropout_prob)
|
| 311 |
+
else:
|
| 312 |
+
raise Exception("please check model type")
|
| 313 |
+
self.tok_embeddings = nn.Embedding(config.vocab_size, config.dim)
|
| 314 |
+
self.tok_dropout = nn.Dropout(config.token_dropout_p)
|
| 315 |
+
|
| 316 |
+
# transformer blocks
|
| 317 |
+
dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.n_layer)]
|
| 318 |
+
self.layers = torch.nn.ModuleList()
|
| 319 |
+
for layer_id in range(config.n_layer):
|
| 320 |
+
self.layers.append(TransformerBlock(config, dpr[layer_id]))
|
| 321 |
+
|
| 322 |
+
# output layer
|
| 323 |
+
self.norm = RMSNorm(config.dim, eps=config.norm_eps)
|
| 324 |
+
self.output = nn.Linear(config.dim, config.vocab_size, bias=False)
|
| 325 |
+
|
| 326 |
+
# 2d rotary pos embedding
|
| 327 |
+
grid_size = int(self.block_size ** 0.5)
|
| 328 |
+
assert grid_size * grid_size == self.block_size
|
| 329 |
+
self.freqs_cis = precompute_freqs_cis_2d(grid_size, self.config.dim // self.config.n_head, self.config.rope_base, self.cls_token_num)
|
| 330 |
+
|
| 331 |
+
# KVCache
|
| 332 |
+
self.max_batch_size = -1
|
| 333 |
+
self.max_seq_length = -1
|
| 334 |
+
|
| 335 |
+
self.initialize_weights()
|
| 336 |
+
|
| 337 |
+
def initialize_weights(self):
|
| 338 |
+
# Initialize nn.Linear and nn.Embedding
|
| 339 |
+
self.apply(self._init_weights)
|
| 340 |
+
|
| 341 |
+
# Zero-out output layers:
|
| 342 |
+
nn.init.constant_(self.output.weight, 0)
|
| 343 |
+
|
| 344 |
+
def _init_weights(self, module):
|
| 345 |
+
std = self.config.initializer_range
|
| 346 |
+
if isinstance(module, nn.Linear):
|
| 347 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 348 |
+
if module.bias is not None:
|
| 349 |
+
module.bias.data.zero_()
|
| 350 |
+
elif isinstance(module, nn.Embedding):
|
| 351 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 352 |
+
|
| 353 |
+
def setup_caches(self, max_batch_size, max_seq_length, dtype):
|
| 354 |
+
# if self.max_seq_length >= max_seq_length and self.max_batch_size >= max_batch_size:
|
| 355 |
+
# return
|
| 356 |
+
head_dim = self.config.dim // self.config.n_head
|
| 357 |
+
max_seq_length = find_multiple(max_seq_length, 8)
|
| 358 |
+
self.max_seq_length = max_seq_length
|
| 359 |
+
self.max_batch_size = max_batch_size
|
| 360 |
+
for b in self.layers:
|
| 361 |
+
b.attention.kv_cache = KVCache(max_batch_size, max_seq_length, self.config.n_head, head_dim, dtype)
|
| 362 |
+
|
| 363 |
+
causal_mask = torch.tril(torch.ones(self.max_seq_length, self.max_seq_length, dtype=torch.bool))
|
| 364 |
+
self.causal_mask = causal_mask.unsqueeze(0).repeat(self.max_batch_size, 1, 1)
|
| 365 |
+
grid_size = int(self.config.block_size ** 0.5)
|
| 366 |
+
assert grid_size * grid_size == self.block_size
|
| 367 |
+
self.freqs_cis = precompute_freqs_cis_2d(grid_size, self.config.dim // self.config.n_head, self.config.rope_base, self.cls_token_num)
|
| 368 |
+
|
| 369 |
+
def forward(
|
| 370 |
+
self,
|
| 371 |
+
idx: torch.Tensor,
|
| 372 |
+
cond_idx: torch.Tensor, # cond_idx_or_embed
|
| 373 |
+
input_pos: Optional[torch.Tensor] = None,
|
| 374 |
+
targets: Optional[torch.Tensor] = None,
|
| 375 |
+
mask: Optional[torch.Tensor] = None,
|
| 376 |
+
valid: Optional[torch.Tensor] = None,
|
| 377 |
+
):
|
| 378 |
+
if idx is not None and cond_idx is not None: # training or naive inference
|
| 379 |
+
cond_embeddings = self.cls_embedding(cond_idx, train=self.training)[:,:self.cls_token_num]
|
| 380 |
+
token_embeddings = self.tok_embeddings(idx)
|
| 381 |
+
token_embeddings = torch.cat((cond_embeddings, token_embeddings), dim=1)
|
| 382 |
+
h = self.tok_dropout(token_embeddings)
|
| 383 |
+
self.freqs_cis = self.freqs_cis.to(h.device)
|
| 384 |
+
else:
|
| 385 |
+
if cond_idx is not None: # prefill in inference
|
| 386 |
+
token_embeddings = self.cls_embedding(cond_idx, train=self.training)[:,:self.cls_token_num]
|
| 387 |
+
else: # decode_n_tokens(kv cache) in inference
|
| 388 |
+
token_embeddings = self.tok_embeddings(idx)
|
| 389 |
+
|
| 390 |
+
bs = token_embeddings.shape[0]
|
| 391 |
+
mask = self.causal_mask[:bs, None, input_pos]
|
| 392 |
+
h = self.tok_dropout(token_embeddings)
|
| 393 |
+
self.freqs_cis = self.freqs_cis
|
| 394 |
+
|
| 395 |
+
if self.training:
|
| 396 |
+
freqs_cis = self.freqs_cis[:token_embeddings.shape[1]]
|
| 397 |
+
else:
|
| 398 |
+
freqs_cis = self.freqs_cis[input_pos]
|
| 399 |
+
# transformer blocks
|
| 400 |
+
for layer in self.layers:
|
| 401 |
+
h = layer(h, freqs_cis, input_pos, mask)
|
| 402 |
+
|
| 403 |
+
# output layers
|
| 404 |
+
h = self.norm(h)
|
| 405 |
+
logits = self.output(h).float()
|
| 406 |
+
|
| 407 |
+
if self.training:
|
| 408 |
+
logits = logits[:, self.cls_token_num - 1:].contiguous()
|
| 409 |
+
|
| 410 |
+
# if we are given some desired targets also calculate the loss
|
| 411 |
+
loss = None
|
| 412 |
+
if valid is not None:
|
| 413 |
+
loss_all = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), reduction='none')
|
| 414 |
+
valid_all = valid[:,None].repeat(1, targets.shape[1]).view(-1)
|
| 415 |
+
loss = (loss_all * valid_all).sum() / max(valid_all.sum(), 1)
|
| 416 |
+
elif targets is not None:
|
| 417 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
|
| 418 |
+
|
| 419 |
+
return logits, loss
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def get_fsdp_wrap_module_list(self) -> List[nn.Module]:
|
| 423 |
+
return list(self.layers)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
#################################################################################
|
| 428 |
+
# Rotary Positional Embedding Functions #
|
| 429 |
+
#################################################################################
|
| 430 |
+
# https://github.com/pytorch-labs/gpt-fast/blob/main/model.py
|
| 431 |
+
def precompute_freqs_cis(seq_len: int, n_elem: int, base: int = 10000, cls_token_num=120):
|
| 432 |
+
freqs = 1.0 / (base ** (torch.arange(0, n_elem, 2)[: (n_elem // 2)].float() / n_elem))
|
| 433 |
+
t = torch.arange(seq_len, device=freqs.device)
|
| 434 |
+
freqs = torch.outer(t, freqs) # (seq_len, head_dim // 2)
|
| 435 |
+
freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
|
| 436 |
+
cache = torch.stack([freqs_cis.real, freqs_cis.imag], dim=-1) # (cls_token_num+seq_len, head_dim // 2, 2)
|
| 437 |
+
cond_cache = torch.cat([torch.zeros(cls_token_num, n_elem // 2, 2), cache]) # (cls_token_num+seq_len, head_dim // 2, 2)
|
| 438 |
+
return cond_cache
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def precompute_freqs_cis_2d(grid_size: int, n_elem: int, base: int = 10000, cls_token_num=120):
|
| 442 |
+
# split the dimension into half, one for x and one for y
|
| 443 |
+
half_dim = n_elem // 2
|
| 444 |
+
freqs = 1.0 / (base ** (torch.arange(0, half_dim, 2)[: (half_dim // 2)].float() / half_dim))
|
| 445 |
+
t = torch.arange(grid_size, device=freqs.device)
|
| 446 |
+
freqs = torch.outer(t, freqs) # (grid_size, head_dim // 2)
|
| 447 |
+
freqs_grid = torch.concat([
|
| 448 |
+
freqs[:, None, :].expand(-1, grid_size, -1),
|
| 449 |
+
freqs[None, :, :].expand(grid_size, -1, -1),
|
| 450 |
+
], dim=-1) # (grid_size, grid_size, head_dim // 2)
|
| 451 |
+
cache_grid = torch.stack([torch.cos(freqs_grid), torch.sin(freqs_grid)], dim=-1) # (grid_size, grid_size, head_dim // 2, 2)
|
| 452 |
+
cache = cache_grid.flatten(0, 1)
|
| 453 |
+
cond_cache = torch.cat([torch.zeros(cls_token_num, n_elem // 2, 2), cache]) # (cls_token_num+grid_size**2, head_dim // 2, 2)
|
| 454 |
+
return cond_cache
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def apply_rotary_emb(x: torch.Tensor, freqs_cis: torch.Tensor):
|
| 458 |
+
# x: (bs, seq_len, n_head, head_dim)
|
| 459 |
+
# freqs_cis (seq_len, head_dim // 2, 2)
|
| 460 |
+
xshaped = x.float().reshape(*x.shape[:-1], -1, 2) # (bs, seq_len, n_head, head_dim//2, 2)
|
| 461 |
+
freqs_cis = freqs_cis.view(1, xshaped.size(1), 1, xshaped.size(3), 2) # (1, seq_len, 1, head_dim//2, 2)
|
| 462 |
+
x_out2 = torch.stack([
|
| 463 |
+
xshaped[..., 0] * freqs_cis[..., 0] - xshaped[..., 1] * freqs_cis[..., 1],
|
| 464 |
+
xshaped[..., 1] * freqs_cis[..., 0] + xshaped[..., 0] * freqs_cis[..., 1],
|
| 465 |
+
], dim=-1)
|
| 466 |
+
x_out2 = x_out2.flatten(3)
|
| 467 |
+
return x_out2.type_as(x)
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
#################################################################################
|
| 472 |
+
# GPT Configs #
|
| 473 |
+
#################################################################################
|
| 474 |
+
### text-conditional
|
| 475 |
+
def GPT_7B(**kwargs):
|
| 476 |
+
return Transformer(ModelArgs(n_layer=32, n_head=32, dim=4096, **kwargs)) # 6.6B
|
| 477 |
+
|
| 478 |
+
def GPT_3B(**kwargs):
|
| 479 |
+
return Transformer(ModelArgs(n_layer=24, n_head=32, dim=3200, **kwargs)) # 3.1B
|
| 480 |
+
|
| 481 |
+
def GPT_1B(**kwargs):
|
| 482 |
+
return Transformer(ModelArgs(n_layer=22, n_head=32, dim=2048, **kwargs)) # 1.2B
|
| 483 |
+
|
| 484 |
+
### class-conditional
|
| 485 |
+
def GPT_XXXL(**kwargs):
|
| 486 |
+
return Transformer(ModelArgs(n_layer=48, n_head=40, dim=2560, **kwargs)) # 3.9B
|
| 487 |
+
|
| 488 |
+
def GPT_XXL(**kwargs):
|
| 489 |
+
return Transformer(ModelArgs(n_layer=48, n_head=24, dim=1536, **kwargs)) # 1.4B
|
| 490 |
+
|
| 491 |
+
def GPT_XL(**kwargs):
|
| 492 |
+
return Transformer(ModelArgs(n_layer=36, n_head=20, dim=1280, **kwargs)) # 775M
|
| 493 |
+
|
| 494 |
+
def GPT_L(**kwargs):
|
| 495 |
+
return Transformer(ModelArgs(n_layer=24, n_head=16, dim=1024, **kwargs)) # 343M
|
| 496 |
+
|
| 497 |
+
def GPT_B(**kwargs):
|
| 498 |
+
return Transformer(ModelArgs(n_layer=12, n_head=12, dim=768, **kwargs)) # 111M
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
GPT_models = {
|
| 502 |
+
'GPT-B': GPT_B, 'GPT-L': GPT_L, 'GPT-XL': GPT_XL, 'GPT-XXL': GPT_XXL, 'G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|
+
import os
|
| 6 |
+
|
| 7 |
+
import torch._dynamo.config
|
| 8 |
+
import torch._inductor.config
|
| 9 |
+
import copy
|
| 10 |
+
|
| 11 |
+
from typing import Optional, Tuple
|
| 12 |
+
|
| 13 |
+
import transformers
|
| 14 |
+
from transformers.generation.utils import GenerationMixin
|
| 15 |
+
|
| 16 |
+
from transformers.generation.logits_process import LogitsProcessor, LogitsProcessorList, LogitsWarper
|
| 17 |
+
from transformers.generation.logits_process import TopKLogitsWarper
|
| 18 |
+
from transformers import GenerationConfig
|
| 19 |
+
|
| 20 |
+
from transformers.utils import ModelOutput
|
| 21 |
+
from dataclasses import dataclass
|
| 22 |
+
|
| 23 |
+
from transformers import StoppingCriteria, StoppingCriteriaList
|
| 24 |
+
|
| 25 |
+
from transformers.cache_utils import Cache, DynamicCache
|
| 26 |
+
|
| 27 |
+
from scheduler.logit_processor_3dim import TopPLogitsWarper3d
|
| 28 |
+
|
| 29 |
+
@dataclass
|
| 30 |
+
class BackboneOutput(ModelOutput):
|
| 31 |
+
logits: torch.Tensor = None
|
| 32 |
+
past_key_values: Cache = None
|
| 33 |
+
|
| 34 |
+
def top_k_top_p_filtering(
|
| 35 |
+
logits,
|
| 36 |
+
top_k: int = 0,
|
| 37 |
+
top_p: float = 1.0,
|
| 38 |
+
filter_value: float = -float("Inf"),
|
| 39 |
+
min_tokens_to_keep: int = 1,
|
| 40 |
+
):
|
| 41 |
+
"""Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
|
| 42 |
+
Args:
|
| 43 |
+
logits: logits distribution shape (batch size, vocabulary size)
|
| 44 |
+
if top_k > 0: keep only top k tokens with highest probability (top-k filtering).
|
| 45 |
+
if top_p < 1.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering).
|
| 46 |
+
Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751)
|
| 47 |
+
Make sure we keep at least min_tokens_to_keep per batch example in the output
|
| 48 |
+
From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317
|
| 49 |
+
"""
|
| 50 |
+
if top_k > 0:
|
| 51 |
+
top_k = min(max(top_k, min_tokens_to_keep), logits.size(-1)) # Safety check
|
| 52 |
+
# Remove all tokens with a probability less than the last token of the top-k
|
| 53 |
+
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
|
| 54 |
+
logits[indices_to_remove] = filter_value
|
| 55 |
+
|
| 56 |
+
if top_p < 1.0:
|
| 57 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
| 58 |
+
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
| 59 |
+
|
| 60 |
+
# Remove tokens with cumulative probability above the threshold (token with 0 are kept)
|
| 61 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
| 62 |
+
if min_tokens_to_keep > 1:
|
| 63 |
+
# Keep at least min_tokens_to_keep (set to min_tokens_to_keep-1 because we add the first one below)
|
| 64 |
+
sorted_indices_to_remove[..., :min_tokens_to_keep] = 0
|
| 65 |
+
# Shift the indices to the right to keep also the first token above the threshold
|
| 66 |
+
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
|
| 67 |
+
sorted_indices_to_remove[..., 0] = 0
|
| 68 |
+
|
| 69 |
+
# scatter sorted tensors to original indexing
|
| 70 |
+
indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
|
| 71 |
+
logits[indices_to_remove] = filter_value
|
| 72 |
+
return logits
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def sample(logits, temperature: float=1.0, top_k: int=0, top_p: float=1.0, sample_logits=True):
|
| 76 |
+
logits = logits[:, -1, :] / max(temperature, 1e-5)
|
| 77 |
+
if top_k > 0 or top_p < 1.0:
|
| 78 |
+
logits = top_k_top_p_filtering(logits, top_k=top_k, top_p=top_p)
|
| 79 |
+
probs = F.softmax(logits, dim=-1)
|
| 80 |
+
if sample_logits:
|
| 81 |
+
idx = torch.multinomial(probs, num_samples=1)
|
| 82 |
+
else:
|
| 83 |
+
_, idx = torch.topk(probs, k=1, dim=-1)
|
| 84 |
+
return idx, probs
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def logits_to_probs(logits, temperature: float = 1.0, top_p: float=1.0, top_k: int = None, **kwargs):
|
| 88 |
+
logits = logits / max(temperature, 1e-5)
|
| 89 |
+
if top_k > 0 or top_p < 1.0:
|
| 90 |
+
logits = top_k_top_p_filtering(logits, top_k=top_k, top_p=top_p)
|
| 91 |
+
probs = torch.nn.functional.softmax(logits, dim=-1)
|
| 92 |
+
return probs
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def prefill(model, cond_idx: torch.Tensor, input_pos: torch.Tensor, cfg_scale: float, **sampling_kwargs):
|
| 96 |
+
if cfg_scale > 1.0:
|
| 97 |
+
logits = model.inference(None, cond_idx, input_pos)
|
| 98 |
+
logits_combined = logits
|
| 99 |
+
cond_logits, uncond_logits = torch.split(logits_combined, len(logits_combined) // 2, dim=0)
|
| 100 |
+
logits = uncond_logits + (cond_logits - uncond_logits) * cfg_scale
|
| 101 |
+
else:
|
| 102 |
+
logits = model.inference(None, cond_idx, input_pos)
|
| 103 |
+
|
| 104 |
+
return sample(logits, **sampling_kwargs)[0]
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def decode_one_token(model, x: torch.Tensor, input_pos: torch.Tensor, cfg_scale: float, cfg_flag: bool, **sampling_kwargs):
|
| 108 |
+
assert input_pos.shape[-1] == 1
|
| 109 |
+
if cfg_scale > 1.0:
|
| 110 |
+
x_combined = torch.cat([x, x])
|
| 111 |
+
logits = model.inference(x_combined, cond_idx=None, input_pos=input_pos)
|
| 112 |
+
logits_combined = logits
|
| 113 |
+
cond_logits, uncond_logits = torch.split(logits_combined, len(logits_combined) // 2, dim=0)
|
| 114 |
+
if cfg_flag:
|
| 115 |
+
logits = uncond_logits + (cond_logits - uncond_logits) * cfg_scale
|
| 116 |
+
else:
|
| 117 |
+
logits = cond_logits
|
| 118 |
+
else:
|
| 119 |
+
logits = model.inference(x, cond_idx=None, input_pos=input_pos)
|
| 120 |
+
return sample(logits, **sampling_kwargs)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def decode_n_tokens(
|
| 124 |
+
model, cur_token: torch.Tensor, input_pos: torch.Tensor, num_new_tokens: int,
|
| 125 |
+
cfg_scale: float, cfg_interval: int,
|
| 126 |
+
**sampling_kwargs,
|
| 127 |
+
):
|
| 128 |
+
new_tokens, new_probs = [], []
|
| 129 |
+
cfg_flag = True
|
| 130 |
+
for i in range(num_new_tokens):
|
| 131 |
+
with torch.backends.cuda.sdp_kernel(enable_flash=False, enable_mem_efficient=False, enable_math=True): # Actually better for Inductor to codegen attention here
|
| 132 |
+
if cfg_interval > -1 and i > cfg_interval:
|
| 133 |
+
cfg_flag = False
|
| 134 |
+
next_token, next_prob = decode_one_token(
|
| 135 |
+
model, cur_token, input_pos, cfg_scale, cfg_flag, **sampling_kwargs
|
| 136 |
+
)
|
| 137 |
+
input_pos += 1
|
| 138 |
+
new_tokens.append(next_token.clone())
|
| 139 |
+
new_probs.append(next_prob.clone())
|
| 140 |
+
cur_token = next_token.view(-1, 1)
|
| 141 |
+
|
| 142 |
+
return new_tokens, new_probs
|
| 143 |
+
|
| 144 |
+
@torch.no_grad()
|
| 145 |
+
def generate(model, cond, max_new_tokens, emb_masks=None, cfg_scale=1.0, cfg_interval=-1, **sampling_kwargs):
|
| 146 |
+
if model.model_type == 'c2i':
|
| 147 |
+
if cfg_scale > 1.0:
|
| 148 |
+
cond_null = torch.ones_like(cond) * model.num_classes
|
| 149 |
+
cond_combined = torch.cat([cond, cond_null])
|
| 150 |
+
else:
|
| 151 |
+
cond_combined = cond
|
| 152 |
+
T = 1
|
| 153 |
+
elif model.model_type == 't2i':
|
| 154 |
+
if cfg_scale > 1.0:
|
| 155 |
+
cond_null = torch.zeros_like(cond) + model.cls_embedding.uncond_embedding
|
| 156 |
+
cond_combined = torch.cat([cond, cond_null])
|
| 157 |
+
else:
|
| 158 |
+
cond_combined = cond
|
| 159 |
+
T = cond.shape[1]
|
| 160 |
+
else:
|
| 161 |
+
raise Exception("please check model type")
|
| 162 |
+
|
| 163 |
+
T_new = T + max_new_tokens
|
| 164 |
+
max_seq_length = T_new
|
| 165 |
+
max_batch_size = cond.shape[0]
|
| 166 |
+
|
| 167 |
+
device = cond.device
|
| 168 |
+
with torch.device(device):
|
| 169 |
+
max_batch_size_cfg = max_batch_size * 2 if cfg_scale > 1.0 else max_batch_size
|
| 170 |
+
model.setup_caches(max_batch_size=max_batch_size_cfg, max_seq_length=max_seq_length, dtype=model.tok_embeddings.weight.dtype)
|
| 171 |
+
|
| 172 |
+
if emb_masks is not None:
|
| 173 |
+
assert emb_masks.shape[0] == max_batch_size
|
| 174 |
+
assert emb_masks.shape[-1] == T
|
| 175 |
+
if cfg_scale > 1.0:
|
| 176 |
+
model.causal_mask[:, :, :T] = model.causal_mask[:, :, :T] * torch.cat([emb_masks, emb_masks]).unsqueeze(1)
|
| 177 |
+
else:
|
| 178 |
+
model.causal_mask[:, :, :T] = model.causal_mask[:, :, :T] * emb_masks.unsqueeze(1)
|
| 179 |
+
|
| 180 |
+
eye_matrix = torch.eye(model.causal_mask.size(1), model.causal_mask.size(2), device=device)
|
| 181 |
+
model.causal_mask[:] = model.causal_mask * (1 - eye_matrix) + eye_matrix
|
| 182 |
+
|
| 183 |
+
# create an empty tensor of the expected final shape and fill in the current tokens
|
| 184 |
+
seq = torch.empty((max_batch_size, T_new), dtype=torch.int, device=device)
|
| 185 |
+
|
| 186 |
+
input_pos = torch.arange(0, T, device=device)
|
| 187 |
+
next_token = prefill(model, cond_combined, input_pos, cfg_scale, **sampling_kwargs)
|
| 188 |
+
seq[:, T:T+1] = next_token
|
| 189 |
+
|
| 190 |
+
input_pos = torch.tensor([T], device=device, dtype=torch.int)
|
| 191 |
+
generated_tokens, _ = decode_n_tokens(model, next_token, input_pos, max_new_tokens-1, cfg_scale, cfg_interval, **sampling_kwargs)
|
| 192 |
+
seq[:, T+1:] = torch.cat(generated_tokens, dim=1)
|
| 193 |
+
|
| 194 |
+
return seq[:, T:]
|
| 195 |
+
|
| 196 |
+
def renew_llamagen(
|
| 197 |
+
model_class,
|
| 198 |
+
):
|
| 199 |
+
class WrappedLLamaGen(model_class, GenerationMixin):
|
| 200 |
+
def __init__(self, *args, **kwargs):
|
| 201 |
+
super().__init__(*args, **kwargs)
|
| 202 |
+
|
| 203 |
+
def _init_new_params(self, *args, **kwargs):
|
| 204 |
+
self.config.is_encoder_decoder = False
|
| 205 |
+
|
| 206 |
+
def clear_kvcache(self):
|
| 207 |
+
for layer_idx, b in enumerate(self.layers):
|
| 208 |
+
b.attention.kv_cache.k_cache[..., :, :] = 0
|
| 209 |
+
b.attention.kv_cache.v_cache[..., :, :] = 0
|
| 210 |
+
|
| 211 |
+
def assign_kvcache(self, past_key_values):
|
| 212 |
+
for layer_idx, b in enumerate(self.layers):
|
| 213 |
+
used_len = past_key_values.key_cache[layer_idx].shape[-2]
|
| 214 |
+
b.attention.kv_cache.k_cache[..., :used_len, :] = past_key_values.key_cache[layer_idx]
|
| 215 |
+
b.attention.kv_cache.v_cache[..., :used_len, :] = past_key_values.value_cache[layer_idx]
|
| 216 |
+
|
| 217 |
+
def get_max_kvcache_len(self):
|
| 218 |
+
max_kvcache_len = 0
|
| 219 |
+
for b in self.layers:
|
| 220 |
+
max_kvcache_len = max(max_kvcache_len, b.attention.kv_cache.k_cache.shape[-2])
|
| 221 |
+
return max_kvcache_len
|
| 222 |
+
|
| 223 |
+
def assign_past_key_values(self, past_key_values, used_len):
|
| 224 |
+
for layer_idx, b in enumerate(self.layers):
|
| 225 |
+
if layer_idx < len(past_key_values.key_cache):
|
| 226 |
+
past_key_values.key_cache[layer_idx] = b.attention.kv_cache.k_cache[..., :used_len, :]
|
| 227 |
+
past_key_values.value_cache[layer_idx] = b.attention.kv_cache.v_cache[..., :used_len, :]
|
| 228 |
+
else:
|
| 229 |
+
past_key_values.key_cache.append(b.attention.kv_cache.k_cache[..., :used_len, :])
|
| 230 |
+
past_key_values.value_cache.append(b.attention.kv_cache.v_cache[..., :used_len, :])
|
| 231 |
+
|
| 232 |
+
return past_key_values
|
| 233 |
+
|
| 234 |
+
def forward(
|
| 235 |
+
self,
|
| 236 |
+
input_ids,
|
| 237 |
+
position_ids,
|
| 238 |
+
cache_position,
|
| 239 |
+
past_key_values,
|
| 240 |
+
use_cache,
|
| 241 |
+
attention_mask,
|
| 242 |
+
**kwargs,
|
| 243 |
+
):
|
| 244 |
+
dtype = self.tok_embeddings.weight.dtype
|
| 245 |
+
|
| 246 |
+
input_pos = position_ids[0][-input_ids.shape[1]:]
|
| 247 |
+
|
| 248 |
+
while attention_mask.dim() < 4:
|
| 249 |
+
attention_mask = attention_mask.unsqueeze(1)
|
| 250 |
+
|
| 251 |
+
max_kvcache_len = self.get_max_kvcache_len()
|
| 252 |
+
if attention_mask.shape[-1] < max_kvcache_len:
|
| 253 |
+
attention_mask = torch.cat([
|
| 254 |
+
attention_mask,
|
| 255 |
+
torch.zeros(
|
| 256 |
+
*attention_mask.shape[:-1],
|
| 257 |
+
max_kvcache_len - attention_mask.shape[-1],
|
| 258 |
+
dtype=attention_mask.dtype,
|
| 259 |
+
device=attention_mask.device
|
| 260 |
+
)
|
| 261 |
+
], dim=-1)
|
| 262 |
+
|
| 263 |
+
causal_mask = self.causal_mask
|
| 264 |
+
while causal_mask.dim() < 4:
|
| 265 |
+
causal_mask = causal_mask.unsqueeze(1)
|
| 266 |
+
|
| 267 |
+
causal_mask = causal_mask[:, :, input_pos, :].to(attention_mask.dtype)
|
| 268 |
+
attention_mask = torch.minimum(attention_mask, causal_mask)
|
| 269 |
+
|
| 270 |
+
min_dtype = torch.finfo(dtype).min
|
| 271 |
+
attention_mask = ((attention_mask == 0).to(dtype) * min_dtype).to(dtype)
|
| 272 |
+
mask = attention_mask
|
| 273 |
+
|
| 274 |
+
is_kvcache_not_empty = (past_key_values.get_seq_length() > 0)
|
| 275 |
+
|
| 276 |
+
# idx = input_ids if is_kvcache_not_empty else None
|
| 277 |
+
# cond_idx = None if is_kvcache_not_empty else input_ids
|
| 278 |
+
idx = input_ids
|
| 279 |
+
|
| 280 |
+
if is_kvcache_not_empty:
|
| 281 |
+
self.assign_kvcache(past_key_values)
|
| 282 |
+
|
| 283 |
+
logits = self.inference(
|
| 284 |
+
idx = idx,
|
| 285 |
+
cond_idx = None,
|
| 286 |
+
input_pos=input_pos,
|
| 287 |
+
mask=None, #mask,
|
| 288 |
+
)
|
| 289 |
+
used_len = position_ids[0][-1:] + 1
|
| 290 |
+
past_key_values = self.assign_past_key_values(past_key_values, used_len)
|
| 291 |
+
outputs = BackboneOutput(
|
| 292 |
+
logits = logits,
|
| 293 |
+
past_key_values = past_key_values,
|
| 294 |
+
)
|
| 295 |
+
return outputs
|
| 296 |
+
|
| 297 |
+
def inference(
|
| 298 |
+
self,
|
| 299 |
+
idx: torch.Tensor,
|
| 300 |
+
cond_idx: torch.Tensor, # cond_idx_or_embed
|
| 301 |
+
input_pos: Optional[torch.Tensor] = None,
|
| 302 |
+
mask: Optional[torch.Tensor] = None,
|
| 303 |
+
):
|
| 304 |
+
if idx is not None and cond_idx is not None: # training or naive inference
|
| 305 |
+
cond_embeddings = self.cls_embedding(cond_idx, train=self.training)[:,:self.cls_token_num]
|
| 306 |
+
token_embeddings = self.tok_embeddings(idx)
|
| 307 |
+
token_embeddings = torch.cat((cond_embeddings, token_embeddings), dim=1)
|
| 308 |
+
h = self.tok_dropout(token_embeddings)
|
| 309 |
+
self.freqs_cis = self.freqs_cis.to(h.device)
|
| 310 |
+
else:
|
| 311 |
+
if cond_idx is not None: # pre fill in inference
|
| 312 |
+
token_embeddings = self.cls_embedding(cond_idx, train=self.training)[:,:self.cls_token_num]
|
| 313 |
+
else: # decode_n_tokens(kv cache) in inference
|
| 314 |
+
token_embeddings = self.tok_embeddings(idx)
|
| 315 |
+
|
| 316 |
+
bs = token_embeddings.shape[0]
|
| 317 |
+
if mask is None:
|
| 318 |
+
mask = self.causal_mask[:bs, None, input_pos, :]
|
| 319 |
+
h = self.tok_dropout(token_embeddings)
|
| 320 |
+
self.freqs_cis = self.freqs_cis
|
| 321 |
+
|
| 322 |
+
if self.training:
|
| 323 |
+
freqs_cis = self.freqs_cis[:token_embeddings.shape[1]]
|
| 324 |
+
else:
|
| 325 |
+
freqs_cis = self.freqs_cis[input_pos]
|
| 326 |
+
# transformer blocks
|
| 327 |
+
for layer in self.layers:
|
| 328 |
+
h = layer(h, freqs_cis, input_pos, mask)
|
| 329 |
+
|
| 330 |
+
# output layers
|
| 331 |
+
h = self.norm(h)
|
| 332 |
+
logits = self.output(h).float()
|
| 333 |
+
|
| 334 |
+
if self.training:
|
| 335 |
+
logits = logits[:, self.cls_token_num - 1:].contiguous()
|
| 336 |
+
|
| 337 |
+
return logits
|
| 338 |
+
|
| 339 |
+
return WrappedLLamaGen
|
| 340 |
+
|
| 341 |
+
class MaxlenCriteria(StoppingCriteria):
|
| 342 |
+
def __init__(self, max_seq_length):
|
| 343 |
+
super().__init__()
|
| 344 |
+
self.max_seq_length = max_seq_length
|
| 345 |
+
|
| 346 |
+
def __call__(self, input_ids, scores, **kwargs):
|
| 347 |
+
return input_ids.shape[-1] >= self.max_seq_length
|
| 348 |
+
|
| 349 |
+
class LlamaGenSolver:
|
| 350 |
+
def __init__(self, model, image_top_k, image_top_p):
|
| 351 |
+
self.model = model
|
| 352 |
+
self.image_top_k = image_top_k
|
| 353 |
+
self.image_top_p = image_top_p
|
| 354 |
+
|
| 355 |
+
def _sample(self, *args, **kwargs):
|
| 356 |
+
raise NotImplementedError
|
| 357 |
+
|
| 358 |
+
def _init_model_kwargs(self, prefill_num, mask=None, device='cuda', *args, **kwargs):
|
| 359 |
+
# print('mas22k', mask[0, :50, :50], mask.shape)
|
| 360 |
+
model_kwargs = dict(
|
| 361 |
+
use_cache = True,
|
| 362 |
+
attention_mask = mask[0, -1:, :prefill_num] if mask is not None else torch.ones(
|
| 363 |
+
(1, prefill_num), device=device
|
| 364 |
+
),
|
| 365 |
+
past_key_values = transformers.DynamicCache(),
|
| 366 |
+
cache_position=prefill_num,
|
| 367 |
+
)
|
| 368 |
+
return model_kwargs
|
| 369 |
+
|
| 370 |
+
@torch.no_grad()
|
| 371 |
+
def generate(self, cond, max_new_tokens, emb_masks=None, cfg_scale=1.0, cfg_interval=-1, return_accl=False,**sampling_kwargs):
|
| 372 |
+
model = self.model
|
| 373 |
+
if model.model_type == 'c2i':
|
| 374 |
+
if cfg_scale > 1.0:
|
| 375 |
+
cond_null = torch.ones_like(cond) * model.num_classes
|
| 376 |
+
cond_combined = torch.cat([cond, cond_null])
|
| 377 |
+
else:
|
| 378 |
+
cond_combined = cond
|
| 379 |
+
T = 1
|
| 380 |
+
elif model.model_type == 't2i':
|
| 381 |
+
if cfg_scale > 1.0:
|
| 382 |
+
cond_null = torch.zeros_like(cond) + model.cls_embedding.uncond_embedding
|
| 383 |
+
cond_combined = torch.cat([cond, cond_null])
|
| 384 |
+
else:
|
| 385 |
+
cond_combined = cond
|
| 386 |
+
T = cond.shape[1]
|
| 387 |
+
else:
|
| 388 |
+
raise Exception("please check model type")
|
| 389 |
+
|
| 390 |
+
T_new = T + max_new_tokens
|
| 391 |
+
max_seq_length = T_new
|
| 392 |
+
max_batch_size = cond.shape[0]
|
| 393 |
+
|
| 394 |
+
device = cond.device
|
| 395 |
+
with torch.device(device):
|
| 396 |
+
max_batch_size_cfg = max_batch_size * 2 if cfg_scale > 1.0 else max_batch_size
|
| 397 |
+
model.setup_caches(
|
| 398 |
+
max_batch_size=max_batch_size_cfg,
|
| 399 |
+
max_seq_length=max_seq_length ,
|
| 400 |
+
dtype=model.tok_embeddings.weight.dtype
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
if emb_masks is not None:
|
| 404 |
+
assert emb_masks.shape[0] == max_batch_size
|
| 405 |
+
assert emb_masks.shape[-1] == T
|
| 406 |
+
if cfg_scale > 1.0:
|
| 407 |
+
model.causal_mask[:, :, :T] = model.causal_mask[:, :, :T] * torch.cat([emb_masks, emb_masks]).unsqueeze(1)
|
| 408 |
+
else:
|
| 409 |
+
model.causal_mask[:, :, :T] = model.causal_mask[:, :, :T] * emb_masks.unsqueeze(1)
|
| 410 |
+
|
| 411 |
+
eye_matrix = torch.eye(model.causal_mask.size(1), model.causal_mask.size(2), device=device)
|
| 412 |
+
model.causal_mask[:] = model.causal_mask * (1 - eye_matrix) + eye_matrix
|
| 413 |
+
|
| 414 |
+
mask = model.causal_mask
|
| 415 |
+
|
| 416 |
+
input_pos = torch.arange(0, T, device=device)
|
| 417 |
+
next_token = prefill(model, cond_combined, input_pos, cfg_scale, **sampling_kwargs)
|
| 418 |
+
|
| 419 |
+
input_ids = next_token
|
| 420 |
+
|
| 421 |
+
max_gen_len = max_seq_length # max_new_tokens
|
| 422 |
+
temperature = 1.0
|
| 423 |
+
synced_gpus = False
|
| 424 |
+
stopping_criteria = StoppingCriteriaList([
|
| 425 |
+
MaxlenCriteria(max_new_tokens) # As llamagen has T5
|
| 426 |
+
])
|
| 427 |
+
generation_config = GenerationConfig(
|
| 428 |
+
max_new_tokens=max_gen_len,
|
| 429 |
+
max_length=max_gen_len,
|
| 430 |
+
temperature=temperature,
|
| 431 |
+
top_k=None,
|
| 432 |
+
do_sample=True, # eos_token_id= [8710],
|
| 433 |
+
_pad_token_tensor=None,
|
| 434 |
+
return_dict_in_generate = False,
|
| 435 |
+
return_accl = return_accl
|
| 436 |
+
)
|
| 437 |
+
model_kwargs = self._init_model_kwargs(
|
| 438 |
+
prefill_num = T+1, # existing `next_token`, an already decoded image token
|
| 439 |
+
mask = None, # this mask only used for generating the positional indexes
|
| 440 |
+
device = device,
|
| 441 |
+
)
|
| 442 |
+
logits_processor = self.create_logits_processor()
|
| 443 |
+
|
| 444 |
+
result = model._sample(
|
| 445 |
+
input_ids=input_ids,
|
| 446 |
+
logits_processor=logits_processor,
|
| 447 |
+
stopping_criteria = stopping_criteria,
|
| 448 |
+
generation_config=generation_config,
|
| 449 |
+
synced_gpus=synced_gpus,
|
| 450 |
+
streamer=None,
|
| 451 |
+
logits_warper=None,
|
| 452 |
+
**model_kwargs,
|
| 453 |
+
)
|
| 454 |
+
outputs = result.input_ids
|
| 455 |
+
generated_tokens = outputs if isinstance(outputs, torch.Tensor) else outputs.sequences
|
| 456 |
+
generated_tokens = generated_tokens[:, -max_new_tokens:]
|
| 457 |
+
model.clear_kvcache()
|
| 458 |
+
if return_accl:
|
| 459 |
+
result.input_ids = generated_tokens
|
| 460 |
+
return result
|
| 461 |
+
else:
|
| 462 |
+
return generated_tokens
|
| 463 |
+
|
| 464 |
+
def create_logits_processor(self, ):
|
| 465 |
+
image_top_k = self.image_top_k
|
| 466 |
+
image_top_p = self.image_top_p
|
| 467 |
+
|
| 468 |
+
logits_processor = LogitsProcessorList()
|
| 469 |
+
|
| 470 |
+
topk_logits_warper = TopKLogitsWarper(top_k=image_top_k)
|
| 471 |
+
topp_logits_warper = TopPLogitsWarper3d(top_p=image_top_p)
|
| 472 |
+
|
| 473 |
+
logits_processor.append(topk_logits_warper)
|
| 474 |
+
logits_processor.append(topp_logits_warper)
|
| 475 |
+
|
| 476 |
+
return logits_processor
|
sjdtree/llamagen/tokenizer/consistencydecoder/README.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Consistency Decoder from OpenAI
|
| 2 |
+
|
| 3 |
+
### install
|
| 4 |
+
```
|
| 5 |
+
pip install diffusers
|
| 6 |
+
pip install accelerate
|
| 7 |
+
```
|
| 8 |
+
|
| 9 |
+
### demo
|
| 10 |
+
```
|
| 11 |
+
cd ${THIS_REPO_ROOT}
|
| 12 |
+
python3 tokenizer/consistencydecoder/cd_demo.py
|
| 13 |
+
```
|
| 14 |
+
|
sjdtree/llamagen/tokenizer/consistencydecoder/cd_demo.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from diffusers import ConsistencyDecoderVAE
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def main(args):
|
| 10 |
+
# Setup PyTorch:
|
| 11 |
+
torch.manual_seed(args.seed)
|
| 12 |
+
torch.set_grad_enabled(False)
|
| 13 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 14 |
+
|
| 15 |
+
# create and load model
|
| 16 |
+
vae = ConsistencyDecoderVAE.from_pretrained("openai/consistency-decoder", torch_dtype=torch.float16).to(device)
|
| 17 |
+
|
| 18 |
+
# load image
|
| 19 |
+
img_path = args.image_path
|
| 20 |
+
out_path = args.image_path.replace('.jpg', '_cd.jpg').replace('.jpeg', '_cd.jpeg').replace('.png', '_cd.png')
|
| 21 |
+
input_size = args.image_size
|
| 22 |
+
img = Image.open(img_path).convert("RGB")
|
| 23 |
+
|
| 24 |
+
# preprocess
|
| 25 |
+
size_org = img.size
|
| 26 |
+
img = img.resize((input_size, input_size))
|
| 27 |
+
img = np.array(img) / 255.
|
| 28 |
+
x = 2.0 * img - 1.0 # x value is between [-1, 1]
|
| 29 |
+
x = torch.tensor(x)
|
| 30 |
+
x = x.unsqueeze(dim=0)
|
| 31 |
+
x = torch.einsum('nhwc->nchw', x)
|
| 32 |
+
x_input = x.half().to(device)
|
| 33 |
+
|
| 34 |
+
# inference
|
| 35 |
+
with torch.no_grad():
|
| 36 |
+
# Map input images to latent space + normalize latents:
|
| 37 |
+
latent = vae.encode(x_input).latent_dist.sample().mul_(0.18215)
|
| 38 |
+
# reconstruct:
|
| 39 |
+
output = vae.decode(latent / 0.18215).sample # output value is between [-1, 1]
|
| 40 |
+
|
| 41 |
+
# postprocess
|
| 42 |
+
output = F.interpolate(output, size=[size_org[1], size_org[0]], mode='bilinear').permute(0, 2, 3, 1)[0]
|
| 43 |
+
sample = torch.clamp(127.5 * output + 128.0, 0, 255).to("cpu", dtype=torch.uint8).numpy()
|
| 44 |
+
|
| 45 |
+
# save
|
| 46 |
+
Image.fromarray(sample).save(out_path)
|
| 47 |
+
print("Reconstructed image is saved to {}".format(out_path))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
if __name__ == "__main__":
|
| 52 |
+
parser = argparse.ArgumentParser()
|
| 53 |
+
parser.add_argument("--image-path", type=str, default="assets/example.jpg")
|
| 54 |
+
parser.add_argument("--image-size", type=int, choices=[256, 512, 1024], default=512)
|
| 55 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 56 |
+
args = parser.parse_args()
|
| 57 |
+
main(args)
|
sjdtree/llamagen/tokenizer/consistencydecoder/reconstruction_cd_ddp.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 1 |
+
import torch
|
| 2 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 3 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 4 |
+
import torch.distributed as dist
|
| 5 |
+
from torch.utils.data import Dataset, DataLoader
|
| 6 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 7 |
+
from torchvision.datasets import ImageFolder
|
| 8 |
+
from torchvision import transforms
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
import os
|
| 11 |
+
import itertools
|
| 12 |
+
from PIL import Image
|
| 13 |
+
import numpy as np
|
| 14 |
+
import argparse
|
| 15 |
+
import random
|
| 16 |
+
|
| 17 |
+
from skimage.metrics import peak_signal_noise_ratio as psnr_loss
|
| 18 |
+
from skimage.metrics import structural_similarity as ssim_loss
|
| 19 |
+
from diffusers.models import ConsistencyDecoderVAE
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class SingleFolderDataset(Dataset):
|
| 23 |
+
def __init__(self, directory, transform=None):
|
| 24 |
+
super().__init__()
|
| 25 |
+
self.directory = directory
|
| 26 |
+
self.transform = transform
|
| 27 |
+
self.image_paths = [os.path.join(directory, file_name) for file_name in os.listdir(directory)
|
| 28 |
+
if os.path.isfile(os.path.join(directory, file_name))]
|
| 29 |
+
|
| 30 |
+
def __len__(self):
|
| 31 |
+
return len(self.image_paths)
|
| 32 |
+
|
| 33 |
+
def __getitem__(self, idx):
|
| 34 |
+
image_path = self.image_paths[idx]
|
| 35 |
+
image = Image.open(image_path).convert('RGB')
|
| 36 |
+
if self.transform:
|
| 37 |
+
image = self.transform(image)
|
| 38 |
+
return image, torch.tensor(0)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def create_npz_from_sample_folder(sample_dir, num=50_000):
|
| 42 |
+
"""
|
| 43 |
+
Builds a single .npz file from a folder of .png samples.
|
| 44 |
+
"""
|
| 45 |
+
samples = []
|
| 46 |
+
for i in tqdm(range(num), desc="Building .npz file from samples"):
|
| 47 |
+
sample_pil = Image.open(f"{sample_dir}/{i:06d}.png")
|
| 48 |
+
sample_np = np.asarray(sample_pil).astype(np.uint8)
|
| 49 |
+
samples.append(sample_np)
|
| 50 |
+
|
| 51 |
+
random.shuffle(samples) # This is very important for IS(Inception Score) !!!
|
| 52 |
+
samples = np.stack(samples)
|
| 53 |
+
assert samples.shape == (num, samples.shape[1], samples.shape[2], 3)
|
| 54 |
+
npz_path = f"{sample_dir}.npz"
|
| 55 |
+
np.savez(npz_path, arr_0=samples)
|
| 56 |
+
print(f"Saved .npz file to {npz_path} [shape={samples.shape}].")
|
| 57 |
+
return npz_path
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def center_crop_arr(pil_image, image_size):
|
| 61 |
+
"""
|
| 62 |
+
Center cropping implementation from ADM.
|
| 63 |
+
https://github.com/openai/guided-diffusion/blob/8fb3ad9197f16bbc40620447b2742e13458d2831/guided_diffusion/image_datasets.py#L126
|
| 64 |
+
"""
|
| 65 |
+
while min(*pil_image.size) >= 2 * image_size:
|
| 66 |
+
pil_image = pil_image.resize(
|
| 67 |
+
tuple(x // 2 for x in pil_image.size), resample=Image.BOX
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
scale = image_size / min(*pil_image.size)
|
| 71 |
+
pil_image = pil_image.resize(
|
| 72 |
+
tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
arr = np.array(pil_image)
|
| 76 |
+
crop_y = (arr.shape[0] - image_size) // 2
|
| 77 |
+
crop_x = (arr.shape[1] - image_size) // 2
|
| 78 |
+
return Image.fromarray(arr[crop_y: crop_y + image_size, crop_x: crop_x + image_size])
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def main(args):
|
| 82 |
+
# Setup PyTorch:
|
| 83 |
+
assert torch.cuda.is_available(), "Sampling with DDP requires at least one GPU. sample.py supports CPU-only usage"
|
| 84 |
+
torch.set_grad_enabled(False)
|
| 85 |
+
|
| 86 |
+
# Setup env
|
| 87 |
+
dist.init_process_group("nccl")
|
| 88 |
+
rank = dist.get_rank()
|
| 89 |
+
device = rank % torch.cuda.device_count()
|
| 90 |
+
seed = args.global_seed * dist.get_world_size() + rank
|
| 91 |
+
torch.manual_seed(seed)
|
| 92 |
+
torch.cuda.set_device(device)
|
| 93 |
+
print(f"Starting rank={rank}, seed={seed}, world_size={dist.get_world_size()}.")
|
| 94 |
+
|
| 95 |
+
# create and load model
|
| 96 |
+
vae = ConsistencyDecoderVAE.from_pretrained("openai/consistency-decoder", torch_dtype=torch.float16).to("cuda:{}".format(device))
|
| 97 |
+
|
| 98 |
+
# Create folder to save samples:
|
| 99 |
+
folder_name = f"openai-consistencydecoder-{args.dataset}-size-{args.image_size}-seed-{args.global_seed}"
|
| 100 |
+
sample_folder_dir = f"{args.sample_dir}/{folder_name}"
|
| 101 |
+
if rank == 0:
|
| 102 |
+
os.makedirs(sample_folder_dir, exist_ok=True)
|
| 103 |
+
print(f"Saving .png samples at {sample_folder_dir}")
|
| 104 |
+
dist.barrier()
|
| 105 |
+
|
| 106 |
+
# Setup data:
|
| 107 |
+
transform = transforms.Compose([
|
| 108 |
+
transforms.Lambda(lambda pil_image: center_crop_arr(pil_image, args.image_size)),
|
| 109 |
+
transforms.ToTensor(),
|
| 110 |
+
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True)
|
| 111 |
+
])
|
| 112 |
+
if args.dataset == 'imagenet':
|
| 113 |
+
dataset = ImageFolder(args.data_path, transform=transform)
|
| 114 |
+
num_fid_samples = 50000
|
| 115 |
+
elif args.dataset == 'coco':
|
| 116 |
+
dataset = SingleFolderDataset(args.data_path, transform=transform)
|
| 117 |
+
num_fid_samples = 5000
|
| 118 |
+
else:
|
| 119 |
+
raise Exception("please check dataset")
|
| 120 |
+
sampler = DistributedSampler(
|
| 121 |
+
dataset,
|
| 122 |
+
num_replicas=dist.get_world_size(),
|
| 123 |
+
rank=rank,
|
| 124 |
+
shuffle=False,
|
| 125 |
+
seed=args.global_seed
|
| 126 |
+
)
|
| 127 |
+
loader = DataLoader(
|
| 128 |
+
dataset,
|
| 129 |
+
batch_size=args.per_proc_batch_size,
|
| 130 |
+
shuffle=False,
|
| 131 |
+
sampler=sampler,
|
| 132 |
+
num_workers=args.num_workers,
|
| 133 |
+
pin_memory=True,
|
| 134 |
+
drop_last=False
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
# Figure out how many samples we need to generate on each GPU and how many iterations we need to run:
|
| 138 |
+
n = args.per_proc_batch_size
|
| 139 |
+
global_batch_size = n * dist.get_world_size()
|
| 140 |
+
psnr_val_rgb = []
|
| 141 |
+
ssim_val_rgb = []
|
| 142 |
+
|
| 143 |
+
loader = tqdm(loader) if rank == 0 else loader
|
| 144 |
+
total = 0
|
| 145 |
+
for x, _ in loader:
|
| 146 |
+
rgb_gts = x
|
| 147 |
+
rgb_gts = (rgb_gts.permute(0, 2, 3, 1).to("cpu").numpy() + 1.0) / 2.0 # rgb_gt value is between [0, 1]
|
| 148 |
+
x = x.half().to("cuda:{}".format(device))
|
| 149 |
+
with torch.no_grad():
|
| 150 |
+
# Map input images to latent space + normalize latents:
|
| 151 |
+
latent = vae.encode(x).latent_dist.sample().mul_(0.18215)
|
| 152 |
+
# reconstruct:
|
| 153 |
+
samples = vae.decode(latent / 0.18215).sample # output value is between [-1, 1]
|
| 154 |
+
samples = torch.clamp(127.5 * samples + 128.0, 0, 255).permute(0, 2, 3, 1).to("cpu", dtype=torch.uint8).numpy()
|
| 155 |
+
|
| 156 |
+
# Save samples to disk as individual .png files
|
| 157 |
+
for i, (sample, rgb_gt) in enumerate(zip(samples, rgb_gts)):
|
| 158 |
+
index = i * dist.get_world_size() + rank + total
|
| 159 |
+
Image.fromarray(sample).save(f"{sample_folder_dir}/{index:06d}.png")
|
| 160 |
+
# metric
|
| 161 |
+
rgb_restored = sample.astype(np.float32) / 255. # rgb_restored value is between [0, 1]
|
| 162 |
+
psnr = psnr_loss(rgb_restored, rgb_gt)
|
| 163 |
+
ssim = ssim_loss(rgb_restored, rgb_gt, multichannel=True, data_range=2.0, channel_axis=-1)
|
| 164 |
+
psnr_val_rgb.append(psnr)
|
| 165 |
+
ssim_val_rgb.append(ssim)
|
| 166 |
+
total += global_batch_size
|
| 167 |
+
|
| 168 |
+
# ------------------------------------
|
| 169 |
+
# Summary
|
| 170 |
+
# ------------------------------------
|
| 171 |
+
# Make sure all processes have finished saving their samples
|
| 172 |
+
dist.barrier()
|
| 173 |
+
world_size = dist.get_world_size()
|
| 174 |
+
gather_psnr_val = [None for _ in range(world_size)]
|
| 175 |
+
gather_ssim_val = [None for _ in range(world_size)]
|
| 176 |
+
dist.all_gather_object(gather_psnr_val, psnr_val_rgb)
|
| 177 |
+
dist.all_gather_object(gather_ssim_val, ssim_val_rgb)
|
| 178 |
+
|
| 179 |
+
if rank == 0:
|
| 180 |
+
gather_psnr_val = list(itertools.chain(*gather_psnr_val))
|
| 181 |
+
gather_ssim_val = list(itertools.chain(*gather_ssim_val))
|
| 182 |
+
psnr_val_rgb = sum(gather_psnr_val) / len(gather_psnr_val)
|
| 183 |
+
ssim_val_rgb = sum(gather_ssim_val) / len(gather_ssim_val)
|
| 184 |
+
print("PSNR: %f, SSIM: %f " % (psnr_val_rgb, ssim_val_rgb))
|
| 185 |
+
|
| 186 |
+
result_file = f"{sample_folder_dir}_results.txt"
|
| 187 |
+
print("writing results to {}".format(result_file))
|
| 188 |
+
with open(result_file, 'w') as f:
|
| 189 |
+
print("PSNR: %f, SSIM: %f " % (psnr_val_rgb, ssim_val_rgb), file=f)
|
| 190 |
+
|
| 191 |
+
create_npz_from_sample_folder(sample_folder_dir, num_fid_samples)
|
| 192 |
+
print("Done.")
|
| 193 |
+
|
| 194 |
+
dist.barrier()
|
| 195 |
+
dist.destroy_process_group()
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
if __name__ == "__main__":
|
| 199 |
+
parser = argparse.ArgumentParser()
|
| 200 |
+
parser.add_argument("--data-path", type=str, required=True)
|
| 201 |
+
parser.add_argument("--dataset", type=str, choices=['imagenet', 'coco'], default='imagenet')
|
| 202 |
+
parser.add_argument("--image-size", type=int, choices=[256, 512], default=256)
|
| 203 |
+
parser.add_argument("--sample-dir", type=str, default="reconstructions")
|
| 204 |
+
parser.add_argument("--per-proc-batch-size", type=int, default=32)
|
| 205 |
+
parser.add_argument("--global-seed", type=int, default=0)
|
| 206 |
+
parser.add_argument("--num-workers", type=int, default=4)
|
| 207 |
+
args = parser.parse_args()
|
| 208 |
+
main(args)
|
sjdtree/llamagen/tokenizer/tokenizer_image/discriminator.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modified from:
|
| 2 |
+
# taming-transformers: https://github.com/CompVis/taming-transformers
|
| 3 |
+
# stylegan2-pytorch: https://github.com/rosinality/stylegan2-pytorch/blob/master/model.py
|
| 4 |
+
# maskgit: https://github.com/google-research/maskgit/blob/main/maskgit/nets/discriminator.py
|
| 5 |
+
import functools
|
| 6 |
+
import math
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
try:
|
| 10 |
+
from kornia.filters import filter2d
|
| 11 |
+
except:
|
| 12 |
+
pass
|
| 13 |
+
|
| 14 |
+
#################################################################################
|
| 15 |
+
# PatchGAN #
|
| 16 |
+
#################################################################################
|
| 17 |
+
class PatchGANDiscriminator(nn.Module):
|
| 18 |
+
"""Defines a PatchGAN discriminator as in Pix2Pix
|
| 19 |
+
--> see https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/networks.py
|
| 20 |
+
"""
|
| 21 |
+
def __init__(self, input_nc=3, ndf=64, n_layers=3, use_actnorm=False):
|
| 22 |
+
"""Construct a PatchGAN discriminator
|
| 23 |
+
Parameters:
|
| 24 |
+
input_nc (int) -- the number of channels in input images
|
| 25 |
+
ndf (int) -- the number of filters in the last conv layer
|
| 26 |
+
n_layers (int) -- the number of conv layers in the discriminator
|
| 27 |
+
norm_layer -- normalization layer
|
| 28 |
+
"""
|
| 29 |
+
super(PatchGANDiscriminator, self).__init__()
|
| 30 |
+
if not use_actnorm:
|
| 31 |
+
norm_layer = nn.BatchNorm2d
|
| 32 |
+
else:
|
| 33 |
+
norm_layer = ActNorm
|
| 34 |
+
if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters
|
| 35 |
+
use_bias = norm_layer.func != nn.BatchNorm2d
|
| 36 |
+
else:
|
| 37 |
+
use_bias = norm_layer != nn.BatchNorm2d
|
| 38 |
+
|
| 39 |
+
kw = 4
|
| 40 |
+
padw = 1
|
| 41 |
+
sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]
|
| 42 |
+
nf_mult = 1
|
| 43 |
+
nf_mult_prev = 1
|
| 44 |
+
for n in range(1, n_layers): # gradually increase the number of filters
|
| 45 |
+
nf_mult_prev = nf_mult
|
| 46 |
+
nf_mult = min(2 ** n, 8)
|
| 47 |
+
sequence += [
|
| 48 |
+
nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias),
|
| 49 |
+
norm_layer(ndf * nf_mult),
|
| 50 |
+
nn.LeakyReLU(0.2, True)
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
nf_mult_prev = nf_mult
|
| 54 |
+
nf_mult = min(2 ** n_layers, 8)
|
| 55 |
+
sequence += [
|
| 56 |
+
nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),
|
| 57 |
+
norm_layer(ndf * nf_mult),
|
| 58 |
+
nn.LeakyReLU(0.2, True)
|
| 59 |
+
]
|
| 60 |
+
|
| 61 |
+
sequence += [
|
| 62 |
+
nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # output 1 channel prediction map
|
| 63 |
+
self.main = nn.Sequential(*sequence)
|
| 64 |
+
|
| 65 |
+
self.apply(self._init_weights)
|
| 66 |
+
|
| 67 |
+
def _init_weights(self, module):
|
| 68 |
+
if isinstance(module, nn.Conv2d):
|
| 69 |
+
nn.init.normal_(module.weight.data, 0.0, 0.02)
|
| 70 |
+
elif isinstance(module, nn.BatchNorm2d):
|
| 71 |
+
nn.init.normal_(module.weight.data, 1.0, 0.02)
|
| 72 |
+
nn.init.constant_(module.bias.data, 0)
|
| 73 |
+
|
| 74 |
+
def forward(self, input):
|
| 75 |
+
"""Standard forward."""
|
| 76 |
+
return self.main(input)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class ActNorm(nn.Module):
|
| 80 |
+
def __init__(self, num_features, logdet=False, affine=True,
|
| 81 |
+
allow_reverse_init=False):
|
| 82 |
+
assert affine
|
| 83 |
+
super().__init__()
|
| 84 |
+
self.logdet = logdet
|
| 85 |
+
self.loc = nn.Parameter(torch.zeros(1, num_features, 1, 1))
|
| 86 |
+
self.scale = nn.Parameter(torch.ones(1, num_features, 1, 1))
|
| 87 |
+
self.allow_reverse_init = allow_reverse_init
|
| 88 |
+
|
| 89 |
+
self.register_buffer('initialized', torch.tensor(0, dtype=torch.uint8))
|
| 90 |
+
|
| 91 |
+
def initialize(self, input):
|
| 92 |
+
with torch.no_grad():
|
| 93 |
+
flatten = input.permute(1, 0, 2, 3).contiguous().view(input.shape[1], -1)
|
| 94 |
+
mean = (
|
| 95 |
+
flatten.mean(1)
|
| 96 |
+
.unsqueeze(1)
|
| 97 |
+
.unsqueeze(2)
|
| 98 |
+
.unsqueeze(3)
|
| 99 |
+
.permute(1, 0, 2, 3)
|
| 100 |
+
)
|
| 101 |
+
std = (
|
| 102 |
+
flatten.std(1)
|
| 103 |
+
.unsqueeze(1)
|
| 104 |
+
.unsqueeze(2)
|
| 105 |
+
.unsqueeze(3)
|
| 106 |
+
.permute(1, 0, 2, 3)
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
self.loc.data.copy_(-mean)
|
| 110 |
+
self.scale.data.copy_(1 / (std + 1e-6))
|
| 111 |
+
|
| 112 |
+
def forward(self, input, reverse=False):
|
| 113 |
+
if reverse:
|
| 114 |
+
return self.reverse(input)
|
| 115 |
+
if len(input.shape) == 2:
|
| 116 |
+
input = input[:,:,None,None]
|
| 117 |
+
squeeze = True
|
| 118 |
+
else:
|
| 119 |
+
squeeze = False
|
| 120 |
+
|
| 121 |
+
_, _, height, width = input.shape
|
| 122 |
+
|
| 123 |
+
if self.training and self.initialized.item() == 0:
|
| 124 |
+
self.initialize(input)
|
| 125 |
+
self.initialized.fill_(1)
|
| 126 |
+
|
| 127 |
+
h = self.scale * (input + self.loc)
|
| 128 |
+
|
| 129 |
+
if squeeze:
|
| 130 |
+
h = h.squeeze(-1).squeeze(-1)
|
| 131 |
+
|
| 132 |
+
if self.logdet:
|
| 133 |
+
log_abs = torch.log(torch.abs(self.scale))
|
| 134 |
+
logdet = height*width*torch.sum(log_abs)
|
| 135 |
+
logdet = logdet * torch.ones(input.shape[0]).to(input)
|
| 136 |
+
return h, logdet
|
| 137 |
+
|
| 138 |
+
return h
|
| 139 |
+
|
| 140 |
+
def reverse(self, output):
|
| 141 |
+
if self.training and self.initialized.item() == 0:
|
| 142 |
+
if not self.allow_reverse_init:
|
| 143 |
+
raise RuntimeError(
|
| 144 |
+
"Initializing ActNorm in reverse direction is "
|
| 145 |
+
"disabled by default. Use allow_reverse_init=True to enable."
|
| 146 |
+
)
|
| 147 |
+
else:
|
| 148 |
+
self.initialize(output)
|
| 149 |
+
self.initialized.fill_(1)
|
| 150 |
+
|
| 151 |
+
if len(output.shape) == 2:
|
| 152 |
+
output = output[:,:,None,None]
|
| 153 |
+
squeeze = True
|
| 154 |
+
else:
|
| 155 |
+
squeeze = False
|
| 156 |
+
|
| 157 |
+
h = output / self.scale - self.loc
|
| 158 |
+
|
| 159 |
+
if squeeze:
|
| 160 |
+
h = h.squeeze(-1).squeeze(-1)
|
| 161 |
+
return h
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
#################################################################################
|
| 166 |
+
# StyleGAN #
|
| 167 |
+
#################################################################################
|
| 168 |
+
class StyleGANDiscriminator(nn.Module):
|
| 169 |
+
def __init__(self, input_nc=3, ndf=64, n_layers=3, channel_multiplier=1, image_size=256):
|
| 170 |
+
super().__init__()
|
| 171 |
+
channels = {
|
| 172 |
+
4: 512,
|
| 173 |
+
8: 512,
|
| 174 |
+
16: 512,
|
| 175 |
+
32: 512,
|
| 176 |
+
64: 256 * channel_multiplier,
|
| 177 |
+
128: 128 * channel_multiplier,
|
| 178 |
+
256: 64 * channel_multiplier,
|
| 179 |
+
512: 32 * channel_multiplier,
|
| 180 |
+
1024: 16 * channel_multiplier,
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
log_size = int(math.log(image_size, 2))
|
| 184 |
+
in_channel = channels[image_size]
|
| 185 |
+
|
| 186 |
+
blocks = [nn.Conv2d(input_nc, in_channel, 3, padding=1), leaky_relu()]
|
| 187 |
+
for i in range(log_size, 2, -1):
|
| 188 |
+
out_channel = channels[2 ** (i - 1)]
|
| 189 |
+
blocks.append(DiscriminatorBlock(in_channel, out_channel))
|
| 190 |
+
in_channel = out_channel
|
| 191 |
+
self.blocks = nn.ModuleList(blocks)
|
| 192 |
+
|
| 193 |
+
self.final_conv = nn.Sequential(
|
| 194 |
+
nn.Conv2d(in_channel, channels[4], 3, padding=1),
|
| 195 |
+
leaky_relu(),
|
| 196 |
+
)
|
| 197 |
+
self.final_linear = nn.Sequential(
|
| 198 |
+
nn.Linear(channels[4] * 4 * 4, channels[4]),
|
| 199 |
+
leaky_relu(),
|
| 200 |
+
nn.Linear(channels[4], 1)
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
def forward(self, x):
|
| 204 |
+
for block in self.blocks:
|
| 205 |
+
x = block(x)
|
| 206 |
+
x = self.final_conv(x)
|
| 207 |
+
x = x.view(x.shape[0], -1)
|
| 208 |
+
x = self.final_linear(x)
|
| 209 |
+
return x
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class DiscriminatorBlock(nn.Module):
|
| 213 |
+
def __init__(self, input_channels, filters, downsample=True):
|
| 214 |
+
super().__init__()
|
| 215 |
+
self.conv_res = nn.Conv2d(input_channels, filters, 1, stride = (2 if downsample else 1))
|
| 216 |
+
|
| 217 |
+
self.net = nn.Sequential(
|
| 218 |
+
nn.Conv2d(input_channels, filters, 3, padding=1),
|
| 219 |
+
leaky_relu(),
|
| 220 |
+
nn.Conv2d(filters, filters, 3, padding=1),
|
| 221 |
+
leaky_relu()
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
self.downsample = nn.Sequential(
|
| 225 |
+
Blur(),
|
| 226 |
+
nn.Conv2d(filters, filters, 3, padding = 1, stride = 2)
|
| 227 |
+
) if downsample else None
|
| 228 |
+
|
| 229 |
+
def forward(self, x):
|
| 230 |
+
res = self.conv_res(x)
|
| 231 |
+
x = self.net(x)
|
| 232 |
+
if exists(self.downsample):
|
| 233 |
+
x = self.downsample(x)
|
| 234 |
+
x = (x + res) * (1 / math.sqrt(2))
|
| 235 |
+
return x
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
class Blur(nn.Module):
|
| 239 |
+
def __init__(self):
|
| 240 |
+
super().__init__()
|
| 241 |
+
f = torch.Tensor([1, 2, 1])
|
| 242 |
+
self.register_buffer('f', f)
|
| 243 |
+
|
| 244 |
+
def forward(self, x):
|
| 245 |
+
f = self.f
|
| 246 |
+
f = f[None, None, :] * f [None, :, None]
|
| 247 |
+
return filter2d(x, f, normalized=True)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def leaky_relu(p=0.2):
|
| 251 |
+
return nn.LeakyReLU(p, inplace=True)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def exists(val):
|
| 255 |
+
return val is not None
|
sjdtree/llamagen/tokenizer/tokenizer_image/discriminator_patchgan.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modified from:
|
| 2 |
+
# taming-transformers: https://github.com/CompVis/taming-transformers
|
| 3 |
+
import functools
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class NLayerDiscriminator(nn.Module):
|
| 9 |
+
"""Defines a PatchGAN discriminator as in Pix2Pix
|
| 10 |
+
--> see https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/networks.py
|
| 11 |
+
"""
|
| 12 |
+
def __init__(self, input_nc=3, ndf=64, n_layers=3, use_actnorm=False):
|
| 13 |
+
"""Construct a PatchGAN discriminator
|
| 14 |
+
Parameters:
|
| 15 |
+
input_nc (int) -- the number of channels in input images
|
| 16 |
+
ndf (int) -- the number of filters in the last conv layer
|
| 17 |
+
n_layers (int) -- the number of conv layers in the discriminator
|
| 18 |
+
norm_layer -- normalization layer
|
| 19 |
+
"""
|
| 20 |
+
super(NLayerDiscriminator, self).__init__()
|
| 21 |
+
if not use_actnorm:
|
| 22 |
+
norm_layer = nn.BatchNorm2d
|
| 23 |
+
else:
|
| 24 |
+
norm_layer = ActNorm
|
| 25 |
+
if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters
|
| 26 |
+
use_bias = norm_layer.func != nn.BatchNorm2d
|
| 27 |
+
else:
|
| 28 |
+
use_bias = norm_layer != nn.BatchNorm2d
|
| 29 |
+
|
| 30 |
+
kw = 4
|
| 31 |
+
padw = 1
|
| 32 |
+
sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]
|
| 33 |
+
nf_mult = 1
|
| 34 |
+
nf_mult_prev = 1
|
| 35 |
+
for n in range(1, n_layers): # gradually increase the number of filters
|
| 36 |
+
nf_mult_prev = nf_mult
|
| 37 |
+
nf_mult = min(2 ** n, 8)
|
| 38 |
+
sequence += [
|
| 39 |
+
nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias),
|
| 40 |
+
norm_layer(ndf * nf_mult),
|
| 41 |
+
nn.LeakyReLU(0.2, True)
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
nf_mult_prev = nf_mult
|
| 45 |
+
nf_mult = min(2 ** n_layers, 8)
|
| 46 |
+
sequence += [
|
| 47 |
+
nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),
|
| 48 |
+
norm_layer(ndf * nf_mult),
|
| 49 |
+
nn.LeakyReLU(0.2, True)
|
| 50 |
+
]
|
| 51 |
+
|
| 52 |
+
sequence += [
|
| 53 |
+
nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # output 1 channel prediction map
|
| 54 |
+
self.main = nn.Sequential(*sequence)
|
| 55 |
+
|
| 56 |
+
self.apply(self._init_weights)
|
| 57 |
+
|
| 58 |
+
def _init_weights(self, module):
|
| 59 |
+
if isinstance(module, nn.Conv2d):
|
| 60 |
+
nn.init.normal_(module.weight.data, 0.0, 0.02)
|
| 61 |
+
elif isinstance(module, nn.BatchNorm2d):
|
| 62 |
+
nn.init.normal_(module.weight.data, 1.0, 0.02)
|
| 63 |
+
nn.init.constant_(module.bias.data, 0)
|
| 64 |
+
|
| 65 |
+
def forward(self, input):
|
| 66 |
+
"""Standard forward."""
|
| 67 |
+
return self.main(input)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class ActNorm(nn.Module):
|
| 71 |
+
def __init__(self, num_features, logdet=False, affine=True,
|
| 72 |
+
allow_reverse_init=False):
|
| 73 |
+
assert affine
|
| 74 |
+
super().__init__()
|
| 75 |
+
self.logdet = logdet
|
| 76 |
+
self.loc = nn.Parameter(torch.zeros(1, num_features, 1, 1))
|
| 77 |
+
self.scale = nn.Parameter(torch.ones(1, num_features, 1, 1))
|
| 78 |
+
self.allow_reverse_init = allow_reverse_init
|
| 79 |
+
|
| 80 |
+
self.register_buffer('initialized', torch.tensor(0, dtype=torch.uint8))
|
| 81 |
+
|
| 82 |
+
def initialize(self, input):
|
| 83 |
+
with torch.no_grad():
|
| 84 |
+
flatten = input.permute(1, 0, 2, 3).contiguous().view(input.shape[1], -1)
|
| 85 |
+
mean = (
|
| 86 |
+
flatten.mean(1)
|
| 87 |
+
.unsqueeze(1)
|
| 88 |
+
.unsqueeze(2)
|
| 89 |
+
.unsqueeze(3)
|
| 90 |
+
.permute(1, 0, 2, 3)
|
| 91 |
+
)
|
| 92 |
+
std = (
|
| 93 |
+
flatten.std(1)
|
| 94 |
+
.unsqueeze(1)
|
| 95 |
+
.unsqueeze(2)
|
| 96 |
+
.unsqueeze(3)
|
| 97 |
+
.permute(1, 0, 2, 3)
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
self.loc.data.copy_(-mean)
|
| 101 |
+
self.scale.data.copy_(1 / (std + 1e-6))
|
| 102 |
+
|
| 103 |
+
def forward(self, input, reverse=False):
|
| 104 |
+
if reverse:
|
| 105 |
+
return self.reverse(input)
|
| 106 |
+
if len(input.shape) == 2:
|
| 107 |
+
input = input[:,:,None,None]
|
| 108 |
+
squeeze = True
|
| 109 |
+
else:
|
| 110 |
+
squeeze = False
|
| 111 |
+
|
| 112 |
+
_, _, height, width = input.shape
|
| 113 |
+
|
| 114 |
+
if self.training and self.initialized.item() == 0:
|
| 115 |
+
self.initialize(input)
|
| 116 |
+
self.initialized.fill_(1)
|
| 117 |
+
|
| 118 |
+
h = self.scale * (input + self.loc)
|
| 119 |
+
|
| 120 |
+
if squeeze:
|
| 121 |
+
h = h.squeeze(-1).squeeze(-1)
|
| 122 |
+
|
| 123 |
+
if self.logdet:
|
| 124 |
+
log_abs = torch.log(torch.abs(self.scale))
|
| 125 |
+
logdet = height*width*torch.sum(log_abs)
|
| 126 |
+
logdet = logdet * torch.ones(input.shape[0]).to(input)
|
| 127 |
+
return h, logdet
|
| 128 |
+
|
| 129 |
+
return h
|
| 130 |
+
|
| 131 |
+
def reverse(self, output):
|
| 132 |
+
if self.training and self.initialized.item() == 0:
|
| 133 |
+
if not self.allow_reverse_init:
|
| 134 |
+
raise RuntimeError(
|
| 135 |
+
"Initializing ActNorm in reverse direction is "
|
| 136 |
+
"disabled by default. Use allow_reverse_init=True to enable."
|
| 137 |
+
)
|
| 138 |
+
else:
|
| 139 |
+
self.initialize(output)
|
| 140 |
+
self.initialized.fill_(1)
|
| 141 |
+
|
| 142 |
+
if len(output.shape) == 2:
|
| 143 |
+
output = output[:,:,None,None]
|
| 144 |
+
squeeze = True
|
| 145 |
+
else:
|
| 146 |
+
squeeze = False
|
| 147 |
+
|
| 148 |
+
h = output / self.scale - self.loc
|
| 149 |
+
|
| 150 |
+
if squeeze:
|
| 151 |
+
h = h.squeeze(-1).squeeze(-1)
|
| 152 |
+
return h
|
sjdtree/llamagen/tokenizer/tokenizer_image/discriminator_stylegan.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modified from:
|
| 2 |
+
# stylegan2-pytorch: https://github.com/lucidrains/stylegan2-pytorch/blob/master/stylegan2_pytorch/stylegan2_pytorch.py
|
| 3 |
+
# stylegan2-pytorch: https://github.com/rosinality/stylegan2-pytorch/blob/master/model.py
|
| 4 |
+
# maskgit: https://github.com/google-research/maskgit/blob/main/maskgit/nets/discriminator.py
|
| 5 |
+
import math
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
try:
|
| 9 |
+
from kornia.filters import filter2d
|
| 10 |
+
except:
|
| 11 |
+
pass
|
| 12 |
+
|
| 13 |
+
class Discriminator(nn.Module):
|
| 14 |
+
def __init__(self, input_nc=3, ndf=64, n_layers=3, channel_multiplier=1, image_size=256):
|
| 15 |
+
super().__init__()
|
| 16 |
+
channels = {
|
| 17 |
+
4: 512,
|
| 18 |
+
8: 512,
|
| 19 |
+
16: 512,
|
| 20 |
+
32: 512,
|
| 21 |
+
64: 256 * channel_multiplier,
|
| 22 |
+
128: 128 * channel_multiplier,
|
| 23 |
+
256: 64 * channel_multiplier,
|
| 24 |
+
512: 32 * channel_multiplier,
|
| 25 |
+
1024: 16 * channel_multiplier,
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
log_size = int(math.log(image_size, 2))
|
| 29 |
+
in_channel = channels[image_size]
|
| 30 |
+
|
| 31 |
+
blocks = [nn.Conv2d(input_nc, in_channel, 3, padding=1), leaky_relu()]
|
| 32 |
+
for i in range(log_size, 2, -1):
|
| 33 |
+
out_channel = channels[2 ** (i - 1)]
|
| 34 |
+
blocks.append(DiscriminatorBlock(in_channel, out_channel))
|
| 35 |
+
in_channel = out_channel
|
| 36 |
+
self.blocks = nn.ModuleList(blocks)
|
| 37 |
+
|
| 38 |
+
self.final_conv = nn.Sequential(
|
| 39 |
+
nn.Conv2d(in_channel, channels[4], 3, padding=1),
|
| 40 |
+
leaky_relu(),
|
| 41 |
+
)
|
| 42 |
+
self.final_linear = nn.Sequential(
|
| 43 |
+
nn.Linear(channels[4] * 4 * 4, channels[4]),
|
| 44 |
+
leaky_relu(),
|
| 45 |
+
nn.Linear(channels[4], 1)
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
def forward(self, x):
|
| 49 |
+
for block in self.blocks:
|
| 50 |
+
x = block(x)
|
| 51 |
+
x = self.final_conv(x)
|
| 52 |
+
x = x.view(x.shape[0], -1)
|
| 53 |
+
x = self.final_linear(x)
|
| 54 |
+
return x
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class DiscriminatorBlock(nn.Module):
|
| 58 |
+
def __init__(self, input_channels, filters, downsample=True):
|
| 59 |
+
super().__init__()
|
| 60 |
+
self.conv_res = nn.Conv2d(input_channels, filters, 1, stride = (2 if downsample else 1))
|
| 61 |
+
|
| 62 |
+
self.net = nn.Sequential(
|
| 63 |
+
nn.Conv2d(input_channels, filters, 3, padding=1),
|
| 64 |
+
leaky_relu(),
|
| 65 |
+
nn.Conv2d(filters, filters, 3, padding=1),
|
| 66 |
+
leaky_relu()
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
self.downsample = nn.Sequential(
|
| 70 |
+
Blur(),
|
| 71 |
+
nn.Conv2d(filters, filters, 3, padding = 1, stride = 2)
|
| 72 |
+
) if downsample else None
|
| 73 |
+
|
| 74 |
+
def forward(self, x):
|
| 75 |
+
res = self.conv_res(x)
|
| 76 |
+
x = self.net(x)
|
| 77 |
+
if exists(self.downsample):
|
| 78 |
+
x = self.downsample(x)
|
| 79 |
+
x = (x + res) * (1 / math.sqrt(2))
|
| 80 |
+
return x
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class Blur(nn.Module):
|
| 85 |
+
def __init__(self):
|
| 86 |
+
super().__init__()
|
| 87 |
+
f = torch.Tensor([1, 2, 1])
|
| 88 |
+
self.register_buffer('f', f)
|
| 89 |
+
|
| 90 |
+
def forward(self, x):
|
| 91 |
+
f = self.f
|
| 92 |
+
f = f[None, None, :] * f [None, :, None]
|
| 93 |
+
return filter2d(x, f, normalized=True)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def leaky_relu(p=0.2):
|
| 97 |
+
return nn.LeakyReLU(p, inplace=True)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def exists(val):
|
| 101 |
+
return val is not None
|
sjdtree/llamagen/tokenizer/tokenizer_image/lpips.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stripped version of https://github.com/richzhang/PerceptualSimilarity/tree/master/models"""
|
| 2 |
+
|
| 3 |
+
import os, hashlib
|
| 4 |
+
import requests
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
from torchvision import models
|
| 10 |
+
from collections import namedtuple
|
| 11 |
+
|
| 12 |
+
URL_MAP = {
|
| 13 |
+
"vgg_lpips": "https://heibox.uni-heidelberg.de/f/607503859c864bc1b30b/?dl=1"
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
CKPT_MAP = {
|
| 17 |
+
"vgg_lpips": "vgg.pth"
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
MD5_MAP = {
|
| 21 |
+
"vgg_lpips": "d507d7349b931f0638a25a48a722f98a"
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
def download(url, local_path, chunk_size=1024):
|
| 25 |
+
os.makedirs(os.path.split(local_path)[0], exist_ok=True)
|
| 26 |
+
with requests.get(url, stream=True) as r:
|
| 27 |
+
total_size = int(r.headers.get("content-length", 0))
|
| 28 |
+
with tqdm(total=total_size, unit="B", unit_scale=True) as pbar:
|
| 29 |
+
with open(local_path, "wb") as f:
|
| 30 |
+
for data in r.iter_content(chunk_size=chunk_size):
|
| 31 |
+
if data:
|
| 32 |
+
f.write(data)
|
| 33 |
+
pbar.update(chunk_size)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def md5_hash(path):
|
| 37 |
+
with open(path, "rb") as f:
|
| 38 |
+
content = f.read()
|
| 39 |
+
return hashlib.md5(content).hexdigest()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def get_ckpt_path(name, root, check=False):
|
| 43 |
+
assert name in URL_MAP
|
| 44 |
+
path = os.path.join(root, CKPT_MAP[name])
|
| 45 |
+
if not os.path.exists(path) or (check and not md5_hash(path) == MD5_MAP[name]):
|
| 46 |
+
print("Downloading {} model from {} to {}".format(name, URL_MAP[name], path))
|
| 47 |
+
download(URL_MAP[name], path)
|
| 48 |
+
md5 = md5_hash(path)
|
| 49 |
+
assert md5 == MD5_MAP[name], md5
|
| 50 |
+
return path
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class LPIPS(nn.Module):
|
| 54 |
+
# Learned perceptual metric
|
| 55 |
+
def __init__(self, use_dropout=True):
|
| 56 |
+
super().__init__()
|
| 57 |
+
self.scaling_layer = ScalingLayer()
|
| 58 |
+
self.chns = [64, 128, 256, 512, 512] # vg16 features
|
| 59 |
+
self.net = vgg16(pretrained=True, requires_grad=False)
|
| 60 |
+
self.lin0 = NetLinLayer(self.chns[0], use_dropout=use_dropout)
|
| 61 |
+
self.lin1 = NetLinLayer(self.chns[1], use_dropout=use_dropout)
|
| 62 |
+
self.lin2 = NetLinLayer(self.chns[2], use_dropout=use_dropout)
|
| 63 |
+
self.lin3 = NetLinLayer(self.chns[3], use_dropout=use_dropout)
|
| 64 |
+
self.lin4 = NetLinLayer(self.chns[4], use_dropout=use_dropout)
|
| 65 |
+
self.load_from_pretrained()
|
| 66 |
+
for param in self.parameters():
|
| 67 |
+
param.requires_grad = False
|
| 68 |
+
|
| 69 |
+
def load_from_pretrained(self, name="vgg_lpips"):
|
| 70 |
+
ckpt = get_ckpt_path(name, os.path.join(os.path.dirname(os.path.abspath(__file__)), "cache"))
|
| 71 |
+
self.load_state_dict(torch.load(ckpt, map_location=torch.device("cpu")), strict=False)
|
| 72 |
+
print("loaded pretrained LPIPS loss from {}".format(ckpt))
|
| 73 |
+
|
| 74 |
+
@classmethod
|
| 75 |
+
def from_pretrained(cls, name="vgg_lpips"):
|
| 76 |
+
if name != "vgg_lpips":
|
| 77 |
+
raise NotImplementedError
|
| 78 |
+
model = cls()
|
| 79 |
+
ckpt = get_ckpt_path(name, os.path.join(os.path.dirname(os.path.abspath(__file__)), "cache"))
|
| 80 |
+
model.load_state_dict(torch.load(ckpt, map_location=torch.device("cpu")), strict=False)
|
| 81 |
+
return model
|
| 82 |
+
|
| 83 |
+
def forward(self, input, target):
|
| 84 |
+
in0_input, in1_input = (self.scaling_layer(input), self.scaling_layer(target))
|
| 85 |
+
outs0, outs1 = self.net(in0_input), self.net(in1_input)
|
| 86 |
+
feats0, feats1, diffs = {}, {}, {}
|
| 87 |
+
lins = [self.lin0, self.lin1, self.lin2, self.lin3, self.lin4]
|
| 88 |
+
for kk in range(len(self.chns)):
|
| 89 |
+
feats0[kk], feats1[kk] = normalize_tensor(outs0[kk]), normalize_tensor(outs1[kk])
|
| 90 |
+
diffs[kk] = (feats0[kk] - feats1[kk]) ** 2
|
| 91 |
+
|
| 92 |
+
res = [spatial_average(lins[kk].model(diffs[kk]), keepdim=True) for kk in range(len(self.chns))]
|
| 93 |
+
val = res[0]
|
| 94 |
+
for l in range(1, len(self.chns)):
|
| 95 |
+
val += res[l]
|
| 96 |
+
return val
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class ScalingLayer(nn.Module):
|
| 100 |
+
def __init__(self):
|
| 101 |
+
super(ScalingLayer, self).__init__()
|
| 102 |
+
self.register_buffer('shift', torch.Tensor([-.030, -.088, -.188])[None, :, None, None])
|
| 103 |
+
self.register_buffer('scale', torch.Tensor([.458, .448, .450])[None, :, None, None])
|
| 104 |
+
|
| 105 |
+
def forward(self, inp):
|
| 106 |
+
return (inp - self.shift) / self.scale
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class NetLinLayer(nn.Module):
|
| 110 |
+
""" A single linear layer which does a 1x1 conv """
|
| 111 |
+
def __init__(self, chn_in, chn_out=1, use_dropout=False):
|
| 112 |
+
super(NetLinLayer, self).__init__()
|
| 113 |
+
layers = [nn.Dropout(), ] if (use_dropout) else []
|
| 114 |
+
layers += [nn.Conv2d(chn_in, chn_out, 1, stride=1, padding=0, bias=False), ]
|
| 115 |
+
self.model = nn.Sequential(*layers)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class vgg16(torch.nn.Module):
|
| 119 |
+
def __init__(self, requires_grad=False, pretrained=True):
|
| 120 |
+
super(vgg16, self).__init__()
|
| 121 |
+
vgg_pretrained_features = models.vgg16(pretrained=pretrained).features
|
| 122 |
+
self.slice1 = torch.nn.Sequential()
|
| 123 |
+
self.slice2 = torch.nn.Sequential()
|
| 124 |
+
self.slice3 = torch.nn.Sequential()
|
| 125 |
+
self.slice4 = torch.nn.Sequential()
|
| 126 |
+
self.slice5 = torch.nn.Sequential()
|
| 127 |
+
self.N_slices = 5
|
| 128 |
+
for x in range(4):
|
| 129 |
+
self.slice1.add_module(str(x), vgg_pretrained_features[x])
|
| 130 |
+
for x in range(4, 9):
|
| 131 |
+
self.slice2.add_module(str(x), vgg_pretrained_features[x])
|
| 132 |
+
for x in range(9, 16):
|
| 133 |
+
self.slice3.add_module(str(x), vgg_pretrained_features[x])
|
| 134 |
+
for x in range(16, 23):
|
| 135 |
+
self.slice4.add_module(str(x), vgg_pretrained_features[x])
|
| 136 |
+
for x in range(23, 30):
|
| 137 |
+
self.slice5.add_module(str(x), vgg_pretrained_features[x])
|
| 138 |
+
if not requires_grad:
|
| 139 |
+
for param in self.parameters():
|
| 140 |
+
param.requires_grad = False
|
| 141 |
+
|
| 142 |
+
def forward(self, X):
|
| 143 |
+
h = self.slice1(X)
|
| 144 |
+
h_relu1_2 = h
|
| 145 |
+
h = self.slice2(h)
|
| 146 |
+
h_relu2_2 = h
|
| 147 |
+
h = self.slice3(h)
|
| 148 |
+
h_relu3_3 = h
|
| 149 |
+
h = self.slice4(h)
|
| 150 |
+
h_relu4_3 = h
|
| 151 |
+
h = self.slice5(h)
|
| 152 |
+
h_relu5_3 = h
|
| 153 |
+
vgg_outputs = namedtuple("VggOutputs", ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3', 'relu5_3'])
|
| 154 |
+
out = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3, h_relu5_3)
|
| 155 |
+
return out
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def normalize_tensor(x,eps=1e-10):
|
| 159 |
+
norm_factor = torch.sqrt(torch.sum(x**2,dim=1,keepdim=True))
|
| 160 |
+
return x/(norm_factor+eps)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def spatial_average(x, keepdim=True):
|
| 164 |
+
return x.mean([2,3],keepdim=keepdim)
|
sjdtree/llamagen/tokenizer/tokenizer_image/reconstruction_vq_ddp.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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32 = True
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import torch.distributed as dist
|
| 6 |
+
from torch.utils.data import DataLoader
|
| 7 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 8 |
+
from torchvision import transforms
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
import os
|
| 11 |
+
from PIL import Image
|
| 12 |
+
import numpy as np
|
| 13 |
+
import argparse
|
| 14 |
+
import itertools
|
| 15 |
+
|
| 16 |
+
from skimage.metrics import peak_signal_noise_ratio as psnr_loss
|
| 17 |
+
from skimage.metrics import structural_similarity as ssim_loss
|
| 18 |
+
|
| 19 |
+
from dataset.augmentation import center_crop_arr
|
| 20 |
+
from dataset.build import build_dataset
|
| 21 |
+
from tokenizer.tokenizer_image.vq_model import VQ_models
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def create_npz_from_sample_folder(sample_dir, num=50000):
|
| 26 |
+
"""
|
| 27 |
+
Builds a single .npz file from a folder of .png samples.
|
| 28 |
+
"""
|
| 29 |
+
samples = []
|
| 30 |
+
for i in tqdm(range(num), desc="Building .npz file from samples"):
|
| 31 |
+
sample_pil = Image.open(f"{sample_dir}/{i:06d}.png")
|
| 32 |
+
sample_np = np.asarray(sample_pil).astype(np.uint8)
|
| 33 |
+
samples.append(sample_np)
|
| 34 |
+
samples = np.stack(samples)
|
| 35 |
+
assert samples.shape == (num, samples.shape[1], samples.shape[2], 3)
|
| 36 |
+
npz_path = f"{sample_dir}.npz"
|
| 37 |
+
np.savez(npz_path, arr_0=samples)
|
| 38 |
+
print(f"Saved .npz file to {npz_path} [shape={samples.shape}].")
|
| 39 |
+
return npz_path
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def main(args):
|
| 44 |
+
# Setup PyTorch:
|
| 45 |
+
assert torch.cuda.is_available(), "Sampling with DDP requires at least one GPU. sample.py supports CPU-only usage"
|
| 46 |
+
torch.set_grad_enabled(False)
|
| 47 |
+
|
| 48 |
+
# Setup DDP:
|
| 49 |
+
dist.init_process_group("nccl")
|
| 50 |
+
rank = dist.get_rank()
|
| 51 |
+
device = rank % torch.cuda.device_count()
|
| 52 |
+
seed = args.global_seed * dist.get_world_size() + rank
|
| 53 |
+
torch.manual_seed(seed)
|
| 54 |
+
torch.cuda.set_device(device)
|
| 55 |
+
print(f"Starting rank={rank}, seed={seed}, world_size={dist.get_world_size()}.")
|
| 56 |
+
|
| 57 |
+
# create and load model
|
| 58 |
+
vq_model = VQ_models[args.vq_model](
|
| 59 |
+
codebook_size=args.codebook_size,
|
| 60 |
+
codebook_embed_dim=args.codebook_embed_dim)
|
| 61 |
+
vq_model.to(device)
|
| 62 |
+
vq_model.eval()
|
| 63 |
+
checkpoint = torch.load(args.vq_ckpt, map_location="cpu")
|
| 64 |
+
if "ema" in checkpoint: # ema
|
| 65 |
+
model_weight = checkpoint["ema"]
|
| 66 |
+
elif "model" in checkpoint: # ddp
|
| 67 |
+
model_weight = checkpoint["model"]
|
| 68 |
+
elif "state_dict" in checkpoint:
|
| 69 |
+
model_weight = checkpoint["state_dict"]
|
| 70 |
+
else:
|
| 71 |
+
raise Exception("please check model weight")
|
| 72 |
+
vq_model.load_state_dict(model_weight)
|
| 73 |
+
del checkpoint
|
| 74 |
+
|
| 75 |
+
# Create folder to save samples:
|
| 76 |
+
folder_name = (f"{args.vq_model}-{args.dataset}-size-{args.image_size}-size-{args.image_size_eval}"
|
| 77 |
+
f"-codebook-size-{args.codebook_size}-dim-{args.codebook_embed_dim}-seed-{args.global_seed}")
|
| 78 |
+
sample_folder_dir = f"{args.sample_dir}/{folder_name}"
|
| 79 |
+
if rank == 0:
|
| 80 |
+
os.makedirs(sample_folder_dir, exist_ok=True)
|
| 81 |
+
print(f"Saving .png samples at {sample_folder_dir}")
|
| 82 |
+
dist.barrier()
|
| 83 |
+
|
| 84 |
+
# Setup data:
|
| 85 |
+
transform = transforms.Compose([
|
| 86 |
+
transforms.Lambda(lambda pil_image: center_crop_arr(pil_image, args.image_size)),
|
| 87 |
+
transforms.ToTensor(),
|
| 88 |
+
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True)
|
| 89 |
+
])
|
| 90 |
+
|
| 91 |
+
if args.dataset == 'imagenet':
|
| 92 |
+
dataset = build_dataset(args, transform=transform)
|
| 93 |
+
num_fid_samples = 50000
|
| 94 |
+
elif args.dataset == 'coco':
|
| 95 |
+
dataset = build_dataset(args, transform=transform)
|
| 96 |
+
num_fid_samples = 5000
|
| 97 |
+
else:
|
| 98 |
+
raise Exception("please check dataset")
|
| 99 |
+
|
| 100 |
+
sampler = DistributedSampler(
|
| 101 |
+
dataset,
|
| 102 |
+
num_replicas=dist.get_world_size(),
|
| 103 |
+
rank=rank,
|
| 104 |
+
shuffle=False,
|
| 105 |
+
seed=args.global_seed
|
| 106 |
+
)
|
| 107 |
+
loader = DataLoader(
|
| 108 |
+
dataset,
|
| 109 |
+
batch_size=args.per_proc_batch_size,
|
| 110 |
+
shuffle=False,
|
| 111 |
+
sampler=sampler,
|
| 112 |
+
num_workers=args.num_workers,
|
| 113 |
+
pin_memory=True,
|
| 114 |
+
drop_last=False
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
# Figure out how many samples we need to generate on each GPU and how many iterations we need to run:
|
| 118 |
+
n = args.per_proc_batch_size
|
| 119 |
+
global_batch_size = n * dist.get_world_size()
|
| 120 |
+
|
| 121 |
+
psnr_val_rgb = []
|
| 122 |
+
ssim_val_rgb = []
|
| 123 |
+
loader = tqdm(loader) if rank == 0 else loader
|
| 124 |
+
total = 0
|
| 125 |
+
for x, _ in loader:
|
| 126 |
+
if args.image_size_eval != args.image_size:
|
| 127 |
+
rgb_gts = F.interpolate(x, size=(args.image_size_eval, args.image_size_eval), mode='bicubic')
|
| 128 |
+
else:
|
| 129 |
+
rgb_gts = x
|
| 130 |
+
rgb_gts = (rgb_gts.permute(0, 2, 3, 1).to("cpu").numpy() + 1.0) / 2.0 # rgb_gt value is between [0, 1]
|
| 131 |
+
x = x.to(device, non_blocking=True)
|
| 132 |
+
with torch.no_grad():
|
| 133 |
+
latent, _, [_, _, indices] = vq_model.encode(x)
|
| 134 |
+
samples = vq_model.decode_code(indices, latent.shape) # output value is between [-1, 1]
|
| 135 |
+
if args.image_size_eval != args.image_size:
|
| 136 |
+
samples = F.interpolate(samples, size=(args.image_size_eval, args.image_size_eval), mode='bicubic')
|
| 137 |
+
samples = torch.clamp(127.5 * samples + 128.0, 0, 255).permute(0, 2, 3, 1).to("cpu", dtype=torch.uint8).numpy()
|
| 138 |
+
|
| 139 |
+
# Save samples to disk as individual .png files
|
| 140 |
+
for i, (sample, rgb_gt) in enumerate(zip(samples, rgb_gts)):
|
| 141 |
+
index = i * dist.get_world_size() + rank + total
|
| 142 |
+
Image.fromarray(sample).save(f"{sample_folder_dir}/{index:06d}.png")
|
| 143 |
+
# metric
|
| 144 |
+
rgb_restored = sample.astype(np.float32) / 255. # rgb_restored value is between [0, 1]
|
| 145 |
+
psnr = psnr_loss(rgb_restored, rgb_gt)
|
| 146 |
+
ssim = ssim_loss(rgb_restored, rgb_gt, multichannel=True, data_range=2.0, channel_axis=-1)
|
| 147 |
+
psnr_val_rgb.append(psnr)
|
| 148 |
+
ssim_val_rgb.append(ssim)
|
| 149 |
+
|
| 150 |
+
total += global_batch_size
|
| 151 |
+
|
| 152 |
+
# ------------------------------------
|
| 153 |
+
# Summary
|
| 154 |
+
# ------------------------------------
|
| 155 |
+
# Make sure all processes have finished saving their samples
|
| 156 |
+
dist.barrier()
|
| 157 |
+
world_size = dist.get_world_size()
|
| 158 |
+
gather_psnr_val = [None for _ in range(world_size)]
|
| 159 |
+
gather_ssim_val = [None for _ in range(world_size)]
|
| 160 |
+
dist.all_gather_object(gather_psnr_val, psnr_val_rgb)
|
| 161 |
+
dist.all_gather_object(gather_ssim_val, ssim_val_rgb)
|
| 162 |
+
|
| 163 |
+
if rank == 0:
|
| 164 |
+
gather_psnr_val = list(itertools.chain(*gather_psnr_val))
|
| 165 |
+
gather_ssim_val = list(itertools.chain(*gather_ssim_val))
|
| 166 |
+
psnr_val_rgb = sum(gather_psnr_val) / len(gather_psnr_val)
|
| 167 |
+
ssim_val_rgb = sum(gather_ssim_val) / len(gather_ssim_val)
|
| 168 |
+
print("PSNR: %f, SSIM: %f " % (psnr_val_rgb, ssim_val_rgb))
|
| 169 |
+
|
| 170 |
+
result_file = f"{sample_folder_dir}_results.txt"
|
| 171 |
+
print("writing results to {}".format(result_file))
|
| 172 |
+
with open(result_file, 'w') as f:
|
| 173 |
+
print("PSNR: %f, SSIM: %f " % (psnr_val_rgb, ssim_val_rgb), file=f)
|
| 174 |
+
|
| 175 |
+
create_npz_from_sample_folder(sample_folder_dir, num_fid_samples)
|
| 176 |
+
print("Done.")
|
| 177 |
+
|
| 178 |
+
dist.barrier()
|
| 179 |
+
dist.destroy_process_group()
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
if __name__ == "__main__":
|
| 183 |
+
parser = argparse.ArgumentParser()
|
| 184 |
+
parser.add_argument("--data-path", type=str, required=True)
|
| 185 |
+
parser.add_argument("--dataset", type=str, choices=['imagenet', 'coco'], default='imagenet')
|
| 186 |
+
parser.add_argument("--vq-model", type=str, choices=list(VQ_models.keys()), default="VQ-16")
|
| 187 |
+
parser.add_argument("--vq-ckpt", type=str, default=None, help="ckpt path for vq model")
|
| 188 |
+
parser.add_argument("--codebook-size", type=int, default=16384, help="codebook size for vector quantization")
|
| 189 |
+
parser.add_argument("--codebook-embed-dim", type=int, default=8, help="codebook dimension for vector quantization")
|
| 190 |
+
parser.add_argument("--image-size", type=int, choices=[256, 384, 512], default=256)
|
| 191 |
+
parser.add_argument("--image-size-eval", type=int, choices=[256, 384, 512], default=256)
|
| 192 |
+
parser.add_argument("--sample-dir", type=str, default="reconstructions")
|
| 193 |
+
parser.add_argument("--per-proc-batch-size", type=int, default=32)
|
| 194 |
+
parser.add_argument("--global-seed", type=int, default=0)
|
| 195 |
+
parser.add_argument("--num-workers", type=int, default=4)
|
| 196 |
+
args = parser.parse_args()
|
| 197 |
+
main(args)
|
sjdtree/llamagen/tokenizer/tokenizer_image/vq_demo.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import argparse
|
| 6 |
+
import numpy as np
|
| 7 |
+
from PIL import Image
|
| 8 |
+
|
| 9 |
+
from tokenizer.tokenizer_image.vq_model import VQ_models
|
| 10 |
+
from dataset.augmentation import center_crop_arr
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def main(args):
|
| 14 |
+
# Setup PyTorch:
|
| 15 |
+
torch.manual_seed(args.seed)
|
| 16 |
+
torch.set_grad_enabled(False)
|
| 17 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 18 |
+
|
| 19 |
+
# create and load model
|
| 20 |
+
model = VQ_models[args.vq_model](
|
| 21 |
+
codebook_size=args.codebook_size,
|
| 22 |
+
codebook_embed_dim=args.codebook_embed_dim)
|
| 23 |
+
model.to(device)
|
| 24 |
+
model.eval()
|
| 25 |
+
checkpoint = torch.load(args.vq_ckpt, map_location="cpu")
|
| 26 |
+
if "ema" in checkpoint: # ema
|
| 27 |
+
model_weight = checkpoint["ema"]
|
| 28 |
+
elif "model" in checkpoint: # ddp
|
| 29 |
+
model_weight = checkpoint["model"]
|
| 30 |
+
elif "state_dict" in checkpoint:
|
| 31 |
+
model_weight = checkpoint["state_dict"]
|
| 32 |
+
else:
|
| 33 |
+
raise Exception("please check model weight")
|
| 34 |
+
model.load_state_dict(model_weight)
|
| 35 |
+
del checkpoint
|
| 36 |
+
|
| 37 |
+
# output dir
|
| 38 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 39 |
+
out_path = args.image_path.replace('.jpg', '_{}.jpg'.format(args.suffix))
|
| 40 |
+
out_path = out_path.replace('.jpeg', '_{}.jpeg'.format(args.suffix))
|
| 41 |
+
out_path = out_path.replace('.png', '_{}.png'.format(args.suffix))
|
| 42 |
+
out_filename = out_path.split('/')[-1]
|
| 43 |
+
out_path = os.path.join(args.output_dir, out_filename)
|
| 44 |
+
|
| 45 |
+
# load image
|
| 46 |
+
pil_image = Image.open(args.image_path).convert("RGB")
|
| 47 |
+
img = center_crop_arr(pil_image, args.image_size)
|
| 48 |
+
# # preprocess
|
| 49 |
+
# size_org = img.size
|
| 50 |
+
# img = img.resize((input_size, input_size))
|
| 51 |
+
img = np.array(img) / 255.
|
| 52 |
+
x = 2.0 * img - 1.0 # x value is between [-1, 1]
|
| 53 |
+
x = torch.tensor(x)
|
| 54 |
+
x = x.unsqueeze(dim=0)
|
| 55 |
+
x = torch.einsum('nhwc->nchw', x)
|
| 56 |
+
x_input = x.float().to("cuda")
|
| 57 |
+
|
| 58 |
+
# inference
|
| 59 |
+
with torch.no_grad():
|
| 60 |
+
latent, _, [_, _, indices] = model.encode(x_input)
|
| 61 |
+
output = model.decode_code(indices, latent.shape) # output value is between [-1, 1]
|
| 62 |
+
|
| 63 |
+
# postprocess
|
| 64 |
+
output = F.interpolate(output, size=[args.image_size, args.image_size], mode='bicubic').permute(0, 2, 3, 1)[0]
|
| 65 |
+
sample = torch.clamp(127.5 * output + 128.0, 0, 255).to("cpu", dtype=torch.uint8).numpy()
|
| 66 |
+
|
| 67 |
+
# save
|
| 68 |
+
Image.fromarray(sample).save(out_path)
|
| 69 |
+
print("Reconstructed image is saved to {}".format(out_path))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
if __name__ == "__main__":
|
| 73 |
+
parser = argparse.ArgumentParser()
|
| 74 |
+
parser.add_argument("--image-path", type=str, default="assets/example.jpg")
|
| 75 |
+
parser.add_argument("--output-dir", type=str, default="output_vq_demo")
|
| 76 |
+
parser.add_argument("--suffix", type=str, default="tokenizer_image")
|
| 77 |
+
parser.add_argument("--vq-model", type=str, choices=list(VQ_models.keys()), default="VQ-16")
|
| 78 |
+
parser.add_argument("--vq-ckpt", type=str, default=None, help="ckpt path for vq model")
|
| 79 |
+
parser.add_argument("--codebook-size", type=int, default=16384, help="codebook size for vector quantization")
|
| 80 |
+
parser.add_argument("--codebook-embed-dim", type=int, default=8, help="codebook dimension for vector quantization")
|
| 81 |
+
parser.add_argument("--image-size", type=int, choices=[256, 384, 448, 512, 1024], default=512)
|
| 82 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 83 |
+
args = parser.parse_args()
|
| 84 |
+
main(args)
|
sjdtree/llamagen/tokenizer/tokenizer_image/vq_loss.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modified from:
|
| 2 |
+
# taming-transformers: https://github.com/CompVis/taming-transformers
|
| 3 |
+
# muse-maskgit-pytorch: https://github.com/lucidrains/muse-maskgit-pytorch/blob/main/muse_maskgit_pytorch/vqgan_vae.py
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
|
| 8 |
+
from tokenizer.tokenizer_image.lpips import LPIPS
|
| 9 |
+
from tokenizer.tokenizer_image.discriminator_patchgan import NLayerDiscriminator as PatchGANDiscriminator
|
| 10 |
+
from tokenizer.tokenizer_image.discriminator_stylegan import Discriminator as StyleGANDiscriminator
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def hinge_d_loss(logits_real, logits_fake):
|
| 15 |
+
loss_real = torch.mean(F.relu(1. - logits_real))
|
| 16 |
+
loss_fake = torch.mean(F.relu(1. + logits_fake))
|
| 17 |
+
d_loss = 0.5 * (loss_real + loss_fake)
|
| 18 |
+
return d_loss
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def vanilla_d_loss(logits_real, logits_fake):
|
| 22 |
+
loss_real = torch.mean(F.softplus(-logits_real))
|
| 23 |
+
loss_fake = torch.mean(F.softplus(logits_fake))
|
| 24 |
+
d_loss = 0.5 * (loss_real + loss_fake)
|
| 25 |
+
return d_loss
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def non_saturating_d_loss(logits_real, logits_fake):
|
| 29 |
+
loss_real = torch.mean(F.binary_cross_entropy_with_logits(torch.ones_like(logits_real), logits_real))
|
| 30 |
+
loss_fake = torch.mean(F.binary_cross_entropy_with_logits(torch.zeros_like(logits_fake), logits_fake))
|
| 31 |
+
d_loss = 0.5 * (loss_real + loss_fake)
|
| 32 |
+
return d_loss
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def hinge_gen_loss(logit_fake):
|
| 36 |
+
return -torch.mean(logit_fake)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def non_saturating_gen_loss(logit_fake):
|
| 40 |
+
return torch.mean(F.binary_cross_entropy_with_logits(torch.ones_like(logit_fake), logit_fake))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def adopt_weight(weight, global_step, threshold=0, value=0.):
|
| 44 |
+
if global_step < threshold:
|
| 45 |
+
weight = value
|
| 46 |
+
return weight
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class VQLoss(nn.Module):
|
| 50 |
+
def __init__(self, disc_start, disc_loss="hinge", disc_dim=64, disc_type='patchgan', image_size=256,
|
| 51 |
+
disc_num_layers=3, disc_in_channels=3, disc_weight=1.0, disc_adaptive_weight = False,
|
| 52 |
+
gen_adv_loss='hinge', reconstruction_loss='l2', reconstruction_weight=1.0,
|
| 53 |
+
codebook_weight=1.0, perceptual_weight=1.0,
|
| 54 |
+
):
|
| 55 |
+
super().__init__()
|
| 56 |
+
# discriminator loss
|
| 57 |
+
assert disc_type in ["patchgan", "stylegan"]
|
| 58 |
+
assert disc_loss in ["hinge", "vanilla", "non-saturating"]
|
| 59 |
+
if disc_type == "patchgan":
|
| 60 |
+
self.discriminator = PatchGANDiscriminator(
|
| 61 |
+
input_nc=disc_in_channels,
|
| 62 |
+
n_layers=disc_num_layers,
|
| 63 |
+
ndf=disc_dim,
|
| 64 |
+
)
|
| 65 |
+
elif disc_type == "stylegan":
|
| 66 |
+
self.discriminator = StyleGANDiscriminator(
|
| 67 |
+
input_nc=disc_in_channels,
|
| 68 |
+
image_size=image_size,
|
| 69 |
+
)
|
| 70 |
+
else:
|
| 71 |
+
raise ValueError(f"Unknown GAN discriminator type '{disc_type}'.")
|
| 72 |
+
if disc_loss == "hinge":
|
| 73 |
+
self.disc_loss = hinge_d_loss
|
| 74 |
+
elif disc_loss == "vanilla":
|
| 75 |
+
self.disc_loss = vanilla_d_loss
|
| 76 |
+
elif disc_loss == "non-saturating":
|
| 77 |
+
self.disc_loss = non_saturating_d_loss
|
| 78 |
+
else:
|
| 79 |
+
raise ValueError(f"Unknown GAN discriminator loss '{disc_loss}'.")
|
| 80 |
+
self.discriminator_iter_start = disc_start
|
| 81 |
+
self.disc_weight = disc_weight
|
| 82 |
+
self.disc_adaptive_weight = disc_adaptive_weight
|
| 83 |
+
|
| 84 |
+
assert gen_adv_loss in ["hinge", "non-saturating"]
|
| 85 |
+
# gen_adv_loss
|
| 86 |
+
if gen_adv_loss == "hinge":
|
| 87 |
+
self.gen_adv_loss = hinge_gen_loss
|
| 88 |
+
elif gen_adv_loss == "non-saturating":
|
| 89 |
+
self.gen_adv_loss = non_saturating_gen_loss
|
| 90 |
+
else:
|
| 91 |
+
raise ValueError(f"Unknown GAN generator loss '{gen_adv_loss}'.")
|
| 92 |
+
|
| 93 |
+
# perceptual loss
|
| 94 |
+
self.perceptual_loss = LPIPS().eval()
|
| 95 |
+
self.perceptual_weight = perceptual_weight
|
| 96 |
+
|
| 97 |
+
# reconstruction loss
|
| 98 |
+
if reconstruction_loss == "l1":
|
| 99 |
+
self.rec_loss = F.l1_loss
|
| 100 |
+
elif reconstruction_loss == "l2":
|
| 101 |
+
self.rec_loss = F.mse_loss
|
| 102 |
+
else:
|
| 103 |
+
raise ValueError(f"Unknown rec loss '{reconstruction_loss}'.")
|
| 104 |
+
self.rec_weight = reconstruction_weight
|
| 105 |
+
|
| 106 |
+
# codebook loss
|
| 107 |
+
self.codebook_weight = codebook_weight
|
| 108 |
+
|
| 109 |
+
def calculate_adaptive_weight(self, nll_loss, g_loss, last_layer):
|
| 110 |
+
nll_grads = torch.autograd.grad(nll_loss, last_layer, retain_graph=True)[0]
|
| 111 |
+
g_grads = torch.autograd.grad(g_loss, last_layer, retain_graph=True)[0]
|
| 112 |
+
|
| 113 |
+
d_weight = torch.norm(nll_grads) / (torch.norm(g_grads) + 1e-4)
|
| 114 |
+
d_weight = torch.clamp(d_weight, 0.0, 1e4).detach()
|
| 115 |
+
return d_weight.detach()
|
| 116 |
+
|
| 117 |
+
def forward(self, codebook_loss, inputs, reconstructions, optimizer_idx, global_step, last_layer=None,
|
| 118 |
+
logger=None, log_every=100):
|
| 119 |
+
# generator update
|
| 120 |
+
if optimizer_idx == 0:
|
| 121 |
+
# reconstruction loss
|
| 122 |
+
rec_loss = self.rec_loss(inputs.contiguous(), reconstructions.contiguous())
|
| 123 |
+
|
| 124 |
+
# perceptual loss
|
| 125 |
+
p_loss = self.perceptual_loss(inputs.contiguous(), reconstructions.contiguous())
|
| 126 |
+
p_loss = torch.mean(p_loss)
|
| 127 |
+
|
| 128 |
+
# discriminator loss
|
| 129 |
+
logits_fake = self.discriminator(reconstructions.contiguous())
|
| 130 |
+
generator_adv_loss = self.gen_adv_loss(logits_fake)
|
| 131 |
+
|
| 132 |
+
if self.disc_adaptive_weight:
|
| 133 |
+
null_loss = self.rec_weight * rec_loss + self.perceptual_weight * p_loss
|
| 134 |
+
disc_adaptive_weight = self.calculate_adaptive_weight(null_loss, generator_adv_loss, last_layer=last_layer)
|
| 135 |
+
else:
|
| 136 |
+
disc_adaptive_weight = 1
|
| 137 |
+
disc_weight = adopt_weight(self.disc_weight, global_step, threshold=self.discriminator_iter_start)
|
| 138 |
+
|
| 139 |
+
loss = self.rec_weight * rec_loss + \
|
| 140 |
+
self.perceptual_weight * p_loss + \
|
| 141 |
+
disc_adaptive_weight * disc_weight * generator_adv_loss + \
|
| 142 |
+
codebook_loss[0] + codebook_loss[1] + codebook_loss[2]
|
| 143 |
+
|
| 144 |
+
if global_step % log_every == 0:
|
| 145 |
+
rec_loss = self.rec_weight * rec_loss
|
| 146 |
+
p_loss = self.perceptual_weight * p_loss
|
| 147 |
+
generator_adv_loss = disc_adaptive_weight * disc_weight * generator_adv_loss
|
| 148 |
+
logger.info(f"(Generator) rec_loss: {rec_loss:.4f}, perceptual_loss: {p_loss:.4f}, "
|
| 149 |
+
f"vq_loss: {codebook_loss[0]:.4f}, commit_loss: {codebook_loss[1]:.4f}, entropy_loss: {codebook_loss[2]:.4f}, "
|
| 150 |
+
f"codebook_usage: {codebook_loss[3]:.4f}, generator_adv_loss: {generator_adv_loss:.4f}, "
|
| 151 |
+
f"disc_adaptive_weight: {disc_adaptive_weight:.4f}, disc_weight: {disc_weight:.4f}")
|
| 152 |
+
return loss
|
| 153 |
+
|
| 154 |
+
# discriminator update
|
| 155 |
+
if optimizer_idx == 1:
|
| 156 |
+
logits_real = self.discriminator(inputs.contiguous().detach())
|
| 157 |
+
logits_fake = self.discriminator(reconstructions.contiguous().detach())
|
| 158 |
+
|
| 159 |
+
disc_weight = adopt_weight(self.disc_weight, global_step, threshold=self.discriminator_iter_start)
|
| 160 |
+
d_adversarial_loss = disc_weight * self.disc_loss(logits_real, logits_fake)
|
| 161 |
+
|
| 162 |
+
if global_step % log_every == 0:
|
| 163 |
+
logits_real = logits_real.detach().mean()
|
| 164 |
+
logits_fake = logits_fake.detach().mean()
|
| 165 |
+
logger.info(f"(Discriminator) "
|
| 166 |
+
f"discriminator_adv_loss: {d_adversarial_loss:.4f}, disc_weight: {disc_weight:.4f}, "
|
| 167 |
+
f"logits_real: {logits_real:.4f}, logits_fake: {logits_fake:.4f}")
|
| 168 |
+
return d_adversarial_loss
|
sjdtree/llamagen/tokenizer/tokenizer_image/vq_model.py
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modified from:
|
| 2 |
+
# taming-transformers: https://github.com/CompVis/taming-transformers
|
| 3 |
+
# maskgit: https://github.com/google-research/maskgit
|
| 4 |
+
from dataclasses import dataclass, field
|
| 5 |
+
from typing import List
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@dataclass
|
| 13 |
+
class ModelArgs:
|
| 14 |
+
codebook_size: int = 16384
|
| 15 |
+
codebook_embed_dim: int = 8
|
| 16 |
+
codebook_l2_norm: bool = True
|
| 17 |
+
codebook_show_usage: bool = True
|
| 18 |
+
commit_loss_beta: float = 0.25
|
| 19 |
+
entropy_loss_ratio: float = 0.0
|
| 20 |
+
|
| 21 |
+
encoder_ch_mult: List[int] = field(default_factory=lambda: [1, 1, 2, 2, 4])
|
| 22 |
+
decoder_ch_mult: List[int] = field(default_factory=lambda: [1, 1, 2, 2, 4])
|
| 23 |
+
z_channels: int = 256
|
| 24 |
+
dropout_p: float = 0.0
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class VQModel(nn.Module):
|
| 29 |
+
def __init__(self, config: ModelArgs):
|
| 30 |
+
super().__init__()
|
| 31 |
+
self.config = config
|
| 32 |
+
self.encoder = Encoder(ch_mult=config.encoder_ch_mult, z_channels=config.z_channels, dropout=config.dropout_p)
|
| 33 |
+
self.decoder = Decoder(ch_mult=config.decoder_ch_mult, z_channels=config.z_channels, dropout=config.dropout_p)
|
| 34 |
+
|
| 35 |
+
self.quantize = VectorQuantizer(config.codebook_size, config.codebook_embed_dim,
|
| 36 |
+
config.commit_loss_beta, config.entropy_loss_ratio,
|
| 37 |
+
config.codebook_l2_norm, config.codebook_show_usage)
|
| 38 |
+
self.quant_conv = nn.Conv2d(config.z_channels, config.codebook_embed_dim, 1)
|
| 39 |
+
self.post_quant_conv = nn.Conv2d(config.codebook_embed_dim, config.z_channels, 1)
|
| 40 |
+
|
| 41 |
+
def encode(self, x):
|
| 42 |
+
h = self.encoder(x)
|
| 43 |
+
h = self.quant_conv(h)
|
| 44 |
+
quant, emb_loss, info = self.quantize(h)
|
| 45 |
+
return quant, emb_loss, info
|
| 46 |
+
|
| 47 |
+
def decode(self, quant):
|
| 48 |
+
quant = self.post_quant_conv(quant)
|
| 49 |
+
dec = self.decoder(quant)
|
| 50 |
+
return dec
|
| 51 |
+
|
| 52 |
+
def decode_code(self, code_b, shape=None, channel_first=True):
|
| 53 |
+
quant_b = self.quantize.get_codebook_entry(code_b, shape, channel_first)
|
| 54 |
+
dec = self.decode(quant_b)
|
| 55 |
+
return dec
|
| 56 |
+
|
| 57 |
+
def forward(self, input):
|
| 58 |
+
quant, diff, _ = self.encode(input)
|
| 59 |
+
dec = self.decode(quant)
|
| 60 |
+
return dec, diff
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class Encoder(nn.Module):
|
| 65 |
+
def __init__(self, in_channels=3, ch=128, ch_mult=(1,1,2,2,4), num_res_blocks=2,
|
| 66 |
+
norm_type='group', dropout=0.0, resamp_with_conv=True, z_channels=256):
|
| 67 |
+
super().__init__()
|
| 68 |
+
self.num_resolutions = len(ch_mult)
|
| 69 |
+
self.num_res_blocks = num_res_blocks
|
| 70 |
+
self.conv_in = nn.Conv2d(in_channels, ch, kernel_size=3, stride=1, padding=1)
|
| 71 |
+
|
| 72 |
+
# downsampling
|
| 73 |
+
in_ch_mult = (1,) + tuple(ch_mult)
|
| 74 |
+
self.conv_blocks = nn.ModuleList()
|
| 75 |
+
for i_level in range(self.num_resolutions):
|
| 76 |
+
conv_block = nn.Module()
|
| 77 |
+
# res & attn
|
| 78 |
+
res_block = nn.ModuleList()
|
| 79 |
+
attn_block = nn.ModuleList()
|
| 80 |
+
block_in = ch*in_ch_mult[i_level]
|
| 81 |
+
block_out = ch*ch_mult[i_level]
|
| 82 |
+
for _ in range(self.num_res_blocks):
|
| 83 |
+
res_block.append(ResnetBlock(block_in, block_out, dropout=dropout, norm_type=norm_type))
|
| 84 |
+
block_in = block_out
|
| 85 |
+
if i_level == self.num_resolutions - 1:
|
| 86 |
+
attn_block.append(AttnBlock(block_in, norm_type))
|
| 87 |
+
conv_block.res = res_block
|
| 88 |
+
conv_block.attn = attn_block
|
| 89 |
+
# downsample
|
| 90 |
+
if i_level != self.num_resolutions-1:
|
| 91 |
+
conv_block.downsample = Downsample(block_in, resamp_with_conv)
|
| 92 |
+
self.conv_blocks.append(conv_block)
|
| 93 |
+
|
| 94 |
+
# middle
|
| 95 |
+
self.mid = nn.ModuleList()
|
| 96 |
+
self.mid.append(ResnetBlock(block_in, block_in, dropout=dropout, norm_type=norm_type))
|
| 97 |
+
self.mid.append(AttnBlock(block_in, norm_type=norm_type))
|
| 98 |
+
self.mid.append(ResnetBlock(block_in, block_in, dropout=dropout, norm_type=norm_type))
|
| 99 |
+
|
| 100 |
+
# end
|
| 101 |
+
self.norm_out = Normalize(block_in, norm_type)
|
| 102 |
+
self.conv_out = nn.Conv2d(block_in, z_channels, kernel_size=3, stride=1, padding=1)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def forward(self, x):
|
| 106 |
+
h = self.conv_in(x)
|
| 107 |
+
# downsampling
|
| 108 |
+
for i_level, block in enumerate(self.conv_blocks):
|
| 109 |
+
for i_block in range(self.num_res_blocks):
|
| 110 |
+
h = block.res[i_block](h)
|
| 111 |
+
if len(block.attn) > 0:
|
| 112 |
+
h = block.attn[i_block](h)
|
| 113 |
+
if i_level != self.num_resolutions - 1:
|
| 114 |
+
h = block.downsample(h)
|
| 115 |
+
|
| 116 |
+
# middle
|
| 117 |
+
for mid_block in self.mid:
|
| 118 |
+
h = mid_block(h)
|
| 119 |
+
|
| 120 |
+
# end
|
| 121 |
+
h = self.norm_out(h)
|
| 122 |
+
h = nonlinearity(h)
|
| 123 |
+
h = self.conv_out(h)
|
| 124 |
+
return h
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class Decoder(nn.Module):
|
| 129 |
+
def __init__(self, z_channels=256, ch=128, ch_mult=(1,1,2,2,4), num_res_blocks=2, norm_type="group",
|
| 130 |
+
dropout=0.0, resamp_with_conv=True, out_channels=3):
|
| 131 |
+
super().__init__()
|
| 132 |
+
self.num_resolutions = len(ch_mult)
|
| 133 |
+
self.num_res_blocks = num_res_blocks
|
| 134 |
+
|
| 135 |
+
block_in = ch*ch_mult[self.num_resolutions-1]
|
| 136 |
+
# z to block_in
|
| 137 |
+
self.conv_in = nn.Conv2d(z_channels, block_in, kernel_size=3, stride=1, padding=1)
|
| 138 |
+
|
| 139 |
+
# middle
|
| 140 |
+
self.mid = nn.ModuleList()
|
| 141 |
+
self.mid.append(ResnetBlock(block_in, block_in, dropout=dropout, norm_type=norm_type))
|
| 142 |
+
self.mid.append(AttnBlock(block_in, norm_type=norm_type))
|
| 143 |
+
self.mid.append(ResnetBlock(block_in, block_in, dropout=dropout, norm_type=norm_type))
|
| 144 |
+
|
| 145 |
+
# upsampling
|
| 146 |
+
self.conv_blocks = nn.ModuleList()
|
| 147 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 148 |
+
conv_block = nn.Module()
|
| 149 |
+
# res & attn
|
| 150 |
+
res_block = nn.ModuleList()
|
| 151 |
+
attn_block = nn.ModuleList()
|
| 152 |
+
block_out = ch*ch_mult[i_level]
|
| 153 |
+
for _ in range(self.num_res_blocks + 1):
|
| 154 |
+
res_block.append(ResnetBlock(block_in, block_out, dropout=dropout, norm_type=norm_type))
|
| 155 |
+
block_in = block_out
|
| 156 |
+
if i_level == self.num_resolutions - 1:
|
| 157 |
+
attn_block.append(AttnBlock(block_in, norm_type))
|
| 158 |
+
conv_block.res = res_block
|
| 159 |
+
conv_block.attn = attn_block
|
| 160 |
+
# downsample
|
| 161 |
+
if i_level != 0:
|
| 162 |
+
conv_block.upsample = Upsample(block_in, resamp_with_conv)
|
| 163 |
+
self.conv_blocks.append(conv_block)
|
| 164 |
+
|
| 165 |
+
# end
|
| 166 |
+
self.norm_out = Normalize(block_in, norm_type)
|
| 167 |
+
self.conv_out = nn.Conv2d(block_in, out_channels, kernel_size=3, stride=1, padding=1)
|
| 168 |
+
|
| 169 |
+
@property
|
| 170 |
+
def last_layer(self):
|
| 171 |
+
return self.conv_out.weight
|
| 172 |
+
|
| 173 |
+
def forward(self, z):
|
| 174 |
+
# z to block_in
|
| 175 |
+
h = self.conv_in(z)
|
| 176 |
+
|
| 177 |
+
# middle
|
| 178 |
+
for mid_block in self.mid:
|
| 179 |
+
h = mid_block(h)
|
| 180 |
+
|
| 181 |
+
# upsampling
|
| 182 |
+
for i_level, block in enumerate(self.conv_blocks):
|
| 183 |
+
for i_block in range(self.num_res_blocks + 1):
|
| 184 |
+
h = block.res[i_block](h)
|
| 185 |
+
if len(block.attn) > 0:
|
| 186 |
+
h = block.attn[i_block](h)
|
| 187 |
+
if i_level != self.num_resolutions - 1:
|
| 188 |
+
h = block.upsample(h)
|
| 189 |
+
|
| 190 |
+
# end
|
| 191 |
+
h = self.norm_out(h)
|
| 192 |
+
h = nonlinearity(h)
|
| 193 |
+
h = self.conv_out(h)
|
| 194 |
+
return h
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class VectorQuantizer(nn.Module):
|
| 198 |
+
def __init__(self, n_e, e_dim, beta, entropy_loss_ratio, l2_norm, show_usage):
|
| 199 |
+
super().__init__()
|
| 200 |
+
self.n_e = n_e
|
| 201 |
+
self.e_dim = e_dim
|
| 202 |
+
self.beta = beta
|
| 203 |
+
self.entropy_loss_ratio = entropy_loss_ratio
|
| 204 |
+
self.l2_norm = l2_norm
|
| 205 |
+
self.show_usage = show_usage
|
| 206 |
+
|
| 207 |
+
self.embedding = nn.Embedding(self.n_e, self.e_dim)
|
| 208 |
+
self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e)
|
| 209 |
+
if self.l2_norm:
|
| 210 |
+
self.embedding.weight.data = F.normalize(self.embedding.weight.data, p=2, dim=-1)
|
| 211 |
+
if self.show_usage:
|
| 212 |
+
self.register_buffer("codebook_used", nn.Parameter(torch.zeros(65536)))
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def forward(self, z):
|
| 216 |
+
# reshape z -> (batch, height, width, channel) and flatten
|
| 217 |
+
z = torch.einsum('b c h w -> b h w c', z).contiguous()
|
| 218 |
+
z_flattened = z.view(-1, self.e_dim)
|
| 219 |
+
# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
|
| 220 |
+
|
| 221 |
+
if self.l2_norm:
|
| 222 |
+
z = F.normalize(z, p=2, dim=-1)
|
| 223 |
+
z_flattened = F.normalize(z_flattened, p=2, dim=-1)
|
| 224 |
+
embedding = F.normalize(self.embedding.weight, p=2, dim=-1)
|
| 225 |
+
else:
|
| 226 |
+
embedding = self.embedding.weight
|
| 227 |
+
|
| 228 |
+
d = torch.sum(z_flattened ** 2, dim=1, keepdim=True) + \
|
| 229 |
+
torch.sum(embedding**2, dim=1) - 2 * \
|
| 230 |
+
torch.einsum('bd,dn->bn', z_flattened, torch.einsum('n d -> d n', embedding))
|
| 231 |
+
|
| 232 |
+
min_encoding_indices = torch.argmin(d, dim=1)
|
| 233 |
+
z_q = embedding[min_encoding_indices].view(z.shape)
|
| 234 |
+
perplexity = None
|
| 235 |
+
min_encodings = None
|
| 236 |
+
vq_loss = None
|
| 237 |
+
commit_loss = None
|
| 238 |
+
entropy_loss = None
|
| 239 |
+
codebook_usage = 0
|
| 240 |
+
|
| 241 |
+
if self.show_usage and self.training:
|
| 242 |
+
cur_len = min_encoding_indices.shape[0]
|
| 243 |
+
self.codebook_used[:-cur_len] = self.codebook_used[cur_len:].clone()
|
| 244 |
+
self.codebook_used[-cur_len:] = min_encoding_indices
|
| 245 |
+
codebook_usage = len(torch.unique(self.codebook_used)) / self.n_e
|
| 246 |
+
|
| 247 |
+
# compute loss for embedding
|
| 248 |
+
if self.training:
|
| 249 |
+
vq_loss = torch.mean((z_q - z.detach()) ** 2)
|
| 250 |
+
commit_loss = self.beta * torch.mean((z_q.detach() - z) ** 2)
|
| 251 |
+
entropy_loss = self.entropy_loss_ratio * compute_entropy_loss(-d)
|
| 252 |
+
|
| 253 |
+
# preserve gradients
|
| 254 |
+
z_q = z + (z_q - z).detach()
|
| 255 |
+
|
| 256 |
+
# reshape back to match original input shape
|
| 257 |
+
z_q = torch.einsum('b h w c -> b c h w', z_q)
|
| 258 |
+
|
| 259 |
+
return z_q, (vq_loss, commit_loss, entropy_loss, codebook_usage), (perplexity, min_encodings, min_encoding_indices)
|
| 260 |
+
|
| 261 |
+
def get_codebook_entry(self, indices, shape=None, channel_first=True):
|
| 262 |
+
# shape = (batch, channel, height, width) if channel_first else (batch, height, width, channel)
|
| 263 |
+
if self.l2_norm:
|
| 264 |
+
embedding = F.normalize(self.embedding.weight, p=2, dim=-1)
|
| 265 |
+
else:
|
| 266 |
+
embedding = self.embedding.weight
|
| 267 |
+
z_q = embedding[indices] # (b*h*w, c)
|
| 268 |
+
|
| 269 |
+
if shape is not None:
|
| 270 |
+
if channel_first:
|
| 271 |
+
z_q = z_q.reshape(shape[0], shape[2], shape[3], shape[1])
|
| 272 |
+
# reshape back to match original input shape
|
| 273 |
+
z_q = z_q.permute(0, 3, 1, 2).contiguous()
|
| 274 |
+
else:
|
| 275 |
+
z_q = z_q.view(shape)
|
| 276 |
+
return z_q
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class ResnetBlock(nn.Module):
|
| 280 |
+
def __init__(self, in_channels, out_channels=None, conv_shortcut=False, dropout=0.0, norm_type='group'):
|
| 281 |
+
super().__init__()
|
| 282 |
+
self.in_channels = in_channels
|
| 283 |
+
out_channels = in_channels if out_channels is None else out_channels
|
| 284 |
+
self.out_channels = out_channels
|
| 285 |
+
self.use_conv_shortcut = conv_shortcut
|
| 286 |
+
|
| 287 |
+
self.norm1 = Normalize(in_channels, norm_type)
|
| 288 |
+
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
| 289 |
+
self.norm2 = Normalize(out_channels, norm_type)
|
| 290 |
+
self.dropout = nn.Dropout(dropout)
|
| 291 |
+
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
| 292 |
+
|
| 293 |
+
if self.in_channels != self.out_channels:
|
| 294 |
+
if self.use_conv_shortcut:
|
| 295 |
+
self.conv_shortcut = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
| 296 |
+
else:
|
| 297 |
+
self.nin_shortcut = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
|
| 298 |
+
|
| 299 |
+
def forward(self, x):
|
| 300 |
+
h = x
|
| 301 |
+
h = self.norm1(h)
|
| 302 |
+
h = nonlinearity(h)
|
| 303 |
+
h = self.conv1(h)
|
| 304 |
+
h = self.norm2(h)
|
| 305 |
+
h = nonlinearity(h)
|
| 306 |
+
h = self.dropout(h)
|
| 307 |
+
h = self.conv2(h)
|
| 308 |
+
|
| 309 |
+
if self.in_channels != self.out_channels:
|
| 310 |
+
if self.use_conv_shortcut:
|
| 311 |
+
x = self.conv_shortcut(x)
|
| 312 |
+
else:
|
| 313 |
+
x = self.nin_shortcut(x)
|
| 314 |
+
return x+h
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
class AttnBlock(nn.Module):
|
| 318 |
+
def __init__(self, in_channels, norm_type='group'):
|
| 319 |
+
super().__init__()
|
| 320 |
+
self.norm = Normalize(in_channels, norm_type)
|
| 321 |
+
self.q = nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
|
| 322 |
+
self.k = nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
|
| 323 |
+
self.v = nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
|
| 324 |
+
self.proj_out = nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def forward(self, x):
|
| 328 |
+
h_ = x
|
| 329 |
+
h_ = self.norm(h_)
|
| 330 |
+
q = self.q(h_)
|
| 331 |
+
k = self.k(h_)
|
| 332 |
+
v = self.v(h_)
|
| 333 |
+
|
| 334 |
+
# compute attention
|
| 335 |
+
b,c,h,w = q.shape
|
| 336 |
+
q = q.reshape(b,c,h*w)
|
| 337 |
+
q = q.permute(0,2,1) # b,hw,c
|
| 338 |
+
k = k.reshape(b,c,h*w) # b,c,hw
|
| 339 |
+
w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
|
| 340 |
+
w_ = w_ * (int(c)**(-0.5))
|
| 341 |
+
w_ = F.softmax(w_, dim=2)
|
| 342 |
+
|
| 343 |
+
# attend to values
|
| 344 |
+
v = v.reshape(b,c,h*w)
|
| 345 |
+
w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q)
|
| 346 |
+
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]
|
| 347 |
+
h_ = h_.reshape(b,c,h,w)
|
| 348 |
+
|
| 349 |
+
h_ = self.proj_out(h_)
|
| 350 |
+
|
| 351 |
+
return x+h_
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def nonlinearity(x):
|
| 355 |
+
# swish
|
| 356 |
+
return x*torch.sigmoid(x)
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def Normalize(in_channels, norm_type='group'):
|
| 360 |
+
assert norm_type in ['group', 'batch']
|
| 361 |
+
if norm_type == 'group':
|
| 362 |
+
return nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
|
| 363 |
+
elif norm_type == 'batch':
|
| 364 |
+
return nn.SyncBatchNorm(in_channels)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
class Upsample(nn.Module):
|
| 368 |
+
def __init__(self, in_channels, with_conv):
|
| 369 |
+
super().__init__()
|
| 370 |
+
self.with_conv = with_conv
|
| 371 |
+
if self.with_conv:
|
| 372 |
+
self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)
|
| 373 |
+
|
| 374 |
+
def forward(self, x):
|
| 375 |
+
x = F.interpolate(x, scale_factor=2.0, mode="nearest")
|
| 376 |
+
if self.with_conv:
|
| 377 |
+
x = self.conv(x)
|
| 378 |
+
return x
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
class Downsample(nn.Module):
|
| 382 |
+
def __init__(self, in_channels, with_conv):
|
| 383 |
+
super().__init__()
|
| 384 |
+
self.with_conv = with_conv
|
| 385 |
+
if self.with_conv:
|
| 386 |
+
# no asymmetric padding in torch conv, must do it ourselves
|
| 387 |
+
self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=0)
|
| 388 |
+
|
| 389 |
+
def forward(self, x):
|
| 390 |
+
if self.with_conv:
|
| 391 |
+
pad = (0,1,0,1)
|
| 392 |
+
x = F.pad(x, pad, mode="constant", value=0)
|
| 393 |
+
x = self.conv(x)
|
| 394 |
+
else:
|
| 395 |
+
x = F.avg_pool2d(x, kernel_size=2, stride=2)
|
| 396 |
+
return x
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def compute_entropy_loss(affinity, loss_type="softmax", temperature=0.01):
|
| 400 |
+
flat_affinity = affinity.reshape(-1, affinity.shape[-1])
|
| 401 |
+
flat_affinity /= temperature
|
| 402 |
+
probs = F.softmax(flat_affinity, dim=-1)
|
| 403 |
+
log_probs = F.log_softmax(flat_affinity + 1e-5, dim=-1)
|
| 404 |
+
if loss_type == "softmax":
|
| 405 |
+
target_probs = probs
|
| 406 |
+
else:
|
| 407 |
+
raise ValueError("Entropy loss {} not supported".format(loss_type))
|
| 408 |
+
avg_probs = torch.mean(target_probs, dim=0)
|
| 409 |
+
avg_entropy = - torch.sum(avg_probs * torch.log(avg_probs + 1e-5))
|
| 410 |
+
sample_entropy = - torch.mean(torch.sum(target_probs * log_probs, dim=-1))
|
| 411 |
+
loss = sample_entropy - avg_entropy
|
| 412 |
+
return loss
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
#################################################################################
|
| 416 |
+
# VQ Model Configs #
|
| 417 |
+
#################################################################################
|
| 418 |
+
def VQ_8(**kwargs):
|
| 419 |
+
return VQModel(ModelArgs(encoder_ch_mult=[1, 2, 2, 4], decoder_ch_mult=[1, 2, 2, 4], **kwargs))
|
| 420 |
+
|
| 421 |
+
def VQ_16(**kwargs):
|
| 422 |
+
return VQModel(ModelArgs(encoder_ch_mult=[1, 1, 2, 2, 4], decoder_ch_mult=[1, 1, 2, 2, 4], **kwargs))
|
| 423 |
+
|
| 424 |
+
VQ_models = {'VQ-16': VQ_16, 'VQ-8': VQ_8}
|
sjdtree/llamagen/tokenizer/tokenizer_image/vq_model_hf.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from huggingface_hub import PyTorchModelHubMixin
|
| 2 |
+
|
| 3 |
+
from tokenizer.tokenizer_image.vq_model import ModelArgs, VQModel
|
| 4 |
+
|
| 5 |
+
class VQModelHF(VQModel, PyTorchModelHubMixin, repo_url="https://github.com/FoundationVision/LlamaGen", license="mit", tags=["llamagen", "text-to-image"]):
|
| 6 |
+
pass
|
| 7 |
+
|
| 8 |
+
#################################################################################
|
| 9 |
+
# VQ Model Configs #
|
| 10 |
+
#################################################################################
|
| 11 |
+
def VQ_8(**kwargs):
|
| 12 |
+
return VQModelHF(ModelArgs(encoder_ch_mult=[1, 2, 2, 4], decoder_ch_mult=[1, 2, 2, 4], **kwargs))
|
| 13 |
+
|
| 14 |
+
def VQ_16(**kwargs):
|
| 15 |
+
return VQModelHF(ModelArgs(encoder_ch_mult=[1, 1, 2, 2, 4], decoder_ch_mult=[1, 1, 2, 2, 4], **kwargs))
|
| 16 |
+
|
| 17 |
+
VQ_models_HF = {'VQ-16': VQ_16, 'VQ-8': VQ_8}
|
sjdtree/llamagen/tokenizer/tokenizer_image/vq_train.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modified from:
|
| 2 |
+
# fast-DiT: https://github.com/chuanyangjin/fast-DiT/blob/main/train.py
|
| 3 |
+
# nanoGPT: https://github.com/karpathy/nanoGPT/blob/master/model.py
|
| 4 |
+
import torch
|
| 5 |
+
# the first flag below was False when we tested this script but True makes A100 training a lot faster:
|
| 6 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 7 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 8 |
+
import torch.distributed as dist
|
| 9 |
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
| 10 |
+
from torch.utils.data import Dataset, DataLoader
|
| 11 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 12 |
+
from torchvision.datasets import ImageFolder
|
| 13 |
+
from torchvision import transforms
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import time
|
| 17 |
+
import argparse
|
| 18 |
+
from glob import glob
|
| 19 |
+
from copy import deepcopy
|
| 20 |
+
|
| 21 |
+
from utils.logger import create_logger
|
| 22 |
+
from utils.distributed import init_distributed_mode
|
| 23 |
+
from utils.ema import update_ema, requires_grad
|
| 24 |
+
from dataset.augmentation import random_crop_arr
|
| 25 |
+
from dataset.build import build_dataset
|
| 26 |
+
from tokenizer.tokenizer_image.vq_model import VQ_models
|
| 27 |
+
from tokenizer.tokenizer_image.vq_loss import VQLoss
|
| 28 |
+
|
| 29 |
+
import warnings
|
| 30 |
+
warnings.filterwarnings('ignore')
|
| 31 |
+
|
| 32 |
+
#################################################################################
|
| 33 |
+
# Training Loop #
|
| 34 |
+
#################################################################################
|
| 35 |
+
|
| 36 |
+
def main(args):
|
| 37 |
+
"""
|
| 38 |
+
Trains a new model.
|
| 39 |
+
"""
|
| 40 |
+
assert torch.cuda.is_available(), "Training currently requires at least one GPU."
|
| 41 |
+
|
| 42 |
+
# Setup DDP:
|
| 43 |
+
init_distributed_mode(args)
|
| 44 |
+
assert args.global_batch_size % dist.get_world_size() == 0, f"Batch size must be divisible by world size."
|
| 45 |
+
rank = dist.get_rank()
|
| 46 |
+
device = rank % torch.cuda.device_count()
|
| 47 |
+
seed = args.global_seed * dist.get_world_size() + rank
|
| 48 |
+
torch.manual_seed(seed)
|
| 49 |
+
torch.cuda.set_device(device)
|
| 50 |
+
|
| 51 |
+
# Setup an experiment folder:
|
| 52 |
+
if rank == 0:
|
| 53 |
+
os.makedirs(args.results_dir, exist_ok=True) # Make results folder (holds all experiment subfolders)
|
| 54 |
+
experiment_index = len(glob(f"{args.results_dir}/*"))
|
| 55 |
+
model_string_name = args.vq_model.replace("/", "-")
|
| 56 |
+
experiment_dir = f"{args.results_dir}/{experiment_index:03d}-{model_string_name}" # Create an experiment folder
|
| 57 |
+
checkpoint_dir = f"{experiment_dir}/checkpoints" # Stores saved model checkpoints
|
| 58 |
+
os.makedirs(checkpoint_dir, exist_ok=True)
|
| 59 |
+
logger = create_logger(experiment_dir)
|
| 60 |
+
logger.info(f"Experiment directory created at {experiment_dir}")
|
| 61 |
+
|
| 62 |
+
time_record = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
|
| 63 |
+
cloud_results_dir = f"{args.cloud_save_path}/{time_record}"
|
| 64 |
+
cloud_checkpoint_dir = f"{cloud_results_dir}/{experiment_index:03d}-{model_string_name}/checkpoints"
|
| 65 |
+
os.makedirs(cloud_checkpoint_dir, exist_ok=True)
|
| 66 |
+
logger.info(f"Experiment directory created in cloud at {cloud_checkpoint_dir}")
|
| 67 |
+
|
| 68 |
+
else:
|
| 69 |
+
logger = create_logger(None)
|
| 70 |
+
|
| 71 |
+
# training args
|
| 72 |
+
logger.info(f"{args}")
|
| 73 |
+
|
| 74 |
+
# training env
|
| 75 |
+
logger.info(f"Starting rank={rank}, seed={seed}, world_size={dist.get_world_size()}.")
|
| 76 |
+
|
| 77 |
+
# create and load model
|
| 78 |
+
vq_model = VQ_models[args.vq_model](
|
| 79 |
+
codebook_size=args.codebook_size,
|
| 80 |
+
codebook_embed_dim=args.codebook_embed_dim,
|
| 81 |
+
commit_loss_beta=args.commit_loss_beta,
|
| 82 |
+
entropy_loss_ratio=args.entropy_loss_ratio,
|
| 83 |
+
dropout_p=args.dropout_p,
|
| 84 |
+
)
|
| 85 |
+
logger.info(f"VQ Model Parameters: {sum(p.numel() for p in vq_model.parameters()):,}")
|
| 86 |
+
if args.ema:
|
| 87 |
+
ema = deepcopy(vq_model).to(device) # Create an EMA of the model for use after training
|
| 88 |
+
requires_grad(ema, False)
|
| 89 |
+
logger.info(f"VQ Model EMA Parameters: {sum(p.numel() for p in ema.parameters()):,}")
|
| 90 |
+
vq_model = vq_model.to(device)
|
| 91 |
+
|
| 92 |
+
vq_loss = VQLoss(
|
| 93 |
+
disc_start=args.disc_start,
|
| 94 |
+
disc_weight=args.disc_weight,
|
| 95 |
+
disc_type=args.disc_type,
|
| 96 |
+
disc_loss=args.disc_loss,
|
| 97 |
+
gen_adv_loss=args.gen_loss,
|
| 98 |
+
image_size=args.image_size,
|
| 99 |
+
perceptual_weight=args.perceptual_weight,
|
| 100 |
+
reconstruction_weight=args.reconstruction_weight,
|
| 101 |
+
reconstruction_loss=args.reconstruction_loss,
|
| 102 |
+
codebook_weight=args.codebook_weight,
|
| 103 |
+
).to(device)
|
| 104 |
+
logger.info(f"Discriminator Parameters: {sum(p.numel() for p in vq_loss.discriminator.parameters()):,}")
|
| 105 |
+
|
| 106 |
+
# initialize a GradScaler. If enabled=False scaler is a no-op
|
| 107 |
+
scaler = torch.cuda.amp.GradScaler(enabled=(args.mixed_precision =='fp16'))
|
| 108 |
+
scaler_disc = torch.cuda.amp.GradScaler(enabled=(args.mixed_precision =='fp16'))
|
| 109 |
+
# Setup optimizer
|
| 110 |
+
optimizer = torch.optim.Adam(vq_model.parameters(), lr=args.lr, betas=(args.beta1, args.beta2))
|
| 111 |
+
optimizer_disc = torch.optim.Adam(vq_loss.discriminator.parameters(), lr=args.lr, betas=(args.beta1, args.beta2))
|
| 112 |
+
|
| 113 |
+
# Setup data:
|
| 114 |
+
transform = transforms.Compose([
|
| 115 |
+
transforms.Lambda(lambda pil_image: random_crop_arr(pil_image, args.image_size)),
|
| 116 |
+
transforms.RandomHorizontalFlip(),
|
| 117 |
+
transforms.ToTensor(),
|
| 118 |
+
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True)
|
| 119 |
+
])
|
| 120 |
+
dataset = build_dataset(args, transform=transform)
|
| 121 |
+
sampler = DistributedSampler(
|
| 122 |
+
dataset,
|
| 123 |
+
num_replicas=dist.get_world_size(),
|
| 124 |
+
rank=rank,
|
| 125 |
+
shuffle=True,
|
| 126 |
+
seed=args.global_seed
|
| 127 |
+
)
|
| 128 |
+
loader = DataLoader(
|
| 129 |
+
dataset,
|
| 130 |
+
batch_size=int(args.global_batch_size // dist.get_world_size()),
|
| 131 |
+
shuffle=False,
|
| 132 |
+
sampler=sampler,
|
| 133 |
+
num_workers=args.num_workers,
|
| 134 |
+
pin_memory=True,
|
| 135 |
+
drop_last=True
|
| 136 |
+
)
|
| 137 |
+
logger.info(f"Dataset contains {len(dataset):,} images ({args.data_path})")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# Prepare models for training:
|
| 141 |
+
if args.vq_ckpt:
|
| 142 |
+
checkpoint = torch.load(args.vq_ckpt, map_location="cpu")
|
| 143 |
+
vq_model.load_state_dict(checkpoint["model"])
|
| 144 |
+
if args.ema:
|
| 145 |
+
ema.load_state_dict(checkpoint["ema"])
|
| 146 |
+
optimizer.load_state_dict(checkpoint["optimizer"])
|
| 147 |
+
vq_loss.discriminator.load_state_dict(checkpoint["discriminator"])
|
| 148 |
+
optimizer_disc.load_state_dict(checkpoint["optimizer_disc"])
|
| 149 |
+
if not args.finetune:
|
| 150 |
+
train_steps = checkpoint["steps"] if "steps" in checkpoint else int(args.vq_ckpt.split('/')[-1].split('.')[0])
|
| 151 |
+
start_epoch = int(train_steps / int(len(dataset) / args.global_batch_size))
|
| 152 |
+
train_steps = int(start_epoch * int(len(dataset) / args.global_batch_size))
|
| 153 |
+
else:
|
| 154 |
+
train_steps = 0
|
| 155 |
+
start_epoch = 0
|
| 156 |
+
del checkpoint
|
| 157 |
+
logger.info(f"Resume training from checkpoint: {args.vq_ckpt}")
|
| 158 |
+
logger.info(f"Initial state: steps={train_steps}, epochs={start_epoch}")
|
| 159 |
+
else:
|
| 160 |
+
train_steps = 0
|
| 161 |
+
start_epoch = 0
|
| 162 |
+
if args.ema:
|
| 163 |
+
update_ema(ema, vq_model, decay=0) # Ensure EMA is initialized with synced weights
|
| 164 |
+
|
| 165 |
+
if args.compile:
|
| 166 |
+
logger.info("compiling the model... (may take several minutes)")
|
| 167 |
+
vq_model = torch.compile(vq_model) # requires PyTorch 2.0
|
| 168 |
+
|
| 169 |
+
vq_model = DDP(vq_model.to(device), device_ids=[args.gpu])
|
| 170 |
+
vq_model.train()
|
| 171 |
+
if args.ema:
|
| 172 |
+
ema.eval() # EMA model should always be in eval mode
|
| 173 |
+
vq_loss = DDP(vq_loss.to(device), device_ids=[args.gpu])
|
| 174 |
+
vq_loss.train()
|
| 175 |
+
|
| 176 |
+
ptdtype = {'none': torch.float32, 'bf16': torch.bfloat16, 'fp16': torch.float16}[args.mixed_precision]
|
| 177 |
+
|
| 178 |
+
# Variables for monitoring/logging purposes:
|
| 179 |
+
log_steps = 0
|
| 180 |
+
running_loss = 0
|
| 181 |
+
start_time = time.time()
|
| 182 |
+
|
| 183 |
+
logger.info(f"Training for {args.epochs} epochs...")
|
| 184 |
+
for epoch in range(start_epoch, args.epochs):
|
| 185 |
+
sampler.set_epoch(epoch)
|
| 186 |
+
logger.info(f"Beginning epoch {epoch}...")
|
| 187 |
+
for x, y in loader:
|
| 188 |
+
imgs = x.to(device, non_blocking=True)
|
| 189 |
+
|
| 190 |
+
# generator training
|
| 191 |
+
optimizer.zero_grad()
|
| 192 |
+
with torch.cuda.amp.autocast(dtype=ptdtype):
|
| 193 |
+
recons_imgs, codebook_loss = vq_model(imgs)
|
| 194 |
+
loss_gen = vq_loss(codebook_loss, imgs, recons_imgs, optimizer_idx=0, global_step=train_steps+1,
|
| 195 |
+
last_layer=vq_model.module.decoder.last_layer,
|
| 196 |
+
logger=logger, log_every=args.log_every)
|
| 197 |
+
scaler.scale(loss_gen).backward()
|
| 198 |
+
if args.max_grad_norm != 0.0:
|
| 199 |
+
scaler.unscale_(optimizer)
|
| 200 |
+
torch.nn.utils.clip_grad_norm_(vq_model.parameters(), args.max_grad_norm)
|
| 201 |
+
scaler.step(optimizer)
|
| 202 |
+
scaler.update()
|
| 203 |
+
if args.ema:
|
| 204 |
+
update_ema(ema, vq_model.module._orig_mod if args.compile else vq_model.module)
|
| 205 |
+
|
| 206 |
+
# discriminator training
|
| 207 |
+
optimizer_disc.zero_grad()
|
| 208 |
+
with torch.cuda.amp.autocast(dtype=ptdtype):
|
| 209 |
+
loss_disc = vq_loss(codebook_loss, imgs, recons_imgs, optimizer_idx=1, global_step=train_steps+1,
|
| 210 |
+
logger=logger, log_every=args.log_every)
|
| 211 |
+
scaler_disc.scale(loss_disc).backward()
|
| 212 |
+
if args.max_grad_norm != 0.0:
|
| 213 |
+
scaler_disc.unscale_(optimizer_disc)
|
| 214 |
+
torch.nn.utils.clip_grad_norm_(vq_loss.module.discriminator.parameters(), args.max_grad_norm)
|
| 215 |
+
scaler_disc.step(optimizer_disc)
|
| 216 |
+
scaler_disc.update()
|
| 217 |
+
|
| 218 |
+
# # Log loss values:
|
| 219 |
+
running_loss += loss_gen.item() + loss_disc.item()
|
| 220 |
+
|
| 221 |
+
log_steps += 1
|
| 222 |
+
train_steps += 1
|
| 223 |
+
if train_steps % args.log_every == 0:
|
| 224 |
+
# Measure training speed:
|
| 225 |
+
torch.cuda.synchronize()
|
| 226 |
+
end_time = time.time()
|
| 227 |
+
steps_per_sec = log_steps / (end_time - start_time)
|
| 228 |
+
# Reduce loss history over all processes:
|
| 229 |
+
avg_loss = torch.tensor(running_loss / log_steps, device=device)
|
| 230 |
+
dist.all_reduce(avg_loss, op=dist.ReduceOp.SUM)
|
| 231 |
+
avg_loss = avg_loss.item() / dist.get_world_size()
|
| 232 |
+
logger.info(f"(step={train_steps:07d}) Train Loss: {avg_loss:.4f}, Train Steps/Sec: {steps_per_sec:.2f}")
|
| 233 |
+
# Reset monitoring variables:
|
| 234 |
+
running_loss = 0
|
| 235 |
+
log_steps = 0
|
| 236 |
+
start_time = time.time()
|
| 237 |
+
|
| 238 |
+
# Save checkpoint:
|
| 239 |
+
if train_steps % args.ckpt_every == 0 and train_steps > 0:
|
| 240 |
+
if rank == 0:
|
| 241 |
+
if args.compile:
|
| 242 |
+
model_weight = vq_model.module._orig_mod.state_dict()
|
| 243 |
+
else:
|
| 244 |
+
model_weight = vq_model.module.state_dict()
|
| 245 |
+
checkpoint = {
|
| 246 |
+
"model": model_weight,
|
| 247 |
+
"optimizer": optimizer.state_dict(),
|
| 248 |
+
"discriminator": vq_loss.module.discriminator.state_dict(),
|
| 249 |
+
"optimizer_disc": optimizer_disc.state_dict(),
|
| 250 |
+
"steps": train_steps,
|
| 251 |
+
"args": args
|
| 252 |
+
}
|
| 253 |
+
if args.ema:
|
| 254 |
+
checkpoint["ema"] = ema.state_dict()
|
| 255 |
+
if not args.no_local_save:
|
| 256 |
+
checkpoint_path = f"{checkpoint_dir}/{train_steps:07d}.pt"
|
| 257 |
+
torch.save(checkpoint, checkpoint_path)
|
| 258 |
+
logger.info(f"Saved checkpoint to {checkpoint_path}")
|
| 259 |
+
|
| 260 |
+
cloud_checkpoint_path = f"{cloud_checkpoint_dir}/{train_steps:07d}.pt"
|
| 261 |
+
torch.save(checkpoint, cloud_checkpoint_path)
|
| 262 |
+
logger.info(f"Saved checkpoint in cloud to {cloud_checkpoint_path}")
|
| 263 |
+
dist.barrier()
|
| 264 |
+
|
| 265 |
+
vq_model.eval() # important! This disables randomized embedding dropout
|
| 266 |
+
# do any sampling/FID calculation/etc. with ema (or model) in eval mode ...
|
| 267 |
+
|
| 268 |
+
logger.info("Done!")
|
| 269 |
+
dist.destroy_process_group()
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
if __name__ == "__main__":
|
| 274 |
+
parser = argparse.ArgumentParser()
|
| 275 |
+
parser.add_argument("--data-path", type=str, required=True)
|
| 276 |
+
parser.add_argument("--data-face-path", type=str, default=None, help="face datasets to improve vq model")
|
| 277 |
+
parser.add_argument("--cloud-save-path", type=str, required=True, help='please specify a cloud disk path, if not, local path')
|
| 278 |
+
parser.add_argument("--no-local-save", action='store_true', help='no save checkpoints to local path for limited disk volume')
|
| 279 |
+
parser.add_argument("--vq-model", type=str, choices=list(VQ_models.keys()), default="VQ-16")
|
| 280 |
+
parser.add_argument("--vq-ckpt", type=str, default=None, help="ckpt path for resume training")
|
| 281 |
+
parser.add_argument("--finetune", action='store_true', help="finetune a pre-trained vq model")
|
| 282 |
+
parser.add_argument("--ema", action='store_true', help="whether using ema training")
|
| 283 |
+
parser.add_argument("--codebook-size", type=int, default=16384, help="codebook size for vector quantization")
|
| 284 |
+
parser.add_argument("--codebook-embed-dim", type=int, default=8, help="codebook dimension for vector quantization")
|
| 285 |
+
parser.add_argument("--codebook-l2-norm", action='store_true', default=True, help="l2 norm codebook")
|
| 286 |
+
parser.add_argument("--codebook-weight", type=float, default=1.0, help="codebook loss weight for vector quantization")
|
| 287 |
+
parser.add_argument("--entropy-loss-ratio", type=float, default=0.0, help="entropy loss ratio in codebook loss")
|
| 288 |
+
parser.add_argument("--commit-loss-beta", type=float, default=0.25, help="commit loss beta in codebook loss")
|
| 289 |
+
parser.add_argument("--reconstruction-weight", type=float, default=1.0, help="reconstruction loss weight of image pixel")
|
| 290 |
+
parser.add_argument("--reconstruction-loss", type=str, default='l2', help="reconstruction loss type of image pixel")
|
| 291 |
+
parser.add_argument("--perceptual-weight", type=float, default=1.0, help="perceptual loss weight of LPIPS")
|
| 292 |
+
parser.add_argument("--disc-weight", type=float, default=0.5, help="discriminator loss weight for gan training")
|
| 293 |
+
parser.add_argument("--disc-start", type=int, default=20000, help="iteration to start discriminator training and loss")
|
| 294 |
+
parser.add_argument("--disc-type", type=str, choices=['patchgan', 'stylegan'], default='patchgan', help="discriminator type")
|
| 295 |
+
parser.add_argument("--disc-loss", type=str, choices=['hinge', 'vanilla', 'non-saturating'], default='hinge', help="discriminator loss")
|
| 296 |
+
parser.add_argument("--gen-loss", type=str, choices=['hinge', 'non-saturating'], default='hinge', help="generator loss for gan training")
|
| 297 |
+
parser.add_argument("--compile", action='store_true', default=False)
|
| 298 |
+
parser.add_argument("--dropout-p", type=float, default=0.0, help="dropout_p")
|
| 299 |
+
parser.add_argument("--results-dir", type=str, default="results_tokenizer_image")
|
| 300 |
+
parser.add_argument("--dataset", type=str, default='imagenet')
|
| 301 |
+
parser.add_argument("--image-size", type=int, choices=[256, 512], default=256)
|
| 302 |
+
parser.add_argument("--epochs", type=int, default=40)
|
| 303 |
+
parser.add_argument("--lr", type=float, default=1e-4)
|
| 304 |
+
parser.add_argument("--weight-decay", type=float, default=5e-2, help="Weight decay to use.")
|
| 305 |
+
parser.add_argument("--beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
| 306 |
+
parser.add_argument("--beta2", type=float, default=0.95, help="The beta2 parameter for the Adam optimizer.")
|
| 307 |
+
parser.add_argument("--max-grad-norm", default=1.0, type=float, help="Max gradient norm.")
|
| 308 |
+
parser.add_argument("--global-batch-size", type=int, default=128)
|
| 309 |
+
parser.add_argument("--global-seed", type=int, default=0)
|
| 310 |
+
parser.add_argument("--num-workers", type=int, default=16)
|
| 311 |
+
parser.add_argument("--log-every", type=int, default=100)
|
| 312 |
+
parser.add_argument("--ckpt-every", type=int, default=5000)
|
| 313 |
+
parser.add_argument("--gradient-accumulation-steps", type=int, default=1)
|
| 314 |
+
parser.add_argument("--mixed-precision", type=str, default='bf16', choices=["none", "fp16", "bf16"])
|
| 315 |
+
args = parser.parse_args()
|
| 316 |
+
main(args)
|
sjdtree/llamagen/tokenizer/vae/README.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## VAE Models from Stable Diffusion
|
| 2 |
+
|
| 3 |
+
### install
|
| 4 |
+
```
|
| 5 |
+
pip install diffusers
|
| 6 |
+
pip install accelerate
|
| 7 |
+
```
|
| 8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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 3 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 4 |
+
import torch.distributed as dist
|
| 5 |
+
from torch.utils.data import Dataset, DataLoader
|
| 6 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 7 |
+
from torchvision.datasets import ImageFolder
|
| 8 |
+
from torchvision import transforms
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
import os
|
| 11 |
+
import itertools
|
| 12 |
+
from PIL import Image
|
| 13 |
+
import numpy as np
|
| 14 |
+
import argparse
|
| 15 |
+
import random
|
| 16 |
+
|
| 17 |
+
from skimage.metrics import peak_signal_noise_ratio as psnr_loss
|
| 18 |
+
from skimage.metrics import structural_similarity as ssim_loss
|
| 19 |
+
from diffusers.models import AutoencoderKL
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class SingleFolderDataset(Dataset):
|
| 23 |
+
def __init__(self, directory, transform=None):
|
| 24 |
+
super().__init__()
|
| 25 |
+
self.directory = directory
|
| 26 |
+
self.transform = transform
|
| 27 |
+
self.image_paths = [os.path.join(directory, file_name) for file_name in os.listdir(directory)
|
| 28 |
+
if os.path.isfile(os.path.join(directory, file_name))]
|
| 29 |
+
|
| 30 |
+
def __len__(self):
|
| 31 |
+
return len(self.image_paths)
|
| 32 |
+
|
| 33 |
+
def __getitem__(self, idx):
|
| 34 |
+
image_path = self.image_paths[idx]
|
| 35 |
+
image = Image.open(image_path).convert('RGB')
|
| 36 |
+
if self.transform:
|
| 37 |
+
image = self.transform(image)
|
| 38 |
+
return image, torch.tensor(0)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def create_npz_from_sample_folder(sample_dir, num=50_000):
|
| 42 |
+
"""
|
| 43 |
+
Builds a single .npz file from a folder of .png samples.
|
| 44 |
+
"""
|
| 45 |
+
samples = []
|
| 46 |
+
for i in tqdm(range(num), desc="Building .npz file from samples"):
|
| 47 |
+
sample_pil = Image.open(f"{sample_dir}/{i:06d}.png")
|
| 48 |
+
sample_np = np.asarray(sample_pil).astype(np.uint8)
|
| 49 |
+
samples.append(sample_np)
|
| 50 |
+
|
| 51 |
+
random.shuffle(samples) # This is very important for IS(Inception Score) !!!
|
| 52 |
+
samples = np.stack(samples)
|
| 53 |
+
assert samples.shape == (num, samples.shape[1], samples.shape[2], 3)
|
| 54 |
+
npz_path = f"{sample_dir}.npz"
|
| 55 |
+
np.savez(npz_path, arr_0=samples)
|
| 56 |
+
print(f"Saved .npz file to {npz_path} [shape={samples.shape}].")
|
| 57 |
+
return npz_path
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def center_crop_arr(pil_image, image_size):
|
| 61 |
+
"""
|
| 62 |
+
Center cropping implementation from ADM.
|
| 63 |
+
https://github.com/openai/guided-diffusion/blob/8fb3ad9197f16bbc40620447b2742e13458d2831/guided_diffusion/image_datasets.py#L126
|
| 64 |
+
"""
|
| 65 |
+
while min(*pil_image.size) >= 2 * image_size:
|
| 66 |
+
pil_image = pil_image.resize(
|
| 67 |
+
tuple(x // 2 for x in pil_image.size), resample=Image.BOX
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
scale = image_size / min(*pil_image.size)
|
| 71 |
+
pil_image = pil_image.resize(
|
| 72 |
+
tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
arr = np.array(pil_image)
|
| 76 |
+
crop_y = (arr.shape[0] - image_size) // 2
|
| 77 |
+
crop_x = (arr.shape[1] - image_size) // 2
|
| 78 |
+
return Image.fromarray(arr[crop_y: crop_y + image_size, crop_x: crop_x + image_size])
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def main(args):
|
| 82 |
+
# Setup PyTorch:
|
| 83 |
+
assert torch.cuda.is_available(), "Sampling with DDP requires at least one GPU. sample.py supports CPU-only usage"
|
| 84 |
+
torch.set_grad_enabled(False)
|
| 85 |
+
|
| 86 |
+
# Setup DDP:
|
| 87 |
+
dist.init_process_group("nccl")
|
| 88 |
+
rank = dist.get_rank()
|
| 89 |
+
device = rank % torch.cuda.device_count()
|
| 90 |
+
seed = args.global_seed * dist.get_world_size() + rank
|
| 91 |
+
torch.manual_seed(seed)
|
| 92 |
+
torch.cuda.set_device(device)
|
| 93 |
+
print(f"Starting rank={rank}, seed={seed}, world_size={dist.get_world_size()}.")
|
| 94 |
+
|
| 95 |
+
# load vae
|
| 96 |
+
vae = AutoencoderKL.from_pretrained(f"stabilityai/{args.vae}").to(device)
|
| 97 |
+
|
| 98 |
+
# Create folder to save samples:
|
| 99 |
+
folder_name = f"stabilityai-{args.vae}-{args.dataset}-size-{args.image_size}-seed-{args.global_seed}"
|
| 100 |
+
sample_folder_dir = f"{args.sample_dir}/{folder_name}"
|
| 101 |
+
if rank == 0:
|
| 102 |
+
os.makedirs(sample_folder_dir, exist_ok=True)
|
| 103 |
+
print(f"Saving .png samples at {sample_folder_dir}")
|
| 104 |
+
dist.barrier()
|
| 105 |
+
|
| 106 |
+
# Setup data:
|
| 107 |
+
transform = transforms.Compose([
|
| 108 |
+
transforms.Lambda(lambda pil_image: center_crop_arr(pil_image, args.image_size)),
|
| 109 |
+
transforms.ToTensor(),
|
| 110 |
+
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True)
|
| 111 |
+
])
|
| 112 |
+
if args.dataset == 'imagenet':
|
| 113 |
+
dataset = ImageFolder(args.data_path, transform=transform)
|
| 114 |
+
num_fid_samples = 50000
|
| 115 |
+
elif args.dataset == 'coco':
|
| 116 |
+
dataset = SingleFolderDataset(args.data_path, transform=transform)
|
| 117 |
+
num_fid_samples = 5000
|
| 118 |
+
else:
|
| 119 |
+
raise Exception("please check dataset")
|
| 120 |
+
|
| 121 |
+
sampler = DistributedSampler(
|
| 122 |
+
dataset,
|
| 123 |
+
num_replicas=dist.get_world_size(),
|
| 124 |
+
rank=rank,
|
| 125 |
+
shuffle=False,
|
| 126 |
+
seed=args.global_seed
|
| 127 |
+
)
|
| 128 |
+
loader = DataLoader(
|
| 129 |
+
dataset,
|
| 130 |
+
batch_size=args.per_proc_batch_size,
|
| 131 |
+
shuffle=False,
|
| 132 |
+
sampler=sampler,
|
| 133 |
+
num_workers=args.num_workers,
|
| 134 |
+
pin_memory=True,
|
| 135 |
+
drop_last=False
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
# Figure out how many samples we need to generate on each GPU and how many iterations we need to run:
|
| 139 |
+
n = args.per_proc_batch_size
|
| 140 |
+
global_batch_size = n * dist.get_world_size()
|
| 141 |
+
|
| 142 |
+
psnr_val_rgb = []
|
| 143 |
+
ssim_val_rgb = []
|
| 144 |
+
loader = tqdm(loader) if rank == 0 else loader
|
| 145 |
+
total = 0
|
| 146 |
+
for x, _ in loader:
|
| 147 |
+
rgb_gts = x
|
| 148 |
+
rgb_gts = (rgb_gts.permute(0, 2, 3, 1).to("cpu").numpy() + 1.0) / 2.0 # rgb_gt value is between [0, 1]
|
| 149 |
+
x = x.to(device)
|
| 150 |
+
with torch.no_grad():
|
| 151 |
+
# Map input images to latent space + normalize latents:
|
| 152 |
+
latent = vae.encode(x).latent_dist.sample().mul_(0.18215)
|
| 153 |
+
# reconstruct:
|
| 154 |
+
samples = vae.decode(latent / 0.18215).sample # output value is between [-1, 1]
|
| 155 |
+
samples = torch.clamp(127.5 * samples + 128.0, 0, 255).permute(0, 2, 3, 1).to("cpu", dtype=torch.uint8).numpy()
|
| 156 |
+
|
| 157 |
+
# Save samples to disk as individual .png files
|
| 158 |
+
for i, (sample, rgb_gt) in enumerate(zip(samples, rgb_gts)):
|
| 159 |
+
index = i * dist.get_world_size() + rank + total
|
| 160 |
+
Image.fromarray(sample).save(f"{sample_folder_dir}/{index:06d}.png")
|
| 161 |
+
# metric
|
| 162 |
+
rgb_restored = sample.astype(np.float32) / 255. # rgb_restored value is between [0, 1]
|
| 163 |
+
psnr = psnr_loss(rgb_restored, rgb_gt)
|
| 164 |
+
ssim = ssim_loss(rgb_restored, rgb_gt, multichannel=True, data_range=2.0, channel_axis=-1)
|
| 165 |
+
psnr_val_rgb.append(psnr)
|
| 166 |
+
ssim_val_rgb.append(ssim)
|
| 167 |
+
total += global_batch_size
|
| 168 |
+
|
| 169 |
+
# ------------------------------------
|
| 170 |
+
# Summary
|
| 171 |
+
# ------------------------------------
|
| 172 |
+
# Make sure all processes have finished saving their samples
|
| 173 |
+
dist.barrier()
|
| 174 |
+
world_size = dist.get_world_size()
|
| 175 |
+
gather_psnr_val = [None for _ in range(world_size)]
|
| 176 |
+
gather_ssim_val = [None for _ in range(world_size)]
|
| 177 |
+
dist.all_gather_object(gather_psnr_val, psnr_val_rgb)
|
| 178 |
+
dist.all_gather_object(gather_ssim_val, ssim_val_rgb)
|
| 179 |
+
|
| 180 |
+
if rank == 0:
|
| 181 |
+
gather_psnr_val = list(itertools.chain(*gather_psnr_val))
|
| 182 |
+
gather_ssim_val = list(itertools.chain(*gather_ssim_val))
|
| 183 |
+
psnr_val_rgb = sum(gather_psnr_val) / len(gather_psnr_val)
|
| 184 |
+
ssim_val_rgb = sum(gather_ssim_val) / len(gather_ssim_val)
|
| 185 |
+
print("PSNR: %f, SSIM: %f " % (psnr_val_rgb, ssim_val_rgb))
|
| 186 |
+
|
| 187 |
+
result_file = f"{sample_folder_dir}_results.txt"
|
| 188 |
+
print("writing results to {}".format(result_file))
|
| 189 |
+
with open(result_file, 'w') as f:
|
| 190 |
+
print("PSNR: %f, SSIM: %f " % (psnr_val_rgb, ssim_val_rgb), file=f)
|
| 191 |
+
|
| 192 |
+
create_npz_from_sample_folder(sample_folder_dir, num_fid_samples)
|
| 193 |
+
print("Done.")
|
| 194 |
+
|
| 195 |
+
dist.barrier()
|
| 196 |
+
dist.destroy_process_group()
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
if __name__ == "__main__":
|
| 200 |
+
parser = argparse.ArgumentParser()
|
| 201 |
+
parser.add_argument("--data-path", type=str, required=True)
|
| 202 |
+
parser.add_argument("--dataset", type=str, choices=['imagenet', 'coco'], default='imagenet')
|
| 203 |
+
parser.add_argument("--vae", type=str, choices=["sdxl-vae", "sd-vae-ft-mse"], default="sd-vae-ft-mse")
|
| 204 |
+
parser.add_argument("--image-size", type=int, choices=[256, 512], default=256)
|
| 205 |
+
parser.add_argument("--sample-dir", type=str, default="reconstructions")
|
| 206 |
+
parser.add_argument("--per-proc-batch-size", type=int, default=32)
|
| 207 |
+
parser.add_argument("--global-seed", type=int, default=0)
|
| 208 |
+
parser.add_argument("--num-workers", type=int, default=4)
|
| 209 |
+
args = parser.parse_args()
|
| 210 |
+
main(args)
|
sjdtree/llamagen/tokenizer/vae/sd_vae_demo.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from diffusers.models import AutoencoderKL
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def main(args):
|
| 10 |
+
# Setup PyTorch:
|
| 11 |
+
torch.manual_seed(args.seed)
|
| 12 |
+
torch.set_grad_enabled(False)
|
| 13 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 14 |
+
|
| 15 |
+
# create and load model
|
| 16 |
+
vae = AutoencoderKL.from_pretrained(f"stabilityai/{args.vae}").to(device)
|
| 17 |
+
|
| 18 |
+
# load image
|
| 19 |
+
img_path = args.image_path
|
| 20 |
+
out_path = args.image_path.replace('.jpg', '_vae.jpg').replace('.jpeg', '_vae.jpeg').replace('.png', '_vae.png')
|
| 21 |
+
input_size = args.image_size
|
| 22 |
+
img = Image.open(img_path).convert("RGB")
|
| 23 |
+
|
| 24 |
+
# preprocess
|
| 25 |
+
size_org = img.size
|
| 26 |
+
img = img.resize((input_size, input_size))
|
| 27 |
+
img = np.array(img) / 255.
|
| 28 |
+
x = 2.0 * img - 1.0 # x value is between [-1, 1]
|
| 29 |
+
x = torch.tensor(x)
|
| 30 |
+
x = x.unsqueeze(dim=0)
|
| 31 |
+
x = torch.einsum('nhwc->nchw', x)
|
| 32 |
+
x_input = x.float().to("cuda")
|
| 33 |
+
|
| 34 |
+
# inference
|
| 35 |
+
with torch.no_grad():
|
| 36 |
+
# Map input images to latent space + normalize latents:
|
| 37 |
+
latent = vae.encode(x_input).latent_dist.sample().mul_(0.18215)
|
| 38 |
+
# reconstruct:
|
| 39 |
+
output = vae.decode(latent / 0.18215).sample # output value is between [-1, 1]
|
| 40 |
+
|
| 41 |
+
# postprocess
|
| 42 |
+
output = F.interpolate(output, size=[size_org[1], size_org[0]], mode='bilinear').permute(0, 2, 3, 1)[0]
|
| 43 |
+
sample = torch.clamp(127.5 * output + 128.0, 0, 255).to("cpu", dtype=torch.uint8).numpy()
|
| 44 |
+
|
| 45 |
+
# save
|
| 46 |
+
Image.fromarray(sample).save(out_path)
|
| 47 |
+
print("Reconstructed image is saved to {}".format(out_path))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
parser = argparse.ArgumentParser()
|
| 52 |
+
parser.add_argument("--image-path", type=str, default="assets/example.jpg")
|
| 53 |
+
parser.add_argument("--vae", type=str, choices=["sdxl-vae", "sd-vae-ft-mse"], default="sd-vae-ft-mse")
|
| 54 |
+
parser.add_argument("--image-size", type=int, choices=[256, 512, 1024], default=512)
|
| 55 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 56 |
+
args = parser.parse_args()
|
| 57 |
+
main(args)
|
sjdtree/llamagen/tokenizer/validation/val_ddp.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 3 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 4 |
+
import torch.distributed as dist
|
| 5 |
+
from torch.utils.data import Dataset, DataLoader
|
| 6 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 7 |
+
from torchvision.datasets import ImageFolder
|
| 8 |
+
from torchvision import transforms
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
import os
|
| 11 |
+
from PIL import Image
|
| 12 |
+
import numpy as np
|
| 13 |
+
import argparse
|
| 14 |
+
import random
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class SingleFolderDataset(Dataset):
|
| 18 |
+
def __init__(self, directory, transform=None):
|
| 19 |
+
super().__init__()
|
| 20 |
+
self.directory = directory
|
| 21 |
+
self.transform = transform
|
| 22 |
+
self.image_paths = [os.path.join(directory, file_name) for file_name in os.listdir(directory)
|
| 23 |
+
if os.path.isfile(os.path.join(directory, file_name))]
|
| 24 |
+
|
| 25 |
+
def __len__(self):
|
| 26 |
+
return len(self.image_paths)
|
| 27 |
+
|
| 28 |
+
def __getitem__(self, idx):
|
| 29 |
+
image_path = self.image_paths[idx]
|
| 30 |
+
image = Image.open(image_path).convert('RGB')
|
| 31 |
+
if self.transform:
|
| 32 |
+
image = self.transform(image)
|
| 33 |
+
return image, torch.tensor(0)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def create_npz_from_sample_folder(sample_dir, num=50_000):
|
| 37 |
+
"""
|
| 38 |
+
Builds a single .npz file from a folder of .png samples.
|
| 39 |
+
"""
|
| 40 |
+
samples = []
|
| 41 |
+
for i in tqdm(range(num), desc="Building .npz file from samples"):
|
| 42 |
+
sample_pil = Image.open(f"{sample_dir}/{i:06d}.png")
|
| 43 |
+
sample_np = np.asarray(sample_pil).astype(np.uint8)
|
| 44 |
+
samples.append(sample_np)
|
| 45 |
+
|
| 46 |
+
random.shuffle(samples) # This is very important for IS(Inception Score) !!!
|
| 47 |
+
samples = np.stack(samples)
|
| 48 |
+
assert samples.shape == (num, samples.shape[1], samples.shape[2], 3)
|
| 49 |
+
npz_path = f"{sample_dir}.npz"
|
| 50 |
+
np.savez(npz_path, arr_0=samples)
|
| 51 |
+
print(f"Saved .npz file to {npz_path} [shape={samples.shape}].")
|
| 52 |
+
return npz_path
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def center_crop_arr(pil_image, image_size):
|
| 56 |
+
"""
|
| 57 |
+
Center cropping implementation from ADM.
|
| 58 |
+
https://github.com/openai/guided-diffusion/blob/8fb3ad9197f16bbc40620447b2742e13458d2831/guided_diffusion/image_datasets.py#L126
|
| 59 |
+
"""
|
| 60 |
+
while min(*pil_image.size) >= 2 * image_size:
|
| 61 |
+
pil_image = pil_image.resize(
|
| 62 |
+
tuple(x // 2 for x in pil_image.size), resample=Image.BOX
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
scale = image_size / min(*pil_image.size)
|
| 66 |
+
pil_image = pil_image.resize(
|
| 67 |
+
tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
arr = np.array(pil_image)
|
| 71 |
+
crop_y = (arr.shape[0] - image_size) // 2
|
| 72 |
+
crop_x = (arr.shape[1] - image_size) // 2
|
| 73 |
+
return Image.fromarray(arr[crop_y: crop_y + image_size, crop_x: crop_x + image_size])
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def main(args):
|
| 77 |
+
# Setup PyTorch:
|
| 78 |
+
assert torch.cuda.is_available(), "Sampling with DDP requires at least one GPU. sample.py supports CPU-only usage"
|
| 79 |
+
torch.set_grad_enabled(False)
|
| 80 |
+
|
| 81 |
+
# Setup env
|
| 82 |
+
dist.init_process_group("nccl")
|
| 83 |
+
rank = dist.get_rank()
|
| 84 |
+
device = rank % torch.cuda.device_count()
|
| 85 |
+
seed = args.global_seed * dist.get_world_size() + rank
|
| 86 |
+
torch.manual_seed(seed)
|
| 87 |
+
torch.cuda.set_device(device)
|
| 88 |
+
print(f"Starting rank={rank}, seed={seed}, world_size={dist.get_world_size()}.")
|
| 89 |
+
|
| 90 |
+
# Create folder to save samples:
|
| 91 |
+
folder_name = f"val_{args.dataset}"
|
| 92 |
+
sample_folder_dir = f"{args.sample_dir}/{folder_name}"
|
| 93 |
+
if rank == 0:
|
| 94 |
+
os.makedirs(sample_folder_dir, exist_ok=True)
|
| 95 |
+
print(f"Saving .png samples at {sample_folder_dir}")
|
| 96 |
+
dist.barrier()
|
| 97 |
+
|
| 98 |
+
# Setup data:
|
| 99 |
+
transform = transforms.Compose([
|
| 100 |
+
transforms.Lambda(lambda pil_image: center_crop_arr(pil_image, args.image_size)),
|
| 101 |
+
transforms.ToTensor(),
|
| 102 |
+
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True)
|
| 103 |
+
])
|
| 104 |
+
|
| 105 |
+
if args.dataset == 'imagenet':
|
| 106 |
+
dataset = ImageFolder(args.data_path, transform=transform)
|
| 107 |
+
num_fid_samples = 50000
|
| 108 |
+
elif args.dataset == 'coco':
|
| 109 |
+
dataset = SingleFolderDataset(args.data_path, transform=transform)
|
| 110 |
+
num_fid_samples = 5000
|
| 111 |
+
else:
|
| 112 |
+
raise Exception("please check dataset")
|
| 113 |
+
|
| 114 |
+
sampler = DistributedSampler(
|
| 115 |
+
dataset,
|
| 116 |
+
num_replicas=dist.get_world_size(),
|
| 117 |
+
rank=rank,
|
| 118 |
+
shuffle=False,
|
| 119 |
+
seed=args.global_seed
|
| 120 |
+
)
|
| 121 |
+
loader = DataLoader(
|
| 122 |
+
dataset,
|
| 123 |
+
batch_size=args.per_proc_batch_size,
|
| 124 |
+
shuffle=False,
|
| 125 |
+
sampler=sampler,
|
| 126 |
+
num_workers=args.num_workers,
|
| 127 |
+
pin_memory=True,
|
| 128 |
+
drop_last=False
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# Figure out how many samples we need to generate on each GPU and how many iterations we need to run:
|
| 132 |
+
n = args.per_proc_batch_size
|
| 133 |
+
global_batch_size = n * dist.get_world_size()
|
| 134 |
+
|
| 135 |
+
loader = tqdm(loader) if rank == 0 else loader
|
| 136 |
+
total = 0
|
| 137 |
+
for x, _ in loader:
|
| 138 |
+
samples = torch.clamp(127.5 * x + 128.0, 0, 255).permute(0, 2, 3, 1).to("cpu", dtype=torch.uint8).numpy()
|
| 139 |
+
# Save samples to disk as individual .png files
|
| 140 |
+
for i, sample in enumerate(samples):
|
| 141 |
+
index = i * dist.get_world_size() + rank + total
|
| 142 |
+
Image.fromarray(sample).save(f"{sample_folder_dir}/{index:06d}.png")
|
| 143 |
+
|
| 144 |
+
total += global_batch_size
|
| 145 |
+
|
| 146 |
+
# Make sure all processes have finished saving their samples before attempting to convert to .npz
|
| 147 |
+
dist.barrier()
|
| 148 |
+
if rank == 0:
|
| 149 |
+
create_npz_from_sample_folder(sample_folder_dir, num_fid_samples)
|
| 150 |
+
print("Done.")
|
| 151 |
+
dist.barrier()
|
| 152 |
+
dist.destroy_process_group()
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
if __name__ == "__main__":
|
| 156 |
+
parser = argparse.ArgumentParser()
|
| 157 |
+
parser.add_argument("--data-path", type=str, required=True)
|
| 158 |
+
parser.add_argument("--dataset", type=str, choices=['imagenet', 'coco'], default='imagenet')
|
| 159 |
+
parser.add_argument("--image-size", type=int, choices=[256, 512], default=256)
|
| 160 |
+
parser.add_argument("--sample-dir", type=str, default="reconstructions")
|
| 161 |
+
parser.add_argument("--per-proc-batch-size", type=int, default=32)
|
| 162 |
+
parser.add_argument("--global-seed", type=int, default=0)
|
| 163 |
+
parser.add_argument("--num-workers", type=int, default=4)
|
| 164 |
+
args = parser.parse_args()
|
| 165 |
+
main(args)
|
sjdtree/llamagen/tokenizer/vqgan/README.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Pretrained VQVAE Models
|
| 2 |
+
|
| 3 |
+
### install
|
| 4 |
+
```
|
| 5 |
+
pip install omegaconf
|
| 6 |
+
pip install einops
|
| 7 |
+
```
|
| 8 |
+
* download all needed models from https://github.com/CompVis/taming-transformers and put in pretrained_models/
|
| 9 |
+
* pip install pytorch_lightning
|
| 10 |
+
* python3 tools/convert_pytorch_lightning_to_torch.py
|
| 11 |
+
* pip uninstall pytorch_lightning
|
| 12 |
+
|
| 13 |
+
### demo
|
| 14 |
+
```
|
| 15 |
+
cd ${THIS_REPO_ROOT}
|
| 16 |
+
python3 tokenizer/vqgan/taming_vqgan_demo.py
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
### acknowledge
|
| 20 |
+
Codes in this folder are modified from from https://github.com/CompVis/taming-transformers
|
| 21 |
+
|
sjdtree/llamagen/tokenizer/vqgan/configs/vqgan_imagenet_f16_1024.yaml
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
model:
|
| 2 |
+
base_learning_rate: 4.5e-06
|
| 3 |
+
target: taming.models.vqgan.VQModel
|
| 4 |
+
params:
|
| 5 |
+
embed_dim: 256
|
| 6 |
+
n_embed: 1024
|
| 7 |
+
ddconfig:
|
| 8 |
+
double_z: false
|
| 9 |
+
z_channels: 256
|
| 10 |
+
resolution: 256
|
| 11 |
+
in_channels: 3
|
| 12 |
+
out_ch: 3
|
| 13 |
+
ch: 128
|
| 14 |
+
ch_mult:
|
| 15 |
+
- 1
|
| 16 |
+
- 1
|
| 17 |
+
- 2
|
| 18 |
+
- 2
|
| 19 |
+
- 4
|
| 20 |
+
num_res_blocks: 2
|
| 21 |
+
attn_resolutions:
|
| 22 |
+
- 16
|
| 23 |
+
dropout: 0.0
|
| 24 |
+
lossconfig:
|
| 25 |
+
target: taming.modules.losses.vqperceptual.VQLPIPSWithDiscriminator
|
| 26 |
+
params:
|
| 27 |
+
disc_conditional: false
|
| 28 |
+
disc_in_channels: 3
|
| 29 |
+
disc_start: 0
|
| 30 |
+
disc_weight: 0.8
|
| 31 |
+
codebook_weight: 1.0
|
| 32 |
+
|