ClaireOzzz commited on
Commit
6cc3d67
1 Parent(s): 8e4a774

added app_train.py

Browse files
Files changed (1) hide show
  1. app_train.py +389 -0
app_train.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import os
4
+ import shutil
5
+ import requests
6
+ import subprocess
7
+ from subprocess import getoutput
8
+ from huggingface_hub import login, HfFileSystem, snapshot_download, HfApi, create_repo
9
+
10
+ is_gpu_associated = torch.cuda.is_available()
11
+
12
+ is_shared_ui = False
13
+
14
+ hf_token = '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'
15
+
16
+ fs = HfFileSystem(token=hf_token)
17
+ api = HfApi()
18
+
19
+ if is_gpu_associated:
20
+ gpu_info = getoutput('nvidia-smi')
21
+ if("A10G" in gpu_info):
22
+ which_gpu = "A10G"
23
+ elif("T4" in gpu_info):
24
+ which_gpu = "T4"
25
+ else:
26
+ which_gpu = "CPU"
27
+
28
+ def check_upload_or_no(value):
29
+ if value is True:
30
+ return gr.update(visible=True)
31
+ else:
32
+ return gr.update(visible=False)
33
+
34
+ def load_images_to_dataset(images, dataset_name):
35
+
36
+ if is_shared_ui:
37
+ raise gr.Error("This Space only works in duplicated instances")
38
+
39
+ if dataset_name == "":
40
+ raise gr.Error("You forgot to name your new dataset. ")
41
+
42
+ # Create the directory if it doesn't exist
43
+ my_working_directory = f"my_working_directory_for_{dataset_name}"
44
+ if not os.path.exists(my_working_directory):
45
+ os.makedirs(my_working_directory)
46
+
47
+ # Assuming 'images' is a list of image file paths
48
+ for idx, image in enumerate(images):
49
+ # Get the base file name (without path) from the original location
50
+ image_name = os.path.basename(image.name)
51
+
52
+ # Construct the destination path in the working directory
53
+ destination_path = os.path.join(my_working_directory, image_name)
54
+
55
+ # Copy the image from the original location to the working directory
56
+ shutil.copy(image.name, destination_path)
57
+
58
+ # Print the image name and its corresponding save path
59
+ print(f"Image {idx + 1}: {image_name} copied to {destination_path}")
60
+
61
+ path_to_folder = my_working_directory
62
+ your_username = api.whoami(token=hf_token)["name"]
63
+ repo_id = f"{your_username}/{dataset_name}"
64
+ create_repo(repo_id=repo_id, repo_type="dataset", token=hf_token)
65
+
66
+ api.upload_folder(
67
+ folder_path=path_to_folder,
68
+ repo_id=repo_id,
69
+ repo_type="dataset",
70
+ token=hf_token
71
+ )
72
+
73
+ return "Done, your dataset is ready and loaded for the training step!", repo_id
74
+
75
+ def swap_hardware(hf_token, hardware="cpu-basic"):
76
+ hardware_url = f"https://huggingface.co/spaces/ClaireOzzz/train-dreambooth-lora-sdxl/hardware"
77
+ headers = { "authorization" : f"Bearer {hf_token}"}
78
+ body = {'flavor': hardware}
79
+ requests.post(hardware_url, json = body, headers=headers)
80
+
81
+ def swap_sleep_time(hf_token,sleep_time):
82
+ sleep_time_url = f"https://huggingface.co/api/spaces/ClaireOzzz/train-dreambooth-lora-sdxl/sleeptime"
83
+ headers = { "authorization" : f"Bearer {hf_token}"}
84
+ body = {'seconds':sleep_time}
85
+ requests.post(sleep_time_url,json=body,headers=headers)
86
+
87
+ def get_sleep_time(hf_token):
88
+ sleep_time_url = f"https://huggingface.co/api/spaces/ClaireOzzz/train-dreambooth-lora-sdxl"
89
+ headers = { "authorization" : f"Bearer {hf_token}"}
90
+ response = requests.get(sleep_time_url,headers=headers)
91
+ try:
92
+ gcTimeout = response.json()['runtime']['gcTimeout']
93
+ except:
94
+ gcTimeout = None
95
+ return gcTimeout
96
+
97
+ def write_to_community(title, description,hf_token):
98
+
99
+ api.create_discussion(repo_id=os.environ['ClaireOzzz/train-dreambooth-lora-sdxl'], title=title, description=description,repo_type="space", token=hf_token)
100
+
101
+
102
+ def set_accelerate_default_config():
103
+ try:
104
+ subprocess.run(["accelerate", "config", "default"], check=True)
105
+ print("Accelerate default config set successfully!")
106
+ except subprocess.CalledProcessError as e:
107
+ print(f"An error occurred: {e}")
108
+
109
+ def train_dreambooth_lora_sdxl(dataset_id, instance_data_dir, lora_trained_xl_folder, instance_prompt, max_train_steps, checkpoint_steps, remove_gpu):
110
+
111
+ script_filename = "train_dreambooth_lora_sdxl.py" # Assuming it's in the same folder
112
+
113
+ command = [
114
+ "accelerate",
115
+ "launch",
116
+ script_filename, # Use the local script
117
+ "--pretrained_model_name_or_path=stabilityai/stable-diffusion-xl-base-1.0",
118
+ "--pretrained_vae_model_name_or_path=madebyollin/sdxl-vae-fp16-fix",
119
+ f"--dataset_id={dataset_id}",
120
+ f"--instance_data_dir={instance_data_dir}",
121
+ f"--output_dir={lora_trained_xl_folder}",
122
+ "--mixed_precision=fp16",
123
+ f"--instance_prompt={instance_prompt}",
124
+ "--resolution=1024",
125
+ "--train_batch_size=2",
126
+ "--gradient_accumulation_steps=2",
127
+ "--gradient_checkpointing",
128
+ "--learning_rate=1e-4",
129
+ "--lr_scheduler=constant",
130
+ "--lr_warmup_steps=0",
131
+ "--enable_xformers_memory_efficient_attention",
132
+ "--mixed_precision=fp16",
133
+ "--use_8bit_adam",
134
+ f"--max_train_steps={max_train_steps}",
135
+ f"--checkpointing_steps={checkpoint_steps}",
136
+ "--seed=0",
137
+ "--push_to_hub",
138
+ f"--hub_token={hf_token}"
139
+ ]
140
+
141
+ try:
142
+ subprocess.run(command, check=True)
143
+ print("Training is finished!")
144
+ if remove_gpu:
145
+ swap_hardware(hf_token, "cpu-basic")
146
+ else:
147
+ swap_sleep_time(hf_token, 300)
148
+ except subprocess.CalledProcessError as e:
149
+ print(f"An error occurred: {e}")
150
+
151
+ title="There was an error on during your training"
152
+ description=f'''
153
+ Unfortunately there was an error during training your {lora_trained_xl_folder} model.
154
+ Please check it out below. Feel free to report this issue to [SD-XL Dreambooth LoRa Training](https://huggingface.co/spaces/fffiloni/train-dreambooth-lora-sdxl):
155
+ ```
156
+ {str(e)}
157
+ ```
158
+ '''
159
+ if remove_gpu:
160
+ swap_hardware(hf_token, "cpu-basic")
161
+ else:
162
+ swap_sleep_time(hf_token, 300)
163
+ #write_to_community(title,description,hf_token)
164
+
165
+ def main(dataset_id,
166
+ lora_trained_xl_folder,
167
+ instance_prompt,
168
+ max_train_steps,
169
+ checkpoint_steps,
170
+ remove_gpu):
171
+
172
+
173
+ if is_shared_ui:
174
+ raise gr.Error("This Space only works in duplicated instances")
175
+
176
+ if not is_gpu_associated:
177
+ raise gr.Error("Please associate a T4 or A10G GPU for this Space")
178
+
179
+ if dataset_id == "":
180
+ raise gr.Error("You forgot to specify an image dataset")
181
+
182
+ if instance_prompt == "":
183
+ raise gr.Error("You forgot to specify a concept prompt")
184
+
185
+ if lora_trained_xl_folder == "":
186
+ raise gr.Error("You forgot to name the output folder for your model")
187
+
188
+ sleep_time = get_sleep_time(hf_token)
189
+ if sleep_time:
190
+ swap_sleep_time(hf_token, -1)
191
+
192
+ gr.Warning("If you did not check the `Remove GPU After training`, don't forget to remove the GPU attribution after you are done. ")
193
+
194
+ dataset_repo = dataset_id
195
+
196
+ # Automatically set local_dir based on the last part of dataset_repo
197
+ repo_parts = dataset_repo.split("/")
198
+ local_dir = f"./{repo_parts[-1]}" # Use the last part of the split
199
+
200
+ # Check if the directory exists and create it if necessary
201
+ if not os.path.exists(local_dir):
202
+ os.makedirs(local_dir)
203
+
204
+ gr.Info("Downloading dataset ...")
205
+
206
+ snapshot_download(
207
+ dataset_repo,
208
+ local_dir=local_dir,
209
+ repo_type="dataset",
210
+ ignore_patterns=".gitattributes",
211
+ token=hf_token
212
+ )
213
+
214
+ set_accelerate_default_config()
215
+
216
+ gr.Info("Training begins ...")
217
+
218
+ instance_data_dir = repo_parts[-1]
219
+ train_dreambooth_lora_sdxl(dataset_id, instance_data_dir, lora_trained_xl_folder, instance_prompt, max_train_steps, checkpoint_steps, remove_gpu)
220
+
221
+ your_username = api.whoami(token=hf_token)["name"]
222
+ return f"Done, your trained model has been stored in your models library: {your_username}/{lora_trained_xl_folder}"
223
+
224
+ css="""
225
+ #col-container {max-width: 780px; margin-left: auto; margin-right: auto;}
226
+ #upl-dataset-group {background-color: none!important;}
227
+
228
+ div#warning-ready {
229
+ background-color: #ecfdf5;
230
+ padding: 0 10px 5px;
231
+ margin: 20px 0;
232
+ }
233
+ div#warning-ready > .gr-prose > h2, div#warning-ready > .gr-prose > p {
234
+ color: #057857!important;
235
+ }
236
+
237
+ div#warning-duplicate {
238
+ background-color: #ebf5ff;
239
+ padding: 0 10px 5px;
240
+ margin: 20px 0;
241
+ }
242
+
243
+ div#warning-duplicate > .gr-prose > h2, div#warning-duplicate > .gr-prose > p {
244
+ color: #0f4592!important;
245
+ }
246
+
247
+ div#warning-duplicate strong {
248
+ color: #0f4592;
249
+ }
250
+
251
+ p.actions {
252
+ display: flex;
253
+ align-items: center;
254
+ margin: 20px 0;
255
+ }
256
+
257
+ div#warning-duplicate .actions a {
258
+ display: inline-block;
259
+ margin-right: 10px;
260
+ }
261
+
262
+ div#warning-setgpu {
263
+ background-color: #fff4eb;
264
+ padding: 0 10px 5px;
265
+ margin: 20px 0;
266
+ }
267
+
268
+ div#warning-setgpu > .gr-prose > h2, div#warning-setgpu > .gr-prose > p {
269
+ color: #92220f!important;
270
+ }
271
+
272
+ div#warning-setgpu a, div#warning-setgpu b {
273
+ color: #91230f;
274
+ }
275
+
276
+ div#warning-setgpu p.actions > a {
277
+ display: inline-block;
278
+ background: #1f1f23;
279
+ border-radius: 40px;
280
+ padding: 6px 24px;
281
+ color: antiquewhite;
282
+ text-decoration: none;
283
+ font-weight: 600;
284
+ font-size: 1.2em;
285
+ }
286
+
287
+ button#load-dataset-btn{
288
+ min-height: 60px;
289
+ }
290
+ """
291
+ def create_training_demo() -> gr.Blocks:
292
+ with gr.Blocks(css=css) as demo:
293
+ with gr.Column(elem_id="col-container"):
294
+ if is_shared_ui:
295
+ top_description = gr.HTML(f'''
296
+ <div class="gr-prose">
297
+ <h2><svg xmlns="http://www.w3.org/2000/svg" width="18px" height="18px" style="margin-right: 0px;display: inline-block;"fill="none"><path fill="#fff" d="M7 13.2a6.3 6.3 0 0 0 4.4-10.7A6.3 6.3 0 0 0 .6 6.9 6.3 6.3 0 0 0 7 13.2Z"/><path fill="#fff" fill-rule="evenodd" d="M7 0a6.9 6.9 0 0 1 4.8 11.8A6.9 6.9 0 0 1 0 7 6.9 6.9 0 0 1 7 0Zm0 0v.7V0ZM0 7h.6H0Zm7 6.8v-.6.6ZM13.7 7h-.6.6ZM9.1 1.7c-.7-.3-1.4-.4-2.2-.4a5.6 5.6 0 0 0-4 1.6 5.6 5.6 0 0 0-1.6 4 5.6 5.6 0 0 0 1.6 4 5.6 5.6 0 0 0 4 1.7 5.6 5.6 0 0 0 4-1.7 5.6 5.6 0 0 0 1.7-4 5.6 5.6 0 0 0-1.7-4c-.5-.5-1.1-.9-1.8-1.2Z" clip-rule="evenodd"/><path fill="#000" fill-rule="evenodd" d="M7 2.9a.8.8 0 1 1 0 1.5A.8.8 0 0 1 7 3ZM5.8 5.7c0-.4.3-.6.6-.6h.7c.3 0 .6.2.6.6v3.7h.5a.6.6 0 0 1 0 1.3H6a.6.6 0 0 1 0-1.3h.4v-3a.6.6 0 0 1-.6-.7Z" clip-rule="evenodd"/></svg>
298
+ Attention: this Space need to be duplicated to work</h2>
299
+ <p class="main-message">
300
+ To make it work, <strong>duplicate the Space</strong> and run it on your own profile using a <strong>private</strong> GPU (T4-small or A10G-small).<br />
301
+ A T4 costs <strong>US$0.60/h</strong>, so it should cost < US$1 to train most models.
302
+ </p>
303
+ <p class="actions">
304
+
305
+ to start training your own image model
306
+ </p>
307
+ </div>
308
+ ''', elem_id="warning-duplicate")
309
+ # else:
310
+ # if(is_gpu_associated):
311
+ # top_description = gr.HTML(f'''
312
+ # <div class="gr-prose">
313
+ # <h2><svg xmlns="http://www.w3.org/2000/svg" width="18px" height="18px" style="margin-right: 0px;display: inline-block;"fill="none"><path fill="#fff" d="M7 13.2a6.3 6.3 0 0 0 4.4-10.7A6.3 6.3 0 0 0 .6 6.9 6.3 6.3 0 0 0 7 13.2Z"/><path fill="#fff" fill-rule="evenodd" d="M7 0a6.9 6.9 0 0 1 4.8 11.8A6.9 6.9 0 0 1 0 7 6.9 6.9 0 0 1 7 0Zm0 0v.7V0ZM0 7h.6H0Zm7 6.8v-.6.6ZM13.7 7h-.6.6ZM9.1 1.7c-.7-.3-1.4-.4-2.2-.4a5.6 5.6 0 0 0-4 1.6 5.6 5.6 0 0 0-1.6 4 5.6 5.6 0 0 0 1.6 4 5.6 5.6 0 0 0 4 1.7 5.6 5.6 0 0 0 4-1.7 5.6 5.6 0 0 0 1.7-4 5.6 5.6 0 0 0-1.7-4c-.5-.5-1.1-.9-1.8-1.2Z" clip-rule="evenodd"/><path fill="#000" fill-rule="evenodd" d="M7 2.9a.8.8 0 1 1 0 1.5A.8.8 0 0 1 7 3ZM5.8 5.7c0-.4.3-.6.6-.6h.7c.3 0 .6.2.6.6v3.7h.5a.6.6 0 0 1 0 1.3H6a.6.6 0 0 1 0-1.3h.4v-3a.6.6 0 0 1-.6-.7Z" clip-rule="evenodd"/></svg>
314
+ # You have successfully associated a {which_gpu} GPU to the SD-XL Training Space 🎉</h2>
315
+ # <p>
316
+ # You can now train your model! You will be billed by the minute from when you activated the GPU until when it is turned off.
317
+ # </p>
318
+ # </div>
319
+ # ''', elem_id="warning-ready")
320
+ # else:
321
+ # top_description = gr.HTML(f'''
322
+ # <div class="gr-prose">
323
+ # <h2><svg xmlns="http://www.w3.org/2000/svg" width="18px" height="18px" style="margin-right: 0px;display: inline-block;"fill="none"><path fill="#fff" d="M7 13.2a6.3 6.3 0 0 0 4.4-10.7A6.3 6.3 0 0 0 .6 6.9 6.3 6.3 0 0 0 7 13.2Z"/><path fill="#fff" fill-rule="evenodd" d="M7 0a6.9 6.9 0 0 1 4.8 11.8A6.9 6.9 0 0 1 0 7 6.9 6.9 0 0 1 7 0Zm0 0v.7V0ZM0 7h.6H0Zm7 6.8v-.6.6ZM13.7 7h-.6.6ZM9.1 1.7c-.7-.3-1.4-.4-2.2-.4a5.6 5.6 0 0 0-4 1.6 5.6 5.6 0 0 0-1.6 4 5.6 5.6 0 0 0 1.6 4 5.6 5.6 0 0 0 4 1.7 5.6 5.6 0 0 0 4-1.7 5.6 5.6 0 0 0 1.7-4 5.6 5.6 0 0 0-1.7-4c-.5-.5-1.1-.9-1.8-1.2Z" clip-rule="evenodd"/><path fill="#000" fill-rule="evenodd" d="M7 2.9a.8.8 0 1 1 0 1.5A.8.8 0 0 1 7 3ZM5.8 5.7c0-.4.3-.6.6-.6h.7c.3 0 .6.2.6.6v3.7h.5a.6.6 0 0 1 0 1.3H6a.6.6 0 0 1 0-1.3h.4v-3a.6.6 0 0 1-.6-.7Z" clip-rule="evenodd"/></svg>
324
+ # You have successfully duplicated the SD-XL Training Space 🎉</h2>
325
+ # <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.
326
+ # You will be billed by the minute from when you activate the GPU until when it is turned off.</p>
327
+ # <p class="actions">
328
+ # <a href="https://huggingface.co/spaces/ClaireOzzz/train-dreambooth-lora-sdxl/settings">🔥 &nbsp; Set recommended GPU</a>
329
+ # </p>
330
+ # </div>
331
+ # ''', elem_id="warning-setgpu")
332
+
333
+ gr.Markdown("# SD-XL Dreambooth LoRa Training UI 💭")
334
+
335
+ upload_my_images = gr.Checkbox(label="Drop your training images ? (optional)", value=False)
336
+ gr.Markdown("Use this step to upload your training images and create a new dataset. If you already have a dataset stored on your HF profile, you can skip this step, and provide your dataset ID in the training `Datased ID` input below.")
337
+
338
+ with gr.Group(visible=False, elem_id="upl-dataset-group") as upload_group:
339
+ with gr.Row():
340
+ images = gr.File(file_types=["image"], label="Upload your images", file_count="multiple", interactive=True, visible=True)
341
+ with gr.Column():
342
+ new_dataset_name = gr.Textbox(label="Set new dataset name", placeholder="e.g.: my_awesome_dataset")
343
+ dataset_status = gr.Textbox(label="dataset status")
344
+ load_btn = gr.Button("Load images to new dataset", elem_id="load-dataset-btn")
345
+
346
+ gr.Markdown("## Training ")
347
+ gr.Markdown("You can use an existing image dataset, find a dataset example here: [https://huggingface.co/datasets/diffusers/dog-example](https://huggingface.co/datasets/diffusers/dog-example) ;)")
348
+
349
+ with gr.Row():
350
+ dataset_id = gr.Textbox(label="Dataset ID", info="use one of your previously uploaded image datasets on your HF profile", placeholder="diffusers/dog-example")
351
+ instance_prompt = gr.Textbox(label="Concept prompt", info="concept prompt - use a unique, made up word to avoid collisions")
352
+
353
+ with gr.Row():
354
+ model_output_folder = gr.Textbox(label="Output model folder name", placeholder="lora-trained-xl-folder")
355
+ max_train_steps = gr.Number(label="Max Training Steps", value=500, precision=0, step=10)
356
+ checkpoint_steps = gr.Number(label="Checkpoints Steps", value=100, precision=0, step=10)
357
+
358
+ remove_gpu = gr.Checkbox(label="Remove GPU After Training", value=True, info="If NOT enabled, don't forget to remove the GPU attribution after you are done.")
359
+ train_button = gr.Button("Train !")
360
+
361
+ train_status = gr.Textbox(label="Training status")
362
+
363
+ upload_my_images.change(
364
+ fn = check_upload_or_no,
365
+ inputs =[upload_my_images],
366
+ outputs = [upload_group]
367
+ )
368
+
369
+ load_btn.click(
370
+ fn = load_images_to_dataset,
371
+ inputs = [images, new_dataset_name],
372
+ outputs = [dataset_status, dataset_id]
373
+ )
374
+
375
+ train_button.click(
376
+ fn = main,
377
+ inputs = [
378
+ dataset_id,
379
+ model_output_folder,
380
+ instance_prompt,
381
+ max_train_steps,
382
+ checkpoint_steps,
383
+ remove_gpu
384
+ ],
385
+ outputs = [train_status]
386
+ )
387
+ return demo
388
+
389
+ #demo.launch(debug=True, share=True)