Spaces:
Build error
Build error
Commit ·
2d28cd4
0
Parent(s):
Duplicate from multimodalart/dreambooth-training
Browse filesCo-authored-by: Apolinário from multimodal AI art <multimodalart@users.noreply.huggingface.co>
Files changed (17)
- .gitattributesAdded+35
- .gitignoreAdded+7
- README.mdAdded+15
- app.pyAdded+687
- arrow.pngAdded
- cat-toy-deprec.pngAdded
- cat-toy.pngAdded
- cattoy.pngAdded
- convertosd.pyAdded+302
- duplicate.pngAdded
- mix.zipAdded+3
- model_index.jsonAdded+32
- person.pngAdded
- requirements-local.txtAdded+18
- requirements.txtAdded+17
- train_dreambooth.pyAdded+889
- trsl_style.pngAdded
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textxformers-0.0.14.dev0-cp38-cp38-linux_x86_64_t4.whl filter=lfs diff=lfs merge=lfs -textxformers-0.0.14.dev0-cp38-cp38-linux_x86_64.whl filter=lfs diff=lfs merge=lfs -text1234567Mixoutput_modelinstance_images__pycache__intraining.lockhastrained.successdiffusers_model.tar123456789101112131415---title: Dreambooth Trainingemoji: ☁️colorFrom: pinkcolorTo: redsdk: gradiosdk_version: 3.16.2app_file: app.pypinned: falsesuggested_hardware: t4-smalllicense: mitduplicated_from: multimodalart/dreambooth-training---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687from subprocess import getoutputimport os
gpu_info = getoutput('nvidia-smi')if("A10G" in gpu_info): which_gpu = "A10G" os.system(f"pip install --no-deps xformers==0.0.16rc425")elif("T4" in gpu_info): which_gpu = "T4" os.system(f"pip install -q https://github.com/camenduru/stable-diffusion-webui-colab/releases/download/0.0.15/xformers-0.0.15.dev0+1515f77.d20221130-cp38-cp38-linux_x86_64.whl")else: which_gpu = "CPU" import gradio as grfrom pathlib import Pathimport argparseimport shutilfrom train_dreambooth import run_trainingfrom convertosd import convertfrom PIL import Imagefrom slugify import slugifyimport requestsimport torchimport zipfileimport tarfileimport urllib.parseimport gcfrom diffusers import StableDiffusionPipelinefrom huggingface_hub import snapshot_download, update_repo_visibility, HfApi
is_spaces = True if "SPACE_ID" in os.environ else Falseif(is_spaces): is_shared_ui = True if "multimodalart/dreambooth-training" in os.environ['SPACE_ID'] else Falseelse: is_shared_ui = Falseis_gpu_associated = torch.cuda.is_available()
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
if(is_gpu_associated): model_v1 = snapshot_download(repo_id="multimodalart/sd-fine-tunable") model_v2 = snapshot_download(repo_id="stabilityai/stable-diffusion-2-1", ignore_patterns=["*.ckpt", "*.safetensors"]) model_v2_512 = snapshot_download(repo_id="stabilityai/stable-diffusion-2-1-base", ignore_patterns=["*.ckpt", "*.safetensors"]) safety_checker = snapshot_download(repo_id="multimodalart/sd-sc") model_to_load = model_v1
def swap_base_model(selected_model): if(is_gpu_associated): global model_to_load if(selected_model == "v1-5"): model_to_load = model_v1 elif(selected_model == "v2-1-768"): model_to_load = model_v2 else: model_to_load = model_v2_512
css = ''' .instruction{position: absolute; top: 0;right: 0;margin-top: 0px !important} .arrow{position: absolute;top: 0;right: -110px;margin-top: -8px !important} #component-4, #component-3, #component-10{min-height: 0} .duplicate-button img{margin: 0}'''maximum_concepts = 3
def swap_text(option, base): resize_width = 768 if base == "v2-1-768" else 512 mandatory_liability = "You must have the right to do so and you are liable for the images you use, example:" if(option == "object"): instance_prompt_example = "cttoy" freeze_for = 30 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)] elif(option == "person"): instance_prompt_example = "julcto" freeze_for = 70 #show_prior_preservation = True if base != "v2-1-768" else False show_prior_preservation=False if(show_prior_preservation): prior_preservation_box_update = gr.update(visible=show_prior_preservation) else: prior_preservation_box_update = gr.update(visible=show_prior_preservation, value=False) 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] elif(option == "style"): instance_prompt_example = "trsldamrl" freeze_for = 10 return [f"You are going to train a `style`, upload 10-20 images of the style you are planning on training on. You can use services like <a style='text-decoration: underline' target='_blank' href='https://www.birme.net/?target_width={resize_width}&target_height={resize_width}'>birme</a> for smart cropping. {mandatory_liability}:", '''<img src="file=trsl_style.png" />''', f"You should name your concept with a unique made up word that has low chance of the model already knowing it (e.g.: `{instance_prompt_example}` here). Images will be automatically cropped to {resize_width}x{resize_width}", freeze_for, gr.update(visible=False)]
def count_files(*inputs): file_counter = 0 concept_counter = 0 for i, input in enumerate(inputs): if(i < maximum_concepts): files = inputs[i] if(files): concept_counter+=1 file_counter+=len(files) uses_custom = inputs[-1] type_of_thing = inputs[-4] selected_model = inputs[-5] experimental_faces = inputs[-6] if(uses_custom): Training_Steps = int(inputs[-3]) else: Training_Steps = file_counter*150 if(type_of_thing == "person" and Training_Steps > 2400): Training_Steps = 2400 #Avoid overfitting on person faces if(is_spaces): if(selected_model == "v1-5"): its = 1.1 if which_gpu == "T4" else 1.8 if(experimental_faces): its = 1 elif(selected_model == "v2-1-512"): its = 0.8 if which_gpu == "T4" else 1.5 if(experimental_faces): its = 0.7 elif(selected_model == "v2-1-768"): its = 0.48 if which_gpu == "T4" else 0.85 gpu_price = 0.60 if which_gpu == "T4" else 1.10 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. The setup, compression and uploading the model can take up to 20 minutes.<br>As the {which_gpu}-Small GPU costs US${gpu_price} for 1h, <span style="font-size: 120%"><b>the estimated cost for this training is below US${round((((Training_Steps/its)/3600)+0.3+0.1)*gpu_price, 2)}.</b></span><br><br> 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>''' else: summary_sentence = f'''You are going to train {concept_counter} {type_of_thing}(s), with {file_counter} images for {Training_Steps} steps.<br><br>''' return([gr.update(visible=True), gr.update(visible=True, value=summary_sentence)])
def update_steps(*files_list): file_counter = 0 for i, files in enumerate(files_list): if(files): file_counter+=len(files) return(gr.update(value=file_counter*200))
def visualise_progress_bar(): return gr.update(visible=True)
def pad_image(image): w, h = image.size if w == h: return image elif w > h: new_image = Image.new(image.mode, (w, w), (0, 0, 0)) new_image.paste(image, (0, (w - h) // 2)) return new_image else: new_image = Image.new(image.mode, (h, h), (0, 0, 0)) new_image.paste(image, ((h - w) // 2, 0)) return new_image
def validate_model_upload(hf_token, model_name): if(hf_token != ''): api = HfApi() try: _ = api.whoami(hf_token) except: raise gr.Error("You have inserted an invalid Hugging Face token") try: if(is_spaces): update_repo_visibility(repo_id=os.environ['SPACE_ID'], private=True, token=hf_token, repo_type="space") except: raise gr.Error("Oops, you created a Hugging Face token with read permissions only. You need one with write permissions") else: raise gr.Error("Please insert a Hugging Face Token (make sure to create it with write permissions)") if(model_name == ""): raise gr.Error("Please fill in your model's name")
def swap_hardware(hf_token, hardware="cpu-basic"): hardware_url = f"https://huggingface.co/spaces/{os.environ['SPACE_ID']}/hardware" headers = { "authorization" : f"Bearer {hf_token}"} body = {'flavor': hardware} requests.post(hardware_url, json = body, headers=headers)
def swap_sleep_time(hf_token,sleep_time): sleep_time_url = f"https://huggingface.co/api/spaces/{os.environ['SPACE_ID']}/sleeptime" headers = { "authorization" : f"Bearer {hf_token}"} body = {'seconds':sleep_time} requests.post(sleep_time_url,json=body,headers=headers)
def get_sleep_time(hf_token): sleep_time_url = f"https://huggingface.co/api/spaces/{os.environ['SPACE_ID']}" headers = { "authorization" : f"Bearer {hf_token}"} response = requests.get(sleep_time_url,headers=headers) try: gcTimeout = response.json()['runtime']['gcTimeout'] except: gcTimeout = None return gcTimeout
def write_to_community(title, description,hf_token): from huggingface_hub import HfApi api = HfApi() api.create_discussion(repo_id=os.environ['SPACE_ID'], title=title, description=description,repo_type="space", token=hf_token)
def train(progress=gr.Progress(track_tqdm=True), *inputs): which_model = inputs[-10] if(which_model == ""): raise gr.Error("You forgot to select a base model to use") if is_shared_ui: raise gr.Error("This Space only works in duplicated instances") if not is_gpu_associated: raise gr.Error("Please associate a T4 or A10G GPU for this Space") hf_token = inputs[-5] model_name = inputs[-7] if(is_spaces): sleep_time = get_sleep_time(hf_token) if sleep_time: swap_sleep_time(hf_token, -1) remove_attribution_after = inputs[-6] else: remove_attribution_after = False if(remove_attribution_after): validate_model_upload(hf_token, model_name) torch.cuda.empty_cache() if 'pipe' in globals(): global pipe, pipe_is_set del pipe pipe_is_set = False gc.collect() if os.path.exists("output_model"): shutil.rmtree('output_model') if os.path.exists("instance_images"): shutil.rmtree('instance_images') if os.path.exists("diffusers_model.tar"): os.remove("diffusers_model.tar") if os.path.exists("model.ckpt"): os.remove("model.ckpt") if os.path.exists("hastrained.success"): os.remove("hastrained.success") file_counter = 0 resolution = 512 if which_model != "v2-1-768" else 768 for i, input in enumerate(inputs): if(i < maximum_concepts-1): if(input): os.makedirs('instance_images',exist_ok=True) files = inputs[i+(maximum_concepts*2)] prompt = inputs[i+maximum_concepts] if(prompt == "" or prompt == None): raise gr.Error("You forgot to define your concept prompt") for j, file_temp in enumerate(files): file = Image.open(file_temp.name) image = pad_image(file) image = image.resize((resolution, resolution)) extension = file_temp.name.split(".")[1] image = image.convert('RGB') image.save(f'instance_images/{prompt}_({j+1}).jpg', format="JPEG", quality = 100) file_counter += 1 os.makedirs('output_model',exist_ok=True) uses_custom = inputs[-1] type_of_thing = inputs[-4] experimental_face_improvement = inputs[-9] if(uses_custom): Training_Steps = int(inputs[-3]) Train_text_encoder_for = int(inputs[-2]) else: if(type_of_thing == "object"): Train_text_encoder_for=30 elif(type_of_thing == "style"): Train_text_encoder_for=15 elif(type_of_thing == "person"): Train_text_encoder_for=70 Training_Steps = file_counter*150 if(type_of_thing == "person" and Training_Steps > 2600): Training_Steps = 2600 #Avoid overfitting on people's faces stptxt = int((Training_Steps*Train_text_encoder_for)/100) gradient_checkpointing = True if (experimental_face_improvement or which_model != "v1-5") else False cache_latents = True if which_model != "v1-5" else False if (type_of_thing == "object" or type_of_thing == "style" or (type_of_thing == "person" and not experimental_face_improvement)): args_general = argparse.Namespace( image_captions_filename = True, train_text_encoder = True if stptxt > 0 else False, stop_text_encoder_training = stptxt, save_n_steps = 0, pretrained_model_name_or_path = model_to_load, instance_data_dir="instance_images", class_data_dir=None, output_dir="output_model", instance_prompt="", seed=42, resolution=resolution, mixed_precision="fp16", train_batch_size=1, gradient_accumulation_steps=1, use_8bit_adam=True, learning_rate=2e-6, lr_scheduler="polynomial", lr_warmup_steps = 0, max_train_steps=Training_Steps, gradient_checkpointing=gradient_checkpointing, cache_latents=cache_latents, ) print("Starting single training...") lock_file = open("intraining.lock", "w") lock_file.close() try: run_training(args_general) except Exception as e: if(is_spaces): title="There was an error on during your training" description=f''' Unfortunately there was an error during training your {model_name} model. Please check it out below. Feel free to report this issue to [Dreambooth Training](https://huggingface.co/spaces/multimodalart/dreambooth-training): ``` {str(e)} ``` ''' swap_hardware(hf_token, "cpu-basic") write_to_community(title,description,hf_token) gc.collect() torch.cuda.empty_cache() if(which_model == "v1-5"): print("Adding Safety Checker to the model...") shutil.copytree(f"{safety_checker}/feature_extractor", "output_model/feature_extractor", dirs_exist_ok=True) shutil.copytree(f"{safety_checker}/safety_checker", "output_model/safety_checker", dirs_exist_ok=True) shutil.copy(f"model_index.json", "output_model/model_index.json") if(not remove_attribution_after): swap_sleep_time(hf_token, sleep_time) print("Archiving model file...") with tarfile.open("diffusers_model.tar", "w") as tar: tar.add("output_model", arcname=os.path.basename("output_model")) if os.path.exists("intraining.lock"): os.remove("intraining.lock") trained_file = open("hastrained.success", "w") trained_file.close() print("Training completed!") return [ gr.update(visible=False), #progress_bar gr.update(visible=True, value=["diffusers_model.tar"]), #result gr.update(visible=True), #try_your_model gr.update(visible=True), #push_to_hub gr.update(visible=True), #convert_button gr.update(visible=False), #training_ongoing gr.update(visible=True) #completed_training ] else: where_to_upload = inputs[-8] push(model_name, where_to_upload, hf_token, which_model, True) swap_hardware(hf_token, "cpu-basic")
pipe_is_set = Falsedef generate(prompt, steps): torch.cuda.empty_cache() from diffusers import StableDiffusionPipeline global pipe_is_set if(not pipe_is_set): global pipe pipe = StableDiffusionPipeline.from_pretrained("./output_model", torch_dtype=torch.float16) pipe = pipe.to("cuda") pipe_is_set = True image = pipe(prompt, num_inference_steps=steps).images[0] return(image)
def push(model_name, where_to_upload, hf_token, which_model, comes_from_automated=False): validate_model_upload(hf_token, model_name) if(not os.path.exists("model.ckpt")): convert("output_model", "model.ckpt") from huggingface_hub import HfApi, HfFolder, CommitOperationAdd from huggingface_hub import create_repo model_name_slug = slugify(model_name) api = HfApi() your_username = api.whoami(token=hf_token)["name"] if(where_to_upload == "My personal profile"): model_id = f"{your_username}/{model_name_slug}" else: model_id = f"sd-dreambooth-library/{model_name_slug}" headers = {"Authorization" : f"Bearer: {hf_token}", "Content-Type": "application/json"} response = requests.post("https://huggingface.co/organizations/sd-dreambooth-library/share/SSeOwppVCscfTEzFGQaqpfcjukVeNrKNHX", headers=headers)
print(f"Starting to upload the model {model_id}...") images_upload = os.listdir("instance_images") image_string = "" instance_prompt_list = [] previous_instance_prompt = '' for i, image in enumerate(images_upload): instance_prompt = image.split("_")[0] if(instance_prompt != previous_instance_prompt): title_instance_prompt_string = instance_prompt instance_prompt_list.append(instance_prompt) else: title_instance_prompt_string = '' previous_instance_prompt = instance_prompt image_string = f'''{title_instance_prompt_string} {"(use that on your prompt)" if title_instance_prompt_string != "" else ""} {image_string}})''' readme_text = f'''---license: creativeml-openrail-mtags:- text-to-imagewidget:- text: {instance_prompt_list[0]}---### {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
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!
Sample pictures of:{image_string}''' #Save the readme to a file readme_file = open("model.README.md", "w") readme_file.write(readme_text) readme_file.close() #Save the token identifier to a file text_file = open("token_identifier.txt", "w") text_file.write(', '.join(instance_prompt_list)) text_file.close() try: create_repo(model_id,private=True, token=hf_token) except: import time epoch_time = str(int(time.time())) create_repo(f"{model_id}-{epoch_time}", private=True,token=hf_token) operations = [ CommitOperationAdd(path_in_repo="token_identifier.txt", path_or_fileobj="token_identifier.txt"), CommitOperationAdd(path_in_repo="README.md", path_or_fileobj="model.README.md"), CommitOperationAdd(path_in_repo=f"model.ckpt",path_or_fileobj="model.ckpt") ] api.create_commit( repo_id=model_id, operations=operations, commit_message=f"Upload the model {model_name}", token=hf_token ) api.upload_folder( folder_path="output_model", repo_id=model_id, token=hf_token ) api.upload_folder( folder_path="instance_images", path_in_repo="concept_images", repo_id=model_id, token=hf_token ) if is_spaces: if(not comes_from_automated): extra_message = "Don't forget to remove the GPU attribution after you play with it." else: extra_message = "The GPU has been removed automatically as requested, and you can try the model via the model page" 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}" write_to_community(title, description, hf_token) #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) print("Model uploaded successfully!") 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"])]
def convert_to_ckpt(): if 'pipe' in globals(): global pipe, pipe_is_set del pipe pipe_is_set = False gc.collect() convert("output_model", "model.ckpt") return gr.update(visible=True, value=["diffusers_model.tar", "model.ckpt"])
def check_status(top_description): if os.path.exists("hastrained.success"): if is_spaces: update_top_tag = gr.update(value=f''' <div class="gr-prose" style="max-width: 80%"> <h2>Your model has finished training ✅</h2> <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> </div> ''') else: update_top_tag = gr.update(value=f''' <div class="gr-prose" style="max-width: 80%"> <h2>Your model has finished training ✅</h2> <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> </div> ''') show_outputs = True elif os.path.exists("intraining.lock"): update_top_tag = gr.update(value=''' <div class="gr-prose" style="max-width: 80%"> <h2>Don't worry, your model is still training! ⌛</h2> <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> </div> ''') show_outputs = False else: update_top_tag = gr.update(value=top_description) show_outputs = False if os.path.exists("diffusers_model.tar"): update_files_tag = gr.update(visible=show_outputs, value=["diffusers_model.tar"]) else: update_files_tag = gr.update(visible=show_outputs) return [ update_top_tag, #top_description gr.update(visible=show_outputs), #try_your_model gr.update(visible=show_outputs), #push_to_hub update_files_tag, #result gr.update(visible=show_outputs), #convert_button ]
def checkbox_swap(checkbox): return [gr.update(visible=checkbox), gr.update(visible=checkbox), gr.update(visible=checkbox), gr.update(visible=checkbox)]
with gr.Blocks(css=css) as demo: with gr.Box(): if is_shared_ui: top_description = gr.HTML(f''' <div class="gr-prose" style="max-width: 80%"> <h2>Attention - This Space doesn't work in this shared UI</h2> <p>For it to work, you can either run locally or duplicate the Space and run it on your own profile using a (paid) private T4-small or A10G-small GPU for training. A T4 costs US$0.60/h, so it should cost < US$1 to train most models using default settings with it! <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> <img class="instruction" src="file=duplicate.png"> <img class="arrow" src="file=arrow.png" /> </div> ''') elif(is_spaces): if(is_gpu_associated): top_description = gr.HTML(f''' <div class="gr-prose" style="max-width: 80%"> <h2>You have successfully associated a {which_gpu} GPU to the Dreambooth Training Space 🎉</h2> <p>You can now train your model! You will be billed by the minute from when you activated the GPU until when it is turned it off.</p> </div> ''') else: top_description = gr.HTML(f''' <div class="gr-prose" style="max-width: 80%"> <h2>You have successfully duplicated the Dreambooth Training Space 🎉</h2> <p>There's only one step left before you can train your model: <a href="https://huggingface.co/spaces/{os.environ['SPACE_ID']}/settings" style="text-decoration: underline" target="_blank">attribute a <b>T4-small or A10G-small GPU</b> to it (via the Settings tab)</a> and run the training below. You will be billed by the minute from when you activate the GPU until when it is turned it off.</p> </div> ''') else: top_description = gr.HTML(f''' <div class="gr-prose" style="max-width: 80%"> <h2>You have successfully cloned the Dreambooth Training Space locally 🎉</h2> <p>Do a <code>pip install requirements-local.txt</code></p> </div> ''') gr.Markdown("# Dreambooth Training UI 💭") 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)") with gr.Row() as what_are_you_training: type_of_thing = gr.Dropdown(label="What would you like to train?", choices=["object", "person", "style"], value="object", interactive=True) with gr.Column(): base_model_to_use = gr.Dropdown(label="Which base model would you like to use?", choices=["v1-5", "v2-1-512", "v2-1-768"], value="v1-5", interactive=True)
#Very hacky approach to emulate dynamically created Gradio components with gr.Row() as upload_your_concept: with gr.Column(): 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") thing_experimental = gr.Checkbox(label="Improve faces (prior preservation) - can take longer training but can improve faces", visible=False, value=False) thing_image_example = gr.HTML('''<img src="file=cat-toy.png" />''') 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.") with gr.Column(): file_collection = [] concept_collection = [] buttons_collection = [] delete_collection = [] is_visible = []
row = [None] * maximum_concepts for x in range(maximum_concepts): ordinal = lambda n: "%d%s" % (n, "tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10::4]) if(x == 0): visible = True is_visible.append(gr.State(value=True)) else: visible = False is_visible.append(gr.State(value=False))
file_collection.append(gr.File(file_types=["image"], label=f'''Upload the images for your {ordinal(x+1) if (x>0) else ""} concept''', file_count="multiple", interactive=True, visible=visible)) with gr.Column(visible=visible) as row[x]: 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''')) with gr.Row(): if(x < maximum_concepts-1): buttons_collection.append(gr.Button(value="Add +1 concept", visible=visible)) if(x > 0): delete_collection.append(gr.Button(value=f"Delete {ordinal(x+1)} concept")) counter_add = 1 for button in buttons_collection: if(counter_add < len(buttons_collection)): button.click(lambda: [gr.update(visible=True),gr.update(visible=True), gr.update(visible=False), gr.update(visible=True), True, None], None, [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) else: 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) counter_add += 1 counter_delete = 1 for delete_button in delete_collection: if(counter_delete < len(delete_collection)+1): 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) counter_delete += 1 with gr.Accordion("Custom Settings", open=False): swap_auto_calculated = gr.Checkbox(label="Use custom settings") 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.") steps = gr.Number(label="How many steps", value=2400) perc_txt_encoder = gr.Number(label="Percentage of the training steps the text-encoder should be trained as well", value=30) with gr.Box(visible=False) as training_summary: training_summary_text = gr.HTML("", visible=True, label="Training Summary") is_advanced_visible = True if is_spaces else False 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) training_summary_model_name = gr.Textbox(label="Name of your model", visible=True) training_summary_where_to_upload = gr.Dropdown(["My personal profile", "Public Library"], value="My personal profile", label="Upload to", visible=True) 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) training_summary_token = gr.Textbox(label="Hugging Face Write Token", type="password", visible=True) train_btn = gr.Button("Start Training") progress_bar = gr.Textbox(visible=False) if(is_shared_ui): training_ongoing = gr.Markdown("## This Space only works in duplicated instances. Please duplicate it and try again!", visible=False) elif(not is_gpu_associated): training_ongoing = gr.Markdown("## Oops, you haven't associated your T4 or A10G GPU to this Space. Visit the Settings tab, associate and try again.", visible=False) else: 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) #Post-training UI completed_training = gr.Markdown('''# ✅ Training completed. ### Don't forget to remove the GPU attribution after you are done trying and uploading your model''', visible=False) with gr.Row(): with gr.Box(visible=False) as try_your_model: gr.Markdown("## Try your model") prompt = gr.Textbox(label="Type your prompt") result_image = gr.Image() inference_steps = gr.Slider(minimum=1, maximum=150, value=50, step=1) generate_button = gr.Button("Generate Image") with gr.Box(visible=False) as push_to_hub: gr.Markdown("## Push to Hugging Face Hub") model_name = gr.Textbox(label="Name of your model", placeholder="Tarsila do Amaral Style") where_to_upload = gr.Dropdown(["My personal profile", "Public Library"], label="Upload to") 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.") hf_token = gr.Textbox(label="Hugging Face Write Token", type="password") push_button = gr.Button("Push to the Hub") result = gr.File(label="Download the uploaded models in the diffusers format", visible=True) success_message_upload = gr.Markdown(visible=False) convert_button = gr.Button("Convert to CKPT", visible=False) #Swap the examples and the % of text encoder trained depending if it is an object, person or style 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) #Swap the base model 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) #base_model_to_use.change(fn=visualise_progress_bar, inputs=[], outputs=progress_bar) base_model_to_use.change(fn=swap_base_model, inputs=base_model_to_use, outputs=[]) #Update the summary box below the UI according to how many images are uploaded and whether users are using custom settings or not for file in file_collection: #file.change(fn=update_steps,inputs=file_collection, outputs=steps) 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) 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) 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) 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) 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) #Give more options if the user wants to finish everything after training if(is_spaces): 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) #Add a message for while it is in training #train_btn.click(lambda:gr.update(visible=True), inputs=None, outputs=training_ongoing) #The main train function train_btn.click(lambda:gr.update(visible=True), inputs=[], outputs=progress_bar) train_btn.click(fn=train, inputs=is_visible+concept_collection+file_collection+[base_model_to_use]+[thing_experimental]+[training_summary_where_to_upload]+[training_summary_model_name]+[training_summary_checkbox]+[training_summary_token]+[type_of_thing]+[steps]+[perc_txt_encoder]+[swap_auto_calculated], outputs=[progress_bar, result, try_your_model, push_to_hub, convert_button, training_ongoing, completed_training], queue=False) #Button to generate an image from your trained model after training generate_button.click(fn=generate, inputs=[prompt, inference_steps], outputs=result_image, queue=False) #Button to push the model to the Hugging Face Hub push_button.click(fn=push, inputs=[model_name, where_to_upload, hf_token, base_model_to_use], outputs=[success_message_upload, result], queue=False) #Button to convert the model to ckpt format convert_button.click(fn=convert_to_ckpt, inputs=[], outputs=result, queue=False) #Checks if the training is running 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)
demo.queue(default_enabled=False).launch(debug=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302# Script for converting a HF Diffusers saved pipeline to a Stable Diffusion checkpoint.# *Only* converts the UNet, VAE, and Text Encoder.# Does not convert optimizer state or any other thing.
import argparseimport os.path as ospimport re
import torchimport gc
# =================## UNet Conversion ## =================#
unet_conversion_map = [ # (stable-diffusion, HF Diffusers) ("time_embed.0.weight", "time_embedding.linear_1.weight"), ("time_embed.0.bias", "time_embedding.linear_1.bias"), ("time_embed.2.weight", "time_embedding.linear_2.weight"), ("time_embed.2.bias", "time_embedding.linear_2.bias"), ("input_blocks.0.0.weight", "conv_in.weight"), ("input_blocks.0.0.bias", "conv_in.bias"), ("out.0.weight", "conv_norm_out.weight"), ("out.0.bias", "conv_norm_out.bias"), ("out.2.weight", "conv_out.weight"), ("out.2.bias", "conv_out.bias"),]
unet_conversion_map_resnet = [ # (stable-diffusion, HF Diffusers) ("in_layers.0", "norm1"), ("in_layers.2", "conv1"), ("out_layers.0", "norm2"), ("out_layers.3", "conv2"), ("emb_layers.1", "time_emb_proj"), ("skip_connection", "conv_shortcut"),]
unet_conversion_map_layer = []# hardcoded number of downblocks and resnets/attentions...# would need smarter logic for other networks.for i in range(4): # loop over downblocks/upblocks
for j in range(2): # loop over resnets/attentions for downblocks hf_down_res_prefix = f"down_blocks.{i}.resnets.{j}." sd_down_res_prefix = f"input_blocks.{3*i + j + 1}.0." unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))
if i < 3: # no attention layers in down_blocks.3 hf_down_atn_prefix = f"down_blocks.{i}.attentions.{j}." sd_down_atn_prefix = f"input_blocks.{3*i + j + 1}.1." unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))
for j in range(3): # loop over resnets/attentions for upblocks hf_up_res_prefix = f"up_blocks.{i}.resnets.{j}." sd_up_res_prefix = f"output_blocks.{3*i + j}.0." unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))
if i > 0: # no attention layers in up_blocks.0 hf_up_atn_prefix = f"up_blocks.{i}.attentions.{j}." sd_up_atn_prefix = f"output_blocks.{3*i + j}.1." unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))
if i < 3: # no downsample in down_blocks.3 hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0.conv." sd_downsample_prefix = f"input_blocks.{3*(i+1)}.0.op." unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))
# no upsample in up_blocks.3 hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0." sd_upsample_prefix = f"output_blocks.{3*i + 2}.{1 if i == 0 else 2}." unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))
hf_mid_atn_prefix = "mid_block.attentions.0."sd_mid_atn_prefix = "middle_block.1."unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))
for j in range(2): hf_mid_res_prefix = f"mid_block.resnets.{j}." sd_mid_res_prefix = f"middle_block.{2*j}." unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))
def convert_unet_state_dict(unet_state_dict): # buyer beware: this is a *brittle* function, # and correct output requires that all of these pieces interact in # the exact order in which I have arranged them. mapping = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: mapping[hf_name] = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: v = v.replace(hf_part, sd_part) mapping[k] = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: v = v.replace(hf_part, sd_part) mapping[k] = v new_state_dict = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict
# ================## VAE Conversion ## ================#
vae_conversion_map = [ # (stable-diffusion, HF Diffusers) ("nin_shortcut", "conv_shortcut"), ("norm_out", "conv_norm_out"), ("mid.attn_1.", "mid_block.attentions.0."),]
for i in range(4): # down_blocks have two resnets for j in range(2): hf_down_prefix = f"encoder.down_blocks.{i}.resnets.{j}." sd_down_prefix = f"encoder.down.{i}.block.{j}." vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
if i < 3: hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0." sd_downsample_prefix = f"down.{i}.downsample." vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0." sd_upsample_prefix = f"up.{3-i}.upsample." vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
# up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): hf_up_prefix = f"decoder.up_blocks.{i}.resnets.{j}." sd_up_prefix = f"decoder.up.{3-i}.block.{j}." vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
# this part accounts for mid blocks in both the encoder and the decoderfor i in range(2): hf_mid_res_prefix = f"mid_block.resnets.{i}." sd_mid_res_prefix = f"mid.block_{i+1}." vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
vae_conversion_map_attn = [ # (stable-diffusion, HF Diffusers) ("norm.", "group_norm."), ("q.", "query."), ("k.", "key."), ("v.", "value."), ("proj_out.", "proj_attn."),]
def reshape_weight_for_sd(w): # convert HF linear weights to SD conv2d weights return w.reshape(*w.shape, 1, 1)
def convert_vae_state_dict(vae_state_dict): mapping = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: v = v.replace(hf_part, sd_part) mapping[k] = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: v = v.replace(hf_part, sd_part) mapping[k] = v new_state_dict = {v: vae_state_dict[k] for k, v in mapping.items()} weights_to_convert = ["q", "k", "v", "proj_out"] print("Converting to CKPT ...") for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f"mid.attn_1.{weight_name}.weight" in k: print(f"Reshaping {k} for SD format") new_state_dict[k] = reshape_weight_for_sd(v) return new_state_dict
# =========================## Text Encoder Conversion ## =========================#
textenc_conversion_lst = [ # (stable-diffusion, HF Diffusers) ("resblocks.", "text_model.encoder.layers."), ("ln_1", "layer_norm1"), ("ln_2", "layer_norm2"), (".c_fc.", ".fc1."), (".c_proj.", ".fc2."), (".attn", ".self_attn"), ("ln_final.", "transformer.text_model.final_layer_norm."), ("token_embedding.weight", "transformer.text_model.embeddings.token_embedding.weight"), ("positional_embedding", "transformer.text_model.embeddings.position_embedding.weight"),]protected = {re.escape(x[1]): x[0] for x in textenc_conversion_lst}textenc_pattern = re.compile("|".join(protected.keys()))
# Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cppcode2idx = {"q": 0, "k": 1, "v": 2}
def convert_text_enc_state_dict_v20(text_enc_dict): new_state_dict = {} capture_qkv_weight = {} capture_qkv_bias = {} for k, v in text_enc_dict.items(): if ( k.endswith(".self_attn.q_proj.weight") or k.endswith(".self_attn.k_proj.weight") or k.endswith(".self_attn.v_proj.weight") ): k_pre = k[: -len(".q_proj.weight")] k_code = k[-len("q_proj.weight")] if k_pre not in capture_qkv_weight: capture_qkv_weight[k_pre] = [None, None, None] capture_qkv_weight[k_pre][code2idx[k_code]] = v continue
if ( k.endswith(".self_attn.q_proj.bias") or k.endswith(".self_attn.k_proj.bias") or k.endswith(".self_attn.v_proj.bias") ): k_pre = k[: -len(".q_proj.bias")] k_code = k[-len("q_proj.bias")] if k_pre not in capture_qkv_bias: capture_qkv_bias[k_pre] = [None, None, None] capture_qkv_bias[k_pre][code2idx[k_code]] = v continue
relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k) new_state_dict[relabelled_key] = v
for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing") relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre) new_state_dict[relabelled_key + ".in_proj_weight"] = torch.cat(tensors)
for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing") relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre) new_state_dict[relabelled_key + ".in_proj_bias"] = torch.cat(tensors)
return new_state_dict
def convert_text_enc_state_dict(text_enc_dict): return text_enc_dict
def convert(model_path, checkpoint_path): unet_path = osp.join(model_path, "unet", "diffusion_pytorch_model.bin") vae_path = osp.join(model_path, "vae", "diffusion_pytorch_model.bin") text_enc_path = osp.join(model_path, "text_encoder", "pytorch_model.bin")
# Convert the UNet model unet_state_dict = torch.load(unet_path, map_location="cpu") unet_state_dict = convert_unet_state_dict(unet_state_dict) unet_state_dict = {"model.diffusion_model." + k: v for k, v in unet_state_dict.items()}
# Convert the VAE model vae_state_dict = torch.load(vae_path, map_location="cpu") vae_state_dict = convert_vae_state_dict(vae_state_dict) vae_state_dict = {"first_stage_model." + k: v for k, v in vae_state_dict.items()}
# Convert the text encoder model text_enc_dict = torch.load(text_enc_path, map_location="cpu")
# Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper is_v20_model = "text_model.encoder.layers.22.layer_norm2.bias" in text_enc_dict
if is_v20_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm text_enc_dict = {"transformer." + k: v for k, v in text_enc_dict.items()} text_enc_dict = convert_text_enc_state_dict_v20(text_enc_dict) text_enc_dict = {"cond_stage_model.model." + k: v for k, v in text_enc_dict.items()} else: text_enc_dict = convert_text_enc_state_dict(text_enc_dict) text_enc_dict = {"cond_stage_model.transformer." + k: v for k, v in text_enc_dict.items()}
# Put together new checkpoint state_dict = {**unet_state_dict, **vae_state_dict, **text_enc_dict} state_dict = {k: v.half() for k, v in state_dict.items()} state_dict = {"state_dict": state_dict} torch.save(state_dict, checkpoint_path) del state_dict, text_enc_dict, vae_state_dict, unet_state_dict torch.cuda.empty_cache() gc.collect() 123version https://git-lfs.github.com/spec/v1oid sha256:09207c4e95fcf5296eb0ff708fdc672da960aeb2864d298810db5094b072a0d4size 280226531234567891011121314151617181920212223242526272829303132{ "_class_name": "StableDiffusionPipeline", "_diffusers_version": "0.6.0", "feature_extractor": [ "transformers", "CLIPFeatureExtractor" ], "safety_checker": [ "stable_diffusion", "StableDiffusionSafetyChecker" ], "scheduler": [ "diffusers", "PNDMScheduler" ], "text_encoder": [ "transformers", "CLIPTextModel" ], "tokenizer": [ "transformers", "CLIPTokenizer" ], "unet": [ "diffusers", "UNet2DConditionModel" ], "vae": [ "diffusers", "AutoencoderKL" ]}123456789101112131415161718--extra-index-url https://download.pytorch.org/whl/cu113torch==1.12.1+cu113torchvision==0.13.1+cu113diffusers==0.9.0accelerate==0.12.0OmegaConfwgetpytorch_lightninghuggingface_hubftfytransformerspyfiglettriton==2.0.0.dev20220701bitsandbytespython-slugifyrequeststensorboardpip install git+https://github.com/facebookresearch/xformers@7e4c02c#egg=xformers1234567891011121314151617--extra-index-url https://download.pytorch.org/whl/cu113torch==1.12.1+cu113torchvision==0.13.1+cu113diffusers==0.11.1accelerate==0.12.0OmegaConfwgetpytorch_lightninghuggingface_hubftfytransformers==4.25.1pyfiglettriton==2.0.0.dev20221030bitsandbytes==0.35.4python-slugifyrequeststensorboard123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889import argparseimport itertoolsimport mathimport osfrom pathlib import Pathfrom typing import Optionalimport subprocessimport sysimport gcimport random
import torchimport torch.nn.functional as Fimport torch.utils.checkpointfrom torch.utils.data import Dataset
from accelerate import Acceleratorfrom accelerate.logging import get_loggerfrom accelerate.utils import set_seedfrom diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionPipeline, UNet2DConditionModelfrom diffusers.utils.import_utils import is_xformers_availablefrom diffusers.optimization import get_schedulerfrom huggingface_hub import HfFolder, Repository, whoamifrom PIL import Imagefrom torchvision import transformsfrom tqdm.auto import tqdmfrom transformers import CLIPTextModel, CLIPTokenizer
logger = get_logger(__name__)
def parse_args(): parser = argparse.ArgumentParser(description="Simple example of a training script.") parser.add_argument( "--pretrained_model_name_or_path", type=str, default=None, #required=True, help="Path to pretrained model or model identifier from huggingface.co/models.", ) parser.add_argument( "--tokenizer_name", type=str, default=None, help="Pretrained tokenizer name or path if not the same as model_name", ) parser.add_argument( "--instance_data_dir", type=str, default=None, #required=True, help="A folder containing the training data of instance images.", ) parser.add_argument( "--class_data_dir", type=str, default=None, #required=False, help="A folder containing the training data of class images.", ) parser.add_argument( "--instance_prompt", type=str, default=None, help="The prompt with identifier specifying the instance", ) parser.add_argument( "--class_prompt", type=str, default="", help="The prompt to specify images in the same class as provided instance images.", ) parser.add_argument( "--with_prior_preservation", default=False, action="store_true", help="Flag to add prior preservation loss.", ) parser.add_argument("--prior_loss_weight", type=float, default=1.0, help="The weight of prior preservation loss.") parser.add_argument( "--num_class_images", type=int, default=100, help=( "Minimal class images for prior preservation loss. If not have enough images, additional images will be" " sampled with class_prompt." ), ) parser.add_argument( "--output_dir", type=str, default="", help="The output directory where the model predictions and checkpoints will be written.", ) parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.") parser.add_argument( "--resolution", type=int, default=512, help=( "The resolution for input images, all the images in the train/validation dataset will be resized to this" " resolution" ), ) parser.add_argument( "--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution" ) parser.add_argument("--train_text_encoder", action="store_true", help="Whether to train the text encoder") parser.add_argument( "--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader." ) parser.add_argument( "--sample_batch_size", type=int, default=4, help="Batch size (per device) for sampling images." ) parser.add_argument("--num_train_epochs", type=int, default=1) parser.add_argument( "--max_train_steps", type=int, default=None, help="Total number of training steps to perform. If provided, overrides num_train_epochs.", ) parser.add_argument( "--gradient_accumulation_steps", type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.", ) parser.add_argument( "--gradient_checkpointing", action="store_true", help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.", ) parser.add_argument( "--learning_rate", type=float, default=5e-6, help="Initial learning rate (after the potential warmup period) to use.", ) parser.add_argument( "--scale_lr", action="store_true", default=False, help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.", ) parser.add_argument( "--lr_scheduler", type=str, default="constant", help=( 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",' ' "constant", "constant_with_warmup"]' ), ) parser.add_argument( "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler." ) parser.add_argument( "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes." ) parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.") parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.") parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.") parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer") parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.") parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.") parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.") parser.add_argument( "--hub_model_id", type=str, default=None, help="The name of the repository to keep in sync with the local `output_dir`.", ) parser.add_argument( "--logging_dir", type=str, default="logs", help=( "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to" " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***." ), ) parser.add_argument( "--mixed_precision", type=str, default="no", choices=["no", "fp16", "bf16"], help=( "Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." ), )
parser.add_argument( "--save_n_steps", type=int, default=1, help=("Save the model every n global_steps"), ) parser.add_argument( "--save_starting_step", type=int, default=1, help=("The step from which it starts saving intermediary checkpoints"), ) parser.add_argument( "--stop_text_encoder_training", type=int, default=1000000, help=("The step at which the text_encoder is no longer trained"), )
parser.add_argument( "--image_captions_filename", action="store_true", help="Get captions from filename", ) parser.add_argument( "--dump_only_text_encoder", action="store_true", default=False, help="Dump only text encoder", )
parser.add_argument( "--train_only_unet", action="store_true", default=False, help="Train only the unet", ) parser.add_argument( "--cache_latents", action="store_true", default=False, help="Train only the unet", ) parser.add_argument( "--Session_dir", type=str, default="", help="Current session directory", )
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
args = parser.parse_args() env_local_rank = int(os.environ.get("LOCAL_RANK", -1)) if env_local_rank != -1 and env_local_rank != args.local_rank: args.local_rank = env_local_rank
#if args.instance_data_dir is None: # raise ValueError("You must specify a train data directory.")
#if args.with_prior_preservation: # if args.class_data_dir is None: # raise ValueError("You must specify a data directory for class images.") # if args.class_prompt is None: # raise ValueError("You must specify prompt for class images.")
return args
class DreamBoothDataset(Dataset): """ A dataset to prepare the instance and class images with the prompts for fine-tuning the model. It pre-processes the images and the tokenizes prompts. """
def __init__( self, instance_data_root, instance_prompt, tokenizer, args, class_data_root=None, class_prompt=None, size=512, center_crop=False, ): self.size = size self.center_crop = center_crop self.tokenizer = tokenizer self.image_captions_filename = None
self.instance_data_root = Path(instance_data_root) if not self.instance_data_root.exists(): raise ValueError("Instance images root doesn't exists.")
self.instance_images_path = list(Path(instance_data_root).iterdir()) self.num_instance_images = len(self.instance_images_path) self.instance_prompt = instance_prompt self._length = self.num_instance_images
if args.image_captions_filename: self.image_captions_filename = True if class_data_root is not None: self.class_data_root = Path(class_data_root) self.class_data_root.mkdir(parents=True, exist_ok=True) self.class_images_path = list(self.class_data_root.iterdir()) random.shuffle(self.class_images_path) self.num_class_images = len(self.class_images_path) self._length = max(self.num_class_images, self.num_instance_images) self.class_prompt = class_prompt else: self.class_data_root = None
self.image_transforms = transforms.Compose( [ transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR), transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] )
def __len__(self): return self._length
def __getitem__(self, index): example = {} path = self.instance_images_path[index % self.num_instance_images] instance_image = Image.open(path) if not instance_image.mode == "RGB": instance_image = instance_image.convert("RGB") instance_prompt = self.instance_prompt if self.image_captions_filename: filename = Path(path).stem pt=''.join([i for i in filename if not i.isdigit()]) pt=pt.replace("_"," ") pt=pt.replace("(","") pt=pt.replace(")","") pt=pt.replace("-","") instance_prompt = pt sys.stdout.write(" [0;32m" +instance_prompt+" [0m") sys.stdout.flush()
example["instance_images"] = self.image_transforms(instance_image) example["instance_prompt_ids"] = self.tokenizer( instance_prompt, padding="do_not_pad", truncation=True, max_length=self.tokenizer.model_max_length, ).input_ids
if self.class_data_root: class_image = Image.open(self.class_images_path[index % self.num_class_images]) if not class_image.mode == "RGB": class_image = class_image.convert("RGB") example["class_images"] = self.image_transforms(class_image) example["class_prompt_ids"] = self.tokenizer( self.class_prompt, padding="do_not_pad", truncation=True, max_length=self.tokenizer.model_max_length, ).input_ids
return example
class PromptDataset(Dataset): "A simple dataset to prepare the prompts to generate class images on multiple GPUs."
def __init__(self, prompt, num_samples): self.prompt = prompt self.num_samples = num_samples
def __len__(self): return self.num_samples
def __getitem__(self, index): example = {} example["prompt"] = self.prompt example["index"] = index return example
class LatentsDataset(Dataset): def __init__(self, latents_cache, text_encoder_cache): self.latents_cache = latents_cache self.text_encoder_cache = text_encoder_cache
def __len__(self): return len(self.latents_cache)
def __getitem__(self, index): return self.latents_cache[index], self.text_encoder_cache[index]
def get_full_repo_name(model_id: str, organization: Optional[str] = None, token: Optional[str] = None): if token is None: token = HfFolder.get_token() if organization is None: username = whoami(token)["name"] return f"{username}/{model_id}" else: return f"{organization}/{model_id}"
def merge_two_dicts(starting_dict: dict, updater_dict: dict) -> dict: """ Starts from base starting dict and then adds the remaining key values from updater replacing the values from the first starting/base dict with the second updater dict.
For later: how does d = {**d1, **d2} replace collision?
:param starting_dict: :param updater_dict: :return: """ new_dict: dict = starting_dict.copy() # start with keys and values of starting_dict new_dict.update(updater_dict) # modifies starting_dict with keys and values of updater_dict return new_dict
def merge_args(args1: argparse.Namespace, args2: argparse.Namespace) -> argparse.Namespace: """
ref: https://stackoverflow.com/questions/56136549/how-can-i-merge-two-argparse-namespaces-in-python-2-x :param args1: :param args2: :return: """ # - the merged args # The vars() function returns the __dict__ attribute to values of the given object e.g {field:value}. merged_key_values_for_namespace: dict = merge_two_dicts(vars(args1), vars(args2)) args = argparse.Namespace(**merged_key_values_for_namespace) return args
def run_training(args_imported): args_default = parse_args() args = merge_args(args_default, args_imported) print(args) logging_dir = Path(args.output_dir, args.logging_dir) i=args.save_starting_step accelerator = Accelerator( gradient_accumulation_steps=args.gradient_accumulation_steps, mixed_precision=args.mixed_precision, log_with="tensorboard", logging_dir=logging_dir, )
# Currently, it's not possible to do gradient accumulation when training two models with accelerate.accumulate # This will be enabled soon in accelerate. For now, we don't allow gradient accumulation when training two models. # TODO (patil-suraj): Remove this check when gradient accumulation with two models is enabled in accelerate. if args.train_text_encoder and args.gradient_accumulation_steps > 1 and accelerator.num_processes > 1: raise ValueError( "Gradient accumulation is not supported when training the text encoder in distributed training. " "Please set gradient_accumulation_steps to 1. This feature will be supported in the future." )
if args.seed is not None: set_seed(args.seed)
if args.with_prior_preservation: class_images_dir = Path(args.class_data_dir) if not class_images_dir.exists(): class_images_dir.mkdir(parents=True) cur_class_images = len(list(class_images_dir.iterdir()))
if cur_class_images < args.num_class_images: torch_dtype = torch.float16 if accelerator.device.type == "cuda" else torch.float32 pipeline = StableDiffusionPipeline.from_pretrained( args.pretrained_model_name_or_path, torch_dtype=torch_dtype ) pipeline.set_progress_bar_config(disable=True)
num_new_images = args.num_class_images - cur_class_images logger.info(f"Number of class images to sample: {num_new_images}.")
sample_dataset = PromptDataset(args.class_prompt, num_new_images) sample_dataloader = torch.utils.data.DataLoader(sample_dataset, batch_size=args.sample_batch_size)
sample_dataloader = accelerator.prepare(sample_dataloader) pipeline.to(accelerator.device)
for example in tqdm( sample_dataloader, desc="Generating class images", disable=not accelerator.is_local_main_process ): with torch.autocast("cuda"): images = pipeline(example["prompt"]).images
for i, image in enumerate(images): image.save(class_images_dir / f"{example['index'][i] + cur_class_images}.jpg")
del pipeline if torch.cuda.is_available(): torch.cuda.empty_cache()
# Handle the repository creation if accelerator.is_main_process: if args.push_to_hub: if args.hub_model_id is None: repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token) else: repo_name = args.hub_model_id repo = Repository(args.output_dir, clone_from=repo_name)
with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore: if "step_*" not in gitignore: gitignore.write("step_*\n") if "epoch_*" not in gitignore: gitignore.write("epoch_*\n") elif args.output_dir is not None: os.makedirs(args.output_dir, exist_ok=True)
# Load the tokenizer if args.tokenizer_name: tokenizer = CLIPTokenizer.from_pretrained(args.tokenizer_name) elif args.pretrained_model_name_or_path: tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
# Load models and create wrapper for stable diffusion if args.train_only_unet: if os.path.exists(str(args.output_dir+"/text_encoder_trained")): text_encoder = CLIPTextModel.from_pretrained(args.output_dir, subfolder="text_encoder_trained") elif os.path.exists(str(args.output_dir+"/text_encoder")): text_encoder = CLIPTextModel.from_pretrained(args.output_dir, subfolder="text_encoder") else: text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder") else: text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder") vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae") unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet") if is_xformers_available(): try: print("Enabling memory efficient attention with xformers...") unet.enable_xformers_memory_efficient_attention() except Exception as e: logger.warning( f"Could not enable memory efficient attention. Make sure xformers is installed correctly and a GPU is available: {e}" ) vae.requires_grad_(False) if not args.train_text_encoder: text_encoder.requires_grad_(False)
if args.gradient_checkpointing: unet.enable_gradient_checkpointing() if args.train_text_encoder: text_encoder.gradient_checkpointing_enable()
if args.scale_lr: args.learning_rate = ( args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes )
# Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs if args.use_8bit_adam: try: import bitsandbytes as bnb except ImportError: raise ImportError( "To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`." )
optimizer_class = bnb.optim.AdamW8bit else: optimizer_class = torch.optim.AdamW
params_to_optimize = ( itertools.chain(unet.parameters(), text_encoder.parameters()) if args.train_text_encoder else unet.parameters() ) optimizer = optimizer_class( params_to_optimize, lr=args.learning_rate, betas=(args.adam_beta1, args.adam_beta2), weight_decay=args.adam_weight_decay, eps=args.adam_epsilon, )
noise_scheduler = DDPMScheduler.from_config(args.pretrained_model_name_or_path, subfolder="scheduler")
train_dataset = DreamBoothDataset( instance_data_root=args.instance_data_dir, instance_prompt=args.instance_prompt, class_data_root=args.class_data_dir if args.with_prior_preservation else None, class_prompt=args.class_prompt, tokenizer=tokenizer, size=args.resolution, center_crop=args.center_crop, args=args, )
def collate_fn(examples): input_ids = [example["instance_prompt_ids"] for example in examples] pixel_values = [example["instance_images"] for example in examples]
# Concat class and instance examples for prior preservation. # We do this to avoid doing two forward passes. if args.with_prior_preservation: input_ids += [example["class_prompt_ids"] for example in examples] pixel_values += [example["class_images"] for example in examples]
pixel_values = torch.stack(pixel_values) pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
input_ids = tokenizer.pad({"input_ids": input_ids}, padding=True, return_tensors="pt").input_ids
batch = { "input_ids": input_ids, "pixel_values": pixel_values, } return batch
train_dataloader = torch.utils.data.DataLoader( train_dataset, batch_size=args.train_batch_size, shuffle=True, collate_fn=collate_fn )
# Scheduler and math around the number of training steps. overrode_max_train_steps = False num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps) if args.max_train_steps is None: args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch overrode_max_train_steps = True
lr_scheduler = get_scheduler( args.lr_scheduler, optimizer=optimizer, num_warmup_steps=args.lr_warmup_steps * args.gradient_accumulation_steps, num_training_steps=args.max_train_steps * args.gradient_accumulation_steps, )
if args.train_text_encoder: unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare( unet, text_encoder, optimizer, train_dataloader, lr_scheduler ) else: unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare( unet, optimizer, train_dataloader, lr_scheduler )
weight_dtype = torch.float32 if args.mixed_precision == "fp16": weight_dtype = torch.float16 elif args.mixed_precision == "bf16": weight_dtype = torch.bfloat16
# Move text_encode and vae to gpu. # For mixed precision training we cast the text_encoder and vae weights to half-precision # as these models are only used for inference, keeping weights in full precision is not required. vae.to(accelerator.device, dtype=weight_dtype) if not args.train_text_encoder: text_encoder.to(accelerator.device, dtype=weight_dtype)
if args.cache_latents: latents_cache = [] text_encoder_cache = [] for batch in tqdm(train_dataloader, desc="Caching latents"): with torch.no_grad(): batch["pixel_values"] = batch["pixel_values"].to(accelerator.device, non_blocking=True, dtype=weight_dtype) batch["input_ids"] = batch["input_ids"].to(accelerator.device, non_blocking=True) latents_cache.append(vae.encode(batch["pixel_values"]).latent_dist) if args.train_text_encoder: text_encoder_cache.append(batch["input_ids"]) else: text_encoder_cache.append(text_encoder(batch["input_ids"])[0]) train_dataset = LatentsDataset(latents_cache, text_encoder_cache) train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=1, collate_fn=lambda x: x, shuffle=True)
del vae #if not args.train_text_encoder: # del text_encoder if torch.cuda.is_available(): torch.cuda.empty_cache()
# We need to recalculate our total training steps as the size of the training dataloader may have changed. num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps) if overrode_max_train_steps: args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch # Afterwards we recalculate our number of training epochs args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
# We need to initialize the trackers we use, and also store our configuration. # The trackers initializes automatically on the main process. if accelerator.is_main_process: accelerator.init_trackers("dreambooth", config=vars(args))
def bar(prg): br='|'+'█' * prg + ' ' * (25-prg)+'|' return br
# Train! total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
logger.info("***** Running training *****") logger.info(f" Num examples = {len(train_dataset)}") logger.info(f" Num batches each epoch = {len(train_dataloader)}") logger.info(f" Num Epochs = {args.num_train_epochs}") logger.info(f" Instantaneous batch size per device = {args.train_batch_size}") logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}") logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}") logger.info(f" Total optimization steps = {args.max_train_steps}") # Only show the progress bar once on each machine. progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process) global_step = 0
for epoch in range(args.num_train_epochs): unet.train() if args.train_text_encoder: text_encoder.train() for step, batch in enumerate(train_dataloader): with accelerator.accumulate(unet): # Convert images to latent space with torch.no_grad(): if args.cache_latents: latents_dist = batch[0][0] else: latents_dist = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist latents = latents_dist.sample() * 0.18215
# Sample noise that we'll add to the latents noise = torch.randn_like(latents) bsz = latents.shape[0] # Sample a random timestep for each image timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device) timesteps = timesteps.long()
# Add noise to the latents according to the noise magnitude at each timestep # (this is the forward diffusion process) noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
# Get the text embedding for conditioning if(args.cache_latents): if args.train_text_encoder: encoder_hidden_states = text_encoder(batch[0][1])[0] else: encoder_hidden_states = batch[0][1] else: encoder_hidden_states = text_encoder(batch["input_ids"])[0]
# Predict the noise residual model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample # Get the target for loss depending on the prediction type if noise_scheduler.config.prediction_type == "epsilon": target = noise elif noise_scheduler.config.prediction_type == "v_prediction": target = noise_scheduler.get_velocity(latents, noise, timesteps) else: raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}") if args.with_prior_preservation: # Chunk the noise and model_pred into two parts and compute the loss on each part separately. model_pred, model_pred_prior = torch.chunk(model_pred, 2, dim=0) target, target_prior = torch.chunk(target, 2, dim=0)
# Compute instance loss loss = F.mse_loss(model_pred.float(), target.float(), reduction="none").mean([1, 2, 3]).mean()
# Compute prior loss prior_loss = F.mse_loss(model_pred_prior.float(), target_prior.float(), reduction="mean")
# Add the prior loss to the instance loss. loss = loss + args.prior_loss_weight * prior_loss else: loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
accelerator.backward(loss) if accelerator.sync_gradients: params_to_clip = ( itertools.chain(unet.parameters(), text_encoder.parameters()) if args.train_text_encoder else unet.parameters() ) accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm) optimizer.step() lr_scheduler.step() optimizer.zero_grad()
# Checks if the accelerator has performed an optimization step behind the scenes if accelerator.sync_gradients: progress_bar.update(1) global_step += 1
fll=round((global_step*100)/args.max_train_steps) fll=round(fll/4) pr=bar(fll) logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]} progress_bar.set_postfix(**logs) progress_bar.set_description_str("Progress:"+pr) accelerator.log(logs, step=global_step)
if global_step >= args.max_train_steps: break
if args.train_text_encoder and global_step == args.stop_text_encoder_training and global_step >= 30: if accelerator.is_main_process: print(" [0;32m" +" Freezing the text_encoder ..."+" [0m") frz_dir=args.output_dir + "/text_encoder_frozen" if os.path.exists(frz_dir): subprocess.call('rm -r '+ frz_dir, shell=True) os.mkdir(frz_dir) pipeline = StableDiffusionPipeline.from_pretrained( args.pretrained_model_name_or_path, unet=accelerator.unwrap_model(unet), text_encoder=accelerator.unwrap_model(text_encoder), ) pipeline.text_encoder.save_pretrained(frz_dir) if args.save_n_steps >= 200: if global_step < args.max_train_steps and global_step+1==i: ckpt_name = "_step_" + str(global_step+1) save_dir = Path(args.output_dir+ckpt_name) save_dir=str(save_dir) save_dir=save_dir.replace(" ", "_") if not os.path.exists(save_dir): os.mkdir(save_dir) inst=save_dir[16:] inst=inst.replace(" ", "_") print(" [1;32mSAVING CHECKPOINT: "+args.Session_dir+"/"+inst+".ckpt") # Create the pipeline using the trained modules and save it. if accelerator.is_main_process: pipeline = StableDiffusionPipeline.from_pretrained( args.pretrained_model_name_or_path, unet=accelerator.unwrap_model(unet), text_encoder=accelerator.unwrap_model(text_encoder), ) pipeline.save_pretrained(save_dir) frz_dir=args.output_dir + "/text_encoder_frozen" if args.train_text_encoder and os.path.exists(frz_dir): subprocess.call('rm -r '+save_dir+'/text_encoder/*.*', shell=True) subprocess.call('cp -f '+frz_dir +'/*.* '+ save_dir+'/text_encoder', shell=True) chkpth=args.Session_dir+"/"+inst+".ckpt" subprocess.call('python /content/diffusers/scripts/convert_diffusers_to_original_stable_diffusion.py --model_path ' + save_dir + ' --checkpoint_path ' + chkpth + ' --half', shell=True) subprocess.call('rm -r '+ save_dir, shell=True) i=i+args.save_n_steps accelerator.wait_for_everyone()
# Create the pipeline using using the trained modules and save it. if accelerator.is_main_process: if args.dump_only_text_encoder: txt_dir=args.output_dir + "/text_encoder_trained" if not os.path.exists(txt_dir): os.mkdir(txt_dir) pipeline = StableDiffusionPipeline.from_pretrained( args.pretrained_model_name_or_path, unet=accelerator.unwrap_model(unet), text_encoder=accelerator.unwrap_model(text_encoder), ) pipeline.text_encoder.save_pretrained(txt_dir)
elif args.train_only_unet: pipeline = StableDiffusionPipeline.from_pretrained( args.pretrained_model_name_or_path, unet=accelerator.unwrap_model(unet), text_encoder=accelerator.unwrap_model(text_encoder), ) pipeline.save_pretrained(args.output_dir) txt_dir=args.output_dir + "/text_encoder_trained" subprocess.call('rm -r '+txt_dir, shell=True) else: pipeline = StableDiffusionPipeline.from_pretrained( args.pretrained_model_name_or_path, unet=accelerator.unwrap_model(unet), text_encoder=accelerator.unwrap_model(text_encoder), ) frz_dir=args.output_dir + "/text_encoder_frozen" pipeline.save_pretrained(args.output_dir) if args.train_text_encoder and os.path.exists(frz_dir): subprocess.call('mv -f '+frz_dir +'/*.* '+ args.output_dir+'/text_encoder', shell=True) subprocess.call('rm -r '+ frz_dir, shell=True)
if args.push_to_hub: repo.push_to_hub(commit_message="End of training", blocking=False, auto_lfs_prune=True)
accelerator.end_training() del pipeline torch.cuda.empty_cache() gc.collect()if __name__ == "__main__": pass #main()
.gitattributesAdded+35
.gitignoreAdded+7
README.mdAdded+15
app.pyAdded+687
arrow.pngAdded

cat-toy-deprec.pngAdded

cat-toy.pngAdded

cattoy.pngAdded

convertosd.pyAdded+302
duplicate.pngAdded

mix.zipAdded+3
model_index.jsonAdded+32
person.pngAdded

requirements-local.txtAdded+18
requirements.txtAdded+17
train_dreambooth.pyAdded+889
trsl_style.pngAdded
