amonig commited on
Commit
cea9607
·
verified ·
1 Parent(s): e3b46e3

Initial commit with folder contents

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