amankishore multimodalart
HF staff
commited on
Commit
00bee52
0 Parent(s):

Duplicate from multimodalart/dreambooth-training

Browse files

Co-authored-by: Multimodal AI art <multimodalart@users.noreply.huggingface.co>

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
Binary file (571 Bytes). View file
cat-toy-deprec.png ADDED
Binary file (928 kB). View file
cat-toy.png ADDED
Binary file (693 kB). View file
cattoy.png ADDED
Binary file (693 kB). View file
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
Binary file (5.76 kB). View file
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
Binary file (570 kB). View file
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 @@