shsolanki commited on
Commit
841615f
·
1 Parent(s): 2cc0ccf

Difix Model Release

Browse files
Files changed (8) hide show
  1. .gitattributes +1 -35
  2. Dockerfile +56 -0
  3. README.md +1 -4
  4. app.py +317 -4
  5. assets/example1.png +3 -0
  6. assets/example2.png +3 -0
  7. pipeline_difix.py +1120 -0
  8. requirements.txt +11 -0
.gitattributes CHANGED
@@ -1,35 +1 @@
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
 
1
+ */*.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dockerfile ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use the exact same base image from the log
2
+ FROM docker.io/nvidia/cuda:12.3.2-cudnn9-devel-ubuntu22.04@sha256:fb1ad20f2552f5b3aafb2c9c478ed57da95e2bb027d15218d7a55b3a0e4b4413
3
+
4
+ # Set environment variables for non-interactive installation
5
+ ENV DEBIAN_FRONTEND=noninteractive
6
+ ENV TZ=UTC
7
+
8
+ # Install system dependencies including Python and pip
9
+ RUN apt-get update && apt-get install -y \
10
+ python3 python3-pip python3-dev \
11
+ && rm -rf /var/lib/apt/lists/*
12
+
13
+ # Setup fakeroot and user
14
+ RUN apt-get update && apt-get install -y fakeroot && \
15
+ mv /usr/bin/apt-get /usr/bin/.apt-get && \
16
+ echo '#!/usr/bin/env sh\nfakeroot /usr/bin/.apt-get $@' > /usr/bin/apt-get && \
17
+ chmod +x /usr/bin/apt-get && \
18
+ rm -rf /var/lib/apt/lists/* && \
19
+ useradd -m -u 1000 user
20
+
21
+ # Set working directory
22
+ WORKDIR /home/user/app
23
+
24
+ # Copy requirements.txt and install Python dependencies
25
+ COPY requirements.txt /tmp/requirements.txt
26
+ RUN pip install --no-cache-dir -r /tmp/requirements.txt
27
+
28
+ # Install additional packages
29
+ RUN pip install --no-cache-dir spaces
30
+
31
+ # Install huggingface_hub
32
+ RUN pip install --no-cache-dir huggingface_hub
33
+
34
+ # Set HF_TOKEN from secret and make it available as environment variable
35
+ RUN --mount=type=secret,id=HF_TOKEN,mode=0444,required=true \
36
+ echo "export HF_TOKEN=$(cat /run/secrets/HF_TOKEN)" > /etc/hf_env && \
37
+ chmod +x /etc/hf_env
38
+
39
+ # Create a startup script that sources the environment and runs the app
40
+ RUN echo '#!/bin/bash\nsource /etc/hf_env\nexec "$@"' > /usr/local/bin/entrypoint.sh && \
41
+ chmod +x /usr/local/bin/entrypoint.sh
42
+
43
+ # Copy only specific project files
44
+ COPY --chown=1000:1000 app.py /home/user/app/
45
+ COPY --chown=1000:1000 pipeline_difix.py /home/user/app/
46
+ COPY --chown=1000:1000 assets/ /home/user/app/assets/
47
+
48
+ # Switch to user
49
+ USER user
50
+
51
+ # Expose port for Gradio
52
+ EXPOSE 7860
53
+
54
+ # Use the entrypoint script
55
+ ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
56
+ CMD ["python3", "app.py"]
README.md CHANGED
@@ -1,11 +1,8 @@
1
  ---
2
  title: Difix3D
3
- emoji: 📉
4
  colorFrom: green
5
  colorTo: indigo
6
- sdk: gradio
7
- sdk_version: 5.32.1
8
- app_file: app.py
9
  pinned: false
10
  short_description: Interface to interact with NVIDIA's Difix3D+ model
11
  ---
 
1
  ---
2
  title: Difix3D
 
3
  colorFrom: green
4
  colorTo: indigo
5
+ sdk: docker
 
 
6
  pinned: false
7
  short_description: Interface to interact with NVIDIA's Difix3D+ model
8
  ---
app.py CHANGED
@@ -1,7 +1,320 @@
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
 
 
 
 
 
 
 
 
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import numpy as np
3
+ from PIL import Image
4
+ import torch
5
+ import os
6
+ from pipeline_difix import DifixPipeline
7
+ from diffusers.utils import load_image
8
+ import gradio.themes as gr_themes
9
+ from pathlib import Path
10
+ import logging
11
+ import time
12
 
13
+ # Configure logging
14
+ logging.basicConfig(
15
+ level=logging.INFO,
16
+ format='%(asctime)s - %(levelname)s - %(message)s',
17
+ handlers=[
18
+ logging.StreamHandler(), # Console output
19
+ logging.FileHandler('/tmp/difix3d_app.log', mode='a') # File output
20
+ ]
21
+ )
22
+ logger = logging.getLogger(__name__)
23
 
24
+ # Configuration
25
+ MODEL_NAME = "nvidia/difix"
26
+ DEFAULT_PROMPT = "remove degradation"
27
+ DEFAULT_HEIGHT = 576
28
+ DEFAULT_WIDTH = 1024
29
+ DEFAULT_TIMESTEP = 199
30
+ DEFAULT_GUIDANCE_SCALE = 0.0
31
+ DEFAULT_NUM_INFERENCE_STEPS = 1
32
+
33
+ # Global pipeline variable
34
+ pipe = None
35
+
36
+ logger.info("=== Difix Demo Starting ===")
37
+ logger.info(f"MODEL_NAME: {MODEL_NAME}")
38
+ logger.info(f"Current working directory: {os.getcwd()}")
39
+ logger.info(f"CUDA Available: {torch.cuda.is_available()}")
40
+ if torch.cuda.is_available():
41
+ logger.info(f"CUDA Device: {torch.cuda.get_device_name()}")
42
+ logger.info(f"CUDA Memory: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB")
43
+
44
+ # Login to Hugging Face using environment variable
45
+ try:
46
+ from huggingface_hub import login
47
+ hf_token = os.getenv('HF_TOKEN')
48
+
49
+ # If not in environment, try reading from /etc/hf_env
50
+ if not hf_token and os.path.exists('/etc/hf_env'):
51
+ with open('/etc/hf_env', 'r') as f:
52
+ for line in f:
53
+ if line.strip().startswith('export HF_TOKEN='):
54
+ hf_token = line.strip().split('=', 1)[1]
55
+ break
56
+ elif line.strip().startswith('HF_TOKEN='):
57
+ hf_token = line.strip().split('=', 1)[1]
58
+ break
59
+
60
+ if hf_token:
61
+ login(hf_token)
62
+ logger.info("Successfully authenticated with Hugging Face")
63
+ else:
64
+ logger.warning("HF_TOKEN not found in environment or /etc/hf_env")
65
+ except Exception as e:
66
+ logger.error(f"Failed to authenticate with Hugging Face: {str(e)}")
67
+
68
+ def initialize_pipeline():
69
+ """Initialize the Difix pipeline and perform warmup"""
70
+ global pipe
71
+
72
+ logger.info("Starting pipeline initialization...")
73
+ start_time = time.time()
74
+
75
+ try:
76
+ logger.info(f"Loading DifixPipeline from {MODEL_NAME}...")
77
+ # Initialize pipeline using the new approach
78
+ pipe = DifixPipeline.from_pretrained(MODEL_NAME, trust_remote_code=True)
79
+ logger.info("DifixPipeline loaded successfully")
80
+
81
+ logger.info("Moving pipeline to CUDA...")
82
+ if torch.cuda.is_available():
83
+ pipe.to("cuda")
84
+ logger.info("Pipeline moved to CUDA")
85
+ else:
86
+ logger.warning("CUDA not available, using CPU")
87
+
88
+ init_time = time.time() - start_time
89
+ logger.info(f"Pipeline initialization completed in {init_time:.2f} seconds")
90
+
91
+ # Warmup with dummy data
92
+ logger.info("Starting pipeline warmup...")
93
+ warmup_start = time.time()
94
+ try:
95
+ # Create dummy image with the model's expected resolution
96
+ dummy_image = Image.new('RGB', (DEFAULT_WIDTH, DEFAULT_HEIGHT), color='red')
97
+ logger.info(f"Created dummy image: {dummy_image.size}")
98
+
99
+ _ = pipe(
100
+ DEFAULT_PROMPT,
101
+ image=dummy_image,
102
+ num_inference_steps=DEFAULT_NUM_INFERENCE_STEPS,
103
+ timesteps=[DEFAULT_TIMESTEP],
104
+ guidance_scale=DEFAULT_GUIDANCE_SCALE
105
+ ).images[0]
106
+
107
+ warmup_time = time.time() - warmup_start
108
+ logger.info(f"Pipeline warmup completed successfully in {warmup_time:.2f} seconds")
109
+ except Exception as e:
110
+ logger.warning(f"Pipeline warmup failed: {e}")
111
+
112
+ except Exception as e:
113
+ logger.error(f"Pipeline initialization failed: {e}")
114
+ raise
115
+
116
+ def process_image(image):
117
+ """
118
+ Process the input image using the Difix pipeline to remove artifacts.
119
+ """
120
+ global pipe
121
+
122
+ if image is None:
123
+ return None, "Error: No image provided"
124
+
125
+ if pipe is None:
126
+ error_msg = "Pipeline not initialized"
127
+ return None, f"Error: {error_msg}"
128
+
129
+ try:
130
+ # Convert numpy array to PIL Image if needed
131
+ if isinstance(image, np.ndarray):
132
+ image = Image.fromarray(image)
133
+
134
+ # Ensure image is in RGB mode
135
+ if image.mode != 'RGB':
136
+ image = image.convert('RGB')
137
+
138
+ # Process the image using Difix pipeline
139
+ output_image = pipe(
140
+ DEFAULT_PROMPT,
141
+ image=image,
142
+ num_inference_steps=DEFAULT_NUM_INFERENCE_STEPS,
143
+ timesteps=[DEFAULT_TIMESTEP],
144
+ guidance_scale=DEFAULT_GUIDANCE_SCALE
145
+ ).images[0]
146
+
147
+ return output_image, None
148
+
149
+ except Exception as e:
150
+ error_msg = f"Error processing image: {str(e)}"
151
+ logger.error(error_msg)
152
+ return None, error_msg
153
+
154
+ def gradio_interface(image):
155
+ """Wrapper function for Gradio interface"""
156
+ result, error = process_image(image)
157
+ if error:
158
+ gr.Warning(error)
159
+ return None
160
+ return result
161
+
162
+ # Initialize pipeline at startup
163
+ logger.info("=== Starting Pipeline Initialization ===")
164
+ try:
165
+ initialize_pipeline()
166
+ model_status = "✅ Pipeline loaded successfully"
167
+ logger.info("Pipeline initialization successful")
168
+ except Exception as e:
169
+ model_status = f"❌ Pipeline initialization failed: {e}"
170
+ logger.error(f"Pipeline initialization error: {e}")
171
+
172
+ logger.info("=== Creating UI Components ===")
173
+
174
+ # Article content for Difix
175
+ article = (
176
+ "<p style='font-size: 1.1em;'>"
177
+ "This demo showcases <strong>Difix</strong>, a single-step image diffusion model trained to enhance and remove artifacts in rendered novel views caused by underconstrained regions of 3D representation."
178
+ "</p>"
179
+ "<p><strong style='color: #76B900; font-size: 1.2em;'>Key Features:</strong></p>"
180
+ "<ul style='font-size: 1.1em;'>"
181
+ " <li>Single-step diffusion-based artifact removal for 3D novel views</li>"
182
+ " <li>Enhancement of underconstrained 3D regions (1024x576 default)</li>"
183
+ "</ul>"
184
+ "<p style='font-size: 1.1em;'>"
185
+ f"<strong>Model Status:</strong> {model_status}"
186
+ "</p>"
187
+ "<p style='font-size: 1.0em; color: #666;'>"
188
+ "Upload an image to see the restoration capabilities of Difix+. The model will automatically process your image and return an enhanced version."
189
+ "</p>"
190
+
191
+ "<p style='text-align: center;'>"
192
+ "<a href='https://github.com/nv-tlabs/Difix3D' target='_blank'>🧑‍💻 GitHub Repository</a> | "
193
+ "<a href='https://arxiv.org/abs/2503.01774' target='_blank'>📄 Research Paper</a> | "
194
+ "<a href='https://huggingface.co/nvidia/difix' target='_blank'>🤗 Hugging Face Model</a>"
195
+ "</p>"
196
+ )
197
+
198
+ logger.info("Creating theme...")
199
+ # Define a modern green-inspired theme similar to NVIDIA
200
+ difix_theme = gr_themes.Default(
201
+ primary_hue=gr_themes.Color(
202
+ c50="#E6F7E6", # Lightest green
203
+ c100="#CCF2CC",
204
+ c200="#99E699",
205
+ c300="#66D966",
206
+ c400="#33CC33",
207
+ c500="#00B300", # Primary green
208
+ c600="#009900",
209
+ c700="#007A00",
210
+ c800="#005C00",
211
+ c900="#003D00", # Darkest green
212
+ c950="#002600"
213
+ ),
214
+ secondary_hue=gr_themes.Color(
215
+ c50="#F0F8FF", # Light blue accent
216
+ c100="#E0F0FF",
217
+ c200="#C0E0FF",
218
+ c300="#A0D0FF",
219
+ c400="#80C0FF",
220
+ c500="#4A90E2", # Secondary blue
221
+ c600="#3A80D2",
222
+ c700="#2A70C2",
223
+ c800="#1A60B2",
224
+ c900="#0A50A2",
225
+ c950="#004092"
226
+ ),
227
+ neutral_hue="slate",
228
+ font=[gr_themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"],
229
+ ).set(
230
+ body_background_fill="*neutral_50",
231
+ block_background_fill="white",
232
+ block_border_width="1px",
233
+ block_border_color="*neutral_200",
234
+ block_radius="8px",
235
+ block_shadow="0 2px 4px rgba(0,0,0,0.1)",
236
+ button_primary_background_fill="*primary_500",
237
+ button_primary_background_fill_hover="*primary_600",
238
+ button_primary_text_color="white",
239
+ )
240
+
241
+ logger.info("Creating Gradio interface...")
242
+ # Create Gradio interface with Blocks for better control
243
+ with gr.Blocks(theme=difix_theme, title="Difix") as demo:
244
+ gr.Markdown("<h1 style='text-align: center; margin: 0 auto; color: #00B300;'>🎨 Difix</h1>")
245
+ gr.HTML(article)
246
+
247
+ gr.Markdown("---")
248
+
249
+ with gr.Row():
250
+ with gr.Column(scale=1):
251
+ input_image = gr.Image(
252
+ type="pil",
253
+ label="📤 Upload Image for Restoration",
254
+ height=400
255
+ )
256
+
257
+ process_btn = gr.Button(
258
+ "🚀 Fix Image",
259
+ variant="primary",
260
+ size="lg"
261
+ )
262
+
263
+ gr.Examples(
264
+ examples=["assets/example1.png","assets/example2.png"],
265
+ inputs=[input_image],
266
+ label="📋 Example Images"
267
+ )
268
+
269
+ with gr.Column(scale=1):
270
+ output_image = gr.Image(
271
+ type="pil",
272
+ label="✨ Fixed Image",
273
+ height=400
274
+ )
275
+
276
+ gr.Markdown("---")
277
+ gr.Markdown(
278
+ "<p style='text-align: center; color: #666; font-size: 0.9em;'>"
279
+ f"Model: {MODEL_NAME} | "
280
+ f"Resolution: {DEFAULT_WIDTH}×{DEFAULT_HEIGHT} | "
281
+ f"Prompt: '{DEFAULT_PROMPT}' | "
282
+ f"Steps: {DEFAULT_NUM_INFERENCE_STEPS} | "
283
+ f"Timestep: {DEFAULT_TIMESTEP} | "
284
+ f"Guidance Scale: {DEFAULT_GUIDANCE_SCALE}"
285
+ "</p>"
286
+ )
287
+
288
+ # Event handlers
289
+ process_btn.click(
290
+ fn=gradio_interface,
291
+ inputs=[input_image],
292
+ outputs=[output_image],
293
+ api_name="restore_image"
294
+ )
295
+
296
+ logger.info("Configuring queue...")
297
+ # Configure queueing for better performance
298
+ demo.queue(
299
+ default_concurrency_limit=2, # Process up to 2 requests simultaneously
300
+ max_size=20, # Maximum 20 users can wait in queue
301
+ )
302
+
303
+ logger.info("=== Gradio Interface Created Successfully ===")
304
+
305
+ if __name__ == "__main__":
306
+ logger.info("=== Starting Gradio Launch ===")
307
+ logger.info(f"Server config: 0.0.0.0:7860, max_threads=10")
308
+
309
+ # Set up file access for assets directory
310
+ assets_path = Path("assets").absolute()
311
+ if assets_path.exists():
312
+ logger.info(f"Setting up file access for assets directory: {assets_path}")
313
+
314
+ demo.launch(
315
+ server_name="0.0.0.0",
316
+ server_port=7860,
317
+ max_threads=10,
318
+ # Allow access to assets directory
319
+ allowed_paths=[str(assets_path)] if assets_path.exists() else []
320
+ )
assets/example1.png ADDED

Git LFS Details

  • SHA256: 316a3674d1f9ff4643cd9b4f9f312bb9996d8ae8bb7660dc1ddc7e8e1d44a497
  • Pointer size: 131 Bytes
  • Size of remote file: 795 kB
assets/example2.png ADDED

Git LFS Details

  • SHA256: 0820c2925931cf67f15d6ccbe4cc16a185eb7fdb9051f4372ce17f56c7a4e5d1
  • Pointer size: 131 Bytes
  • Size of remote file: 613 kB
pipeline_difix.py ADDED
@@ -0,0 +1,1120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import PIL.Image
19
+ import torch
20
+ from packaging import version
21
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
22
+
23
+ from diffusers.configuration_utils import FrozenDict
24
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
25
+ from diffusers.loaders import FromSingleFileMixin, IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
26
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
27
+ from diffusers.models.attention_processor import FusedAttnProcessor2_0
28
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
29
+ from diffusers.schedulers import KarrasDiffusionSchedulers
30
+ from diffusers.utils import (
31
+ USE_PEFT_BACKEND,
32
+ deprecate,
33
+ logging,
34
+ replace_example_docstring,
35
+ scale_lora_layers,
36
+ unscale_lora_layers,
37
+ )
38
+ from diffusers.utils.torch_utils import randn_tensor
39
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
40
+ from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
41
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
42
+
43
+
44
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
45
+
46
+ EXAMPLE_DOC_STRING = """
47
+ Examples:
48
+ ```py
49
+ >>> import torch
50
+ >>> from diffusers import StableDiffusionPipeline
51
+
52
+ >>> pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
53
+ >>> pipe = pipe.to("cuda")
54
+
55
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
56
+ >>> image = pipe(prompt).images[0]
57
+ ```
58
+ """
59
+
60
+
61
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
62
+ """
63
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
64
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
65
+ """
66
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
67
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
68
+ # rescale the results from guidance (fixes overexposure)
69
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
70
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
71
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
72
+ return noise_cfg
73
+
74
+
75
+ def retrieve_timesteps(
76
+ scheduler,
77
+ num_inference_steps: Optional[int] = None,
78
+ device: Optional[Union[str, torch.device]] = None,
79
+ timesteps: Optional[List[int]] = None,
80
+ **kwargs,
81
+ ):
82
+ """
83
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
84
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
85
+
86
+ Args:
87
+ scheduler (`SchedulerMixin`):
88
+ The scheduler to get timesteps from.
89
+ num_inference_steps (`int`):
90
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
91
+ `timesteps` must be `None`.
92
+ device (`str` or `torch.device`, *optional*):
93
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
94
+ timesteps (`List[int]`, *optional*):
95
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
96
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
97
+ must be `None`.
98
+
99
+ Returns:
100
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
101
+ second element is the number of inference steps.
102
+ """
103
+ if timesteps is not None:
104
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
105
+ if not accepts_timesteps:
106
+ raise ValueError(
107
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
108
+ f" timestep schedules. Please check whether you are using the correct scheduler."
109
+ )
110
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
111
+ timesteps = scheduler.timesteps
112
+ num_inference_steps = len(timesteps)
113
+ else:
114
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
115
+ timesteps = scheduler.timesteps
116
+ return timesteps, num_inference_steps
117
+
118
+
119
+ def retrieve_latents(
120
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
121
+ ):
122
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
123
+ return encoder_output.latent_dist.sample(generator)
124
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
125
+ return encoder_output.latent_dist.mode()
126
+ elif hasattr(encoder_output, "latents"):
127
+ return encoder_output.latents
128
+ else:
129
+ raise AttributeError("Could not access latents of provided encoder_output")
130
+
131
+
132
+ class DifixPipeline(
133
+ DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, IPAdapterMixin, FromSingleFileMixin
134
+ ):
135
+ r"""
136
+ Pipeline for text-to-image generation using Stable Diffusion.
137
+
138
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
139
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
140
+
141
+ The pipeline also inherits the following loading methods:
142
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
143
+ - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
144
+ - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
145
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
146
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
147
+
148
+ Args:
149
+ vae ([`AutoencoderKL`]):
150
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
151
+ text_encoder ([`~transformers.CLIPTextModel`]):
152
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
153
+ tokenizer ([`~transformers.CLIPTokenizer`]):
154
+ A `CLIPTokenizer` to tokenize text.
155
+ unet ([`UNet2DConditionModel`]):
156
+ A `UNet2DConditionModel` to denoise the encoded image latents.
157
+ scheduler ([`SchedulerMixin`]):
158
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
159
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
160
+ safety_checker ([`StableDiffusionSafetyChecker`]):
161
+ Classification module that estimates whether generated images could be considered offensive or harmful.
162
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
163
+ about a model's potential harms.
164
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
165
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
166
+ """
167
+
168
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
169
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
170
+ _exclude_from_cpu_offload = ["safety_checker"]
171
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
172
+
173
+ def __init__(
174
+ self,
175
+ vae: AutoencoderKL,
176
+ text_encoder: CLIPTextModel,
177
+ tokenizer: CLIPTokenizer,
178
+ unet: UNet2DConditionModel,
179
+ scheduler: KarrasDiffusionSchedulers,
180
+ safety_checker: StableDiffusionSafetyChecker,
181
+ feature_extractor: CLIPImageProcessor,
182
+ image_encoder: CLIPVisionModelWithProjection = None,
183
+ requires_safety_checker: bool = True,
184
+ ):
185
+ super().__init__()
186
+
187
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
188
+ deprecation_message = (
189
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
190
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
191
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
192
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
193
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
194
+ " file"
195
+ )
196
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
197
+ new_config = dict(scheduler.config)
198
+ new_config["steps_offset"] = 1
199
+ scheduler._internal_dict = FrozenDict(new_config)
200
+
201
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
202
+ deprecation_message = (
203
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
204
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
205
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
206
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
207
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
208
+ )
209
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
210
+ new_config = dict(scheduler.config)
211
+ new_config["clip_sample"] = False
212
+ scheduler._internal_dict = FrozenDict(new_config)
213
+
214
+ if safety_checker is None and requires_safety_checker:
215
+ logger.warning(
216
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
217
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
218
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
219
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
220
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
221
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
222
+ )
223
+
224
+ if safety_checker is not None and feature_extractor is None:
225
+ raise ValueError(
226
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
227
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
228
+ )
229
+
230
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
231
+ version.parse(unet.config._diffusers_version).base_version
232
+ ) < version.parse("0.9.0.dev0")
233
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
234
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
235
+ deprecation_message = (
236
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
237
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
238
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
239
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
240
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
241
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
242
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
243
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
244
+ " the `unet/config.json` file"
245
+ )
246
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
247
+ new_config = dict(unet.config)
248
+ new_config["sample_size"] = 64
249
+ unet._internal_dict = FrozenDict(new_config)
250
+
251
+ self.register_modules(
252
+ vae=vae,
253
+ text_encoder=text_encoder,
254
+ tokenizer=tokenizer,
255
+ unet=unet,
256
+ scheduler=scheduler,
257
+ safety_checker=safety_checker,
258
+ feature_extractor=feature_extractor,
259
+ image_encoder=image_encoder,
260
+ )
261
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
262
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
263
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
264
+
265
+ def enable_vae_slicing(self):
266
+ r"""
267
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
268
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
269
+ """
270
+ self.vae.enable_slicing()
271
+
272
+ def disable_vae_slicing(self):
273
+ r"""
274
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
275
+ computing decoding in one step.
276
+ """
277
+ self.vae.disable_slicing()
278
+
279
+ def enable_vae_tiling(self):
280
+ r"""
281
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
282
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
283
+ processing larger images.
284
+ """
285
+ self.vae.enable_tiling()
286
+
287
+ def disable_vae_tiling(self):
288
+ r"""
289
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
290
+ computing decoding in one step.
291
+ """
292
+ self.vae.disable_tiling()
293
+
294
+ def _encode_prompt(
295
+ self,
296
+ prompt,
297
+ device,
298
+ num_images_per_prompt,
299
+ do_classifier_free_guidance,
300
+ negative_prompt=None,
301
+ prompt_embeds: Optional[torch.FloatTensor] = None,
302
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
303
+ lora_scale: Optional[float] = None,
304
+ **kwargs,
305
+ ):
306
+ deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
307
+ deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
308
+
309
+ prompt_embeds_tuple = self.encode_prompt(
310
+ prompt=prompt,
311
+ device=device,
312
+ num_images_per_prompt=num_images_per_prompt,
313
+ do_classifier_free_guidance=do_classifier_free_guidance,
314
+ negative_prompt=negative_prompt,
315
+ prompt_embeds=prompt_embeds,
316
+ negative_prompt_embeds=negative_prompt_embeds,
317
+ lora_scale=lora_scale,
318
+ **kwargs,
319
+ )
320
+
321
+ # concatenate for backwards comp
322
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
323
+
324
+ return prompt_embeds
325
+
326
+ def encode_prompt(
327
+ self,
328
+ prompt,
329
+ device,
330
+ num_images_per_prompt,
331
+ do_classifier_free_guidance,
332
+ negative_prompt=None,
333
+ prompt_embeds: Optional[torch.FloatTensor] = None,
334
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
335
+ lora_scale: Optional[float] = None,
336
+ clip_skip: Optional[int] = None,
337
+ ):
338
+ r"""
339
+ Encodes the prompt into text encoder hidden states.
340
+
341
+ Args:
342
+ prompt (`str` or `List[str]`, *optional*):
343
+ prompt to be encoded
344
+ device: (`torch.device`):
345
+ torch device
346
+ num_images_per_prompt (`int`):
347
+ number of images that should be generated per prompt
348
+ do_classifier_free_guidance (`bool`):
349
+ whether to use classifier free guidance or not
350
+ negative_prompt (`str` or `List[str]`, *optional*):
351
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
352
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
353
+ less than `1`).
354
+ prompt_embeds (`torch.FloatTensor`, *optional*):
355
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
356
+ provided, text embeddings will be generated from `prompt` input argument.
357
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
358
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
359
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
360
+ argument.
361
+ lora_scale (`float`, *optional*):
362
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
363
+ clip_skip (`int`, *optional*):
364
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
365
+ the output of the pre-final layer will be used for computing the prompt embeddings.
366
+ """
367
+ # set lora scale so that monkey patched LoRA
368
+ # function of text encoder can correctly access it
369
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
370
+ self._lora_scale = lora_scale
371
+
372
+ # dynamically adjust the LoRA scale
373
+ if not USE_PEFT_BACKEND:
374
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
375
+ else:
376
+ scale_lora_layers(self.text_encoder, lora_scale)
377
+
378
+ if prompt is not None and isinstance(prompt, str):
379
+ batch_size = 1
380
+ elif prompt is not None and isinstance(prompt, list):
381
+ batch_size = len(prompt)
382
+ else:
383
+ batch_size = prompt_embeds.shape[0]
384
+
385
+ if prompt_embeds is None:
386
+ # textual inversion: procecss multi-vector tokens if necessary
387
+ if isinstance(self, TextualInversionLoaderMixin):
388
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
389
+
390
+ text_inputs = self.tokenizer(
391
+ prompt,
392
+ padding="max_length",
393
+ max_length=self.tokenizer.model_max_length,
394
+ truncation=True,
395
+ return_tensors="pt",
396
+ )
397
+ text_input_ids = text_inputs.input_ids
398
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
399
+
400
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
401
+ text_input_ids, untruncated_ids
402
+ ):
403
+ removed_text = self.tokenizer.batch_decode(
404
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
405
+ )
406
+ logger.warning(
407
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
408
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
409
+ )
410
+
411
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
412
+ attention_mask = text_inputs.attention_mask.to(device)
413
+ else:
414
+ attention_mask = None
415
+
416
+ if clip_skip is None:
417
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
418
+ prompt_embeds = prompt_embeds[0]
419
+ else:
420
+ prompt_embeds = self.text_encoder(
421
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
422
+ )
423
+ # Access the `hidden_states` first, that contains a tuple of
424
+ # all the hidden states from the encoder layers. Then index into
425
+ # the tuple to access the hidden states from the desired layer.
426
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
427
+ # We also need to apply the final LayerNorm here to not mess with the
428
+ # representations. The `last_hidden_states` that we typically use for
429
+ # obtaining the final prompt representations passes through the LayerNorm
430
+ # layer.
431
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
432
+
433
+ if self.text_encoder is not None:
434
+ prompt_embeds_dtype = self.text_encoder.dtype
435
+ elif self.unet is not None:
436
+ prompt_embeds_dtype = self.unet.dtype
437
+ else:
438
+ prompt_embeds_dtype = prompt_embeds.dtype
439
+
440
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
441
+
442
+ bs_embed, seq_len, _ = prompt_embeds.shape
443
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
444
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
445
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
446
+
447
+ # get unconditional embeddings for classifier free guidance
448
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
449
+ uncond_tokens: List[str]
450
+ if negative_prompt is None:
451
+ uncond_tokens = [""] * batch_size
452
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
453
+ raise TypeError(
454
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
455
+ f" {type(prompt)}."
456
+ )
457
+ elif isinstance(negative_prompt, str):
458
+ uncond_tokens = [negative_prompt]
459
+ elif batch_size != len(negative_prompt):
460
+ raise ValueError(
461
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
462
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
463
+ " the batch size of `prompt`."
464
+ )
465
+ else:
466
+ uncond_tokens = negative_prompt
467
+
468
+ # textual inversion: procecss multi-vector tokens if necessary
469
+ if isinstance(self, TextualInversionLoaderMixin):
470
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
471
+
472
+ max_length = prompt_embeds.shape[1]
473
+ uncond_input = self.tokenizer(
474
+ uncond_tokens,
475
+ padding="max_length",
476
+ max_length=max_length,
477
+ truncation=True,
478
+ return_tensors="pt",
479
+ )
480
+
481
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
482
+ attention_mask = uncond_input.attention_mask.to(device)
483
+ else:
484
+ attention_mask = None
485
+
486
+ negative_prompt_embeds = self.text_encoder(
487
+ uncond_input.input_ids.to(device),
488
+ attention_mask=attention_mask,
489
+ )
490
+ negative_prompt_embeds = negative_prompt_embeds[0]
491
+
492
+ if do_classifier_free_guidance:
493
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
494
+ seq_len = negative_prompt_embeds.shape[1]
495
+
496
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
497
+
498
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
499
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
500
+
501
+ if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
502
+ # Retrieve the original scale by scaling back the LoRA layers
503
+ unscale_lora_layers(self.text_encoder, lora_scale)
504
+
505
+ return prompt_embeds, negative_prompt_embeds
506
+
507
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
508
+ dtype = next(self.image_encoder.parameters()).dtype
509
+
510
+ if not isinstance(image, torch.Tensor):
511
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
512
+
513
+ image = image.to(device=device, dtype=dtype)
514
+ if output_hidden_states:
515
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
516
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
517
+ uncond_image_enc_hidden_states = self.image_encoder(
518
+ torch.zeros_like(image), output_hidden_states=True
519
+ ).hidden_states[-2]
520
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
521
+ num_images_per_prompt, dim=0
522
+ )
523
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
524
+ else:
525
+ image_embeds = self.image_encoder(image).image_embeds
526
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
527
+ uncond_image_embeds = torch.zeros_like(image_embeds)
528
+
529
+ return image_embeds, uncond_image_embeds
530
+
531
+ def run_safety_checker(self, image, device, dtype):
532
+ if self.safety_checker is None:
533
+ has_nsfw_concept = None
534
+ else:
535
+ if torch.is_tensor(image):
536
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
537
+ else:
538
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
539
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
540
+ image, has_nsfw_concept = self.safety_checker(
541
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
542
+ )
543
+ return image, has_nsfw_concept
544
+
545
+ def decode_latents(self, latents):
546
+ deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
547
+ deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
548
+
549
+ latents = 1 / self.vae.config.scaling_factor * latents
550
+ image = self.vae.decode(latents, return_dict=False)[0]
551
+ image = (image / 2 + 0.5).clamp(0, 1)
552
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
553
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
554
+ return image
555
+
556
+ def prepare_extra_step_kwargs(self, generator, eta):
557
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
558
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
559
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
560
+ # and should be between [0, 1]
561
+
562
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
563
+ extra_step_kwargs = {}
564
+ if accepts_eta:
565
+ extra_step_kwargs["eta"] = eta
566
+
567
+ # check if the scheduler accepts generator
568
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
569
+ if accepts_generator:
570
+ extra_step_kwargs["generator"] = generator
571
+ return extra_step_kwargs
572
+
573
+ def check_inputs(
574
+ self,
575
+ prompt,
576
+ height,
577
+ width,
578
+ callback_steps,
579
+ negative_prompt=None,
580
+ prompt_embeds=None,
581
+ negative_prompt_embeds=None,
582
+ callback_on_step_end_tensor_inputs=None,
583
+ ):
584
+ if height % 8 != 0 or width % 8 != 0:
585
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
586
+
587
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
588
+ raise ValueError(
589
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
590
+ f" {type(callback_steps)}."
591
+ )
592
+ if callback_on_step_end_tensor_inputs is not None and not all(
593
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
594
+ ):
595
+ raise ValueError(
596
+ 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]}"
597
+ )
598
+
599
+ if prompt is not None and prompt_embeds is not None:
600
+ raise ValueError(
601
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
602
+ " only forward one of the two."
603
+ )
604
+ elif prompt is None and prompt_embeds is None:
605
+ raise ValueError(
606
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
607
+ )
608
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
609
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
610
+
611
+ if negative_prompt is not None and negative_prompt_embeds is not None:
612
+ raise ValueError(
613
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
614
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
615
+ )
616
+
617
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
618
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
619
+ raise ValueError(
620
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
621
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
622
+ f" {negative_prompt_embeds.shape}."
623
+ )
624
+
625
+ def prepare_latents(self, image, batch_size, num_images_per_prompt, dtype, device, generator=None):
626
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
627
+ raise ValueError(
628
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
629
+ )
630
+
631
+ image = image.to(device=device, dtype=dtype)
632
+
633
+ batch_size = batch_size * num_images_per_prompt
634
+
635
+ if image.shape[1] == 4:
636
+ init_latents = image
637
+
638
+ else:
639
+ if isinstance(generator, list) and len(generator) != batch_size:
640
+ raise ValueError(
641
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
642
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
643
+ )
644
+
645
+ elif isinstance(generator, list):
646
+ init_latents = [
647
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
648
+ for i in range(batch_size)
649
+ ]
650
+ init_latents = torch.cat(init_latents, dim=0)
651
+ else:
652
+ init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
653
+
654
+ init_latents = self.vae.config.scaling_factor * init_latents
655
+
656
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
657
+ # expand init_latents for batch_size
658
+ deprecation_message = (
659
+ f"You have passed {batch_size} text prompts (`prompt`), but only {init_latents.shape[0]} initial"
660
+ " images (`image`). Initial images are now duplicating to match the number of text prompts. Note"
661
+ " that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update"
662
+ " your script to pass as many initial images as text prompts to suppress this warning."
663
+ )
664
+ deprecate("len(prompt) != len(image)", "1.0.0", deprecation_message, standard_warn=False)
665
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
666
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
667
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
668
+ raise ValueError(
669
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
670
+ )
671
+ else:
672
+ init_latents = torch.cat([init_latents], dim=0)
673
+
674
+ # shape = init_latents.shape
675
+ # noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
676
+
677
+ # get latents
678
+ # init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
679
+ latents = init_latents
680
+
681
+ return latents
682
+
683
+ def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
684
+ r"""Enables the FreeU mechanism as in https://arxiv.org/abs/2309.11497.
685
+
686
+ The suffixes after the scaling factors represent the stages where they are being applied.
687
+
688
+ Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of the values
689
+ that are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
690
+
691
+ Args:
692
+ s1 (`float`):
693
+ Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
694
+ mitigate "oversmoothing effect" in the enhanced denoising process.
695
+ s2 (`float`):
696
+ Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
697
+ mitigate "oversmoothing effect" in the enhanced denoising process.
698
+ b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
699
+ b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
700
+ """
701
+ if not hasattr(self, "unet"):
702
+ raise ValueError("The pipeline must have `unet` for using FreeU.")
703
+ self.unet.enable_freeu(s1=s1, s2=s2, b1=b1, b2=b2)
704
+
705
+ def disable_freeu(self):
706
+ """Disables the FreeU mechanism if enabled."""
707
+ self.unet.disable_freeu()
708
+
709
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.fuse_qkv_projections
710
+ def fuse_qkv_projections(self, unet: bool = True, vae: bool = True):
711
+ """
712
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query,
713
+ key, value) are fused. For cross-attention modules, key and value projection matrices are fused.
714
+
715
+ <Tip warning={true}>
716
+
717
+ This API is 🧪 experimental.
718
+
719
+ </Tip>
720
+
721
+ Args:
722
+ unet (`bool`, defaults to `True`): To apply fusion on the UNet.
723
+ vae (`bool`, defaults to `True`): To apply fusion on the VAE.
724
+ """
725
+ self.fusing_unet = False
726
+ self.fusing_vae = False
727
+
728
+ if unet:
729
+ self.fusing_unet = True
730
+ self.unet.fuse_qkv_projections()
731
+ self.unet.set_attn_processor(FusedAttnProcessor2_0())
732
+
733
+ if vae:
734
+ if not isinstance(self.vae, AutoencoderKL):
735
+ raise ValueError("`fuse_qkv_projections()` is only supported for the VAE of type `AutoencoderKL`.")
736
+
737
+ self.fusing_vae = True
738
+ self.vae.fuse_qkv_projections()
739
+ self.vae.set_attn_processor(FusedAttnProcessor2_0())
740
+
741
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.unfuse_qkv_projections
742
+ def unfuse_qkv_projections(self, unet: bool = True, vae: bool = True):
743
+ """Disable QKV projection fusion if enabled.
744
+
745
+ <Tip warning={true}>
746
+
747
+ This API is 🧪 experimental.
748
+
749
+ </Tip>
750
+
751
+ Args:
752
+ unet (`bool`, defaults to `True`): To apply fusion on the UNet.
753
+ vae (`bool`, defaults to `True`): To apply fusion on the VAE.
754
+
755
+ """
756
+ if unet:
757
+ if not self.fusing_unet:
758
+ logger.warning("The UNet was not initially fused for QKV projections. Doing nothing.")
759
+ else:
760
+ self.unet.unfuse_qkv_projections()
761
+ self.fusing_unet = False
762
+
763
+ if vae:
764
+ if not self.fusing_vae:
765
+ logger.warning("The VAE was not initially fused for QKV projections. Doing nothing.")
766
+ else:
767
+ self.vae.unfuse_qkv_projections()
768
+ self.fusing_vae = False
769
+
770
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
771
+ def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
772
+ """
773
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
774
+
775
+ Args:
776
+ timesteps (`torch.Tensor`):
777
+ generate embedding vectors at these timesteps
778
+ embedding_dim (`int`, *optional*, defaults to 512):
779
+ dimension of the embeddings to generate
780
+ dtype:
781
+ data type of the generated embeddings
782
+
783
+ Returns:
784
+ `torch.FloatTensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
785
+ """
786
+ assert len(w.shape) == 1
787
+ w = w * 1000.0
788
+
789
+ half_dim = embedding_dim // 2
790
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
791
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
792
+ emb = w.to(dtype)[:, None] * emb[None, :]
793
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
794
+ if embedding_dim % 2 == 1: # zero pad
795
+ emb = torch.nn.functional.pad(emb, (0, 1))
796
+ assert emb.shape == (w.shape[0], embedding_dim)
797
+ return emb
798
+
799
+ @property
800
+ def guidance_scale(self):
801
+ return self._guidance_scale
802
+
803
+ @property
804
+ def guidance_rescale(self):
805
+ return self._guidance_rescale
806
+
807
+ @property
808
+ def clip_skip(self):
809
+ return self._clip_skip
810
+
811
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
812
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
813
+ # corresponds to doing no classifier free guidance.
814
+ @property
815
+ def do_classifier_free_guidance(self):
816
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
817
+
818
+ @property
819
+ def cross_attention_kwargs(self):
820
+ return self._cross_attention_kwargs
821
+
822
+ @property
823
+ def num_timesteps(self):
824
+ return self._num_timesteps
825
+
826
+ @property
827
+ def interrupt(self):
828
+ return self._interrupt
829
+
830
+ @torch.no_grad()
831
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
832
+ def __call__(
833
+ self,
834
+ prompt: Union[str, List[str]] = None,
835
+ image: PipelineImageInput = None,
836
+ height: Optional[int] = None,
837
+ width: Optional[int] = None,
838
+ num_inference_steps: int = 50,
839
+ timesteps: List[int] = None,
840
+ guidance_scale: float = 7.5,
841
+ negative_prompt: Optional[Union[str, List[str]]] = None,
842
+ num_images_per_prompt: Optional[int] = 1,
843
+ eta: float = 0.0,
844
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
845
+ latents: Optional[torch.FloatTensor] = None,
846
+ prompt_embeds: Optional[torch.FloatTensor] = None,
847
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
848
+ ip_adapter_image: Optional[PipelineImageInput] = None,
849
+ output_type: Optional[str] = "pil",
850
+ return_dict: bool = True,
851
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
852
+ guidance_rescale: float = 0.0,
853
+ clip_skip: Optional[int] = None,
854
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
855
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
856
+ **kwargs,
857
+ ):
858
+ r"""
859
+ The call function to the pipeline for generation.
860
+
861
+ Args:
862
+ prompt (`str` or `List[str]`, *optional*):
863
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
864
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
865
+ The height in pixels of the generated image.
866
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
867
+ The width in pixels of the generated image.
868
+ num_inference_steps (`int`, *optional*, defaults to 50):
869
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
870
+ expense of slower inference.
871
+ timesteps (`List[int]`, *optional*):
872
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
873
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
874
+ passed will be used. Must be in descending order.
875
+ guidance_scale (`float`, *optional*, defaults to 7.5):
876
+ A higher guidance scale value encourages the model to generate images closely linked to the text
877
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
878
+ negative_prompt (`str` or `List[str]`, *optional*):
879
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
880
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
881
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
882
+ The number of images to generate per prompt.
883
+ eta (`float`, *optional*, defaults to 0.0):
884
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
885
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
886
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
887
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
888
+ generation deterministic.
889
+ latents (`torch.FloatTensor`, *optional*):
890
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
891
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
892
+ tensor is generated by sampling using the supplied random `generator`.
893
+ prompt_embeds (`torch.FloatTensor`, *optional*):
894
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
895
+ provided, text embeddings are generated from the `prompt` input argument.
896
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
897
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
898
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
899
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
900
+ output_type (`str`, *optional*, defaults to `"pil"`):
901
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
902
+ return_dict (`bool`, *optional*, defaults to `True`):
903
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
904
+ plain tuple.
905
+ cross_attention_kwargs (`dict`, *optional*):
906
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
907
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
908
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
909
+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
910
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
911
+ using zero terminal SNR.
912
+ clip_skip (`int`, *optional*):
913
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
914
+ the output of the pre-final layer will be used for computing the prompt embeddings.
915
+ callback_on_step_end (`Callable`, *optional*):
916
+ A function that calls at the end of each denoising steps during the inference. The function is called
917
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
918
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
919
+ `callback_on_step_end_tensor_inputs`.
920
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
921
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
922
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
923
+ `._callback_tensor_inputs` attribute of your pipeline class.
924
+
925
+ Examples:
926
+
927
+ Returns:
928
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
929
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
930
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
931
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
932
+ "not-safe-for-work" (nsfw) content.
933
+ """
934
+
935
+ callback = kwargs.pop("callback", None)
936
+ callback_steps = kwargs.pop("callback_steps", None)
937
+
938
+ if callback is not None:
939
+ deprecate(
940
+ "callback",
941
+ "1.0.0",
942
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
943
+ )
944
+ if callback_steps is not None:
945
+ deprecate(
946
+ "callback_steps",
947
+ "1.0.0",
948
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
949
+ )
950
+
951
+ # 0. Default height and width to unet
952
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
953
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
954
+ # to deal with lora scaling and other possible forward hooks
955
+
956
+ # 1. Check inputs. Raise error if not correct
957
+ self.check_inputs(
958
+ prompt,
959
+ height,
960
+ width,
961
+ callback_steps,
962
+ negative_prompt,
963
+ prompt_embeds,
964
+ negative_prompt_embeds,
965
+ callback_on_step_end_tensor_inputs,
966
+ )
967
+
968
+ self._guidance_scale = guidance_scale
969
+ self._guidance_rescale = guidance_rescale
970
+ self._clip_skip = clip_skip
971
+ self._cross_attention_kwargs = cross_attention_kwargs
972
+ self._interrupt = False
973
+
974
+ # 2. Define call parameters
975
+ if prompt is not None and isinstance(prompt, str):
976
+ batch_size = 1
977
+ elif prompt is not None and isinstance(prompt, list):
978
+ batch_size = len(prompt)
979
+ else:
980
+ batch_size = prompt_embeds.shape[0]
981
+
982
+ device = self._execution_device
983
+
984
+ # 3. Encode input prompt
985
+ lora_scale = (
986
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
987
+ )
988
+
989
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
990
+ prompt,
991
+ device,
992
+ num_images_per_prompt,
993
+ self.do_classifier_free_guidance,
994
+ negative_prompt,
995
+ prompt_embeds=prompt_embeds,
996
+ negative_prompt_embeds=negative_prompt_embeds,
997
+ lora_scale=lora_scale,
998
+ clip_skip=self.clip_skip,
999
+ )
1000
+
1001
+ # For classifier free guidance, we need to do two forward passes.
1002
+ # Here we concatenate the unconditional and text embeddings into a single batch
1003
+ # to avoid doing two forward passes
1004
+ if self.do_classifier_free_guidance:
1005
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
1006
+
1007
+ if ip_adapter_image is not None:
1008
+ output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
1009
+ image_embeds, negative_image_embeds = self.encode_image(
1010
+ ip_adapter_image, device, num_images_per_prompt, output_hidden_state
1011
+ )
1012
+ if self.do_classifier_free_guidance:
1013
+ image_embeds = torch.cat([negative_image_embeds, image_embeds])
1014
+
1015
+ image = self.image_processor.preprocess(image)
1016
+
1017
+ # 4. Prepare timesteps
1018
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
1019
+
1020
+ # 5. Prepare latent variables
1021
+ latents = self.prepare_latents(
1022
+ image,
1023
+ batch_size,
1024
+ num_images_per_prompt,
1025
+ prompt_embeds.dtype,
1026
+ device,
1027
+ generator,
1028
+ )
1029
+
1030
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1031
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1032
+
1033
+ # 6.1 Add image embeds for IP-Adapter
1034
+ added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
1035
+
1036
+ # 6.2 Optionally get Guidance Scale Embedding
1037
+ timestep_cond = None
1038
+ if self.unet.config.time_cond_proj_dim is not None:
1039
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1040
+ timestep_cond = self.get_guidance_scale_embedding(
1041
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1042
+ ).to(device=device, dtype=latents.dtype)
1043
+
1044
+ # 7. Denoising loop
1045
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1046
+ self._num_timesteps = len(timesteps)
1047
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1048
+ for i, t in enumerate(timesteps):
1049
+ if self.interrupt:
1050
+ continue
1051
+
1052
+ # expand the latents if we are doing classifier free guidance
1053
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1054
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1055
+
1056
+ # predict the noise residual
1057
+ noise_pred = self.unet(
1058
+ latent_model_input,
1059
+ t,
1060
+ encoder_hidden_states=prompt_embeds,
1061
+ timestep_cond=timestep_cond,
1062
+ cross_attention_kwargs=self.cross_attention_kwargs,
1063
+ added_cond_kwargs=added_cond_kwargs,
1064
+ return_dict=False,
1065
+ )[0]
1066
+
1067
+ # perform guidance
1068
+ if self.do_classifier_free_guidance:
1069
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1070
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1071
+
1072
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1073
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1074
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1075
+
1076
+ # compute the previous noisy sample x_t -> x_t-1
1077
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1078
+
1079
+ self.vae.decoder.incoming_skip_acts = self.vae.encoder.current_down_blocks
1080
+
1081
+ if callback_on_step_end is not None:
1082
+ callback_kwargs = {}
1083
+ for k in callback_on_step_end_tensor_inputs:
1084
+ callback_kwargs[k] = locals()[k]
1085
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1086
+
1087
+ latents = callback_outputs.pop("latents", latents)
1088
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1089
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1090
+
1091
+ # call the callback, if provided
1092
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1093
+ progress_bar.update()
1094
+ if callback is not None and i % callback_steps == 0:
1095
+ step_idx = i // getattr(self.scheduler, "order", 1)
1096
+ callback(step_idx, t, latents)
1097
+
1098
+ if not output_type == "latent":
1099
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
1100
+ 0
1101
+ ]
1102
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1103
+ else:
1104
+ image = latents
1105
+ has_nsfw_concept = None
1106
+
1107
+ if has_nsfw_concept is None:
1108
+ do_denormalize = [True] * image.shape[0]
1109
+ else:
1110
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1111
+
1112
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1113
+
1114
+ # Offload all models
1115
+ self.maybe_free_model_hooks()
1116
+
1117
+ if not return_dict:
1118
+ return (image, has_nsfw_concept)
1119
+
1120
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ einops
4
+ lpips
5
+ peft==0.9.0
6
+ diffusers==0.25.1
7
+ huggingface-hub==0.25.1
8
+ transformers==4.38.0
9
+
10
+ pydantic==2.10.6
11
+ gradio==5.14.0