Upload folder using huggingface_hub
Browse files- DensePose/__init__.py +158 -0
- DensePose/__pycache__/__init__.cpython-311.pyc +0 -0
- SCHP/__init__.py +179 -0
- SCHP/__pycache__/__init__.cpython-311.pyc +0 -0
- SCHP/networks/AugmentCE2P.py +362 -0
- SCHP/networks/__init__.py +13 -0
- SCHP/networks/__pycache__/AugmentCE2P.cpython-311.pyc +0 -0
- SCHP/networks/__pycache__/AugmentCE2P.cpython-39.pyc +0 -0
- SCHP/networks/__pycache__/__init__.cpython-311.pyc +0 -0
- SCHP/networks/__pycache__/__init__.cpython-39.pyc +0 -0
- SCHP/utils/__pycache__/transforms.cpython-311.pyc +0 -0
- SCHP/utils/__pycache__/transforms.cpython-39.pyc +0 -0
- SCHP/utils/transforms.py +167 -0
- __pycache__/attn_processor.cpython-311.pyc +0 -0
- __pycache__/cloth_masker.cpython-311.pyc +0 -0
- __pycache__/pipeline.cpython-311.pyc +0 -0
- __pycache__/utils.cpython-311.pyc +0 -0
- attn_processor.py +113 -0
- cloth_masker.py +273 -0
- flux/pipeline_flux_tryon.py +499 -0
- flux/transformer_flux.py +672 -0
- pipeline.py +332 -0
- utils.py +84 -0
DensePose/__init__.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import glob
|
| 3 |
+
import os
|
| 4 |
+
from random import randint
|
| 5 |
+
import shutil
|
| 6 |
+
import time
|
| 7 |
+
|
| 8 |
+
import cv2
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
from PIL import Image
|
| 12 |
+
from densepose import add_densepose_config
|
| 13 |
+
from densepose.vis.base import CompoundVisualizer
|
| 14 |
+
from densepose.vis.densepose_results import DensePoseResultsFineSegmentationVisualizer
|
| 15 |
+
from densepose.vis.extractor import create_extractor, CompoundExtractor
|
| 16 |
+
from detectron2.config import get_cfg
|
| 17 |
+
from detectron2.data.detection_utils import read_image
|
| 18 |
+
from detectron2.engine.defaults import DefaultPredictor
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class DensePose:
|
| 22 |
+
"""
|
| 23 |
+
DensePose used in this project is from Detectron2 (https://github.com/facebookresearch/detectron2).
|
| 24 |
+
These codes are modified from https://github.com/facebookresearch/detectron2/tree/main/projects/DensePose.
|
| 25 |
+
The checkpoint is downloaded from https://github.com/facebookresearch/detectron2/blob/main/projects/DensePose/doc/DENSEPOSE_IUV.md#ModelZoo.
|
| 26 |
+
|
| 27 |
+
We use the model R_50_FPN_s1x with id 165712039, but other models should also work.
|
| 28 |
+
The config file is downloaded from https://github.com/facebookresearch/detectron2/tree/main/projects/DensePose/configs.
|
| 29 |
+
Noted that the config file should match the model checkpoint and Base-DensePose-RCNN-FPN.yaml is also needed.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(self, model_path="./checkpoints/densepose_", device="cuda"):
|
| 33 |
+
self.device = device
|
| 34 |
+
self.config_path = os.path.join(model_path, 'densepose_rcnn_R_50_FPN_s1x.yaml')
|
| 35 |
+
self.model_path = os.path.join(model_path, 'model_final_162be9.pkl')
|
| 36 |
+
self.visualizations = ["dp_segm"]
|
| 37 |
+
self.VISUALIZERS = {"dp_segm": DensePoseResultsFineSegmentationVisualizer}
|
| 38 |
+
self.min_score = 0.8
|
| 39 |
+
|
| 40 |
+
self.cfg = self.setup_config()
|
| 41 |
+
self.predictor = DefaultPredictor(self.cfg)
|
| 42 |
+
self.predictor.model.to(self.device)
|
| 43 |
+
|
| 44 |
+
def setup_config(self):
|
| 45 |
+
opts = ["MODEL.ROI_HEADS.SCORE_THRESH_TEST", str(self.min_score)]
|
| 46 |
+
cfg = get_cfg()
|
| 47 |
+
add_densepose_config(cfg)
|
| 48 |
+
cfg.merge_from_file(self.config_path)
|
| 49 |
+
cfg.merge_from_list(opts)
|
| 50 |
+
cfg.MODEL.WEIGHTS = self.model_path
|
| 51 |
+
cfg.freeze()
|
| 52 |
+
return cfg
|
| 53 |
+
|
| 54 |
+
@staticmethod
|
| 55 |
+
def _get_input_file_list(input_spec: str):
|
| 56 |
+
if os.path.isdir(input_spec):
|
| 57 |
+
file_list = [os.path.join(input_spec, fname) for fname in os.listdir(input_spec)
|
| 58 |
+
if os.path.isfile(os.path.join(input_spec, fname))]
|
| 59 |
+
elif os.path.isfile(input_spec):
|
| 60 |
+
file_list = [input_spec]
|
| 61 |
+
else:
|
| 62 |
+
file_list = glob.glob(input_spec)
|
| 63 |
+
return file_list
|
| 64 |
+
|
| 65 |
+
def create_context(self, cfg, output_path):
|
| 66 |
+
vis_specs = self.visualizations
|
| 67 |
+
visualizers = []
|
| 68 |
+
extractors = []
|
| 69 |
+
for vis_spec in vis_specs:
|
| 70 |
+
texture_atlas = texture_atlases_dict = None
|
| 71 |
+
vis = self.VISUALIZERS[vis_spec](
|
| 72 |
+
cfg=cfg,
|
| 73 |
+
texture_atlas=texture_atlas,
|
| 74 |
+
texture_atlases_dict=texture_atlases_dict,
|
| 75 |
+
alpha=1.0
|
| 76 |
+
)
|
| 77 |
+
visualizers.append(vis)
|
| 78 |
+
extractor = create_extractor(vis)
|
| 79 |
+
extractors.append(extractor)
|
| 80 |
+
visualizer = CompoundVisualizer(visualizers)
|
| 81 |
+
extractor = CompoundExtractor(extractors)
|
| 82 |
+
context = {
|
| 83 |
+
"extractor": extractor,
|
| 84 |
+
"visualizer": visualizer,
|
| 85 |
+
"out_fname": output_path,
|
| 86 |
+
"entry_idx": 0,
|
| 87 |
+
}
|
| 88 |
+
return context
|
| 89 |
+
|
| 90 |
+
def execute_on_outputs(self, context, entry, outputs):
|
| 91 |
+
extractor = context["extractor"]
|
| 92 |
+
|
| 93 |
+
data = extractor(outputs)
|
| 94 |
+
|
| 95 |
+
H, W, _ = entry["image"].shape
|
| 96 |
+
result = np.zeros((H, W), dtype=np.uint8)
|
| 97 |
+
|
| 98 |
+
data, box = data[0]
|
| 99 |
+
x, y, w, h = [int(_) for _ in box[0].cpu().numpy()]
|
| 100 |
+
i_array = data[0].labels[None].cpu().numpy()[0]
|
| 101 |
+
result[y:y + h, x:x + w] = i_array
|
| 102 |
+
result = Image.fromarray(result)
|
| 103 |
+
result.save(context["out_fname"])
|
| 104 |
+
|
| 105 |
+
def __call__(self, image_or_path, resize=512) -> Image.Image:
|
| 106 |
+
"""
|
| 107 |
+
:param image_or_path: Path of the input image.
|
| 108 |
+
:param resize: Resize the input image if its max size is larger than this value.
|
| 109 |
+
:return: Dense pose image.
|
| 110 |
+
"""
|
| 111 |
+
# random tmp path with timestamp
|
| 112 |
+
tmp_path = f"./densepose_/tmp/"
|
| 113 |
+
if not os.path.exists(tmp_path):
|
| 114 |
+
os.makedirs(tmp_path)
|
| 115 |
+
|
| 116 |
+
image_path = os.path.join(tmp_path, f"{int(time.time())}-{self.device}-{randint(0, 100000)}.png")
|
| 117 |
+
if isinstance(image_or_path, str):
|
| 118 |
+
assert image_or_path.split(".")[-1] in ["jpg", "png"], "Only support jpg and png images."
|
| 119 |
+
shutil.copy(image_or_path, image_path)
|
| 120 |
+
elif isinstance(image_or_path, Image.Image):
|
| 121 |
+
image_or_path.save(image_path)
|
| 122 |
+
else:
|
| 123 |
+
shutil.rmtree(tmp_path)
|
| 124 |
+
raise TypeError("image_path must be str or PIL.Image.Image")
|
| 125 |
+
|
| 126 |
+
output_path = image_path.replace(".png", "_dense.png").replace(".jpg", "_dense.png")
|
| 127 |
+
w, h = Image.open(image_path).size
|
| 128 |
+
|
| 129 |
+
file_list = self._get_input_file_list(image_path)
|
| 130 |
+
assert len(file_list), "No input images found!"
|
| 131 |
+
context = self.create_context(self.cfg, output_path)
|
| 132 |
+
for file_name in file_list:
|
| 133 |
+
img = read_image(file_name, format="BGR") # predictor expects BGR image.
|
| 134 |
+
# resize
|
| 135 |
+
if (_ := max(img.shape)) > resize:
|
| 136 |
+
scale = resize / _
|
| 137 |
+
img = cv2.resize(img, (int(img.shape[1] * scale), int(img.shape[0] * scale)))
|
| 138 |
+
|
| 139 |
+
with torch.no_grad():
|
| 140 |
+
outputs = self.predictor(img)["instances"]
|
| 141 |
+
try:
|
| 142 |
+
self.execute_on_outputs(context, {"file_name": file_name, "image": img}, outputs)
|
| 143 |
+
except Exception as e:
|
| 144 |
+
null_gray = Image.new('L', (1, 1))
|
| 145 |
+
null_gray.save(output_path)
|
| 146 |
+
|
| 147 |
+
dense_gray = Image.open(output_path).convert("L")
|
| 148 |
+
dense_gray = dense_gray.resize((w, h), Image.NEAREST)
|
| 149 |
+
# remove image_path and output_path
|
| 150 |
+
os.remove(image_path)
|
| 151 |
+
os.remove(output_path)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
return dense_gray
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
if __name__ == '__main__':
|
| 158 |
+
pass
|
DensePose/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (10.6 kB). View file
|
|
|
SCHP/__init__.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from model.SCHP import networks
|
| 2 |
+
from model.SCHP.utils.transforms import get_affine_transform, transform_logits
|
| 3 |
+
|
| 4 |
+
from collections import OrderedDict
|
| 5 |
+
import torch
|
| 6 |
+
import numpy as np
|
| 7 |
+
import cv2
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from torchvision import transforms
|
| 10 |
+
|
| 11 |
+
def get_palette(num_cls):
|
| 12 |
+
""" Returns the color map for visualizing the segmentation mask.
|
| 13 |
+
Args:
|
| 14 |
+
num_cls: Number of classes
|
| 15 |
+
Returns:
|
| 16 |
+
The color map
|
| 17 |
+
"""
|
| 18 |
+
n = num_cls
|
| 19 |
+
palette = [0] * (n * 3)
|
| 20 |
+
for j in range(0, n):
|
| 21 |
+
lab = j
|
| 22 |
+
palette[j * 3 + 0] = 0
|
| 23 |
+
palette[j * 3 + 1] = 0
|
| 24 |
+
palette[j * 3 + 2] = 0
|
| 25 |
+
i = 0
|
| 26 |
+
while lab:
|
| 27 |
+
palette[j * 3 + 0] |= (((lab >> 0) & 1) << (7 - i))
|
| 28 |
+
palette[j * 3 + 1] |= (((lab >> 1) & 1) << (7 - i))
|
| 29 |
+
palette[j * 3 + 2] |= (((lab >> 2) & 1) << (7 - i))
|
| 30 |
+
i += 1
|
| 31 |
+
lab >>= 3
|
| 32 |
+
return palette
|
| 33 |
+
|
| 34 |
+
dataset_settings = {
|
| 35 |
+
'lip': {
|
| 36 |
+
'input_size': [473, 473],
|
| 37 |
+
'num_classes': 20,
|
| 38 |
+
'label': ['Background', 'Hat', 'Hair', 'Glove', 'Sunglasses', 'Upper-clothes', 'Dress', 'Coat',
|
| 39 |
+
'Socks', 'Pants', 'Jumpsuits', 'Scarf', 'Skirt', 'Face', 'Left-arm', 'Right-arm',
|
| 40 |
+
'Left-leg', 'Right-leg', 'Left-shoe', 'Right-shoe']
|
| 41 |
+
},
|
| 42 |
+
'atr': {
|
| 43 |
+
'input_size': [512, 512],
|
| 44 |
+
'num_classes': 18,
|
| 45 |
+
'label': ['Background', 'Hat', 'Hair', 'Sunglasses', 'Upper-clothes', 'Skirt', 'Pants', 'Dress', 'Belt',
|
| 46 |
+
'Left-shoe', 'Right-shoe', 'Face', 'Left-leg', 'Right-leg', 'Left-arm', 'Right-arm', 'Bag', 'Scarf']
|
| 47 |
+
},
|
| 48 |
+
'pascal': {
|
| 49 |
+
'input_size': [512, 512],
|
| 50 |
+
'num_classes': 7,
|
| 51 |
+
'label': ['Background', 'Head', 'Torso', 'Upper Arms', 'Lower Arms', 'Upper Legs', 'Lower Legs'],
|
| 52 |
+
}
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
class SCHP:
|
| 56 |
+
def __init__(self, ckpt_path, device):
|
| 57 |
+
dataset_type = None
|
| 58 |
+
if 'lip' in ckpt_path:
|
| 59 |
+
dataset_type = 'lip'
|
| 60 |
+
elif 'atr' in ckpt_path:
|
| 61 |
+
dataset_type = 'atr'
|
| 62 |
+
elif 'pascal' in ckpt_path:
|
| 63 |
+
dataset_type = 'pascal'
|
| 64 |
+
assert dataset_type is not None, 'Dataset type not found in checkpoint path'
|
| 65 |
+
self.device = device
|
| 66 |
+
self.num_classes = dataset_settings[dataset_type]['num_classes']
|
| 67 |
+
self.input_size = dataset_settings[dataset_type]['input_size']
|
| 68 |
+
self.aspect_ratio = self.input_size[1] * 1.0 / self.input_size[0]
|
| 69 |
+
self.palette = get_palette(self.num_classes)
|
| 70 |
+
|
| 71 |
+
self.label = dataset_settings[dataset_type]['label']
|
| 72 |
+
self.model = networks.init_model('resnet101', num_classes=self.num_classes, pretrained=None).to(device)
|
| 73 |
+
self.load_ckpt(ckpt_path)
|
| 74 |
+
self.model.eval()
|
| 75 |
+
|
| 76 |
+
self.transform = transforms.Compose([
|
| 77 |
+
transforms.ToTensor(),
|
| 78 |
+
transforms.Normalize(mean=[0.406, 0.456, 0.485], std=[0.225, 0.224, 0.229])
|
| 79 |
+
])
|
| 80 |
+
self.upsample = torch.nn.Upsample(size=self.input_size, mode='bilinear', align_corners=True)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def load_ckpt(self, ckpt_path):
|
| 84 |
+
rename_map = {
|
| 85 |
+
"decoder.conv3.2.weight": "decoder.conv3.3.weight",
|
| 86 |
+
"decoder.conv3.3.weight": "decoder.conv3.4.weight",
|
| 87 |
+
"decoder.conv3.3.bias": "decoder.conv3.4.bias",
|
| 88 |
+
"decoder.conv3.3.running_mean": "decoder.conv3.4.running_mean",
|
| 89 |
+
"decoder.conv3.3.running_var": "decoder.conv3.4.running_var",
|
| 90 |
+
"fushion.3.weight": "fushion.4.weight",
|
| 91 |
+
"fushion.3.bias": "fushion.4.bias",
|
| 92 |
+
}
|
| 93 |
+
state_dict = torch.load(ckpt_path, map_location='cpu')['state_dict']
|
| 94 |
+
new_state_dict = OrderedDict()
|
| 95 |
+
for k, v in state_dict.items():
|
| 96 |
+
name = k[7:] # remove `module.`
|
| 97 |
+
new_state_dict[name] = v
|
| 98 |
+
new_state_dict_ = OrderedDict()
|
| 99 |
+
for k, v in list(new_state_dict.items()):
|
| 100 |
+
if k in rename_map:
|
| 101 |
+
new_state_dict_[rename_map[k]] = v
|
| 102 |
+
else:
|
| 103 |
+
new_state_dict_[k] = v
|
| 104 |
+
self.model.load_state_dict(new_state_dict_, strict=False)
|
| 105 |
+
|
| 106 |
+
def _box2cs(self, box):
|
| 107 |
+
x, y, w, h = box[:4]
|
| 108 |
+
return self._xywh2cs(x, y, w, h)
|
| 109 |
+
|
| 110 |
+
def _xywh2cs(self, x, y, w, h):
|
| 111 |
+
center = np.zeros((2), dtype=np.float32)
|
| 112 |
+
center[0] = x + w * 0.5
|
| 113 |
+
center[1] = y + h * 0.5
|
| 114 |
+
if w > self.aspect_ratio * h:
|
| 115 |
+
h = w * 1.0 / self.aspect_ratio
|
| 116 |
+
elif w < self.aspect_ratio * h:
|
| 117 |
+
w = h * self.aspect_ratio
|
| 118 |
+
scale = np.array([w, h], dtype=np.float32)
|
| 119 |
+
return center, scale
|
| 120 |
+
|
| 121 |
+
def preprocess(self, image):
|
| 122 |
+
if isinstance(image, str):
|
| 123 |
+
img = cv2.imread(image, cv2.IMREAD_COLOR)
|
| 124 |
+
elif isinstance(image, Image.Image):
|
| 125 |
+
# to cv2 format
|
| 126 |
+
img = np.array(image)
|
| 127 |
+
|
| 128 |
+
h, w, _ = img.shape
|
| 129 |
+
# Get person center and scale
|
| 130 |
+
person_center, s = self._box2cs([0, 0, w - 1, h - 1])
|
| 131 |
+
r = 0
|
| 132 |
+
trans = get_affine_transform(person_center, s, r, self.input_size)
|
| 133 |
+
input = cv2.warpAffine(
|
| 134 |
+
img,
|
| 135 |
+
trans,
|
| 136 |
+
(int(self.input_size[1]), int(self.input_size[0])),
|
| 137 |
+
flags=cv2.INTER_LINEAR,
|
| 138 |
+
borderMode=cv2.BORDER_CONSTANT,
|
| 139 |
+
borderValue=(0, 0, 0))
|
| 140 |
+
|
| 141 |
+
input = self.transform(input).to(self.device).unsqueeze(0)
|
| 142 |
+
meta = {
|
| 143 |
+
'center': person_center,
|
| 144 |
+
'height': h,
|
| 145 |
+
'width': w,
|
| 146 |
+
'scale': s,
|
| 147 |
+
'rotation': r
|
| 148 |
+
}
|
| 149 |
+
return input, meta
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def __call__(self, image_or_path):
|
| 153 |
+
if isinstance(image_or_path, list):
|
| 154 |
+
image_list = []
|
| 155 |
+
meta_list = []
|
| 156 |
+
for image in image_or_path:
|
| 157 |
+
image, meta = self.preprocess(image)
|
| 158 |
+
image_list.append(image)
|
| 159 |
+
meta_list.append(meta)
|
| 160 |
+
image = torch.cat(image_list, dim=0)
|
| 161 |
+
else:
|
| 162 |
+
image, meta = self.preprocess(image_or_path)
|
| 163 |
+
meta_list = [meta]
|
| 164 |
+
|
| 165 |
+
output = self.model(image)
|
| 166 |
+
# upsample_outputs = self.upsample(output[0][-1])
|
| 167 |
+
upsample_outputs = self.upsample(output)
|
| 168 |
+
upsample_outputs = upsample_outputs.permute(0, 2, 3, 1) # BCHW -> BHWC
|
| 169 |
+
|
| 170 |
+
output_img_list = []
|
| 171 |
+
for upsample_output, meta in zip(upsample_outputs, meta_list):
|
| 172 |
+
c, s, w, h = meta['center'], meta['scale'], meta['width'], meta['height']
|
| 173 |
+
logits_result = transform_logits(upsample_output.data.cpu().numpy(), c, s, w, h, input_size=self.input_size)
|
| 174 |
+
parsing_result = np.argmax(logits_result, axis=2)
|
| 175 |
+
output_img = Image.fromarray(np.asarray(parsing_result, dtype=np.uint8))
|
| 176 |
+
output_img.putpalette(self.palette)
|
| 177 |
+
output_img_list.append(output_img)
|
| 178 |
+
|
| 179 |
+
return output_img_list[0] if len(output_img_list) == 1 else output_img_list
|
SCHP/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (9.79 kB). View file
|
|
|
SCHP/networks/AugmentCE2P.py
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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/usr/bin/env python
|
| 2 |
+
# -*- encoding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
@Author : Peike Li
|
| 6 |
+
@Contact : peike.li@yahoo.com
|
| 7 |
+
@File : AugmentCE2P.py
|
| 8 |
+
@Time : 8/4/19 3:35 PM
|
| 9 |
+
@Desc :
|
| 10 |
+
@License : This source code is licensed under the license found in the
|
| 11 |
+
LICENSE file in the root directory of this source tree.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
import torch.nn as nn
|
| 16 |
+
from torch.nn import functional as F
|
| 17 |
+
|
| 18 |
+
from torch.nn import BatchNorm2d, LeakyReLU
|
| 19 |
+
|
| 20 |
+
affine_par = True
|
| 21 |
+
pretrained_settings = {
|
| 22 |
+
'resnet101': {
|
| 23 |
+
'imagenet': {
|
| 24 |
+
'input_space': 'BGR',
|
| 25 |
+
'input_size': [3, 224, 224],
|
| 26 |
+
'input_range': [0, 1],
|
| 27 |
+
'mean': [0.406, 0.456, 0.485],
|
| 28 |
+
'std': [0.225, 0.224, 0.229],
|
| 29 |
+
'num_classes': 1000
|
| 30 |
+
}
|
| 31 |
+
},
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def conv3x3(in_planes, out_planes, stride=1):
|
| 36 |
+
"3x3 convolution with padding"
|
| 37 |
+
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
|
| 38 |
+
padding=1, bias=False)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Bottleneck(nn.Module):
|
| 42 |
+
expansion = 4
|
| 43 |
+
|
| 44 |
+
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, fist_dilation=1, multi_grid=1):
|
| 45 |
+
super(Bottleneck, self).__init__()
|
| 46 |
+
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
|
| 47 |
+
self.bn1 = BatchNorm2d(planes)
|
| 48 |
+
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
|
| 49 |
+
padding=dilation * multi_grid, dilation=dilation * multi_grid, bias=False)
|
| 50 |
+
self.bn2 = BatchNorm2d(planes)
|
| 51 |
+
self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
|
| 52 |
+
self.bn3 = BatchNorm2d(planes * 4)
|
| 53 |
+
self.relu = nn.ReLU(inplace=False)
|
| 54 |
+
self.relu_inplace = nn.ReLU(inplace=True)
|
| 55 |
+
self.downsample = downsample
|
| 56 |
+
self.dilation = dilation
|
| 57 |
+
self.stride = stride
|
| 58 |
+
|
| 59 |
+
def forward(self, x):
|
| 60 |
+
residual = x
|
| 61 |
+
|
| 62 |
+
out = self.conv1(x)
|
| 63 |
+
out = self.bn1(out)
|
| 64 |
+
out = self.relu(out)
|
| 65 |
+
|
| 66 |
+
out = self.conv2(out)
|
| 67 |
+
out = self.bn2(out)
|
| 68 |
+
out = self.relu(out)
|
| 69 |
+
|
| 70 |
+
out = self.conv3(out)
|
| 71 |
+
out = self.bn3(out)
|
| 72 |
+
|
| 73 |
+
if self.downsample is not None:
|
| 74 |
+
residual = self.downsample(x)
|
| 75 |
+
|
| 76 |
+
out = out + residual
|
| 77 |
+
out = self.relu_inplace(out)
|
| 78 |
+
|
| 79 |
+
return out
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class PSPModule(nn.Module):
|
| 83 |
+
"""
|
| 84 |
+
Reference:
|
| 85 |
+
Zhao, Hengshuang, et al. *"Pyramid scene parsing network."*
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
def __init__(self, features, out_features=512, sizes=(1, 2, 3, 6)):
|
| 89 |
+
super(PSPModule, self).__init__()
|
| 90 |
+
|
| 91 |
+
self.stages = []
|
| 92 |
+
self.stages = nn.ModuleList([self._make_stage(features, out_features, size) for size in sizes])
|
| 93 |
+
self.bottleneck = nn.Sequential(
|
| 94 |
+
nn.Conv2d(features + len(sizes) * out_features, out_features, kernel_size=3, padding=1, dilation=1,
|
| 95 |
+
bias=False),
|
| 96 |
+
BatchNorm2d(out_features),
|
| 97 |
+
LeakyReLU(),
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
def _make_stage(self, features, out_features, size):
|
| 101 |
+
prior = nn.AdaptiveAvgPool2d(output_size=(size, size))
|
| 102 |
+
conv = nn.Conv2d(features, out_features, kernel_size=1, bias=False)
|
| 103 |
+
return nn.Sequential(
|
| 104 |
+
prior,
|
| 105 |
+
conv,
|
| 106 |
+
# bn
|
| 107 |
+
BatchNorm2d(out_features),
|
| 108 |
+
LeakyReLU(),
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
def forward(self, feats):
|
| 112 |
+
h, w = feats.size(2), feats.size(3)
|
| 113 |
+
priors = [F.interpolate(input=stage(feats), size=(h, w), mode='bilinear', align_corners=True) for stage in
|
| 114 |
+
self.stages] + [feats]
|
| 115 |
+
bottle = self.bottleneck(torch.cat(priors, 1))
|
| 116 |
+
return bottle
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class ASPPModule(nn.Module):
|
| 120 |
+
"""
|
| 121 |
+
Reference:
|
| 122 |
+
Chen, Liang-Chieh, et al. *"Rethinking Atrous Convolution for Semantic Image Segmentation."*
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
def __init__(self, features, inner_features=256, out_features=512, dilations=(12, 24, 36)):
|
| 126 |
+
super(ASPPModule, self).__init__()
|
| 127 |
+
|
| 128 |
+
self.conv1 = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
|
| 129 |
+
nn.Conv2d(features, inner_features, kernel_size=1, padding=0, dilation=1,
|
| 130 |
+
bias=False),
|
| 131 |
+
# InPlaceABNSync(inner_features)
|
| 132 |
+
BatchNorm2d(inner_features),
|
| 133 |
+
LeakyReLU(),
|
| 134 |
+
)
|
| 135 |
+
self.conv2 = nn.Sequential(
|
| 136 |
+
nn.Conv2d(features, inner_features, kernel_size=1, padding=0, dilation=1, bias=False),
|
| 137 |
+
BatchNorm2d(inner_features),
|
| 138 |
+
LeakyReLU(),
|
| 139 |
+
)
|
| 140 |
+
self.conv3 = nn.Sequential(
|
| 141 |
+
nn.Conv2d(features, inner_features, kernel_size=3, padding=dilations[0], dilation=dilations[0], bias=False),
|
| 142 |
+
BatchNorm2d(inner_features),
|
| 143 |
+
LeakyReLU(),
|
| 144 |
+
)
|
| 145 |
+
self.conv4 = nn.Sequential(
|
| 146 |
+
nn.Conv2d(features, inner_features, kernel_size=3, padding=dilations[1], dilation=dilations[1], bias=False),
|
| 147 |
+
BatchNorm2d(inner_features),
|
| 148 |
+
LeakyReLU(),
|
| 149 |
+
)
|
| 150 |
+
self.conv5 = nn.Sequential(
|
| 151 |
+
nn.Conv2d(features, inner_features, kernel_size=3, padding=dilations[2], dilation=dilations[2], bias=False),
|
| 152 |
+
BatchNorm2d(inner_features),
|
| 153 |
+
LeakyReLU(),
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
self.bottleneck = nn.Sequential(
|
| 157 |
+
nn.Conv2d(inner_features * 5, out_features, kernel_size=1, padding=0, dilation=1, bias=False),
|
| 158 |
+
BatchNorm2d(inner_features),
|
| 159 |
+
LeakyReLU(),
|
| 160 |
+
nn.Dropout2d(0.1)
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
def forward(self, x):
|
| 164 |
+
_, _, h, w = x.size()
|
| 165 |
+
|
| 166 |
+
feat1 = F.interpolate(self.conv1(x), size=(h, w), mode='bilinear', align_corners=True)
|
| 167 |
+
|
| 168 |
+
feat2 = self.conv2(x)
|
| 169 |
+
feat3 = self.conv3(x)
|
| 170 |
+
feat4 = self.conv4(x)
|
| 171 |
+
feat5 = self.conv5(x)
|
| 172 |
+
out = torch.cat((feat1, feat2, feat3, feat4, feat5), 1)
|
| 173 |
+
|
| 174 |
+
bottle = self.bottleneck(out)
|
| 175 |
+
return bottle
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class Edge_Module(nn.Module):
|
| 179 |
+
"""
|
| 180 |
+
Edge Learning Branch
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
def __init__(self, in_fea=[256, 512, 1024], mid_fea=256, out_fea=2):
|
| 184 |
+
super(Edge_Module, self).__init__()
|
| 185 |
+
|
| 186 |
+
self.conv1 = nn.Sequential(
|
| 187 |
+
nn.Conv2d(in_fea[0], mid_fea, kernel_size=1, padding=0, dilation=1, bias=False),
|
| 188 |
+
BatchNorm2d(mid_fea),
|
| 189 |
+
LeakyReLU(),
|
| 190 |
+
)
|
| 191 |
+
self.conv2 = nn.Sequential(
|
| 192 |
+
nn.Conv2d(in_fea[1], mid_fea, kernel_size=1, padding=0, dilation=1, bias=False),
|
| 193 |
+
BatchNorm2d(mid_fea),
|
| 194 |
+
LeakyReLU(),
|
| 195 |
+
)
|
| 196 |
+
self.conv3 = nn.Sequential(
|
| 197 |
+
nn.Conv2d(in_fea[2], mid_fea, kernel_size=1, padding=0, dilation=1, bias=False),
|
| 198 |
+
BatchNorm2d(mid_fea),
|
| 199 |
+
LeakyReLU(),
|
| 200 |
+
)
|
| 201 |
+
self.conv4 = nn.Conv2d(mid_fea, out_fea, kernel_size=3, padding=1, dilation=1, bias=True)
|
| 202 |
+
# self.conv5 = nn.Conv2d(out_fea * 3, out_fea, kernel_size=1, padding=0, dilation=1, bias=True)
|
| 203 |
+
|
| 204 |
+
def forward(self, x1, x2, x3):
|
| 205 |
+
_, _, h, w = x1.size()
|
| 206 |
+
|
| 207 |
+
edge1_fea = self.conv1(x1)
|
| 208 |
+
# edge1 = self.conv4(edge1_fea)
|
| 209 |
+
edge2_fea = self.conv2(x2)
|
| 210 |
+
edge2 = self.conv4(edge2_fea)
|
| 211 |
+
edge3_fea = self.conv3(x3)
|
| 212 |
+
edge3 = self.conv4(edge3_fea)
|
| 213 |
+
|
| 214 |
+
edge2_fea = F.interpolate(edge2_fea, size=(h, w), mode='bilinear', align_corners=True)
|
| 215 |
+
edge3_fea = F.interpolate(edge3_fea, size=(h, w), mode='bilinear', align_corners=True)
|
| 216 |
+
edge2 = F.interpolate(edge2, size=(h, w), mode='bilinear', align_corners=True)
|
| 217 |
+
edge3 = F.interpolate(edge3, size=(h, w), mode='bilinear', align_corners=True)
|
| 218 |
+
|
| 219 |
+
# edge = torch.cat([edge1, edge2, edge3], dim=1)
|
| 220 |
+
edge_fea = torch.cat([edge1_fea, edge2_fea, edge3_fea], dim=1)
|
| 221 |
+
# edge = self.conv5(edge)
|
| 222 |
+
|
| 223 |
+
# return edge, edge_fea
|
| 224 |
+
return edge_fea
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class Decoder_Module(nn.Module):
|
| 228 |
+
"""
|
| 229 |
+
Parsing Branch Decoder Module.
|
| 230 |
+
"""
|
| 231 |
+
|
| 232 |
+
def __init__(self, num_classes):
|
| 233 |
+
super(Decoder_Module, self).__init__()
|
| 234 |
+
self.conv1 = nn.Sequential(
|
| 235 |
+
nn.Conv2d(512, 256, kernel_size=1, padding=0, dilation=1, bias=False),
|
| 236 |
+
BatchNorm2d(256),
|
| 237 |
+
LeakyReLU(),
|
| 238 |
+
)
|
| 239 |
+
self.conv2 = nn.Sequential(
|
| 240 |
+
nn.Conv2d(256, 48, kernel_size=1, stride=1, padding=0, dilation=1, bias=False),
|
| 241 |
+
BatchNorm2d(48),
|
| 242 |
+
LeakyReLU(),
|
| 243 |
+
)
|
| 244 |
+
self.conv3 = nn.Sequential(
|
| 245 |
+
nn.Conv2d(304, 256, kernel_size=1, padding=0, dilation=1, bias=False),
|
| 246 |
+
BatchNorm2d(256),
|
| 247 |
+
LeakyReLU(),
|
| 248 |
+
nn.Conv2d(256, 256, kernel_size=1, padding=0, dilation=1, bias=False),
|
| 249 |
+
BatchNorm2d(256),
|
| 250 |
+
LeakyReLU(),
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
# self.conv4 = nn.Conv2d(256, num_classes, kernel_size=1, padding=0, dilation=1, bias=True)
|
| 254 |
+
|
| 255 |
+
def forward(self, xt, xl):
|
| 256 |
+
_, _, h, w = xl.size()
|
| 257 |
+
xt = F.interpolate(self.conv1(xt), size=(h, w), mode='bilinear', align_corners=True)
|
| 258 |
+
xl = self.conv2(xl)
|
| 259 |
+
x = torch.cat([xt, xl], dim=1)
|
| 260 |
+
x = self.conv3(x)
|
| 261 |
+
# seg = self.conv4(x)
|
| 262 |
+
# return seg, x
|
| 263 |
+
return x
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
class ResNet(nn.Module):
|
| 267 |
+
def __init__(self, block, layers, num_classes):
|
| 268 |
+
self.inplanes = 128
|
| 269 |
+
super(ResNet, self).__init__()
|
| 270 |
+
self.conv1 = conv3x3(3, 64, stride=2)
|
| 271 |
+
self.bn1 = BatchNorm2d(64)
|
| 272 |
+
self.relu1 = nn.ReLU(inplace=False)
|
| 273 |
+
self.conv2 = conv3x3(64, 64)
|
| 274 |
+
self.bn2 = BatchNorm2d(64)
|
| 275 |
+
self.relu2 = nn.ReLU(inplace=False)
|
| 276 |
+
self.conv3 = conv3x3(64, 128)
|
| 277 |
+
self.bn3 = BatchNorm2d(128)
|
| 278 |
+
self.relu3 = nn.ReLU(inplace=False)
|
| 279 |
+
|
| 280 |
+
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
|
| 281 |
+
|
| 282 |
+
self.layer1 = self._make_layer(block, 64, layers[0])
|
| 283 |
+
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
|
| 284 |
+
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
|
| 285 |
+
self.layer4 = self._make_layer(block, 512, layers[3], stride=1, dilation=2, multi_grid=(1, 1, 1))
|
| 286 |
+
|
| 287 |
+
self.context_encoding = PSPModule(2048, 512)
|
| 288 |
+
|
| 289 |
+
self.edge = Edge_Module()
|
| 290 |
+
self.decoder = Decoder_Module(num_classes)
|
| 291 |
+
|
| 292 |
+
self.fushion = nn.Sequential(
|
| 293 |
+
nn.Conv2d(1024, 256, kernel_size=1, padding=0, dilation=1, bias=False),
|
| 294 |
+
BatchNorm2d(256),
|
| 295 |
+
LeakyReLU(),
|
| 296 |
+
nn.Dropout2d(0.1),
|
| 297 |
+
nn.Conv2d(256, num_classes, kernel_size=1, padding=0, dilation=1, bias=True)
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
def _make_layer(self, block, planes, blocks, stride=1, dilation=1, multi_grid=1):
|
| 301 |
+
downsample = None
|
| 302 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
| 303 |
+
downsample = nn.Sequential(
|
| 304 |
+
nn.Conv2d(self.inplanes, planes * block.expansion,
|
| 305 |
+
kernel_size=1, stride=stride, bias=False),
|
| 306 |
+
BatchNorm2d(planes * block.expansion, affine=affine_par))
|
| 307 |
+
|
| 308 |
+
layers = []
|
| 309 |
+
generate_multi_grid = lambda index, grids: grids[index % len(grids)] if isinstance(grids, tuple) else 1
|
| 310 |
+
layers.append(block(self.inplanes, planes, stride, dilation=dilation, downsample=downsample,
|
| 311 |
+
multi_grid=generate_multi_grid(0, multi_grid)))
|
| 312 |
+
self.inplanes = planes * block.expansion
|
| 313 |
+
for i in range(1, blocks):
|
| 314 |
+
layers.append(
|
| 315 |
+
block(self.inplanes, planes, dilation=dilation, multi_grid=generate_multi_grid(i, multi_grid)))
|
| 316 |
+
|
| 317 |
+
return nn.Sequential(*layers)
|
| 318 |
+
|
| 319 |
+
def forward(self, x):
|
| 320 |
+
x = self.relu1(self.bn1(self.conv1(x)))
|
| 321 |
+
x = self.relu2(self.bn2(self.conv2(x)))
|
| 322 |
+
x = self.relu3(self.bn3(self.conv3(x)))
|
| 323 |
+
x = self.maxpool(x)
|
| 324 |
+
x2 = self.layer1(x)
|
| 325 |
+
x3 = self.layer2(x2)
|
| 326 |
+
x4 = self.layer3(x3)
|
| 327 |
+
x5 = self.layer4(x4)
|
| 328 |
+
x = self.context_encoding(x5)
|
| 329 |
+
# parsing_result, parsing_fea = self.decoder(x, x2)
|
| 330 |
+
parsing_fea = self.decoder(x, x2)
|
| 331 |
+
# Edge Branch
|
| 332 |
+
# edge_result, edge_fea = self.edge(x2, x3, x4)
|
| 333 |
+
edge_fea = self.edge(x2, x3, x4)
|
| 334 |
+
# Fusion Branch
|
| 335 |
+
x = torch.cat([parsing_fea, edge_fea], dim=1)
|
| 336 |
+
fusion_result = self.fushion(x)
|
| 337 |
+
# return [[parsing_result, fusion_result], [edge_result]]
|
| 338 |
+
return fusion_result
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def initialize_pretrained_model(model, settings, pretrained='./models/resnet101-imagenet.pth'):
|
| 342 |
+
model.input_space = settings['input_space']
|
| 343 |
+
model.input_size = settings['input_size']
|
| 344 |
+
model.input_range = settings['input_range']
|
| 345 |
+
model.mean = settings['mean']
|
| 346 |
+
model.std = settings['std']
|
| 347 |
+
|
| 348 |
+
if pretrained is not None:
|
| 349 |
+
saved_state_dict = torch.load(pretrained)
|
| 350 |
+
new_params = model.state_dict().copy()
|
| 351 |
+
for i in saved_state_dict:
|
| 352 |
+
i_parts = i.split('.')
|
| 353 |
+
if not i_parts[0] == 'fc':
|
| 354 |
+
new_params['.'.join(i_parts[0:])] = saved_state_dict[i]
|
| 355 |
+
model.load_state_dict(new_params)
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def resnet101(num_classes=20, pretrained='./models/resnet101-imagenet.pth'):
|
| 359 |
+
model = ResNet(Bottleneck, [3, 4, 23, 3], num_classes)
|
| 360 |
+
settings = pretrained_settings['resnet101']['imagenet']
|
| 361 |
+
initialize_pretrained_model(model, settings, pretrained)
|
| 362 |
+
return model
|
SCHP/networks/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import absolute_import
|
| 2 |
+
|
| 3 |
+
from model.SCHP.networks.AugmentCE2P import resnet101
|
| 4 |
+
|
| 5 |
+
__factory = {
|
| 6 |
+
'resnet101': resnet101,
|
| 7 |
+
}
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def init_model(name, *args, **kwargs):
|
| 11 |
+
if name not in __factory.keys():
|
| 12 |
+
raise KeyError("Unknown model arch: {}".format(name))
|
| 13 |
+
return __factory[name](*args, **kwargs)
|
SCHP/networks/__pycache__/AugmentCE2P.cpython-311.pyc
ADDED
|
Binary file (21.2 kB). View file
|
|
|
SCHP/networks/__pycache__/AugmentCE2P.cpython-39.pyc
ADDED
|
Binary file (10.2 kB). View file
|
|
|
SCHP/networks/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (762 Bytes). View file
|
|
|
SCHP/networks/__pycache__/__init__.cpython-39.pyc
ADDED
|
Binary file (516 Bytes). View file
|
|
|
SCHP/utils/__pycache__/transforms.cpython-311.pyc
ADDED
|
Binary file (9.11 kB). View file
|
|
|
SCHP/utils/__pycache__/transforms.cpython-39.pyc
ADDED
|
Binary file (4.88 kB). View file
|
|
|
SCHP/utils/transforms.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ------------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
|
| 5 |
+
# ------------------------------------------------------------------------------
|
| 6 |
+
|
| 7 |
+
from __future__ import absolute_import
|
| 8 |
+
from __future__ import division
|
| 9 |
+
from __future__ import print_function
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import cv2
|
| 13 |
+
import torch
|
| 14 |
+
|
| 15 |
+
class BRG2Tensor_transform(object):
|
| 16 |
+
def __call__(self, pic):
|
| 17 |
+
img = torch.from_numpy(pic.transpose((2, 0, 1)))
|
| 18 |
+
if isinstance(img, torch.ByteTensor):
|
| 19 |
+
return img.float()
|
| 20 |
+
else:
|
| 21 |
+
return img
|
| 22 |
+
|
| 23 |
+
class BGR2RGB_transform(object):
|
| 24 |
+
def __call__(self, tensor):
|
| 25 |
+
return tensor[[2,1,0],:,:]
|
| 26 |
+
|
| 27 |
+
def flip_back(output_flipped, matched_parts):
|
| 28 |
+
'''
|
| 29 |
+
ouput_flipped: numpy.ndarray(batch_size, num_joints, height, width)
|
| 30 |
+
'''
|
| 31 |
+
assert output_flipped.ndim == 4,\
|
| 32 |
+
'output_flipped should be [batch_size, num_joints, height, width]'
|
| 33 |
+
|
| 34 |
+
output_flipped = output_flipped[:, :, :, ::-1]
|
| 35 |
+
|
| 36 |
+
for pair in matched_parts:
|
| 37 |
+
tmp = output_flipped[:, pair[0], :, :].copy()
|
| 38 |
+
output_flipped[:, pair[0], :, :] = output_flipped[:, pair[1], :, :]
|
| 39 |
+
output_flipped[:, pair[1], :, :] = tmp
|
| 40 |
+
|
| 41 |
+
return output_flipped
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def fliplr_joints(joints, joints_vis, width, matched_parts):
|
| 45 |
+
"""
|
| 46 |
+
flip coords
|
| 47 |
+
"""
|
| 48 |
+
# Flip horizontal
|
| 49 |
+
joints[:, 0] = width - joints[:, 0] - 1
|
| 50 |
+
|
| 51 |
+
# Change left-right parts
|
| 52 |
+
for pair in matched_parts:
|
| 53 |
+
joints[pair[0], :], joints[pair[1], :] = \
|
| 54 |
+
joints[pair[1], :], joints[pair[0], :].copy()
|
| 55 |
+
joints_vis[pair[0], :], joints_vis[pair[1], :] = \
|
| 56 |
+
joints_vis[pair[1], :], joints_vis[pair[0], :].copy()
|
| 57 |
+
|
| 58 |
+
return joints*joints_vis, joints_vis
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def transform_preds(coords, center, scale, input_size):
|
| 62 |
+
target_coords = np.zeros(coords.shape)
|
| 63 |
+
trans = get_affine_transform(center, scale, 0, input_size, inv=1)
|
| 64 |
+
for p in range(coords.shape[0]):
|
| 65 |
+
target_coords[p, 0:2] = affine_transform(coords[p, 0:2], trans)
|
| 66 |
+
return target_coords
|
| 67 |
+
|
| 68 |
+
def transform_parsing(pred, center, scale, width, height, input_size):
|
| 69 |
+
|
| 70 |
+
trans = get_affine_transform(center, scale, 0, input_size, inv=1)
|
| 71 |
+
target_pred = cv2.warpAffine(
|
| 72 |
+
pred,
|
| 73 |
+
trans,
|
| 74 |
+
(int(width), int(height)), #(int(width), int(height)),
|
| 75 |
+
flags=cv2.INTER_NEAREST,
|
| 76 |
+
borderMode=cv2.BORDER_CONSTANT,
|
| 77 |
+
borderValue=(0))
|
| 78 |
+
|
| 79 |
+
return target_pred
|
| 80 |
+
|
| 81 |
+
def transform_logits(logits, center, scale, width, height, input_size):
|
| 82 |
+
|
| 83 |
+
trans = get_affine_transform(center, scale, 0, input_size, inv=1)
|
| 84 |
+
channel = logits.shape[2]
|
| 85 |
+
target_logits = []
|
| 86 |
+
for i in range(channel):
|
| 87 |
+
target_logit = cv2.warpAffine(
|
| 88 |
+
logits[:,:,i],
|
| 89 |
+
trans,
|
| 90 |
+
(int(width), int(height)), #(int(width), int(height)),
|
| 91 |
+
flags=cv2.INTER_LINEAR,
|
| 92 |
+
borderMode=cv2.BORDER_CONSTANT,
|
| 93 |
+
borderValue=(0))
|
| 94 |
+
target_logits.append(target_logit)
|
| 95 |
+
target_logits = np.stack(target_logits,axis=2)
|
| 96 |
+
|
| 97 |
+
return target_logits
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def get_affine_transform(center,
|
| 101 |
+
scale,
|
| 102 |
+
rot,
|
| 103 |
+
output_size,
|
| 104 |
+
shift=np.array([0, 0], dtype=np.float32),
|
| 105 |
+
inv=0):
|
| 106 |
+
if not isinstance(scale, np.ndarray) and not isinstance(scale, list):
|
| 107 |
+
print(scale)
|
| 108 |
+
scale = np.array([scale, scale])
|
| 109 |
+
|
| 110 |
+
scale_tmp = scale
|
| 111 |
+
|
| 112 |
+
src_w = scale_tmp[0]
|
| 113 |
+
dst_w = output_size[1]
|
| 114 |
+
dst_h = output_size[0]
|
| 115 |
+
|
| 116 |
+
rot_rad = np.pi * rot / 180
|
| 117 |
+
src_dir = get_dir([0, src_w * -0.5], rot_rad)
|
| 118 |
+
dst_dir = np.array([0, (dst_w-1) * -0.5], np.float32)
|
| 119 |
+
|
| 120 |
+
src = np.zeros((3, 2), dtype=np.float32)
|
| 121 |
+
dst = np.zeros((3, 2), dtype=np.float32)
|
| 122 |
+
src[0, :] = center + scale_tmp * shift
|
| 123 |
+
src[1, :] = center + src_dir + scale_tmp * shift
|
| 124 |
+
dst[0, :] = [(dst_w-1) * 0.5, (dst_h-1) * 0.5]
|
| 125 |
+
dst[1, :] = np.array([(dst_w-1) * 0.5, (dst_h-1) * 0.5]) + dst_dir
|
| 126 |
+
|
| 127 |
+
src[2:, :] = get_3rd_point(src[0, :], src[1, :])
|
| 128 |
+
dst[2:, :] = get_3rd_point(dst[0, :], dst[1, :])
|
| 129 |
+
|
| 130 |
+
if inv:
|
| 131 |
+
trans = cv2.getAffineTransform(np.float32(dst), np.float32(src))
|
| 132 |
+
else:
|
| 133 |
+
trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))
|
| 134 |
+
|
| 135 |
+
return trans
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def affine_transform(pt, t):
|
| 139 |
+
new_pt = np.array([pt[0], pt[1], 1.]).T
|
| 140 |
+
new_pt = np.dot(t, new_pt)
|
| 141 |
+
return new_pt[:2]
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def get_3rd_point(a, b):
|
| 145 |
+
direct = a - b
|
| 146 |
+
return b + np.array([-direct[1], direct[0]], dtype=np.float32)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def get_dir(src_point, rot_rad):
|
| 150 |
+
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
|
| 151 |
+
|
| 152 |
+
src_result = [0, 0]
|
| 153 |
+
src_result[0] = src_point[0] * cs - src_point[1] * sn
|
| 154 |
+
src_result[1] = src_point[0] * sn + src_point[1] * cs
|
| 155 |
+
|
| 156 |
+
return src_result
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def crop(img, center, scale, output_size, rot=0):
|
| 160 |
+
trans = get_affine_transform(center, scale, rot, output_size)
|
| 161 |
+
|
| 162 |
+
dst_img = cv2.warpAffine(img,
|
| 163 |
+
trans,
|
| 164 |
+
(int(output_size[1]), int(output_size[0])),
|
| 165 |
+
flags=cv2.INTER_LINEAR)
|
| 166 |
+
|
| 167 |
+
return dst_img
|
__pycache__/attn_processor.cpython-311.pyc
ADDED
|
Binary file (4.99 kB). View file
|
|
|
__pycache__/cloth_masker.cpython-311.pyc
ADDED
|
Binary file (13.9 kB). View file
|
|
|
__pycache__/pipeline.cpython-311.pyc
ADDED
|
Binary file (19.4 kB). View file
|
|
|
__pycache__/utils.cpython-311.pyc
ADDED
|
Binary file (5.21 kB). View file
|
|
|
attn_processor.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from torch.nn import functional as F
|
| 2 |
+
import torch
|
| 3 |
+
# from flash_attn import flash_attn_func
|
| 4 |
+
|
| 5 |
+
class SkipAttnProcessor(torch.nn.Module):
|
| 6 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 7 |
+
super().__init__()
|
| 8 |
+
|
| 9 |
+
def __call__(
|
| 10 |
+
self,
|
| 11 |
+
attn,
|
| 12 |
+
hidden_states,
|
| 13 |
+
encoder_hidden_states=None,
|
| 14 |
+
attention_mask=None,
|
| 15 |
+
temb=None,
|
| 16 |
+
):
|
| 17 |
+
return hidden_states
|
| 18 |
+
|
| 19 |
+
class AttnProcessor2_0(torch.nn.Module):
|
| 20 |
+
r"""
|
| 21 |
+
Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(
|
| 25 |
+
self,
|
| 26 |
+
hidden_size=None,
|
| 27 |
+
cross_attention_dim=None,
|
| 28 |
+
**kwargs
|
| 29 |
+
):
|
| 30 |
+
super().__init__()
|
| 31 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
| 32 |
+
raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
|
| 33 |
+
|
| 34 |
+
def __call__(
|
| 35 |
+
self,
|
| 36 |
+
attn,
|
| 37 |
+
hidden_states,
|
| 38 |
+
encoder_hidden_states=None,
|
| 39 |
+
attention_mask=None,
|
| 40 |
+
temb=None,
|
| 41 |
+
*args,
|
| 42 |
+
**kwargs,
|
| 43 |
+
):
|
| 44 |
+
residual = hidden_states
|
| 45 |
+
|
| 46 |
+
if attn.spatial_norm is not None:
|
| 47 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
| 48 |
+
|
| 49 |
+
input_ndim = hidden_states.ndim
|
| 50 |
+
|
| 51 |
+
if input_ndim == 4:
|
| 52 |
+
batch_size, channel, height, width = hidden_states.shape
|
| 53 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
| 54 |
+
|
| 55 |
+
batch_size, sequence_length, _ = (
|
| 56 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
if attention_mask is not None:
|
| 60 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 61 |
+
# scaled_dot_product_attention expects attention_mask shape to be
|
| 62 |
+
# (batch, heads, source_length, target_length)
|
| 63 |
+
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
| 64 |
+
|
| 65 |
+
if attn.group_norm is not None:
|
| 66 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 67 |
+
|
| 68 |
+
query = attn.to_q(hidden_states)
|
| 69 |
+
|
| 70 |
+
if encoder_hidden_states is None:
|
| 71 |
+
encoder_hidden_states = hidden_states
|
| 72 |
+
elif attn.norm_cross:
|
| 73 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 74 |
+
|
| 75 |
+
key = attn.to_k(encoder_hidden_states)
|
| 76 |
+
value = attn.to_v(encoder_hidden_states)
|
| 77 |
+
|
| 78 |
+
inner_dim = key.shape[-1]
|
| 79 |
+
head_dim = inner_dim // attn.heads
|
| 80 |
+
|
| 81 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 82 |
+
|
| 83 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 84 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 85 |
+
|
| 86 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
| 87 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
| 88 |
+
|
| 89 |
+
hidden_states = F.scaled_dot_product_attention(
|
| 90 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
| 91 |
+
)
|
| 92 |
+
# hidden_states = flash_attn_func(
|
| 93 |
+
# query, key, value, dropout_p=0.0, causal=False
|
| 94 |
+
# )
|
| 95 |
+
|
| 96 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
| 97 |
+
hidden_states = hidden_states.to(query.dtype)
|
| 98 |
+
|
| 99 |
+
# linear proj
|
| 100 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 101 |
+
# dropout
|
| 102 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 103 |
+
|
| 104 |
+
if input_ndim == 4:
|
| 105 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
| 106 |
+
|
| 107 |
+
if attn.residual_connection:
|
| 108 |
+
hidden_states = hidden_states + residual
|
| 109 |
+
|
| 110 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
| 111 |
+
|
| 112 |
+
return hidden_states
|
| 113 |
+
|
cloth_masker.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from PIL import Image
|
| 3 |
+
from typing import Union
|
| 4 |
+
import numpy as np
|
| 5 |
+
import cv2
|
| 6 |
+
from diffusers.image_processor import VaeImageProcessor
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
from model.SCHP import SCHP # type: ignore
|
| 10 |
+
from model.DensePose import DensePose # type: ignore
|
| 11 |
+
|
| 12 |
+
DENSE_INDEX_MAP = {
|
| 13 |
+
"background": [0],
|
| 14 |
+
"torso": [1, 2],
|
| 15 |
+
"right hand": [3],
|
| 16 |
+
"left hand": [4],
|
| 17 |
+
"right foot": [5],
|
| 18 |
+
"left foot": [6],
|
| 19 |
+
"right thigh": [7, 9],
|
| 20 |
+
"left thigh": [8, 10],
|
| 21 |
+
"right leg": [11, 13],
|
| 22 |
+
"left leg": [12, 14],
|
| 23 |
+
"left big arm": [15, 17],
|
| 24 |
+
"right big arm": [16, 18],
|
| 25 |
+
"left forearm": [19, 21],
|
| 26 |
+
"right forearm": [20, 22],
|
| 27 |
+
"face": [23, 24],
|
| 28 |
+
"thighs": [7, 8, 9, 10],
|
| 29 |
+
"legs": [11, 12, 13, 14],
|
| 30 |
+
"hands": [3, 4],
|
| 31 |
+
"feet": [5, 6],
|
| 32 |
+
"big arms": [15, 16, 17, 18],
|
| 33 |
+
"forearms": [19, 20, 21, 22],
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
ATR_MAPPING = {
|
| 37 |
+
'Background': 0, 'Hat': 1, 'Hair': 2, 'Sunglasses': 3,
|
| 38 |
+
'Upper-clothes': 4, 'Skirt': 5, 'Pants': 6, 'Dress': 7,
|
| 39 |
+
'Belt': 8, 'Left-shoe': 9, 'Right-shoe': 10, 'Face': 11,
|
| 40 |
+
'Left-leg': 12, 'Right-leg': 13, 'Left-arm': 14, 'Right-arm': 15,
|
| 41 |
+
'Bag': 16, 'Scarf': 17
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
LIP_MAPPING = {
|
| 45 |
+
'Background': 0, 'Hat': 1, 'Hair': 2, 'Glove': 3,
|
| 46 |
+
'Sunglasses': 4, 'Upper-clothes': 5, 'Dress': 6, 'Coat': 7,
|
| 47 |
+
'Socks': 8, 'Pants': 9, 'Jumpsuits': 10, 'Scarf': 11,
|
| 48 |
+
'Skirt': 12, 'Face': 13, 'Left-arm': 14, 'Right-arm': 15,
|
| 49 |
+
'Left-leg': 16, 'Right-leg': 17, 'Left-shoe': 18, 'Right-shoe': 19
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
PROTECT_BODY_PARTS = {
|
| 53 |
+
'upper': ['Left-leg', 'Right-leg'],
|
| 54 |
+
'lower': ['Right-arm', 'Left-arm', 'Face'],
|
| 55 |
+
'overall': [],
|
| 56 |
+
'inner': ['Left-leg', 'Right-leg'],
|
| 57 |
+
'outer': ['Left-leg', 'Right-leg'],
|
| 58 |
+
}
|
| 59 |
+
PROTECT_CLOTH_PARTS = {
|
| 60 |
+
'upper': {
|
| 61 |
+
'ATR': ['Skirt', 'Pants'],
|
| 62 |
+
'LIP': ['Skirt', 'Pants']
|
| 63 |
+
},
|
| 64 |
+
'lower': {
|
| 65 |
+
'ATR': ['Upper-clothes'],
|
| 66 |
+
'LIP': ['Upper-clothes', 'Coat']
|
| 67 |
+
},
|
| 68 |
+
'overall': {
|
| 69 |
+
'ATR': [],
|
| 70 |
+
'LIP': []
|
| 71 |
+
},
|
| 72 |
+
'inner': {
|
| 73 |
+
'ATR': ['Dress', 'Coat', 'Skirt', 'Pants'],
|
| 74 |
+
'LIP': ['Dress', 'Coat', 'Skirt', 'Pants', 'Jumpsuits']
|
| 75 |
+
},
|
| 76 |
+
'outer': {
|
| 77 |
+
'ATR': ['Dress', 'Pants', 'Skirt'],
|
| 78 |
+
'LIP': ['Upper-clothes', 'Dress', 'Pants', 'Skirt', 'Jumpsuits']
|
| 79 |
+
}
|
| 80 |
+
}
|
| 81 |
+
MASK_CLOTH_PARTS = {
|
| 82 |
+
'upper': ['Upper-clothes', 'Coat', 'Dress', 'Jumpsuits'],
|
| 83 |
+
'lower': ['Pants', 'Skirt', 'Dress', 'Jumpsuits'],
|
| 84 |
+
'overall': ['Upper-clothes', 'Dress', 'Pants', 'Skirt', 'Coat', 'Jumpsuits'],
|
| 85 |
+
'inner': ['Upper-clothes'],
|
| 86 |
+
'outer': ['Coat',]
|
| 87 |
+
}
|
| 88 |
+
MASK_DENSE_PARTS = {
|
| 89 |
+
'upper': ['torso', 'big arms', 'forearms'],
|
| 90 |
+
'lower': ['thighs', 'legs'],
|
| 91 |
+
'overall': ['torso', 'thighs', 'legs', 'big arms', 'forearms'],
|
| 92 |
+
'inner': ['torso'],
|
| 93 |
+
'outer': ['torso', 'big arms', 'forearms']
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
schp_public_protect_parts = ['Hat', 'Hair', 'Sunglasses', 'Left-shoe', 'Right-shoe', 'Bag', 'Glove', 'Scarf']
|
| 97 |
+
schp_protect_parts = {
|
| 98 |
+
'upper': ['Left-leg', 'Right-leg', 'Skirt', 'Pants', 'Jumpsuits'],
|
| 99 |
+
'lower': ['Left-arm', 'Right-arm', 'Upper-clothes', 'Coat'],
|
| 100 |
+
'overall': [],
|
| 101 |
+
'inner': ['Left-leg', 'Right-leg', 'Skirt', 'Pants', 'Jumpsuits', 'Coat'],
|
| 102 |
+
'outer': ['Left-leg', 'Right-leg', 'Skirt', 'Pants', 'Jumpsuits', 'Upper-clothes']
|
| 103 |
+
}
|
| 104 |
+
schp_mask_parts = {
|
| 105 |
+
'upper': ['Upper-clothes', 'Dress', 'Coat', 'Jumpsuits'],
|
| 106 |
+
'lower': ['Pants', 'Skirt', 'Dress', 'Jumpsuits', 'socks'],
|
| 107 |
+
'overall': ['Upper-clothes', 'Dress', 'Pants', 'Skirt', 'Coat', 'Jumpsuits', 'socks'],
|
| 108 |
+
'inner': ['Upper-clothes'],
|
| 109 |
+
'outer': ['Coat',]
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
dense_mask_parts = {
|
| 113 |
+
'upper': ['torso', 'big arms', 'forearms'],
|
| 114 |
+
'lower': ['thighs', 'legs'],
|
| 115 |
+
'overall': ['torso', 'thighs', 'legs', 'big arms', 'forearms'],
|
| 116 |
+
'inner': ['torso'],
|
| 117 |
+
'outer': ['torso', 'big arms', 'forearms']
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
def vis_mask(image, mask):
|
| 121 |
+
image = np.array(image).astype(np.uint8)
|
| 122 |
+
mask = np.array(mask).astype(np.uint8)
|
| 123 |
+
mask[mask > 127] = 255
|
| 124 |
+
mask[mask <= 127] = 0
|
| 125 |
+
mask = np.expand_dims(mask, axis=-1)
|
| 126 |
+
mask = np.repeat(mask, 3, axis=-1)
|
| 127 |
+
mask = mask / 255
|
| 128 |
+
return Image.fromarray((image * (1 - mask)).astype(np.uint8))
|
| 129 |
+
|
| 130 |
+
def part_mask_of(part: Union[str, list],
|
| 131 |
+
parse: np.ndarray, mapping: dict):
|
| 132 |
+
if isinstance(part, str):
|
| 133 |
+
part = [part]
|
| 134 |
+
mask = np.zeros_like(parse)
|
| 135 |
+
for _ in part:
|
| 136 |
+
if _ not in mapping:
|
| 137 |
+
continue
|
| 138 |
+
if isinstance(mapping[_], list):
|
| 139 |
+
for i in mapping[_]:
|
| 140 |
+
mask += (parse == i)
|
| 141 |
+
else:
|
| 142 |
+
mask += (parse == mapping[_])
|
| 143 |
+
return mask
|
| 144 |
+
|
| 145 |
+
def hull_mask(mask_area: np.ndarray):
|
| 146 |
+
ret, binary = cv2.threshold(mask_area, 127, 255, cv2.THRESH_BINARY)
|
| 147 |
+
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 148 |
+
hull_mask = np.zeros_like(mask_area)
|
| 149 |
+
for c in contours:
|
| 150 |
+
hull = cv2.convexHull(c)
|
| 151 |
+
hull_mask = cv2.fillPoly(np.zeros_like(mask_area), [hull], 255) | hull_mask
|
| 152 |
+
return hull_mask
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class AutoMasker:
|
| 156 |
+
def __init__(
|
| 157 |
+
self,
|
| 158 |
+
densepose_ckpt='./Models/DensePose',
|
| 159 |
+
schp_ckpt='./Models/SCHP',
|
| 160 |
+
device='cuda'):
|
| 161 |
+
np.random.seed(0)
|
| 162 |
+
torch.manual_seed(0)
|
| 163 |
+
torch.cuda.manual_seed(0)
|
| 164 |
+
|
| 165 |
+
self.densepose_processor = DensePose(densepose_ckpt, device)
|
| 166 |
+
self.schp_processor_atr = SCHP(ckpt_path=os.path.join(schp_ckpt, 'exp-schp-201908301523-atr.pth'), device=device)
|
| 167 |
+
self.schp_processor_lip = SCHP(ckpt_path=os.path.join(schp_ckpt, 'exp-schp-201908261155-lip.pth'), device=device)
|
| 168 |
+
|
| 169 |
+
self.mask_processor = VaeImageProcessor(vae_scale_factor=8, do_normalize=False, do_binarize=True, do_convert_grayscale=True)
|
| 170 |
+
|
| 171 |
+
def process_densepose(self, image_or_path):
|
| 172 |
+
return self.densepose_processor(image_or_path, resize=1024)
|
| 173 |
+
|
| 174 |
+
def process_schp_lip(self, image_or_path):
|
| 175 |
+
return self.schp_processor_lip(image_or_path)
|
| 176 |
+
|
| 177 |
+
def process_schp_atr(self, image_or_path):
|
| 178 |
+
return self.schp_processor_atr(image_or_path)
|
| 179 |
+
|
| 180 |
+
def preprocess_image(self, image_or_path):
|
| 181 |
+
return {
|
| 182 |
+
'densepose': self.densepose_processor(image_or_path, resize=1024),
|
| 183 |
+
'schp_atr': self.schp_processor_atr(image_or_path),
|
| 184 |
+
'schp_lip': self.schp_processor_lip(image_or_path)
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
@staticmethod
|
| 188 |
+
def cloth_agnostic_mask(
|
| 189 |
+
densepose_mask: Image.Image,
|
| 190 |
+
schp_lip_mask: Image.Image,
|
| 191 |
+
schp_atr_mask: Image.Image,
|
| 192 |
+
part: str='overall',
|
| 193 |
+
**kwargs
|
| 194 |
+
):
|
| 195 |
+
assert part in ['upper', 'lower', 'overall', 'inner', 'outer'], f"part should be one of ['upper', 'lower', 'overall', 'inner', 'outer'], but got {part}"
|
| 196 |
+
w, h = densepose_mask.size
|
| 197 |
+
|
| 198 |
+
dilate_kernel = max(w, h) // 250
|
| 199 |
+
dilate_kernel = dilate_kernel if dilate_kernel % 2 == 1 else dilate_kernel + 1
|
| 200 |
+
dilate_kernel = np.ones((dilate_kernel, dilate_kernel), np.uint8)
|
| 201 |
+
|
| 202 |
+
kernal_size = max(w, h) // 25
|
| 203 |
+
kernal_size = kernal_size if kernal_size % 2 == 1 else kernal_size + 1
|
| 204 |
+
|
| 205 |
+
densepose_mask = np.array(densepose_mask)
|
| 206 |
+
schp_lip_mask = np.array(schp_lip_mask)
|
| 207 |
+
schp_atr_mask = np.array(schp_atr_mask)
|
| 208 |
+
|
| 209 |
+
# Strong Protect Area (Hands, Face, Accessory, Feet)
|
| 210 |
+
hands_protect_area = part_mask_of(['hands', 'feet'], densepose_mask, DENSE_INDEX_MAP)
|
| 211 |
+
hands_protect_area = cv2.dilate(hands_protect_area, dilate_kernel, iterations=1)
|
| 212 |
+
hands_protect_area = hands_protect_area & \
|
| 213 |
+
(part_mask_of(['Left-arm', 'Right-arm', 'Left-leg', 'Right-leg'], schp_atr_mask, ATR_MAPPING) | \
|
| 214 |
+
part_mask_of(['Left-arm', 'Right-arm', 'Left-leg', 'Right-leg'], schp_lip_mask, LIP_MAPPING))
|
| 215 |
+
face_protect_area = part_mask_of('Face', schp_lip_mask, LIP_MAPPING)
|
| 216 |
+
|
| 217 |
+
strong_protect_area = hands_protect_area | face_protect_area
|
| 218 |
+
|
| 219 |
+
# Weak Protect Area (Hair, Irrelevant Clothes, Body Parts)
|
| 220 |
+
body_protect_area = part_mask_of(PROTECT_BODY_PARTS[part], schp_lip_mask, LIP_MAPPING) | part_mask_of(PROTECT_BODY_PARTS[part], schp_atr_mask, ATR_MAPPING)
|
| 221 |
+
hair_protect_area = part_mask_of(['Hair'], schp_lip_mask, LIP_MAPPING) | \
|
| 222 |
+
part_mask_of(['Hair'], schp_atr_mask, ATR_MAPPING)
|
| 223 |
+
cloth_protect_area = part_mask_of(PROTECT_CLOTH_PARTS[part]['LIP'], schp_lip_mask, LIP_MAPPING) | \
|
| 224 |
+
part_mask_of(PROTECT_CLOTH_PARTS[part]['ATR'], schp_atr_mask, ATR_MAPPING)
|
| 225 |
+
accessory_protect_area = part_mask_of((accessory_parts := ['Hat', 'Glove', 'Sunglasses', 'Bag', 'Left-shoe', 'Right-shoe', 'Scarf', 'Socks']), schp_lip_mask, LIP_MAPPING) | \
|
| 226 |
+
part_mask_of(accessory_parts, schp_atr_mask, ATR_MAPPING)
|
| 227 |
+
weak_protect_area = body_protect_area | cloth_protect_area | hair_protect_area | strong_protect_area | accessory_protect_area
|
| 228 |
+
|
| 229 |
+
# Mask Area
|
| 230 |
+
strong_mask_area = part_mask_of(MASK_CLOTH_PARTS[part], schp_lip_mask, LIP_MAPPING) | \
|
| 231 |
+
part_mask_of(MASK_CLOTH_PARTS[part], schp_atr_mask, ATR_MAPPING)
|
| 232 |
+
background_area = part_mask_of(['Background'], schp_lip_mask, LIP_MAPPING) & part_mask_of(['Background'], schp_atr_mask, ATR_MAPPING)
|
| 233 |
+
mask_dense_area = part_mask_of(MASK_DENSE_PARTS[part], densepose_mask, DENSE_INDEX_MAP)
|
| 234 |
+
mask_dense_area = cv2.resize(mask_dense_area.astype(np.uint8), None, fx=0.25, fy=0.25, interpolation=cv2.INTER_NEAREST)
|
| 235 |
+
mask_dense_area = cv2.dilate(mask_dense_area, dilate_kernel, iterations=2)
|
| 236 |
+
mask_dense_area = cv2.resize(mask_dense_area.astype(np.uint8), None, fx=4, fy=4, interpolation=cv2.INTER_NEAREST)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
mask_area = (np.ones_like(densepose_mask) & (~weak_protect_area) & (~background_area)) | mask_dense_area
|
| 240 |
+
|
| 241 |
+
mask_area = hull_mask(mask_area * 255) // 255 # Convex Hull to expand the mask area
|
| 242 |
+
mask_area = mask_area & (~weak_protect_area)
|
| 243 |
+
mask_area = cv2.GaussianBlur(mask_area * 255, (kernal_size, kernal_size), 0)
|
| 244 |
+
mask_area[mask_area < 25] = 0
|
| 245 |
+
mask_area[mask_area >= 25] = 1
|
| 246 |
+
mask_area = (mask_area | strong_mask_area) & (~strong_protect_area)
|
| 247 |
+
mask_area = cv2.dilate(mask_area, dilate_kernel, iterations=1)
|
| 248 |
+
|
| 249 |
+
return Image.fromarray(mask_area * 255)
|
| 250 |
+
|
| 251 |
+
def __call__(
|
| 252 |
+
self,
|
| 253 |
+
image: Union[str, Image.Image],
|
| 254 |
+
mask_type: str = "upper",
|
| 255 |
+
):
|
| 256 |
+
assert mask_type in ['upper', 'lower', 'overall', 'inner', 'outer'], f"mask_type should be one of ['upper', 'lower', 'overall', 'inner', 'outer'], but got {mask_type}"
|
| 257 |
+
preprocess_results = self.preprocess_image(image)
|
| 258 |
+
mask = self.cloth_agnostic_mask(
|
| 259 |
+
preprocess_results['densepose'],
|
| 260 |
+
preprocess_results['schp_lip'],
|
| 261 |
+
preprocess_results['schp_atr'],
|
| 262 |
+
part=mask_type,
|
| 263 |
+
)
|
| 264 |
+
return {
|
| 265 |
+
'mask': mask,
|
| 266 |
+
'densepose': preprocess_results['densepose'],
|
| 267 |
+
'schp_lip': preprocess_results['schp_lip'],
|
| 268 |
+
'schp_atr': preprocess_results['schp_atr']
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
if __name__ == '__main__':
|
| 273 |
+
pass
|
flux/pipeline_flux_tryon.py
ADDED
|
@@ -0,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+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers.image_processor import VaeImageProcessor
|
| 7 |
+
from diffusers.loaders import (
|
| 8 |
+
FluxLoraLoaderMixin,
|
| 9 |
+
FromSingleFileMixin,
|
| 10 |
+
TextualInversionLoaderMixin,
|
| 11 |
+
)
|
| 12 |
+
from diffusers.models.autoencoders import AutoencoderKL
|
| 13 |
+
from diffusers.pipelines.flux.pipeline_flux_fill import (
|
| 14 |
+
calculate_shift,
|
| 15 |
+
retrieve_latents,
|
| 16 |
+
retrieve_timesteps,
|
| 17 |
+
)
|
| 18 |
+
from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
|
| 19 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
| 20 |
+
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
|
| 21 |
+
from diffusers.utils import logging
|
| 22 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 23 |
+
|
| 24 |
+
from model.flux.transformer_flux import FluxTransformer2DModel
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 27 |
+
|
| 28 |
+
# Modified from `diffusers.pipelines.flux.pipeline_flux_fill.FluxFillPipeline`
|
| 29 |
+
class FluxTryOnPipeline(
|
| 30 |
+
DiffusionPipeline,
|
| 31 |
+
FluxLoraLoaderMixin,
|
| 32 |
+
FromSingleFileMixin,
|
| 33 |
+
TextualInversionLoaderMixin,
|
| 34 |
+
):
|
| 35 |
+
model_cpu_offload_seq = "transformer->vae"
|
| 36 |
+
_optional_components = []
|
| 37 |
+
_callback_tensor_inputs = ["latents"]
|
| 38 |
+
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
vae: AutoencoderKL,
|
| 42 |
+
scheduler: FlowMatchEulerDiscreteScheduler,
|
| 43 |
+
transformer: FluxTransformer2DModel,
|
| 44 |
+
):
|
| 45 |
+
super().__init__()
|
| 46 |
+
self.register_modules(
|
| 47 |
+
vae=vae,
|
| 48 |
+
scheduler=scheduler,
|
| 49 |
+
transformer=transformer,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
self.vae_scale_factor = (
|
| 53 |
+
2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
# Flux latents are turned into 2x2 patches and packed. This means the latent width and height has to be divisible
|
| 57 |
+
# by the patch size. So the vae scale factor is multiplied by the patch size to account for this
|
| 58 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
|
| 59 |
+
self.mask_processor = VaeImageProcessor(
|
| 60 |
+
vae_scale_factor=self.vae_scale_factor * 2,
|
| 61 |
+
vae_latent_channels=self.vae.config.latent_channels,
|
| 62 |
+
do_normalize=False,
|
| 63 |
+
do_binarize=True,
|
| 64 |
+
do_convert_grayscale=True,
|
| 65 |
+
)
|
| 66 |
+
self.default_sample_size = 128
|
| 67 |
+
|
| 68 |
+
self.transformer.remove_text_layers() # TryOnEdit: remove text layers
|
| 69 |
+
|
| 70 |
+
@classmethod
|
| 71 |
+
def from_pretrained(cls, pretrained_model_name_or_path, subfolder=None, **kwargs):
|
| 72 |
+
transformer = FluxTransformer2DModel.from_pretrained(pretrained_model_name_or_path, subfolder="transformer")
|
| 73 |
+
transformer.remove_text_layers()
|
| 74 |
+
vae = AutoencoderKL.from_pretrained(pretrained_model_name_or_path, subfolder="vae")
|
| 75 |
+
scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(pretrained_model_name_or_path, subfolder="scheduler")
|
| 76 |
+
return FluxTryOnPipeline(vae, scheduler, transformer)
|
| 77 |
+
|
| 78 |
+
def prepare_mask_latents(
|
| 79 |
+
self,
|
| 80 |
+
mask,
|
| 81 |
+
masked_image,
|
| 82 |
+
batch_size,
|
| 83 |
+
num_channels_latents,
|
| 84 |
+
num_images_per_prompt,
|
| 85 |
+
height,
|
| 86 |
+
width,
|
| 87 |
+
dtype,
|
| 88 |
+
device,
|
| 89 |
+
generator,
|
| 90 |
+
):
|
| 91 |
+
# 1. calculate the height and width of the latents
|
| 92 |
+
# VAE applies 8x compression on images but we must also account for packing which requires
|
| 93 |
+
# latent height and width to be divisible by 2.
|
| 94 |
+
height = 2 * (int(height) // (self.vae_scale_factor * 2))
|
| 95 |
+
width = 2 * (int(width) // (self.vae_scale_factor * 2))
|
| 96 |
+
|
| 97 |
+
# 2. encode the masked image
|
| 98 |
+
if masked_image.shape[1] == num_channels_latents:
|
| 99 |
+
masked_image_latents = masked_image
|
| 100 |
+
else:
|
| 101 |
+
masked_image_latents = retrieve_latents(self.vae.encode(masked_image), generator=generator)
|
| 102 |
+
|
| 103 |
+
masked_image_latents = (masked_image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
|
| 104 |
+
masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
|
| 105 |
+
|
| 106 |
+
# 3. duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
|
| 107 |
+
batch_size = batch_size * num_images_per_prompt
|
| 108 |
+
if mask.shape[0] < batch_size:
|
| 109 |
+
if not batch_size % mask.shape[0] == 0:
|
| 110 |
+
raise ValueError(
|
| 111 |
+
"The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
|
| 112 |
+
f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number"
|
| 113 |
+
" of masks that you pass is divisible by the total requested batch size."
|
| 114 |
+
)
|
| 115 |
+
mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
|
| 116 |
+
if masked_image_latents.shape[0] < batch_size:
|
| 117 |
+
if not batch_size % masked_image_latents.shape[0] == 0:
|
| 118 |
+
raise ValueError(
|
| 119 |
+
"The passed images and the required batch size don't match. Images are supposed to be duplicated"
|
| 120 |
+
f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
|
| 121 |
+
" Make sure the number of images that you pass is divisible by the total requested batch size."
|
| 122 |
+
)
|
| 123 |
+
masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1)
|
| 124 |
+
|
| 125 |
+
# 4. pack the masked_image_latents
|
| 126 |
+
# batch_size, num_channels_latents, height, width -> batch_size, height//2 * width//2 , num_channels_latents*4
|
| 127 |
+
masked_image_latents = self._pack_latents(
|
| 128 |
+
masked_image_latents,
|
| 129 |
+
batch_size,
|
| 130 |
+
num_channels_latents,
|
| 131 |
+
height,
|
| 132 |
+
width,
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
# 5.resize mask to latents shape we we concatenate the mask to the latents
|
| 136 |
+
mask = mask[:, 0, :, :] # batch_size, 8 * height, 8 * width (mask has not been 8x compressed)
|
| 137 |
+
mask = mask.view(
|
| 138 |
+
batch_size, height, self.vae_scale_factor, width, self.vae_scale_factor
|
| 139 |
+
) # batch_size, height, 8, width, 8
|
| 140 |
+
mask = mask.permute(0, 2, 4, 1, 3) # batch_size, 8, 8, height, width
|
| 141 |
+
mask = mask.reshape(
|
| 142 |
+
batch_size, self.vae_scale_factor * self.vae_scale_factor, height, width
|
| 143 |
+
) # batch_size, 8*8, height, width
|
| 144 |
+
|
| 145 |
+
# 6. pack the mask:
|
| 146 |
+
# batch_size, 64, height, width -> batch_size, height//2 * width//2 , 64*2*2
|
| 147 |
+
mask = self._pack_latents(
|
| 148 |
+
mask,
|
| 149 |
+
batch_size,
|
| 150 |
+
self.vae_scale_factor * self.vae_scale_factor,
|
| 151 |
+
height,
|
| 152 |
+
width,
|
| 153 |
+
)
|
| 154 |
+
mask = mask.to(device=device, dtype=dtype)
|
| 155 |
+
|
| 156 |
+
return mask, masked_image_latents
|
| 157 |
+
|
| 158 |
+
def check_inputs(
|
| 159 |
+
self,
|
| 160 |
+
height,
|
| 161 |
+
width,
|
| 162 |
+
callback_on_step_end_tensor_inputs=None,
|
| 163 |
+
max_sequence_length=None,
|
| 164 |
+
image=None,
|
| 165 |
+
mask_image=None,
|
| 166 |
+
condition_image=None,
|
| 167 |
+
masked_image_latents=None,
|
| 168 |
+
):
|
| 169 |
+
if height % (self.vae_scale_factor * 2) != 0 or width % (self.vae_scale_factor * 2) != 0:
|
| 170 |
+
logger.warning(
|
| 171 |
+
f"`height` and `width` have to be divisible by {self.vae_scale_factor * 2} but are {height} and {width}. Dimensions will be resized accordingly"
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 175 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 176 |
+
):
|
| 177 |
+
raise ValueError(
|
| 178 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
if max_sequence_length is not None and max_sequence_length > 512:
|
| 182 |
+
raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
|
| 183 |
+
|
| 184 |
+
if image is not None and masked_image_latents is not None:
|
| 185 |
+
raise ValueError(
|
| 186 |
+
"Please provide either `image` or `masked_image_latents`, `masked_image_latents` should not be passed."
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
if image is not None and mask_image is None:
|
| 190 |
+
raise ValueError("Please provide `mask_image` when passing `image`.")
|
| 191 |
+
|
| 192 |
+
if condition_image is None:
|
| 193 |
+
raise ValueError("Please provide `condition_image`.")
|
| 194 |
+
|
| 195 |
+
@staticmethod
|
| 196 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._prepare_latent_image_ids
|
| 197 |
+
def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
|
| 198 |
+
latent_image_ids = torch.zeros(height, width, 3)
|
| 199 |
+
latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height)[:, None]
|
| 200 |
+
latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width)[None, :]
|
| 201 |
+
|
| 202 |
+
latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
|
| 203 |
+
|
| 204 |
+
latent_image_ids = latent_image_ids.reshape(
|
| 205 |
+
latent_image_id_height * latent_image_id_width, latent_image_id_channels
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
return latent_image_ids.to(device=device, dtype=dtype)
|
| 209 |
+
|
| 210 |
+
@staticmethod
|
| 211 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._pack_latents
|
| 212 |
+
def _pack_latents(latents, batch_size, num_channels_latents, height, width):
|
| 213 |
+
latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
|
| 214 |
+
latents = latents.permute(0, 2, 4, 1, 3, 5)
|
| 215 |
+
latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
|
| 216 |
+
|
| 217 |
+
return latents
|
| 218 |
+
|
| 219 |
+
@staticmethod
|
| 220 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._unpack_latents
|
| 221 |
+
def _unpack_latents(latents, height, width, vae_scale_factor):
|
| 222 |
+
batch_size, num_patches, channels = latents.shape
|
| 223 |
+
|
| 224 |
+
# VAE applies 8x compression on images but we must also account for packing which requires
|
| 225 |
+
# latent height and width to be divisible by 2.
|
| 226 |
+
height = 2 * (int(height) // (vae_scale_factor * 2))
|
| 227 |
+
width = 2 * (int(width) // (vae_scale_factor * 2))
|
| 228 |
+
|
| 229 |
+
latents = latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2)
|
| 230 |
+
latents = latents.permute(0, 3, 1, 4, 2, 5)
|
| 231 |
+
|
| 232 |
+
latents = latents.reshape(batch_size, channels // (2 * 2), height, width)
|
| 233 |
+
|
| 234 |
+
return latents
|
| 235 |
+
|
| 236 |
+
def enable_vae_slicing(self):
|
| 237 |
+
r"""
|
| 238 |
+
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
| 239 |
+
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
| 240 |
+
"""
|
| 241 |
+
self.vae.enable_slicing()
|
| 242 |
+
|
| 243 |
+
def disable_vae_slicing(self):
|
| 244 |
+
r"""
|
| 245 |
+
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
|
| 246 |
+
computing decoding in one step.
|
| 247 |
+
"""
|
| 248 |
+
self.vae.disable_slicing()
|
| 249 |
+
|
| 250 |
+
def enable_vae_tiling(self):
|
| 251 |
+
r"""
|
| 252 |
+
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
| 253 |
+
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
| 254 |
+
processing larger images.
|
| 255 |
+
"""
|
| 256 |
+
self.vae.enable_tiling()
|
| 257 |
+
|
| 258 |
+
def disable_vae_tiling(self):
|
| 259 |
+
r"""
|
| 260 |
+
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
|
| 261 |
+
computing decoding in one step.
|
| 262 |
+
"""
|
| 263 |
+
self.vae.disable_tiling()
|
| 264 |
+
|
| 265 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.prepare_latents
|
| 266 |
+
def prepare_latents(
|
| 267 |
+
self,
|
| 268 |
+
batch_size,
|
| 269 |
+
num_channels_latents,
|
| 270 |
+
height,
|
| 271 |
+
width,
|
| 272 |
+
dtype,
|
| 273 |
+
device,
|
| 274 |
+
generator,
|
| 275 |
+
latents=None,
|
| 276 |
+
):
|
| 277 |
+
# VAE applies 8x compression on images but we must also account for packing which requires
|
| 278 |
+
# latent height and width to be divisible by 2.
|
| 279 |
+
height = 2 * (int(height) // (self.vae_scale_factor * 2))
|
| 280 |
+
width = 2 * (int(width) // (self.vae_scale_factor * 2))
|
| 281 |
+
|
| 282 |
+
shape = (batch_size, num_channels_latents, height, width)
|
| 283 |
+
|
| 284 |
+
if latents is not None:
|
| 285 |
+
latent_image_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
|
| 286 |
+
return latents.to(device=device, dtype=dtype), latent_image_ids
|
| 287 |
+
|
| 288 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 289 |
+
raise ValueError(
|
| 290 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 291 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 295 |
+
latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
|
| 296 |
+
|
| 297 |
+
latent_image_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
|
| 298 |
+
|
| 299 |
+
return latents, latent_image_ids
|
| 300 |
+
|
| 301 |
+
@property
|
| 302 |
+
def guidance_scale(self):
|
| 303 |
+
return self._guidance_scale
|
| 304 |
+
|
| 305 |
+
@property
|
| 306 |
+
def joint_attention_kwargs(self):
|
| 307 |
+
return self._joint_attention_kwargs
|
| 308 |
+
|
| 309 |
+
@property
|
| 310 |
+
def num_timesteps(self):
|
| 311 |
+
return self._num_timesteps
|
| 312 |
+
|
| 313 |
+
@property
|
| 314 |
+
def interrupt(self):
|
| 315 |
+
return self._interrupt
|
| 316 |
+
|
| 317 |
+
@torch.no_grad()
|
| 318 |
+
def __call__(
|
| 319 |
+
self,
|
| 320 |
+
image: Optional[torch.FloatTensor] = None,
|
| 321 |
+
condition_image: Optional[torch.FloatTensor] = None, # TryOnEdit: condition image (garment)
|
| 322 |
+
mask_image: Optional[torch.FloatTensor] = None,
|
| 323 |
+
masked_image_latents: Optional[torch.FloatTensor] = None,
|
| 324 |
+
height: Optional[int] = None,
|
| 325 |
+
width: Optional[int] = None,
|
| 326 |
+
num_inference_steps: int = 50,
|
| 327 |
+
sigmas: Optional[List[float]] = None,
|
| 328 |
+
guidance_scale: float = 30.0,
|
| 329 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 330 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 331 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 332 |
+
output_type: Optional[str] = "pil",
|
| 333 |
+
return_dict: bool = True,
|
| 334 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 335 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
| 336 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 337 |
+
max_sequence_length: int = 512,
|
| 338 |
+
):
|
| 339 |
+
height = height or self.default_sample_size * self.vae_scale_factor
|
| 340 |
+
width = width or self.default_sample_size * self.vae_scale_factor
|
| 341 |
+
|
| 342 |
+
# 1. Check inputs. Raise error if not correct
|
| 343 |
+
self.check_inputs(
|
| 344 |
+
height,
|
| 345 |
+
width,
|
| 346 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
| 347 |
+
max_sequence_length=max_sequence_length,
|
| 348 |
+
image=image,
|
| 349 |
+
mask_image=mask_image,
|
| 350 |
+
condition_image=condition_image,
|
| 351 |
+
masked_image_latents=masked_image_latents,
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
self._guidance_scale = guidance_scale
|
| 355 |
+
self._joint_attention_kwargs = joint_attention_kwargs
|
| 356 |
+
self._interrupt = False
|
| 357 |
+
|
| 358 |
+
# 2. Define call parameters
|
| 359 |
+
batch_size = 1
|
| 360 |
+
device = self._execution_device
|
| 361 |
+
dtype = self.transformer.dtype
|
| 362 |
+
|
| 363 |
+
# 3. Prepare prompt embeddings
|
| 364 |
+
lora_scale = (
|
| 365 |
+
self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
# 4. Prepare latent variables
|
| 369 |
+
num_channels_latents = self.vae.config.latent_channels
|
| 370 |
+
latents, latent_image_ids = self.prepare_latents(
|
| 371 |
+
batch_size * num_images_per_prompt,
|
| 372 |
+
num_channels_latents,
|
| 373 |
+
height,
|
| 374 |
+
width * 2, # TryOnEdit: width * 2
|
| 375 |
+
dtype,
|
| 376 |
+
device,
|
| 377 |
+
generator,
|
| 378 |
+
latents,
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
# 5. Prepare mask and masked image latents
|
| 382 |
+
if masked_image_latents is not None:
|
| 383 |
+
masked_image_latents = masked_image_latents.to(latents.device)
|
| 384 |
+
else:
|
| 385 |
+
image = self.image_processor.preprocess(image, height=height, width=width)
|
| 386 |
+
condition_image = self.image_processor.preprocess(condition_image, height=height, width=width)
|
| 387 |
+
mask_image = self.mask_processor.preprocess(mask_image, height=height, width=width)
|
| 388 |
+
|
| 389 |
+
masked_image = image * (1 - mask_image)
|
| 390 |
+
masked_image = masked_image.to(device=device, dtype=dtype)
|
| 391 |
+
|
| 392 |
+
# TryOnEdit: Concat condition image to masked image
|
| 393 |
+
condition_image = condition_image.to(device=device, dtype=dtype)
|
| 394 |
+
masked_image = torch.cat((masked_image, condition_image), dim=-1)
|
| 395 |
+
mask_image = torch.cat((mask_image, torch.zeros_like(mask_image)), dim=-1)
|
| 396 |
+
|
| 397 |
+
height, width = image.shape[-2:]
|
| 398 |
+
mask, masked_image_latents = self.prepare_mask_latents(
|
| 399 |
+
mask_image,
|
| 400 |
+
masked_image,
|
| 401 |
+
batch_size,
|
| 402 |
+
num_channels_latents,
|
| 403 |
+
num_images_per_prompt,
|
| 404 |
+
height,
|
| 405 |
+
width * 2, # TryOnEdit: width * 2
|
| 406 |
+
dtype,
|
| 407 |
+
device,
|
| 408 |
+
generator,
|
| 409 |
+
)
|
| 410 |
+
masked_image_latents = torch.cat((masked_image_latents, mask), dim=-1)
|
| 411 |
+
|
| 412 |
+
# 6. Prepare timesteps
|
| 413 |
+
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
|
| 414 |
+
image_seq_len = latents.shape[1]
|
| 415 |
+
mu = calculate_shift(
|
| 416 |
+
image_seq_len,
|
| 417 |
+
self.scheduler.config.base_image_seq_len,
|
| 418 |
+
self.scheduler.config.max_image_seq_len,
|
| 419 |
+
self.scheduler.config.base_shift,
|
| 420 |
+
self.scheduler.config.max_shift,
|
| 421 |
+
)
|
| 422 |
+
timesteps, num_inference_steps = retrieve_timesteps(
|
| 423 |
+
self.scheduler,
|
| 424 |
+
num_inference_steps,
|
| 425 |
+
device,
|
| 426 |
+
sigmas=sigmas,
|
| 427 |
+
mu=mu,
|
| 428 |
+
)
|
| 429 |
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
| 430 |
+
self._num_timesteps = len(timesteps)
|
| 431 |
+
|
| 432 |
+
# handle guidance
|
| 433 |
+
if self.transformer.config.guidance_embeds:
|
| 434 |
+
guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
|
| 435 |
+
guidance = guidance.expand(latents.shape[0])
|
| 436 |
+
else:
|
| 437 |
+
guidance = None
|
| 438 |
+
|
| 439 |
+
# 7. Denoising loop
|
| 440 |
+
pooled_prompt_embeds = torch.zeros([latents.shape[0], 768], device=device, dtype=dtype) # TryOnEdit: for now, we don't use pooled prompt embeddings
|
| 441 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 442 |
+
for i, t in enumerate(timesteps):
|
| 443 |
+
if self.interrupt:
|
| 444 |
+
continue
|
| 445 |
+
|
| 446 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
| 447 |
+
timestep = t.expand(latents.shape[0]).to(latents.dtype)
|
| 448 |
+
|
| 449 |
+
noise_pred = self.transformer(
|
| 450 |
+
hidden_states=torch.cat((latents, masked_image_latents), dim=2),
|
| 451 |
+
timestep=timestep / 1000,
|
| 452 |
+
guidance=guidance,
|
| 453 |
+
pooled_projections=pooled_prompt_embeds,
|
| 454 |
+
encoder_hidden_states=None,
|
| 455 |
+
txt_ids=None,
|
| 456 |
+
img_ids=latent_image_ids,
|
| 457 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
| 458 |
+
return_dict=False,
|
| 459 |
+
)[0]
|
| 460 |
+
|
| 461 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 462 |
+
latents_dtype = latents.dtype
|
| 463 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
| 464 |
+
|
| 465 |
+
if latents.dtype != latents_dtype:
|
| 466 |
+
if torch.backends.mps.is_available():
|
| 467 |
+
# some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
|
| 468 |
+
latents = latents.to(latents_dtype)
|
| 469 |
+
|
| 470 |
+
if callback_on_step_end is not None:
|
| 471 |
+
callback_kwargs = {}
|
| 472 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 473 |
+
callback_kwargs[k] = locals()[k]
|
| 474 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 475 |
+
|
| 476 |
+
latents = callback_outputs.pop("latents", latents)
|
| 477 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 478 |
+
|
| 479 |
+
# call the callback, if provided
|
| 480 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 481 |
+
progress_bar.update()
|
| 482 |
+
|
| 483 |
+
# 8. Post-process the image
|
| 484 |
+
if output_type == "latent":
|
| 485 |
+
image = latents
|
| 486 |
+
else:
|
| 487 |
+
latents = self._unpack_latents(latents, height, width * 2, self.vae_scale_factor) # TryOnEdit: width * 2
|
| 488 |
+
latents = latents.split(latents.shape[-1] // 2, dim=-1)[0] # TryOnEdit: split along the last dimension
|
| 489 |
+
latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
|
| 490 |
+
image = self.vae.decode(latents, return_dict=False)[0]
|
| 491 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
| 492 |
+
|
| 493 |
+
# Offload all models
|
| 494 |
+
self.maybe_free_model_hooks()
|
| 495 |
+
|
| 496 |
+
if not return_dict:
|
| 497 |
+
return (image,)
|
| 498 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|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
|
| 8 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 9 |
+
from diffusers.models.normalization import AdaLayerNormContinuous, AdaLayerNormZero, AdaLayerNormZeroSingle
|
| 10 |
+
from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
|
| 11 |
+
from diffusers.utils.torch_utils import maybe_allow_in_graph
|
| 12 |
+
from diffusers.models.embeddings import CombinedTimestepGuidanceTextProjEmbeddings, CombinedTimestepTextProjEmbeddings, FluxPosEmbed
|
| 13 |
+
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
| 14 |
+
|
| 15 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 16 |
+
from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
|
| 17 |
+
from diffusers.models.attention import FeedForward
|
| 18 |
+
from diffusers.models.attention_processor import (
|
| 19 |
+
Attention,
|
| 20 |
+
AttentionProcessor,
|
| 21 |
+
FusedFluxAttnProcessor2_0,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# Modified from `diffusers.models.attention_processor.FluxAttnProcessor2_0`
|
| 28 |
+
class FluxAttnProcessor2_0:
|
| 29 |
+
"""Attention processor used typically in processing the SD3-like self-attention projections."""
|
| 30 |
+
|
| 31 |
+
def __init__(self):
|
| 32 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
| 33 |
+
raise ImportError("FluxAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
|
| 34 |
+
|
| 35 |
+
def __call__(
|
| 36 |
+
self,
|
| 37 |
+
attn: Attention,
|
| 38 |
+
hidden_states: torch.FloatTensor,
|
| 39 |
+
encoder_hidden_states: torch.FloatTensor = None,
|
| 40 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 41 |
+
image_rotary_emb: Optional[torch.Tensor] = None,
|
| 42 |
+
) -> torch.FloatTensor:
|
| 43 |
+
batch_size, _, _ = hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 44 |
+
|
| 45 |
+
# `sample` projections.
|
| 46 |
+
query = attn.to_q(hidden_states)
|
| 47 |
+
key = attn.to_k(hidden_states)
|
| 48 |
+
value = attn.to_v(hidden_states)
|
| 49 |
+
|
| 50 |
+
inner_dim = key.shape[-1]
|
| 51 |
+
head_dim = inner_dim // attn.heads
|
| 52 |
+
|
| 53 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 54 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 55 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 56 |
+
|
| 57 |
+
if attn.norm_q is not None:
|
| 58 |
+
query = attn.norm_q(query)
|
| 59 |
+
if attn.norm_k is not None:
|
| 60 |
+
key = attn.norm_k(key)
|
| 61 |
+
|
| 62 |
+
# the attention in FluxSingleTransformerBlock does not use `encoder_hidden_states`
|
| 63 |
+
if encoder_hidden_states is not None:
|
| 64 |
+
# `context` projections.
|
| 65 |
+
encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
|
| 66 |
+
encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
|
| 67 |
+
encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
|
| 68 |
+
|
| 69 |
+
encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
|
| 70 |
+
batch_size, -1, attn.heads, head_dim
|
| 71 |
+
).transpose(1, 2)
|
| 72 |
+
encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
|
| 73 |
+
batch_size, -1, attn.heads, head_dim
|
| 74 |
+
).transpose(1, 2)
|
| 75 |
+
encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
|
| 76 |
+
batch_size, -1, attn.heads, head_dim
|
| 77 |
+
).transpose(1, 2)
|
| 78 |
+
|
| 79 |
+
if attn.norm_added_q is not None:
|
| 80 |
+
encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
|
| 81 |
+
if attn.norm_added_k is not None:
|
| 82 |
+
encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
|
| 83 |
+
|
| 84 |
+
# attention
|
| 85 |
+
query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
|
| 86 |
+
key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
|
| 87 |
+
value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
|
| 88 |
+
|
| 89 |
+
if image_rotary_emb is not None:
|
| 90 |
+
from diffusers.models.embeddings import apply_rotary_emb
|
| 91 |
+
|
| 92 |
+
query = apply_rotary_emb(query, image_rotary_emb)
|
| 93 |
+
key = apply_rotary_emb(key, image_rotary_emb)
|
| 94 |
+
|
| 95 |
+
hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False)
|
| 96 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
| 97 |
+
hidden_states = hidden_states.to(query.dtype)
|
| 98 |
+
|
| 99 |
+
if encoder_hidden_states is not None:
|
| 100 |
+
encoder_hidden_states, hidden_states = (
|
| 101 |
+
hidden_states[:, : encoder_hidden_states.shape[1]],
|
| 102 |
+
hidden_states[:, encoder_hidden_states.shape[1] :],
|
| 103 |
+
)
|
| 104 |
+
encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
|
| 105 |
+
|
| 106 |
+
# edited for try-on
|
| 107 |
+
if not attn.pre_only:
|
| 108 |
+
# linear proj
|
| 109 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 110 |
+
# dropout
|
| 111 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 112 |
+
|
| 113 |
+
if encoder_hidden_states is not None:
|
| 114 |
+
return hidden_states, encoder_hidden_states
|
| 115 |
+
else:
|
| 116 |
+
return hidden_states
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
@maybe_allow_in_graph
|
| 120 |
+
class FluxSingleTransformerBlock(nn.Module):
|
| 121 |
+
r"""
|
| 122 |
+
A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3.
|
| 123 |
+
|
| 124 |
+
Reference: https://arxiv.org/abs/2403.03206
|
| 125 |
+
|
| 126 |
+
Parameters:
|
| 127 |
+
dim (`int`): The number of channels in the input and output.
|
| 128 |
+
num_attention_heads (`int`): The number of heads to use for multi-head attention.
|
| 129 |
+
attention_head_dim (`int`): The number of channels in each head.
|
| 130 |
+
context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the
|
| 131 |
+
processing of `context` conditions.
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
def __init__(self, dim, num_attention_heads, attention_head_dim, mlp_ratio=4.0):
|
| 135 |
+
super().__init__()
|
| 136 |
+
self.mlp_hidden_dim = int(dim * mlp_ratio)
|
| 137 |
+
|
| 138 |
+
self.norm = AdaLayerNormZeroSingle(dim)
|
| 139 |
+
self.proj_mlp = nn.Linear(dim, self.mlp_hidden_dim)
|
| 140 |
+
self.act_mlp = nn.GELU(approximate="tanh")
|
| 141 |
+
self.proj_out = nn.Linear(dim + self.mlp_hidden_dim, dim)
|
| 142 |
+
|
| 143 |
+
processor = FluxAttnProcessor2_0()
|
| 144 |
+
self.attn = Attention(
|
| 145 |
+
query_dim=dim,
|
| 146 |
+
cross_attention_dim=None,
|
| 147 |
+
dim_head=attention_head_dim,
|
| 148 |
+
heads=num_attention_heads,
|
| 149 |
+
out_dim=dim,
|
| 150 |
+
bias=True,
|
| 151 |
+
processor=processor,
|
| 152 |
+
qk_norm="rms_norm",
|
| 153 |
+
eps=1e-6,
|
| 154 |
+
pre_only=True,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
def forward(
|
| 158 |
+
self,
|
| 159 |
+
hidden_states: torch.FloatTensor,
|
| 160 |
+
temb: torch.FloatTensor,
|
| 161 |
+
image_rotary_emb=None,
|
| 162 |
+
joint_attention_kwargs=None,
|
| 163 |
+
):
|
| 164 |
+
residual = hidden_states
|
| 165 |
+
norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
|
| 166 |
+
mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
|
| 167 |
+
joint_attention_kwargs = joint_attention_kwargs or {}
|
| 168 |
+
attn_output = self.attn(
|
| 169 |
+
hidden_states=norm_hidden_states,
|
| 170 |
+
image_rotary_emb=image_rotary_emb,
|
| 171 |
+
**joint_attention_kwargs,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
|
| 175 |
+
gate = gate.unsqueeze(1)
|
| 176 |
+
hidden_states = gate * self.proj_out(hidden_states)
|
| 177 |
+
hidden_states = residual + hidden_states
|
| 178 |
+
if hidden_states.dtype == torch.float16:
|
| 179 |
+
hidden_states = hidden_states.clip(-65504, 65504)
|
| 180 |
+
|
| 181 |
+
return hidden_states
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@maybe_allow_in_graph
|
| 185 |
+
class FluxTransformerBlock(nn.Module):
|
| 186 |
+
r"""
|
| 187 |
+
A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3.
|
| 188 |
+
|
| 189 |
+
Reference: https://arxiv.org/abs/2403.03206
|
| 190 |
+
|
| 191 |
+
Parameters:
|
| 192 |
+
dim (`int`): The number of channels in the input and output.
|
| 193 |
+
num_attention_heads (`int`): The number of heads to use for multi-head attention.
|
| 194 |
+
attention_head_dim (`int`): The number of channels in each head.
|
| 195 |
+
context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the
|
| 196 |
+
processing of `context` conditions.
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
def __init__(self, dim, num_attention_heads, attention_head_dim, qk_norm="rms_norm", eps=1e-6):
|
| 200 |
+
super().__init__()
|
| 201 |
+
|
| 202 |
+
self.norm1 = AdaLayerNormZero(dim)
|
| 203 |
+
|
| 204 |
+
self.norm1_context = AdaLayerNormZero(dim)
|
| 205 |
+
|
| 206 |
+
if hasattr(F, "scaled_dot_product_attention"):
|
| 207 |
+
processor = FluxAttnProcessor2_0()
|
| 208 |
+
else:
|
| 209 |
+
raise ValueError(
|
| 210 |
+
"The current PyTorch version does not support the `scaled_dot_product_attention` function."
|
| 211 |
+
)
|
| 212 |
+
self.attn = Attention(
|
| 213 |
+
query_dim=dim,
|
| 214 |
+
cross_attention_dim=None,
|
| 215 |
+
added_kv_proj_dim=dim,
|
| 216 |
+
dim_head=attention_head_dim,
|
| 217 |
+
heads=num_attention_heads,
|
| 218 |
+
out_dim=dim,
|
| 219 |
+
context_pre_only=False,
|
| 220 |
+
bias=True,
|
| 221 |
+
processor=processor,
|
| 222 |
+
qk_norm=qk_norm,
|
| 223 |
+
eps=eps,
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
|
| 227 |
+
self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
|
| 228 |
+
|
| 229 |
+
self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
|
| 230 |
+
self.ff_context = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
|
| 231 |
+
|
| 232 |
+
# let chunk size default to None
|
| 233 |
+
self._chunk_size = None
|
| 234 |
+
self._chunk_dim = 0
|
| 235 |
+
|
| 236 |
+
def remove_text_layers(self):
|
| 237 |
+
# for try-on, we don't need the text conditioning
|
| 238 |
+
self.norm1_context = None
|
| 239 |
+
self.ff_context = None
|
| 240 |
+
self.norm2_context = None
|
| 241 |
+
self.attn.to_added_qkv = None
|
| 242 |
+
self.attn.norm_added_q = None
|
| 243 |
+
self.attn.norm_added_k = None
|
| 244 |
+
|
| 245 |
+
def forward(
|
| 246 |
+
self,
|
| 247 |
+
hidden_states: torch.FloatTensor,
|
| 248 |
+
encoder_hidden_states: torch.FloatTensor,
|
| 249 |
+
temb: torch.FloatTensor,
|
| 250 |
+
image_rotary_emb=None,
|
| 251 |
+
joint_attention_kwargs=None,
|
| 252 |
+
):
|
| 253 |
+
norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
|
| 254 |
+
|
| 255 |
+
if encoder_hidden_states is not None:
|
| 256 |
+
norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
|
| 257 |
+
encoder_hidden_states, emb=temb
|
| 258 |
+
)
|
| 259 |
+
else:
|
| 260 |
+
norm_encoder_hidden_states = None
|
| 261 |
+
|
| 262 |
+
joint_attention_kwargs = joint_attention_kwargs or {}
|
| 263 |
+
# Attention.
|
| 264 |
+
|
| 265 |
+
outputs = self.attn(
|
| 266 |
+
hidden_states=norm_hidden_states,
|
| 267 |
+
encoder_hidden_states=norm_encoder_hidden_states,
|
| 268 |
+
image_rotary_emb=image_rotary_emb,
|
| 269 |
+
**joint_attention_kwargs,
|
| 270 |
+
)
|
| 271 |
+
if isinstance(outputs, tuple):
|
| 272 |
+
attn_output, context_attn_output = outputs
|
| 273 |
+
else:
|
| 274 |
+
attn_output = outputs
|
| 275 |
+
|
| 276 |
+
# Process attention outputs for the `hidden_states`.
|
| 277 |
+
attn_output = gate_msa.unsqueeze(1) * attn_output
|
| 278 |
+
hidden_states = hidden_states + attn_output
|
| 279 |
+
|
| 280 |
+
norm_hidden_states = self.norm2(hidden_states)
|
| 281 |
+
norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
|
| 282 |
+
|
| 283 |
+
ff_output = self.ff(norm_hidden_states)
|
| 284 |
+
ff_output = gate_mlp.unsqueeze(1) * ff_output
|
| 285 |
+
|
| 286 |
+
hidden_states = hidden_states + ff_output
|
| 287 |
+
|
| 288 |
+
# Process attention outputs for the `encoder_hidden_states`.
|
| 289 |
+
if encoder_hidden_states is not None:
|
| 290 |
+
context_attn_output = c_gate_msa.unsqueeze(1) * context_attn_output
|
| 291 |
+
encoder_hidden_states = encoder_hidden_states + context_attn_output
|
| 292 |
+
|
| 293 |
+
norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
|
| 294 |
+
norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
|
| 295 |
+
|
| 296 |
+
context_ff_output = self.ff_context(norm_encoder_hidden_states)
|
| 297 |
+
encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
|
| 298 |
+
if encoder_hidden_states.dtype == torch.float16:
|
| 299 |
+
encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504)
|
| 300 |
+
|
| 301 |
+
return encoder_hidden_states, hidden_states
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class FluxTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
|
| 305 |
+
"""
|
| 306 |
+
The Transformer model introduced in Flux.
|
| 307 |
+
|
| 308 |
+
Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
|
| 309 |
+
|
| 310 |
+
Parameters:
|
| 311 |
+
patch_size (`int`): Patch size to turn the input data into small patches.
|
| 312 |
+
in_channels (`int`, *optional*, defaults to 16): The number of channels in the input.
|
| 313 |
+
num_layers (`int`, *optional*, defaults to 18): The number of layers of MMDiT blocks to use.
|
| 314 |
+
num_single_layers (`int`, *optional*, defaults to 18): The number of layers of single DiT blocks to use.
|
| 315 |
+
attention_head_dim (`int`, *optional*, defaults to 64): The number of channels in each head.
|
| 316 |
+
num_attention_heads (`int`, *optional*, defaults to 18): The number of heads to use for multi-head attention.
|
| 317 |
+
joint_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
|
| 318 |
+
pooled_projection_dim (`int`): Number of dimensions to use when projecting the `pooled_projections`.
|
| 319 |
+
guidance_embeds (`bool`, defaults to False): Whether to use guidance embeddings.
|
| 320 |
+
"""
|
| 321 |
+
|
| 322 |
+
_supports_gradient_checkpointing = True
|
| 323 |
+
_no_split_modules = ["FluxTransformerBlock", "FluxSingleTransformerBlock"]
|
| 324 |
+
|
| 325 |
+
@register_to_config
|
| 326 |
+
def __init__(
|
| 327 |
+
self,
|
| 328 |
+
patch_size: int = 1,
|
| 329 |
+
in_channels: int = 64,
|
| 330 |
+
out_channels: Optional[int] = None,
|
| 331 |
+
num_layers: int = 19,
|
| 332 |
+
num_single_layers: int = 38,
|
| 333 |
+
attention_head_dim: int = 128,
|
| 334 |
+
num_attention_heads: int = 24,
|
| 335 |
+
joint_attention_dim: int = 4096,
|
| 336 |
+
pooled_projection_dim: int = 768,
|
| 337 |
+
guidance_embeds: bool = False,
|
| 338 |
+
axes_dims_rope: Tuple[int] = (16, 56, 56),
|
| 339 |
+
):
|
| 340 |
+
super().__init__()
|
| 341 |
+
self.out_channels = out_channels or in_channels
|
| 342 |
+
self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim
|
| 343 |
+
|
| 344 |
+
self.pos_embed = FluxPosEmbed(theta=10000, axes_dim=axes_dims_rope)
|
| 345 |
+
|
| 346 |
+
text_time_guidance_cls = (
|
| 347 |
+
CombinedTimestepGuidanceTextProjEmbeddings if guidance_embeds else CombinedTimestepTextProjEmbeddings
|
| 348 |
+
)
|
| 349 |
+
self.time_text_embed = text_time_guidance_cls(
|
| 350 |
+
embedding_dim=self.inner_dim, pooled_projection_dim=self.config.pooled_projection_dim
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
self.context_embedder = nn.Linear(self.config.joint_attention_dim, self.inner_dim)
|
| 354 |
+
self.x_embedder = torch.nn.Linear(self.config.in_channels, self.inner_dim)
|
| 355 |
+
|
| 356 |
+
self.transformer_blocks = nn.ModuleList(
|
| 357 |
+
[
|
| 358 |
+
FluxTransformerBlock(
|
| 359 |
+
dim=self.inner_dim,
|
| 360 |
+
num_attention_heads=self.config.num_attention_heads,
|
| 361 |
+
attention_head_dim=self.config.attention_head_dim,
|
| 362 |
+
)
|
| 363 |
+
for i in range(self.config.num_layers)
|
| 364 |
+
]
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
self.single_transformer_blocks = nn.ModuleList(
|
| 368 |
+
[
|
| 369 |
+
FluxSingleTransformerBlock(
|
| 370 |
+
dim=self.inner_dim,
|
| 371 |
+
num_attention_heads=self.config.num_attention_heads,
|
| 372 |
+
attention_head_dim=self.config.attention_head_dim,
|
| 373 |
+
)
|
| 374 |
+
for i in range(self.config.num_single_layers)
|
| 375 |
+
]
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
|
| 379 |
+
self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
|
| 380 |
+
|
| 381 |
+
self.gradient_checkpointing = False
|
| 382 |
+
|
| 383 |
+
@property
|
| 384 |
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
|
| 385 |
+
def attn_processors(self) -> Dict[str, AttentionProcessor]:
|
| 386 |
+
r"""
|
| 387 |
+
Returns:
|
| 388 |
+
`dict` of attention processors: A dictionary containing all attention processors used in the model with
|
| 389 |
+
indexed by its weight name.
|
| 390 |
+
"""
|
| 391 |
+
# set recursively
|
| 392 |
+
processors = {}
|
| 393 |
+
|
| 394 |
+
def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
|
| 395 |
+
if hasattr(module, "get_processor"):
|
| 396 |
+
processors[f"{name}.processor"] = module.get_processor()
|
| 397 |
+
|
| 398 |
+
for sub_name, child in module.named_children():
|
| 399 |
+
fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
|
| 400 |
+
|
| 401 |
+
return processors
|
| 402 |
+
|
| 403 |
+
for name, module in self.named_children():
|
| 404 |
+
fn_recursive_add_processors(name, module, processors)
|
| 405 |
+
|
| 406 |
+
return processors
|
| 407 |
+
|
| 408 |
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
|
| 409 |
+
def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
|
| 410 |
+
r"""
|
| 411 |
+
Sets the attention processor to use to compute attention.
|
| 412 |
+
|
| 413 |
+
Parameters:
|
| 414 |
+
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
|
| 415 |
+
The instantiated processor class or a dictionary of processor classes that will be set as the processor
|
| 416 |
+
for **all** `Attention` layers.
|
| 417 |
+
|
| 418 |
+
If `processor` is a dict, the key needs to define the path to the corresponding cross attention
|
| 419 |
+
processor. This is strongly recommended when setting trainable attention processors.
|
| 420 |
+
|
| 421 |
+
"""
|
| 422 |
+
count = len(self.attn_processors.keys())
|
| 423 |
+
|
| 424 |
+
if isinstance(processor, dict) and len(processor) != count:
|
| 425 |
+
raise ValueError(
|
| 426 |
+
f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
|
| 427 |
+
f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
|
| 431 |
+
if hasattr(module, "set_processor"):
|
| 432 |
+
if not isinstance(processor, dict):
|
| 433 |
+
module.set_processor(processor)
|
| 434 |
+
else:
|
| 435 |
+
module.set_processor(processor.pop(f"{name}.processor"))
|
| 436 |
+
|
| 437 |
+
for sub_name, child in module.named_children():
|
| 438 |
+
fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
|
| 439 |
+
|
| 440 |
+
for name, module in self.named_children():
|
| 441 |
+
fn_recursive_attn_processor(name, module, processor)
|
| 442 |
+
|
| 443 |
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections with FusedAttnProcessor2_0->FusedFluxAttnProcessor2_0
|
| 444 |
+
def fuse_qkv_projections(self):
|
| 445 |
+
"""
|
| 446 |
+
Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
|
| 447 |
+
are fused. For cross-attention modules, key and value projection matrices are fused.
|
| 448 |
+
|
| 449 |
+
<Tip warning={true}>
|
| 450 |
+
|
| 451 |
+
This API is 🧪 experimental.
|
| 452 |
+
|
| 453 |
+
</Tip>
|
| 454 |
+
"""
|
| 455 |
+
self.original_attn_processors = None
|
| 456 |
+
|
| 457 |
+
for _, attn_processor in self.attn_processors.items():
|
| 458 |
+
if "Added" in str(attn_processor.__class__.__name__):
|
| 459 |
+
raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
|
| 460 |
+
|
| 461 |
+
self.original_attn_processors = self.attn_processors
|
| 462 |
+
|
| 463 |
+
for module in self.modules():
|
| 464 |
+
if isinstance(module, Attention):
|
| 465 |
+
module.fuse_projections(fuse=True)
|
| 466 |
+
|
| 467 |
+
self.set_attn_processor(FusedFluxAttnProcessor2_0())
|
| 468 |
+
|
| 469 |
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
|
| 470 |
+
def unfuse_qkv_projections(self):
|
| 471 |
+
"""Disables the fused QKV projection if enabled.
|
| 472 |
+
|
| 473 |
+
<Tip warning={true}>
|
| 474 |
+
|
| 475 |
+
This API is 🧪 experimental.
|
| 476 |
+
|
| 477 |
+
</Tip>
|
| 478 |
+
|
| 479 |
+
"""
|
| 480 |
+
if self.original_attn_processors is not None:
|
| 481 |
+
self.set_attn_processor(self.original_attn_processors)
|
| 482 |
+
|
| 483 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 484 |
+
if hasattr(module, "gradient_checkpointing"):
|
| 485 |
+
module.gradient_checkpointing = value
|
| 486 |
+
|
| 487 |
+
def remove_text_layers(self):
|
| 488 |
+
self.context_embedder = None
|
| 489 |
+
for transformer_block in self.transformer_blocks:
|
| 490 |
+
transformer_block.remove_text_layers()
|
| 491 |
+
|
| 492 |
+
def forward(
|
| 493 |
+
self,
|
| 494 |
+
hidden_states: torch.Tensor,
|
| 495 |
+
encoder_hidden_states: torch.Tensor = None,
|
| 496 |
+
condition_hidden_states: torch.Tensor = None,
|
| 497 |
+
pooled_projections: torch.Tensor = None,
|
| 498 |
+
timestep: torch.LongTensor = None,
|
| 499 |
+
img_ids: torch.Tensor = None,
|
| 500 |
+
txt_ids: torch.Tensor = None,
|
| 501 |
+
guidance: torch.Tensor = None,
|
| 502 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 503 |
+
controlnet_block_samples=None,
|
| 504 |
+
controlnet_single_block_samples=None,
|
| 505 |
+
return_dict: bool = True,
|
| 506 |
+
controlnet_blocks_repeat: bool = False,
|
| 507 |
+
) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
|
| 508 |
+
"""
|
| 509 |
+
The [`FluxTransformer2DModel`] forward method.
|
| 510 |
+
|
| 511 |
+
Args:
|
| 512 |
+
hidden_states (`torch.FloatTensor` of shape `(batch size, channel, height, width)`):
|
| 513 |
+
Input `hidden_states`.
|
| 514 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch size, sequence_len, embed_dims)`):
|
| 515 |
+
Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
|
| 516 |
+
pooled_projections (`torch.FloatTensor` of shape `(batch_size, projection_dim)`): Embeddings projected
|
| 517 |
+
from the embeddings of input conditions.
|
| 518 |
+
timestep ( `torch.LongTensor`):
|
| 519 |
+
Used to indicate denoising step.
|
| 520 |
+
block_controlnet_hidden_states: (`list` of `torch.Tensor`):
|
| 521 |
+
A list of tensors that if specified are added to the residuals of transformer blocks.
|
| 522 |
+
joint_attention_kwargs (`dict`, *optional*):
|
| 523 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 524 |
+
`self.processor` in
|
| 525 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 526 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 527 |
+
Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
|
| 528 |
+
tuple.
|
| 529 |
+
|
| 530 |
+
Returns:
|
| 531 |
+
If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
|
| 532 |
+
`tuple` where the first element is the sample tensor.
|
| 533 |
+
"""
|
| 534 |
+
if joint_attention_kwargs is not None:
|
| 535 |
+
joint_attention_kwargs = joint_attention_kwargs.copy()
|
| 536 |
+
lora_scale = joint_attention_kwargs.pop("scale", 1.0)
|
| 537 |
+
else:
|
| 538 |
+
lora_scale = 1.0
|
| 539 |
+
|
| 540 |
+
if USE_PEFT_BACKEND:
|
| 541 |
+
# weight the lora layers by setting `lora_scale` for each PEFT layer
|
| 542 |
+
scale_lora_layers(self, lora_scale)
|
| 543 |
+
else:
|
| 544 |
+
if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
|
| 545 |
+
logger.warning(
|
| 546 |
+
"Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
hidden_states = self.x_embedder(hidden_states)
|
| 550 |
+
|
| 551 |
+
timestep = timestep.to(hidden_states.dtype) * 1000
|
| 552 |
+
guidance = guidance.to(hidden_states.dtype) * 1000 if guidance is not None else None
|
| 553 |
+
|
| 554 |
+
temb = self.time_text_embed(timestep, pooled_projections) if guidance is None else self.time_text_embed(timestep, guidance, pooled_projections)
|
| 555 |
+
|
| 556 |
+
if encoder_hidden_states is not None:
|
| 557 |
+
encoder_hidden_states = self.context_embedder(encoder_hidden_states)
|
| 558 |
+
|
| 559 |
+
ids = torch.cat((txt_ids, img_ids), dim=0) if txt_ids is not None else img_ids # for try-on, we don't need txt_ids
|
| 560 |
+
image_rotary_emb = self.pos_embed(ids)
|
| 561 |
+
|
| 562 |
+
# MMDiT Blocks
|
| 563 |
+
for index_block, block in enumerate(self.transformer_blocks):
|
| 564 |
+
if self.training and self.gradient_checkpointing:
|
| 565 |
+
def create_custom_forward(module, return_dict=None):
|
| 566 |
+
def custom_forward(*inputs):
|
| 567 |
+
if return_dict is not None:
|
| 568 |
+
return module(*inputs, return_dict=return_dict)
|
| 569 |
+
else:
|
| 570 |
+
return module(*inputs)
|
| 571 |
+
|
| 572 |
+
return custom_forward
|
| 573 |
+
|
| 574 |
+
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
| 575 |
+
result = torch.utils.checkpoint.checkpoint(
|
| 576 |
+
create_custom_forward(block),
|
| 577 |
+
hidden_states,
|
| 578 |
+
encoder_hidden_states,
|
| 579 |
+
temb,
|
| 580 |
+
image_rotary_emb,
|
| 581 |
+
**ckpt_kwargs,
|
| 582 |
+
)
|
| 583 |
+
if isinstance(result, tuple):
|
| 584 |
+
encoder_hidden_states, hidden_states = result
|
| 585 |
+
else:
|
| 586 |
+
hidden_states = result
|
| 587 |
+
|
| 588 |
+
else:
|
| 589 |
+
result = block(
|
| 590 |
+
hidden_states=hidden_states,
|
| 591 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 592 |
+
temb=temb,
|
| 593 |
+
image_rotary_emb=image_rotary_emb,
|
| 594 |
+
joint_attention_kwargs=joint_attention_kwargs,
|
| 595 |
+
)
|
| 596 |
+
if isinstance(result, tuple):
|
| 597 |
+
encoder_hidden_states, hidden_states = result
|
| 598 |
+
else:
|
| 599 |
+
hidden_states = result
|
| 600 |
+
|
| 601 |
+
# Condition residual (for try-on pose conditioning)
|
| 602 |
+
if condition_hidden_states is not None and index_block == 0:
|
| 603 |
+
hidden_states = hidden_states + condition_hidden_states
|
| 604 |
+
|
| 605 |
+
# controlnet residual
|
| 606 |
+
if controlnet_block_samples is not None:
|
| 607 |
+
interval_control = len(self.transformer_blocks) / len(controlnet_block_samples)
|
| 608 |
+
interval_control = int(np.ceil(interval_control))
|
| 609 |
+
# For Xlabs ControlNet.
|
| 610 |
+
if controlnet_blocks_repeat:
|
| 611 |
+
hidden_states = (
|
| 612 |
+
hidden_states + controlnet_block_samples[index_block % len(controlnet_block_samples)]
|
| 613 |
+
)
|
| 614 |
+
else:
|
| 615 |
+
hidden_states = hidden_states + controlnet_block_samples[index_block // interval_control]
|
| 616 |
+
|
| 617 |
+
if encoder_hidden_states is not None:
|
| 618 |
+
hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
|
| 619 |
+
|
| 620 |
+
# Single DiT Blocks
|
| 621 |
+
for index_block, block in enumerate(self.single_transformer_blocks):
|
| 622 |
+
if self.training and self.gradient_checkpointing:
|
| 623 |
+
|
| 624 |
+
def create_custom_forward(module, return_dict=None):
|
| 625 |
+
def custom_forward(*inputs):
|
| 626 |
+
if return_dict is not None:
|
| 627 |
+
return module(*inputs, return_dict=return_dict)
|
| 628 |
+
else:
|
| 629 |
+
return module(*inputs)
|
| 630 |
+
|
| 631 |
+
return custom_forward
|
| 632 |
+
|
| 633 |
+
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
| 634 |
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
| 635 |
+
create_custom_forward(block),
|
| 636 |
+
hidden_states,
|
| 637 |
+
temb,
|
| 638 |
+
image_rotary_emb,
|
| 639 |
+
**ckpt_kwargs,
|
| 640 |
+
)
|
| 641 |
+
|
| 642 |
+
else:
|
| 643 |
+
hidden_states = block(
|
| 644 |
+
hidden_states=hidden_states,
|
| 645 |
+
temb=temb,
|
| 646 |
+
image_rotary_emb=image_rotary_emb,
|
| 647 |
+
joint_attention_kwargs=joint_attention_kwargs,
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
# controlnet residual
|
| 651 |
+
if controlnet_single_block_samples is not None:
|
| 652 |
+
interval_control = len(self.single_transformer_blocks) / len(controlnet_single_block_samples)
|
| 653 |
+
interval_control = int(np.ceil(interval_control))
|
| 654 |
+
hidden_states[:, encoder_hidden_states.shape[1] :, ...] = (
|
| 655 |
+
hidden_states[:, encoder_hidden_states.shape[1] :, ...]
|
| 656 |
+
+ controlnet_single_block_samples[index_block // interval_control]
|
| 657 |
+
)
|
| 658 |
+
|
| 659 |
+
if encoder_hidden_states is not None:
|
| 660 |
+
hidden_states = hidden_states[:, encoder_hidden_states.shape[1] :, ...]
|
| 661 |
+
|
| 662 |
+
hidden_states = self.norm_out(hidden_states, temb)
|
| 663 |
+
output = self.proj_out(hidden_states)
|
| 664 |
+
|
| 665 |
+
if USE_PEFT_BACKEND:
|
| 666 |
+
# remove `lora_scale` from each PEFT layer
|
| 667 |
+
unscale_lora_layers(self, lora_scale)
|
| 668 |
+
|
| 669 |
+
if not return_dict:
|
| 670 |
+
return (output,)
|
| 671 |
+
|
| 672 |
+
return Transformer2DModelOutput(sample=output)
|
pipeline.py
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import os
|
| 3 |
+
from typing import Union
|
| 4 |
+
|
| 5 |
+
import PIL
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
import tqdm
|
| 9 |
+
from accelerate import load_checkpoint_in_model
|
| 10 |
+
from diffusers import AutoencoderKL, DDIMScheduler, UNet2DConditionModel
|
| 11 |
+
from diffusers.pipelines.stable_diffusion.safety_checker import \
|
| 12 |
+
StableDiffusionSafetyChecker
|
| 13 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 14 |
+
from huggingface_hub import snapshot_download
|
| 15 |
+
from transformers import CLIPImageProcessor
|
| 16 |
+
|
| 17 |
+
from model.attn_processor import SkipAttnProcessor
|
| 18 |
+
from model.utils import get_trainable_module, init_adapter
|
| 19 |
+
from utils import (compute_vae_encodings, numpy_to_pil, prepare_image,
|
| 20 |
+
prepare_mask_image, resize_and_crop, resize_and_padding)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class CatVTONPipeline:
|
| 24 |
+
def __init__(
|
| 25 |
+
self,
|
| 26 |
+
base_ckpt,
|
| 27 |
+
attn_ckpt,
|
| 28 |
+
attn_ckpt_version="mix",
|
| 29 |
+
weight_dtype=torch.float32,
|
| 30 |
+
device='cuda',
|
| 31 |
+
compile=False,
|
| 32 |
+
skip_safety_check=False,
|
| 33 |
+
use_tf32=True,
|
| 34 |
+
):
|
| 35 |
+
self.device = device
|
| 36 |
+
self.weight_dtype = weight_dtype
|
| 37 |
+
self.skip_safety_check = skip_safety_check
|
| 38 |
+
|
| 39 |
+
self.noise_scheduler = DDIMScheduler.from_pretrained(base_ckpt, subfolder="scheduler")
|
| 40 |
+
self.vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse").to(device, dtype=weight_dtype)
|
| 41 |
+
if not skip_safety_check:
|
| 42 |
+
self.feature_extractor = CLIPImageProcessor.from_pretrained(base_ckpt, subfolder="feature_extractor")
|
| 43 |
+
self.safety_checker = StableDiffusionSafetyChecker.from_pretrained(base_ckpt, subfolder="safety_checker").to(device, dtype=weight_dtype)
|
| 44 |
+
self.unet = UNet2DConditionModel.from_pretrained(base_ckpt, subfolder="unet").to(device, dtype=weight_dtype)
|
| 45 |
+
init_adapter(self.unet, cross_attn_cls=SkipAttnProcessor) # Skip Cross-Attention
|
| 46 |
+
self.attn_modules = get_trainable_module(self.unet, "attention")
|
| 47 |
+
self.auto_attn_ckpt_load(attn_ckpt, attn_ckpt_version)
|
| 48 |
+
# Pytorch 2.0 Compile
|
| 49 |
+
if compile:
|
| 50 |
+
self.unet = torch.compile(self.unet)
|
| 51 |
+
self.vae = torch.compile(self.vae, mode="reduce-overhead")
|
| 52 |
+
|
| 53 |
+
# Enable TF32 for faster training on Ampere GPUs (A100 and RTX 30 series).
|
| 54 |
+
if use_tf32:
|
| 55 |
+
torch.set_float32_matmul_precision("high")
|
| 56 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 57 |
+
|
| 58 |
+
def auto_attn_ckpt_load(self, attn_ckpt, version):
|
| 59 |
+
sub_folder = {
|
| 60 |
+
"mix": "mix-48k-1024",
|
| 61 |
+
"vitonhd": "vitonhd-16k-512",
|
| 62 |
+
"dresscode": "dresscode-16k-512",
|
| 63 |
+
}[version]
|
| 64 |
+
if os.path.exists(attn_ckpt):
|
| 65 |
+
load_checkpoint_in_model(self.attn_modules, os.path.join(attn_ckpt, sub_folder, 'attention'))
|
| 66 |
+
else:
|
| 67 |
+
repo_path = snapshot_download(repo_id=attn_ckpt)
|
| 68 |
+
print(f"Downloaded {attn_ckpt} to {repo_path}")
|
| 69 |
+
load_checkpoint_in_model(self.attn_modules, os.path.join(repo_path, sub_folder, 'attention'))
|
| 70 |
+
|
| 71 |
+
def run_safety_checker(self, image):
|
| 72 |
+
if self.safety_checker is None:
|
| 73 |
+
has_nsfw_concept = None
|
| 74 |
+
else:
|
| 75 |
+
safety_checker_input = self.feature_extractor(image, return_tensors="pt").to(self.device)
|
| 76 |
+
image, has_nsfw_concept = self.safety_checker(
|
| 77 |
+
images=image, clip_input=safety_checker_input.pixel_values.to(self.weight_dtype)
|
| 78 |
+
)
|
| 79 |
+
return image, has_nsfw_concept
|
| 80 |
+
|
| 81 |
+
def check_inputs(self, image, condition_image, mask, width, height):
|
| 82 |
+
if isinstance(image, torch.Tensor) and isinstance(condition_image, torch.Tensor) and isinstance(mask, torch.Tensor):
|
| 83 |
+
return image, condition_image, mask
|
| 84 |
+
assert image.size == mask.size, "Image and mask must have the same size"
|
| 85 |
+
image = resize_and_crop(image, (width, height))
|
| 86 |
+
mask = resize_and_crop(mask, (width, height))
|
| 87 |
+
condition_image = resize_and_padding(condition_image, (width, height))
|
| 88 |
+
return image, condition_image, mask
|
| 89 |
+
|
| 90 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
| 91 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 92 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 93 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 94 |
+
# and should be between [0, 1]
|
| 95 |
+
|
| 96 |
+
accepts_eta = "eta" in set(
|
| 97 |
+
inspect.signature(self.noise_scheduler.step).parameters.keys()
|
| 98 |
+
)
|
| 99 |
+
extra_step_kwargs = {}
|
| 100 |
+
if accepts_eta:
|
| 101 |
+
extra_step_kwargs["eta"] = eta
|
| 102 |
+
|
| 103 |
+
# check if the scheduler accepts generator
|
| 104 |
+
accepts_generator = "generator" in set(
|
| 105 |
+
inspect.signature(self.noise_scheduler.step).parameters.keys()
|
| 106 |
+
)
|
| 107 |
+
if accepts_generator:
|
| 108 |
+
extra_step_kwargs["generator"] = generator
|
| 109 |
+
return extra_step_kwargs
|
| 110 |
+
|
| 111 |
+
@torch.no_grad()
|
| 112 |
+
def __call__(
|
| 113 |
+
self,
|
| 114 |
+
image: Union[PIL.Image.Image, torch.Tensor],
|
| 115 |
+
condition_image: Union[PIL.Image.Image, torch.Tensor],
|
| 116 |
+
mask: Union[PIL.Image.Image, torch.Tensor],
|
| 117 |
+
num_inference_steps: int = 50,
|
| 118 |
+
guidance_scale: float = 2.5,
|
| 119 |
+
height: int = 1024,
|
| 120 |
+
width: int = 768,
|
| 121 |
+
generator=None,
|
| 122 |
+
eta=1.0,
|
| 123 |
+
**kwargs
|
| 124 |
+
):
|
| 125 |
+
concat_dim = -2 # FIXME: y axis concat
|
| 126 |
+
# Prepare inputs to Tensor
|
| 127 |
+
image, condition_image, mask = self.check_inputs(image, condition_image, mask, width, height)
|
| 128 |
+
image = prepare_image(image).to(self.device, dtype=self.weight_dtype)
|
| 129 |
+
condition_image = prepare_image(condition_image).to(self.device, dtype=self.weight_dtype)
|
| 130 |
+
mask = prepare_mask_image(mask).to(self.device, dtype=self.weight_dtype)
|
| 131 |
+
# Mask image
|
| 132 |
+
masked_image = image * (mask < 0.5)
|
| 133 |
+
# VAE encoding
|
| 134 |
+
masked_latent = compute_vae_encodings(masked_image, self.vae)
|
| 135 |
+
condition_latent = compute_vae_encodings(condition_image, self.vae)
|
| 136 |
+
mask_latent = torch.nn.functional.interpolate(mask, size=masked_latent.shape[-2:], mode="nearest")
|
| 137 |
+
del image, mask, condition_image
|
| 138 |
+
# Concatenate latents
|
| 139 |
+
masked_latent_concat = torch.cat([masked_latent, condition_latent], dim=concat_dim)
|
| 140 |
+
mask_latent_concat = torch.cat([mask_latent, torch.zeros_like(mask_latent)], dim=concat_dim)
|
| 141 |
+
# Prepare noise
|
| 142 |
+
latents = randn_tensor(
|
| 143 |
+
masked_latent_concat.shape,
|
| 144 |
+
generator=generator,
|
| 145 |
+
device=masked_latent_concat.device,
|
| 146 |
+
dtype=self.weight_dtype,
|
| 147 |
+
)
|
| 148 |
+
# Prepare timesteps
|
| 149 |
+
self.noise_scheduler.set_timesteps(num_inference_steps, device=self.device)
|
| 150 |
+
timesteps = self.noise_scheduler.timesteps
|
| 151 |
+
latents = latents * self.noise_scheduler.init_noise_sigma
|
| 152 |
+
# Classifier-Free Guidance
|
| 153 |
+
if do_classifier_free_guidance := (guidance_scale > 1.0):
|
| 154 |
+
masked_latent_concat = torch.cat(
|
| 155 |
+
[
|
| 156 |
+
torch.cat([masked_latent, torch.zeros_like(condition_latent)], dim=concat_dim),
|
| 157 |
+
masked_latent_concat,
|
| 158 |
+
]
|
| 159 |
+
)
|
| 160 |
+
mask_latent_concat = torch.cat([mask_latent_concat] * 2)
|
| 161 |
+
|
| 162 |
+
# Denoising loop
|
| 163 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 164 |
+
num_warmup_steps = (len(timesteps) - num_inference_steps * self.noise_scheduler.order)
|
| 165 |
+
with tqdm.tqdm(total=num_inference_steps) as progress_bar:
|
| 166 |
+
for i, t in enumerate(timesteps):
|
| 167 |
+
# expand the latents if we are doing classifier free guidance
|
| 168 |
+
non_inpainting_latent_model_input = (torch.cat([latents] * 2) if do_classifier_free_guidance else latents)
|
| 169 |
+
non_inpainting_latent_model_input = self.noise_scheduler.scale_model_input(non_inpainting_latent_model_input, t)
|
| 170 |
+
# prepare the input for the inpainting model
|
| 171 |
+
inpainting_latent_model_input = torch.cat([non_inpainting_latent_model_input, mask_latent_concat, masked_latent_concat], dim=1)
|
| 172 |
+
# predict the noise residual
|
| 173 |
+
noise_pred= self.unet(
|
| 174 |
+
inpainting_latent_model_input,
|
| 175 |
+
t.to(self.device),
|
| 176 |
+
encoder_hidden_states=None, # FIXME
|
| 177 |
+
return_dict=False,
|
| 178 |
+
)[0]
|
| 179 |
+
# perform guidance
|
| 180 |
+
if do_classifier_free_guidance:
|
| 181 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 182 |
+
noise_pred = noise_pred_uncond + guidance_scale * (
|
| 183 |
+
noise_pred_text - noise_pred_uncond
|
| 184 |
+
)
|
| 185 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 186 |
+
latents = self.noise_scheduler.step(
|
| 187 |
+
noise_pred, t, latents, **extra_step_kwargs
|
| 188 |
+
).prev_sample
|
| 189 |
+
# call the callback, if provided
|
| 190 |
+
if i == len(timesteps) - 1 or (
|
| 191 |
+
(i + 1) > num_warmup_steps
|
| 192 |
+
and (i + 1) % self.noise_scheduler.order == 0
|
| 193 |
+
):
|
| 194 |
+
progress_bar.update()
|
| 195 |
+
|
| 196 |
+
# Decode the final latents
|
| 197 |
+
latents = latents.split(latents.shape[concat_dim] // 2, dim=concat_dim)[0]
|
| 198 |
+
latents = 1 / self.vae.config.scaling_factor * latents
|
| 199 |
+
image = self.vae.decode(latents.to(self.device, dtype=self.weight_dtype)).sample
|
| 200 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 201 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
| 202 |
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 203 |
+
image = numpy_to_pil(image)
|
| 204 |
+
|
| 205 |
+
# Safety Check
|
| 206 |
+
if not self.skip_safety_check:
|
| 207 |
+
current_script_directory = os.path.dirname(os.path.realpath(__file__))
|
| 208 |
+
nsfw_image = os.path.join(os.path.dirname(current_script_directory), 'resource', 'img', 'NSFW.jpg')
|
| 209 |
+
nsfw_image = PIL.Image.open(nsfw_image).resize(image[0].size)
|
| 210 |
+
image_np = np.array(image)
|
| 211 |
+
_, has_nsfw_concept = self.run_safety_checker(image=image_np)
|
| 212 |
+
for i, not_safe in enumerate(has_nsfw_concept):
|
| 213 |
+
if not_safe:
|
| 214 |
+
image[i] = nsfw_image
|
| 215 |
+
return image
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class CatVTONPix2PixPipeline(CatVTONPipeline):
|
| 219 |
+
def auto_attn_ckpt_load(self, attn_ckpt, version):
|
| 220 |
+
# TODO: Temperal fix for the model version
|
| 221 |
+
if os.path.exists(attn_ckpt):
|
| 222 |
+
load_checkpoint_in_model(self.attn_modules, os.path.join(attn_ckpt, version, 'attention'))
|
| 223 |
+
else:
|
| 224 |
+
repo_path = snapshot_download(repo_id=attn_ckpt)
|
| 225 |
+
print(f"Downloaded {attn_ckpt} to {repo_path}")
|
| 226 |
+
load_checkpoint_in_model(self.attn_modules, os.path.join(repo_path, version, 'attention'))
|
| 227 |
+
|
| 228 |
+
def check_inputs(self, image, condition_image, width, height):
|
| 229 |
+
if isinstance(image, torch.Tensor) and isinstance(condition_image, torch.Tensor) and isinstance(torch.Tensor):
|
| 230 |
+
return image, condition_image
|
| 231 |
+
image = resize_and_crop(image, (width, height))
|
| 232 |
+
condition_image = resize_and_padding(condition_image, (width, height))
|
| 233 |
+
return image, condition_image
|
| 234 |
+
|
| 235 |
+
@torch.no_grad()
|
| 236 |
+
def __call__(
|
| 237 |
+
self,
|
| 238 |
+
image: Union[PIL.Image.Image, torch.Tensor],
|
| 239 |
+
condition_image: Union[PIL.Image.Image, torch.Tensor],
|
| 240 |
+
num_inference_steps: int = 50,
|
| 241 |
+
guidance_scale: float = 2.5,
|
| 242 |
+
height: int = 1024,
|
| 243 |
+
width: int = 768,
|
| 244 |
+
generator=None,
|
| 245 |
+
eta=1.0,
|
| 246 |
+
**kwargs
|
| 247 |
+
):
|
| 248 |
+
concat_dim = -1
|
| 249 |
+
# Prepare inputs to Tensor
|
| 250 |
+
image, condition_image = self.check_inputs(image, condition_image, width, height)
|
| 251 |
+
image = prepare_image(image).to(self.device, dtype=self.weight_dtype)
|
| 252 |
+
condition_image = prepare_image(condition_image).to(self.device, dtype=self.weight_dtype)
|
| 253 |
+
# VAE encoding
|
| 254 |
+
image_latent = compute_vae_encodings(image, self.vae)
|
| 255 |
+
condition_latent = compute_vae_encodings(condition_image, self.vae)
|
| 256 |
+
del image, condition_image
|
| 257 |
+
# Concatenate latents
|
| 258 |
+
condition_latent_concat = torch.cat([image_latent, condition_latent], dim=concat_dim)
|
| 259 |
+
# Prepare noise
|
| 260 |
+
latents = randn_tensor(
|
| 261 |
+
condition_latent_concat.shape,
|
| 262 |
+
generator=generator,
|
| 263 |
+
device=condition_latent_concat.device,
|
| 264 |
+
dtype=self.weight_dtype,
|
| 265 |
+
)
|
| 266 |
+
# Prepare timesteps
|
| 267 |
+
self.noise_scheduler.set_timesteps(num_inference_steps, device=self.device)
|
| 268 |
+
timesteps = self.noise_scheduler.timesteps
|
| 269 |
+
latents = latents * self.noise_scheduler.init_noise_sigma
|
| 270 |
+
# Classifier-Free Guidance
|
| 271 |
+
if do_classifier_free_guidance := (guidance_scale > 1.0):
|
| 272 |
+
condition_latent_concat = torch.cat(
|
| 273 |
+
[
|
| 274 |
+
torch.cat([image_latent, torch.zeros_like(condition_latent)], dim=concat_dim),
|
| 275 |
+
condition_latent_concat,
|
| 276 |
+
]
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
# Denoising loop
|
| 280 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 281 |
+
num_warmup_steps = (len(timesteps) - num_inference_steps * self.noise_scheduler.order)
|
| 282 |
+
with tqdm.tqdm(total=num_inference_steps) as progress_bar:
|
| 283 |
+
for i, t in enumerate(timesteps):
|
| 284 |
+
# expand the latents if we are doing classifier free guidance
|
| 285 |
+
latent_model_input = (torch.cat([latents] * 2) if do_classifier_free_guidance else latents)
|
| 286 |
+
latent_model_input = self.noise_scheduler.scale_model_input(latent_model_input, t)
|
| 287 |
+
# prepare the input for the inpainting model
|
| 288 |
+
p2p_latent_model_input = torch.cat([latent_model_input, condition_latent_concat], dim=1)
|
| 289 |
+
# predict the noise residual
|
| 290 |
+
noise_pred= self.unet(
|
| 291 |
+
p2p_latent_model_input,
|
| 292 |
+
t.to(self.device),
|
| 293 |
+
encoder_hidden_states=None,
|
| 294 |
+
return_dict=False,
|
| 295 |
+
)[0]
|
| 296 |
+
# perform guidance
|
| 297 |
+
if do_classifier_free_guidance:
|
| 298 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 299 |
+
noise_pred = noise_pred_uncond + guidance_scale * (
|
| 300 |
+
noise_pred_text - noise_pred_uncond
|
| 301 |
+
)
|
| 302 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 303 |
+
latents = self.noise_scheduler.step(
|
| 304 |
+
noise_pred, t, latents, **extra_step_kwargs
|
| 305 |
+
).prev_sample
|
| 306 |
+
# call the callback, if provided
|
| 307 |
+
if i == len(timesteps) - 1 or (
|
| 308 |
+
(i + 1) > num_warmup_steps
|
| 309 |
+
and (i + 1) % self.noise_scheduler.order == 0
|
| 310 |
+
):
|
| 311 |
+
progress_bar.update()
|
| 312 |
+
|
| 313 |
+
# Decode the final latents
|
| 314 |
+
latents = latents.split(latents.shape[concat_dim] // 2, dim=concat_dim)[0]
|
| 315 |
+
latents = 1 / self.vae.config.scaling_factor * latents
|
| 316 |
+
image = self.vae.decode(latents.to(self.device, dtype=self.weight_dtype)).sample
|
| 317 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 318 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
| 319 |
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 320 |
+
image = numpy_to_pil(image)
|
| 321 |
+
|
| 322 |
+
# Safety Check
|
| 323 |
+
if not self.skip_safety_check:
|
| 324 |
+
current_script_directory = os.path.dirname(os.path.realpath(__file__))
|
| 325 |
+
nsfw_image = os.path.join(os.path.dirname(current_script_directory), 'resource', 'img', 'NSFW.jpg')
|
| 326 |
+
nsfw_image = PIL.Image.open(nsfw_image).resize(image[0].size)
|
| 327 |
+
image_np = np.array(image)
|
| 328 |
+
_, has_nsfw_concept = self.run_safety_checker(image=image_np)
|
| 329 |
+
for i, not_safe in enumerate(has_nsfw_concept):
|
| 330 |
+
if not_safe:
|
| 331 |
+
image[i] = nsfw_image
|
| 332 |
+
return image
|
utils.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import torch
|
| 4 |
+
from model.attn_processor import AttnProcessor2_0, SkipAttnProcessor
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def init_adapter(unet,
|
| 8 |
+
cross_attn_cls=SkipAttnProcessor,
|
| 9 |
+
self_attn_cls=None,
|
| 10 |
+
cross_attn_dim=None,
|
| 11 |
+
**kwargs):
|
| 12 |
+
if cross_attn_dim is None:
|
| 13 |
+
cross_attn_dim = unet.config.cross_attention_dim
|
| 14 |
+
attn_procs = {}
|
| 15 |
+
for name in unet.attn_processors.keys():
|
| 16 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else cross_attn_dim
|
| 17 |
+
if name.startswith("mid_block"):
|
| 18 |
+
hidden_size = unet.config.block_out_channels[-1]
|
| 19 |
+
elif name.startswith("up_blocks"):
|
| 20 |
+
block_id = int(name[len("up_blocks.")])
|
| 21 |
+
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
|
| 22 |
+
elif name.startswith("down_blocks"):
|
| 23 |
+
block_id = int(name[len("down_blocks.")])
|
| 24 |
+
hidden_size = unet.config.block_out_channels[block_id]
|
| 25 |
+
if cross_attention_dim is None:
|
| 26 |
+
if self_attn_cls is not None:
|
| 27 |
+
attn_procs[name] = self_attn_cls(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, **kwargs)
|
| 28 |
+
else:
|
| 29 |
+
# retain the original attn processor
|
| 30 |
+
attn_procs[name] = AttnProcessor2_0(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, **kwargs)
|
| 31 |
+
else:
|
| 32 |
+
attn_procs[name] = cross_attn_cls(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, **kwargs)
|
| 33 |
+
|
| 34 |
+
unet.set_attn_processor(attn_procs)
|
| 35 |
+
adapter_modules = torch.nn.ModuleList(unet.attn_processors.values())
|
| 36 |
+
return adapter_modules
|
| 37 |
+
|
| 38 |
+
def init_diffusion_model(diffusion_model_name_or_path, unet_class=None):
|
| 39 |
+
from diffusers import AutoencoderKL
|
| 40 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
| 41 |
+
|
| 42 |
+
text_encoder = CLIPTextModel.from_pretrained(diffusion_model_name_or_path, subfolder="text_encoder")
|
| 43 |
+
vae = AutoencoderKL.from_pretrained(diffusion_model_name_or_path, subfolder="vae")
|
| 44 |
+
tokenizer = CLIPTokenizer.from_pretrained(diffusion_model_name_or_path, subfolder="tokenizer")
|
| 45 |
+
try:
|
| 46 |
+
unet_folder = os.path.join(diffusion_model_name_or_path, "unet")
|
| 47 |
+
unet_configs = json.load(open(os.path.join(unet_folder, "config.json"), "r"))
|
| 48 |
+
unet = unet_class(**unet_configs)
|
| 49 |
+
unet.load_state_dict(torch.load(os.path.join(unet_folder, "diffusion_pytorch_model.bin"), map_location="cpu"), strict=True)
|
| 50 |
+
except:
|
| 51 |
+
unet = None
|
| 52 |
+
return text_encoder, vae, tokenizer, unet
|
| 53 |
+
|
| 54 |
+
def attn_of_unet(unet):
|
| 55 |
+
attn_blocks = torch.nn.ModuleList()
|
| 56 |
+
for name, param in unet.named_modules():
|
| 57 |
+
if "attn1" in name:
|
| 58 |
+
attn_blocks.append(param)
|
| 59 |
+
return attn_blocks
|
| 60 |
+
|
| 61 |
+
def get_trainable_module(unet, trainable_module_name):
|
| 62 |
+
if trainable_module_name == "unet":
|
| 63 |
+
return unet
|
| 64 |
+
elif trainable_module_name == "transformer":
|
| 65 |
+
trainable_modules = torch.nn.ModuleList()
|
| 66 |
+
for blocks in [unet.down_blocks, unet.mid_block, unet.up_blocks]:
|
| 67 |
+
if hasattr(blocks, "attentions"):
|
| 68 |
+
trainable_modules.append(blocks.attentions)
|
| 69 |
+
else:
|
| 70 |
+
for block in blocks:
|
| 71 |
+
if hasattr(block, "attentions"):
|
| 72 |
+
trainable_modules.append(block.attentions)
|
| 73 |
+
return trainable_modules
|
| 74 |
+
elif trainable_module_name == "attention":
|
| 75 |
+
attn_blocks = torch.nn.ModuleList()
|
| 76 |
+
for name, param in unet.named_modules():
|
| 77 |
+
if "attn1" in name:
|
| 78 |
+
attn_blocks.append(param)
|
| 79 |
+
return attn_blocks
|
| 80 |
+
else:
|
| 81 |
+
raise ValueError(f"Unknown trainable_module_name: {trainable_module_name}")
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
|