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