Spaces:
Running
on
Zero
Running
on
Zero
Upload 50 files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +8 -0
- app.py +317 -0
- assets/dog.webp +0 -0
- assets/vulcano.jpg +0 -0
- assets/vulcano_mask.webp +0 -0
- pipeline_rf.py +732 -0
- requirements.txt +9 -0
- saved_results/20241129_210517/input.png +0 -0
- saved_results/20241129_210517/mask.png +0 -0
- saved_results/20241129_210517/output.png +0 -0
- saved_results/20241129_210517/parameters.json +10 -0
- saved_results/20241129_211124/input.png +0 -0
- saved_results/20241129_211124/mask.png +0 -0
- saved_results/20241129_211124/output.png +0 -0
- saved_results/20241129_211124/parameters.json +10 -0
- saved_results/20241129_211142/input.png +0 -0
- saved_results/20241129_211142/mask.png +0 -0
- saved_results/20241129_211142/output.png +0 -0
- saved_results/20241129_211142/parameters.json +10 -0
- saved_results/20241129_211621/input.png +3 -0
- saved_results/20241129_211621/mask.png +0 -0
- saved_results/20241129_211621/output.png +0 -0
- saved_results/20241129_211621/parameters.json +10 -0
- saved_results/20241129_211904/input.png +3 -0
- saved_results/20241129_211904/mask.png +0 -0
- saved_results/20241129_211904/output.png +0 -0
- saved_results/20241129_211904/parameters.json +10 -0
- saved_results/20241129_212001/input.png +3 -0
- saved_results/20241129_212001/mask.png +0 -0
- saved_results/20241129_212001/output.png +0 -0
- saved_results/20241129_212001/parameters.json +10 -0
- saved_results/20241129_212022/input.png +3 -0
- saved_results/20241129_212022/mask.png +0 -0
- saved_results/20241129_212022/output.png +0 -0
- saved_results/20241129_212022/parameters.json +10 -0
- saved_results/20241129_212052/input.png +3 -0
- saved_results/20241129_212052/mask.png +0 -0
- saved_results/20241129_212052/output.png +0 -0
- saved_results/20241129_212052/parameters.json +10 -0
- saved_results/20241129_212110/input.png +3 -0
- saved_results/20241129_212110/mask.png +0 -0
- saved_results/20241129_212110/output.png +0 -0
- saved_results/20241129_212110/parameters.json +10 -0
- saved_results/20241129_212155/input.png +3 -0
- saved_results/20241129_212155/mask.png +0 -0
- saved_results/20241129_212155/output.png +0 -0
- saved_results/20241129_212155/parameters.json +10 -0
- saved_results/20241129_212220/input.png +3 -0
- saved_results/20241129_212220/mask.png +0 -0
- saved_results/20241129_212220/output.png +0 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,11 @@ saved_model/**/* 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 36 |
+
saved_results/20241129_211621/input.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
saved_results/20241129_211904/input.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
saved_results/20241129_212001/input.png filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
saved_results/20241129_212022/input.png filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
saved_results/20241129_212052/input.png filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
saved_results/20241129_212110/input.png filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
saved_results/20241129_212155/input.png filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
saved_results/20241129_212220/input.png filter=lfs diff=lfs merge=lfs -text
|
app.py
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import spaces
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import torch
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import random
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
import os
|
| 9 |
+
import json
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
|
| 12 |
+
from pipeline_rf import RectifiedFlowPipeline
|
| 13 |
+
|
| 14 |
+
# Load the Stable Diffusion Inpainting model
|
| 15 |
+
pipe = RectifiedFlowPipeline.from_pretrained("XCLIU/2_rectified_flow_from_sd_1_5", torch_dtype=torch.float32)
|
| 16 |
+
pipe.to("cuda") # Comment this line if GPU is not available
|
| 17 |
+
|
| 18 |
+
# Function to process the image
|
| 19 |
+
@spaces.GPU(duration=20)
|
| 20 |
+
def process_image(
|
| 21 |
+
image_layers, prompt, seed, randomize_seed, num_inference_steps,
|
| 22 |
+
max_steps, learning_rate, optimization_steps, inverseproblem, mask_input
|
| 23 |
+
):
|
| 24 |
+
image_with_mask = {
|
| 25 |
+
"image": image_layers["background"],
|
| 26 |
+
"mask": image_layers["layers"][0] if mask_input is None else mask_input
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
# Set seed
|
| 30 |
+
if randomize_seed or seed is None:
|
| 31 |
+
seed = random.randint(0, 2**32 - 1)
|
| 32 |
+
generator = torch.Generator("cuda").manual_seed(int(seed))
|
| 33 |
+
|
| 34 |
+
# Unpack image and mask
|
| 35 |
+
if image_with_mask is None:
|
| 36 |
+
return None, f"❌ Please upload an image and create a mask."
|
| 37 |
+
image = image_with_mask["image"]
|
| 38 |
+
mask = image_with_mask["mask"]
|
| 39 |
+
|
| 40 |
+
if image is None or mask is None:
|
| 41 |
+
return None, f"❌ Please ensure both image and mask are provided."
|
| 42 |
+
|
| 43 |
+
# Convert images to RGB
|
| 44 |
+
image = image.convert("RGB")
|
| 45 |
+
mask = mask.split()[-1] # Convert mask to grayscale
|
| 46 |
+
|
| 47 |
+
if not prompt:
|
| 48 |
+
return None, f"❌ Please provide a prompt for inpainting."
|
| 49 |
+
with torch.autocast("cuda"):
|
| 50 |
+
# Placeholder for using advanced parameters in the future
|
| 51 |
+
# Adjust parameters according to advanced settings if applicable
|
| 52 |
+
result = pipe(
|
| 53 |
+
prompt=prompt,
|
| 54 |
+
negative_prompt="",
|
| 55 |
+
input_image=image.resize((512, 512)),
|
| 56 |
+
mask_image=mask.resize((512, 512)),
|
| 57 |
+
num_inference_steps=num_inference_steps,
|
| 58 |
+
guidance_scale=0.0,
|
| 59 |
+
generator=generator,
|
| 60 |
+
save_masked_image=True,
|
| 61 |
+
output_path="test.png",
|
| 62 |
+
learning_rate=learning_rate,
|
| 63 |
+
max_steps=max_steps,
|
| 64 |
+
optimization_steps=optimization_steps,
|
| 65 |
+
inverseproblem=inverseproblem
|
| 66 |
+
).images[0]
|
| 67 |
+
return result, f"✅ Inpainting completed with seed {seed}."
|
| 68 |
+
|
| 69 |
+
# Design the Gradio interface
|
| 70 |
+
with gr.Blocks() as demo:
|
| 71 |
+
gr.Markdown(
|
| 72 |
+
"""
|
| 73 |
+
<style>
|
| 74 |
+
body {background-color: #f5f5f5; color: #333333;}
|
| 75 |
+
h1 {text-align: center; font-family: 'Helvetica', sans-serif; margin-bottom: 10px;}
|
| 76 |
+
h2 {text-align: center; color: #666666; font-weight: normal; margin-bottom: 30px;}
|
| 77 |
+
.gradio-container {max-width: 800px; margin: auto;}
|
| 78 |
+
.footer {text-align: center; margin-top: 20px; color: #999999; font-size: 12px;}
|
| 79 |
+
</style>
|
| 80 |
+
"""
|
| 81 |
+
)
|
| 82 |
+
gr.Markdown("<h1>🍲 FlowChef 🍲</h1>")
|
| 83 |
+
gr.Markdown("<h2>Inversion/Gradient/Training-free Steering of <u>InstaFlow (SDv1.5) for Inpainting (Inverse Problem)</u></h2>")
|
| 84 |
+
gr.Markdown("<h3><p><a href='https://flowchef.github.io/'>Project Page</a> | <a href='#'>Paper</a></p> (Steering Rectified Flow Models in the Vector Field for Controlled Image Generation)</h3>")
|
| 85 |
+
gr.Markdown("<h3>💡 We recommend going through our <a href='#'>tutorial introduction</a> before getting started!</h3>")
|
| 86 |
+
gr.Markdown("<h3>⚡ For better performance, check out our demo on <a href='https://huggingface.co/spaces/FlowChef/FlowChef-Flux1-dev'>Flux</a>!</h3>")
|
| 87 |
+
|
| 88 |
+
# Store current state
|
| 89 |
+
current_input_image = None
|
| 90 |
+
current_mask = None
|
| 91 |
+
current_output_image = None
|
| 92 |
+
current_params = {}
|
| 93 |
+
|
| 94 |
+
# Images at the top
|
| 95 |
+
with gr.Row():
|
| 96 |
+
with gr.Column():
|
| 97 |
+
image_input = gr.ImageMask(
|
| 98 |
+
# source="upload",
|
| 99 |
+
# tool="sketch",
|
| 100 |
+
type="pil",
|
| 101 |
+
label="Input Image and Mask",
|
| 102 |
+
image_mode="RGBA",
|
| 103 |
+
height=512,
|
| 104 |
+
width=512,
|
| 105 |
+
)
|
| 106 |
+
with gr.Column():
|
| 107 |
+
output_image = gr.Image(label="Output Image")
|
| 108 |
+
|
| 109 |
+
# All options below
|
| 110 |
+
with gr.Column():
|
| 111 |
+
prompt = gr.Textbox(
|
| 112 |
+
label="Prompt",
|
| 113 |
+
placeholder="Describe what should appear in the masked area..."
|
| 114 |
+
)
|
| 115 |
+
with gr.Row():
|
| 116 |
+
seed = gr.Number(label="Seed (Optional)", value=None)
|
| 117 |
+
randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
|
| 118 |
+
num_inference_steps = gr.Slider(
|
| 119 |
+
label="Inference Steps", minimum=50, maximum=200, value=100
|
| 120 |
+
)
|
| 121 |
+
# Advanced settings in an accordion
|
| 122 |
+
with gr.Accordion("Advanced Settings", open=False):
|
| 123 |
+
max_steps = gr.Slider(label="Max Steps", minimum=50, maximum=200, value=200)
|
| 124 |
+
learning_rate = gr.Slider(label="Learning Rate", minimum=0.01, maximum=0.5, value=0.02)
|
| 125 |
+
optimization_steps = gr.Slider(label="Optimization Steps", minimum=1, maximum=10, value=1)
|
| 126 |
+
inverseproblem = gr.Checkbox(label="Apply mask on pixel space", value=False, info="Enables inverse problem formulation for inpainting by masking the RGB image itself. Hence, to avoid artifacts we increase the mask size manually during inference.")
|
| 127 |
+
mask_input = gr.Image(
|
| 128 |
+
type="pil",
|
| 129 |
+
label="Optional Mask",
|
| 130 |
+
image_mode="RGBA",
|
| 131 |
+
)
|
| 132 |
+
with gr.Row():
|
| 133 |
+
run_button = gr.Button("Run", variant="primary")
|
| 134 |
+
# save_button = gr.Button("Save Data", variant="secondary")
|
| 135 |
+
|
| 136 |
+
# def update_visibility(selected_mode):
|
| 137 |
+
# if selected_mode == "Inpainting":
|
| 138 |
+
# return gr.update(visible=True), gr.update(visible=False)
|
| 139 |
+
# else:
|
| 140 |
+
# return gr.update(visible=True), gr.update(visible=True)
|
| 141 |
+
|
| 142 |
+
# mode.change(
|
| 143 |
+
# update_visibility,
|
| 144 |
+
# inputs=mode,
|
| 145 |
+
# outputs=[prompt, edit_prompt],
|
| 146 |
+
# )
|
| 147 |
+
|
| 148 |
+
def run_and_update_status(
|
| 149 |
+
image_with_mask, prompt, seed, randomize_seed, num_inference_steps,
|
| 150 |
+
max_steps, learning_rate, optimization_steps, inverseproblem, mask_input
|
| 151 |
+
):
|
| 152 |
+
result_image, result_status = process_image(
|
| 153 |
+
image_with_mask, prompt, seed, randomize_seed, num_inference_steps,
|
| 154 |
+
max_steps, learning_rate, optimization_steps, inverseproblem, mask_input
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
# Store current state
|
| 158 |
+
global current_input_image, current_mask, current_output_image, current_params
|
| 159 |
+
|
| 160 |
+
current_input_image = image_with_mask["background"] if image_with_mask else None
|
| 161 |
+
current_mask = mask_input if mask_input is not None else (image_with_mask["layers"][0] if image_with_mask else None)
|
| 162 |
+
current_output_image = result_image
|
| 163 |
+
current_params = {
|
| 164 |
+
"prompt": prompt,
|
| 165 |
+
"seed": seed,
|
| 166 |
+
"randomize_seed": randomize_seed,
|
| 167 |
+
"num_inference_steps": num_inference_steps,
|
| 168 |
+
"max_steps": max_steps,
|
| 169 |
+
"learning_rate": learning_rate,
|
| 170 |
+
"optimization_steps": optimization_steps,
|
| 171 |
+
"inverseproblem": inverseproblem,
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
return result_image
|
| 175 |
+
|
| 176 |
+
def save_data():
|
| 177 |
+
if not os.path.exists("saved_results"):
|
| 178 |
+
os.makedirs("saved_results")
|
| 179 |
+
|
| 180 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 181 |
+
save_dir = os.path.join("saved_results", timestamp)
|
| 182 |
+
os.makedirs(save_dir)
|
| 183 |
+
|
| 184 |
+
# Save images
|
| 185 |
+
if current_input_image:
|
| 186 |
+
current_input_image.save(os.path.join(save_dir, "input.png"))
|
| 187 |
+
if current_mask:
|
| 188 |
+
current_mask.save(os.path.join(save_dir, "mask.png"))
|
| 189 |
+
if current_output_image:
|
| 190 |
+
current_output_image.save(os.path.join(save_dir, "output.png"))
|
| 191 |
+
|
| 192 |
+
# Save parameters
|
| 193 |
+
with open(os.path.join(save_dir, "parameters.json"), "w") as f:
|
| 194 |
+
json.dump(current_params, f, indent=4)
|
| 195 |
+
|
| 196 |
+
return f"✅ Data saved in {save_dir}"
|
| 197 |
+
|
| 198 |
+
run_button.click(
|
| 199 |
+
fn=run_and_update_status,
|
| 200 |
+
inputs=[
|
| 201 |
+
image_input,
|
| 202 |
+
prompt,
|
| 203 |
+
seed,
|
| 204 |
+
randomize_seed,
|
| 205 |
+
num_inference_steps,
|
| 206 |
+
max_steps,
|
| 207 |
+
learning_rate,
|
| 208 |
+
optimization_steps,
|
| 209 |
+
inverseproblem,
|
| 210 |
+
mask_input
|
| 211 |
+
],
|
| 212 |
+
outputs=output_image,
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
# save_button.click(fn=save_data)
|
| 216 |
+
|
| 217 |
+
gr.Markdown(
|
| 218 |
+
"<div class='footer'>Developed with ❤️ using InstaFlow (Stable Diffusion v1.5) and Gradio by <a href='https://maitreyapatel.com'>Maitreya Patel</a></div>"
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
def load_example_image_with_mask(image_path):
|
| 222 |
+
# Load the image
|
| 223 |
+
image = Image.open(image_path)
|
| 224 |
+
# Create an empty mask of the same size
|
| 225 |
+
mask = Image.new('L', image.size, 0)
|
| 226 |
+
return {"background": image, "layers": [mask], "composite": image}
|
| 227 |
+
|
| 228 |
+
examples_dir = "assets"
|
| 229 |
+
volcano_dict = load_example_image_with_mask(os.path.join(examples_dir, "vulcano.jpg"))
|
| 230 |
+
dog_dict = load_example_image_with_mask(os.path.join(examples_dir, "dog.webp"))
|
| 231 |
+
|
| 232 |
+
gr.Examples(
|
| 233 |
+
examples=[
|
| 234 |
+
[
|
| 235 |
+
"./saved_results/20241129_210517/input.png", # image with mask
|
| 236 |
+
"./saved_results/20241129_210517/mask.png",
|
| 237 |
+
"./saved_results/20241129_210517/output.png",
|
| 238 |
+
"a cat", # prompt
|
| 239 |
+
0, # seed
|
| 240 |
+
True, # randomize_seed
|
| 241 |
+
200, # num_inference_steps
|
| 242 |
+
200, # max_steps
|
| 243 |
+
0.1, # learning_rate
|
| 244 |
+
1, # optimization_steps
|
| 245 |
+
False,
|
| 246 |
+
],
|
| 247 |
+
[
|
| 248 |
+
"./saved_results/20241129_211124/input.png", # image with mask
|
| 249 |
+
"./saved_results/20241129_211124/mask.png",
|
| 250 |
+
"./saved_results/20241129_211124/output.png",
|
| 251 |
+
" ", # prompt
|
| 252 |
+
0, # seed
|
| 253 |
+
True, # randomize_seed
|
| 254 |
+
200, # num_inference_steps
|
| 255 |
+
200, # max_steps
|
| 256 |
+
0.1, # learning_rate
|
| 257 |
+
5, # optimization_steps
|
| 258 |
+
False,
|
| 259 |
+
],
|
| 260 |
+
[
|
| 261 |
+
"./saved_results/20241129_212001/input.png", # image with mask
|
| 262 |
+
"./saved_results/20241129_212001/mask.png",
|
| 263 |
+
"./saved_results/20241129_212001/output.png",
|
| 264 |
+
" ", # prompt
|
| 265 |
+
52, # seed
|
| 266 |
+
False, # randomize_seed
|
| 267 |
+
200, # num_inference_steps
|
| 268 |
+
200, # max_steps
|
| 269 |
+
0.02, # learning_rate
|
| 270 |
+
10, # optimization_steps
|
| 271 |
+
True,
|
| 272 |
+
],
|
| 273 |
+
[
|
| 274 |
+
"./saved_results/20241129_212052/input.png", # image with mask
|
| 275 |
+
"./saved_results/20241129_212052/mask.png",
|
| 276 |
+
"./saved_results/20241129_212052/output.png",
|
| 277 |
+
" ", # prompt
|
| 278 |
+
52, # seed
|
| 279 |
+
False, # randomize_seed
|
| 280 |
+
200, # num_inference_steps
|
| 281 |
+
200, # max_steps
|
| 282 |
+
0.02, # learning_rate
|
| 283 |
+
10, # optimization_steps
|
| 284 |
+
True,
|
| 285 |
+
],
|
| 286 |
+
[
|
| 287 |
+
"./saved_results/20241129_212155/input.png", # image with mask
|
| 288 |
+
"./saved_results/20241129_212155/mask.png",
|
| 289 |
+
"./saved_results/20241129_212155/output.png",
|
| 290 |
+
" ", # prompt
|
| 291 |
+
52, # seed
|
| 292 |
+
False, # randomize_seed
|
| 293 |
+
200, # num_inference_steps
|
| 294 |
+
200, # max_steps
|
| 295 |
+
0.02, # learning_rate
|
| 296 |
+
10, # optimization_steps
|
| 297 |
+
True,
|
| 298 |
+
],
|
| 299 |
+
],
|
| 300 |
+
inputs=[
|
| 301 |
+
image_input,
|
| 302 |
+
mask_input,
|
| 303 |
+
output_image,
|
| 304 |
+
prompt,
|
| 305 |
+
seed,
|
| 306 |
+
randomize_seed,
|
| 307 |
+
num_inference_steps,
|
| 308 |
+
max_steps,
|
| 309 |
+
learning_rate,
|
| 310 |
+
optimization_steps,
|
| 311 |
+
inverseproblem
|
| 312 |
+
],
|
| 313 |
+
# outputs=[output_image],
|
| 314 |
+
# fn=run_and_update_status,
|
| 315 |
+
# cache_examples=True,
|
| 316 |
+
)
|
| 317 |
+
demo.launch()
|
assets/dog.webp
ADDED
|
assets/vulcano.jpg
ADDED
|
assets/vulcano_mask.webp
ADDED
|
pipeline_rf.py
ADDED
|
@@ -0,0 +1,732 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 torch
|
| 19 |
+
from packaging import version
|
| 20 |
+
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
|
| 21 |
+
|
| 22 |
+
from diffusers.configuration_utils import FrozenDict
|
| 23 |
+
from diffusers.image_processor import VaeImageProcessor
|
| 24 |
+
from diffusers.loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin
|
| 25 |
+
from diffusers.models import AutoencoderKL, UNet2DConditionModel
|
| 26 |
+
from diffusers.models.lora import adjust_lora_scale_text_encoder
|
| 27 |
+
from diffusers.schedulers import KarrasDiffusionSchedulers
|
| 28 |
+
from diffusers.utils import (
|
| 29 |
+
deprecate,
|
| 30 |
+
logging,
|
| 31 |
+
replace_example_docstring,
|
| 32 |
+
)
|
| 33 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 34 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
| 35 |
+
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
|
| 36 |
+
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
|
| 37 |
+
|
| 38 |
+
import os
|
| 39 |
+
import torch
|
| 40 |
+
|
| 41 |
+
from torchvision import transforms as TF
|
| 42 |
+
|
| 43 |
+
import sys
|
| 44 |
+
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
|
| 45 |
+
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
|
| 46 |
+
|
| 47 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 48 |
+
|
| 49 |
+
def retrieve_latents(
|
| 50 |
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
| 51 |
+
):
|
| 52 |
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
| 53 |
+
return encoder_output.latent_dist.sample(generator)
|
| 54 |
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
| 55 |
+
return encoder_output.latent_dist.mode()
|
| 56 |
+
elif hasattr(encoder_output, "latents"):
|
| 57 |
+
return encoder_output.latents
|
| 58 |
+
else:
|
| 59 |
+
raise AttributeError("Could not access latents of provided encoder_output")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
|
| 63 |
+
"""
|
| 64 |
+
Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
|
| 65 |
+
Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
|
| 66 |
+
"""
|
| 67 |
+
std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
|
| 68 |
+
std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
|
| 69 |
+
# rescale the results from guidance (fixes overexposure)
|
| 70 |
+
noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
|
| 71 |
+
# mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
|
| 72 |
+
noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
|
| 73 |
+
return noise_cfg
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class RectifiedFlowPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin):
|
| 77 |
+
r"""
|
| 78 |
+
Pipeline for text-to-image generation using Rectified Flow and Euler discretization.
|
| 79 |
+
This customized pipeline is based on StableDiffusionPipeline from the official Diffusers library (0.21.4)
|
| 80 |
+
|
| 81 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 82 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 83 |
+
|
| 84 |
+
The pipeline also inherits the following loading methods:
|
| 85 |
+
- [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
|
| 86 |
+
- [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
| 87 |
+
- [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
| 88 |
+
- [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
|
| 89 |
+
|
| 90 |
+
Args:
|
| 91 |
+
vae ([`AutoencoderKL`]):
|
| 92 |
+
Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
|
| 93 |
+
text_encoder ([`~transformers.CLIPTextModel`]):
|
| 94 |
+
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
| 95 |
+
tokenizer ([`~transformers.CLIPTokenizer`]):
|
| 96 |
+
A `CLIPTokenizer` to tokenize text.
|
| 97 |
+
unet ([`UNet2DConditionModel`]):
|
| 98 |
+
A `UNet2DConditionModel` to denoise the encoded image latents.
|
| 99 |
+
scheduler ([`SchedulerMixin`]):
|
| 100 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
| 101 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
| 102 |
+
safety_checker ([`StableDiffusionSafetyChecker`]):
|
| 103 |
+
Classification module that estimates whether generated images could be considered offensive or harmful.
|
| 104 |
+
Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
|
| 105 |
+
about a model's potential harms.
|
| 106 |
+
feature_extractor ([`~transformers.CLIPImageProcessor`]):
|
| 107 |
+
A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
|
| 108 |
+
"""
|
| 109 |
+
model_cpu_offload_seq = "text_encoder->unet->vae"
|
| 110 |
+
_optional_components = ["safety_checker", "feature_extractor"]
|
| 111 |
+
_exclude_from_cpu_offload = ["safety_checker"]
|
| 112 |
+
|
| 113 |
+
def __init__(
|
| 114 |
+
self,
|
| 115 |
+
vae: AutoencoderKL,
|
| 116 |
+
text_encoder: CLIPTextModel,
|
| 117 |
+
tokenizer: CLIPTokenizer,
|
| 118 |
+
unet: UNet2DConditionModel,
|
| 119 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 120 |
+
safety_checker: StableDiffusionSafetyChecker,
|
| 121 |
+
feature_extractor: CLIPImageProcessor,
|
| 122 |
+
requires_safety_checker: bool = True,
|
| 123 |
+
):
|
| 124 |
+
super().__init__()
|
| 125 |
+
|
| 126 |
+
if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
|
| 127 |
+
deprecation_message = (
|
| 128 |
+
f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
|
| 129 |
+
f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
|
| 130 |
+
"to update the config accordingly as leaving `steps_offset` might led to incorrect results"
|
| 131 |
+
" in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
|
| 132 |
+
" it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
|
| 133 |
+
" file"
|
| 134 |
+
)
|
| 135 |
+
deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
|
| 136 |
+
new_config = dict(scheduler.config)
|
| 137 |
+
new_config["steps_offset"] = 1
|
| 138 |
+
scheduler._internal_dict = FrozenDict(new_config)
|
| 139 |
+
|
| 140 |
+
if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
|
| 141 |
+
deprecation_message = (
|
| 142 |
+
f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
|
| 143 |
+
" `clip_sample` should be set to False in the configuration file. Please make sure to update the"
|
| 144 |
+
" config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
|
| 145 |
+
" future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
|
| 146 |
+
" nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
|
| 147 |
+
)
|
| 148 |
+
deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
|
| 149 |
+
new_config = dict(scheduler.config)
|
| 150 |
+
new_config["clip_sample"] = False
|
| 151 |
+
scheduler._internal_dict = FrozenDict(new_config)
|
| 152 |
+
|
| 153 |
+
if safety_checker is None and requires_safety_checker:
|
| 154 |
+
logger.warning(
|
| 155 |
+
f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
|
| 156 |
+
" that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
|
| 157 |
+
" results in services or applications open to the public. Both the diffusers team and Hugging Face"
|
| 158 |
+
" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
|
| 159 |
+
" it only for use-cases that involve analyzing network behavior or auditing its results. For more"
|
| 160 |
+
" information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
if safety_checker is not None and feature_extractor is None:
|
| 164 |
+
raise ValueError(
|
| 165 |
+
"Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
|
| 166 |
+
" checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
|
| 170 |
+
version.parse(unet.config._diffusers_version).base_version
|
| 171 |
+
) < version.parse("0.9.0.dev0")
|
| 172 |
+
is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
|
| 173 |
+
if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
|
| 174 |
+
deprecation_message = (
|
| 175 |
+
"The configuration file of the unet has set the default `sample_size` to smaller than"
|
| 176 |
+
" 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
|
| 177 |
+
" following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
|
| 178 |
+
" CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
|
| 179 |
+
" \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
|
| 180 |
+
" configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
|
| 181 |
+
" in the config might lead to incorrect results in future versions. If you have downloaded this"
|
| 182 |
+
" checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
|
| 183 |
+
" the `unet/config.json` file"
|
| 184 |
+
)
|
| 185 |
+
deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
|
| 186 |
+
new_config = dict(unet.config)
|
| 187 |
+
new_config["sample_size"] = 64
|
| 188 |
+
unet._internal_dict = FrozenDict(new_config)
|
| 189 |
+
|
| 190 |
+
self.register_modules(
|
| 191 |
+
vae=vae,
|
| 192 |
+
text_encoder=text_encoder,
|
| 193 |
+
tokenizer=tokenizer,
|
| 194 |
+
unet=unet,
|
| 195 |
+
scheduler=scheduler,
|
| 196 |
+
safety_checker=safety_checker,
|
| 197 |
+
feature_extractor=feature_extractor,
|
| 198 |
+
)
|
| 199 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 200 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
| 201 |
+
self.register_to_config(requires_safety_checker=requires_safety_checker)
|
| 202 |
+
|
| 203 |
+
def enable_vae_slicing(self):
|
| 204 |
+
r"""
|
| 205 |
+
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
| 206 |
+
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
| 207 |
+
"""
|
| 208 |
+
self.vae.enable_slicing()
|
| 209 |
+
|
| 210 |
+
def disable_vae_slicing(self):
|
| 211 |
+
r"""
|
| 212 |
+
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
|
| 213 |
+
computing decoding in one step.
|
| 214 |
+
"""
|
| 215 |
+
self.vae.disable_slicing()
|
| 216 |
+
|
| 217 |
+
def enable_vae_tiling(self):
|
| 218 |
+
r"""
|
| 219 |
+
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
| 220 |
+
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
| 221 |
+
processing larger images.
|
| 222 |
+
"""
|
| 223 |
+
self.vae.enable_tiling()
|
| 224 |
+
|
| 225 |
+
def disable_vae_tiling(self):
|
| 226 |
+
r"""
|
| 227 |
+
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
|
| 228 |
+
computing decoding in one step.
|
| 229 |
+
"""
|
| 230 |
+
self.vae.disable_tiling()
|
| 231 |
+
|
| 232 |
+
def _encode_prompt(
|
| 233 |
+
self,
|
| 234 |
+
prompt,
|
| 235 |
+
device,
|
| 236 |
+
num_images_per_prompt,
|
| 237 |
+
do_classifier_free_guidance,
|
| 238 |
+
negative_prompt=None,
|
| 239 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 240 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 241 |
+
lora_scale: Optional[float] = None,
|
| 242 |
+
):
|
| 243 |
+
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."
|
| 244 |
+
deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
|
| 245 |
+
|
| 246 |
+
prompt_embeds_tuple = self.encode_prompt(
|
| 247 |
+
prompt=prompt,
|
| 248 |
+
device=device,
|
| 249 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 250 |
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
| 251 |
+
negative_prompt=negative_prompt,
|
| 252 |
+
prompt_embeds=prompt_embeds,
|
| 253 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 254 |
+
lora_scale=lora_scale,
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
# concatenate for backwards comp
|
| 258 |
+
prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
|
| 259 |
+
|
| 260 |
+
return prompt_embeds
|
| 261 |
+
|
| 262 |
+
def encode_prompt(
|
| 263 |
+
self,
|
| 264 |
+
prompt,
|
| 265 |
+
device,
|
| 266 |
+
num_images_per_prompt,
|
| 267 |
+
do_classifier_free_guidance,
|
| 268 |
+
negative_prompt=None,
|
| 269 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 270 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 271 |
+
lora_scale: Optional[float] = None,
|
| 272 |
+
):
|
| 273 |
+
r"""
|
| 274 |
+
Encodes the prompt into text encoder hidden states.
|
| 275 |
+
|
| 276 |
+
Args:
|
| 277 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 278 |
+
prompt to be encoded
|
| 279 |
+
device: (`torch.device`):
|
| 280 |
+
torch device
|
| 281 |
+
num_images_per_prompt (`int`):
|
| 282 |
+
number of images that should be generated per prompt
|
| 283 |
+
do_classifier_free_guidance (`bool`):
|
| 284 |
+
whether to use classifier free guidance or not
|
| 285 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 286 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 287 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 288 |
+
less than `1`).
|
| 289 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 290 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 291 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 292 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 293 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 294 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 295 |
+
argument.
|
| 296 |
+
lora_scale (`float`, *optional*):
|
| 297 |
+
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
| 298 |
+
"""
|
| 299 |
+
# set lora scale so that monkey patched LoRA
|
| 300 |
+
# function of text encoder can correctly access it
|
| 301 |
+
if lora_scale is not None and isinstance(self, LoraLoaderMixin):
|
| 302 |
+
self._lora_scale = lora_scale
|
| 303 |
+
|
| 304 |
+
# dynamically adjust the LoRA scale
|
| 305 |
+
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
| 306 |
+
|
| 307 |
+
if prompt is not None and isinstance(prompt, str):
|
| 308 |
+
batch_size = 1
|
| 309 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 310 |
+
batch_size = len(prompt)
|
| 311 |
+
else:
|
| 312 |
+
batch_size = prompt_embeds.shape[0]
|
| 313 |
+
|
| 314 |
+
if prompt_embeds is None:
|
| 315 |
+
# textual inversion: procecss multi-vector tokens if necessary
|
| 316 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 317 |
+
prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
|
| 318 |
+
|
| 319 |
+
text_inputs = self.tokenizer(
|
| 320 |
+
prompt,
|
| 321 |
+
padding="max_length",
|
| 322 |
+
max_length=self.tokenizer.model_max_length,
|
| 323 |
+
truncation=True,
|
| 324 |
+
return_tensors="pt",
|
| 325 |
+
)
|
| 326 |
+
text_input_ids = text_inputs.input_ids
|
| 327 |
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
| 328 |
+
|
| 329 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
| 330 |
+
text_input_ids, untruncated_ids
|
| 331 |
+
):
|
| 332 |
+
removed_text = self.tokenizer.batch_decode(
|
| 333 |
+
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
|
| 334 |
+
)
|
| 335 |
+
logger.warning(
|
| 336 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
| 337 |
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 341 |
+
attention_mask = text_inputs.attention_mask.to(device)
|
| 342 |
+
else:
|
| 343 |
+
attention_mask = None
|
| 344 |
+
|
| 345 |
+
prompt_embeds = self.text_encoder(
|
| 346 |
+
text_input_ids.to(device),
|
| 347 |
+
attention_mask=attention_mask,
|
| 348 |
+
)
|
| 349 |
+
prompt_embeds = prompt_embeds[0]
|
| 350 |
+
|
| 351 |
+
if self.text_encoder is not None:
|
| 352 |
+
prompt_embeds_dtype = self.text_encoder.dtype
|
| 353 |
+
elif self.unet is not None:
|
| 354 |
+
prompt_embeds_dtype = self.unet.dtype
|
| 355 |
+
else:
|
| 356 |
+
prompt_embeds_dtype = prompt_embeds.dtype
|
| 357 |
+
|
| 358 |
+
prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
| 359 |
+
|
| 360 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 361 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 362 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 363 |
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 364 |
+
|
| 365 |
+
# get unconditional embeddings for classifier free guidance
|
| 366 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 367 |
+
uncond_tokens: List[str]
|
| 368 |
+
if negative_prompt is None:
|
| 369 |
+
uncond_tokens = [""] * batch_size
|
| 370 |
+
elif prompt is not None and type(prompt) is not type(negative_prompt):
|
| 371 |
+
raise TypeError(
|
| 372 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 373 |
+
f" {type(prompt)}."
|
| 374 |
+
)
|
| 375 |
+
elif isinstance(negative_prompt, str):
|
| 376 |
+
uncond_tokens = [negative_prompt]
|
| 377 |
+
elif batch_size != len(negative_prompt):
|
| 378 |
+
raise ValueError(
|
| 379 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 380 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 381 |
+
" the batch size of `prompt`."
|
| 382 |
+
)
|
| 383 |
+
else:
|
| 384 |
+
uncond_tokens = negative_prompt
|
| 385 |
+
|
| 386 |
+
# textual inversion: procecss multi-vector tokens if necessary
|
| 387 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 388 |
+
uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
|
| 389 |
+
|
| 390 |
+
max_length = prompt_embeds.shape[1]
|
| 391 |
+
uncond_input = self.tokenizer(
|
| 392 |
+
uncond_tokens,
|
| 393 |
+
padding="max_length",
|
| 394 |
+
max_length=max_length,
|
| 395 |
+
truncation=True,
|
| 396 |
+
return_tensors="pt",
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 400 |
+
attention_mask = uncond_input.attention_mask.to(device)
|
| 401 |
+
else:
|
| 402 |
+
attention_mask = None
|
| 403 |
+
|
| 404 |
+
negative_prompt_embeds = self.text_encoder(
|
| 405 |
+
uncond_input.input_ids.to(device),
|
| 406 |
+
attention_mask=attention_mask,
|
| 407 |
+
)
|
| 408 |
+
negative_prompt_embeds = negative_prompt_embeds[0]
|
| 409 |
+
|
| 410 |
+
if do_classifier_free_guidance:
|
| 411 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 412 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 413 |
+
|
| 414 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
| 415 |
+
|
| 416 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 417 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 418 |
+
|
| 419 |
+
return prompt_embeds, negative_prompt_embeds
|
| 420 |
+
|
| 421 |
+
def run_safety_checker(self, image, device, dtype):
|
| 422 |
+
if self.safety_checker is None:
|
| 423 |
+
has_nsfw_concept = None
|
| 424 |
+
else:
|
| 425 |
+
if torch.is_tensor(image):
|
| 426 |
+
feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
|
| 427 |
+
else:
|
| 428 |
+
feature_extractor_input = self.image_processor.numpy_to_pil(image)
|
| 429 |
+
safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
|
| 430 |
+
image, has_nsfw_concept = self.safety_checker(
|
| 431 |
+
images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
|
| 432 |
+
)
|
| 433 |
+
return image, has_nsfw_concept
|
| 434 |
+
|
| 435 |
+
def decode_latents(self, latents):
|
| 436 |
+
deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
|
| 437 |
+
deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
|
| 438 |
+
|
| 439 |
+
latents = 1 / self.vae.config.scaling_factor * latents
|
| 440 |
+
image = self.vae.decode(latents, return_dict=False)[0]
|
| 441 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 442 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
| 443 |
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 444 |
+
return image
|
| 445 |
+
|
| 446 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
| 447 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 448 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 449 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 450 |
+
# and should be between [0, 1]
|
| 451 |
+
|
| 452 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 453 |
+
extra_step_kwargs = {}
|
| 454 |
+
if accepts_eta:
|
| 455 |
+
extra_step_kwargs["eta"] = eta
|
| 456 |
+
|
| 457 |
+
# check if the scheduler accepts generator
|
| 458 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 459 |
+
if accepts_generator:
|
| 460 |
+
extra_step_kwargs["generator"] = generator
|
| 461 |
+
return extra_step_kwargs
|
| 462 |
+
|
| 463 |
+
def check_inputs(
|
| 464 |
+
self,
|
| 465 |
+
prompt,
|
| 466 |
+
height,
|
| 467 |
+
width,
|
| 468 |
+
callback_steps,
|
| 469 |
+
negative_prompt=None,
|
| 470 |
+
prompt_embeds=None,
|
| 471 |
+
negative_prompt_embeds=None,
|
| 472 |
+
):
|
| 473 |
+
if height % 8 != 0 or width % 8 != 0:
|
| 474 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
| 475 |
+
|
| 476 |
+
if (callback_steps is None) or (
|
| 477 |
+
callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
|
| 478 |
+
):
|
| 479 |
+
raise ValueError(
|
| 480 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
| 481 |
+
f" {type(callback_steps)}."
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
if prompt is not None and prompt_embeds is not None:
|
| 485 |
+
raise ValueError(
|
| 486 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 487 |
+
" only forward one of the two."
|
| 488 |
+
)
|
| 489 |
+
elif prompt is None and prompt_embeds is None:
|
| 490 |
+
raise ValueError(
|
| 491 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 492 |
+
)
|
| 493 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 494 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 495 |
+
|
| 496 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
| 497 |
+
raise ValueError(
|
| 498 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
| 499 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
| 503 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
| 504 |
+
raise ValueError(
|
| 505 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
| 506 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
| 507 |
+
f" {negative_prompt_embeds.shape}."
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
|
| 511 |
+
shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
|
| 512 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 513 |
+
raise ValueError(
|
| 514 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 515 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 516 |
+
)
|
| 517 |
+
|
| 518 |
+
if latents is None:
|
| 519 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 520 |
+
else:
|
| 521 |
+
latents = latents.to(device)
|
| 522 |
+
|
| 523 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
| 524 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 525 |
+
return latents
|
| 526 |
+
|
| 527 |
+
@torch.no_grad()
|
| 528 |
+
def __call__(
|
| 529 |
+
self,
|
| 530 |
+
prompt: Union[str, List[str]] = None,
|
| 531 |
+
height: Optional[int] = None,
|
| 532 |
+
width: Optional[int] = None,
|
| 533 |
+
num_inference_steps: int = 50,
|
| 534 |
+
guidance_scale: float = 7.5,
|
| 535 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 536 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 537 |
+
eta: float = 0.0,
|
| 538 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 539 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 540 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 541 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 542 |
+
output_type: Optional[str] = "pil",
|
| 543 |
+
return_dict: bool = True,
|
| 544 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 545 |
+
callback_steps: int = 1,
|
| 546 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 547 |
+
guidance_rescale: float = 0.0,
|
| 548 |
+
optimization_steps: int = 1,
|
| 549 |
+
learning_rate: float = 0.05,
|
| 550 |
+
max_steps: int = 50,
|
| 551 |
+
input_image = None,
|
| 552 |
+
mask_image = None,
|
| 553 |
+
save_masked_image = False,
|
| 554 |
+
output_path : str = "",
|
| 555 |
+
inverseproblem: bool = False,
|
| 556 |
+
):
|
| 557 |
+
assert input_image is not None, "Please provide an input image for the inpainting task."
|
| 558 |
+
|
| 559 |
+
# 0. Default height and width to unet
|
| 560 |
+
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
| 561 |
+
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
| 562 |
+
|
| 563 |
+
# 1. Check inputs
|
| 564 |
+
self.check_inputs(prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds)
|
| 565 |
+
|
| 566 |
+
# 2. Define call parameters
|
| 567 |
+
batch_size = 1 if prompt is None else (1 if isinstance(prompt, str) else len(prompt))
|
| 568 |
+
device = self._execution_device
|
| 569 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
| 570 |
+
|
| 571 |
+
# 3. Encode input prompt
|
| 572 |
+
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
| 573 |
+
prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt,
|
| 574 |
+
prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds,
|
| 575 |
+
lora_scale=cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None,
|
| 576 |
+
)
|
| 577 |
+
if do_classifier_free_guidance:
|
| 578 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
| 579 |
+
|
| 580 |
+
# 4. Prepare timesteps
|
| 581 |
+
timesteps = [(1. - i/num_inference_steps) * 1000. for i in range(num_inference_steps)]
|
| 582 |
+
|
| 583 |
+
# Convert PIL image to tensor
|
| 584 |
+
mask_image = mask_image.convert("L")
|
| 585 |
+
mask = TF.ToTensor()(mask_image).to(device=device, dtype=self.unet.dtype)
|
| 586 |
+
mask = TF.Resize(input_image.size, interpolation=TF.InterpolationMode.NEAREST)(mask)
|
| 587 |
+
mask = (mask > 0.5)
|
| 588 |
+
mask = ~mask
|
| 589 |
+
|
| 590 |
+
# 4. Preprocess image
|
| 591 |
+
image = self.image_processor.preprocess(input_image).to(device=device, dtype=self.unet.dtype)
|
| 592 |
+
if inverseproblem:
|
| 593 |
+
image = image*mask
|
| 594 |
+
image = image.to(device=device, dtype=self.unet.dtype)
|
| 595 |
+
noisy_image = image.detach().clone()
|
| 596 |
+
|
| 597 |
+
latents = retrieve_latents(self.vae.encode(noisy_image), generator=generator) * self.vae.config.scaling_factor
|
| 598 |
+
|
| 599 |
+
# 5. Prepare latent variables
|
| 600 |
+
num_channels_latents = self.unet.config.in_channels
|
| 601 |
+
latents = self.prepare_latents(
|
| 602 |
+
batch_size * num_images_per_prompt, num_channels_latents, height, width,
|
| 603 |
+
prompt_embeds.dtype, device, generator, latents,
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
# 6. Prepare extra step kwargs
|
| 607 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 608 |
+
|
| 609 |
+
print(mask.shape)
|
| 610 |
+
h, w = latents.shape[2], latents.shape[3]
|
| 611 |
+
mask = TF.Resize((h, w))(mask.to(device))
|
| 612 |
+
mask = (~(mask > 0.1)).float()
|
| 613 |
+
|
| 614 |
+
# Slightly dilate the mask to increase coverage
|
| 615 |
+
# We do this to ensure that the VAE model does not have the adverse effect due to the compression
|
| 616 |
+
if inverseproblem:
|
| 617 |
+
print("Dilating the masks.")
|
| 618 |
+
kernel_size = 3 # Decreased from 3 to 2
|
| 619 |
+
kernel = torch.ones((1, 1, kernel_size, kernel_size), device=device)
|
| 620 |
+
mask = torch.nn.functional.conv2d(
|
| 621 |
+
mask.unsqueeze(0),
|
| 622 |
+
kernel,
|
| 623 |
+
padding=kernel_size//2
|
| 624 |
+
).squeeze(0)
|
| 625 |
+
mask = torch.clamp(mask, 0, 1)
|
| 626 |
+
|
| 627 |
+
mask = (mask > 0.1).float()
|
| 628 |
+
|
| 629 |
+
# Apply the mask to latents_copy
|
| 630 |
+
random_latents = self.prepare_latents(
|
| 631 |
+
batch_size * num_images_per_prompt, num_channels_latents, height, width,
|
| 632 |
+
prompt_embeds.dtype, device, generator
|
| 633 |
+
)
|
| 634 |
+
|
| 635 |
+
bool_mask = mask.bool().unsqueeze(0).expand_as(latents)
|
| 636 |
+
mask = ~bool_mask
|
| 637 |
+
|
| 638 |
+
masked_latents = (latents * mask).clone().detach()
|
| 639 |
+
if save_masked_image:
|
| 640 |
+
masked_image = self.vae.decode(masked_latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
| 641 |
+
masked_image = self.image_processor.postprocess(masked_image, output_type="pil")[0]
|
| 642 |
+
masked_image_path = output_path.replace(".", "_ip_degraded.")
|
| 643 |
+
masked_image.save(masked_image_path)
|
| 644 |
+
print(f"Masked image saved to: {masked_image_path}")
|
| 645 |
+
|
| 646 |
+
latents = random_latents.clone().detach()
|
| 647 |
+
|
| 648 |
+
self.unet.eval()
|
| 649 |
+
self.vae.eval()
|
| 650 |
+
|
| 651 |
+
# Initialize timing and memory tracking if not already done
|
| 652 |
+
if not hasattr(self, 'avg_total_time'):
|
| 653 |
+
self.avg_total_time = 0
|
| 654 |
+
self.num_calls = 0
|
| 655 |
+
if not hasattr(self, 'max_memory'):
|
| 656 |
+
self.max_memory = 0
|
| 657 |
+
|
| 658 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 659 |
+
for i, t in enumerate(timesteps):
|
| 660 |
+
latents = self.perform_denoising_step(
|
| 661 |
+
latents, t, prompt_embeds, do_classifier_free_guidance, guidance_scale,
|
| 662 |
+
device, i, optimization_steps, learning_rate,
|
| 663 |
+
max_steps, timesteps, mask, masked_latents, noisy_image
|
| 664 |
+
)
|
| 665 |
+
|
| 666 |
+
if callback is not None and i % callback_steps == 0:
|
| 667 |
+
callback(i // getattr(self.scheduler, "order", 1), t, latents)
|
| 668 |
+
|
| 669 |
+
progress_bar.update()
|
| 670 |
+
|
| 671 |
+
# 10. Post-processing
|
| 672 |
+
image = self.post_process_image(latents, output_type)
|
| 673 |
+
|
| 674 |
+
# 11. Offload all models
|
| 675 |
+
self.maybe_free_model_hooks()
|
| 676 |
+
|
| 677 |
+
if not return_dict:
|
| 678 |
+
return (image, None)
|
| 679 |
+
|
| 680 |
+
return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=None)
|
| 681 |
+
|
| 682 |
+
def load_and_preprocess_image(self, image_path, custom_image_processor, device):
|
| 683 |
+
from diffusers.utils import load_image
|
| 684 |
+
img = load_image(image_path)
|
| 685 |
+
img = img.resize((512, 512))
|
| 686 |
+
return custom_image_processor(img).unsqueeze(0).to(device)
|
| 687 |
+
|
| 688 |
+
def perform_denoising_step(self, latents, t, prompt_embeds, do_classifier_free_guidance, guidance_scale,
|
| 689 |
+
device, step, optimization_steps, learning_rate,
|
| 690 |
+
max_steps, timesteps, mask, masked_latents, noisy_image):
|
| 691 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
| 692 |
+
vec_t = torch.ones((latent_model_input.shape[0],), device=latents.device) * t
|
| 693 |
+
v_pred = self.unet(latent_model_input, vec_t, encoder_hidden_states=prompt_embeds).sample
|
| 694 |
+
|
| 695 |
+
if do_classifier_free_guidance:
|
| 696 |
+
v_pred_neg, v_pred_text = v_pred.chunk(2)
|
| 697 |
+
v_pred = v_pred_neg + guidance_scale * (v_pred_text - v_pred_neg)
|
| 698 |
+
|
| 699 |
+
if step <= max_steps:
|
| 700 |
+
latents = self.optimize_latents(latents, v_pred, t,
|
| 701 |
+
device, optimization_steps, learning_rate, mask, masked_latents, noisy_image)
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
return latents + (1.0 / len(timesteps)) * v_pred
|
| 705 |
+
|
| 706 |
+
def optimize_latents(self, latents, v_pred, t, device, optimization_steps, learning_rate,
|
| 707 |
+
mask, masked_latents, noisy_image):
|
| 708 |
+
with torch.enable_grad():
|
| 709 |
+
latents = torch.autograd.Variable(latents, requires_grad=True)
|
| 710 |
+
optimizer = torch.optim.Adam([latents], lr=learning_rate)
|
| 711 |
+
|
| 712 |
+
for _ in range(optimization_steps):
|
| 713 |
+
latents_p = latents + t/1000 * v_pred
|
| 714 |
+
loss = (0.001*torch.nn.functional.mse_loss(latents_p, masked_latents, reduction='none')*mask).mean()
|
| 715 |
+
|
| 716 |
+
loss.backward()
|
| 717 |
+
optimizer.step()
|
| 718 |
+
optimizer.zero_grad()
|
| 719 |
+
|
| 720 |
+
return latents
|
| 721 |
+
|
| 722 |
+
def decode_latents(self, latents):
|
| 723 |
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
| 724 |
+
return self.image_processor.postprocess(image, output_type="pt")[0]
|
| 725 |
+
|
| 726 |
+
def post_process_image(self, latents, output_type):
|
| 727 |
+
if output_type == "latent":
|
| 728 |
+
return latents
|
| 729 |
+
|
| 730 |
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
| 731 |
+
do_denormalize = [True] * image.shape[0]
|
| 732 |
+
return self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
spaces
|
| 2 |
+
diffusers==0.31.0
|
| 3 |
+
gradio==5.6.0
|
| 4 |
+
numpy==2.1.3
|
| 5 |
+
Pillow==11.0.0
|
| 6 |
+
torch==2.1.2
|
| 7 |
+
torch_xla==2.5.1
|
| 8 |
+
torchvision==0.16.2
|
| 9 |
+
transformers==4.45.2
|
saved_results/20241129_210517/input.png
ADDED
|
saved_results/20241129_210517/mask.png
ADDED
|
saved_results/20241129_210517/output.png
ADDED
|
saved_results/20241129_210517/parameters.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"prompt": "a cat",
|
| 3 |
+
"seed": 0,
|
| 4 |
+
"randomize_seed": true,
|
| 5 |
+
"num_inference_steps": 200,
|
| 6 |
+
"max_steps": 200,
|
| 7 |
+
"learning_rate": 0.1,
|
| 8 |
+
"optimization_steps": 1,
|
| 9 |
+
"inverseproblem": false
|
| 10 |
+
}
|
saved_results/20241129_211124/input.png
ADDED
|
saved_results/20241129_211124/mask.png
ADDED
|
saved_results/20241129_211124/output.png
ADDED
|
saved_results/20241129_211124/parameters.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"prompt": " ",
|
| 3 |
+
"seed": 0,
|
| 4 |
+
"randomize_seed": true,
|
| 5 |
+
"num_inference_steps": 200,
|
| 6 |
+
"max_steps": 200,
|
| 7 |
+
"learning_rate": 0.1,
|
| 8 |
+
"optimization_steps": 5,
|
| 9 |
+
"inverseproblem": false
|
| 10 |
+
}
|
saved_results/20241129_211142/input.png
ADDED
|
saved_results/20241129_211142/mask.png
ADDED
|
saved_results/20241129_211142/output.png
ADDED
|
saved_results/20241129_211142/parameters.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"prompt": " ",
|
| 3 |
+
"seed": 0,
|
| 4 |
+
"randomize_seed": true,
|
| 5 |
+
"num_inference_steps": 200,
|
| 6 |
+
"max_steps": 200,
|
| 7 |
+
"learning_rate": 0.1,
|
| 8 |
+
"optimization_steps": 5,
|
| 9 |
+
"inverseproblem": true
|
| 10 |
+
}
|
saved_results/20241129_211621/input.png
ADDED
|
Git LFS Details
|
saved_results/20241129_211621/mask.png
ADDED
|
saved_results/20241129_211621/output.png
ADDED
|
saved_results/20241129_211621/parameters.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"prompt": " ",
|
| 3 |
+
"seed": 0,
|
| 4 |
+
"randomize_seed": true,
|
| 5 |
+
"num_inference_steps": 200,
|
| 6 |
+
"max_steps": 200,
|
| 7 |
+
"learning_rate": 0.1,
|
| 8 |
+
"optimization_steps": 5,
|
| 9 |
+
"inverseproblem": true
|
| 10 |
+
}
|
saved_results/20241129_211904/input.png
ADDED
|
Git LFS Details
|
saved_results/20241129_211904/mask.png
ADDED
|
saved_results/20241129_211904/output.png
ADDED
|
saved_results/20241129_211904/parameters.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"prompt": " ",
|
| 3 |
+
"seed": 0,
|
| 4 |
+
"randomize_seed": true,
|
| 5 |
+
"num_inference_steps": 200,
|
| 6 |
+
"max_steps": 200,
|
| 7 |
+
"learning_rate": 0.02,
|
| 8 |
+
"optimization_steps": 5,
|
| 9 |
+
"inverseproblem": true
|
| 10 |
+
}
|
saved_results/20241129_212001/input.png
ADDED
|
Git LFS Details
|
saved_results/20241129_212001/mask.png
ADDED
|
saved_results/20241129_212001/output.png
ADDED
|
saved_results/20241129_212001/parameters.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"prompt": " ",
|
| 3 |
+
"seed": 52,
|
| 4 |
+
"randomize_seed": false,
|
| 5 |
+
"num_inference_steps": 200,
|
| 6 |
+
"max_steps": 200,
|
| 7 |
+
"learning_rate": 0.02,
|
| 8 |
+
"optimization_steps": 10,
|
| 9 |
+
"inverseproblem": true
|
| 10 |
+
}
|
saved_results/20241129_212022/input.png
ADDED
|
Git LFS Details
|
saved_results/20241129_212022/mask.png
ADDED
|
saved_results/20241129_212022/output.png
ADDED
|
saved_results/20241129_212022/parameters.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"prompt": " ",
|
| 3 |
+
"seed": 52,
|
| 4 |
+
"randomize_seed": false,
|
| 5 |
+
"num_inference_steps": 200,
|
| 6 |
+
"max_steps": 200,
|
| 7 |
+
"learning_rate": 0.02,
|
| 8 |
+
"optimization_steps": 10,
|
| 9 |
+
"inverseproblem": false
|
| 10 |
+
}
|
saved_results/20241129_212052/input.png
ADDED
|
Git LFS Details
|
saved_results/20241129_212052/mask.png
ADDED
|
saved_results/20241129_212052/output.png
ADDED
|
saved_results/20241129_212052/parameters.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"prompt": " ",
|
| 3 |
+
"seed": 52,
|
| 4 |
+
"randomize_seed": false,
|
| 5 |
+
"num_inference_steps": 200,
|
| 6 |
+
"max_steps": 200,
|
| 7 |
+
"learning_rate": 0.02,
|
| 8 |
+
"optimization_steps": 10,
|
| 9 |
+
"inverseproblem": true
|
| 10 |
+
}
|
saved_results/20241129_212110/input.png
ADDED
|
Git LFS Details
|
saved_results/20241129_212110/mask.png
ADDED
|
saved_results/20241129_212110/output.png
ADDED
|
saved_results/20241129_212110/parameters.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"prompt": " ",
|
| 3 |
+
"seed": 52,
|
| 4 |
+
"randomize_seed": false,
|
| 5 |
+
"num_inference_steps": 200,
|
| 6 |
+
"max_steps": 200,
|
| 7 |
+
"learning_rate": 0.02,
|
| 8 |
+
"optimization_steps": 10,
|
| 9 |
+
"inverseproblem": false
|
| 10 |
+
}
|
saved_results/20241129_212155/input.png
ADDED
|
Git LFS Details
|
saved_results/20241129_212155/mask.png
ADDED
|
saved_results/20241129_212155/output.png
ADDED
|
saved_results/20241129_212155/parameters.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"prompt": " ",
|
| 3 |
+
"seed": 52,
|
| 4 |
+
"randomize_seed": false,
|
| 5 |
+
"num_inference_steps": 200,
|
| 6 |
+
"max_steps": 200,
|
| 7 |
+
"learning_rate": 0.02,
|
| 8 |
+
"optimization_steps": 10,
|
| 9 |
+
"inverseproblem": true
|
| 10 |
+
}
|
saved_results/20241129_212220/input.png
ADDED
|
Git LFS Details
|
saved_results/20241129_212220/mask.png
ADDED
|
saved_results/20241129_212220/output.png
ADDED
|