Spaces:
Configuration error
Configuration error
Commit
·
50773f7
0
Parent(s):
Duplicate from MirageML/dreambooth
Browse filesCo-authored-by: Aman Kishore <[email protected]>
- .gitattributes +35 -0
- .gitignore +7 -0
- README.md +14 -0
- app.py +618 -0
- arrow.png +0 -0
- cat-toy.png +0 -0
- convertosd.py +226 -0
- duplicate.png +0 -0
- mirage.png +0 -0
- mix.zip +3 -0
- model_index.json +32 -0
- person.png +0 -0
- requirements-local.txt +18 -0
- requirements.txt +18 -0
- train_dreambooth.py +881 -0
- trsl_style.png +0 -0
.gitattributes
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
25 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
26 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
34 |
+
xformers-0.0.14.dev0-cp38-cp38-linux_x86_64_t4.whl filter=lfs diff=lfs merge=lfs -text
|
35 |
+
xformers-0.0.14.dev0-cp38-cp38-linux_x86_64.whl filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Mix
|
2 |
+
output_model
|
3 |
+
instance_images
|
4 |
+
__pycache__
|
5 |
+
intraining.lock
|
6 |
+
hastrained.success
|
7 |
+
diffusers_model.tar
|
README.md
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: Dreambooth Web UI
|
3 |
+
emoji: ☁️
|
4 |
+
colorFrom: pink
|
5 |
+
colorTo: red
|
6 |
+
sdk: gradio
|
7 |
+
sdk_version: 3.11
|
8 |
+
app_file: app.py
|
9 |
+
pinned: false
|
10 |
+
license: mit
|
11 |
+
duplicated_from: MirageML/dreambooth
|
12 |
+
---
|
13 |
+
|
14 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
@@ -0,0 +1,618 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os
|
3 |
+
from pathlib import Path
|
4 |
+
import argparse
|
5 |
+
import shutil
|
6 |
+
from train_dreambooth import run_training
|
7 |
+
from convertosd import convert
|
8 |
+
from PIL import Image
|
9 |
+
from slugify import slugify
|
10 |
+
import requests
|
11 |
+
import torch
|
12 |
+
import zipfile
|
13 |
+
import tarfile
|
14 |
+
import urllib.parse
|
15 |
+
import gc
|
16 |
+
from diffusers import StableDiffusionPipeline
|
17 |
+
from huggingface_hub import snapshot_download
|
18 |
+
|
19 |
+
|
20 |
+
is_spaces = True if "SPACE_ID" in os.environ else False
|
21 |
+
is_shared_ui = True if "IS_SHARED_UI" in os.environ else False
|
22 |
+
is_gpu_associated = torch.cuda.is_available()
|
23 |
+
|
24 |
+
css = '''
|
25 |
+
.instruction{position: absolute; top: 0;right: 0;margin-top: 0px !important}
|
26 |
+
.arrow{position: absolute;top: 0;right: -110px;margin-top: -8px !important}
|
27 |
+
#component-4, #component-3, #component-10{min-height: 0}
|
28 |
+
.duplicate-button img{margin: 0}
|
29 |
+
'''
|
30 |
+
maximum_concepts = 3
|
31 |
+
|
32 |
+
#Pre download the files
|
33 |
+
if(is_gpu_associated):
|
34 |
+
model_v1 = snapshot_download(repo_id="multimodalart/sd-fine-tunable")
|
35 |
+
model_v2 = snapshot_download(repo_id="stabilityai/stable-diffusion-2")
|
36 |
+
model_v2_512 = snapshot_download(repo_id="stabilityai/stable-diffusion-2-base")
|
37 |
+
safety_checker = snapshot_download(repo_id="multimodalart/sd-sc")
|
38 |
+
model_to_load = model_v1
|
39 |
+
|
40 |
+
with zipfile.ZipFile("mix.zip", 'r') as zip_ref:
|
41 |
+
zip_ref.extractall(".")
|
42 |
+
|
43 |
+
def swap_base_model(selected_model):
|
44 |
+
if(is_gpu_associated):
|
45 |
+
global model_to_load
|
46 |
+
if(selected_model == "v1-5"):
|
47 |
+
model_to_load = model_v1
|
48 |
+
elif(selected_model == "v2-768"):
|
49 |
+
model_to_load = model_v2
|
50 |
+
else:
|
51 |
+
model_to_load = model_v2_512
|
52 |
+
|
53 |
+
def count_files(*inputs):
|
54 |
+
file_counter = 0
|
55 |
+
concept_counter = 0
|
56 |
+
for i, input in enumerate(inputs):
|
57 |
+
if(i < maximum_concepts-1):
|
58 |
+
files = inputs[i]
|
59 |
+
if(files):
|
60 |
+
concept_counter+=1
|
61 |
+
file_counter+=len(files)
|
62 |
+
uses_custom = inputs[-1]
|
63 |
+
selected_model = inputs[-4]
|
64 |
+
experimental_faces = inputs[-5]
|
65 |
+
if(uses_custom):
|
66 |
+
Training_Steps = int(inputs[-3])
|
67 |
+
else:
|
68 |
+
Training_Steps = file_counter*150
|
69 |
+
if(is_spaces):
|
70 |
+
if(selected_model == "v1-5"):
|
71 |
+
its = 1.1
|
72 |
+
if(experimental_faces):
|
73 |
+
its = 1
|
74 |
+
elif(selected_model == "v2-512"):
|
75 |
+
its = 0.8
|
76 |
+
if(experimental_faces):
|
77 |
+
its = 0.7
|
78 |
+
elif(selected_model == "v2-768"):
|
79 |
+
its = 0.5
|
80 |
+
summary_sentence = f'''You are going to train {concept_counter}, with {file_counter} images for {Training_Steps} steps. The training should take around {round(Training_Steps/its, 2)} seconds, or {round((Training_Steps/its)/60, 2)} minutes.
|
81 |
+
The setup, compression and uploading the model can take up to 20 minutes.<br>As the T4-Small GPU costs US$0.60 for 1h, <span style="font-size: 120%"><b>the estimated cost for this training is below US${round((((Training_Steps/its)/3600)+0.3+0.1)*0.60, 2)}.</b></span><br><br>
|
82 |
+
If you check the box below the GPU attribution will automatically removed after training is done and the model is uploaded. If not, don't forget to come back here and swap the hardware back to CPU.<br><br>'''
|
83 |
+
else:
|
84 |
+
summary_sentence = f'''You are going to train {concept_counter}, with {file_counter} images for {Training_Steps} steps.<br><br>'''
|
85 |
+
|
86 |
+
return([gr.update(visible=True), gr.update(visible=True, value=summary_sentence)])
|
87 |
+
|
88 |
+
def update_steps(*files_list):
|
89 |
+
file_counter = 0
|
90 |
+
for i, files in enumerate(files_list):
|
91 |
+
if(files):
|
92 |
+
file_counter+=len(files)
|
93 |
+
return(gr.update(value=file_counter*200))
|
94 |
+
|
95 |
+
def pad_image(image):
|
96 |
+
w, h = image.size
|
97 |
+
if w == h:
|
98 |
+
return image
|
99 |
+
elif w > h:
|
100 |
+
new_image = Image.new(image.mode, (w, w), (0, 0, 0))
|
101 |
+
new_image.paste(image, (0, (w - h) // 2))
|
102 |
+
return new_image
|
103 |
+
else:
|
104 |
+
new_image = Image.new(image.mode, (h, h), (0, 0, 0))
|
105 |
+
new_image.paste(image, ((h - w) // 2, 0))
|
106 |
+
return new_image
|
107 |
+
|
108 |
+
def train(*inputs):
|
109 |
+
if is_shared_ui:
|
110 |
+
raise gr.Error("This Space only works in duplicated instances")
|
111 |
+
if not is_gpu_associated:
|
112 |
+
raise gr.Error("Please associate a T4 GPU for this Space")
|
113 |
+
torch.cuda.empty_cache()
|
114 |
+
if 'pipe' in globals():
|
115 |
+
global pipe, pipe_is_set
|
116 |
+
del pipe
|
117 |
+
pipe_is_set = False
|
118 |
+
gc.collect()
|
119 |
+
|
120 |
+
if os.path.exists("output_model"): shutil.rmtree('output_model')
|
121 |
+
if os.path.exists("instance_images"): shutil.rmtree('instance_images')
|
122 |
+
if os.path.exists("diffusers_model.tar"): os.remove("diffusers_model.tar")
|
123 |
+
if os.path.exists("model.ckpt"): os.remove("model.ckpt")
|
124 |
+
if os.path.exists("hastrained.success"): os.remove("hastrained.success")
|
125 |
+
file_counter = 0
|
126 |
+
which_model = inputs[-10]
|
127 |
+
resolution = 512 if which_model != "v2-768" else 768
|
128 |
+
for i, input in enumerate(inputs):
|
129 |
+
if(i < maximum_concepts-1):
|
130 |
+
if(input):
|
131 |
+
os.makedirs('instance_images',exist_ok=True)
|
132 |
+
files = inputs[i+(maximum_concepts*2)]
|
133 |
+
prompt = inputs[i+maximum_concepts]
|
134 |
+
if(prompt == "" or prompt == None):
|
135 |
+
raise gr.Error("You forgot to define your concept prompt")
|
136 |
+
for j, file_temp in enumerate(files):
|
137 |
+
file = Image.open(file_temp.name)
|
138 |
+
image = pad_image(file)
|
139 |
+
image = image.resize((resolution, resolution))
|
140 |
+
extension = file_temp.name.split(".")[1]
|
141 |
+
image = image.convert('RGB')
|
142 |
+
image.save(f'instance_images/{prompt}_({j+1}).jpg', format="JPEG", quality = 100)
|
143 |
+
file_counter += 1
|
144 |
+
|
145 |
+
os.makedirs('output_model',exist_ok=True)
|
146 |
+
uses_custom = inputs[-1]
|
147 |
+
remove_attribution_after = inputs[-5]
|
148 |
+
experimental_face_improvement = inputs[-8]
|
149 |
+
|
150 |
+
if(uses_custom):
|
151 |
+
Training_Steps = int(inputs[-3])
|
152 |
+
Train_text_encoder_for = int(inputs[-2])
|
153 |
+
else:
|
154 |
+
Train_text_encoder_for=30
|
155 |
+
Training_Steps = file_counter*150
|
156 |
+
stptxt = int((Training_Steps*Train_text_encoder_for)/100)
|
157 |
+
gradient_checkpointing = True if (experimental_face_improvement or which_model != "v1-5") else False
|
158 |
+
cache_latents = True if which_model != "v1-5" else False
|
159 |
+
args_general = argparse.Namespace(
|
160 |
+
image_captions_filename = True,
|
161 |
+
train_text_encoder = True if stptxt > 0 else False,
|
162 |
+
stop_text_encoder_training = stptxt,
|
163 |
+
save_n_steps = 0,
|
164 |
+
pretrained_model_name_or_path = model_to_load,
|
165 |
+
instance_data_dir="instance_images",
|
166 |
+
class_data_dir="Mix",
|
167 |
+
output_dir="output_model",
|
168 |
+
with_prior_preservation=True,
|
169 |
+
prior_loss_weight=1.0,
|
170 |
+
instance_prompt="",
|
171 |
+
seed=42,
|
172 |
+
resolution=resolution,
|
173 |
+
mixed_precision="fp16",
|
174 |
+
train_batch_size=1,
|
175 |
+
gradient_accumulation_steps=1,
|
176 |
+
use_8bit_adam=True,
|
177 |
+
learning_rate=2e-6,
|
178 |
+
lr_scheduler="polynomial",
|
179 |
+
lr_warmup_steps = 0,
|
180 |
+
max_train_steps=Training_Steps,
|
181 |
+
num_class_images=200,
|
182 |
+
gradient_checkpointing=gradient_checkpointing,
|
183 |
+
cache_latents=cache_latents,
|
184 |
+
)
|
185 |
+
print("Starting multi-training...")
|
186 |
+
lock_file = open("intraining.lock", "w")
|
187 |
+
lock_file.close()
|
188 |
+
run_training(args_general)
|
189 |
+
gc.collect()
|
190 |
+
torch.cuda.empty_cache()
|
191 |
+
if(which_model == "v1-5"):
|
192 |
+
print("Adding Safety Checker to the model...")
|
193 |
+
shutil.copytree(f"{safety_checker}/feature_extractor", "output_model/feature_extractor")
|
194 |
+
shutil.copytree(f"{safety_checker}/safety_checker", "output_model/safety_checker")
|
195 |
+
shutil.copy(f"model_index.json", "output_model/model_index.json")
|
196 |
+
|
197 |
+
if(not remove_attribution_after):
|
198 |
+
print("Archiving model file...")
|
199 |
+
with tarfile.open("diffusers_model.tar", "w") as tar:
|
200 |
+
tar.add("output_model", arcname=os.path.basename("output_model"))
|
201 |
+
if os.path.exists("intraining.lock"): os.remove("intraining.lock")
|
202 |
+
trained_file = open("hastrained.success", "w")
|
203 |
+
trained_file.close()
|
204 |
+
print("Training completed!")
|
205 |
+
return [
|
206 |
+
gr.update(visible=True, value=["diffusers_model.tar"]), #result
|
207 |
+
gr.update(visible=True), #try_your_model
|
208 |
+
gr.update(visible=True), #push_to_hub
|
209 |
+
gr.update(visible=True), #convert_button
|
210 |
+
gr.update(visible=False), #training_ongoing
|
211 |
+
gr.update(visible=True) #completed_training
|
212 |
+
]
|
213 |
+
else:
|
214 |
+
hf_token = inputs[-4]
|
215 |
+
model_name = inputs[-6]
|
216 |
+
where_to_upload = inputs[-7]
|
217 |
+
push(model_name, where_to_upload, hf_token, which_model, True)
|
218 |
+
hardware_url = f"https://huggingface.co/spaces/{os.environ['SPACE_ID']}/hardware"
|
219 |
+
headers = { "authorization" : f"Bearer {hf_token}"}
|
220 |
+
body = {'flavor': 'cpu-basic'}
|
221 |
+
requests.post(hardware_url, json = body, headers=headers)
|
222 |
+
|
223 |
+
pipe_is_set = False
|
224 |
+
def generate(prompt, steps):
|
225 |
+
torch.cuda.empty_cache()
|
226 |
+
from diffusers import StableDiffusionPipeline
|
227 |
+
global pipe_is_set
|
228 |
+
if(not pipe_is_set):
|
229 |
+
global pipe
|
230 |
+
pipe = StableDiffusionPipeline.from_pretrained("./output_model", torch_dtype=torch.float16)
|
231 |
+
pipe = pipe.to("cuda")
|
232 |
+
pipe_is_set = True
|
233 |
+
|
234 |
+
image = pipe(prompt, num_inference_steps=steps).images[0]
|
235 |
+
return(image)
|
236 |
+
|
237 |
+
def push(model_name, where_to_upload, hf_token, which_model, comes_from_automated=False):
|
238 |
+
if(not os.path.exists("model.ckpt")):
|
239 |
+
convert("output_model", "model.ckpt")
|
240 |
+
from huggingface_hub import HfApi, HfFolder, CommitOperationAdd
|
241 |
+
from huggingface_hub import create_repo
|
242 |
+
model_name_slug = slugify(model_name)
|
243 |
+
api = HfApi()
|
244 |
+
your_username = api.whoami(token=hf_token)["name"]
|
245 |
+
if(where_to_upload == "My personal profile"):
|
246 |
+
model_id = f"{your_username}/{model_name_slug}"
|
247 |
+
else:
|
248 |
+
model_id = f"sd-dreambooth-library/{model_name_slug}"
|
249 |
+
headers = {"Authorization" : f"Bearer: {hf_token}", "Content-Type": "application/json"}
|
250 |
+
response = requests.post("https://huggingface.co/organizations/sd-dreambooth-library/share/SSeOwppVCscfTEzFGQaqpfcjukVeNrKNHX", headers=headers)
|
251 |
+
|
252 |
+
images_upload = os.listdir("instance_images")
|
253 |
+
image_string = ""
|
254 |
+
instance_prompt_list = []
|
255 |
+
previous_instance_prompt = ''
|
256 |
+
for i, image in enumerate(images_upload):
|
257 |
+
instance_prompt = image.split("_")[0]
|
258 |
+
if(instance_prompt != previous_instance_prompt):
|
259 |
+
title_instance_prompt_string = instance_prompt
|
260 |
+
instance_prompt_list.append(instance_prompt)
|
261 |
+
else:
|
262 |
+
title_instance_prompt_string = ''
|
263 |
+
previous_instance_prompt = instance_prompt
|
264 |
+
image_string = f'''{title_instance_prompt_string} {"(use that on your prompt)" if title_instance_prompt_string != "" else ""}
|
265 |
+
{image_string}})'''
|
266 |
+
readme_text = f'''---
|
267 |
+
license: creativeml-openrail-m
|
268 |
+
tags:
|
269 |
+
- text-to-image
|
270 |
+
widget:
|
271 |
+
- text: {instance_prompt_list[0]}
|
272 |
+
---
|
273 |
+
### {model_name} Dreambooth model trained by {api.whoami(token=hf_token)["name"]} with [Hugging Face Dreambooth Training Space](https://huggingface.co/spaces/multimodalart/dreambooth-training) with the {which_model} base model
|
274 |
+
|
275 |
+
You run your new concept via `diffusers` [Colab Notebook for Inference](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/sd_dreambooth_inference.ipynb). Don't forget to use the concept prompts!
|
276 |
+
|
277 |
+
Sample pictures of:
|
278 |
+
{image_string}
|
279 |
+
'''
|
280 |
+
#Save the readme to a file
|
281 |
+
readme_file = open("model.README.md", "w")
|
282 |
+
readme_file.write(readme_text)
|
283 |
+
readme_file.close()
|
284 |
+
#Save the token identifier to a file
|
285 |
+
text_file = open("token_identifier.txt", "w")
|
286 |
+
text_file.write(', '.join(instance_prompt_list))
|
287 |
+
text_file.close()
|
288 |
+
try:
|
289 |
+
create_repo(model_id,private=True, token=hf_token)
|
290 |
+
except:
|
291 |
+
import time
|
292 |
+
epoch_time = str(int(time.time()))
|
293 |
+
create_repo(f"{model_id}-{epoch_time}", private=True,token=hf_token)
|
294 |
+
operations = [
|
295 |
+
CommitOperationAdd(path_in_repo="token_identifier.txt", path_or_fileobj="token_identifier.txt"),
|
296 |
+
CommitOperationAdd(path_in_repo="README.md", path_or_fileobj="model.README.md"),
|
297 |
+
CommitOperationAdd(path_in_repo=f"model.ckpt",path_or_fileobj="model.ckpt")
|
298 |
+
]
|
299 |
+
api.create_commit(
|
300 |
+
repo_id=model_id,
|
301 |
+
operations=operations,
|
302 |
+
commit_message=f"Upload the model {model_name}",
|
303 |
+
token=hf_token
|
304 |
+
)
|
305 |
+
api.upload_folder(
|
306 |
+
folder_path="output_model",
|
307 |
+
repo_id=model_id,
|
308 |
+
token=hf_token
|
309 |
+
)
|
310 |
+
api.upload_folder(
|
311 |
+
folder_path="instance_images",
|
312 |
+
path_in_repo="concept_images",
|
313 |
+
repo_id=model_id,
|
314 |
+
token=hf_token
|
315 |
+
)
|
316 |
+
if is_spaces:
|
317 |
+
if(not comes_from_automated):
|
318 |
+
extra_message = "Don't forget to remove the GPU attribution after you play with it."
|
319 |
+
else:
|
320 |
+
extra_message = "The GPU has been removed automatically as requested, and you can try the model via the model page"
|
321 |
+
api.create_discussion(repo_id=os.environ['SPACE_ID'], title=f"Your model {model_name} has finished trained from the Dreambooth Train Spaces!", description=f"Your model has been successfully uploaded to: https://huggingface.co/{model_id}. {extra_message}",repo_type="space", token=hf_token)
|
322 |
+
|
323 |
+
return [gr.update(visible=True, value=f"Successfully uploaded your model. Access it [here](https://huggingface.co/{model_id})"), gr.update(visible=True, value=["diffusers_model.tar", "model.ckpt"])]
|
324 |
+
|
325 |
+
def convert_to_ckpt():
|
326 |
+
if 'pipe' in globals():
|
327 |
+
global pipe, pipe_is_set
|
328 |
+
del pipe
|
329 |
+
pipe_is_set = False
|
330 |
+
gc.collect()
|
331 |
+
convert("output_model", "model.ckpt")
|
332 |
+
return gr.update(visible=True, value=["diffusers_model.tar", "model.ckpt"])
|
333 |
+
|
334 |
+
def check_status(top_description):
|
335 |
+
if os.path.exists("hastrained.success"):
|
336 |
+
if is_spaces:
|
337 |
+
update_top_tag = gr.update(value=f'''
|
338 |
+
<div class="gr-prose" style="max-width: 80%">
|
339 |
+
<h2>Your model has finished training ✅</h2>
|
340 |
+
<p>Yay, congratulations on training your model. Scroll down to play with with it, save it (either downloading it or on the Hugging Face Hub). Once you are done, your model is safe, and you don't want to train a new one, go to the <a href="https://huggingface.co/spaces/{os.environ['SPACE_ID']}" target="_blank">settings page</a> and downgrade your Space to a CPU Basic</p>
|
341 |
+
</div>
|
342 |
+
''')
|
343 |
+
else:
|
344 |
+
update_top_tag = gr.update(value=f'''
|
345 |
+
<div style="text-align: center; max-width: 650px; margin: 0 auto;">
|
346 |
+
<div>
|
347 |
+
<img class="logo" src="file/mirage.png" alt="Mirage Logo"
|
348 |
+
style="margin: auto; max-width: 7rem;">
|
349 |
+
<br />
|
350 |
+
<h1 style="font-weight: 900; font-size: 2.5rem;">
|
351 |
+
Dreambooth Web UI
|
352 |
+
</h1>
|
353 |
+
<br />
|
354 |
+
<a class="duplicate-button" style="display:inline-block" target="_blank" href="https://huggingface.co/spaces/MirageML/dreambooth?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a>
|
355 |
+
</div>
|
356 |
+
<br />
|
357 |
+
<br />
|
358 |
+
<h2>Your model has finished training ✅</h2>
|
359 |
+
<p>Yay, congratulations on training your model. Scroll down to play with with it, save it (either downloading it or on the Hugging Face Hub).</p>
|
360 |
+
</div>
|
361 |
+
''')
|
362 |
+
show_outputs = True
|
363 |
+
elif os.path.exists("intraining.lock"):
|
364 |
+
update_top_tag = gr.update(value='''
|
365 |
+
<div style="text-align: center; max-width: 650px; margin: 0 auto;">
|
366 |
+
<div>
|
367 |
+
<img class="logo" src="file/mirage.png" alt="Mirage Logo"
|
368 |
+
style="margin: auto; max-width: 7rem;">
|
369 |
+
<br />
|
370 |
+
<h1 style="font-weight: 900; font-size: 2.5rem;">
|
371 |
+
Dreambooth Web UI
|
372 |
+
</h1>
|
373 |
+
<br />
|
374 |
+
<a class="duplicate-button" style="display:inline-block" target="_blank" href="https://huggingface.co/spaces/MirageML/dreambooth?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a>
|
375 |
+
</div>
|
376 |
+
<br />
|
377 |
+
<br />
|
378 |
+
<h2>Don't worry, your model is still training! ⌛</h2>
|
379 |
+
<p>You closed the tab while your model was training, but it's all good! It is still training right now. You can click the "Open logs" button above here to check the training status. Once training is done, reload this tab to interact with your model</p>
|
380 |
+
</div>
|
381 |
+
''')
|
382 |
+
show_outputs = False
|
383 |
+
else:
|
384 |
+
update_top_tag = gr.update(value=top_description)
|
385 |
+
show_outputs = False
|
386 |
+
if os.path.exists("diffusers_model.tar"):
|
387 |
+
update_files_tag = gr.update(visible=show_outputs, value=["diffusers_model.tar"])
|
388 |
+
else:
|
389 |
+
update_files_tag = gr.update(visible=show_outputs)
|
390 |
+
return [
|
391 |
+
update_top_tag, #top_description
|
392 |
+
gr.update(visible=show_outputs), #try_your_model
|
393 |
+
gr.update(visible=show_outputs), #push_to_hub
|
394 |
+
update_files_tag, #result
|
395 |
+
gr.update(visible=show_outputs), #convert_button
|
396 |
+
]
|
397 |
+
|
398 |
+
def checkbox_swap(checkbox):
|
399 |
+
return [gr.update(visible=checkbox), gr.update(visible=checkbox), gr.update(visible=checkbox), gr.update(visible=checkbox)]
|
400 |
+
|
401 |
+
with gr.Blocks(css=css) as demo:
|
402 |
+
with gr.Box():
|
403 |
+
if is_shared_ui:
|
404 |
+
top_description = gr.HTML(f'''
|
405 |
+
<div class="gr-prose" style="max-width: 80%">
|
406 |
+
<h2>Attention - This Space doesn't work in this shared UI</h2>
|
407 |
+
<p>For it to work, you can either run locally or duplicate the Space and run it on your own profile using a (paid) private T4 GPU for training. As each T4 costs US$0.60/h, it should cost < US$1 to train most models using default settings! <a class="duplicate-button" style="display:inline-block" target="_blank" href="https://huggingface.co/spaces/MirageML/dreambooth?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a></p>
|
408 |
+
<img class="instruction" src="file/duplicate.png">
|
409 |
+
<img class="arrow" src="file/arrow.png" />
|
410 |
+
</div>
|
411 |
+
''')
|
412 |
+
elif(is_spaces):
|
413 |
+
if(is_gpu_associated):
|
414 |
+
top_description = gr.HTML(f'''
|
415 |
+
<div style="text-align: center; max-width: 650px; margin: 0 auto;">
|
416 |
+
<div>
|
417 |
+
<img class="logo" src="file/mirage.png" alt="Mirage Logo"
|
418 |
+
style="margin: auto; max-width: 7rem;">
|
419 |
+
<br />
|
420 |
+
<h1 style="font-weight: 900; font-size: 2.5rem;">
|
421 |
+
Dreambooth Web UI
|
422 |
+
</h1>
|
423 |
+
<br />
|
424 |
+
<a class="duplicate-button" style="display:inline-block" target="_blank" href="https://huggingface.co/spaces/MirageML/dreambooth?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a>
|
425 |
+
</div>
|
426 |
+
<br />
|
427 |
+
<br />
|
428 |
+
<p style="margin-bottom: 10px; font-size: 94%">
|
429 |
+
Customize Stable Diffusion v1 or v2 by giving it a few examples of a concept.
|
430 |
+
Based on the <a href="https://github.com/huggingface/diffusers">diffusers</a> implementation, additional techniques from <a href="https://github.com/TheLastBen/diffusers">TheLastBen</a> and <a href="https://github.com/ShivamShrirao/diffusers">ShivamShrirao</a>"
|
431 |
+
</p>
|
432 |
+
<br />
|
433 |
+
<p>There's only one step left before you can train your model: <a href="https://huggingface.co/spaces/{os.environ['SPACE_ID']}/settings" style="text-decoration: underline" target="_blank">attribute a <b>T4 GPU</b> to it (via the Settings tab)</a> and run the training below. Other GPUs are not compatible for now. You will be billed by the minute from when you activate the GPU until when it is turned it off.</p>
|
434 |
+
</div>
|
435 |
+
''')
|
436 |
+
else:
|
437 |
+
top_description = gr.HTML(f'''
|
438 |
+
<div style="text-align: center; max-width: 650px; margin: 0 auto;">
|
439 |
+
<div>
|
440 |
+
<img class="logo" src="file/mirage.png" alt="Mirage Logo"
|
441 |
+
style="margin: auto; max-width: 7rem;">
|
442 |
+
<br />
|
443 |
+
<h1 style="font-weight: 900; font-size: 2.5rem;">
|
444 |
+
Dreambooth Web UI
|
445 |
+
</h1>
|
446 |
+
<br />
|
447 |
+
<a class="duplicate-button" style="display:inline-block" target="_blank" href="https://huggingface.co/spaces/MirageML/dreambooth?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a>
|
448 |
+
</div>
|
449 |
+
<br />
|
450 |
+
<br />
|
451 |
+
<p style="margin-bottom: 10px; font-size: 94%">
|
452 |
+
Customize Stable Diffusion v1 or v2 by giving it a few examples of a concept.
|
453 |
+
Based on the <a href="https://github.com/huggingface/diffusers">diffusers</a> implementation, additional techniques from <a href="https://github.com/TheLastBen/diffusers">TheLastBen</a> and <a href="https://github.com/ShivamShrirao/diffusers">ShivamShrirao</a>"
|
454 |
+
</p>
|
455 |
+
<br />
|
456 |
+
<p>There's only one step left before you can train your model: <a href="https://huggingface.co/spaces/{os.environ['SPACE_ID']}/settings" style="text-decoration: underline" target="_blank">attribute a <b>T4 GPU</b> to it (via the Settings tab)</a> and run the training below. Other GPUs are not compatible for now. You will be billed by the minute from when you activate the GPU until when it is turned it off.</p>
|
457 |
+
</div>
|
458 |
+
''')
|
459 |
+
else:
|
460 |
+
top_description = gr.HTML(f'''
|
461 |
+
<div style="text-align: center; max-width: 650px; margin: 0 auto;">
|
462 |
+
<div>
|
463 |
+
<img class="logo" src="file/mirage.png" alt="Mirage Logo"
|
464 |
+
style="margin: auto; max-width: 7rem;">
|
465 |
+
<br />
|
466 |
+
<h1 style="font-weight: 900; font-size: 2.5rem;">
|
467 |
+
Dreambooth Web UI
|
468 |
+
</h1>
|
469 |
+
<br />
|
470 |
+
<a class="duplicate-button" style="display:inline-block" target="_blank" href="https://huggingface.co/spaces/MirageML/dreambooth?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a>
|
471 |
+
</div>
|
472 |
+
<br />
|
473 |
+
<br />
|
474 |
+
<p style="margin-bottom: 10px; font-size: 94%">
|
475 |
+
Customize Stable Diffusion v1 or v2 by giving it a few examples of a concept.
|
476 |
+
Based on the <a href="https://github.com/huggingface/diffusers">diffusers</a> implementation, additional techniques from <a href="https://github.com/TheLastBen/diffusers">TheLastBen</a> and <a href="https://github.com/ShivamShrirao/diffusers">ShivamShrirao</a>"
|
477 |
+
</p>
|
478 |
+
</div>
|
479 |
+
''')
|
480 |
+
|
481 |
+
#Very hacky approach to emulate dynamically created Gradio components
|
482 |
+
with gr.Column() as upload_your_concept:
|
483 |
+
with gr.Column():
|
484 |
+
thing_description = gr.Markdown("You are going to train an object or style, please upload 10-20 images of the object you are planning on training on from different angles/perspectives. You must have the right to do so and you are liable for the images you use, example")
|
485 |
+
thing_experimental = gr.Checkbox(label="Improve faces (prior preservation) - can take longer training but can improve faces", visible=False, value=False)
|
486 |
+
thing_image_example = gr.HTML('''<div style="display:flex;justify-content:center"><img src="file/cat-toy.png" /></div>''')
|
487 |
+
things_naming = gr.Markdown("You should name your concept with a unique made up word that has low chance of the model already knowing it (e.g.: `fantasy_world` here). Images will be automatically cropped to 512x512.")
|
488 |
+
|
489 |
+
|
490 |
+
file_collection = []
|
491 |
+
concept_collection = []
|
492 |
+
buttons_collection = []
|
493 |
+
delete_collection = []
|
494 |
+
is_visible = []
|
495 |
+
|
496 |
+
row = [None] * maximum_concepts
|
497 |
+
for x in range(maximum_concepts):
|
498 |
+
ordinal = lambda n: "%d%s" % (n, "tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10::4])
|
499 |
+
if(x == 0):
|
500 |
+
visible = True
|
501 |
+
is_visible.append(gr.State(value=True))
|
502 |
+
else:
|
503 |
+
visible = False
|
504 |
+
is_visible.append(gr.State(value=False))
|
505 |
+
|
506 |
+
file_collection.append(gr.File(label=f'''Upload the images for your {ordinal(x+1) if (x>0) else ""} concept''', file_count="multiple", interactive=True, visible=visible))
|
507 |
+
with gr.Column(visible=visible) as row[x]:
|
508 |
+
concept_collection.append(gr.Textbox(label=f'''{ordinal(x+1) if (x>0) else ""} concept prompt - use a unique, made up word to avoid collisions'''))
|
509 |
+
# with gr.Row():
|
510 |
+
# if(x < maximum_concepts-1):
|
511 |
+
# buttons_collection.append(gr.Button(value="Add +1 concept", visible=visible))
|
512 |
+
# if(x > 0):
|
513 |
+
# delete_collection.append(gr.Button(value=f"Delete {ordinal(x+1)} concept"))
|
514 |
+
|
515 |
+
counter_add = 1
|
516 |
+
for button in buttons_collection:
|
517 |
+
if(counter_add < len(buttons_collection)):
|
518 |
+
button.click(lambda:
|
519 |
+
[gr.update(visible=True),gr.update(visible=True), gr.update(visible=False), gr.update(visible=True), True, None],
|
520 |
+
None,
|
521 |
+
[row[counter_add], file_collection[counter_add], buttons_collection[counter_add-1], buttons_collection[counter_add], is_visible[counter_add], file_collection[counter_add]], queue=False)
|
522 |
+
else:
|
523 |
+
button.click(lambda:[gr.update(visible=True),gr.update(visible=True), gr.update(visible=False), True], None, [row[counter_add], file_collection[counter_add], buttons_collection[counter_add-1], is_visible[counter_add]], queue=False)
|
524 |
+
counter_add += 1
|
525 |
+
|
526 |
+
counter_delete = 1
|
527 |
+
for delete_button in delete_collection:
|
528 |
+
if(counter_delete < len(delete_collection)+1):
|
529 |
+
delete_button.click(lambda:[gr.update(visible=False),gr.update(visible=False), gr.update(visible=True), False], None, [file_collection[counter_delete], row[counter_delete], buttons_collection[counter_delete-1], is_visible[counter_delete]], queue=False)
|
530 |
+
counter_delete += 1
|
531 |
+
|
532 |
+
|
533 |
+
with gr.Accordion("Custom Settings", open=False):
|
534 |
+
with gr.Row() as what_are_you_training:
|
535 |
+
base_model_to_use = gr.Dropdown(label="Which base model would you like to use?", choices=["v1-5", "v2-512", "v2-768"], value="v1-5", interactive=True)
|
536 |
+
|
537 |
+
swap_auto_calculated = gr.Checkbox(label="Use custom settings")
|
538 |
+
gr.Markdown("If not checked, the % of frozen encoder will be tuned automatically to whether you are training an `object`, `person` or `style`. The text-encoder is frozen after 10% of the steps for a style, 30% of the steps for an object and 75% trained for persons. The number of steps varies between 1400 and 2400 depending on how many images uploaded. If you see too many artifacts in your output, it means it may have overfit and you need less steps. If your results aren't really what you wanted, it may be underfitting and you need more steps.")
|
539 |
+
steps = gr.Number(label="How many steps", value=2400)
|
540 |
+
perc_txt_encoder = gr.Number(label="Percentage of the training steps the text-encoder should be trained as well", value=30)
|
541 |
+
|
542 |
+
with gr.Box(visible=False) as training_summary:
|
543 |
+
training_summary_text = gr.HTML("", visible=True, label="Training Summary")
|
544 |
+
is_advanced_visible = True if is_spaces else False
|
545 |
+
training_summary_checkbox = gr.Checkbox(label="Automatically remove paid GPU attribution and upload model to the Hugging Face Hub after training", value=True, visible=is_advanced_visible)
|
546 |
+
training_summary_model_name = gr.Textbox(label="Name of your model", visible=True)
|
547 |
+
training_summary_where_to_upload = gr.Dropdown(["My personal profile", "Public Library"], value="My personal profile", label="Upload to", visible=True)
|
548 |
+
training_summary_token_message = gr.Markdown("[A Hugging Face write access token](https://huggingface.co/settings/tokens), go to \"New token\" -> Role : Write. A regular read token won't work here.", visible=True)
|
549 |
+
training_summary_token = gr.Textbox(label="Hugging Face Write Token", type="password", visible=True)
|
550 |
+
|
551 |
+
train_btn = gr.Button("Start Training")
|
552 |
+
if(is_shared_ui):
|
553 |
+
training_ongoing = gr.Markdown("## This Space only works in duplicated instances. Please duplicate it and try again!", visible=False)
|
554 |
+
elif(not is_gpu_associated):
|
555 |
+
training_ongoing = gr.Markdown("## Oops, you haven't associated your T4 GPU to this Space. Visit the Settings tab, associate and try again.", visible=False)
|
556 |
+
else:
|
557 |
+
training_ongoing = gr.Markdown("## Training is ongoing ⌛... You can close this tab if you like or just wait. If you did not check the `Remove GPU After training`, you can come back here to try your model and upload it after training. Don't forget to remove the GPU attribution after you are done. ", visible=False)
|
558 |
+
|
559 |
+
#Post-training UI
|
560 |
+
completed_training = gr.Markdown('''# ✅ Training completed.
|
561 |
+
### Don't forget to remove the GPU attribution after you are done trying and uploading your model''', visible=False)
|
562 |
+
|
563 |
+
with gr.Row():
|
564 |
+
with gr.Box(visible=False) as try_your_model:
|
565 |
+
gr.Markdown("## Try your model")
|
566 |
+
prompt = gr.Textbox(label="Type your prompt")
|
567 |
+
result_image = gr.Image()
|
568 |
+
inference_steps = gr.Slider(minimum=1, maximum=150, value=50, step=1)
|
569 |
+
generate_button = gr.Button("Generate Image")
|
570 |
+
|
571 |
+
with gr.Box(visible=False) as push_to_hub:
|
572 |
+
gr.Markdown("## Push to Hugging Face Hub")
|
573 |
+
model_name = gr.Textbox(label="Name of your model", placeholder="Tarsila do Amaral Style")
|
574 |
+
where_to_upload = gr.Dropdown(["My personal profile", "Public Library"], label="Upload to")
|
575 |
+
gr.Markdown("[A Hugging Face write access token](https://huggingface.co/settings/tokens), go to \"New token\" -> Role : Write. A regular read token won't work here.")
|
576 |
+
hf_token = gr.Textbox(label="Hugging Face Write Token", type="password")
|
577 |
+
|
578 |
+
push_button = gr.Button("Push to the Hub")
|
579 |
+
|
580 |
+
result = gr.File(label="Download the uploaded models in the diffusers format", visible=True)
|
581 |
+
success_message_upload = gr.Markdown(visible=False)
|
582 |
+
convert_button = gr.Button("Convert to CKPT", visible=False)
|
583 |
+
|
584 |
+
#Swap the examples and the % of text encoder trained depending if it is an object, person or style
|
585 |
+
|
586 |
+
#Swap the base model
|
587 |
+
base_model_to_use.change(fn=swap_base_model, inputs=base_model_to_use, outputs=[])
|
588 |
+
|
589 |
+
#Update the summary box below the UI according to how many images are uploaded and whether users are using custom settings or not
|
590 |
+
for file in file_collection:
|
591 |
+
#file.change(fn=update_steps,inputs=file_collection, outputs=steps)
|
592 |
+
file.change(fn=count_files, inputs=file_collection+[thing_experimental]+[base_model_to_use]+[steps]+[perc_txt_encoder]+[swap_auto_calculated], outputs=[training_summary, training_summary_text], queue=False)
|
593 |
+
|
594 |
+
thing_experimental.change(fn=count_files, inputs=file_collection+[thing_experimental]+[base_model_to_use]+[steps]+[perc_txt_encoder]+[swap_auto_calculated], outputs=[training_summary, training_summary_text], queue=False)
|
595 |
+
base_model_to_use.change(fn=count_files, inputs=file_collection+[thing_experimental]+[base_model_to_use]+[steps]+[perc_txt_encoder]+[swap_auto_calculated], outputs=[training_summary, training_summary_text], queue=False)
|
596 |
+
steps.change(fn=count_files, inputs=file_collection+[thing_experimental]+[base_model_to_use]+[steps]+[perc_txt_encoder]+[swap_auto_calculated], outputs=[training_summary, training_summary_text], queue=False)
|
597 |
+
perc_txt_encoder.change(fn=count_files, inputs=file_collection+[thing_experimental]+[base_model_to_use]+[steps]+[perc_txt_encoder]+[swap_auto_calculated], outputs=[training_summary, training_summary_text], queue=False)
|
598 |
+
|
599 |
+
#Give more options if the user wants to finish everything after training
|
600 |
+
if(is_spaces):
|
601 |
+
training_summary_checkbox.change(fn=checkbox_swap, inputs=training_summary_checkbox, outputs=[training_summary_token_message, training_summary_token, training_summary_model_name, training_summary_where_to_upload],queue=False, show_progress=False)
|
602 |
+
#Add a message for while it is in training
|
603 |
+
train_btn.click(lambda:gr.update(visible=True), inputs=None, outputs=training_ongoing)
|
604 |
+
|
605 |
+
#The main train function
|
606 |
+
train_btn.click(fn=train, inputs=is_visible+concept_collection+file_collection+[base_model_to_use]+[thing_experimental]+[training_summary_where_to_upload]+[training_summary_model_name]+[training_summary_checkbox]+[training_summary_token]+[steps]+[perc_txt_encoder]+[swap_auto_calculated], outputs=[result, try_your_model, push_to_hub, convert_button, training_ongoing, completed_training], queue=False)
|
607 |
+
|
608 |
+
#Button to generate an image from your trained model after training
|
609 |
+
generate_button.click(fn=generate, inputs=[prompt, inference_steps], outputs=result_image, queue=False)
|
610 |
+
#Button to push the model to the Hugging Face Hub
|
611 |
+
push_button.click(fn=push, inputs=[model_name, where_to_upload, hf_token, base_model_to_use], outputs=[success_message_upload, result], queue=False)
|
612 |
+
#Button to convert the model to ckpt format
|
613 |
+
convert_button.click(fn=convert_to_ckpt, inputs=[], outputs=result, queue=False)
|
614 |
+
|
615 |
+
#Checks if the training is running
|
616 |
+
demo.load(fn=check_status, inputs=top_description, outputs=[top_description, try_your_model, push_to_hub, result, convert_button], queue=False, show_progress=False)
|
617 |
+
|
618 |
+
demo.queue(default_enabled=False).launch(debug=True)
|
arrow.png
ADDED
![]() |
cat-toy.png
ADDED
![]() |
convertosd.py
ADDED
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Script for converting a HF Diffusers saved pipeline to a Stable Diffusion checkpoint.
|
2 |
+
# *Only* converts the UNet, VAE, and Text Encoder.
|
3 |
+
# Does not convert optimizer state or any other thing.
|
4 |
+
# Written by jachiam
|
5 |
+
|
6 |
+
import argparse
|
7 |
+
import os.path as osp
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import gc
|
11 |
+
|
12 |
+
# =================#
|
13 |
+
# UNet Conversion #
|
14 |
+
# =================#
|
15 |
+
|
16 |
+
unet_conversion_map = [
|
17 |
+
# (stable-diffusion, HF Diffusers)
|
18 |
+
("time_embed.0.weight", "time_embedding.linear_1.weight"),
|
19 |
+
("time_embed.0.bias", "time_embedding.linear_1.bias"),
|
20 |
+
("time_embed.2.weight", "time_embedding.linear_2.weight"),
|
21 |
+
("time_embed.2.bias", "time_embedding.linear_2.bias"),
|
22 |
+
("input_blocks.0.0.weight", "conv_in.weight"),
|
23 |
+
("input_blocks.0.0.bias", "conv_in.bias"),
|
24 |
+
("out.0.weight", "conv_norm_out.weight"),
|
25 |
+
("out.0.bias", "conv_norm_out.bias"),
|
26 |
+
("out.2.weight", "conv_out.weight"),
|
27 |
+
("out.2.bias", "conv_out.bias"),
|
28 |
+
]
|
29 |
+
|
30 |
+
unet_conversion_map_resnet = [
|
31 |
+
# (stable-diffusion, HF Diffusers)
|
32 |
+
("in_layers.0", "norm1"),
|
33 |
+
("in_layers.2", "conv1"),
|
34 |
+
("out_layers.0", "norm2"),
|
35 |
+
("out_layers.3", "conv2"),
|
36 |
+
("emb_layers.1", "time_emb_proj"),
|
37 |
+
("skip_connection", "conv_shortcut"),
|
38 |
+
]
|
39 |
+
|
40 |
+
unet_conversion_map_layer = []
|
41 |
+
# hardcoded number of downblocks and resnets/attentions...
|
42 |
+
# would need smarter logic for other networks.
|
43 |
+
for i in range(4):
|
44 |
+
# loop over downblocks/upblocks
|
45 |
+
|
46 |
+
for j in range(2):
|
47 |
+
# loop over resnets/attentions for downblocks
|
48 |
+
hf_down_res_prefix = f"down_blocks.{i}.resnets.{j}."
|
49 |
+
sd_down_res_prefix = f"input_blocks.{3*i + j + 1}.0."
|
50 |
+
unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))
|
51 |
+
|
52 |
+
if i < 3:
|
53 |
+
# no attention layers in down_blocks.3
|
54 |
+
hf_down_atn_prefix = f"down_blocks.{i}.attentions.{j}."
|
55 |
+
sd_down_atn_prefix = f"input_blocks.{3*i + j + 1}.1."
|
56 |
+
unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))
|
57 |
+
|
58 |
+
for j in range(3):
|
59 |
+
# loop over resnets/attentions for upblocks
|
60 |
+
hf_up_res_prefix = f"up_blocks.{i}.resnets.{j}."
|
61 |
+
sd_up_res_prefix = f"output_blocks.{3*i + j}.0."
|
62 |
+
unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))
|
63 |
+
|
64 |
+
if i > 0:
|
65 |
+
# no attention layers in up_blocks.0
|
66 |
+
hf_up_atn_prefix = f"up_blocks.{i}.attentions.{j}."
|
67 |
+
sd_up_atn_prefix = f"output_blocks.{3*i + j}.1."
|
68 |
+
unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))
|
69 |
+
|
70 |
+
if i < 3:
|
71 |
+
# no downsample in down_blocks.3
|
72 |
+
hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0.conv."
|
73 |
+
sd_downsample_prefix = f"input_blocks.{3*(i+1)}.0.op."
|
74 |
+
unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))
|
75 |
+
|
76 |
+
# no upsample in up_blocks.3
|
77 |
+
hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
|
78 |
+
sd_upsample_prefix = f"output_blocks.{3*i + 2}.{1 if i == 0 else 2}."
|
79 |
+
unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))
|
80 |
+
|
81 |
+
hf_mid_atn_prefix = "mid_block.attentions.0."
|
82 |
+
sd_mid_atn_prefix = "middle_block.1."
|
83 |
+
unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))
|
84 |
+
|
85 |
+
for j in range(2):
|
86 |
+
hf_mid_res_prefix = f"mid_block.resnets.{j}."
|
87 |
+
sd_mid_res_prefix = f"middle_block.{2*j}."
|
88 |
+
unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))
|
89 |
+
|
90 |
+
|
91 |
+
def convert_unet_state_dict(unet_state_dict):
|
92 |
+
# buyer beware: this is a *brittle* function,
|
93 |
+
# and correct output requires that all of these pieces interact in
|
94 |
+
# the exact order in which I have arranged them.
|
95 |
+
mapping = {k: k for k in unet_state_dict.keys()}
|
96 |
+
for sd_name, hf_name in unet_conversion_map:
|
97 |
+
mapping[hf_name] = sd_name
|
98 |
+
for k, v in mapping.items():
|
99 |
+
if "resnets" in k:
|
100 |
+
for sd_part, hf_part in unet_conversion_map_resnet:
|
101 |
+
v = v.replace(hf_part, sd_part)
|
102 |
+
mapping[k] = v
|
103 |
+
for k, v in mapping.items():
|
104 |
+
for sd_part, hf_part in unet_conversion_map_layer:
|
105 |
+
v = v.replace(hf_part, sd_part)
|
106 |
+
mapping[k] = v
|
107 |
+
new_state_dict = {v: unet_state_dict[k] for k, v in mapping.items()}
|
108 |
+
return new_state_dict
|
109 |
+
|
110 |
+
|
111 |
+
# ================#
|
112 |
+
# VAE Conversion #
|
113 |
+
# ================#
|
114 |
+
|
115 |
+
vae_conversion_map = [
|
116 |
+
# (stable-diffusion, HF Diffusers)
|
117 |
+
("nin_shortcut", "conv_shortcut"),
|
118 |
+
("norm_out", "conv_norm_out"),
|
119 |
+
("mid.attn_1.", "mid_block.attentions.0."),
|
120 |
+
]
|
121 |
+
|
122 |
+
for i in range(4):
|
123 |
+
# down_blocks have two resnets
|
124 |
+
for j in range(2):
|
125 |
+
hf_down_prefix = f"encoder.down_blocks.{i}.resnets.{j}."
|
126 |
+
sd_down_prefix = f"encoder.down.{i}.block.{j}."
|
127 |
+
vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
|
128 |
+
|
129 |
+
if i < 3:
|
130 |
+
hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0."
|
131 |
+
sd_downsample_prefix = f"down.{i}.downsample."
|
132 |
+
vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
|
133 |
+
|
134 |
+
hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
|
135 |
+
sd_upsample_prefix = f"up.{3-i}.upsample."
|
136 |
+
vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
|
137 |
+
|
138 |
+
# up_blocks have three resnets
|
139 |
+
# also, up blocks in hf are numbered in reverse from sd
|
140 |
+
for j in range(3):
|
141 |
+
hf_up_prefix = f"decoder.up_blocks.{i}.resnets.{j}."
|
142 |
+
sd_up_prefix = f"decoder.up.{3-i}.block.{j}."
|
143 |
+
vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
|
144 |
+
|
145 |
+
# this part accounts for mid blocks in both the encoder and the decoder
|
146 |
+
for i in range(2):
|
147 |
+
hf_mid_res_prefix = f"mid_block.resnets.{i}."
|
148 |
+
sd_mid_res_prefix = f"mid.block_{i+1}."
|
149 |
+
vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
|
150 |
+
|
151 |
+
|
152 |
+
vae_conversion_map_attn = [
|
153 |
+
# (stable-diffusion, HF Diffusers)
|
154 |
+
("norm.", "group_norm."),
|
155 |
+
("q.", "query."),
|
156 |
+
("k.", "key."),
|
157 |
+
("v.", "value."),
|
158 |
+
("proj_out.", "proj_attn."),
|
159 |
+
]
|
160 |
+
|
161 |
+
|
162 |
+
def reshape_weight_for_sd(w):
|
163 |
+
# convert HF linear weights to SD conv2d weights
|
164 |
+
return w.reshape(*w.shape, 1, 1)
|
165 |
+
|
166 |
+
|
167 |
+
def convert_vae_state_dict(vae_state_dict):
|
168 |
+
mapping = {k: k for k in vae_state_dict.keys()}
|
169 |
+
for k, v in mapping.items():
|
170 |
+
for sd_part, hf_part in vae_conversion_map:
|
171 |
+
v = v.replace(hf_part, sd_part)
|
172 |
+
mapping[k] = v
|
173 |
+
for k, v in mapping.items():
|
174 |
+
if "attentions" in k:
|
175 |
+
for sd_part, hf_part in vae_conversion_map_attn:
|
176 |
+
v = v.replace(hf_part, sd_part)
|
177 |
+
mapping[k] = v
|
178 |
+
new_state_dict = {v: vae_state_dict[k] for k, v in mapping.items()}
|
179 |
+
weights_to_convert = ["q", "k", "v", "proj_out"]
|
180 |
+
print("[1;32mConverting to CKPT ...")
|
181 |
+
for k, v in new_state_dict.items():
|
182 |
+
for weight_name in weights_to_convert:
|
183 |
+
if f"mid.attn_1.{weight_name}.weight" in k:
|
184 |
+
new_state_dict[k] = reshape_weight_for_sd(v)
|
185 |
+
return new_state_dict
|
186 |
+
|
187 |
+
|
188 |
+
# =========================#
|
189 |
+
# Text Encoder Conversion #
|
190 |
+
# =========================#
|
191 |
+
# pretty much a no-op
|
192 |
+
|
193 |
+
|
194 |
+
def convert_text_enc_state_dict(text_enc_dict):
|
195 |
+
return text_enc_dict
|
196 |
+
|
197 |
+
|
198 |
+
def convert(model_path, checkpoint_path):
|
199 |
+
unet_path = osp.join(model_path, "unet", "diffusion_pytorch_model.bin")
|
200 |
+
vae_path = osp.join(model_path, "vae", "diffusion_pytorch_model.bin")
|
201 |
+
text_enc_path = osp.join(model_path, "text_encoder", "pytorch_model.bin")
|
202 |
+
|
203 |
+
# Convert the UNet model
|
204 |
+
unet_state_dict = torch.load(unet_path, map_location='cpu')
|
205 |
+
unet_state_dict = convert_unet_state_dict(unet_state_dict)
|
206 |
+
unet_state_dict = {"model.diffusion_model." + k: v for k, v in unet_state_dict.items()}
|
207 |
+
|
208 |
+
# Convert the VAE model
|
209 |
+
vae_state_dict = torch.load(vae_path, map_location='cpu')
|
210 |
+
vae_state_dict = convert_vae_state_dict(vae_state_dict)
|
211 |
+
vae_state_dict = {"first_stage_model." + k: v for k, v in vae_state_dict.items()}
|
212 |
+
|
213 |
+
# Convert the text encoder model
|
214 |
+
text_enc_dict = torch.load(text_enc_path, map_location='cpu')
|
215 |
+
text_enc_dict = convert_text_enc_state_dict(text_enc_dict)
|
216 |
+
text_enc_dict = {"cond_stage_model.transformer." + k: v for k, v in text_enc_dict.items()}
|
217 |
+
|
218 |
+
# Put together new checkpoint
|
219 |
+
state_dict = {**unet_state_dict, **vae_state_dict, **text_enc_dict}
|
220 |
+
|
221 |
+
state_dict = {k:v.half() for k,v in state_dict.items()}
|
222 |
+
state_dict = {"state_dict": state_dict}
|
223 |
+
torch.save(state_dict, checkpoint_path)
|
224 |
+
del state_dict, text_enc_dict, vae_state_dict, unet_state_dict
|
225 |
+
torch.cuda.empty_cache()
|
226 |
+
gc.collect()
|
duplicate.png
ADDED
![]() |
mirage.png
ADDED
![]() |
mix.zip
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:09207c4e95fcf5296eb0ff708fdc672da960aeb2864d298810db5094b072a0d4
|
3 |
+
size 28022653
|
model_index.json
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_class_name": "StableDiffusionPipeline",
|
3 |
+
"_diffusers_version": "0.6.0",
|
4 |
+
"feature_extractor": [
|
5 |
+
"transformers",
|
6 |
+
"CLIPFeatureExtractor"
|
7 |
+
],
|
8 |
+
"safety_checker": [
|
9 |
+
"stable_diffusion",
|
10 |
+
"StableDiffusionSafetyChecker"
|
11 |
+
],
|
12 |
+
"scheduler": [
|
13 |
+
"diffusers",
|
14 |
+
"PNDMScheduler"
|
15 |
+
],
|
16 |
+
"text_encoder": [
|
17 |
+
"transformers",
|
18 |
+
"CLIPTextModel"
|
19 |
+
],
|
20 |
+
"tokenizer": [
|
21 |
+
"transformers",
|
22 |
+
"CLIPTokenizer"
|
23 |
+
],
|
24 |
+
"unet": [
|
25 |
+
"diffusers",
|
26 |
+
"UNet2DConditionModel"
|
27 |
+
],
|
28 |
+
"vae": [
|
29 |
+
"diffusers",
|
30 |
+
"AutoencoderKL"
|
31 |
+
]
|
32 |
+
}
|
person.png
ADDED
![]() |
requirements-local.txt
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
--extra-index-url https://download.pytorch.org/whl/cu113
|
2 |
+
torch==1.12.1+cu113
|
3 |
+
torchvision==0.13.1+cu113
|
4 |
+
diffusers==0.9.0
|
5 |
+
accelerate==0.12.0
|
6 |
+
OmegaConf
|
7 |
+
wget
|
8 |
+
pytorch_lightning
|
9 |
+
huggingface_hub
|
10 |
+
ftfy
|
11 |
+
transformers
|
12 |
+
pyfiglet
|
13 |
+
triton==2.0.0.dev20220701
|
14 |
+
bitsandbytes
|
15 |
+
python-slugify
|
16 |
+
requests
|
17 |
+
tensorboard
|
18 |
+
pip install git+https://github.com/facebookresearch/xformers@7e4c02c#egg=xformers
|
requirements.txt
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
--extra-index-url https://download.pytorch.org/whl/cu113
|
2 |
+
torch==1.12.1+cu113
|
3 |
+
torchvision==0.13.1+cu113
|
4 |
+
git+https://github.com/huggingface/diffusers.git
|
5 |
+
accelerate==0.12.0
|
6 |
+
OmegaConf
|
7 |
+
wget
|
8 |
+
pytorch_lightning
|
9 |
+
huggingface_hub
|
10 |
+
ftfy
|
11 |
+
transformers
|
12 |
+
pyfiglet
|
13 |
+
triton==2.0.0.dev20220701
|
14 |
+
bitsandbytes
|
15 |
+
python-slugify
|
16 |
+
requests
|
17 |
+
tensorboard
|
18 |
+
https://github.com/apolinario/xformers/releases/download/0.0.2/xformers-0.0.14.dev0-cp38-cp38-linux_x86_64.whl
|
train_dreambooth.py
ADDED
@@ -0,0 +1,881 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import itertools
|
3 |
+
import math
|
4 |
+
import os
|
5 |
+
from pathlib import Path
|
6 |
+
from typing import Optional
|
7 |
+
import subprocess
|
8 |
+
import sys
|
9 |
+
import gc
|
10 |
+
import random
|
11 |
+
|
12 |
+
import torch
|
13 |
+
import torch.nn.functional as F
|
14 |
+
import torch.utils.checkpoint
|
15 |
+
from torch.utils.data import Dataset
|
16 |
+
|
17 |
+
from accelerate import Accelerator
|
18 |
+
from accelerate.logging import get_logger
|
19 |
+
from accelerate.utils import set_seed
|
20 |
+
from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionPipeline, UNet2DConditionModel
|
21 |
+
from diffusers.optimization import get_scheduler
|
22 |
+
from huggingface_hub import HfFolder, Repository, whoami
|
23 |
+
from PIL import Image
|
24 |
+
from torchvision import transforms
|
25 |
+
from tqdm.auto import tqdm
|
26 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
27 |
+
|
28 |
+
|
29 |
+
logger = get_logger(__name__)
|
30 |
+
|
31 |
+
|
32 |
+
def parse_args():
|
33 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
34 |
+
parser.add_argument(
|
35 |
+
"--pretrained_model_name_or_path",
|
36 |
+
type=str,
|
37 |
+
default=None,
|
38 |
+
#required=True,
|
39 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
40 |
+
)
|
41 |
+
parser.add_argument(
|
42 |
+
"--tokenizer_name",
|
43 |
+
type=str,
|
44 |
+
default=None,
|
45 |
+
help="Pretrained tokenizer name or path if not the same as model_name",
|
46 |
+
)
|
47 |
+
parser.add_argument(
|
48 |
+
"--instance_data_dir",
|
49 |
+
type=str,
|
50 |
+
default=None,
|
51 |
+
#required=True,
|
52 |
+
help="A folder containing the training data of instance images.",
|
53 |
+
)
|
54 |
+
parser.add_argument(
|
55 |
+
"--class_data_dir",
|
56 |
+
type=str,
|
57 |
+
default=None,
|
58 |
+
#required=False,
|
59 |
+
help="A folder containing the training data of class images.",
|
60 |
+
)
|
61 |
+
parser.add_argument(
|
62 |
+
"--instance_prompt",
|
63 |
+
type=str,
|
64 |
+
default=None,
|
65 |
+
help="The prompt with identifier specifying the instance",
|
66 |
+
)
|
67 |
+
parser.add_argument(
|
68 |
+
"--class_prompt",
|
69 |
+
type=str,
|
70 |
+
default="",
|
71 |
+
help="The prompt to specify images in the same class as provided instance images.",
|
72 |
+
)
|
73 |
+
parser.add_argument(
|
74 |
+
"--with_prior_preservation",
|
75 |
+
default=False,
|
76 |
+
action="store_true",
|
77 |
+
help="Flag to add prior preservation loss.",
|
78 |
+
)
|
79 |
+
parser.add_argument("--prior_loss_weight", type=float, default=1.0, help="The weight of prior preservation loss.")
|
80 |
+
parser.add_argument(
|
81 |
+
"--num_class_images",
|
82 |
+
type=int,
|
83 |
+
default=100,
|
84 |
+
help=(
|
85 |
+
"Minimal class images for prior preservation loss. If not have enough images, additional images will be"
|
86 |
+
" sampled with class_prompt."
|
87 |
+
),
|
88 |
+
)
|
89 |
+
parser.add_argument(
|
90 |
+
"--output_dir",
|
91 |
+
type=str,
|
92 |
+
default="",
|
93 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
94 |
+
)
|
95 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
96 |
+
parser.add_argument(
|
97 |
+
"--resolution",
|
98 |
+
type=int,
|
99 |
+
default=512,
|
100 |
+
help=(
|
101 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
102 |
+
" resolution"
|
103 |
+
),
|
104 |
+
)
|
105 |
+
parser.add_argument(
|
106 |
+
"--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution"
|
107 |
+
)
|
108 |
+
parser.add_argument("--train_text_encoder", action="store_true", help="Whether to train the text encoder")
|
109 |
+
parser.add_argument(
|
110 |
+
"--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
|
111 |
+
)
|
112 |
+
parser.add_argument(
|
113 |
+
"--sample_batch_size", type=int, default=4, help="Batch size (per device) for sampling images."
|
114 |
+
)
|
115 |
+
parser.add_argument("--num_train_epochs", type=int, default=1)
|
116 |
+
parser.add_argument(
|
117 |
+
"--max_train_steps",
|
118 |
+
type=int,
|
119 |
+
default=None,
|
120 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
121 |
+
)
|
122 |
+
parser.add_argument(
|
123 |
+
"--gradient_accumulation_steps",
|
124 |
+
type=int,
|
125 |
+
default=1,
|
126 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
127 |
+
)
|
128 |
+
parser.add_argument(
|
129 |
+
"--gradient_checkpointing",
|
130 |
+
action="store_true",
|
131 |
+
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
|
132 |
+
)
|
133 |
+
parser.add_argument(
|
134 |
+
"--learning_rate",
|
135 |
+
type=float,
|
136 |
+
default=5e-6,
|
137 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
138 |
+
)
|
139 |
+
parser.add_argument(
|
140 |
+
"--scale_lr",
|
141 |
+
action="store_true",
|
142 |
+
default=False,
|
143 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
144 |
+
)
|
145 |
+
parser.add_argument(
|
146 |
+
"--lr_scheduler",
|
147 |
+
type=str,
|
148 |
+
default="constant",
|
149 |
+
help=(
|
150 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
151 |
+
' "constant", "constant_with_warmup"]'
|
152 |
+
),
|
153 |
+
)
|
154 |
+
parser.add_argument(
|
155 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
156 |
+
)
|
157 |
+
parser.add_argument(
|
158 |
+
"--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
|
159 |
+
)
|
160 |
+
parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
161 |
+
parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
|
162 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
163 |
+
parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
|
164 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
165 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
166 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
167 |
+
parser.add_argument(
|
168 |
+
"--hub_model_id",
|
169 |
+
type=str,
|
170 |
+
default=None,
|
171 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
172 |
+
)
|
173 |
+
parser.add_argument(
|
174 |
+
"--logging_dir",
|
175 |
+
type=str,
|
176 |
+
default="logs",
|
177 |
+
help=(
|
178 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
179 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
180 |
+
),
|
181 |
+
)
|
182 |
+
parser.add_argument(
|
183 |
+
"--mixed_precision",
|
184 |
+
type=str,
|
185 |
+
default="no",
|
186 |
+
choices=["no", "fp16", "bf16"],
|
187 |
+
help=(
|
188 |
+
"Whether to use mixed precision. Choose"
|
189 |
+
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
|
190 |
+
"and an Nvidia Ampere GPU."
|
191 |
+
),
|
192 |
+
)
|
193 |
+
|
194 |
+
parser.add_argument(
|
195 |
+
"--save_n_steps",
|
196 |
+
type=int,
|
197 |
+
default=1,
|
198 |
+
help=("Save the model every n global_steps"),
|
199 |
+
)
|
200 |
+
|
201 |
+
|
202 |
+
parser.add_argument(
|
203 |
+
"--save_starting_step",
|
204 |
+
type=int,
|
205 |
+
default=1,
|
206 |
+
help=("The step from which it starts saving intermediary checkpoints"),
|
207 |
+
)
|
208 |
+
|
209 |
+
parser.add_argument(
|
210 |
+
"--stop_text_encoder_training",
|
211 |
+
type=int,
|
212 |
+
default=1000000,
|
213 |
+
help=("The step at which the text_encoder is no longer trained"),
|
214 |
+
)
|
215 |
+
|
216 |
+
|
217 |
+
parser.add_argument(
|
218 |
+
"--image_captions_filename",
|
219 |
+
action="store_true",
|
220 |
+
help="Get captions from filename",
|
221 |
+
)
|
222 |
+
|
223 |
+
|
224 |
+
parser.add_argument(
|
225 |
+
"--dump_only_text_encoder",
|
226 |
+
action="store_true",
|
227 |
+
default=False,
|
228 |
+
help="Dump only text encoder",
|
229 |
+
)
|
230 |
+
|
231 |
+
parser.add_argument(
|
232 |
+
"--train_only_unet",
|
233 |
+
action="store_true",
|
234 |
+
default=False,
|
235 |
+
help="Train only the unet",
|
236 |
+
)
|
237 |
+
|
238 |
+
parser.add_argument(
|
239 |
+
"--cache_latents",
|
240 |
+
action="store_true",
|
241 |
+
default=False,
|
242 |
+
help="Train only the unet",
|
243 |
+
)
|
244 |
+
|
245 |
+
parser.add_argument(
|
246 |
+
"--Session_dir",
|
247 |
+
type=str,
|
248 |
+
default="",
|
249 |
+
help="Current session directory",
|
250 |
+
)
|
251 |
+
|
252 |
+
|
253 |
+
|
254 |
+
|
255 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
256 |
+
|
257 |
+
args = parser.parse_args()
|
258 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
259 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
260 |
+
args.local_rank = env_local_rank
|
261 |
+
|
262 |
+
#if args.instance_data_dir is None:
|
263 |
+
# raise ValueError("You must specify a train data directory.")
|
264 |
+
|
265 |
+
#if args.with_prior_preservation:
|
266 |
+
# if args.class_data_dir is None:
|
267 |
+
# raise ValueError("You must specify a data directory for class images.")
|
268 |
+
# if args.class_prompt is None:
|
269 |
+
# raise ValueError("You must specify prompt for class images.")
|
270 |
+
|
271 |
+
return args
|
272 |
+
|
273 |
+
|
274 |
+
class DreamBoothDataset(Dataset):
|
275 |
+
"""
|
276 |
+
A dataset to prepare the instance and class images with the prompts for fine-tuning the model.
|
277 |
+
It pre-processes the images and the tokenizes prompts.
|
278 |
+
"""
|
279 |
+
|
280 |
+
def __init__(
|
281 |
+
self,
|
282 |
+
instance_data_root,
|
283 |
+
instance_prompt,
|
284 |
+
tokenizer,
|
285 |
+
args,
|
286 |
+
class_data_root=None,
|
287 |
+
class_prompt=None,
|
288 |
+
size=512,
|
289 |
+
center_crop=False,
|
290 |
+
):
|
291 |
+
self.size = size
|
292 |
+
self.center_crop = center_crop
|
293 |
+
self.tokenizer = tokenizer
|
294 |
+
self.image_captions_filename = None
|
295 |
+
|
296 |
+
self.instance_data_root = Path(instance_data_root)
|
297 |
+
if not self.instance_data_root.exists():
|
298 |
+
raise ValueError("Instance images root doesn't exists.")
|
299 |
+
|
300 |
+
self.instance_images_path = list(Path(instance_data_root).iterdir())
|
301 |
+
self.num_instance_images = len(self.instance_images_path)
|
302 |
+
self.instance_prompt = instance_prompt
|
303 |
+
self._length = self.num_instance_images
|
304 |
+
|
305 |
+
if args.image_captions_filename:
|
306 |
+
self.image_captions_filename = True
|
307 |
+
|
308 |
+
if class_data_root is not None:
|
309 |
+
self.class_data_root = Path(class_data_root)
|
310 |
+
self.class_data_root.mkdir(parents=True, exist_ok=True)
|
311 |
+
self.class_images_path = list(self.class_data_root.iterdir())
|
312 |
+
random.shuffle(self.class_images_path)
|
313 |
+
self.num_class_images = len(self.class_images_path)
|
314 |
+
self._length = max(self.num_class_images, self.num_instance_images)
|
315 |
+
self.class_prompt = class_prompt
|
316 |
+
else:
|
317 |
+
self.class_data_root = None
|
318 |
+
|
319 |
+
self.image_transforms = transforms.Compose(
|
320 |
+
[
|
321 |
+
transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR),
|
322 |
+
transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size),
|
323 |
+
transforms.ToTensor(),
|
324 |
+
transforms.Normalize([0.5], [0.5]),
|
325 |
+
]
|
326 |
+
)
|
327 |
+
|
328 |
+
def __len__(self):
|
329 |
+
return self._length
|
330 |
+
|
331 |
+
def __getitem__(self, index):
|
332 |
+
example = {}
|
333 |
+
path = self.instance_images_path[index % self.num_instance_images]
|
334 |
+
instance_image = Image.open(path)
|
335 |
+
if not instance_image.mode == "RGB":
|
336 |
+
instance_image = instance_image.convert("RGB")
|
337 |
+
|
338 |
+
instance_prompt = self.instance_prompt
|
339 |
+
|
340 |
+
if self.image_captions_filename:
|
341 |
+
filename = Path(path).stem
|
342 |
+
pt=''.join([i for i in filename if not i.isdigit()])
|
343 |
+
pt=pt.replace("_"," ")
|
344 |
+
pt=pt.replace("(","")
|
345 |
+
pt=pt.replace(")","")
|
346 |
+
pt=pt.replace("-","")
|
347 |
+
instance_prompt = pt
|
348 |
+
sys.stdout.write(" [0;32m" +instance_prompt+" [0m")
|
349 |
+
sys.stdout.flush()
|
350 |
+
|
351 |
+
|
352 |
+
example["instance_images"] = self.image_transforms(instance_image)
|
353 |
+
example["instance_prompt_ids"] = self.tokenizer(
|
354 |
+
instance_prompt,
|
355 |
+
padding="do_not_pad",
|
356 |
+
truncation=True,
|
357 |
+
max_length=self.tokenizer.model_max_length,
|
358 |
+
).input_ids
|
359 |
+
|
360 |
+
if self.class_data_root:
|
361 |
+
class_image = Image.open(self.class_images_path[index % self.num_class_images])
|
362 |
+
if not class_image.mode == "RGB":
|
363 |
+
class_image = class_image.convert("RGB")
|
364 |
+
example["class_images"] = self.image_transforms(class_image)
|
365 |
+
example["class_prompt_ids"] = self.tokenizer(
|
366 |
+
self.class_prompt,
|
367 |
+
padding="do_not_pad",
|
368 |
+
truncation=True,
|
369 |
+
max_length=self.tokenizer.model_max_length,
|
370 |
+
).input_ids
|
371 |
+
|
372 |
+
return example
|
373 |
+
|
374 |
+
|
375 |
+
|
376 |
+
class PromptDataset(Dataset):
|
377 |
+
"A simple dataset to prepare the prompts to generate class images on multiple GPUs."
|
378 |
+
|
379 |
+
def __init__(self, prompt, num_samples):
|
380 |
+
self.prompt = prompt
|
381 |
+
self.num_samples = num_samples
|
382 |
+
|
383 |
+
def __len__(self):
|
384 |
+
return self.num_samples
|
385 |
+
|
386 |
+
def __getitem__(self, index):
|
387 |
+
example = {}
|
388 |
+
example["prompt"] = self.prompt
|
389 |
+
example["index"] = index
|
390 |
+
return example
|
391 |
+
|
392 |
+
class LatentsDataset(Dataset):
|
393 |
+
def __init__(self, latents_cache, text_encoder_cache):
|
394 |
+
self.latents_cache = latents_cache
|
395 |
+
self.text_encoder_cache = text_encoder_cache
|
396 |
+
|
397 |
+
def __len__(self):
|
398 |
+
return len(self.latents_cache)
|
399 |
+
|
400 |
+
def __getitem__(self, index):
|
401 |
+
return self.latents_cache[index], self.text_encoder_cache[index]
|
402 |
+
|
403 |
+
def get_full_repo_name(model_id: str, organization: Optional[str] = None, token: Optional[str] = None):
|
404 |
+
if token is None:
|
405 |
+
token = HfFolder.get_token()
|
406 |
+
if organization is None:
|
407 |
+
username = whoami(token)["name"]
|
408 |
+
return f"{username}/{model_id}"
|
409 |
+
else:
|
410 |
+
return f"{organization}/{model_id}"
|
411 |
+
|
412 |
+
def merge_two_dicts(starting_dict: dict, updater_dict: dict) -> dict:
|
413 |
+
"""
|
414 |
+
Starts from base starting dict and then adds the remaining key values from updater replacing the values from
|
415 |
+
the first starting/base dict with the second updater dict.
|
416 |
+
|
417 |
+
For later: how does d = {**d1, **d2} replace collision?
|
418 |
+
|
419 |
+
:param starting_dict:
|
420 |
+
:param updater_dict:
|
421 |
+
:return:
|
422 |
+
"""
|
423 |
+
new_dict: dict = starting_dict.copy() # start with keys and values of starting_dict
|
424 |
+
new_dict.update(updater_dict) # modifies starting_dict with keys and values of updater_dict
|
425 |
+
return new_dict
|
426 |
+
|
427 |
+
def merge_args(args1: argparse.Namespace, args2: argparse.Namespace) -> argparse.Namespace:
|
428 |
+
"""
|
429 |
+
|
430 |
+
ref: https://stackoverflow.com/questions/56136549/how-can-i-merge-two-argparse-namespaces-in-python-2-x
|
431 |
+
:param args1:
|
432 |
+
:param args2:
|
433 |
+
:return:
|
434 |
+
"""
|
435 |
+
# - the merged args
|
436 |
+
# The vars() function returns the __dict__ attribute to values of the given object e.g {field:value}.
|
437 |
+
merged_key_values_for_namespace: dict = merge_two_dicts(vars(args1), vars(args2))
|
438 |
+
args = argparse.Namespace(**merged_key_values_for_namespace)
|
439 |
+
return args
|
440 |
+
|
441 |
+
def run_training(args_imported):
|
442 |
+
args_default = parse_args()
|
443 |
+
args = merge_args(args_default, args_imported)
|
444 |
+
print(args)
|
445 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
446 |
+
i=args.save_starting_step
|
447 |
+
accelerator = Accelerator(
|
448 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
449 |
+
mixed_precision=args.mixed_precision,
|
450 |
+
log_with="tensorboard",
|
451 |
+
logging_dir=logging_dir,
|
452 |
+
)
|
453 |
+
|
454 |
+
# Currently, it's not possible to do gradient accumulation when training two models with accelerate.accumulate
|
455 |
+
# This will be enabled soon in accelerate. For now, we don't allow gradient accumulation when training two models.
|
456 |
+
# TODO (patil-suraj): Remove this check when gradient accumulation with two models is enabled in accelerate.
|
457 |
+
if args.train_text_encoder and args.gradient_accumulation_steps > 1 and accelerator.num_processes > 1:
|
458 |
+
raise ValueError(
|
459 |
+
"Gradient accumulation is not supported when training the text encoder in distributed training. "
|
460 |
+
"Please set gradient_accumulation_steps to 1. This feature will be supported in the future."
|
461 |
+
)
|
462 |
+
|
463 |
+
if args.seed is not None:
|
464 |
+
set_seed(args.seed)
|
465 |
+
|
466 |
+
if args.with_prior_preservation:
|
467 |
+
class_images_dir = Path(args.class_data_dir)
|
468 |
+
if not class_images_dir.exists():
|
469 |
+
class_images_dir.mkdir(parents=True)
|
470 |
+
cur_class_images = len(list(class_images_dir.iterdir()))
|
471 |
+
|
472 |
+
if cur_class_images < args.num_class_images:
|
473 |
+
torch_dtype = torch.float16 if accelerator.device.type == "cuda" else torch.float32
|
474 |
+
pipeline = StableDiffusionPipeline.from_pretrained(
|
475 |
+
args.pretrained_model_name_or_path, torch_dtype=torch_dtype
|
476 |
+
)
|
477 |
+
pipeline.set_progress_bar_config(disable=True)
|
478 |
+
|
479 |
+
num_new_images = args.num_class_images - cur_class_images
|
480 |
+
logger.info(f"Number of class images to sample: {num_new_images}.")
|
481 |
+
|
482 |
+
sample_dataset = PromptDataset(args.class_prompt, num_new_images)
|
483 |
+
sample_dataloader = torch.utils.data.DataLoader(sample_dataset, batch_size=args.sample_batch_size)
|
484 |
+
|
485 |
+
sample_dataloader = accelerator.prepare(sample_dataloader)
|
486 |
+
pipeline.to(accelerator.device)
|
487 |
+
|
488 |
+
for example in tqdm(
|
489 |
+
sample_dataloader, desc="Generating class images", disable=not accelerator.is_local_main_process
|
490 |
+
):
|
491 |
+
with torch.autocast("cuda"):
|
492 |
+
images = pipeline(example["prompt"]).images
|
493 |
+
|
494 |
+
for i, image in enumerate(images):
|
495 |
+
image.save(class_images_dir / f"{example['index'][i] + cur_class_images}.jpg")
|
496 |
+
|
497 |
+
del pipeline
|
498 |
+
if torch.cuda.is_available():
|
499 |
+
torch.cuda.empty_cache()
|
500 |
+
|
501 |
+
# Handle the repository creation
|
502 |
+
if accelerator.is_main_process:
|
503 |
+
if args.push_to_hub:
|
504 |
+
if args.hub_model_id is None:
|
505 |
+
repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)
|
506 |
+
else:
|
507 |
+
repo_name = args.hub_model_id
|
508 |
+
repo = Repository(args.output_dir, clone_from=repo_name)
|
509 |
+
|
510 |
+
with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
|
511 |
+
if "step_*" not in gitignore:
|
512 |
+
gitignore.write("step_*\n")
|
513 |
+
if "epoch_*" not in gitignore:
|
514 |
+
gitignore.write("epoch_*\n")
|
515 |
+
elif args.output_dir is not None:
|
516 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
517 |
+
|
518 |
+
# Load the tokenizer
|
519 |
+
if args.tokenizer_name:
|
520 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.tokenizer_name)
|
521 |
+
elif args.pretrained_model_name_or_path:
|
522 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
|
523 |
+
|
524 |
+
# Load models and create wrapper for stable diffusion
|
525 |
+
if args.train_only_unet:
|
526 |
+
if os.path.exists(str(args.output_dir+"/text_encoder_trained")):
|
527 |
+
text_encoder = CLIPTextModel.from_pretrained(args.output_dir, subfolder="text_encoder_trained")
|
528 |
+
elif os.path.exists(str(args.output_dir+"/text_encoder")):
|
529 |
+
text_encoder = CLIPTextModel.from_pretrained(args.output_dir, subfolder="text_encoder")
|
530 |
+
else:
|
531 |
+
text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder")
|
532 |
+
else:
|
533 |
+
text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder")
|
534 |
+
vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae")
|
535 |
+
unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet")
|
536 |
+
|
537 |
+
vae.requires_grad_(False)
|
538 |
+
if not args.train_text_encoder:
|
539 |
+
text_encoder.requires_grad_(False)
|
540 |
+
|
541 |
+
if args.gradient_checkpointing:
|
542 |
+
unet.enable_gradient_checkpointing()
|
543 |
+
if args.train_text_encoder:
|
544 |
+
text_encoder.gradient_checkpointing_enable()
|
545 |
+
|
546 |
+
if args.scale_lr:
|
547 |
+
args.learning_rate = (
|
548 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
549 |
+
)
|
550 |
+
|
551 |
+
# Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs
|
552 |
+
if args.use_8bit_adam:
|
553 |
+
try:
|
554 |
+
import bitsandbytes as bnb
|
555 |
+
except ImportError:
|
556 |
+
raise ImportError(
|
557 |
+
"To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
|
558 |
+
)
|
559 |
+
|
560 |
+
optimizer_class = bnb.optim.AdamW8bit
|
561 |
+
else:
|
562 |
+
optimizer_class = torch.optim.AdamW
|
563 |
+
|
564 |
+
params_to_optimize = (
|
565 |
+
itertools.chain(unet.parameters(), text_encoder.parameters()) if args.train_text_encoder else unet.parameters()
|
566 |
+
)
|
567 |
+
optimizer = optimizer_class(
|
568 |
+
params_to_optimize,
|
569 |
+
lr=args.learning_rate,
|
570 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
571 |
+
weight_decay=args.adam_weight_decay,
|
572 |
+
eps=args.adam_epsilon,
|
573 |
+
)
|
574 |
+
|
575 |
+
noise_scheduler = DDPMScheduler.from_config(args.pretrained_model_name_or_path, subfolder="scheduler")
|
576 |
+
|
577 |
+
train_dataset = DreamBoothDataset(
|
578 |
+
instance_data_root=args.instance_data_dir,
|
579 |
+
instance_prompt=args.instance_prompt,
|
580 |
+
class_data_root=args.class_data_dir if args.with_prior_preservation else None,
|
581 |
+
class_prompt=args.class_prompt,
|
582 |
+
tokenizer=tokenizer,
|
583 |
+
size=args.resolution,
|
584 |
+
center_crop=args.center_crop,
|
585 |
+
args=args,
|
586 |
+
)
|
587 |
+
|
588 |
+
def collate_fn(examples):
|
589 |
+
input_ids = [example["instance_prompt_ids"] for example in examples]
|
590 |
+
pixel_values = [example["instance_images"] for example in examples]
|
591 |
+
|
592 |
+
# Concat class and instance examples for prior preservation.
|
593 |
+
# We do this to avoid doing two forward passes.
|
594 |
+
if args.with_prior_preservation:
|
595 |
+
input_ids += [example["class_prompt_ids"] for example in examples]
|
596 |
+
pixel_values += [example["class_images"] for example in examples]
|
597 |
+
|
598 |
+
pixel_values = torch.stack(pixel_values)
|
599 |
+
pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
|
600 |
+
|
601 |
+
input_ids = tokenizer.pad({"input_ids": input_ids}, padding=True, return_tensors="pt").input_ids
|
602 |
+
|
603 |
+
batch = {
|
604 |
+
"input_ids": input_ids,
|
605 |
+
"pixel_values": pixel_values,
|
606 |
+
}
|
607 |
+
return batch
|
608 |
+
|
609 |
+
train_dataloader = torch.utils.data.DataLoader(
|
610 |
+
train_dataset, batch_size=args.train_batch_size, shuffle=True, collate_fn=collate_fn
|
611 |
+
)
|
612 |
+
|
613 |
+
# Scheduler and math around the number of training steps.
|
614 |
+
overrode_max_train_steps = False
|
615 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
616 |
+
if args.max_train_steps is None:
|
617 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
618 |
+
overrode_max_train_steps = True
|
619 |
+
|
620 |
+
lr_scheduler = get_scheduler(
|
621 |
+
args.lr_scheduler,
|
622 |
+
optimizer=optimizer,
|
623 |
+
num_warmup_steps=args.lr_warmup_steps * args.gradient_accumulation_steps,
|
624 |
+
num_training_steps=args.max_train_steps * args.gradient_accumulation_steps,
|
625 |
+
)
|
626 |
+
|
627 |
+
if args.train_text_encoder:
|
628 |
+
unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
629 |
+
unet, text_encoder, optimizer, train_dataloader, lr_scheduler
|
630 |
+
)
|
631 |
+
else:
|
632 |
+
unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
633 |
+
unet, optimizer, train_dataloader, lr_scheduler
|
634 |
+
)
|
635 |
+
|
636 |
+
weight_dtype = torch.float32
|
637 |
+
if args.mixed_precision == "fp16":
|
638 |
+
weight_dtype = torch.float16
|
639 |
+
elif args.mixed_precision == "bf16":
|
640 |
+
weight_dtype = torch.bfloat16
|
641 |
+
|
642 |
+
# Move text_encode and vae to gpu.
|
643 |
+
# For mixed precision training we cast the text_encoder and vae weights to half-precision
|
644 |
+
# as these models are only used for inference, keeping weights in full precision is not required.
|
645 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
646 |
+
if not args.train_text_encoder:
|
647 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
648 |
+
|
649 |
+
|
650 |
+
if args.cache_latents:
|
651 |
+
latents_cache = []
|
652 |
+
text_encoder_cache = []
|
653 |
+
for batch in tqdm(train_dataloader, desc="Caching latents"):
|
654 |
+
with torch.no_grad():
|
655 |
+
batch["pixel_values"] = batch["pixel_values"].to(accelerator.device, non_blocking=True, dtype=weight_dtype)
|
656 |
+
batch["input_ids"] = batch["input_ids"].to(accelerator.device, non_blocking=True)
|
657 |
+
latents_cache.append(vae.encode(batch["pixel_values"]).latent_dist)
|
658 |
+
if args.train_text_encoder:
|
659 |
+
text_encoder_cache.append(batch["input_ids"])
|
660 |
+
else:
|
661 |
+
text_encoder_cache.append(text_encoder(batch["input_ids"])[0])
|
662 |
+
train_dataset = LatentsDataset(latents_cache, text_encoder_cache)
|
663 |
+
train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=1, collate_fn=lambda x: x, shuffle=True)
|
664 |
+
|
665 |
+
del vae
|
666 |
+
#if not args.train_text_encoder:
|
667 |
+
# del text_encoder
|
668 |
+
if torch.cuda.is_available():
|
669 |
+
torch.cuda.empty_cache()
|
670 |
+
|
671 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
672 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
673 |
+
if overrode_max_train_steps:
|
674 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
675 |
+
# Afterwards we recalculate our number of training epochs
|
676 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
677 |
+
|
678 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
679 |
+
# The trackers initializes automatically on the main process.
|
680 |
+
if accelerator.is_main_process:
|
681 |
+
accelerator.init_trackers("dreambooth", config=vars(args))
|
682 |
+
|
683 |
+
def bar(prg):
|
684 |
+
br='|'+'█' * prg + ' ' * (25-prg)+'|'
|
685 |
+
return br
|
686 |
+
|
687 |
+
# Train!
|
688 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
689 |
+
|
690 |
+
logger.info("***** Running training *****")
|
691 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
692 |
+
logger.info(f" Num batches each epoch = {len(train_dataloader)}")
|
693 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
694 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
695 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
696 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
697 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
698 |
+
# Only show the progress bar once on each machine.
|
699 |
+
progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process)
|
700 |
+
global_step = 0
|
701 |
+
|
702 |
+
for epoch in range(args.num_train_epochs):
|
703 |
+
unet.train()
|
704 |
+
if args.train_text_encoder:
|
705 |
+
text_encoder.train()
|
706 |
+
for step, batch in enumerate(train_dataloader):
|
707 |
+
with accelerator.accumulate(unet):
|
708 |
+
# Convert images to latent space
|
709 |
+
with torch.no_grad():
|
710 |
+
if args.cache_latents:
|
711 |
+
latents_dist = batch[0][0]
|
712 |
+
else:
|
713 |
+
latents_dist = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist
|
714 |
+
latents = latents_dist.sample() * 0.18215
|
715 |
+
|
716 |
+
# Sample noise that we'll add to the latents
|
717 |
+
noise = torch.randn_like(latents)
|
718 |
+
bsz = latents.shape[0]
|
719 |
+
# Sample a random timestep for each image
|
720 |
+
timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
|
721 |
+
timesteps = timesteps.long()
|
722 |
+
|
723 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
724 |
+
# (this is the forward diffusion process)
|
725 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
726 |
+
|
727 |
+
# Get the text embedding for conditioning
|
728 |
+
if(args.cache_latents):
|
729 |
+
if args.train_text_encoder:
|
730 |
+
encoder_hidden_states = text_encoder(batch[0][1])[0]
|
731 |
+
else:
|
732 |
+
encoder_hidden_states = batch[0][1]
|
733 |
+
else:
|
734 |
+
encoder_hidden_states = text_encoder(batch["input_ids"])[0]
|
735 |
+
|
736 |
+
# Predict the noise residual
|
737 |
+
model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
|
738 |
+
|
739 |
+
# Get the target for loss depending on the prediction type
|
740 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
741 |
+
target = noise
|
742 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
743 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
744 |
+
else:
|
745 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
746 |
+
|
747 |
+
if args.with_prior_preservation:
|
748 |
+
# Chunk the noise and model_pred into two parts and compute the loss on each part separately.
|
749 |
+
model_pred, model_pred_prior = torch.chunk(model_pred, 2, dim=0)
|
750 |
+
target, target_prior = torch.chunk(target, 2, dim=0)
|
751 |
+
|
752 |
+
# Compute instance loss
|
753 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="none").mean([1, 2, 3]).mean()
|
754 |
+
|
755 |
+
# Compute prior loss
|
756 |
+
prior_loss = F.mse_loss(model_pred_prior.float(), target_prior.float(), reduction="mean")
|
757 |
+
|
758 |
+
# Add the prior loss to the instance loss.
|
759 |
+
loss = loss + args.prior_loss_weight * prior_loss
|
760 |
+
else:
|
761 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
|
762 |
+
|
763 |
+
accelerator.backward(loss)
|
764 |
+
if accelerator.sync_gradients:
|
765 |
+
params_to_clip = (
|
766 |
+
itertools.chain(unet.parameters(), text_encoder.parameters())
|
767 |
+
if args.train_text_encoder
|
768 |
+
else unet.parameters()
|
769 |
+
)
|
770 |
+
accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
|
771 |
+
optimizer.step()
|
772 |
+
lr_scheduler.step()
|
773 |
+
optimizer.zero_grad()
|
774 |
+
|
775 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
776 |
+
if accelerator.sync_gradients:
|
777 |
+
progress_bar.update(1)
|
778 |
+
global_step += 1
|
779 |
+
|
780 |
+
fll=round((global_step*100)/args.max_train_steps)
|
781 |
+
fll=round(fll/4)
|
782 |
+
pr=bar(fll)
|
783 |
+
|
784 |
+
logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
785 |
+
progress_bar.set_postfix(**logs)
|
786 |
+
progress_bar.set_description_str("Progress:"+pr)
|
787 |
+
accelerator.log(logs, step=global_step)
|
788 |
+
|
789 |
+
if global_step >= args.max_train_steps:
|
790 |
+
break
|
791 |
+
|
792 |
+
if args.train_text_encoder and global_step == args.stop_text_encoder_training and global_step >= 30:
|
793 |
+
if accelerator.is_main_process:
|
794 |
+
print(" [0;32m" +" Freezing the text_encoder ..."+" [0m")
|
795 |
+
frz_dir=args.output_dir + "/text_encoder_frozen"
|
796 |
+
if os.path.exists(frz_dir):
|
797 |
+
subprocess.call('rm -r '+ frz_dir, shell=True)
|
798 |
+
os.mkdir(frz_dir)
|
799 |
+
pipeline = StableDiffusionPipeline.from_pretrained(
|
800 |
+
args.pretrained_model_name_or_path,
|
801 |
+
unet=accelerator.unwrap_model(unet),
|
802 |
+
text_encoder=accelerator.unwrap_model(text_encoder),
|
803 |
+
)
|
804 |
+
pipeline.text_encoder.save_pretrained(frz_dir)
|
805 |
+
|
806 |
+
if args.save_n_steps >= 200:
|
807 |
+
if global_step < args.max_train_steps and global_step+1==i:
|
808 |
+
ckpt_name = "_step_" + str(global_step+1)
|
809 |
+
save_dir = Path(args.output_dir+ckpt_name)
|
810 |
+
save_dir=str(save_dir)
|
811 |
+
save_dir=save_dir.replace(" ", "_")
|
812 |
+
if not os.path.exists(save_dir):
|
813 |
+
os.mkdir(save_dir)
|
814 |
+
inst=save_dir[16:]
|
815 |
+
inst=inst.replace(" ", "_")
|
816 |
+
print(" [1;32mSAVING CHECKPOINT: "+args.Session_dir+"/"+inst+".ckpt")
|
817 |
+
# Create the pipeline using the trained modules and save it.
|
818 |
+
if accelerator.is_main_process:
|
819 |
+
pipeline = StableDiffusionPipeline.from_pretrained(
|
820 |
+
args.pretrained_model_name_or_path,
|
821 |
+
unet=accelerator.unwrap_model(unet),
|
822 |
+
text_encoder=accelerator.unwrap_model(text_encoder),
|
823 |
+
)
|
824 |
+
pipeline.save_pretrained(save_dir)
|
825 |
+
frz_dir=args.output_dir + "/text_encoder_frozen"
|
826 |
+
if args.train_text_encoder and os.path.exists(frz_dir):
|
827 |
+
subprocess.call('rm -r '+save_dir+'/text_encoder/*.*', shell=True)
|
828 |
+
subprocess.call('cp -f '+frz_dir +'/*.* '+ save_dir+'/text_encoder', shell=True)
|
829 |
+
chkpth=args.Session_dir+"/"+inst+".ckpt"
|
830 |
+
subprocess.call('python /content/diffusers/scripts/convert_diffusers_to_original_stable_diffusion.py --model_path ' + save_dir + ' --checkpoint_path ' + chkpth + ' --half', shell=True)
|
831 |
+
subprocess.call('rm -r '+ save_dir, shell=True)
|
832 |
+
i=i+args.save_n_steps
|
833 |
+
|
834 |
+
accelerator.wait_for_everyone()
|
835 |
+
|
836 |
+
# Create the pipeline using using the trained modules and save it.
|
837 |
+
if accelerator.is_main_process:
|
838 |
+
if args.dump_only_text_encoder:
|
839 |
+
txt_dir=args.output_dir + "/text_encoder_trained"
|
840 |
+
if not os.path.exists(txt_dir):
|
841 |
+
os.mkdir(txt_dir)
|
842 |
+
pipeline = StableDiffusionPipeline.from_pretrained(
|
843 |
+
args.pretrained_model_name_or_path,
|
844 |
+
unet=accelerator.unwrap_model(unet),
|
845 |
+
text_encoder=accelerator.unwrap_model(text_encoder),
|
846 |
+
)
|
847 |
+
pipeline.text_encoder.save_pretrained(txt_dir)
|
848 |
+
|
849 |
+
elif args.train_only_unet:
|
850 |
+
pipeline = StableDiffusionPipeline.from_pretrained(
|
851 |
+
args.pretrained_model_name_or_path,
|
852 |
+
unet=accelerator.unwrap_model(unet),
|
853 |
+
text_encoder=accelerator.unwrap_model(text_encoder),
|
854 |
+
)
|
855 |
+
pipeline.save_pretrained(args.output_dir)
|
856 |
+
txt_dir=args.output_dir + "/text_encoder_trained"
|
857 |
+
subprocess.call('rm -r '+txt_dir, shell=True)
|
858 |
+
|
859 |
+
else:
|
860 |
+
pipeline = StableDiffusionPipeline.from_pretrained(
|
861 |
+
args.pretrained_model_name_or_path,
|
862 |
+
unet=accelerator.unwrap_model(unet),
|
863 |
+
text_encoder=accelerator.unwrap_model(text_encoder),
|
864 |
+
)
|
865 |
+
frz_dir=args.output_dir + "/text_encoder_frozen"
|
866 |
+
pipeline.save_pretrained(args.output_dir)
|
867 |
+
if args.train_text_encoder and os.path.exists(frz_dir):
|
868 |
+
subprocess.call('mv -f '+frz_dir +'/*.* '+ args.output_dir+'/text_encoder', shell=True)
|
869 |
+
subprocess.call('rm -r '+ frz_dir, shell=True)
|
870 |
+
|
871 |
+
if args.push_to_hub:
|
872 |
+
repo.push_to_hub(commit_message="End of training", blocking=False, auto_lfs_prune=True)
|
873 |
+
|
874 |
+
accelerator.end_training()
|
875 |
+
del pipeline
|
876 |
+
torch.cuda.empty_cache()
|
877 |
+
gc.collect()
|
878 |
+
if __name__ == "__main__":
|
879 |
+
pass
|
880 |
+
#main()
|
881 |
+
|
trsl_style.png
ADDED
![]() |