Dakerqi commited on
Commit
03990e9
·
verified ·
1 Parent(s): b011041

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +551 -132
app.py CHANGED
@@ -1,154 +1,573 @@
1
- import gradio as gr
2
- import numpy as np
 
 
 
 
 
 
3
  import random
 
 
4
 
5
- # import spaces #[uncomment to use ZeroGPU]
6
- from diffusers import DiffusionPipeline
 
 
7
  import torch
 
 
8
 
9
- device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
11
-
12
- if torch.cuda.is_available():
13
- torch_dtype = torch.float16
14
- else:
15
- torch_dtype = torch.float32
16
-
17
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
- pipe = pipe.to(device)
19
-
20
- MAX_SEED = np.iinfo(np.int32).max
21
- MAX_IMAGE_SIZE = 1024
22
-
23
-
24
- # @spaces.GPU #[uncomment to use ZeroGPU]
25
- def infer(
26
- prompt,
27
- negative_prompt,
28
- seed,
29
- randomize_seed,
30
- width,
31
- height,
32
- guidance_scale,
33
- num_inference_steps,
34
- progress=gr.Progress(track_tqdm=True),
35
- ):
36
- if randomize_seed:
37
- seed = random.randint(0, MAX_SEED)
38
-
39
- generator = torch.Generator().manual_seed(seed)
40
-
41
- image = pipe(
42
- prompt=prompt,
43
- negative_prompt=negative_prompt,
44
- guidance_scale=guidance_scale,
45
- num_inference_steps=num_inference_steps,
46
- width=width,
47
- height=height,
48
- generator=generator,
49
- ).images[0]
50
-
51
- return image, seed
52
-
53
-
54
- examples = [
55
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
56
- "An astronaut riding a green horse",
57
- "A delicious ceviche cheesecake slice",
58
- ]
59
-
60
- css = """
61
- #col-container {
62
- margin: 0 auto;
63
- max-width: 640px;
64
- }
65
- """
66
-
67
- with gr.Blocks(css=css) as demo:
68
- with gr.Column(elem_id="col-container"):
69
- gr.Markdown(" # Text-to-Image Gradio Template")
70
 
71
- with gr.Row():
72
- prompt = gr.Text(
73
- label="Prompt",
74
- show_label=False,
75
- max_lines=1,
76
- placeholder="Enter your prompt",
77
- container=False,
78
- )
79
 
80
- run_button = gr.Button("Run", scale=0, variant="primary")
 
81
 
