cyd0806 commited on
Commit
92d7777
·
verified ·
1 Parent(s): 5738a0f

Upload test.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. test.py +280 -0
test.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys,os
2
+ import numpy as np
3
+ from PIL import Image
4
+ current_dir = os.path.dirname(__file__)
5
+ sys.path.append(os.path.abspath(os.path.join(current_dir, '..')))
6
+ import argparse
7
+ import logging
8
+ import torch
9
+ import torch.utils.checkpoint
10
+ import transformers
11
+ from accelerate import Accelerator
12
+ from accelerate.logging import get_logger
13
+ from accelerate.utils import ProjectConfiguration, set_seed
14
+ from tqdm.auto import tqdm
15
+ import diffusers
16
+ from diffusers import FluxPipeline
17
+ import json
18
+ from diffusers.image_processor import VaeImageProcessor
19
+ from src.condition import Condition
20
+ from diffusers.utils import check_min_version, is_wandb_available
21
+ from src.dataloader import get_dataset,prepare_dataset,collate_fn
22
+ from datetime import datetime
23
+ if is_wandb_available():
24
+ pass
25
+ import cv2
26
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
27
+ check_min_version("0.32.0.dev0")
28
+
29
+ logger = get_logger(__name__, log_level="INFO")
30
+ os.environ["TOKENIZERS_PARALLELISM"] = "true"
31
+ from src.SubjectGeniusTransformer2DModel import SubjectGeniusTransformer2DModel
32
+ from src.SubjectGeniusPipeline import SubjectGeniusPipeline
33
+
34
+
35
+ def encode_images(pixels: torch.Tensor, vae: torch.nn.Module, weight_dtype):
36
+ pixel_latents = vae.encode(pixels.to(vae.dtype)).latent_dist.sample()
37
+ pixel_latents = (pixel_latents - vae.config.shift_factor) * vae.config.scaling_factor
38
+ return pixel_latents.to(weight_dtype)
39
+
40
+ def parse_args(input_args=None):
41
+ parser = argparse.ArgumentParser(description="testing script.")
42
+ parser.add_argument("--pretrained_model_name_or_path", type=str,default="ckpt/FLUX.1-schnell",)
43
+ parser.add_argument("--transformer",type=str,default="ckpt/FLUX.1-schnell/transformer",)
44
+ parser.add_argument(
45
+ "--dataset_name",type=str,
46
+ default=[
47
+ "dataset/split_SubjectSpatial200K/test",
48
+ "dataset/split_SubjectSpatial200K/Collection3/test"
49
+ ],
50
+ )
51
+ parser.add_argument("--image_column", type=str, default="image", )
52
+ parser.add_argument("--bbox_column", type=str, default="bbox", )
53
+ parser.add_argument("--canny_column", type=str, default="canny", )
54
+ parser.add_argument("--depth_column", type=str, default="depth", )
55
+ parser.add_argument("--condition_types", type=str, nargs='+', default=["canny", "depth"], )
56
+ parser.add_argument("--denoising_lora",type=str,default="ckpt/Denoising_LoRA/depth_canny_union",)
57
+ parser.add_argument("--condition_lora_dir",type=str,default="ckpt/Condition_LoRA",)
58
+ parser.add_argument("--max_sequence_length",type=int,default=512,help="Maximum sequence length to use with with the T5 text encoder")
59
+ parser.add_argument("--work_dir",type=str,default="output/test_result")
60
+ parser.add_argument("--cache_dir",type=str,default="cache")
61
+ parser.add_argument("--seed", type=int, default=0)
62
+ parser.add_argument("--resolution",type=int,default=512,)
63
+ parser.add_argument("--batch_size", type=int, default=8)
64
+ parser.add_argument("--dataloader_num_workers",type=int,default=0,)
65
+ parser.add_argument("--mixed_precision",type=str,default="bf16",choices=["no", "fp16", "bf16"])
66
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed running: local_rank")
67
+
68
+
69
+ args = parser.parse_args()
70
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
71
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
72
+ args.local_rank = env_local_rank
73
+ args.revision = None
74
+ args.variant = None
75
+ args.denoising_lora_name = os.path.basename(os.path.normpath(args.denoising_lora))
76
+ return args
77
+
78
+
79
+ def main(args):
80
+ accelerator = Accelerator(
81
+ mixed_precision=args.mixed_precision,
82
+ )
83
+ logging.basicConfig(
84
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
85
+ datefmt="%m/%d/%Y %H:%M:%S",
86
+ level=logging.INFO,
87
+ )
88
+ logger.info(accelerator.state, main_process_only=False)
89
+ if accelerator.is_local_main_process:
90
+ transformers.utils.logging.set_verbosity_error()
91
+ diffusers.utils.logging.set_verbosity_warning()
92
+ else:
93
+ transformers.utils.logging.set_verbosity_error()
94
+ diffusers.utils.logging.set_verbosity_error()
95
+
96
+ # 2. set seed
97
+ if args.seed is not None:
98
+ set_seed(args.seed)
99
+
100
+ # 3. create the working directory
101
+ if accelerator.is_main_process:
102
+ if args.work_dir is not None:
103
+ os.makedirs(args.work_dir, exist_ok=True)
104
+
105
+ # 4. precision
106
+ weight_dtype = torch.float32
107
+ if accelerator.mixed_precision == "fp16":
108
+ weight_dtype = torch.float16
109
+ elif accelerator.mixed_precision == "bf16":
110
+ weight_dtype = torch.bfloat16
111
+
112
+ # 5. Load pretrained single conditional LoRA modules onto the FLUX transformer
113
+ transformer = SubjectGeniusTransformer2DModel.from_pretrained(
114
+ pretrained_model_name_or_path=args.transformer,
115
+ revision=args.revision,
116
+ variant=args.variant
117
+ ).to(accelerator.device, dtype=weight_dtype)
118
+ lora_names = args.condition_types
119
+ for condition_type in lora_names:
120
+ transformer.load_lora_adapter(f"{args.condition_lora_dir}/{condition_type}.safetensors", adapter_name=condition_type)
121
+ logger.info("You are working on the following condition types: {}".format(lora_names))
122
+
123
+ # 6. get the inference pipeline.
124
+ pipe = SubjectGeniusPipeline.from_pretrained(
125
+ args.pretrained_model_name_or_path,
126
+ transformer=None,
127
+ ).to(accelerator.device, dtype=weight_dtype)
128
+ pipe.transformer = transformer
129
+
130
+ # 7. get the VAE image processor to do the pre-process and post-process for images.
131
+ # (vae_scale_factor is the scale of downsample.)
132
+ vae_scale_factor = 2 ** (len(pipe.vae.config.block_out_channels) - 1)
133
+ image_processor = VaeImageProcessor(vae_scale_factor=vae_scale_factor * 2 ,do_resize=True)
134
+
135
+ # 8. get the dataset
136
+ dataset = get_dataset(args)
137
+ print("len:",len(dataset))
138
+ dataset = prepare_dataset(dataset, vae_scale_factor, accelerator, args)
139
+
140
+ # 9. set the seed
141
+ if args.seed is not None:
142
+ set_seed(args.seed)
143
+
144
+ # 10. get the dataloader
145
+ dataloader = torch.utils.data.DataLoader(
146
+ dataset,
147
+ shuffle=False,
148
+ collate_fn=collate_fn,
149
+ batch_size=args.batch_size,
150
+ num_workers=args.dataloader_num_workers,
151
+ )
152
+
153
+ # 10. accelerator start
154
+ initial_global_step = 0
155
+ pipe, dataloader = accelerator.prepare(
156
+ pipe, dataloader
157
+ )
158
+
159
+ logger.info("***** Running testing *****")
160
+ logger.info(f" Num examples = {len(dataset)}")
161
+ logger.info(f" Instantaneous batch size per device = {args.batch_size}")
162
+ logger.info(f" Transformer Class = {transformer.__class__.__name__}")
163
+ logger.info(f" Num of GPU processes = {accelerator.num_processes}")
164
+
165
+
166
+ progress_bar = tqdm(
167
+ range(0, len(dataloader)),
168
+ initial=initial_global_step,
169
+ desc="Steps",
170
+ # Only show the progress bar once on each machine.
171
+ disable=not accelerator.is_local_main_process,
172
+ )
173
+
174
+ output_dir = os.path.join(args.work_dir, f"{datetime.now().strftime("%y:%m:%d-%H:%M")}")
175
+ logger.info(f"output dir: {output_dir}")
176
+ os.makedirs(os.path.join(output_dir, "info"), exist_ok=True)
177
+
178
+ # 11. start testing!
179
+ for S, batch in enumerate(dataloader):
180
+ prompts = batch["descriptions"]
181
+ # 12.1 Get Conditions input tensors -> "condition_latents"
182
+ # 12.2 Get Conditions positional id list. -> "condition_ids"
183
+ # 12.3 Get Conditions types string list. -> "condition_types"
184
+ # (bs, cond_num, c, h, w) -> [cond_num, (bs, c, h ,w)]
185
+ condition_latents = list(torch.unbind(batch["condition_latents"], dim=1))
186
+ # [cond_num, (len ,3) ]
187
+ condition_ids = []
188
+ # [cond_num]
189
+ condition_types = batch["condition_types"][0]
190
+ for i,images_per_condition in enumerate(condition_latents):
191
+ # i means No.i. Conditional Branch
192
+ # images_per_condition = (bs, c, h ,w)
193
+ images_per_condition = encode_images(pixels=images_per_condition,vae=pipe.vae,weight_dtype=weight_dtype)
194
+ condition_latents[i] = FluxPipeline._pack_latents(
195
+ images_per_condition,
196
+ batch_size=images_per_condition.shape[0],
197
+ num_channels_latents=images_per_condition.shape[1],
198
+ height=images_per_condition.shape[2],
199
+ width=images_per_condition.shape[3],
200
+ )
201
+ cond_ids = FluxPipeline._prepare_latent_image_ids(
202
+ images_per_condition.shape[0],
203
+ images_per_condition.shape[2] // 2,
204
+ images_per_condition.shape[3] // 2,
205
+ accelerator.device,
206
+ weight_dtype,
207
+ )
208
+ if condition_types[i] == "subject":
209
+ cond_ids[:, 2] += images_per_condition.shape[2] // 2
210
+ condition_ids.append(cond_ids)
211
+
212
+ # 13 prepare the input conditions=[Condition1, Condition2, ...] for all the conditional branches
213
+ conditions = []
214
+ for i, condition_type in enumerate(condition_types):
215
+ conditions.append(Condition(condition_type,condition=condition_latents[i],condition_ids=condition_ids[i]))
216
+
217
+ # 14.1 inference of training-based SubjectGenius
218
+ pipe.transformer.load_lora_adapter(args.denoising_lora,adapter_name=args.denoising_lora_name ,use_safetensors=True)
219
+ pipe.transformer.set_adapters([i for i in lora_names] + [args.denoising_lora_name ])
220
+ if args.seed is not None:
221
+ set_seed(args.seed)
222
+ result_img_list = pipe(
223
+ prompt=prompts,
224
+ conditions=conditions,
225
+ height=args.resolution,
226
+ width=args.resolution,
227
+ num_inference_steps=8,
228
+ max_sequence_length=512,
229
+ model_config = {
230
+ },
231
+ accelerator=accelerator
232
+ ).images
233
+ pipe.transformer.delete_adapters(args.denoising_lora_name)
234
+
235
+ # 14.2 inference of training-free SubjectGenius
236
+ pipe.transformer.set_adapters([i for i in lora_names])
237
+ if args.seed is not None:
238
+ set_seed(args.seed)
239
+ origin_result_img_list = pipe(
240
+ prompt=prompts,
241
+ conditions=conditions,
242
+ height=args.resolution,
243
+ width=args.resolution,
244
+ num_inference_steps=8,
245
+ max_sequence_length=512,
246
+ model_config = {
247
+ },
248
+ accelerator = accelerator
249
+ ).images
250
+
251
+ # 15. save the output to the output_dir = "work_dir/datetime"
252
+ for i,(result_img,origin_result_img) in enumerate(zip(result_img_list,origin_result_img_list)):
253
+ target_img = image_processor.postprocess(batch["pixel_values"][i].unsqueeze(0),output_type="pil")[0]
254
+ cond_images = image_processor.postprocess(batch["condition_latents"][i],output_type="pil")
255
+ concat_image = Image.new("RGB", (1536+len(cond_images)*512, 512))
256
+ for j,(cond_image,cond_type) in enumerate(zip(cond_images,condition_types)):
257
+ if cond_type == "fill":
258
+ cond_image = cv2.rectangle(np.array(cond_image), tuple(batch['bboxes'][i][:2]),tuple(batch['bboxes'][i][2:]), color=(128, 128, 128), thickness=-1)
259
+ cond_image = Image.fromarray(cv2.rectangle(cond_image, tuple(batch['bboxes'][i][:2]), tuple(batch['bboxes'][i][2:]),color=(255, 215, 0), thickness=2))
260
+ concat_image.paste(cond_image,(j*512,0))
261
+ concat_image.paste(result_img,(j*512+512,0))
262
+ concat_image.paste(origin_result_img,(j*512+1024,0))
263
+ concat_image.paste(target_img,(j*512+1536,0))
264
+
265
+ concat_image.save(os.path.join(output_dir,f"{S*args.batch_size+i}_{batch['items'][i]}.jpg"))
266
+
267
+ with open(os.path.join(output_dir,"info",f"{S*args.batch_size+i}_rank{accelerator.local_process_index}_{batch['items'][i]}.json"), "w", encoding="utf-8") as file:
268
+ meta_data = {
269
+ "description": prompts[i],
270
+ "bbox": batch["bboxes"][i]
271
+ }
272
+ json.dump(meta_data,file, ensure_ascii=False, indent=4)
273
+
274
+ progress_bar.update(1)
275
+
276
+ if __name__ == "__main__":
277
+ args = parse_args()
278
+ with torch.no_grad():
279
+ main(args)
280
+