julien-c HF Staff multimodalart HF Staff commited on
Commit
c6d65be
·
0 Parent(s):

Duplicate from multimodalart/dreambooth-training

Browse files

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

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