comdoleger commited on
Commit
8fd160d
·
verified ·
1 Parent(s): 633f6dc

Upload flux_train_ui.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. flux_train_ui.py +414 -0
flux_train_ui.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from huggingface_hub import whoami
3
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
4
+ import sys
5
+
6
+ # Add the current working directory to the Python path
7
+ sys.path.insert(0, os.getcwd())
8
+
9
+ import gradio as gr
10
+ from PIL import Image
11
+ import torch
12
+ import uuid
13
+ import os
14
+ import shutil
15
+ import json
16
+ import yaml
17
+ from slugify import slugify
18
+ from transformers import AutoProcessor, AutoModelForCausalLM
19
+
20
+ sys.path.insert(0, "ai-toolkit")
21
+ from toolkit.job import get_job
22
+
23
+ MAX_IMAGES = 150
24
+
25
+ def load_captioning(uploaded_files, concept_sentence):
26
+ uploaded_images = [file for file in uploaded_files if not file.endswith('.txt')]
27
+ txt_files = [file for file in uploaded_files if file.endswith('.txt')]
28
+ txt_files_dict = {os.path.splitext(os.path.basename(txt_file))[0]: txt_file for txt_file in txt_files}
29
+ updates = []
30
+ if len(uploaded_images) <= 1:
31
+ raise gr.Error(
32
+ "Please upload at least 2 images to train your model (the ideal number with default settings is between 4-30)"
33
+ )
34
+ elif len(uploaded_images) > MAX_IMAGES:
35
+ raise gr.Error(f"For now, only {MAX_IMAGES} or less images are allowed for training")
36
+ # Update for the captioning_area
37
+ # for _ in range(3):
38
+ updates.append(gr.update(visible=True))
39
+ # Update visibility and image for each captioning row and image
40
+ for i in range(1, MAX_IMAGES + 1):
41
+ # Determine if the current row and image should be visible
42
+ visible = i <= len(uploaded_images)
43
+
44
+ # Update visibility of the captioning row
45
+ updates.append(gr.update(visible=visible))
46
+
47
+ # Update for image component - display image if available, otherwise hide
48
+ image_value = uploaded_images[i - 1] if visible else None
49
+ updates.append(gr.update(value=image_value, visible=visible))
50
+
51
+ corresponding_caption = False
52
+ if(image_value):
53
+ base_name = os.path.splitext(os.path.basename(image_value))[0]
54
+ print(base_name)
55
+ print(image_value)
56
+ if base_name in txt_files_dict:
57
+ print("entrou")
58
+ with open(txt_files_dict[base_name], 'r') as file:
59
+ corresponding_caption = file.read()
60
+
61
+ # Update value of captioning area
62
+ text_value = corresponding_caption if visible and corresponding_caption else "[trigger]" if visible and concept_sentence else None
63
+ updates.append(gr.update(value=text_value, visible=visible))
64
+
65
+ # Update for the sample caption area
66
+ updates.append(gr.update(visible=True))
67
+ # Update prompt samples
68
+ updates.append(gr.update(placeholder=f'A portrait of person in a bustling cafe {concept_sentence}', value=f'A person in a bustling cafe {concept_sentence}'))
69
+ updates.append(gr.update(placeholder=f"A mountainous landscape in the style of {concept_sentence}"))
70
+ updates.append(gr.update(placeholder=f"A {concept_sentence} in a mall"))
71
+ updates.append(gr.update(visible=True))
72
+ return updates
73
+
74
+ def hide_captioning():
75
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
76
+
77
+ def create_dataset(*inputs):
78
+ print("Creating dataset")
79
+ images = inputs[0]
80
+ destination_folder = str(f"datasets/{uuid.uuid4()}")
81
+ if not os.path.exists(destination_folder):
82
+ os.makedirs(destination_folder)
83
+
84
+ jsonl_file_path = os.path.join(destination_folder, "metadata.jsonl")
85
+ with open(jsonl_file_path, "a") as jsonl_file:
86
+ for index, image in enumerate(images):
87
+ new_image_path = shutil.copy(image, destination_folder)
88
+
89
+ original_caption = inputs[index + 1]
90
+ file_name = os.path.basename(new_image_path)
91
+
92
+ data = {"file_name": file_name, "prompt": original_caption}
93
+
94
+ jsonl_file.write(json.dumps(data) + "\n")
95
+
96
+ return destination_folder
97
+
98
+
99
+ def run_captioning(images, concept_sentence, *captions):
100
+ #Load internally to not consume resources for training
101
+ device = "cuda" if torch.cuda.is_available() else "cpu"
102
+ torch_dtype = torch.float16
103
+ model = AutoModelForCausalLM.from_pretrained(
104
+ "multimodalart/Florence-2-large-no-flash-attn", torch_dtype=torch_dtype, trust_remote_code=True
105
+ ).to(device)
106
+ processor = AutoProcessor.from_pretrained("multimodalart/Florence-2-large-no-flash-attn", trust_remote_code=True)
107
+
108
+ captions = list(captions)
109
+ for i, image_path in enumerate(images):
110
+ print(captions[i])
111
+ if isinstance(image_path, str): # If image is a file path
112
+ image = Image.open(image_path).convert("RGB")
113
+
114
+ prompt = "<DETAILED_CAPTION>"
115
+ inputs = processor(text=prompt, images=image, return_tensors="pt").to(device, torch_dtype)
116
+
117
+ generated_ids = model.generate(
118
+ input_ids=inputs["input_ids"], pixel_values=inputs["pixel_values"], max_new_tokens=1024, num_beams=3
119
+ )
120
+
121
+ generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
122
+ parsed_answer = processor.post_process_generation(
123
+ generated_text, task=prompt, image_size=(image.width, image.height)
124
+ )
125
+ caption_text = parsed_answer["<DETAILED_CAPTION>"].replace("The image shows ", "")
126
+ if concept_sentence:
127
+ caption_text = f"{caption_text} [trigger]"
128
+ captions[i] = caption_text
129
+
130
+ yield captions
131
+ model.to("cpu")
132
+ del model
133
+ del processor
134
+
135
+ def recursive_update(d, u):
136
+ for k, v in u.items():
137
+ if isinstance(v, dict) and v:
138
+ d[k] = recursive_update(d.get(k, {}), v)
139
+ else:
140
+ d[k] = v
141
+ return d
142
+
143
+ def start_training(
144
+ lora_name,
145
+ concept_sentence,
146
+ steps,
147
+ lr,
148
+ rank,
149
+ model_to_train,
150
+ low_vram,
151
+ dataset_folder,
152
+ sample_1,
153
+ sample_2,
154
+ sample_3,
155
+ use_more_advanced_options,
156
+ more_advanced_options,
157
+ ):
158
+ push_to_hub = True
159
+ if not lora_name:
160
+ raise gr.Error("You forgot to insert your LoRA name! This name has to be unique.")
161
+ try:
162
+ if whoami()["auth"]["accessToken"]["role"] == "write" or "repo.write" in whoami()["auth"]["accessToken"]["fineGrained"]["scoped"][0]["permissions"]:
163
+ gr.Info(f"Starting training locally {whoami()['name']}. Your LoRA will be available locally and in Hugging Face after it finishes.")
164
+ else:
165
+ push_to_hub = False
166
+ gr.Warning("Started training locally. Your LoRa will only be available locally because you didn't login with a `write` token to Hugging Face")
167
+ except:
168
+ push_to_hub = False
169
+ gr.Warning("Started training locally. Your LoRa will only be available locally because you didn't login with a `write` token to Hugging Face")
170
+
171
+ print("Started training")
172
+ slugged_lora_name = slugify(lora_name)
173
+
174
+ # Load the default config
175
+ with open("config/examples/train_lora_flux_24gb.yaml", "r") as f:
176
+ config = yaml.safe_load(f)
177
+
178
+ # Update the config with user inputs
179
+ config["config"]["name"] = slugged_lora_name
180
+ config["config"]["process"][0]["model"]["low_vram"] = low_vram
181
+ config["config"]["process"][0]["train"]["skip_first_sample"] = True
182
+ config["config"]["process"][0]["train"]["steps"] = int(steps)
183
+ config["config"]["process"][0]["train"]["lr"] = float(lr)
184
+ config["config"]["process"][0]["network"]["linear"] = int(rank)
185
+ config["config"]["process"][0]["network"]["linear_alpha"] = int(rank)
186
+ config["config"]["process"][0]["datasets"][0]["folder_path"] = dataset_folder
187
+ config["config"]["process"][0]["save"]["push_to_hub"] = push_to_hub
188
+ if(push_to_hub):
189
+ try:
190
+ username = whoami()["name"]
191
+ except:
192
+ raise gr.Error("Error trying to retrieve your username. Are you sure you are logged in with Hugging Face?")
193
+ config["config"]["process"][0]["save"]["hf_repo_id"] = f"{username}/{slugged_lora_name}"
194
+ config["config"]["process"][0]["save"]["hf_private"] = True
195
+ if concept_sentence:
196
+ config["config"]["process"][0]["trigger_word"] = concept_sentence
197
+
198
+ if sample_1 or sample_2 or sample_3:
199
+ config["config"]["process"][0]["train"]["disable_sampling"] = False
200
+ config["config"]["process"][0]["sample"]["sample_every"] = steps
201
+ config["config"]["process"][0]["sample"]["sample_steps"] = 28
202
+ config["config"]["process"][0]["sample"]["prompts"] = []
203
+ if sample_1:
204
+ config["config"]["process"][0]["sample"]["prompts"].append(sample_1)
205
+ if sample_2:
206
+ config["config"]["process"][0]["sample"]["prompts"].append(sample_2)
207
+ if sample_3:
208
+ config["config"]["process"][0]["sample"]["prompts"].append(sample_3)
209
+ else:
210
+ config["config"]["process"][0]["train"]["disable_sampling"] = True
211
+ if(model_to_train == "schnell"):
212
+ config["config"]["process"][0]["model"]["name_or_path"] = "black-forest-labs/FLUX.1-schnell"
213
+ config["config"]["process"][0]["model"]["assistant_lora_path"] = "ostris/FLUX.1-schnell-training-adapter"
214
+ config["config"]["process"][0]["sample"]["sample_steps"] = 4
215
+ if(use_more_advanced_options):
216
+ more_advanced_options_dict = yaml.safe_load(more_advanced_options)
217
+ config["config"]["process"][0] = recursive_update(config["config"]["process"][0], more_advanced_options_dict)
218
+ print(config)
219
+
220
+ # Save the updated config
221
+ # generate a random name for the config
222
+ random_config_name = str(uuid.uuid4())
223
+ os.makedirs("tmp", exist_ok=True)
224
+ config_path = f"tmp/{random_config_name}-{slugged_lora_name}.yaml"
225
+ with open(config_path, "w") as f:
226
+ yaml.dump(config, f)
227
+
228
+ # run the job locally
229
+ job = get_job(config_path)
230
+ job.run()
231
+ job.cleanup()
232
+
233
+ return f"Training completed successfully. Model saved as {slugged_lora_name}"
234
+
235
+ config_yaml = '''
236
+ device: cuda:0
237
+ model:
238
+ is_flux: true
239
+ quantize: true
240
+ network:
241
+ linear: 16 #it will overcome the 'rank' parameter
242
+ linear_alpha: 16 #you can have an alpha different than the ranking if you'd like
243
+ type: lora
244
+ sample:
245
+ guidance_scale: 3.5
246
+ height: 1024
247
+ neg: '' #doesn't work for FLUX
248
+ sample_every: 1000
249
+ sample_steps: 28
250
+ sampler: flowmatch
251
+ seed: 42
252
+ walk_seed: true
253
+ width: 1024
254
+ save:
255
+ dtype: float16
256
+ hf_private: true
257
+ max_step_saves_to_keep: 4
258
+ push_to_hub: true
259
+ save_every: 10000
260
+ train:
261
+ batch_size: 1
262
+ dtype: bf16
263
+ ema_config:
264
+ ema_decay: 0.99
265
+ use_ema: true
266
+ gradient_accumulation_steps: 1
267
+ gradient_checkpointing: true
268
+ noise_scheduler: flowmatch
269
+ optimizer: adamw8bit #options: prodigy, dadaptation, adamw, adamw8bit, lion, lion8bit
270
+ train_text_encoder: false #probably doesn't work for flux
271
+ train_unet: true
272
+ '''
273
+
274
+ theme = gr.themes.Monochrome(
275
+ text_size=gr.themes.Size(lg="18px", md="15px", sm="13px", xl="22px", xs="12px", xxl="24px", xxs="9px"),
276
+ font=[gr.themes.GoogleFont("Source Sans Pro"), "ui-sans-serif", "system-ui", "sans-serif"],
277
+ )
278
+ css = """
279
+ h1{font-size: 2em}
280
+ h3{margin-top: 0}
281
+ #component-1{text-align:center}
282
+ .main_ui_logged_out{opacity: 0.3; pointer-events: none}
283
+ .tabitem{border: 0px}
284
+ .group_padding{padding: .55em}
285
+ """
286
+ with gr.Blocks(theme=theme, css=css) as demo:
287
+ gr.Markdown(
288
+ """# LoRA Ease for FLUX 🧞‍♂️
289
+ ### Train a high quality FLUX LoRA in a breeze ༄ using [Ostris' AI Toolkit](https://github.com/ostris/ai-toolkit)"""
290
+ )
291
+ with gr.Column() as main_ui:
292
+ with gr.Row():
293
+ lora_name = gr.Textbox(
294
+ label="The name of your LoRA",
295
+ info="This has to be a unique name",
296
+ placeholder="e.g.: Persian Miniature Painting style, Cat Toy",
297
+ )
298
+ concept_sentence = gr.Textbox(
299
+ label="Trigger word/sentence",
300
+ info="Trigger word or sentence to be used",
301
+ placeholder="uncommon word like p3rs0n or trtcrd, or sentence like 'in the style of CNSTLL'",
302
+ interactive=True,
303
+ )
304
+ with gr.Group(visible=True) as image_upload:
305
+ with gr.Row():
306
+ images = gr.File(
307
+ file_types=["image", ".txt"],
308
+ label="Upload your images",
309
+ file_count="multiple",
310
+ interactive=True,
311
+ visible=True,
312
+ scale=1,
313
+ )
314
+ with gr.Column(scale=3, visible=False) as captioning_area:
315
+ with gr.Column():
316
+ gr.Markdown(
317
+ """# Custom captioning
318
+ <p style="margin-top:0">You can optionally add a custom caption for each image (or use an AI model for this). [trigger] will represent your concept sentence/trigger word.</p>
319
+ """, elem_classes="group_padding")
320
+ do_captioning = gr.Button("Add AI captions with Florence-2")
321
+ output_components = [captioning_area]
322
+ caption_list = []
323
+ for i in range(1, MAX_IMAGES + 1):
324
+ locals()[f"captioning_row_{i}"] = gr.Row(visible=False)
325
+ with locals()[f"captioning_row_{i}"]:
326
+ locals()[f"image_{i}"] = gr.Image(
327
+ type="filepath",
328
+ width=111,
329
+ height=111,
330
+ min_width=111,
331
+ interactive=False,
332
+ scale=2,
333
+ show_label=False,
334
+ show_share_button=False,
335
+ show_download_button=False,
336
+ )
337
+ locals()[f"caption_{i}"] = gr.Textbox(
338
+ label=f"Caption {i}", scale=15, interactive=True
339
+ )
340
+
341
+ output_components.append(locals()[f"captioning_row_{i}"])
342
+ output_components.append(locals()[f"image_{i}"])
343
+ output_components.append(locals()[f"caption_{i}"])
344
+ caption_list.append(locals()[f"caption_{i}"])
345
+
346
+ with gr.Accordion("Advanced options", open=False):
347
+ steps = gr.Number(label="Steps", value=1000, minimum=1, maximum=10000, step=1)
348
+ lr = gr.Number(label="Learning Rate", value=4e-4, minimum=1e-6, maximum=1e-3, step=1e-6)
349
+ rank = gr.Number(label="LoRA Rank", value=16, minimum=4, maximum=128, step=4)
350
+ model_to_train = gr.Radio(["dev", "schnell"], value="dev", label="Model to train")
351
+ low_vram = gr.Checkbox(label="Low VRAM", value=True)
352
+ with gr.Accordion("Even more advanced options", open=False):
353
+ use_more_advanced_options = gr.Checkbox(label="Use more advanced options", value=False)
354
+ more_advanced_options = gr.Code(config_yaml, language="yaml")
355
+
356
+ with gr.Accordion("Sample prompts (optional)", visible=False) as sample:
357
+ gr.Markdown(
358
+ "Include sample prompts to test out your trained model. Don't forget to include your trigger word/sentence (optional)"
359
+ )
360
+ sample_1 = gr.Textbox(label="Test prompt 1")
361
+ sample_2 = gr.Textbox(label="Test prompt 2")
362
+ sample_3 = gr.Textbox(label="Test prompt 3")
363
+
364
+ output_components.append(sample)
365
+ output_components.append(sample_1)
366
+ output_components.append(sample_2)
367
+ output_components.append(sample_3)
368
+ start = gr.Button("Start training", visible=False)
369
+ output_components.append(start)
370
+ progress_area = gr.Markdown("")
371
+
372
+ dataset_folder = gr.State()
373
+
374
+ images.upload(
375
+ load_captioning,
376
+ inputs=[images, concept_sentence],
377
+ outputs=output_components
378
+ )
379
+
380
+ images.delete(
381
+ load_captioning,
382
+ inputs=[images, concept_sentence],
383
+ outputs=output_components
384
+ )
385
+
386
+ images.clear(
387
+ hide_captioning,
388
+ outputs=[captioning_area, sample, start]
389
+ )
390
+
391
+ start.click(fn=create_dataset, inputs=[images] + caption_list, outputs=dataset_folder).then(
392
+ fn=start_training,
393
+ inputs=[
394
+ lora_name,
395
+ concept_sentence,
396
+ steps,
397
+ lr,
398
+ rank,
399
+ model_to_train,
400
+ low_vram,
401
+ dataset_folder,
402
+ sample_1,
403
+ sample_2,
404
+ sample_3,
405
+ use_more_advanced_options,
406
+ more_advanced_options
407
+ ],
408
+ outputs=progress_area,
409
+ )
410
+
411
+ do_captioning.click(fn=run_captioning, inputs=[images, concept_sentence] + caption_list, outputs=caption_list)
412
+
413
+ if __name__ == "__main__":
414
+ demo.launch(share=True, show_error=True)