baffo32 amankishore commited on
Commit
465d488
·
0 Parent(s):

Duplicate from MirageML/dreambooth

Browse files

Co-authored-by: Aman Kishore <[email protected]>

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