82
- result = gr.Image(label="Result", show_label=False)
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
- with gr.Accordion("Advanced Settings", open=False):
85
- negative_prompt = gr.Text(
86
- label="Negative prompt",
87
- max_lines=1,
88
- placeholder="Enter a negative prompt",
89
- visible=False,
90
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
- seed = gr.Slider(
93
- label="Seed",
94
- minimum=0,
95
- maximum=MAX_SEED,
96
- step=1,
97
- value=0,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  )
 
99
 
100
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
- with gr.Row():
103
- width = gr.Slider(
104
- label="Width",
105
- minimum=256,
106
- maximum=MAX_IMAGE_SIZE,
107
- step=32,
108
- value=1024, # Replace with defaults that work for your model
109
- )
 
 
 
 
 
 
 
 
110
 
111
- height = gr.Slider(
112
- label="Height",
113
- minimum=256,
114
- maximum=MAX_IMAGE_SIZE,
115
- step=32,
116
- value=1024, # Replace with defaults that work for your model
117
  )
118
 
119
- with gr.Row():
120
- guidance_scale = gr.Slider(
121
- label="Guidance scale",
122
- minimum=0.0,
123
- maximum=10.0,
124
- step=0.1,
125
- value=0.0, # Replace with defaults that work for your model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  )
127
 
128
- num_inference_steps = gr.Slider(
129
- label="Number of inference steps",
130
- minimum=1,
131
- maximum=50,
132
- step=1,
133
- value=2, # Replace with defaults that work for your model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
- gr.Examples(examples=examples, inputs=[prompt])
137
- gr.on(
138
- triggers=[run_button.click, prompt.submit],
139
- fn=infer,
140
- inputs=[
141
- prompt,
142
- negative_prompt,
143
- seed,
144
- randomize_seed,
145
- width,
146
- height,
147
- guidance_scale,
148
- num_inference_steps,
149
- ],
150
- outputs=[result, seed],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  )
152
 
 
153
  if __name__ == "__main__":
154
- demo.launch()
 
 
1
+ import argparse
2
+ import os
3
+ #os.environ['CUDA_VISIBLE_DEVICES'] = '7'
4
+ import builtins
5
+ import json
6
+ import math
7
+ import multiprocessing as mp
8
+ import os
9
  import random
10
+ import socket
11
+ import traceback
12
 
13
+ #import fairscale.nn.model_parallel.initialize as fs_init
14
+ import gradio as gr
15
+ import numpy as np
16
+ from safetensors.torch import load_file
17
  import torch
18
+ #i#mport torch.distributed as dist
19
+ from torchvision.transforms.functional import to_pil_image
20
 
21
+ from imgproc import generate_crop_size_list
22
+ import models
23
+ from transport import Sampler, create_transport
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ from multiprocessing import Process,Queue,set_start_method,get_context
26
+ #set_start_method('fork')
 
 
 
 
 
 
27
 
28
+ class ModelFailure:
29
+ pass
30
 
31
+ gemma_path = "./gemma-2-2b"
32
+ #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
33
+ # Adapted from pipelines.StableDiffusionXLPipeline.encode_prompt
34
+ def encode_prompt(prompt_batch, text_encoder, tokenizer, proportion_empty_prompts, is_train=True):
35
+ captions = []
36
+ for caption in prompt_batch:
37
+ if random.random() < proportion_empty_prompts:
38
+ captions.append("")
39
+ elif isinstance(caption, str):
40
+ captions.append(caption)
41
+ elif isinstance(caption, (list, np.ndarray)):
42
+ # take a random caption if there are multiple
43
+ captions.append(random.choice(caption) if is_train else caption[0])
44
 
45
+ with torch.no_grad():
46
+ text_inputs = tokenizer(
47
+ captions,
48
+ padding=True,
49
+ pad_to_multiple_of=8,
50
+ max_length=256,
51
+ truncation=True,
52
+ return_tensors="pt",
53
+ )
54
+
55
+ text_input_ids = text_inputs.input_ids
56
+ prompt_masks = text_inputs.attention_mask
57
+
58
+ prompt_embeds = text_encoder(
59
+ input_ids=text_input_ids.cuda(),
60
+ attention_mask=prompt_masks.cuda(),
61
+ output_hidden_states=True,
62
+ ).hidden_states[-2]
63
+
64
+ return prompt_embeds, prompt_masks
65
+
66
+
67
+ @torch.no_grad()
68
+ def model_main(args, master_port, rank, request_queue, response_queue, mp_barrier):
69
+ # import here to avoid huggingface Tokenizer parallelism warnings
70
+ from diffusers.models import AutoencoderKL
71
+ from transformers import AutoModel, AutoTokenizer
72
+
73
+ # override the default print function since the delay can be large for child process
74
+ original_print = builtins.print
75
+
76
+ # Redefine the print function with flush=True by default
77
+ def print(*args, **kwargs):
78
+ kwargs.setdefault("flush", True)
79
+ original_print(*args, **kwargs)
80
+
81
+ # Override the built-in print with the new version
82
+ builtins.print = print
83
+
84
+ os.environ["MASTER_PORT"] = str(master_port)
85
+ os.environ["MASTER_ADDR"] = "127.0.0.1"
86
+ os.environ["RANK"] = str(rank)
87
+ os.environ["WORLD_SIZE"] = str(args.num_gpus)
88
+
89
+
90
+ train_args = torch.load(os.path.join(args.ckpt, "model_args.pth"))
91
+ print("Loaded model arguments:", json.dumps(train_args.__dict__, indent=2))
92
+
93
+ print(f"Creating lm: Gemma-2-2B")
94
 
95
+ dtype = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}[args.precision]
96
+
97
+ text_encoder = AutoModel.from_pretrained(
98
+ gemma_path, torch_dtype=dtype, device_map="cuda", token=args.hf_token
99
+ ).eval()
100
+ cap_feat_dim = text_encoder.config.hidden_size
101
+ if args.num_gpus > 1:
102
+ raise NotImplementedError("Inference with >1 GPUs not yet supported")
103
+
104
+ tokenizer = AutoTokenizer.from_pretrained(gemma_path, token=args.hf_token)
105
+ tokenizer.padding_side = "right"
106
+
107
+ vae = AutoencoderKL.from_pretrained("./flux", subfolder="vae", token=args.hf_token).cuda()
108
+
109
+ print(f"Creating DiT: {train_args.model}")
110
+
111
+ model = models.__dict__[train_args.model](
112
+ in_channels=16,
113
+ qk_norm=train_args.qk_norm,
114
+ cap_feat_dim=cap_feat_dim,
115
+ )
116
+ model.eval().to("cuda", dtype=dtype)
117
+
118
+ assert train_args.model_parallel_size == args.num_gpus
119
+ if args.ema:
120
+ print("Loading ema model.")
121
+ print('load model')
122
+ ckpt_path = os.path.join(
123
+ args.ckpt,
124
+ f"consolidated{'_ema' if args.ema else ''}.{rank:02d}-of-{args.num_gpus:02d}.safetensors",
125
+ )
126
+ if os.path.exists(ckpt_path):
127
+ ckpt = load_file(ckpt_path)
128
+ else:
129
+ ckpt_path = os.path.join(
130
+ args.ckpt,
131
+ f"consolidated{'_ema' if args.ema else ''}.{rank:02d}-of-{args.num_gpus:02d}.pth",
132
+ )
133
+ assert os.path.exists(ckpt_path)
134
+ ckpt = torch.load(ckpt_path, map_location="cuda")
135
+ model.load_state_dict(ckpt, strict=True)
136
+ print('load model finish')
137
+ mp_barrier.wait()
138
+
139
+ with torch.autocast("cuda", dtype):
140
+ while True:
141
+ (
142
+ cap,
143
+ neg_cap,
144
+ system_type,
145
+ resolution,
146
+ num_sampling_steps,
147
+ cfg_scale,
148
+ cfg_trunc,
149
+ renorm_cfg,
150
+ solver,
151
+ t_shift,
152
+ seed,
153
+ scaling_method,
154
+ scaling_watershed,
155
+ proportional_attn,
156
+ ) = request_queue.get()
157
+
158
+
159
+ system_prompt = system_type
160
+ cap = system_prompt + cap
161
+ if neg_cap != "":
162
+ neg_cap = system_prompt + neg_cap
163
+
164
+ metadata = dict(
165
+ real_cap=cap,
166
+ real_neg_cap=neg_cap,
167
+ system_type=system_type,
168
+ resolution=resolution,
169
+ num_sampling_steps=num_sampling_steps,
170
+ cfg_scale=cfg_scale,
171
+ cfg_trunc=cfg_trunc,
172
+ renorm_cfg=renorm_cfg,
173
+ solver=solver,
174
+ t_shift=t_shift,
175
+ seed=seed,
176
+ scaling_method=scaling_method,
177
+ scaling_watershed=scaling_watershed,
178
+ proportional_attn=proportional_attn,
179
  )
180
+ print("> params:", json.dumps(metadata, indent=2))
181
 
182
+ try:
183
+ # begin sampler
184
+ if solver == "dpm":
185
+ transport = create_transport(
186
+ "Linear",
187
+ "velocity",
188
+ )
189
+ sampler = Sampler(transport)
190
+ sample_fn = sampler.sample_dpm(
191
+ model.forward_with_cfg,
192
+ model_kwargs=model_kwargs,
193
+ )
194
+ else:
195
+ transport = create_transport(
196
+ args.path_type,
197
+ args.prediction,
198
+ args.loss_weight,
199
+ args.train_eps,
200
+ args.sample_eps,
201
+ )
202
+ sampler = Sampler(transport)
203
+ sample_fn = sampler.sample_ode(
204
+ sampling_method=solver,
205
+ num_steps=num_sampling_steps,
206
+ atol=args.atol,
207
+ rtol=args.rtol,
208
+ reverse=args.reverse,
209
+ time_shifting_factor=t_shift,
210
+ )
211
+ # end sampler
212
 
213
+ resolution = resolution.split(" ")[-1]
214
+ w, h = resolution.split("x")
215
+ w, h = int(w), int(h)
216
+ latent_w, latent_h = w // 8, h // 8
217
+ if int(seed) != 0:
218
+ torch.random.manual_seed(int(seed))
219
+ z = torch.randn([1, 16, latent_h, latent_w], device="cuda").to(dtype)
220
+ z = z.repeat(2, 1, 1, 1)
221
+
222
+ with torch.no_grad():
223
+ if neg_cap != "":
224
+ cap_feats, cap_mask = encode_prompt([cap] + [neg_cap], text_encoder, tokenizer, 0.0)
225
+ else:
226
+ cap_feats, cap_mask = encode_prompt([cap] + [""], text_encoder, tokenizer, 0.0)
227
+
228
+ cap_mask = cap_mask.to(cap_feats.device)
229
 
230
+ model_kwargs = dict(
231
+ cap_feats=cap_feats,
232
+ cap_mask=cap_mask,
233
+ cfg_scale=cfg_scale,
234
+ cfg_trunc=1 - cfg_trunc,
235
+ renorm_cfg=renorm_cfg,
236
  )
237
 
238
+ #if dist.get_rank() == 0:
239
+ print(f"> caption: {cap}")
240
+ print(f"> num_sampling_steps: {num_sampling_steps}")
241
+ print(f"> cfg_scale: {cfg_scale}")
242
+ print("> start sample")
243
+ if solver == "dpm":
244
+ samples = sample_fn(z, steps=num_sampling_steps, order=2, skip_type="time_uniform_flow", method="multistep", flow_shift=t_shift)
245
+ else:
246
+ samples = sample_fn(z, model.forward_with_cfg, **model_kwargs)[-1]
247
+ samples = samples[:1]
248
+ print("smaple_dtype", samples.dtype)
249
+
250
+ vae_scale = {
251
+ "sdxl": 0.13025,
252
+ "sd3": 1.5305,
253
+ "ema": 0.18215,
254
+ "mse": 0.18215,
255
+ "cogvideox": 1.15258426,
256
+ "flux": 0.3611,
257
+ }["flux"]
258
+ vae_shift = {
259
+ "sdxl": 0.0,
260
+ "sd3": 0.0609,
261
+ "ema": 0.0,
262
+ "mse": 0.0,
263
+ "cogvideox": 0.0,
264
+ "flux": 0.1159,
265
+ }["flux"]
266
+ print(f"> vae scale: {vae_scale}, shift: {vae_shift}")
267
+ print("samples.shape", samples.shape)
268
+ samples = vae.decode(samples / vae_scale + vae_shift).sample
269
+ samples = (samples + 1.0) / 2.0
270
+ samples.clamp_(0.0, 1.0)
271
+
272
+ img = to_pil_image(samples[0, :].float())
273
+ print("> generated image, done.")
274
+
275
+ if response_queue is not None:
276
+ response_queue.put((img, metadata))
277
+
278
+ except Exception:
279
+ print(traceback.format_exc())
280
+ response_queue.put(ModelFailure())
281
+
282
+
283
+ def none_or_str(value):
284
+ if value == "None":
285
+ return None
286
+ return value
287
+
288
+
289
+ def parse_transport_args(parser):
290
+ group = parser.add_argument_group("Transport arguments")
291
+ group.add_argument(
292
+ "--path-type",
293
+ type=str,
294
+ default="Linear",
295
+ choices=["Linear", "GVP", "VP"],
296
+ help="the type of path for transport: 'Linear', 'GVP' (Geodesic Vector Pursuit), or 'VP' (Vector Pursuit).",
297
+ )
298
+ group.add_argument(
299
+ "--prediction",
300
+ type=str,
301
+ default="velocity",
302
+ choices=["velocity", "score", "noise"],
303
+ help="the prediction model for the transport dynamics.",
304
+ )
305
+ group.add_argument(
306
+ "--loss-weight",
307
+ type=none_or_str,
308
+ default=None,
309
+ choices=[None, "velocity", "likelihood"],
310
+ help="the weighting of different components in the loss function, can be 'velocity' for dynamic modeling, 'likelihood' for statistical consistency, or None for no weighting.",
311
+ )
312
+ group.add_argument("--sample-eps", type=float, help="sampling in the transport model.")
313
+ group.add_argument("--train-eps", type=float, help="training to stabilize the learning process.")
314
+
315
+
316
+ def parse_ode_args(parser):
317
+ group = parser.add_argument_group("ODE arguments")
318
+ group.add_argument(
319
+ "--atol",
320
+ type=float,
321
+ default=1e-6,
322
+ help="Absolute tolerance for the ODE solver.",
323
+ )
324
+ group.add_argument(
325
+ "--rtol",
326
+ type=float,
327
+ default=1e-3,
328
+ help="Relative tolerance for the ODE solver.",
329
+ )
330
+ group.add_argument("--reverse", action="store_true", help="run the ODE solver in reverse.")
331
+ group.add_argument(
332
+ "--likelihood",
333
+ action="store_true",
334
+ help="Enable calculation of likelihood during the ODE solving process.",
335
+ )
336
+
337
+
338
+ def find_free_port() -> int:
339
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
340
+ sock.bind(("", 0))
341
+ port = sock.getsockname()[1]
342
+ sock.close()
343
+ return port
344
+
345
+
346
+ def main():
347
+ parser = argparse.ArgumentParser()
348
+
349
+ parser.add_argument("--num_gpus", type=int, default=1)
350
+ parser.add_argument("--ckpt", type=str,default='/home/ubuntu/zl/T2I/ckt_256_final/', required=False)
351
+ parser.add_argument("--ema", action="store_true")
352
+ parser.add_argument("--precision", default="bf16", choices=["bf16", "fp32"])
353
+ parser.add_argument("--hf_token", type=str, default=None, help="huggingface read token for accessing gated repo.")
354
+ parser.add_argument("--res", type=int, default=1024, choices=[256, 512, 1024])
355
+ parser.add_argument("--port", type=int, default=100023)
356
+
357
+ parse_transport_args(parser)
358
+ parse_ode_args(parser)
359
+
360
+ args = parser.parse_known_args()[0]
361
+
362
+ if args.num_gpus != 1:
363
+ raise NotImplementedError("Multi-GPU Inference is not yet supported")
364
+
365
+ master_port = find_free_port()
366
+ #mp.set_start_method("fork")
367
+ processes = []
368
+ request_queues = []
369
+ response_queue = mp.Queue()
370
+ mp_barrier = mp.Barrier(args.num_gpus + 1)
371
+ for i in range(args.num_gpus):
372
+ request_queues.append(mp.Queue())
373
+ p = mp.Process(
374
+ target=model_main,
375
+ args=(
376
+ args,
377
+ master_port,
378
+ i,
379
+ request_queues[i],
380
+ response_queue if i == 0 else None,
381
+ mp_barrier,
382
+ ),
383
+ )
384
+ p.start()
385
+ processes.append(p)
386
+
387
+ description = args.ckpt.split('/')[-1]
388
+ #"""
389
+ # Lumina Next Text-to-Image
390
+
391
+ #Lumina-Next-T2I is a 2B Next-DiT model with 2B text encoder.
392
+
393
+ #Demo current model: `Lumina-Next-T2I`
394
+
395
+ #"""
396
+ with gr.Blocks() as demo:
397
+ with gr.Row():
398
+ gr.Markdown(description)
399
+ with gr.Row():
400
+ with gr.Column():
401
+ cap = gr.Textbox(
402
+ lines=2,
403
+ label="Caption",
404
+ interactive=True,
405
+ value="Majestic landscape photograph of snow-capped mountains under a dramatic sky at sunset. The mountains dominate the lower half of the image, with rugged peaks and deep crevasses visible. A glacier flows down the right side, partially illuminated by the warm light. The sky is filled with fiery orange and golden clouds, contrasting with the cool tones of the snow. The central peak is partially obscured by clouds, adding a sense of mystery. The foreground features dark, shadowed forested areas, enhancing the depth. High contrast, natural lighting, warm color palette, photorealistic, expansive, awe-inspiring, serene, visually balanced, dynamic composition.",
406
+ placeholder="Enter a caption.",
407
+ )
408
+ neg_cap = gr.Textbox(
409
+ lines=2,
410
+ label="Negative Caption",
411
+ interactive=True,
412
+ value="",
413
+ placeholder="Enter a negative caption.",
414
+ )
415
+ default_value = "You are an assistant designed to generate superior images with the superior degree of image-text alignment based on textual prompts or user prompts."
416
+ system_type = gr.Dropdown(
417
+ value=default_value,
418
+ choices=[
419
+ "You are an assistant designed to generate high-quality images with the highest degree of image-text alignment based on textual prompts.",
420
+ "You are an assistant designed to generate superior images with the superior degree of image-text alignment based on textual prompts or user prompts.",
421
+ "",
422
+ ],
423
+ label="System Type",
424
  )
425
 
426
+ with gr.Row():
427
+ res_choices = [f"{w}x{h}" for w, h in generate_crop_size_list((args.res // 64) ** 2, 64)]
428
+ default_value = "1024x1024" # Set the default value to 256x256
429
+
430
+ resolution = gr.Dropdown(
431
+ value=default_value, choices=res_choices, label="Resolution"
432
+ )
433
+ with gr.Row():
434
+ num_sampling_steps = gr.Slider(
435
+ minimum=1,
436
+ maximum=70,
437
+ value=18,
438
+ step=1,
439
+ interactive=True,
440
+ label="Sampling steps",
441
+ )
442
+ seed = gr.Slider(
443
+ minimum=0,
444
+ maximum=int(1e5),
445
+ value=0,
446
+ step=1,
447
+ interactive=True,
448
+ label="Seed (0 for random)",
449
+ )
450
+ cfg_trunc = gr.Slider(
451
+ minimum=0,
452
+ maximum=1,
453
+ value=0,
454
+ step=0.01,
455
+ interactive=True,
456
+ label="CFG Truncation",
457
+ )
458
+ with gr.Row():
459
+ solver = gr.Dropdown(
460
+ value="midpoint",
461
+ choices=["euler", "midpoint", "rk4"],
462
+ label="solver",
463
+ )
464
+ t_shift = gr.Slider(
465
+ minimum=1,
466
+ maximum=20,
467
+ value=6,
468
+ step=1,
469
+ interactive=True,
470
+ label="Time shift",
471
+ )
472
+ cfg_scale = gr.Slider(
473
+ minimum=1.0,
474
+ maximum=20.0,
475
+ value=4.0,
476
+ interactive=True,
477
+ label="CFG scale",
478
+ )
479
+ with gr.Row():
480
+ renorm_cfg = gr.Dropdown(
481
+ value=True,
482
+ choices=[True, False, 2.0],
483
+ label="CFG Renorm",
484
+ )
485
+ with gr.Accordion("Advanced Settings for Resolution Extrapolation", open=False):
486
+ with gr.Row():
487
+ scaling_method = gr.Dropdown(
488
+ value="Time-aware",
489
+ choices=["Time-aware", "None"],
490
+ label="RoPE scaling method",
491
+ )
492
+ scaling_watershed = gr.Slider(
493
+ minimum=0.0,
494
+ maximum=1.0,
495
+ value=0.3,
496
+ interactive=True,
497
+ label="Linear/NTK watershed",
498
+ )
499
+ with gr.Row():
500
+ proportional_attn = gr.Checkbox(
501
+ value=True,
502
+ interactive=True,
503
+ label="Proportional attention",
504
+ )
505
+ with gr.Row():
506
+ submit_btn = gr.Button("Submit", variant="primary")
507
+ with gr.Column():
508
+ output_img = gr.Image(
509
+ label="Generated image",
510
+ interactive=False,
511
  )
512
+ with gr.Accordion(label="Generation Parameters", open=True):
513
+ gr_metadata = gr.JSON(label="metadata", show_label=False)
514
+
515
+ with gr.Row():
516
+
517
+ prompts=[ "Close-up portrait of a young woman with light brown hair, looking to the right, illuminated by warm, golden sunlight. Her hair is gently tousled, catching the light and creating a halo effect around her head. She wears a white garment with a V-neck, visible in the lower left of the frame. The background is dark and out of focus, enhancing the contrast between her illuminated face and the shadows. Soft, ethereal lighting, high contrast, warm color palette, shallow depth of field, natural backlighting, serene and contemplative mood, cinematic quality, intimate and visually striking composition.",
518
+ "一个剑客,武侠风,红色腰带,戴着斗笠,低头,盖住眼睛,白色背景,细致,精品,杰作,水墨画,墨烟,墨云,泼墨,色带,墨水,墨黑白莲花,光影艺术,笔触。",
519
+ "Aesthetic photograph of a bouquet of pink and white ranunculus flowers in a clear glass vase, centrally positioned on a wooden surface. The flowers are in full bloom, displaying intricate layers of petals with a soft gradient from pale pink to white. The vase is filled with water, visible through the clear glass, and the stems are submerged. In the background, a blurred vase with green stems is partially visible, adding depth to the composition. The lighting is warm and natural, casting soft shadows and highlighting the delicate textures of the petals. The scene is serene and intimate, with a focus on the organic beauty of the flowers. Photorealistic, shallow depth of field, soft natural lighting, warm color palette, high contrast, glossy texture, tranquil, visually balanced.",
520
+ "一只优雅的白猫穿着一件紫色的旗袍,旗袍上绣有精致的牡丹花图案,显得高贵典雅。它头上戴着一朵金色的发饰,嘴里叼着一根象征好运的红色丝带。周围环绕着许多飘动的纸鹤和金色的光点,营造出一种祥瑞和梦幻的氛围。超写实风格。"
521
+ ]
522
+ prompts = [[_] for _ in prompts]
523
+ gr.Examples( # noqa
524
+ prompts,
525
+ [cap],
526
+ label="Examples",
527
+ ) # noqa
528
+
529
+ def on_submit(*args):
530
+ for q in request_queues:
531
+ q.put(args)
532
+ result = response_queue.get()
533
+ if isinstance(result, ModelFailure):
534
+ raise RuntimeError
535
+ img, metadata = result
536
+
537
+ return img, metadata
538
 
539
+ submit_btn.click(
540
+ on_submit,
541
+ [
542
+ cap,
543
+ neg_cap,
544
+ system_type,
545
+ resolution,
546
+ num_sampling_steps,
547
+ cfg_scale,
548
+ cfg_trunc,
549
+ renorm_cfg,
550
+ solver,
551
+ t_shift,
552
+ seed,
553
+ scaling_method,
554
+ scaling_watershed,
555
+ proportional_attn,
556
+ ],
557
+ [output_img, gr_metadata],
558
+ )
559
+
560
+ def show_scaling_watershed(scaling_m):
561
+ return gr.update(visible=scaling_m == "Time-aware")
562
+
563
+ scaling_method.change(show_scaling_watershed, scaling_method, scaling_watershed)
564
+
565
+ mp_barrier.wait()
566
+ demo.queue().launch(share=True,
567
+ server_name="0.0.0.0", server_port=args.port
568
  )
569
 
570
+
571
  if __name__ == "__main__":
572
+ mp.set_start_method("fork")
573
+ main()