TobDeBer commited on
Commit
8daab62
1 Parent(s): aca3f5d

diffusion build

Browse files
Files changed (3) hide show
  1. app_lightning4.py +257 -0
  2. build_diffusion.sh +4 -3
  3. diffusion/Dockerfile +5 -0
app_lightning4.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ import os
3
+ import random
4
+ import uuid
5
+ import gradio as gr
6
+ import numpy as np
7
+ from PIL import Image
8
+ import spaces
9
+ import torch
10
+ from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
11
+
12
+ css = '''
13
+ .gradio-container{max-width: 570px !important}
14
+ h1{text-align:center}
15
+ '''
16
+
17
+ examples = [
18
+ "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
19
+ "Chocolate dripping from a donut against a yellow background, 8k",
20
+ "Illustration of A starry night camp in the mountains, 4k, cinematic --ar 85:128 --v 6.0 --style raw",
21
+ "A photo of a lavender cat, hdr, 4k, --ar 85:128 --v 6.0 --style raw",
22
+ "A delicious ceviche cheesecake slice, 4k, octane render, ray tracing, Ultra-High-Definition"
23
+ ]
24
+
25
+ MODEL_OPTIONS = {
26
+ "Lightning": "SG161222/RealVisXL_V4.0_Lightning"
27
+ }
28
+
29
+ MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "4096"))
30
+ USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1"
31
+ ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"
32
+ BATCH_SIZE = int(os.getenv("BATCH_SIZE", "1"))
33
+
34
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
35
+ print(device)
36
+
37
+ def load_and_prepare_model(model_id):
38
+ pipe = StableDiffusionXLPipeline.from_pretrained(
39
+ model_id,
40
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
41
+ use_safetensors=True,
42
+ add_watermarker=False,
43
+ ).to(device)
44
+ pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
45
+
46
+ if USE_TORCH_COMPILE:
47
+ pipe.compile()
48
+
49
+ if ENABLE_CPU_OFFLOAD:
50
+ pipe.enable_model_cpu_offload()
51
+
52
+ return pipe
53
+
54
+ # Preload and compile both models
55
+ models = {key: load_and_prepare_model(value) for key, value in MODEL_OPTIONS.items()}
56
+
57
+ MAX_SEED = np.iinfo(np.int32).max
58
+
59
+ def save_image(img):
60
+ unique_name = str(uuid.uuid4()) + ".webp"
61
+ img.save(unique_name, quality=90)
62
+ return unique_name
63
+
64
+ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
65
+ if randomize_seed:
66
+ seed = random.randint(0, MAX_SEED)
67
+ return seed
68
+
69
+ @spaces.GPU(duration=60, enable_queue=True)
70
+ def generate(
71
+ model_choice: str,
72
+ prompt: str,
73
+ negative_prompt: str = "",
74
+ use_negative_prompt: bool = False,
75
+ seed: int = 1,
76
+ width: int = 1024,
77
+ height: int = 1024,
78
+ guidance_scale: float = 3,
79
+ num_inference_steps: int = 25,
80
+ randomize_seed: bool = False,
81
+ use_resolution_binning: bool = True,
82
+ num_images: int = 1,
83
+ progress=gr.Progress(track_tqdm=True),
84
+ ):
85
+ global models
86
+ pipe = models[model_choice]
87
+
88
+ seed = int(randomize_seed_fn(seed, randomize_seed))
89
+ generator = torch.Generator(device=device).manual_seed(seed)
90
+
91
+ options = {
92
+ "prompt": [prompt] * num_images,
93
+ "negative_prompt": [negative_prompt] * num_images if use_negative_prompt else None,
94
+ "width": width,
95
+ "height": height,
96
+ "guidance_scale": guidance_scale,
97
+ "num_inference_steps": num_inference_steps,
98
+ "generator": generator,
99
+ "output_type": "pil",
100
+ }
101
+
102
+ if use_resolution_binning:
103
+ options["use_resolution_binning"] = True
104
+
105
+ images = []
106
+ for i in range(0, num_images, BATCH_SIZE):
107
+ batch_options = options.copy()
108
+ batch_options["prompt"] = options["prompt"][i:i+BATCH_SIZE]
109
+ if "negative_prompt" in batch_options:
110
+ batch_options["negative_prompt"] = options["negative_prompt"][i:i+BATCH_SIZE]
111
+ images.extend(pipe(**batch_options).images)
112
+
113
+ image_paths = [save_image(img) for img in images]
114
+ return image_paths, seed
115
+
116
+ #def load_predefined_images():
117
+ # predefined_images = [
118
+ # "assets/1.png",
119
+ # "assets/2.png",
120
+ # "assets/3.png",
121
+ # "assets/4.png",
122
+ # "assets/5.png",
123
+ # "assets/6.png",
124
+ # "assets/7.png",
125
+ # "assets/8.png",
126
+ # "assets/9.png",
127
+ # "assets/10.png",
128
+ # "assets/11.png",
129
+ # "assets/12.png",
130
+ # ]
131
+ # return predefined_images
132
+
133
+
134
+ with gr.Blocks(css=css) as demo:
135
+ gr.Markdown(
136
+ f"""
137
+ # Text🥠Image
138
+ Models used in the playground [[Lightning]](https://huggingface.co/SG161222/RealVisXL_V4.0_Lightning), [[Realvision]](https://huggingface.co/) ,[[Turbo]](https://huggingface.co/SG161222/RealVisXL_V3.0_Turbo) for image generation. stable diffusion xl piped (sdxl) model HF. This is the demo space for generating images using the Stable Diffusion XL models, with multi different variants available. ⚠️ users are accountable for the content they generate and are responsible for ensuring it meets appropriate ethical standards.
139
+ """
140
+ )
141
+ with gr.Row():
142
+ prompt = gr.Text(
143
+ label="Prompt",
144
+ show_label=False,
145
+ max_lines=1,
146
+ placeholder="Enter your prompt",
147
+ container=False,
148
+ )
149
+ run_button = gr.Button("Run⚡", scale=0)
150
+ result = gr.Gallery(label="Result", columns=1, show_label=False)
151
+
152
+ with gr.Row():
153
+ model_choice = gr.Dropdown(
154
+ label="Model Selection",
155
+ choices=list(MODEL_OPTIONS.keys()),
156
+ value="Lightning"
157
+ )
158
+
159
+ with gr.Accordion("Advanced options", open=True, visible=False):
160
+ num_images = gr.Slider(
161
+ label="Number of Images",
162
+ minimum=1,
163
+ maximum=1,
164
+ step=1,
165
+ value=1,
166
+ )
167
+ with gr.Row():
168
+ with gr.Column(scale=1):
169
+ use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True)
170
+ negative_prompt = gr.Text(
171
+ label="Negative prompt",
172
+ max_lines=5,
173
+ lines=4,
174
+ placeholder="Enter a negative prompt",
175
+ value="(deformed, distorted, disfigured:1.3), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, (mutated hands and fingers:1.4), disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation",
176
+ visible=True,
177
+ )
178
+ seed = gr.Slider(
179
+ label="Seed",
180
+ minimum=0,
181
+ maximum=MAX_SEED,
182
+ step=1,
183
+ value=0,
184
+ )
185
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
186
+ with gr.Row():
187
+ width = gr.Slider(
188
+ label="Width",
189
+ minimum=512,
190
+ maximum=MAX_IMAGE_SIZE,
191
+ step=64,
192
+ value=1024,
193
+ )
194
+ height = gr.Slider(
195
+ label="Height",
196
+ minimum=512,
197
+ maximum=MAX_IMAGE_SIZE,
198
+ step=64,
199
+ value=1024,
200
+ )
201
+ with gr.Row():
202
+ guidance_scale = gr.Slider(
203
+ label="Guidance Scale",
204
+ minimum=0.1,
205
+ maximum=6,
206
+ step=0.01,
207
+ value=3.0,
208
+ )
209
+ num_inference_steps = gr.Slider(
210
+ label="Number of inference steps",
211
+ minimum=1,
212
+ maximum=35,
213
+ step=1,
214
+ value=20,
215
+ )
216
+
217
+ gr.Examples(
218
+ examples=examples,
219
+ inputs=prompt,
220
+ cache_examples=False
221
+ )
222
+
223
+ use_negative_prompt.change(
224
+ fn=lambda x: gr.update(visible=x),
225
+ inputs=use_negative_prompt,
226
+ outputs=negative_prompt,
227
+ api_name=False,
228
+ )
229
+
230
+ gr.on(
231
+ triggers=[
232
+ prompt.submit,
233
+ negative_prompt.submit,
234
+ run_button.click,
235
+ ],
236
+ fn=generate,
237
+ inputs=[
238
+ model_choice,
239
+ prompt,
240
+ negative_prompt,
241
+ use_negative_prompt,
242
+ seed,
243
+ width,
244
+ height,
245
+ guidance_scale,
246
+ num_inference_steps,
247
+ randomize_seed,
248
+ num_images
249
+ ],
250
+ outputs=[result, seed],
251
+ api_name="run",
252
+ )
253
+ # with gr.Column(scale=3):
254
+ # gr.Markdown("### Image Gallery")
255
+ # predefined_gallery = gr.Gallery(label="Image Gallery", columns=4, show_label=False, value=load_predefined_images())
256
+ if __name__ == "__main__":
257
+ demo.queue(max_size=20).launch(show_api=True, share=True, server_port=7860)
build_diffusion.sh CHANGED
@@ -1,5 +1,6 @@
1
  podman build --squash-all --tag bookworm:diffusion diffusion
2
- #podman image prune -f
3
- #podman save localhost/bookworm:diffusion >test.tar
4
- #time xz -9e -T0 test.tar
 
5
 
 
1
  podman build --squash-all --tag bookworm:diffusion diffusion
2
+ podman image prune -f
3
+ podman save localhost/bookworm:diffusion >diffusion.tar
4
+ rm diffusion.tar.xz
5
+ time xz -6 -T0 diffusion.tar
6
 
diffusion/Dockerfile CHANGED
@@ -1,2 +1,7 @@
1
  FROM debian:bookworm-slim
 
 
 
 
 
2
  CMD ["sleep", " infinity"]
 
1
  FROM debian:bookworm-slim
2
+
3
+ RUN apt-get update
4
+ RUN apt-get install -y git pip libgl1-mesa-dev libglib2.0-0
5
+ RUN pip install --break-system-packages git+https://github.com/huggingface/diffusers.git torch xformers torchvision pipeline transformers accelerate safetensors sentencepiece spaces beautifulsoup4 ftfy peft protobuf invisible_watermark
6
+
7
  CMD ["sleep", " infinity"]