Upload folder using huggingface_hub
Browse files- .gitmodules +4 -0
- README.md +12 -0
- models/newdream-sdxl-20/.gitattributes +35 -0
- models/newdream-sdxl-20/.gitignore +2 -0
- models/newdream-sdxl-20/README.md +66 -0
- models/newdream-sdxl-20/model_index.json +33 -0
- models/newdream-sdxl-20/scheduler/scheduler_config.json +18 -0
- models/newdream-sdxl-20/text_encoder/config.json +24 -0
- models/newdream-sdxl-20/text_encoder/model.safetensors +3 -0
- models/newdream-sdxl-20/text_encoder/pytorch_model.bin +3 -0
- models/newdream-sdxl-20/text_encoder_2/config.json +24 -0
- models/newdream-sdxl-20/text_encoder_2/model.safetensors +3 -0
- models/newdream-sdxl-20/text_encoder_2/pytorch_model.bin +3 -0
- models/newdream-sdxl-20/tokenizer/merges.txt +0 -0
- models/newdream-sdxl-20/tokenizer/special_tokens_map.json +24 -0
- models/newdream-sdxl-20/tokenizer/tokenizer_config.json +33 -0
- models/newdream-sdxl-20/tokenizer/vocab.json +0 -0
- models/newdream-sdxl-20/tokenizer_2/merges.txt +0 -0
- models/newdream-sdxl-20/tokenizer_2/special_tokens_map.json +24 -0
- models/newdream-sdxl-20/tokenizer_2/tokenizer_config.json +33 -0
- models/newdream-sdxl-20/tokenizer_2/vocab.json +0 -0
- models/newdream-sdxl-20/unet/config.json +71 -0
- models/newdream-sdxl-20/unet/diffusion_pytorch_model.bin +3 -0
- models/newdream-sdxl-20/unet/diffusion_pytorch_model.safetensors +3 -0
- models/newdream-sdxl-20/vae/config.json +31 -0
- models/newdream-sdxl-20/vae/diffusion_pytorch_model.bin +3 -0
- models/newdream-sdxl-20/vae/diffusion_pytorch_model.safetensors +3 -0
- pyproject.toml +26 -0
- requirements.txt +2 -0
- src/main.py +50 -0
- src/pipeline.py +1289 -0
.gitmodules
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[submodule "newdream-sdxl-20"]
|
2 |
+
path = models/newdream-sdxl-20
|
3 |
+
url = https://huggingface.co/stablediffusionapi/newdream-sdxl-20
|
4 |
+
branch = main
|
README.md
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# edge-maxxing-newdream-sdxl
|
2 |
+
|
3 |
+
This holds the baseline for the SDXL Nvidia GeForce RTX 4090 contest, which can be forked freely and optimized
|
4 |
+
|
5 |
+
Some recommendations are as follows:
|
6 |
+
- Installing dependencies should be done in pyproject.toml, including git dependencies
|
7 |
+
- Compiled models should be included directly in the repository(rather than compiling during loading), loading time matters far more than file sizes
|
8 |
+
- Avoid changing `src/main.py`, as that includes mostly protocol logic. Most changes should be in `models` and `src/pipeline.py`
|
9 |
+
- Change `requirements.txt` to add extra arguments to be used when installing the package
|
10 |
+
|
11 |
+
For testing, you need a docker container with pytorch and ubuntu 22.04,
|
12 |
+
you can download your listed dependencies with `pip install -r requirements.txt -e .`, and then running `start_inference`
|
models/newdream-sdxl-20/.gitattributes
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
models/newdream-sdxl-20/.gitignore
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
step_*
|
2 |
+
epoch_*
|
models/newdream-sdxl-20/README.md
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
license: creativeml-openrail-m
|
3 |
+
tags:
|
4 |
+
- stablediffusionapi.com
|
5 |
+
- stable-diffusion-api
|
6 |
+
- text-to-image
|
7 |
+
- ultra-realistic
|
8 |
+
pinned: true
|
9 |
+
---
|
10 |
+
|
11 |
+
# NewDream-SDXL 2.0 API Inference
|
12 |
+
|
13 |
+

