File size: 12,770 Bytes
1ba389d
 
 
 
 
b60af16
 
1ba389d
 
b60af16
1ba389d
b60af16
 
 
1ba389d
 
b60af16
1ba389d
 
 
 
 
 
 
 
b60af16
1ba389d
b60af16
1ba389d
b60af16
 
 
1ba389d
 
b60af16
1ba389d
 
b60af16
 
1ba389d
b60af16
1ba389d
 
 
 
b60af16
1ba389d
b60af16
 
 
 
 
 
 
 
1ba389d
 
 
b60af16
1ba389d
b60af16
 
 
1ba389d
 
 
 
 
b60af16
1ba389d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b60af16
1ba389d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b60af16
1ba389d
 
b60af16
1ba389d
 
b60af16
1ba389d
 
b60af16
 
1ba389d
 
 
 
 
 
 
 
 
 
 
 
 
 
b60af16
1ba389d
 
 
b60af16
1ba389d
 
 
 
b60af16
1ba389d
 
 
 
 
 
 
 
 
 
 
 
 
b60af16
1ba389d
 
 
b60af16
1ba389d
 
b60af16
1ba389d
 
 
 
 
b60af16
1ba389d
 
 
 
 
 
 
 
 
 
 
 
b60af16
 
1ba389d
 
 
 
b60af16
1ba389d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b60af16
 
1ba389d
 
 
b60af16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ba389d
 
b60af16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
import os
import uuid
import shutil
import json
import yaml
import torch
from PIL import Image
from slugify import slugify
from transformers import AutoProcessor, AutoModelForCausalLM
import pinggy as pg

# Ensure the current working directory is in sys.path
import sys
sys.path.insert(0, os.getcwd())
sys.path.insert(0, "ai-toolkit")
from toolkit.job import get_job
from huggingface_hub import whoami

MAX_IMAGES = 150

def load_captioning(uploaded_files, concept_sentence):
    uploaded_images = [file for file in uploaded_files if not file.endswith('.txt')]
    txt_files = [file for file in uploaded_files if file.endswith('.txt')]
    txt_files_dict = {os.path.splitext(os.path.basename(txt_file))[0]: txt_file for txt_file in txt_files}
    updates = []

    if len(uploaded_images) <= 1:
        raise pg.Error("Please upload at least 2 images to train your model (the ideal number with default settings is between 4-30)")
    elif len(uploaded_images) > MAX_IMAGES:
        raise pg.Error(f"For now, only {MAX_IMAGES} or less images are allowed for training")

    updates.append(pg.Update(visible=True))
    for i in range(1, MAX_IMAGES + 1):
        visible = i <= len(uploaded_images)
        updates.append(pg.Update(visible=visible))

        image_value = uploaded_images[i - 1] if visible else None
        updates.append(pg.Update(value=image_value, visible=visible))

        corresponding_caption = False
        if image_value:
            base_name = os.path.splitext(os.path.basename(image_value))[0]
            if base_name in txt_files_dict:
                with open(txt_files_dict[base_name], 'r') as file:
                    corresponding_caption = file.read()

        text_value = corresponding_caption if visible and corresponding_caption else "[trigger]" if visible and concept_sentence else None
        updates.append(pg.Update(value=text_value, visible=visible))

    updates.append(pg.Update(visible=True))
    updates.append(pg.Update(placeholder=f'A portrait of person in a bustling cafe {concept_sentence}', value=f'A person in a bustling cafe {concept_sentence}'))
    updates.append(pg.Update(placeholder=f"A mountainous landscape in the style of {concept_sentence}"))
    updates.append(pg.Update(placeholder=f"A {concept_sentence} in a mall"))
    updates.append(pg.Update(visible=True))

    return updates

def hide_captioning():
    return pg.Update(visible=False), pg.Update(visible=False), pg.Update(visible=False) 

def create_dataset(images, *captions):
    destination_folder = f"datasets/{uuid.uuid4()}"
    os.makedirs(destination_folder, exist_ok=True)

    jsonl_file_path = os.path.join(destination_folder, "metadata.jsonl")
    with open(jsonl_file_path, "a") as jsonl_file:
        for index, image in enumerate(images):
            new_image_path = shutil.copy(image, destination_folder)
            original_caption = captions[index]
            file_name = os.path.basename(new_image_path)
            data = {"file_name": file_name, "prompt": original_caption}
            jsonl_file.write(json.dumps(data) + "\n")

    return destination_folder

