BILLY12138 commited on
Commit
b7362f5
1 Parent(s): 1ac192a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +204 -134
app.py CHANGED
@@ -1,146 +1,216 @@
1
  import gradio as gr
2
- import numpy as np
3
- import random
4
- from diffusers import DiffusionPipeline
5
  import torch
 
 
 
 
 
6
 
7
- device = "cuda" if torch.cuda.is_available() else "cpu"
8
 
9
- if torch.cuda.is_available():
10
- torch.cuda.max_memory_allocated(device=device)
11
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
12
- pipe.enable_xformers_memory_efficient_attention()
13
- pipe = pipe.to(device)
14
- else:
15
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", use_safetensors=True)
16
- pipe = pipe.to(device)
17
-
18
- MAX_SEED = np.iinfo(np.int32).max
19
- MAX_IMAGE_SIZE = 1024
20
-
21
- def infer(prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):
22
-
23
- if randomize_seed:
24
- seed = random.randint(0, MAX_SEED)
25
-
26
- generator = torch.Generator().manual_seed(seed)
27
-
28
- image = pipe(
29
- prompt = prompt,
30
- negative_prompt = negative_prompt,
31
- guidance_scale = guidance_scale,
32
- num_inference_steps = num_inference_steps,
33
- width = width,
34
- height = height,
35
- generator = generator
36
- ).images[0]
37
-
38
- return image
39
-
40
- examples = [
41
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
42
- "An astronaut riding a green horse",
43
- "A delicious ceviche cheesecake slice",
44
- ]
45
-
46
- css="""
47
- #col-container {
48
- margin: 0 auto;
49
- max-width: 520px;
50
  }
51
- """
52
 
53
  if torch.cuda.is_available():
54
- power_device = "GPU"
55
- else:
56
- power_device = "CPU"
 
 
 
 
 
 
 
 
 
57
 
58
- with gr.Blocks(css=css) as demo:
59
-
60
- with gr.Column(elem_id="col-container"):
61
- gr.Markdown(f"""
62
- # Text-to-Image Gradio Template
63
- Currently running on {power_device}.
64
- """)
65
-
66
- with gr.Row():
67
-
68
- prompt = gr.Text(
69
- label="Prompt",
70
- show_label=False,
71
- max_lines=1,
72
- placeholder="Enter your prompt",
73
- container=False,
74
- )
75
-
76
- run_button = gr.Button("Run", scale=0)
77
-
78
- result = gr.Image(label="Result", show_label=False)
79
-
80
- with gr.Accordion("Advanced Settings", open=False):
81
-
82
- negative_prompt = gr.Text(
83
- label="Negative prompt",
84
- max_lines=1,
85
- placeholder="Enter a negative prompt",
86
- visible=False,
87
- )
88
-
89
- seed = gr.Slider(
90
- label="Seed",
91
- minimum=0,
92
- maximum=MAX_SEED,
93
- step=1,
94
- value=0,
95
- )
96
-
97
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
98
-
99
- with gr.Row():
100
-
101
- width = gr.Slider(
102
- label="Width",
103
- minimum=256,
104
- maximum=MAX_IMAGE_SIZE,
105
- step=32,
106
- value=512,
107
- )
108
-
109
- height = gr.Slider(
110
- label="Height",
111
- minimum=256,
112
- maximum=MAX_IMAGE_SIZE,
113
- step=32,
114
- value=512,
115
- )
116
-
117
- with gr.Row():
118
-
119
- guidance_scale = gr.Slider(
120
- label="Guidance scale",
121
- minimum=0.0,
122
- maximum=10.0,
123
- step=0.1,
124
- value=0.0,
125
- )
126
-
127
- num_inference_steps = gr.Slider(
128
- label="Number of inference steps",
129
- minimum=1,
130
- maximum=12,
131
- step=1,
132
- value=2,
133
- )
134
-
135
- gr.Examples(
136
- examples = examples,
137
- inputs = [prompt]
138
  )
139
 