|
14 |
+
## Get API Key
|
15 |
+
|
16 |
+
Get API key from [Stable Diffusion API](http://stablediffusionapi.com/), No Payment needed.
|
17 |
+
|
18 |
+
Replace Key in below code, change **model_id** to "newdream-sdxl-20"
|
19 |
+
|
20 |
+
Coding in PHP/Node/Java etc? Have a look at docs for more code examples: [View docs](https://stablediffusionapi.com/docs)
|
21 |
+
|
22 |
+
Try model for free: [Generate Images](https://stablediffusionapi.com/models/newdream-sdxl-20)
|
23 |
+
|
24 |
+
Model link: [View model](https://stablediffusionapi.com/models/newdream-sdxl-20)
|
25 |
+
|
26 |
+
Credits: [View credits](https://civitai.com/?query=NewDream-SDXL%202.0)
|
27 |
+
|
28 |
+
View all models: [View Models](https://stablediffusionapi.com/models)
|
29 |
+
|
30 |
+
import requests
|
31 |
+
import json
|
32 |
+
|
33 |
+
url = "https://stablediffusionapi.com/api/v4/dreambooth"
|
34 |
+
|
35 |
+
payload = json.dumps({
|
36 |
+
"key": "your_api_key",
|
37 |
+
"model_id": "newdream-sdxl-20",
|
38 |
+
"prompt": "ultra realistic close up portrait ((beautiful pale cyberpunk female with heavy black eyeliner)), blue eyes, shaved side haircut, hyper detail, cinematic lighting, magic neon, dark red city, Canon EOS R3, nikon, f/1.4, ISO 200, 1/160s, 8K, RAW, unedited, symmetrical balance, in-frame, 8K",
|
39 |
+
"negative_prompt": "painting, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, deformed, ugly, blurry, bad anatomy, bad proportions, extra limbs, cloned face, skinny, glitchy, double torso, extra arms, extra hands, mangled fingers, missing lips, ugly face, distorted face, extra legs, anime",
|
40 |
+
"width": "512",
|
41 |
+
"height": "512",
|
42 |
+
"samples": "1",
|
43 |
+
"num_inference_steps": "30",
|
44 |
+
"safety_checker": "no",
|
45 |
+
"enhance_prompt": "yes",
|
46 |
+
"seed": None,
|
47 |
+
"guidance_scale": 7.5,
|
48 |
+
"multi_lingual": "no",
|
49 |
+
"panorama": "no",
|
50 |
+
"self_attention": "no",
|
51 |
+
"upscale": "no",
|
52 |
+
"embeddings": "embeddings_model_id",
|
53 |
+
"lora": "lora_model_id",
|
54 |
+
"webhook": None,
|
55 |
+
"track_id": None
|
56 |
+
})
|
57 |
+
|
58 |
+
headers = {
|
59 |
+
'Content-Type': 'application/json'
|
60 |
+
}
|
61 |
+
|
62 |
+
response = requests.request("POST", url, headers=headers, data=payload)
|
63 |
+
|
64 |
+
print(response.text)
|
65 |
+
|
66 |
+
> Use this coupon code to get 25% off **DMGG0RBN**
|
models/newdream-sdxl-20/model_index.json
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_class_name": "StableDiffusionXLPipeline",
|
3 |
+
"_diffusers_version": "0.21.2",
|
4 |
+
"force_zeros_for_empty_prompt": true,
|
5 |
+
"scheduler": [
|
6 |
+
"diffusers",
|
7 |
+
"EulerDiscreteScheduler"
|
8 |
+
],
|
9 |
+
"text_encoder": [
|
10 |
+
"transformers",
|
11 |
+
"CLIPTextModel"
|
12 |
+
],
|
13 |
+
"text_encoder_2": [
|
14 |
+
"transformers",
|
15 |
+
"CLIPTextModelWithProjection"
|
16 |
+
],
|
17 |
+
"tokenizer": [
|
18 |
+
"transformers",
|
19 |
+
"CLIPTokenizer"
|
20 |
+
],
|
21 |
+
"tokenizer_2": [
|
22 |
+
"transformers",
|
23 |
+
"CLIPTokenizer"
|
24 |
+
],
|
25 |
+
"unet": [
|
26 |
+
"diffusers",
|
27 |
+
"UNet2DConditionModel"
|
28 |
+
],
|
29 |
+
"vae": [
|
30 |
+
"diffusers",
|
31 |
+
"AutoencoderKL"
|
32 |
+
]
|
33 |
+
}
|
models/newdream-sdxl-20/scheduler/scheduler_config.json
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_class_name": "EulerDiscreteScheduler",
|
3 |
+
"_diffusers_version": "0.21.2",
|
4 |
+
"beta_end": 0.012,
|
5 |
+
"beta_schedule": "scaled_linear",
|
6 |
+
"beta_start": 0.00085,
|
7 |
+
"clip_sample": false,
|
8 |
+
"interpolation_type": "linear",
|
9 |
+
"num_train_timesteps": 1000,
|
10 |
+
"prediction_type": "epsilon",
|
11 |
+
"sample_max_value": 1.0,
|
12 |
+
"set_alpha_to_one": false,
|
13 |
+
"skip_prk_steps": true,
|
14 |
+
"steps_offset": 1,
|
15 |
+
"timestep_spacing": "leading",
|
16 |
+
"trained_betas": null,
|
17 |
+
"use_karras_sigmas": false
|
18 |
+
}
|
models/newdream-sdxl-20/text_encoder/config.json
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"CLIPTextModel"
|
4 |
+
],
|
5 |
+
"attention_dropout": 0.0,
|
6 |
+
"bos_token_id": 0,
|
7 |
+
"dropout": 0.0,
|
8 |
+
"eos_token_id": 2,
|
9 |
+
"hidden_act": "quick_gelu",
|
10 |
+
"hidden_size": 768,
|
11 |
+
"initializer_factor": 1.0,
|
12 |
+
"initializer_range": 0.02,
|
13 |
+
"intermediate_size": 3072,
|
14 |
+
"layer_norm_eps": 1e-05,
|
15 |
+
"max_position_embeddings": 77,
|
16 |
+
"model_type": "clip_text_model",
|
17 |
+
"num_attention_heads": 12,
|
18 |
+
"num_hidden_layers": 12,
|
19 |
+
"pad_token_id": 1,
|
20 |
+
"projection_dim": 768,
|
21 |
+
"torch_dtype": "float16",
|
22 |
+
"transformers_version": "4.33.1",
|
23 |
+
"vocab_size": 49408
|
24 |
+
}
|
models/newdream-sdxl-20/text_encoder/model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:57f094c002b6f50986b68a714285e72a23c17d9e1b146b078a2219397c51e37a
|
3 |
+
size 246144152
|
models/newdream-sdxl-20/text_encoder/pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:192a06f4ef7ece4acb33fc3c717790ee37b1f5d85e48e0dcac54dfea93e584a2
|
3 |
+
size 246185562
|
models/newdream-sdxl-20/text_encoder_2/config.json
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"CLIPTextModelWithProjection"
|
4 |
+
],
|
5 |
+
"attention_dropout": 0.0,
|
6 |
+
"bos_token_id": 0,
|
7 |
+
"dropout": 0.0,
|
8 |
+
"eos_token_id": 2,
|
9 |
+
"hidden_act": "gelu",
|
10 |
+
"hidden_size": 1280,
|
11 |
+
"initializer_factor": 1.0,
|
12 |
+
"initializer_range": 0.02,
|
13 |
+
"intermediate_size": 5120,
|
14 |
+
"layer_norm_eps": 1e-05,
|
15 |
+
"max_position_embeddings": 77,
|
16 |
+
"model_type": "clip_text_model",
|
17 |
+
"num_attention_heads": 20,
|
18 |
+
"num_hidden_layers": 32,
|
19 |
+
"pad_token_id": 1,
|
20 |
+
"projection_dim": 1280,
|
21 |
+
"torch_dtype": "float16",
|
22 |
+
"transformers_version": "4.33.1",
|
23 |
+
"vocab_size": 49408
|
24 |
+
}
|
models/newdream-sdxl-20/text_encoder_2/model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8a0d55a94e8508c869f35163fb6fcf34e02ea1b614d9259b47f97c562cff9575
|
3 |
+
size 1389382176
|
models/newdream-sdxl-20/text_encoder_2/pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8841d5e4c05ce74941eb536ec3835f600cc82d36763fc5f30c69d09a886158c9
|
3 |
+
size 1389490462
|
models/newdream-sdxl-20/tokenizer/merges.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
models/newdream-sdxl-20/tokenizer/special_tokens_map.json
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"content": "<|startoftext|>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": true,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"eos_token": {
|
10 |
+
"content": "<|endoftext|>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": true,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"pad_token": "<|endoftext|>",
|
17 |
+
"unk_token": {
|
18 |
+
"content": "<|endoftext|>",
|
19 |
+
"lstrip": false,
|
20 |
+
"normalized": true,
|
21 |
+
"rstrip": false,
|
22 |
+
"single_word": false
|
23 |
+
}
|
24 |
+
}
|
models/newdream-sdxl-20/tokenizer/tokenizer_config.json
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_prefix_space": false,
|
3 |
+
"bos_token": {
|
4 |
+
"__type": "AddedToken",
|
5 |
+
"content": "<|startoftext|>",
|
6 |
+
"lstrip": false,
|
7 |
+
"normalized": true,
|
8 |
+
"rstrip": false,
|
9 |
+
"single_word": false
|
10 |
+
},
|
11 |
+
"clean_up_tokenization_spaces": true,
|
12 |
+
"do_lower_case": true,
|
13 |
+
"eos_token": {
|
14 |
+
"__type": "AddedToken",
|
15 |
+
"content": "<|endoftext|>",
|
16 |
+
"lstrip": false,
|
17 |
+
"normalized": true,
|
18 |
+
"rstrip": false,
|
19 |
+
"single_word": false
|
20 |
+
},
|
21 |
+
"errors": "replace",
|
22 |
+
"model_max_length": 77,
|
23 |
+
"pad_token": "<|endoftext|>",
|
24 |
+
"tokenizer_class": "CLIPTokenizer",
|
25 |
+
"unk_token": {
|
26 |
+
"__type": "AddedToken",
|
27 |
+
"content": "<|endoftext|>",
|
28 |
+
"lstrip": false,
|
29 |
+
"normalized": true,
|
30 |
+
"rstrip": false,
|
31 |
+
"single_word": false
|
32 |
+
}
|
33 |
+
}
|
models/newdream-sdxl-20/tokenizer/vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
models/newdream-sdxl-20/tokenizer_2/merges.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
models/newdream-sdxl-20/tokenizer_2/special_tokens_map.json
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"content": "<|startoftext|>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": true,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"eos_token": {
|
10 |
+
"content": "<|endoftext|>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": true,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"pad_token": "!",
|
17 |
+
"unk_token": {
|
18 |
+
"content": "<|endoftext|>",
|
19 |
+
"lstrip": false,
|
20 |
+
"normalized": true,
|
21 |
+
"rstrip": false,
|
22 |
+
"single_word": false
|
23 |
+
}
|
24 |
+
}
|
models/newdream-sdxl-20/tokenizer_2/tokenizer_config.json
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_prefix_space": false,
|
3 |
+
"bos_token": {
|
4 |
+
"__type": "AddedToken",
|
5 |
+
"content": "<|startoftext|>",
|
6 |
+
"lstrip": false,
|
7 |
+
"normalized": true,
|
8 |
+
"rstrip": false,
|
9 |
+
"single_word": false
|
10 |
+
},
|
11 |
+
"clean_up_tokenization_spaces": true,
|
12 |
+
"do_lower_case": true,
|
13 |
+
"eos_token": {
|
14 |
+
"__type": "AddedToken",
|
15 |
+
"content": "<|endoftext|>",
|
16 |
+
"lstrip": false,
|
17 |
+
"normalized": true,
|
18 |
+
"rstrip": false,
|
19 |
+
"single_word": false
|
20 |
+
},
|
21 |
+
"errors": "replace",
|
22 |
+
"model_max_length": 77,
|
23 |
+
"pad_token": "!",
|
24 |
+
"tokenizer_class": "CLIPTokenizer",
|
25 |
+
"unk_token": {
|
26 |
+
"__type": "AddedToken",
|
27 |
+
"content": "<|endoftext|>",
|
28 |
+
"lstrip": false,
|
29 |
+
"normalized": true,
|
30 |
+
"rstrip": false,
|
31 |
+
"single_word": false
|
32 |
+
}
|
33 |
+
}
|
models/newdream-sdxl-20/tokenizer_2/vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
models/newdream-sdxl-20/unet/config.json
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_class_name": "UNet2DConditionModel",
|
3 |
+
"_diffusers_version": "0.21.2",
|
4 |
+
"act_fn": "silu",
|
5 |
+
"addition_embed_type": "text_time",
|
6 |
+
"addition_embed_type_num_heads": 64,
|
7 |
+
"addition_time_embed_dim": 256,
|
8 |
+
"attention_head_dim": [
|
9 |
+
5,
|
10 |
+
10,
|
11 |
+
20
|
12 |
+
],
|
13 |
+
"attention_type": "default",
|
14 |
+
"block_out_channels": [
|
15 |
+
320,
|
16 |
+
640,
|
17 |
+
1280
|
18 |
+
],
|
19 |
+
"center_input_sample": false,
|
20 |
+
"class_embed_type": null,
|
21 |
+
"class_embeddings_concat": false,
|
22 |
+
"conv_in_kernel": 3,
|
23 |
+
"conv_out_kernel": 3,
|
24 |
+
"cross_attention_dim": 2048,
|
25 |
+
"cross_attention_norm": null,
|
26 |
+
"down_block_types": [
|
27 |
+
"DownBlock2D",
|
28 |
+
"CrossAttnDownBlock2D",
|
29 |
+
"CrossAttnDownBlock2D"
|
30 |
+
],
|
31 |
+
"downsample_padding": 1,
|
32 |
+
"dropout": 0.0,
|
33 |
+
"dual_cross_attention": false,
|
34 |
+
"encoder_hid_dim": null,
|
35 |
+
"encoder_hid_dim_type": null,
|
36 |
+
"flip_sin_to_cos": true,
|
37 |
+
"freq_shift": 0,
|
38 |
+
"in_channels": 4,
|
39 |
+
"layers_per_block": 2,
|
40 |
+
"mid_block_only_cross_attention": null,
|
41 |
+
"mid_block_scale_factor": 1,
|
42 |
+
"mid_block_type": "UNetMidBlock2DCrossAttn",
|
43 |
+
"norm_eps": 1e-05,
|
44 |
+
"norm_num_groups": 32,
|
45 |
+
"num_attention_heads": null,
|
46 |
+
"num_class_embeds": null,
|
47 |
+
"only_cross_attention": false,
|
48 |
+
"out_channels": 4,
|
49 |
+
"projection_class_embeddings_input_dim": 2816,
|
50 |
+
"resnet_out_scale_factor": 1.0,
|
51 |
+
"resnet_skip_time_act": false,
|
52 |
+
"resnet_time_scale_shift": "default",
|
53 |
+
"sample_size": 128,
|
54 |
+
"time_cond_proj_dim": null,
|
55 |
+
"time_embedding_act_fn": null,
|
56 |
+
"time_embedding_dim": null,
|
57 |
+
"time_embedding_type": "positional",
|
58 |
+
"timestep_post_act": null,
|
59 |
+
"transformer_layers_per_block": [
|
60 |
+
1,
|
61 |
+
2,
|
62 |
+
10
|
63 |
+
],
|
64 |
+
"up_block_types": [
|
65 |
+
"CrossAttnUpBlock2D",
|
66 |
+
"CrossAttnUpBlock2D",
|
67 |
+
"UpBlock2D"
|
68 |
+
],
|
69 |
+
"upcast_attention": false,
|
70 |
+
"use_linear_projection": true
|
71 |
+
}
|
models/newdream-sdxl-20/unet/diffusion_pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:56913b74b493462516ce770d525cca996feef7acd44cf0cba65de667a6c1d58c
|
3 |
+
size 5135669022
|
models/newdream-sdxl-20/unet/diffusion_pytorch_model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9715fb3c6d0d81f46fbe6be46ddce05d91806aaf041504a52a44e1ec9e4f660f
|
3 |
+
size 5135149760
|
models/newdream-sdxl-20/vae/config.json
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_class_name": "AutoencoderKL",
|
3 |
+
"_diffusers_version": "0.21.2",
|
4 |
+
"act_fn": "silu",
|
5 |
+
"block_out_channels": [
|
6 |
+
128,
|
7 |
+
256,
|
8 |
+
512,
|
9 |
+
512
|
10 |
+
],
|
11 |
+
"down_block_types": [
|
12 |
+
"DownEncoderBlock2D",
|
13 |
+
"DownEncoderBlock2D",
|
14 |
+
"DownEncoderBlock2D",
|
15 |
+
"DownEncoderBlock2D"
|
16 |
+
],
|
17 |
+
"force_upcast": true,
|
18 |
+
"in_channels": 3,
|
19 |
+
"latent_channels": 4,
|
20 |
+
"layers_per_block": 2,
|
21 |
+
"norm_num_groups": 32,
|
22 |
+
"out_channels": 3,
|
23 |
+
"sample_size": 1024,
|
24 |
+
"scaling_factor": 0.13025,
|
25 |
+
"up_block_types": [
|
26 |
+
"UpDecoderBlock2D",
|
27 |
+
"UpDecoderBlock2D",
|
28 |
+
"UpDecoderBlock2D",
|
29 |
+
"UpDecoderBlock2D"
|
30 |
+
]
|
31 |
+
}
|
models/newdream-sdxl-20/vae/diffusion_pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:33c40ff3dc7adeb21dce76cd411d65828037efa0aa54432e3592418401cf8467
|
3 |
+
size 167404866
|
models/newdream-sdxl-20/vae/diffusion_pytorch_model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:915b909d0eeef5985462226b2c9950ca9da42b5a6ec8c296c2e73f6419ae465c
|
3 |
+
size 167335342
|
pyproject.toml
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[build-system]
|
2 |
+
requires = ["setuptools >= 61.0"]
|
3 |
+
build-backend = "setuptools.build_meta"
|
4 |
+
|
5 |
+
[project]
|
6 |
+
name = "edge-maxxing-4090-newdream"
|
7 |
+
description = "An edge-maxxing model submission for the 4090 newdream contest"
|
8 |
+
requires-python = ">=3.10,<3.11"
|
9 |
+
version = "1.0.0"
|
10 |
+
dependencies = [
|
11 |
+
"diffusers==0.30.3",
|
12 |
+
"onediff==1.2.0",
|
13 |
+
"onediffx==1.2.0",
|
14 |
+
"accelerate==0.31.0",
|
15 |
+
"numpy==1.26.4",
|
16 |
+
"xformers==0.0.25.post1",
|
17 |
+
"triton==2.2.0",
|
18 |
+
"transformers==4.41.2",
|
19 |
+
"omegaconf==2.3.0",
|
20 |
+
"torch==2.2.2",
|
21 |
+
"torchvision==0.17.2",
|
22 |
+
"edge-maxxing-pipelines @ git+https://github.com/womboai/edge-maxxing#subdirectory=pipelines",
|
23 |
+
]
|
24 |
+
|
25 |
+
[project.scripts]
|
26 |
+
start_inference = "main:main"
|
requirements.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
https://github.com/siliconflow/oneflow_releases/releases/download/community_cu118/oneflow-0.9.1.dev20240802%2Bcu118-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
|
2 |
+
https://github.com/chengzeyi/stable-fast/releases/download/v1.0.5/stable_fast-1.0.5+torch222cu121-cp310-cp310-manylinux2014_x86_64.whl
|
src/main.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from io import BytesIO
|
2 |
+
from multiprocessing.connection import Listener
|
3 |
+
from os import chmod, remove
|
4 |
+
from os.path import abspath, exists
|
5 |
+
from pathlib import Path
|
6 |
+
|
7 |
+
from PIL.JpegImagePlugin import JpegImageFile
|
8 |
+
from pipelines.models import TextToImageRequest
|
9 |
+
|
10 |
+
from pipeline import load_pipeline, infer
|
11 |
+
|
12 |
+
SOCKET = abspath(Path(__file__).parent.parent / "inferences.sock")
|
13 |
+
|
14 |
+
|
15 |
+
def main():
|
16 |
+
print(f"Loading pipeline")
|
17 |
+
pipeline = load_pipeline()
|
18 |
+
|
19 |
+
print(f"Pipeline loaded, creating socket at '{SOCKET}'")
|
20 |
+
|
21 |
+
if exists(SOCKET):
|
22 |
+
remove(SOCKET)
|
23 |
+
|
24 |
+
with Listener(SOCKET) as listener:
|
25 |
+
chmod(SOCKET, 0o777)
|
26 |
+
|
27 |
+
print(f"Awaiting connections")
|
28 |
+
with listener.accept() as connection:
|
29 |
+
print(f"Connected")
|
30 |
+
|
31 |
+
while True:
|
32 |
+
try:
|
33 |
+
request = TextToImageRequest.model_validate_json(connection.recv_bytes().decode("utf-8"))
|
34 |
+
except EOFError:
|
35 |
+
print(f"Inference socket exiting")
|
36 |
+
|
37 |
+
return
|
38 |
+
|
39 |
+
image = infer(request, pipeline)
|
40 |
+
|
41 |
+
data = BytesIO()
|
42 |
+
image.save(data, format=JpegImageFile.format)
|
43 |
+
|
44 |
+
packet = data.getvalue()
|
45 |
+
|
46 |
+
connection.send_bytes(packet)
|
47 |
+
|
48 |
+
|
49 |
+
if __name__ == '__main__':
|
50 |
+
main()
|
src/pipeline.py
ADDED
@@ -0,0 +1,1289 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from PIL.Image import Image
|
3 |
+
from diffusers import UniPCMultistepScheduler
|
4 |
+
from sfast.compilers.diffusion_pipeline_compiler import (compile,
|
5 |
+
CompilationConfig)
|
6 |
+
from pipelines.models import TextToImageRequest
|
7 |
+
from torch import Generator
|
8 |
+
|
9 |
+
import inspect
|
10 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
11 |
+
|
12 |
+
import torch
|
13 |
+
from transformers import (
|
14 |
+
CLIPImageProcessor,
|
15 |
+
CLIPTextModel,
|
16 |
+
CLIPTextModelWithProjection,
|
17 |
+
CLIPTokenizer,
|
18 |
+
CLIPVisionModelWithProjection,
|
19 |
+
)
|
20 |
+
|
21 |
+
from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
|
22 |
+
from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
|
23 |
+
from diffusers.loaders import (
|
24 |
+
FromSingleFileMixin,
|
25 |
+
IPAdapterMixin,
|
26 |
+
StableDiffusionXLLoraLoaderMixin,
|
27 |
+
TextualInversionLoaderMixin,
|
28 |
+
)
|
29 |
+
from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
|
30 |
+
from diffusers.models.attention_processor import (
|
31 |
+
AttnProcessor2_0,
|
32 |
+
FusedAttnProcessor2_0,
|
33 |
+
XFormersAttnProcessor,
|
34 |
+
)
|
35 |
+
from diffusers.models.lora import adjust_lora_scale_text_encoder
|
36 |
+
from diffusers.schedulers import KarrasDiffusionSchedulers
|
37 |
+
from diffusers.utils import (
|
38 |
+
USE_PEFT_BACKEND,
|
39 |
+
deprecate,
|
40 |
+
is_invisible_watermark_available,
|
41 |
+
is_torch_xla_available,
|
42 |
+
logging,
|
43 |
+
replace_example_docstring,
|
44 |
+
scale_lora_layers,
|
45 |
+
unscale_lora_layers,
|
46 |
+
)
|
47 |
+
from diffusers.utils.torch_utils import randn_tensor
|
48 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
|
49 |
+
from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
|
50 |
+
|
51 |
+
|
52 |
+
if is_invisible_watermark_available():
|
53 |
+
from .watermark import StableDiffusionXLWatermarker
|
54 |
+
|
55 |
+
if is_torch_xla_available():
|
56 |
+
import torch_xla.core.xla_model as xm
|
57 |
+
|
58 |
+
XLA_AVAILABLE = True
|
59 |
+
else:
|
60 |
+
XLA_AVAILABLE = False
|
61 |
+
|
62 |
+
|
63 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
64 |
+
|
65 |
+
EXAMPLE_DOC_STRING = """
|
66 |
+
Examples:
|
67 |
+
```py
|
68 |
+
>>> import torch
|
69 |
+
>>> from diffusers import StableDiffusionXLPipeline
|
70 |
+
|
71 |
+
>>> pipe = StableDiffusionXLPipeline.from_pretrained(
|
72 |
+
diffusers. "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
73 |
+
diffusers. )
|
74 |
+
>>> pipe = pipe.to("cuda")
|
75 |
+
|
76 |
+
>>> prompt = "a photo of an astronaut riding a horse on mars"
|
77 |
+
>>> image = pipe(prompt).images[0]
|
78 |
+
```
|
79 |
+
"""
|
80 |
+
|
81 |
+
def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
|
82 |
+
"""
|
83 |
+
Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
|
84 |
+
Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
|
85 |
+
"""
|
86 |
+
std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
|
87 |
+
std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
|
88 |
+
# rescale the results from guidance (fixes overexposure)
|
89 |
+
noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
|
90 |
+
# mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
|
91 |
+
noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
|
92 |
+
return noise_cfg
|
93 |
+
|
94 |
+
|
95 |
+
def retrieve_timesteps(
|
96 |
+
scheduler,
|
97 |
+
num_inference_steps: Optional[int] = None,
|
98 |
+
device: Optional[Union[str, torch.device]] = None,
|
99 |
+
timesteps: Optional[List[int]] = None,
|
100 |
+
sigmas: Optional[List[float]] = None,
|
101 |
+
**kwargs,
|
102 |
+
):
|
103 |
+
"""
|
104 |
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
105 |
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
106 |
+
|
107 |
+
Args:
|
108 |
+
scheduler (`SchedulerMixin`):
|
109 |
+
The scheduler to get timesteps from.
|
110 |
+
num_inference_steps (`int`):
|
111 |
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
112 |
+
must be `None`.
|
113 |
+
device (`str` or `torch.device`, *optional*):
|
114 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
115 |
+
timesteps (`List[int]`, *optional*):
|
116 |
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
117 |
+
`num_inference_steps` and `sigmas` must be `None`.
|
118 |
+
sigmas (`List[float]`, *optional*):
|
119 |
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
120 |
+
`num_inference_steps` and `timesteps` must be `None`.
|
121 |
+
|
122 |
+
Returns:
|
123 |
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
124 |
+
second element is the number of inference steps.
|
125 |
+
"""
|
126 |
+
if timesteps is not None and sigmas is not None:
|
127 |
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
128 |
+
if timesteps is not None:
|
129 |
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
130 |
+
if not accepts_timesteps:
|
131 |
+
raise ValueError(
|
132 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
133 |
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
134 |
+
)
|
135 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
136 |
+
timesteps = scheduler.timesteps
|
137 |
+
num_inference_steps = len(timesteps)
|
138 |
+
elif sigmas is not None:
|
139 |
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
140 |
+
if not accept_sigmas:
|
141 |
+
raise ValueError(
|
142 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
143 |
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
144 |
+
)
|
145 |
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
146 |
+
timesteps = scheduler.timesteps
|
147 |
+
num_inference_steps = len(timesteps)
|
148 |
+
else:
|
149 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
150 |
+
timesteps = scheduler.timesteps
|
151 |
+
return timesteps, num_inference_steps
|
152 |
+
|
153 |
+
|
154 |
+
class StableDiffusionXLPipeline(
|
155 |
+
DiffusionPipeline,
|
156 |
+
StableDiffusionMixin,
|
157 |
+
FromSingleFileMixin,
|
158 |
+
StableDiffusionXLLoraLoaderMixin,
|
159 |
+
TextualInversionLoaderMixin,
|
160 |
+
IPAdapterMixin,
|
161 |
+
):
|
162 |
+
r"""
|
163 |
+
Pipeline for text-to-image generation using Stable Diffusion XL.
|
164 |
+
|
165 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
166 |
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
167 |
+
|
168 |
+
The pipeline also inherits the following loading methods:
|
169 |
+
- [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
|
170 |
+
- [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
|
171 |
+
- [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
172 |
+
- [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
173 |
+
- [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
|
174 |
+
|
175 |
+
Args:
|
176 |
+
vae ([`AutoencoderKL`]):
|
177 |
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
178 |
+
text_encoder ([`CLIPTextModel`]):
|
179 |
+
Frozen text-encoder. Stable Diffusion XL uses the text portion of
|
180 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
|
181 |
+
the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
|
182 |
+
text_encoder_2 ([` CLIPTextModelWithProjection`]):
|
183 |
+
Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
|
184 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
|
185 |
+
specifically the
|
186 |
+
[laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
|
187 |
+
variant.
|
188 |
+
tokenizer (`CLIPTokenizer`):
|
189 |
+
Tokenizer of class
|
190 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
191 |
+
tokenizer_2 (`CLIPTokenizer`):
|
192 |
+
Second Tokenizer of class
|
193 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
194 |
+
unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
|
195 |
+
scheduler ([`SchedulerMixin`]):
|
196 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
197 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
198 |
+
force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
|
199 |
+
Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
|
200 |
+
`stabilityai/stable-diffusion-xl-base-1-0`.
|
201 |
+
add_watermarker (`bool`, *optional*):
|
202 |
+
Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
|
203 |
+
watermark output images. If not defined, it will default to True if the package is installed, otherwise no
|
204 |
+
watermarker will be used.
|
205 |
+
"""
|
206 |
+
|
207 |
+
model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
|
208 |
+
_optional_components = [
|
209 |
+
"tokenizer",
|
210 |
+
"tokenizer_2",
|
211 |
+
"text_encoder",
|
212 |
+
"text_encoder_2",
|
213 |
+
"image_encoder",
|
214 |
+
"feature_extractor",
|
215 |
+
]
|
216 |
+
_callback_tensor_inputs = [
|
217 |
+
"latents",
|
218 |
+
"prompt_embeds",
|
219 |
+
"negative_prompt_embeds",
|
220 |
+
"add_text_embeds",
|
221 |
+
"add_time_ids",
|
222 |
+
"negative_pooled_prompt_embeds",
|
223 |
+
"negative_add_time_ids",
|
224 |
+
]
|
225 |
+
|
226 |
+
def __init__(
|
227 |
+
self,
|
228 |
+
vae: AutoencoderKL,
|
229 |
+
text_encoder: CLIPTextModel,
|
230 |
+
text_encoder_2: CLIPTextModelWithProjection,
|
231 |
+
tokenizer: CLIPTokenizer,
|
232 |
+
tokenizer_2: CLIPTokenizer,
|
233 |
+
unet: UNet2DConditionModel,
|
234 |
+
scheduler: KarrasDiffusionSchedulers,
|
235 |
+
image_encoder: CLIPVisionModelWithProjection = None,
|
236 |
+
feature_extractor: CLIPImageProcessor = None,
|
237 |
+
force_zeros_for_empty_prompt: bool = True,
|
238 |
+
add_watermarker: Optional[bool] = None,
|
239 |
+
):
|
240 |
+
super().__init__()
|
241 |
+
|
242 |
+
self.register_modules(
|
243 |
+
vae=vae,
|
244 |
+
text_encoder=text_encoder,
|
245 |
+
text_encoder_2=text_encoder_2,
|
246 |
+
tokenizer=tokenizer,
|
247 |
+
tokenizer_2=tokenizer_2,
|
248 |
+
unet=unet,
|
249 |
+
scheduler=scheduler,
|
250 |
+
image_encoder=image_encoder,
|
251 |
+
feature_extractor=feature_extractor,
|
252 |
+
)
|
253 |
+
self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
|
254 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
255 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
256 |
+
|
257 |
+
self.default_sample_size = self.unet.config.sample_size
|
258 |
+
|
259 |
+
add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
|
260 |
+
|
261 |
+
if add_watermarker:
|
262 |
+
self.watermark = StableDiffusionXLWatermarker()
|
263 |
+
else:
|
264 |
+
self.watermark = None
|
265 |
+
|
266 |
+
def encode_prompt(
|
267 |
+
self,
|
268 |
+
prompt: str,
|
269 |
+
prompt_2: Optional[str] = None,
|
270 |
+
device: Optional[torch.device] = None,
|
271 |
+
num_images_per_prompt: int = 1,
|
272 |
+
do_classifier_free_guidance: bool = True,
|
273 |
+
negative_prompt: Optional[str] = None,
|
274 |
+
negative_prompt_2: Optional[str] = None,
|
275 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
276 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
277 |
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
278 |
+
negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
279 |
+
lora_scale: Optional[float] = None,
|
280 |
+
clip_skip: Optional[int] = None,
|
281 |
+
):
|
282 |
+
r"""
|
283 |
+
Encodes the prompt into text encoder hidden states.
|
284 |
+
|
285 |
+
Args:
|
286 |
+
prompt (`str` or `List[str]`, *optional*):
|
287 |
+
prompt to be encoded
|
288 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
289 |
+
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
290 |
+
used in both text-encoders
|
291 |
+
device: (`torch.device`):
|
292 |
+
torch device
|
293 |
+
num_images_per_prompt (`int`):
|
294 |
+
number of images that should be generated per prompt
|
295 |
+
do_classifier_free_guidance (`bool`):
|
296 |
+
whether to use classifier free guidance or not
|
297 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
298 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
299 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
300 |
+
less than `1`).
|
301 |
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
302 |
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
303 |
+
`text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
|
304 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
305 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
306 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
307 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
308 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
309 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
310 |
+
argument.
|
311 |
+
pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
312 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
313 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
314 |
+
negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
315 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
316 |
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
317 |
+
input argument.
|
318 |
+
lora_scale (`float`, *optional*):
|
319 |
+
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
320 |
+
clip_skip (`int`, *optional*):
|
321 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
322 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
323 |
+
"""
|
324 |
+
device = device or self._execution_device
|
325 |
+
|
326 |
+
if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
|
327 |
+
self._lora_scale = lora_scale
|
328 |
+
|
329 |
+
# dynamically adjust the LoRA scale
|
330 |
+
if self.text_encoder is not None:
|
331 |
+
if not USE_PEFT_BACKEND:
|
332 |
+
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
333 |
+
else:
|
334 |
+
scale_lora_layers(self.text_encoder, lora_scale)
|
335 |
+
|
336 |
+
if self.text_encoder_2 is not None:
|
337 |
+
if not USE_PEFT_BACKEND:
|
338 |
+
adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
|
339 |
+
else:
|
340 |
+
scale_lora_layers(self.text_encoder_2, lora_scale)
|
341 |
+
|
342 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
343 |
+
|
344 |
+
if prompt is not None:
|
345 |
+
batch_size = len(prompt)
|
346 |
+
else:
|
347 |
+
batch_size = prompt_embeds.shape[0]
|
348 |
+
|
349 |
+
tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
|
350 |
+
text_encoders = (
|
351 |
+
[self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
|
352 |
+
)
|
353 |
+
|
354 |
+
if prompt_embeds is None:
|
355 |
+
prompt_2 = prompt_2 or prompt
|
356 |
+
prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
|
357 |
+
|
358 |
+
prompt_embeds_list = []
|
359 |
+
prompts = [prompt, prompt_2]
|
360 |
+
for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
|
361 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
362 |
+
prompt = self.maybe_convert_prompt(prompt, tokenizer)
|
363 |
+
|
364 |
+
text_inputs = tokenizer(
|
365 |
+
prompt,
|
366 |
+
padding="max_length",
|
367 |
+
max_length=tokenizer.model_max_length,
|
368 |
+
truncation=True,
|
369 |
+
return_tensors="pt",
|
370 |
+
)
|
371 |
+
|
372 |
+
text_input_ids = text_inputs.input_ids
|
373 |
+
untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
374 |
+
|
375 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
376 |
+
text_input_ids, untruncated_ids
|
377 |
+
):
|
378 |
+
removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
|
379 |
+
logger.warning(
|
380 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
381 |
+
f" {tokenizer.model_max_length} tokens: {removed_text}"
|
382 |
+
)
|
383 |
+
|
384 |
+
prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
|
385 |
+
|
386 |
+
pooled_prompt_embeds = prompt_embeds[0]
|
387 |
+
if clip_skip is None:
|
388 |
+
prompt_embeds = prompt_embeds.hidden_states[-2]
|
389 |
+
else:
|
390 |
+
prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
|
391 |
+
|
392 |
+
prompt_embeds_list.append(prompt_embeds)
|
393 |
+
|
394 |
+
prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
|
395 |
+
|
396 |
+
zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
|
397 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
|
398 |
+
negative_prompt_embeds = torch.zeros_like(prompt_embeds)
|
399 |
+
negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
|
400 |
+
elif do_classifier_free_guidance and negative_prompt_embeds is None:
|
401 |
+
negative_prompt = negative_prompt or ""
|
402 |
+
negative_prompt_2 = negative_prompt_2 or negative_prompt
|
403 |
+
|
404 |
+
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
405 |
+
negative_prompt_2 = (
|
406 |
+
batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
|
407 |
+
)
|
408 |
+
|
409 |
+
uncond_tokens: List[str]
|
410 |
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
411 |
+
raise TypeError(
|
412 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
413 |
+
f" {type(prompt)}."
|
414 |
+
)
|
415 |
+
elif batch_size != len(negative_prompt):
|
416 |
+
raise ValueError(
|
417 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
418 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
419 |
+
" the batch size of `prompt`."
|
420 |
+
)
|
421 |
+
else:
|
422 |
+
uncond_tokens = [negative_prompt, negative_prompt_2]
|
423 |
+
|
424 |
+
negative_prompt_embeds_list = []
|
425 |
+
for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
|
426 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
427 |
+
negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
|
428 |
+
|
429 |
+
max_length = prompt_embeds.shape[1]
|
430 |
+
uncond_input = tokenizer(
|
431 |
+
negative_prompt,
|
432 |
+
padding="max_length",
|
433 |
+
max_length=max_length,
|
434 |
+
truncation=True,
|
435 |
+
return_tensors="pt",
|
436 |
+
)
|
437 |
+
|
438 |
+
negative_prompt_embeds = text_encoder(
|
439 |
+
uncond_input.input_ids.to(device),
|
440 |
+
output_hidden_states=True,
|
441 |
+
)
|
442 |
+
negative_pooled_prompt_embeds = negative_prompt_embeds[0]
|
443 |
+
negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
|
444 |
+
|
445 |
+
negative_prompt_embeds_list.append(negative_prompt_embeds)
|
446 |
+
|
447 |
+
negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
|
448 |
+
|
449 |
+
if self.text_encoder_2 is not None:
|
450 |
+
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
|
451 |
+
else:
|
452 |
+
prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
|
453 |
+
|
454 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
455 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
456 |
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
457 |
+
|
458 |
+
if do_classifier_free_guidance:
|
459 |
+
seq_len = negative_prompt_embeds.shape[1]
|
460 |
+
|
461 |
+
if self.text_encoder_2 is not None:
|
462 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
|
463 |
+
else:
|
464 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
|
465 |
+
|
466 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
467 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
468 |
+
|
469 |
+
pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
470 |
+
bs_embed * num_images_per_prompt, -1
|
471 |
+
)
|
472 |
+
if do_classifier_free_guidance:
|
473 |
+
negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
474 |
+
bs_embed * num_images_per_prompt, -1
|
475 |
+
)
|
476 |
+
|
477 |
+
if self.text_encoder is not None:
|
478 |
+
if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
|
479 |
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
480 |
+
|
481 |
+
if self.text_encoder_2 is not None:
|
482 |
+
if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
|
483 |
+
unscale_lora_layers(self.text_encoder_2, lora_scale)
|
484 |
+
|
485 |
+
return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
|
486 |
+
|
487 |
+
def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
|
488 |
+
dtype = next(self.image_encoder.parameters()).dtype
|
489 |
+
|
490 |
+
if not isinstance(image, torch.Tensor):
|
491 |
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
492 |
+
|
493 |
+
image = image.to(device=device, dtype=dtype)
|
494 |
+
if output_hidden_states:
|
495 |
+
image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
|
496 |
+
image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
|
497 |
+
uncond_image_enc_hidden_states = self.image_encoder(
|
498 |
+
torch.zeros_like(image), output_hidden_states=True
|
499 |
+
).hidden_states[-2]
|
500 |
+
uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
|
501 |
+
num_images_per_prompt, dim=0
|
502 |
+
)
|
503 |
+
return image_enc_hidden_states, uncond_image_enc_hidden_states
|
504 |
+
else:
|
505 |
+
image_embeds = self.image_encoder(image).image_embeds
|
506 |
+
image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
507 |
+
uncond_image_embeds = torch.zeros_like(image_embeds)
|
508 |
+
|
509 |
+
return image_embeds, uncond_image_embeds
|
510 |
+
|
511 |
+
def prepare_ip_adapter_image_embeds(
|
512 |
+
self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
|
513 |
+
):
|
514 |
+
image_embeds = []
|
515 |
+
if do_classifier_free_guidance:
|
516 |
+
negative_image_embeds = []
|
517 |
+
if ip_adapter_image_embeds is None:
|
518 |
+
if not isinstance(ip_adapter_image, list):
|
519 |
+
ip_adapter_image = [ip_adapter_image]
|
520 |
+
|
521 |
+
if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
|
522 |
+
raise ValueError(
|
523 |
+
f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
|
524 |
+
)
|
525 |
+
|
526 |
+
for single_ip_adapter_image, image_proj_layer in zip(
|
527 |
+
ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
|
528 |
+
):
|
529 |
+
output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
|
530 |
+
single_image_embeds, single_negative_image_embeds = self.encode_image(
|
531 |
+
single_ip_adapter_image, device, 1, output_hidden_state
|
532 |
+
)
|
533 |
+
|
534 |
+
image_embeds.append(single_image_embeds[None, :])
|
535 |
+
if do_classifier_free_guidance:
|
536 |
+
negative_image_embeds.append(single_negative_image_embeds[None, :])
|
537 |
+
else:
|
538 |
+
for single_image_embeds in ip_adapter_image_embeds:
|
539 |
+
if do_classifier_free_guidance:
|
540 |
+
single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
|
541 |
+
negative_image_embeds.append(single_negative_image_embeds)
|
542 |
+
image_embeds.append(single_image_embeds)
|
543 |
+
|
544 |
+
ip_adapter_image_embeds = []
|
545 |
+
for i, single_image_embeds in enumerate(image_embeds):
|
546 |
+
single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
|
547 |
+
if do_classifier_free_guidance:
|
548 |
+
single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
|
549 |
+
single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
|
550 |
+
|
551 |
+
single_image_embeds = single_image_embeds.to(device=device)
|
552 |
+
ip_adapter_image_embeds.append(single_image_embeds)
|
553 |
+
|
554 |
+
return ip_adapter_image_embeds
|
555 |
+
|
556 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
557 |
+
|
558 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
559 |
+
extra_step_kwargs = {}
|
560 |
+
if accepts_eta:
|
561 |
+
extra_step_kwargs["eta"] = eta
|
562 |
+
|
563 |
+
# check if the scheduler accepts generator
|
564 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
565 |
+
if accepts_generator:
|
566 |
+
extra_step_kwargs["generator"] = generator
|
567 |
+
return extra_step_kwargs
|
568 |
+
|
569 |
+
def check_inputs(
|
570 |
+
self,
|
571 |
+
prompt,
|
572 |
+
prompt_2,
|
573 |
+
height,
|
574 |
+
width,
|
575 |
+
callback_steps,
|
576 |
+
negative_prompt=None,
|
577 |
+
negative_prompt_2=None,
|
578 |
+
prompt_embeds=None,
|
579 |
+
negative_prompt_embeds=None,
|
580 |
+
pooled_prompt_embeds=None,
|
581 |
+
negative_pooled_prompt_embeds=None,
|
582 |
+
ip_adapter_image=None,
|
583 |
+
ip_adapter_image_embeds=None,
|
584 |
+
callback_on_step_end_tensor_inputs=None,
|
585 |
+
):
|
586 |
+
if height % 8 != 0 or width % 8 != 0:
|
587 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
588 |
+
|
589 |
+
if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
|
590 |
+
raise ValueError(
|
591 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
592 |
+
f" {type(callback_steps)}."
|
593 |
+
)
|
594 |
+
|
595 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
596 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
597 |
+
):
|
598 |
+
raise ValueError(
|
599 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
600 |
+
)
|
601 |
+
|
602 |
+
if prompt is not None and prompt_embeds is not None:
|
603 |
+
raise ValueError(
|
604 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
605 |
+
" only forward one of the two."
|
606 |
+
)
|
607 |
+
elif prompt_2 is not None and prompt_embeds is not None:
|
608 |
+
raise ValueError(
|
609 |
+
f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
610 |
+
" only forward one of the two."
|
611 |
+
)
|
612 |
+
elif prompt is None and prompt_embeds is None:
|
613 |
+
raise ValueError(
|
614 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
615 |
+
)
|
616 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
617 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
618 |
+
elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
|
619 |
+
raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
|
620 |
+
|
621 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
622 |
+
raise ValueError(
|
623 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
624 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
625 |
+
)
|
626 |
+
elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
|
627 |
+
raise ValueError(
|
628 |
+
f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
|
629 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
630 |
+
)
|
631 |
+
|
632 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
633 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
634 |
+
raise ValueError(
|
635 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
636 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
637 |
+
f" {negative_prompt_embeds.shape}."
|
638 |
+
)
|
639 |
+
|
640 |
+
if prompt_embeds is not None and pooled_prompt_embeds is None:
|
641 |
+
raise ValueError(
|
642 |
+
"If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
|
643 |
+
)
|
644 |
+
|
645 |
+
if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
|
646 |
+
raise ValueError(
|
647 |
+
"If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
|
648 |
+
)
|
649 |
+
|
650 |
+
if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
|
651 |
+
raise ValueError(
|
652 |
+
"Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
|
653 |
+
)
|
654 |
+
|
655 |
+
if ip_adapter_image_embeds is not None:
|
656 |
+
if not isinstance(ip_adapter_image_embeds, list):
|
657 |
+
raise ValueError(
|
658 |
+
f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
|
659 |
+
)
|
660 |
+
elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
|
661 |
+
raise ValueError(
|
662 |
+
f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
|
663 |
+
)
|
664 |
+
|
665 |
+
def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
|
666 |
+
shape = (
|
667 |
+
batch_size,
|
668 |
+
num_channels_latents,
|
669 |
+
int(height) // self.vae_scale_factor,
|
670 |
+
int(width) // self.vae_scale_factor,
|
671 |
+
)
|
672 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
673 |
+
raise ValueError(
|
674 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
675 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
676 |
+
)
|
677 |
+
|
678 |
+
if latents is None:
|
679 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
680 |
+
else:
|
681 |
+
latents = latents.to(device)
|
682 |
+
|
683 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
684 |
+
latents = latents * self.scheduler.init_noise_sigma
|
685 |
+
return latents
|
686 |
+
|
687 |
+
def _get_add_time_ids(
|
688 |
+
self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
|
689 |
+
):
|
690 |
+
add_time_ids = list(original_size + crops_coords_top_left + target_size)
|
691 |
+
|
692 |
+
passed_add_embed_dim = (
|
693 |
+
self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
|
694 |
+
)
|
695 |
+
expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
|
696 |
+
|
697 |
+
if expected_add_embed_dim != passed_add_embed_dim:
|
698 |
+
raise ValueError(
|
699 |
+
f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
|
700 |
+
)
|
701 |
+
|
702 |
+
add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
|
703 |
+
return add_time_ids
|
704 |
+
|
705 |
+
def upcast_vae(self):
|
706 |
+
dtype = self.vae.dtype
|
707 |
+
self.vae.to(dtype=torch.float32)
|
708 |
+
use_torch_2_0_or_xformers = isinstance(
|
709 |
+
self.vae.decoder.mid_block.attentions[0].processor,
|
710 |
+
(
|
711 |
+
AttnProcessor2_0,
|
712 |
+
XFormersAttnProcessor,
|
713 |
+
FusedAttnProcessor2_0,
|
714 |
+
),
|
715 |
+
)
|
716 |
+
if use_torch_2_0_or_xformers:
|
717 |
+
self.vae.post_quant_conv.to(dtype)
|
718 |
+
self.vae.decoder.conv_in.to(dtype)
|
719 |
+
self.vae.decoder.mid_block.to(dtype)
|
720 |
+
|
721 |
+
def get_guidance_scale_embedding(
|
722 |
+
self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
|
723 |
+
) -> torch.Tensor:
|
724 |
+
"""
|
725 |
+
See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
|
726 |
+
|
727 |
+
Args:
|
728 |
+
w (`torch.Tensor`):
|
729 |
+
Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
|
730 |
+
embedding_dim (`int`, *optional*, defaults to 512):
|
731 |
+
Dimension of the embeddings to generate.
|
732 |
+
dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
|
733 |
+
Data type of the generated embeddings.
|
734 |
+
|
735 |
+
Returns:
|
736 |
+
`torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
|
737 |
+
"""
|
738 |
+
assert len(w.shape) == 1
|
739 |
+
w = w * 1000.0
|
740 |
+
|
741 |
+
half_dim = embedding_dim // 2
|
742 |
+
emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
|
743 |
+
emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
|
744 |
+
emb = w.to(dtype)[:, None] * emb[None, :]
|
745 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
746 |
+
if embedding_dim % 2 == 1: # zero pad
|
747 |
+
emb = torch.nn.functional.pad(emb, (0, 1))
|
748 |
+
assert emb.shape == (w.shape[0], embedding_dim)
|
749 |
+
return emb
|
750 |
+
|
751 |
+
@property
|
752 |
+
def guidance_scale(self):
|
753 |
+
return self._guidance_scale
|
754 |
+
|
755 |
+
@property
|
756 |
+
def guidance_rescale(self):
|
757 |
+
return self._guidance_rescale
|
758 |
+
|
759 |
+
@property
|
760 |
+
def clip_skip(self):
|
761 |
+
return self._clip_skip
|
762 |
+
|
763 |
+
@property
|
764 |
+
def do_classifier_free_guidance(self):
|
765 |
+
return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
|
766 |
+
|
767 |
+
@property
|
768 |
+
def cross_attention_kwargs(self):
|
769 |
+
return self._cross_attention_kwargs
|
770 |
+
|
771 |
+
@property
|
772 |
+
def denoising_end(self):
|
773 |
+
return self._denoising_end
|
774 |
+
|
775 |
+
@property
|
776 |
+
def num_timesteps(self):
|
777 |
+
return self._num_timesteps
|
778 |
+
|
779 |
+
@property
|
780 |
+
def interrupt(self):
|
781 |
+
return self._interrupt
|
782 |
+
|
783 |
+
@torch.no_grad()
|
784 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
785 |
+
def __call__(
|
786 |
+
self,
|
787 |
+
prompt: Union[str, List[str]] = None,
|
788 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
789 |
+
height: Optional[int] = None,
|
790 |
+
width: Optional[int] = None,
|
791 |
+
num_inference_steps: int = 50,
|
792 |
+
timesteps: List[int] = None,
|
793 |
+
sigmas: List[float] = None,
|
794 |
+
denoising_end: Optional[float] = None,
|
795 |
+
guidance_scale: float = 5.0,
|
796 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
797 |
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
798 |
+
num_images_per_prompt: Optional[int] = 1,
|
799 |
+
eta: float = 0.0,
|
800 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
801 |
+
latents: Optional[torch.Tensor] = None,
|
802 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
803 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
804 |
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
805 |
+
negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
806 |
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
807 |
+
ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
|
808 |
+
output_type: Optional[str] = "pil",
|
809 |
+
return_dict: bool = True,
|
810 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
811 |
+
guidance_rescale: float = 0.0,
|
812 |
+
end_cfg: float = 0.4,
|
813 |
+
original_size: Optional[Tuple[int, int]] = None,
|
814 |
+
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
815 |
+
target_size: Optional[Tuple[int, int]] = None,
|
816 |
+
negative_original_size: Optional[Tuple[int, int]] = None,
|
817 |
+
negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
|
818 |
+
negative_target_size: Optional[Tuple[int, int]] = None,
|
819 |
+
clip_skip: Optional[int] = None,
|
820 |
+
callback_on_step_end: Optional[
|
821 |
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
822 |
+
] = None,
|
823 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
824 |
+
**kwargs,
|
825 |
+
):
|
826 |
+
r"""
|
827 |
+
Function invoked when calling the pipeline for generation.
|
828 |
+
|
829 |
+
Args:
|
830 |
+
prompt (`str` or `List[str]`, *optional*):
|
831 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
832 |
+
instead.
|
833 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
834 |
+
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
835 |
+
used in both text-encoders
|
836 |
+
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
837 |
+
The height in pixels of the generated image. This is set to 1024 by default for the best results.
|
838 |
+
Anything below 512 pixels won't work well for
|
839 |
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
840 |
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
841 |
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
842 |
+
The width in pixels of the generated image. This is set to 1024 by default for the best results.
|
843 |
+
Anything below 512 pixels won't work well for
|
844 |
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
845 |
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
846 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
847 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
848 |
+
expense of slower inference.
|
849 |
+
timesteps (`List[int]`, *optional*):
|
850 |
+
Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
|
851 |
+
in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
|
852 |
+
passed will be used. Must be in descending order.
|
853 |
+
sigmas (`List[float]`, *optional*):
|
854 |
+
Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
|
855 |
+
their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
|
856 |
+
will be used.
|
857 |
+
denoising_end (`float`, *optional*):
|
858 |
+
When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
|
859 |
+
completed before it is intentionally prematurely terminated. As a result, the returned sample will
|
860 |
+
still retain a substantial amount of noise as determined by the discrete timesteps selected by the
|
861 |
+
scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
|
862 |
+
"Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
|
863 |
+
Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
|
864 |
+
guidance_scale (`float`, *optional*, defaults to 5.0):
|
865 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
866 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
867 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
868 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
869 |
+
usually at the expense of lower image quality.
|
870 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
871 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
872 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
873 |
+
less than `1`).
|
874 |
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
875 |
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
876 |
+
`text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
|
877 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
878 |
+
The number of images to generate per prompt.
|
879 |
+
eta (`float`, *optional*, defaults to 0.0):
|
880 |
+
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
881 |
+
[`schedulers.DDIMScheduler`], will be ignored for others.
|
882 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
883 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
884 |
+
to make generation deterministic.
|
885 |
+
latents (`torch.Tensor`, *optional*):
|
886 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
887 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
888 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
889 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
890 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
891 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
892 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
893 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
894 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
895 |
+
argument.
|
896 |
+
pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
897 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
898 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
899 |
+
negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
900 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
901 |
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
902 |
+
input argument.
|
903 |
+
ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
|
904 |
+
ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
|
905 |
+
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
|
906 |
+
IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
|
907 |
+
contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
|
908 |
+
provided, embeddings are computed from the `ip_adapter_image` input argument.
|
909 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
910 |
+
The output format of the generate image. Choose between
|
911 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
912 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
913 |
+
Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
|
914 |
+
of a plain tuple.
|
915 |
+
cross_attention_kwargs (`dict`, *optional*):
|
916 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
917 |
+
`self.processor` in
|
918 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
919 |
+
guidance_rescale (`float`, *optional*, defaults to 0.0):
|
920 |
+
Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
|
921 |
+
Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
|
922 |
+
[Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
|
923 |
+
Guidance rescale factor should fix overexposure when using zero terminal SNR.
|
924 |
+
original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
925 |
+
If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
|
926 |
+
`original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
|
927 |
+
explained in section 2.2 of
|
928 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
929 |
+
crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
930 |
+
`crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
|
931 |
+
`crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
|
932 |
+
`crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
|
933 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
934 |
+
target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
935 |
+
For most cases, `target_size` should be set to the desired height and width of the generated image. If
|
936 |
+
not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
|
937 |
+
section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
938 |
+
negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
939 |
+
To negatively condition the generation process based on a specific image resolution. Part of SDXL's
|
940 |
+
micro-conditioning as explained in section 2.2 of
|
941 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
942 |
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
943 |
+
negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
944 |
+
To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
|
945 |
+
micro-conditioning as explained in section 2.2 of
|
946 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
947 |
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
948 |
+
negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
949 |
+
To negatively condition the generation process based on a target image resolution. It should be as same
|
950 |
+
as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
|
951 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
952 |
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
953 |
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
954 |
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
955 |
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
956 |
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
957 |
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
958 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
959 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
960 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
961 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
962 |
+
|
963 |
+
Examples:
|
964 |
+
|
965 |
+
Returns:
|
966 |
+
[`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
|
967 |
+
[`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
|
968 |
+
`tuple`. When returning a tuple, the first element is a list with the generated images.
|
969 |
+
"""
|
970 |
+
|
971 |
+
callback = kwargs.pop("callback", None)
|
972 |
+
callback_steps = kwargs.pop("callback_steps", None)
|
973 |
+
|
974 |
+
if callback is not None:
|
975 |
+
deprecate(
|
976 |
+
"callback",
|
977 |
+
"1.0.0",
|
978 |
+
"Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
|
979 |
+
)
|
980 |
+
if callback_steps is not None:
|
981 |
+
deprecate(
|
982 |
+
"callback_steps",
|
983 |
+
"1.0.0",
|
984 |
+
"Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
|
985 |
+
)
|
986 |
+
|
987 |
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
988 |
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
989 |
+
|
990 |
+
height = height or self.default_sample_size * self.vae_scale_factor
|
991 |
+
width = width or self.default_sample_size * self.vae_scale_factor
|
992 |
+
|
993 |
+
original_size = original_size or (height, width)
|
994 |
+
target_size = target_size or (height, width)
|
995 |
+
|
996 |
+
self.check_inputs(
|
997 |
+
prompt,
|
998 |
+
prompt_2,
|
999 |
+
height,
|
1000 |
+
width,
|
1001 |
+
callback_steps,
|
1002 |
+
negative_prompt,
|
1003 |
+
negative_prompt_2,
|
1004 |
+
prompt_embeds,
|
1005 |
+
negative_prompt_embeds,
|
1006 |
+
pooled_prompt_embeds,
|
1007 |
+
negative_pooled_prompt_embeds,
|
1008 |
+
ip_adapter_image,
|
1009 |
+
ip_adapter_image_embeds,
|
1010 |
+
callback_on_step_end_tensor_inputs,
|
1011 |
+
)
|
1012 |
+
|
1013 |
+
self._guidance_scale = guidance_scale
|
1014 |
+
self._guidance_rescale = guidance_rescale
|
1015 |
+
self._clip_skip = clip_skip
|
1016 |
+
self._cross_attention_kwargs = cross_attention_kwargs
|
1017 |
+
self._denoising_end = denoising_end
|
1018 |
+
self._interrupt = False
|
1019 |
+
|
1020 |
+
if prompt is not None and isinstance(prompt, str):
|
1021 |
+
batch_size = 1
|
1022 |
+
elif prompt is not None and isinstance(prompt, list):
|
1023 |
+
batch_size = len(prompt)
|
1024 |
+
else:
|
1025 |
+
batch_size = prompt_embeds.shape[0]
|
1026 |
+
|
1027 |
+
device = self._execution_device
|
1028 |
+
|
1029 |
+
lora_scale = (
|
1030 |
+
self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
|
1031 |
+
)
|
1032 |
+
|
1033 |
+
(
|
1034 |
+
prompt_embeds,
|
1035 |
+
negative_prompt_embeds,
|
1036 |
+
pooled_prompt_embeds,
|
1037 |
+
negative_pooled_prompt_embeds,
|
1038 |
+
) = self.encode_prompt(
|
1039 |
+
prompt=prompt,
|
1040 |
+
prompt_2=prompt_2,
|
1041 |
+
device=device,
|
1042 |
+
num_images_per_prompt=num_images_per_prompt,
|
1043 |
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
1044 |
+
negative_prompt=negative_prompt,
|
1045 |
+
negative_prompt_2=negative_prompt_2,
|
1046 |
+
prompt_embeds=prompt_embeds,
|
1047 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
1048 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
1049 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
1050 |
+
lora_scale=lora_scale,
|
1051 |
+
clip_skip=self.clip_skip,
|
1052 |
+
)
|
1053 |
+
|
1054 |
+
timesteps, num_inference_steps = retrieve_timesteps(
|
1055 |
+
self.scheduler, num_inference_steps, device, timesteps, sigmas
|
1056 |
+
)
|
1057 |
+
|
1058 |
+
# 5. Prepare latent variables
|
1059 |
+
num_channels_latents = self.unet.config.in_channels
|
1060 |
+
latents = self.prepare_latents(
|
1061 |
+
batch_size * num_images_per_prompt,
|
1062 |
+
num_channels_latents,
|
1063 |
+
height,
|
1064 |
+
width,
|
1065 |
+
prompt_embeds.dtype,
|
1066 |
+
device,
|
1067 |
+
generator,
|
1068 |
+
latents,
|
1069 |
+
)
|
1070 |
+
|
1071 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
1072 |
+
|
1073 |
+
add_text_embeds = pooled_prompt_embeds
|
1074 |
+
if self.text_encoder_2 is None:
|
1075 |
+
text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
|
1076 |
+
else:
|
1077 |
+
text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
|
1078 |
+
|
1079 |
+
add_time_ids = self._get_add_time_ids(
|
1080 |
+
original_size,
|
1081 |
+
crops_coords_top_left,
|
1082 |
+
target_size,
|
1083 |
+
dtype=prompt_embeds.dtype,
|
1084 |
+
text_encoder_projection_dim=text_encoder_projection_dim,
|
1085 |
+
)
|
1086 |
+
if negative_original_size is not None and negative_target_size is not None:
|
1087 |
+
negative_add_time_ids = self._get_add_time_ids(
|
1088 |
+
negative_original_size,
|
1089 |
+
negative_crops_coords_top_left,
|
1090 |
+
negative_target_size,
|
1091 |
+
dtype=prompt_embeds.dtype,
|
1092 |
+
text_encoder_projection_dim=text_encoder_projection_dim,
|
1093 |
+
)
|
1094 |
+
else:
|
1095 |
+
negative_add_time_ids = add_time_ids
|
1096 |
+
|
1097 |
+
if self.do_classifier_free_guidance:
|
1098 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
1099 |
+
add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
|
1100 |
+
add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
|
1101 |
+
|
1102 |
+
prompt_embeds = prompt_embeds.to(device)
|
1103 |
+
add_text_embeds = add_text_embeds.to(device)
|
1104 |
+
add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
|
1105 |
+
|
1106 |
+
if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
|
1107 |
+
image_embeds = self.prepare_ip_adapter_image_embeds(
|
1108 |
+
ip_adapter_image,
|
1109 |
+
ip_adapter_image_embeds,
|
1110 |
+
device,
|
1111 |
+
batch_size * num_images_per_prompt,
|
1112 |
+
self.do_classifier_free_guidance,
|
1113 |
+
)
|
1114 |
+
|
1115 |
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
1116 |
+
|
1117 |
+
if (
|
1118 |
+
self.denoising_end is not None
|
1119 |
+
and isinstance(self.denoising_end, float)
|
1120 |
+
and self.denoising_end > 0
|
1121 |
+
and self.denoising_end < 1
|
1122 |
+
):
|
1123 |
+
discrete_timestep_cutoff = int(
|
1124 |
+
round(
|
1125 |
+
self.scheduler.config.num_train_timesteps
|
1126 |
+
- (self.denoising_end * self.scheduler.config.num_train_timesteps)
|
1127 |
+
)
|
1128 |
+
)
|
1129 |
+
num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
|
1130 |
+
timesteps = timesteps[:num_inference_steps]
|
1131 |
+
|
1132 |
+
timestep_cond = None
|
1133 |
+
if self.unet.config.time_cond_proj_dim is not None:
|
1134 |
+
guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
|
1135 |
+
timestep_cond = self.get_guidance_scale_embedding(
|
1136 |
+
guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
|
1137 |
+
).to(device=device, dtype=latents.dtype)
|
1138 |
+
|
1139 |
+
self._num_timesteps = len(timesteps)
|
1140 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
1141 |
+
do_classifier_free_guidance = self.do_classifier_free_guidance
|
1142 |
+
for i, t in enumerate(timesteps):
|
1143 |
+
if self.interrupt:
|
1144 |
+
continue
|
1145 |
+
if end_cfg is not None and i / num_inference_steps > end_cfg and do_classifier_free_guidance:
|
1146 |
+
do_classifier_free_guidance = False
|
1147 |
+
prompt_embeds = torch.chunk(prompt_embeds, 2, dim=0)[-1]
|
1148 |
+
add_text_embeds = torch.chunk(add_text_embeds, 2, dim=0)[-1]
|
1149 |
+
add_time_ids = torch.chunk(add_time_ids, 2, dim=0)[-1]
|
1150 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
1151 |
+
|
1152 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
1153 |
+
|
1154 |
+
added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
|
1155 |
+
if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
|
1156 |
+
added_cond_kwargs["image_embeds"] = image_embeds
|
1157 |
+
noise_pred = self.unet(
|
1158 |
+
latent_model_input,
|
1159 |
+
t,
|
1160 |
+
encoder_hidden_states=prompt_embeds,
|
1161 |
+
timestep_cond=timestep_cond,
|
1162 |
+
cross_attention_kwargs=self.cross_attention_kwargs,
|
1163 |
+
added_cond_kwargs=added_cond_kwargs,
|
1164 |
+
return_dict=False,
|
1165 |
+
)[0]
|
1166 |
+
|
1167 |
+
if do_classifier_free_guidance:
|
1168 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
1169 |
+
noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
|
1170 |
+
|
1171 |
+
if do_classifier_free_guidance and self.guidance_rescale > 0.0:
|
1172 |
+
noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
|
1173 |
+
|
1174 |
+
latents_dtype = latents.dtype
|
1175 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
1176 |
+
if latents.dtype != latents_dtype:
|
1177 |
+
if torch.backends.mps.is_available():
|
1178 |
+
latents = latents.to(latents_dtype)
|
1179 |
+
|
1180 |
+
if callback_on_step_end is not None:
|
1181 |
+
callback_kwargs = {}
|
1182 |
+
for k in callback_on_step_end_tensor_inputs:
|
1183 |
+
callback_kwargs[k] = locals()[k]
|
1184 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
1185 |
+
|
1186 |
+
latents = callback_outputs.pop("latents", latents)
|
1187 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
1188 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
1189 |
+
add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
|
1190 |
+
negative_pooled_prompt_embeds = callback_outputs.pop(
|
1191 |
+
"negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
|
1192 |
+
)
|
1193 |
+
add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
|
1194 |
+
negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
|
1195 |
+
|
1196 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
1197 |
+
progress_bar.update()
|
1198 |
+
if callback is not None and i % callback_steps == 0:
|
1199 |
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
1200 |
+
callback(step_idx, t, latents)
|
1201 |
+
|
1202 |
+
if XLA_AVAILABLE:
|
1203 |
+
xm.mark_step()
|
1204 |
+
|
1205 |
+
if not output_type == "latent":
|
1206 |
+
needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
|
1207 |
+
|
1208 |
+
if needs_upcasting:
|
1209 |
+
self.upcast_vae()
|
1210 |
+
latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
|
1211 |
+
elif latents.dtype != self.vae.dtype:
|
1212 |
+
if torch.backends.mps.is_available():
|
1213 |
+
self.vae = self.vae.to(latents.dtype)
|
1214 |
+
|
1215 |
+
has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
|
1216 |
+
has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
|
1217 |
+
if has_latents_mean and has_latents_std:
|
1218 |
+
latents_mean = (
|
1219 |
+
torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
|
1220 |
+
)
|
1221 |
+
latents_std = (
|
1222 |
+
torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
|
1223 |
+
)
|
1224 |
+
latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
|
1225 |
+
else:
|
1226 |
+
latents = latents / self.vae.config.scaling_factor
|
1227 |
+
|
1228 |
+
image = self.vae.decode(latents, return_dict=False)[0]
|
1229 |
+
|
1230 |
+
if needs_upcasting:
|
1231 |
+
self.vae.to(dtype=torch.float16)
|
1232 |
+
else:
|
1233 |
+
image = latents
|
1234 |
+
|
1235 |
+
if not output_type == "latent":
|
1236 |
+
if self.watermark is not None:
|
1237 |
+
image = self.watermark.apply_watermark(image)
|
1238 |
+
|
1239 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
1240 |
+
|
1241 |
+
self.maybe_free_model_hooks()
|
1242 |
+
|
1243 |
+
if not return_dict:
|
1244 |
+
return (image,)
|
1245 |
+
|
1246 |
+
return StableDiffusionXLPipelineOutput(images=image)
|
1247 |
+
|
1248 |
+
|
1249 |
+
def load_pipeline() -> StableDiffusionXLPipeline:
|
1250 |
+
pipeline = StableDiffusionXLPipeline.from_pretrained(
|
1251 |
+
"./models/newdream-sdxl-20",
|
1252 |
+
torch_dtype=torch.float16,
|
1253 |
+
local_files_only=True,
|
1254 |
+
)
|
1255 |
+
pipeline.scheduler = UniPCMultistepScheduler.from_config(
|
1256 |
+
pipeline.scheduler.config,)
|
1257 |
+
pipeline.to("cuda")
|
1258 |
+
|
1259 |
+
config = CompilationConfig.Default()
|
1260 |
+
try:
|
1261 |
+
import xformers
|
1262 |
+
config.enable_xformers = True
|
1263 |
+
except ImportError:
|
1264 |
+
print('xformers not installed, skip')
|
1265 |
+
try:
|
1266 |
+
import triton
|
1267 |
+
config.enable_triton = True
|
1268 |
+
except ImportError:
|
1269 |
+
print('Triton not installed, skip')
|
1270 |
+
config.enable_cuda_graph = True
|
1271 |
+
|
1272 |
+
pipeline = compile(pipeline, config)
|
1273 |
+
for _ in range(4):
|
1274 |
+
pipeline(prompt="", num_inference_steps=10)
|
1275 |
+
|
1276 |
+
return pipeline
|
1277 |
+
|
1278 |
+
|
1279 |
+
def infer(request: TextToImageRequest, pipeline: StableDiffusionXLPipeline) -> Image:
|
1280 |
+
generator = Generator(pipeline.device).manual_seed(request.seed) if request.seed else None
|
1281 |
+
|
1282 |
+
return pipeline(
|
1283 |
+
prompt=request.prompt,
|
1284 |
+
negative_prompt=request.negative_prompt,
|
1285 |
+
width=request.width,
|
1286 |
+
height=request.height,
|
1287 |
+
generator=generator,
|
1288 |
+
num_inference_steps=8,
|
1289 |
+
).images[0]
|