roubaofeipi commited on
Commit
36a67df
1 Parent(s): 85ad68c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +190 -0
app.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import yaml
3
+ import torch
4
+ import sys
5
+ sys.path.append(os.path.abspath('./'))
6
+ from inference.utils import *
7
+ from train import WurstCoreB
8
+ from gdf import DDPMSampler
9
+ from train import WurstCore_t2i as WurstCoreC
10
+ import numpy as np
11
+ import random
12
+ import argparse
13
+ import gradio as gr
14
+
15
+
16
+ def parse_args():
17
+ parser = argparse.ArgumentParser()
18
+ parser.add_argument( '--height', type=int, default=2560, help='image height')
19
+ parser.add_argument('--width', type=int, default=5120, help='image width')
20
+ parser.add_argument('--seed', type=int, default=123, help='random seed')
21
+ parser.add_argument('--dtype', type=str, default='bf16', help=' if bf16 does not work, change it to float32 ')
22
+ parser.add_argument('--config_c', type=str,
23
+ default='configs/training/t2i.yaml' ,help='config file for stage c, latent generation')
24
+ parser.add_argument('--config_b', type=str,
25
+ default='configs/inference/stage_b_1b.yaml' ,help='config file for stage b, latent decoding')
26
+ parser.add_argument( '--prompt', type=str,
27
+ default='A photo-realistic image of a west highland white terrier in the garden, high quality, detail rich, 8K', help='text prompt')
28
+ parser.add_argument( '--num_image', type=int, default=1, help='how many images generated')
29
+ parser.add_argument( '--output_dir', type=str, default='figures/output_results/', help='output directory for generated image')
30
+ parser.add_argument( '--stage_a_tiled', action='store_true', help='whther or nor to use tiled decoding for stage a to save memory')
31
+ parser.add_argument( '--pretrained_path', type=str, default='models/ultrapixel_t2i.safetensors', help='pretrained path of newly added paramter of UltraPixel')
32
+ args = parser.parse_args()
33
+ return args
34
+
35
+ def clear_image():
36
+ return None
37
+ def load_message(height, width, seed, prompt, args, stage_a_tiled):
38
+ args.height = height
39
+ args.width = width
40
+ args.seed = seed
41
+ args.prompt = prompt + ' rich detail, 4k, high quality'
42
+ args.stage_a_tiled = stage_a_tiled
43
+ return args
44
+ def get_image(height, width, seed, prompt, cfg, timesteps, stage_a_tiled):
45
+ global args
46
+ args = load_message(height, width, seed, prompt, args, stage_a_tiled)
47
+ torch.manual_seed(args.seed)
48
+ random.seed(args.seed)
49
+ np.random.seed(args.seed)
50
+ dtype = torch.bfloat16 if args.dtype == 'bf16' else torch.float
51
+
52
+ captions = [args.prompt] * args.num_image
53
+ height, width = args.height, args.width
54
+ batch_size=1
55
+ height_lr, width_lr = get_target_lr_size(height / width, std_size=32)
56
+ stage_c_latent_shape, stage_b_latent_shape = calculate_latent_sizes(height, width, batch_size=batch_size)
57
+ stage_c_latent_shape_lr, stage_b_latent_shape_lr = calculate_latent_sizes(height_lr, width_lr, batch_size=batch_size)
58
+
59
+ # Stage C Parameters
60
+ extras.sampling_configs['cfg'] = 4
61
+ extras.sampling_configs['shift'] = 1
62
+ extras.sampling_configs['timesteps'] = 20
63
+ extras.sampling_configs['t_start'] = 1.0
64
+ extras.sampling_configs['sampler'] = DDPMSampler(extras.gdf)
65
+
66
+
67
+
68
+ # Stage B Parameters
69
+ extras_b.sampling_configs['cfg'] = 1.1
70
+ extras_b.sampling_configs['shift'] = 1
71
+ extras_b.sampling_configs['timesteps'] = 10
72
+ extras_b.sampling_configs['t_start'] = 1.0
73
+
74
+ for _, caption in enumerate(captions):
75
+
76
+
77
+ batch = {'captions': [caption] * batch_size}
78
+ #conditions = core.get_conditions(batch, models, extras, is_eval=True, is_unconditional=False, eval_image_embeds=False)
79
+ #unconditions = core.get_conditions(batch, models, extras, is_eval=True, is_unconditional=True, eval_image_embeds=False)
80
+
81
+ conditions_b = core_b.get_conditions(batch, models_b, extras_b, is_eval=True, is_unconditional=False)
82
+ unconditions_b = core_b.get_conditions(batch, models_b, extras_b, is_eval=True, is_unconditional=True)
83
+
84
+
85
+ with torch.no_grad():
86
+
87
+
88
+ models.generator.cuda()
89
+ print('STAGE C GENERATION***************************')
90
+ with torch.cuda.amp.autocast(dtype=dtype):
91
+ sampled_c = generation_c(batch, models, extras, core, stage_c_latent_shape, stage_c_latent_shape_lr, device)
92
+
93
+
94
+
95
+ models.generator.cpu()
96
+ torch.cuda.empty_cache()
97
+
98
+ conditions_b = core_b.get_conditions(batch, models_b, extras_b, is_eval=True, is_unconditional=False)
99
+ unconditions_b = core_b.get_conditions(batch, models_b, extras_b, is_eval=True, is_unconditional=True)
100
+ conditions_b['effnet'] = sampled_c
101
+ unconditions_b['effnet'] = torch.zeros_like(sampled_c)
102
+ print('STAGE B + A DECODING***************************')
103
+
104
+ with torch.cuda.amp.autocast(dtype=dtype):
105
+ sampled = decode_b(conditions_b, unconditions_b, models_b, stage_b_latent_shape, extras_b, device, stage_a_tiled=args.stage_a_tiled)
106
+
107
+ torch.cuda.empty_cache()
108
+ imgs = show_images(sampled)
109
+ #for idx, img in enumerate(imgs):
110
+ #print(os.path.join(save_dir, args.prompt[:20]+'_' + str(cnt).zfill(5) + '.jpg'), idx)
111
+ #img.save(os.path.join(save_dir, args.prompt[:20]+'_' + str(cnt).zfill(5) + '.jpg'))
112
+
113
+ return imgs[0]
114
+ #print('finished! Results ')
115
+
116
+
117
+ with gr.Blocks() as demo:
118
+ with gr.Column():
119
+ with gr.Row():
120
+ with gr.Column():
121
+ height = gr.Slider(value=2304, step=32, minimum=1536, maximum=4096, label='Height')
122
+ width = gr.Slider(value=4096, step=32, minimum=1536, maximum=5120, label='Width')
123
+ seed = gr.Number(value=123, step=1, label='Random Seed')
124
+ prompt = gr.Textbox(value='', max_lines=4, label='Text Prompt')
125
+ cfg = gr.Slider(value=4, step=0.1, minimum=3, maximum=10, label='CFG')
126
+ timesteps = gr.Slider(value=20, step=1, minimum=10, maximum=50, label='Timesteps')
127
+ stage_a_tiled = gr.Checkbox(value=False, label='Stage_a_tiled')
128
+ with gr.Row():
129
+ clear_button = gr.Button("Clear!")
130
+ polish_button = gr.Button("Submit!")
131
+ with gr.Column():
132
+ output_img = gr.Image(label='Output Image', sources=None)
133
+ with gr.Column():
134
+ prompt2 = gr.Textbox(
135
+ value='''
136
+ 1. a happy cat
137
+ 2. a happy girl
138
+ ''', label='Text prompt examples'
139
+ )
140
+
141
+ polish_button.click(get_image, inputs=[height, width, seed, prompt, cfg, timesteps, stage_a_tiled], outputs=output_img)
142
+ polish_button.click(clear_image, inputs=[], outputs=output_img)
143
+
144
+ if __name__ == "__main__":
145
+
146
+ args = parse_args()
147
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
148
+
149
+ config_file = args.config_c
150
+ with open(config_file, "r", encoding="utf-8") as file:
151
+ loaded_config = yaml.safe_load(file)
152
+
153
+ core = WurstCoreC(config_dict=loaded_config, device=device, training=False)
154
+
155
+ # SETUP STAGE B
156
+ config_file_b = args.config_b
157
+ with open(config_file_b, "r", encoding="utf-8") as file:
158
+ config_file_b = yaml.safe_load(file)
159
+
160
+ core_b = WurstCoreB(config_dict=config_file_b, device=device, training=False)
161
+
162
+ extras = core.setup_extras_pre()
163
+ models = core.setup_models(extras)
164
+ models.generator.eval().requires_grad_(False)
165
+ print("STAGE C READY")
166
+
167
+ extras_b = core_b.setup_extras_pre()
168
+ models_b = core_b.setup_models(extras_b, skip_clip=True)
169
+ models_b = WurstCoreB.Models(
170
+ **{**models_b.to_dict(), 'tokenizer': models.tokenizer, 'text_model': models.text_model}
171
+ )
172
+ models_b.generator.bfloat16().eval().requires_grad_(False)
173
+ print("STAGE B READY")
174
+
175
+ pretrained_path = args.pretrained_path
176
+ sdd = torch.load(pretrained_path, map_location='cpu')
177
+ collect_sd = {}
178
+ for k, v in sdd.items():
179
+ collect_sd[k[7:]] = v
180
+
181
+ models.train_norm.load_state_dict(collect_sd)
182
+ models.generator.eval()
183
+ models.train_norm.eval()
184
+
185
+
186
+ demo.launch(
187
+ debug=True, share=True,
188
+ #server_name='10.160.211.26', server_port=7867
189
+
190
+ )