140
- run_button.click(
141
- fn = infer,
142
- inputs = [prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
143
- outputs = [result]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  )
145
 
146
- demo.queue().launch()
 
1
  import gradio as gr
 
 
 
2
  import torch
3
+ from diffusers import StableDiffusionXLPipeline, UNet2DConditionModel
4
+ from tdd_scheduler import TDDScheduler
5
+ from safetensors.torch import load_file
6
+ import spaces
7
+ from PIL import Image
8
 
9
+ SAFETY_CHECKER = False
10
 
11
+ loaded_acc = None
12
+ device = "cuda"
13
+ #device = "cuda" if torch.cuda.is_available() else "cpu"
14
+
15
+ ACC_lora={
16
+ "TDD":"RED-AIGC/TDD/sdxl_tdd_wo_adv_lora.safetensors",
17
+ "TDD_adv":"RED-AIGC/TDD/sdxl_tdd_lora_weights.safetensors",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  }
 
19
 
20
  if torch.cuda.is_available():
21
+ base1 = UNet2DConditionModel.from_pretrained(
22
+ "stabilityai/stable-diffusion-xl-base-1.0", subfolder="unet", torch_dtype=torch.float16
23
+ ).to(device)
24
+ base2 = UNet2DConditionModel.from_pretrained(
25
+ "frankjoshua/realvisxlV40_v40Bakedvae", subfolder="unet", torch_dtype=torch.float16
26
+ ).to(device)
27
+ pipe_sdxl = StableDiffusionXLPipeline.from_pretrained(
28
+ "stabilityai/stable-diffusion-xl-base-1.0",
29
+ unet=base1,
30
+ torch_dtype=torch.float16,
31
+ variant="fp16",
32
+ ).to(device)
33
 
34
+ tdd_lora = load_file(ACC_lora["TDD"])
35
+ tdd_adv_lora = ACC_lora["TDD_adv"]
36
+ pipe_sdxl.load_lora_weights(tdd_lora, adapter_name="TDD")
37
+ pipe_sdxl.load_lora_weights(tdd_adv_lora, adapter_name="TDD_adv")
38
+ pipe_sdxl.scheduler = TDDScheduler.from_config(pipe_sdxl.scheduler.config)
39
+
40
+ pipe_sdxl_real = StableDiffusionXLPipeline.from_pretrained(
41
+ "stabilityai/stable-diffusion-xl-base-1.0",
42
+ unet=base2,
43
+ torch_dtype=torch.float16,
44
+ variant="fp16",
45
+ ).to(device)
46
+ pipe_sdxl_real.load_lora_weights(tdd_lora, adapter_name="TDD")
47
+ pipe_sdxl_real.load_lora_weights(tdd_adv_lora, adapter_name="TDD_adv")
48
+ pipe_sdxl_real.scheduler = TDDScheduler.from_config(pipe_sdxl.scheduler.config)
49
+
50
+ def update_base_model(ckpt):
51
+ if torch.cuda.is_available():
52
+ pipe_sdxl = StableDiffusionXLPipeline.from_pretrained(
53
+ "stabilityai/stable-diffusion-xl-base-1.0",
54
+ torch_dtype=torch.float16,
55
+ variant="fp16",
56
+ ).to(device)
57
+ return pipe_sdxl
58
+
59
+
60
+ if SAFETY_CHECKER:
61
+ from safety_checker import StableDiffusionSafetyChecker
62
+ from transformers import CLIPFeatureExtractor
63
+
64
+ safety_checker = StableDiffusionSafetyChecker.from_pretrained(
65
+ "CompVis/stable-diffusion-safety-checker"
66
+ ).to(device)
67
+ feature_extractor = CLIPFeatureExtractor.from_pretrained(
68
+ "openai/clip-vit-base-patch32"
69
+ )
70
+
71
+ def check_nsfw_images(
72
+ images: list[Image.Image],
73
+ ) -> tuple[list[Image.Image], list[bool]]:
74
+ safety_checker_input = feature_extractor(images, return_tensors="pt").to(device)
75
+ has_nsfw_concepts = safety_checker(
76
+ images=[images], clip_input=safety_checker_input.pixel_values.to(device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  )
78
 
79
+ return images, has_nsfw_concepts
80
+
81
+
82
+ @spaces.GPU(enable_queue=True)
83
+ def generate_image(
84
+ prompt,
85
+ negative_prompt,
86
+ ckpt,
87
+ acc,
88
+ num_inference_steps,
89
+ guidance_scale,
90
+ eta,
91
+ seed,
92
+ progress=gr.Progress(track_tqdm=True),
93
+ ):
94
+ global loaded_acc
95
+ #pipe = pipe_sdxl #if mode == "sdxl" else pipe_sd15
96
+
97
+ if ckpt == "Real":
98
+ pipe = pipe_sdxl_real
99
+ else:
100
+ pipe = pipe_sdxl
101
+
102
+ if loaded_acc != acc:
103
+ #pipe.load_lora_weights(ACC_lora[acc], adapter_name=acc)
104
+ pipe.set_adapters([acc], adapter_weights=[1.0])
105
+ print(pipe.get_active_adapters())
106
+ loaded_acc = acc
107
+
108
+ results = pipe(
109
+ prompt=prompt,
110
+ negative_prompt=negative_prompt,
111
+ num_inference_steps=num_inference_steps,
112
+ guidance_scale=guidance_scale,
113
+ eta=eta,
114
+ generator=torch.Generator(device=pipe.device).manual_seed(seed),
115
+ )
116
+
117
+ if SAFETY_CHECKER:
118
+ images, has_nsfw_concepts = check_nsfw_images(results.images)
119
+ if any(has_nsfw_concepts):
120
+ gr.Warning("NSFW content detected.")
121
+ return Image.new("RGB", (512, 512))
122
+ return images[0]
123
+ return results.images[0]
124
+
125
+ css = """
126
+ h1 {
127
+ text-align: center;
128
+ display:block;
129
+ }
130
+ .gradio-container {
131
+ max-width: 70.5rem !important;
132
+ }
133
+ """
134
+
135
+ with gr.Blocks(css=css) as demo:
136
+ gr.Markdown(
137
+ """
138
+ # ✨Target-Driven Distillation✨
139
+
140
+ Target-Driven Distillation (TDD) is a state-of-the-art consistency distillation model that largely accelerates the inference processes of diffusion models. Using its delicate strategies of *target timestep selection* and *decoupled guidance*, models distilled by TDD can generated highly detailed images with only a few steps.
141
+
142
+ [![arXiv](https://img.shields.io/badge/arXiv-coming%20soon-b31b1b.svg?logo=arxiv)](https://arxiv.org) [![Hugging Face Models](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Models-blue)](https://huggingface.co/RedAIGC/TDD)
143
+ """
144
+ )
145
+ with gr.Row():
146
+ with gr.Column(scale=1):
147
+ with gr.Group():
148
+ with gr.Row():
149
+ prompt = gr.Textbox(label="Prompt")
150
+ with gr.Row():
151
+ negative_prompt = gr.Textbox(label="Negative Prompt")
152
+ with gr.Row():
153
+ steps = gr.Slider(
154
+ label="Sampling Steps",
155
+ minimum=4,
156
+ maximum=8,
157
+ step=1,
158
+ value=4,
159
+ )
160
+ with gr.Row():
161
+ guidance_scale = gr.Slider(
162
+ label="CFG Scale",
163
+ minimum=1,
164
+ maximum=4,
165
+ step=0.1,
166
+ value=2.0,
167
+ )
168
+ with gr.Row():
169
+ eta = gr.Slider(
170
+ label="eta",
171
+ minimum=0,
172
+ maximum=0.3,
173
+ step=0.1,
174
+ value=0.2,
175
+ )
176
+ with gr.Row():
177
+ seed = gr.Number(label="Seed", value=-1)
178
+
179
+ with gr.Row():
180
+
181
+ ckpt = gr.Dropdown(
182
+ label="Base Model",
183
+ choices=["SDXL-1.0", "Real"],
184
+ value="SDXL-1.0",
185
+ )
186
+
187
+ acc = gr.Dropdown(
188
+ label="Accelerate Lora",
189
+ choices=["TDD", "TDD_adv"],
190
+ value="TDD_adv",
191
+ )
192
+
193
+ with gr.Column(scale=1):
194
+ with gr.Group():
195
+ img = gr.Image(label="TDD Image", value="/share/wangcunzheng/test1.png")
196
+ submit_sdxl = gr.Button("Run on SDXL")
197
+ gr.Examples(
198
+ examples=[
199
+ ["A photo of a cat made of water.", "", "SDXL-1.0", "TDD_adv", 4, 1.7, 0.2, 546237],
200
+ ["A photo of a dog made of water.", "", "SDXL-1.0", "TDD_adv", 4, 1.7, 0.2, 546237],
201
+
202
+ ],
203
+ inputs=[prompt, negative_prompt, ckpt, acc, steps, guidance_scale, eta, seed],
204
+ outputs=[img],
205
+ fn=generate_image,
206
+ cache_examples="lazy",
207
+ )
208
+
209
+ gr.on(
210
+ fn=generate_image,
211
+ triggers=[ckpt.change, prompt.submit, submit_sdxl.click],
212
+ inputs=[prompt, negative_prompt, ckpt, acc, steps, guidance_scale, eta, seed],
213
+ outputs=[img],
214
  )
215
 
216
+ demo.queue(api_open=False).launch(show_api=False)