mvaloatto multimodalart HF Staff commited on
Commit
48af2ff
·
0 Parent(s):

Duplicate from multimodalart/dreambooth-training

Browse files

Co-authored-by: Multimodal AI art <[email protected]>

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