forked from replicate/cog-sdxl
-
Notifications
You must be signed in to change notification settings - Fork 4
/
predict.py
383 lines (332 loc) · 13.8 KB
/
predict.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
from cog import BasePredictor, Input, Path
import os
import json
import time
import torch
import shutil
import hashlib
import subprocess
import numpy as np
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from weights import WeightsDownloadCache
from diffusers import (
DDIMScheduler,
DiffusionPipeline,
DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
HeunDiscreteScheduler,
PNDMScheduler,
StableDiffusionXLImg2ImgPipeline,
StableDiffusionXLInpaintPipeline,
LCMScheduler,
)
from diffusers.models.attention_processor import LoRAAttnProcessor2_0
from diffusers.pipelines.stable_diffusion.safety_checker import (
StableDiffusionSafetyChecker,
)
from diffusers.utils import load_image
from safetensors.torch import load_file
from transformers import CLIPImageProcessor
from dataset_and_utils import TokenEmbeddingsHandler
SDXL_MODEL_CACHE = "./sdxl-cache"
LCM_CACHE = "./lcm-cache"
SAFETY_CACHE = "./safety-cache"
FEATURE_EXTRACTOR = "./feature-extractor"
SDXL_URL = "https://weights.replicate.delivery/default/sdxl/sdxl-vae-upcast-fix.tar"
SAFETY_URL = "https://weights.replicate.delivery/default/sdxl/safety-1.0.tar"
class KarrasDPM:
def from_config(config):
return DPMSolverMultistepScheduler.from_config(config, use_karras_sigmas=True)
SCHEDULERS = {
"DDIM": DDIMScheduler,
"DPMSolverMultistep": DPMSolverMultistepScheduler,
"HeunDiscrete": HeunDiscreteScheduler,
"KarrasDPM": KarrasDPM,
"K_EULER_ANCESTRAL": EulerAncestralDiscreteScheduler,
"K_EULER": EulerDiscreteScheduler,
"PNDM": PNDMScheduler,
"LCM" : LCMScheduler
}
def download_weights(url, dest):
start = time.time()
print("downloading url: ", url)
print("downloading to: ", dest)
subprocess.check_call(["pget", "-x", url, dest], close_fds=False)
print("downloading took: ", time.time() - start)
class Predictor(BasePredictor):
def load_trained_weights(self, weights, pipe):
from no_init import no_init_or_tensor
# weights can be a URLPath, which behaves in unexpected ways
weights = str(weights)
if self.tuned_weights == weights:
print("skipping loading .. weights already loaded")
return
self.tuned_weights = weights
local_weights_cache = self.weights_cache.ensure(weights)
# load UNET
print("Loading fine-tuned model")
self.is_lora = False
maybe_unet_path = os.path.join(local_weights_cache, "unet.safetensors")
if not os.path.exists(maybe_unet_path):
print("Does not have Unet. assume we are using LoRA")
self.is_lora = True
if not self.is_lora:
print("Loading Unet")
new_unet_params = load_file(
os.path.join(local_weights_cache, "unet.safetensors")
)
# this should return _IncompatibleKeys(missing_keys=[...], unexpected_keys=[])
pipe.unet.load_state_dict(new_unet_params, strict=False)
else:
print("Loading Unet LoRA")
unet = pipe.unet
tensors = load_file(os.path.join(local_weights_cache, "lora.safetensors"))
unet_lora_attn_procs = {}
name_rank_map = {}
for tk, tv in tensors.items():
# up is N, d
if tk.endswith("up.weight"):
proc_name = ".".join(tk.split(".")[:-3])
r = tv.shape[1]
name_rank_map[proc_name] = r
for name, attn_processor in unet.attn_processors.items():
cross_attention_dim = (
None
if name.endswith("attn1.processor")
else unet.config.cross_attention_dim
)
if name.startswith("mid_block"):
hidden_size = unet.config.block_out_channels[-1]
elif name.startswith("up_blocks"):
block_id = int(name[len("up_blocks.")])
hidden_size = list(reversed(unet.config.block_out_channels))[
block_id
]
elif name.startswith("down_blocks"):
block_id = int(name[len("down_blocks.")])
hidden_size = unet.config.block_out_channels[block_id]
with no_init_or_tensor():
module = LoRAAttnProcessor2_0(
hidden_size=hidden_size,
cross_attention_dim=cross_attention_dim,
rank=name_rank_map[name],
)
unet_lora_attn_procs[name] = module.to("cuda", non_blocking=True)
unet.set_attn_processor(unet_lora_attn_procs)
unet.load_state_dict(tensors, strict=False)
# load text
handler = TokenEmbeddingsHandler(
[pipe.text_encoder, pipe.text_encoder_2], [pipe.tokenizer, pipe.tokenizer_2]
)
handler.load_embeddings(os.path.join(local_weights_cache, "embeddings.pti"))
# load params
with open(os.path.join(local_weights_cache, "special_params.json"), "r") as f:
params = json.load(f)
self.token_map = params
self.tuned_model = True
def setup(self, weights: Optional[Path] = None):
"""Load the model into memory to make running multiple predictions efficient"""
start = time.time()
self.tuned_model = False
self.tuned_weights = None
if str(weights) == "weights":
weights = None
self.weights_cache = WeightsDownloadCache()
print("Loading safety checker...")
if not os.path.exists(SAFETY_CACHE):
download_weights(SAFETY_URL, SAFETY_CACHE)
self.safety_checker = StableDiffusionSafetyChecker.from_pretrained(
SAFETY_CACHE, torch_dtype=torch.float16
).to("cuda")
self.feature_extractor = CLIPImageProcessor.from_pretrained(FEATURE_EXTRACTOR)
if not os.path.exists(SDXL_MODEL_CACHE):
download_weights(SDXL_URL, SDXL_MODEL_CACHE)
print("Loading sdxl txt2img pipeline...")
self.txt2img_pipe = DiffusionPipeline.from_pretrained(
SDXL_MODEL_CACHE,
torch_dtype=torch.float16,
use_safetensors=True,
variant="fp16",
)
self.txt2img_pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl", cache_dir=LCM_CACHE)
self.txt2img_pipe.fuse_lora()
self.is_lora = False
if weights or os.path.exists("./trained-model"):
self.load_trained_weights(weights, self.txt2img_pipe)
self.txt2img_pipe.to("cuda")
print("Loading SDXL img2img pipeline...")
self.img2img_pipe = StableDiffusionXLImg2ImgPipeline(
vae=self.txt2img_pipe.vae,
text_encoder=self.txt2img_pipe.text_encoder,
text_encoder_2=self.txt2img_pipe.text_encoder_2,
tokenizer=self.txt2img_pipe.tokenizer,
tokenizer_2=self.txt2img_pipe.tokenizer_2,
unet=self.txt2img_pipe.unet,
scheduler=self.txt2img_pipe.scheduler,
)
self.img2img_pipe.to("cuda")
print("Loading SDXL inpaint pipeline...")
self.inpaint_pipe = StableDiffusionXLInpaintPipeline(
vae=self.txt2img_pipe.vae,
text_encoder=self.txt2img_pipe.text_encoder,
text_encoder_2=self.txt2img_pipe.text_encoder_2,
tokenizer=self.txt2img_pipe.tokenizer,
tokenizer_2=self.txt2img_pipe.tokenizer_2,
unet=self.txt2img_pipe.unet,
scheduler=self.txt2img_pipe.scheduler,
)
self.inpaint_pipe.to("cuda")
print("setup took: ", time.time() - start)
def load_image(self, path):
shutil.copyfile(path, "/tmp/image.png")
return load_image("/tmp/image.png").convert("RGB")
def run_safety_checker(self, image):
safety_checker_input = self.feature_extractor(image, return_tensors="pt").to(
"cuda"
)
np_image = [np.array(val) for val in image]
image, has_nsfw_concept = self.safety_checker(
images=np_image,
clip_input=safety_checker_input.pixel_values.to(torch.float16),
)
return image, has_nsfw_concept
@torch.inference_mode()
def predict(
self,
prompt: str = Input(
description="Input prompt",
default="An astronaut riding a rainbow unicorn, cinematic, dramatic",
),
negative_prompt: str = Input(
description="Input Negative Prompt",
default="",
),
image: Path = Input(
description="Input image for img2img or inpaint mode",
default=None,
),
mask: Path = Input(
description="Input mask for inpaint mode. Black areas will be preserved, white areas will be inpainted.",
default=None,
),
width: int = Input(
description="Width of output image",
default=1024,
),
height: int = Input(
description="Height of output image",
default=1024,
),
num_outputs: int = Input(
description="Number of images to output.",
ge=1,
le=4,
default=1,
),
scheduler: str = Input(
description="scheduler",
choices=SCHEDULERS.keys(),
default="LCM",
),
num_inference_steps: int = Input(
description="Number of denoising steps", ge=1, le=20, default=6
),
guidance_scale: float = Input(
description="Scale for classifier-free guidance", ge=1, le=20, default=2.0
),
prompt_strength: float = Input(
description="Prompt strength when using img2img / inpaint. 1.0 corresponds to full destruction of information in image",
ge=0.0,
le=1.0,
default=0.8,
),
seed: int = Input(
description="Random seed. Leave blank to randomize the seed", default=None
),
apply_watermark: bool = Input(
description="Applies a watermark to enable determining if an image is generated in downstream applications. If you have other provisions for generating or deploying images safely, you can use this to disable watermarking.",
default=True,
),
lora_scale: float = Input(
description="LoRA additive scale. Only applicable on trained models.",
ge=0.0,
le=1.0,
default=0.6,
),
replicate_weights: str = Input(
description="Replicate LoRA weights to use. Leave blank to use the default weights.",
default=None,
),
disable_safety_checker: bool = Input(
description="Disable safety checker for generated images. This feature is only available through the API. See [https://replicate.com/docs/how-does-replicate-work#safety](https://replicate.com/docs/how-does-replicate-work#safety)",
default=False
)
) -> List[Path]:
"""Run a single prediction on the model."""
if seed is None:
seed = int.from_bytes(os.urandom(2), "big")
print(f"Using seed: {seed}")
if replicate_weights:
self.load_trained_weights(replicate_weights, self.txt2img_pipe)
# OOMs can leave vae in bad state
if self.txt2img_pipe.vae.dtype == torch.float32:
self.txt2img_pipe.vae.to(dtype=torch.float16)
sdxl_kwargs = {}
if self.tuned_model:
# consistency with fine-tuning API
for k, v in self.token_map.items():
prompt = prompt.replace(k, v)
print(f"Prompt: {prompt}")
if image and mask:
print("inpainting mode")
sdxl_kwargs["image"] = self.load_image(image)
sdxl_kwargs["mask_image"] = self.load_image(mask)
sdxl_kwargs["strength"] = prompt_strength
sdxl_kwargs["width"] = width
sdxl_kwargs["height"] = height
pipe = self.inpaint_pipe
elif image:
print("img2img mode")
sdxl_kwargs["image"] = self.load_image(image)
sdxl_kwargs["strength"] = prompt_strength
pipe = self.img2img_pipe
else:
print("txt2img mode")
sdxl_kwargs["width"] = width
sdxl_kwargs["height"] = height
pipe = self.txt2img_pipe
if not apply_watermark:
# toggles watermark for this prediction
watermark_cache = pipe.watermark
pipe.watermark = None
pipe.scheduler = SCHEDULERS[scheduler].from_config(pipe.scheduler.config)
generator = torch.Generator("cuda").manual_seed(seed)
common_args = {
"prompt": [prompt] * num_outputs,
"negative_prompt": [negative_prompt] * num_outputs,
"guidance_scale": guidance_scale,
"generator": generator,
"num_inference_steps": num_inference_steps,
}
if self.is_lora:
sdxl_kwargs["cross_attention_kwargs"] = {"scale": lora_scale}
output = pipe(**common_args, **sdxl_kwargs)
if not apply_watermark:
pipe.watermark = watermark_cache
if not disable_safety_checker:
_, has_nsfw_content = self.run_safety_checker(output.images)
output_paths = []
for i, image in enumerate(output.images):
if not disable_safety_checker:
if has_nsfw_content[i]:
print(f"NSFW content detected in image {i}")
continue
output_path = f"/tmp/out-{i}.png"
image.save(output_path)
output_paths.append(Path(output_path))
if len(output_paths) == 0:
raise Exception(
f"NSFW content detected. Try running it again, or try a different prompt."
)
return output_paths