def run_captioning(images, concept_sentence, *captions):
    device = "cuda" if torch.cuda.is_available() else "cpu"
    torch_dtype = torch.float16
    model = AutoModelForCausalLM.from_pretrained(
        "multimodalart/Florence-2-large-no-flash-attn", torch_dtype=torch_dtype, trust_remote_code=True
    ).to(device)
    processor = AutoProcessor.from_pretrained("multimodalart/Florence-2-large-no-flash-attn", trust_remote_code=True)

    captions = list(captions)
    for i, image_path in enumerate(images):
        if isinstance(image_path, str):
            image = Image.open(image_path).convert("RGB")

        prompt = "<DETAILED_CAPTION>"
        inputs = processor(text=prompt, images=image, return_tensors="pt").to(device, torch_dtype)

        generated_ids = model.generate(
            input_ids=inputs["input_ids"], pixel_values=inputs["pixel_values"], max_new_tokens=1024, num_beams=3
        )

        generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
        parsed_answer = processor.post_process_generation(
            generated_text, task=prompt, image_size=(image.width, image.height)
        )
        caption_text = parsed_answer["<DETAILED_CAPTION>"].replace("The image shows ", "")
        if concept_sentence:
            caption_text = f"{caption_text} [trigger]"
        captions[i] = caption_text

        yield captions
    model.to("cpu")
    del model
    del processor

def recursive_update(d, u):
    for k, v in u.items():
        if isinstance(v, dict) and v:
            d[k] = recursive_update(d.get(k, {}), v)
        else:
            d[k] = v
    return d

def start_training(
    lora_name,
    concept_sentence,
    steps,
    lr,
    rank,
    model_to_train,
    low_vram,
    dataset_folder,
    sample_1,
    sample_2,
    sample_3,
    use_more_advanced_options,
    more_advanced_options,
):
    push_to_hub = True
    if not lora_name:
        raise pg.Error("You forgot to insert your LoRA name! This name has to be unique.")
    try:
        if whoami()["auth"]["accessToken"]["role"] == "write" or "repo.write" in whoami()["auth"]["accessToken"]["fineGrained"]["scoped"][0]["permissions"]:
            pg.Info(f"Starting training locally {whoami()['name']}. Your LoRA will be available locally and in Hugging Face after it finishes.")
        else:
            push_to_hub = False
            pg.Warning("Started training locally. Your LoRa will only be available locally because you didn't login with a `write` token to Hugging Face")
    except:
        push_to_hub = False
        pg.Warning("Started training locally. Your LoRa will only be available locally because you didn't login with a `write` token to Hugging Face")

    slugged_lora_name = slugify(lora_name)

    with open("config/examples/train_lora_flux_24gb.yaml", "r") as f:
        config = yaml.safe_load(f)

    config["config"]["name"] = slugged_lora_name
    config["config"]["process"][0]["model"]["low_vram"] = low_vram
    config["config"]["process"][0]["train"]["skip_first_sample"] = True
    config["config"]["process"][0]["train"]["steps"] = int(steps)
    config["config"]["process"][0]["train"]["lr"] = float(lr)
    config["config"]["process"][0]["network"]["linear"] = int(rank)
    config["config"]["process"][0]["network"]["linear_alpha"] = int(rank)
    config["config"]["process"][0]["datasets"][0]["folder_path"] = dataset_folder
    config["config"]["process"][0]["save"]["push_to_hub"] = push_to_hub
    if push_to_hub:
        try:
            username = whoami()["name"]
        except:
            raise pg.Error("Error trying to retrieve your username. Are you sure you are logged in with Hugging Face?")
        config["config"]["process"][0]["save"]["hf_repo_id"] = f"{username}/{slugged_lora_name}"
        config["config"]["process"][0]["save"]["hf_private"] = True
    if concept_sentence:
        config["config"]["process"][0]["trigger_word"] = concept_sentence

    if sample_1 or sample_2 or sample_3:
        config["config"]["process"][0]["train"]["disable_sampling"] = False
        config["config"]["process"][0]["sample"]["sample_every"] = steps
        config["config"]["process"][0]["sample"]["sample_steps"] = 28
        config["config"]["process"][0]["sample"]["prompts"] = []
        if sample_1:
            config["config"]["process"][0]["sample"]["prompts"].append(sample_1)
        if sample_2:
            config["config"]["process"][0]["sample"]["prompts"].append(sample_2)
        if sample_3:
            config["config"]["process"][0]["sample"]["prompts"].append(sample_3)
    else:
        config["config"]["process"][0]["train"]["disable_sampling"] = True
    if model_to_train == "schnell":
        config["config"]["process"][0]["model"]["name_or_path"] = "black-forest-labs/FLUX.1-schnell"
        config["config"]["process"][0]["model"]["assistant_lora_path"] = "ostris/FLUX.1-schnell-training-adapter"
        config["config"]["process"][0]["sample"]["sample_steps"] = 4
    if use_more_advanced_options:
        more_advanced_options_dict = yaml.safe_load(more_advanced_options)
        config["config"]["process"][0] = recursive_update(config["config"]["process"][0], more_advanced_options_dict)

    random_config_name = str(uuid.uuid4())
    os.makedirs("tmp", exist_ok=True)
    config_path = f"tmp/{random_config_name}-{slugged_lora_name}.yaml"
    with open(config_path, "w") as f:
        yaml.dump(config, f)

    job = get_job(config_path)
    job.run()
    job.cleanup()

    return f"Training completed successfully. Model saved as {slugged_lora_name}"

config_yaml = '''
device: cuda:0
model:
  is_flux: true
  quantize: true
network:
  linear: 16
  linear_alpha: 16
  type: lora
sample:
  guidance_scale: 3.5
  height: 1024
  neg: ''
  sample_every: 1000
  sample_steps: 28
  sampler: flowmatch
  seed: 42
  walk_seed: true
  width: 1024
save:
  dtype: float16
  hf_private: true
  max_step_saves_to_keep: 4
  push_to_hub: true
  save_every: 10000
train:
  batch_size: 1
  dtype: bf16
  ema_config:
    ema_decay: 0.99
    use_ema: true
  gradient_accumulation_steps: 1
  gradient_checkpointing: true
  noise_scheduler: flowmatch 
  optimizer: adamw8bit
  train_text_encoder: false
  train_unet: true
'''

def main():
    with pg.App() as app:
        app.add_page(title="LoRA Ease for FLUX", description="Train a high quality FLUX LoRA in a breeze")

        app.add_textbox(
            id="lora_name",
            label="The name of your LoRA",
            placeholder="e.g.: Persian Miniature Painting style, Cat Toy",
        )
        app.add_textbox(
            id="concept_sentence",
            label="Trigger word/sentence",
            placeholder="uncommon word like p3rs0n or trtcrd, or sentence like 'in the style of CNSTLL'",
        )

        image_upload = app.add_file_upload(
            id="images",
            label="Upload your images",
            file_types=["image", ".txt"],
            multiple=True,
        )

        captioning_area = app.add_container(id="captioning_area", visible=False)
        captioning_area.add_text("Custom captioning")
        do_captioning = app.add_button("Add AI captions with Florence-2", id="do_captioning")

        for i in range(1, MAX_IMAGES + 1):
            with captioning_area.add_row(id=f"captioning_row_{i}", visible=False) as row:
                row.add_image(id=f"image_{i}", width=111, height=111, visible=False)
                row.add_textbox(id=f"caption_{i}", label=f"Caption {i}")

        app.add_accordion(title="Advanced options", open=False)
        app.add_number(id="steps", label="Steps", value=1000, min=1, max=10000)
        app.add_number(id="lr", label="Learning Rate", value=4e-4, min=1e-6, max=1e-3)
        app.add_number(id="rank", label="LoRA Rank", value=16, min=4, max=128)
        app.add_radio(id="model_to_train", options=["dev", "schnell"], value="dev", label="Model to train")
        app.add_checkbox(id="low_vram", label="Low VRAM", value=True)

        with app.add_accordion(title="Even more advanced options", open=False):
            app.add_checkbox(id="use_more_advanced_options", label="Use more advanced options", value=False)
            app.add_code(id="more_advanced_options", value=config_yaml, language="yaml")

        app.add_accordion(title="Sample prompts (optional)", visible=False)
        app.add_textbox(id="sample_1", label="Test prompt 1")
        app.add_textbox(id="sample_2", label="Test prompt 2")
        app.add_textbox(id="sample_3", label="Test prompt 3")

        start = app.add_button("Start training", id="start", visible=False)
        progress_area = app.add_text("")

        app.on_upload(id="images", fn=load_captioning, inputs=["images", "concept_sentence"], outputs=["captioning_area", "sample", "start"])
        app.on_click(id="do_captioning", fn=run_captioning, inputs=["images", "concept_sentence"] + [f"caption_{i}" for i in range(1, MAX_IMAGES + 1)], outputs=[f"caption_{i}" for i in range(1, MAX_IMAGES + 1)])
        app.on_click(id="start", fn=create_dataset, inputs=["images"] + [f"caption_{i}" for i in range(1, MAX_IMAGES + 1)], outputs=["dataset_folder"])
        app.on_click(id="start", fn=start_training, inputs=[
            "lora_name",
            "concept_sentence",
            "steps",
            "lr",
            "rank",
            "model_to_train",
            "low_vram",
            "dataset_folder",
            "sample_1",
            "sample_2",
            "sample_3",
            "use_more_advanced_options",
            "more_advanced_options"
        ], outputs=["progress_area"])

        app.run()

if __name__ == "__main__":
    main()