File size: 11,651 Bytes
eabea76
b1c12a9
eabea76
 
 
b1c12a9
eabea76
 
 
 
 
 
 
b1c12a9
eabea76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1c12a9
 
 
 
 
 
 
 
 
 
 
 
 
 
eabea76
b1c12a9
eabea76
 
 
 
b1c12a9
 
eabea76
 
 
 
 
 
 
 
b1c12a9
eabea76
 
 
 
 
b1c12a9
eabea76
 
b1c12a9
 
eabea76
 
b1c12a9
 
 
 
 
 
 
 
 
 
 
 
eabea76
 
 
 
 
 
 
 
 
b1c12a9
eabea76
 
 
 
 
 
 
 
b1c12a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
867abc2
 
 
 
eabea76
 
 
b1c12a9
 
 
eabea76
 
 
 
 
 
 
 
 
 
 
 
 
 
b1c12a9
eabea76
 
 
 
b1c12a9
eabea76
 
 
 
b1c12a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eabea76
 
 
b1c12a9
eabea76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1c12a9
eabea76
 
 
 
 
 
 
 
 
5a2cb85
eabea76
 
 
 
 
 
 
 
 
 
 
 
867abc2
eabea76
 
 
 
b1c12a9
eabea76
 
 
 
 
 
 
 
 
 
b1c12a9
 
 
 
eabea76
 
 
 
 
 
 
 
b1c12a9
 
 
 
 
 
 
 
eabea76
 
 
 
 
 
 
 
 
 
 
b1c12a9
 
eabea76
 
 
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
"""
Flux LoRA Training - Compatible with both single GPU and DeepSpeed multi-GPU.
Uses pre-computed embeddings for maximum GPU efficiency.
"""
import argparse
import os
import time
from pathlib import Path

import torch
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from accelerate import Accelerator
from accelerate.utils import set_seed
from diffusers import FluxTransformer2DModel
from diffusers.optimization import get_scheduler
from peft import LoraConfig, get_peft_model


class EmbeddingDataset(Dataset):
    def __init__(self, embedding_dir):
        self.embedding_dir = Path(embedding_dir)
        self.shard_files = sorted(self.embedding_dir.glob("shard-*.pt"))
        if not self.shard_files:
            raise ValueError(f"No shard files found in {embedding_dir}")

        self.shard_lengths = []
        self.cumulative = [0]
        for sf in self.shard_files:
            data = torch.load(sf, map_location="cpu", weights_only=False)
            self.shard_lengths.append(len(data))
            self.cumulative.append(self.cumulative[-1] + len(data))
            del data

        self.total_samples = self.cumulative[-1]
        self._cache_shard_idx = -1
        self._cache_data = None
        print(f"EmbeddingDataset: {self.total_samples} samples in {len(self.shard_files)} shards")

    def __len__(self):
        return self.total_samples

    def _get_shard_and_local_idx(self, idx):
        for i in range(len(self.shard_files)):
            if idx < self.cumulative[i + 1]:
                return i, idx - self.cumulative[i]
        raise IndexError(f"Index {idx} out of range")

    def __getitem__(self, idx):
        shard_idx, local_idx = self._get_shard_and_local_idx(idx)

        if shard_idx != self._cache_shard_idx:
            self._cache_data = torch.load(
                self.shard_files[shard_idx], map_location="cpu", weights_only=False
            )
            self._cache_shard_idx = shard_idx

        sample = self._cache_data[local_idx]
        return {
            "packed_latents": sample["packed_latents"],
            "pooled_prompt_embeds": sample["pooled_prompt_embeds"],
            "encoder_hidden_states": sample["encoder_hidden_states"],
            "img_ids": sample["img_ids"],
            "txt_ids": sample["txt_ids"],
        }


def find_latest_checkpoint(output_dir):
    output_dir = Path(output_dir)
    if not output_dir.exists():
        return None, 0
    checkpoints = sorted(
        [d for d in output_dir.iterdir() if d.is_dir() and d.name.startswith("checkpoint-")],
        key=lambda p: int(p.name.split("-")[1]) if p.name.split("-")[1].isdigit() else 0,
    )
    if checkpoints:
        step = int(checkpoints[-1].name.split("-")[1])
        return checkpoints[-1], step
    return None, 0


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--model-name", default="black-forest-labs/FLUX.1-schnell")
    parser.add_argument("--embedding-dir", type=Path, default=Path("/data0/datasets/processed/flux_train/embeddings"))
    parser.add_argument("--output-dir", type=Path, default=Path("/data0/checkpoints/flux_lora_ds"))
    parser.add_argument("--cache-dir", default="/data0/models")
    parser.add_argument("--batch-size", type=int, default=1)
    parser.add_argument("--gradient-accumulation", type=int, default=8)
    parser.add_argument("--learning-rate", type=float, default=1e-4)
    parser.add_argument("--lr-scheduler", default="cosine")
    parser.add_argument("--lr-warmup-steps", type=int, default=500)
    parser.add_argument("--max-train-steps", type=int, default=100000)
    parser.add_argument("--save-steps", type=int, default=5000)
    parser.add_argument("--lora-rank", type=int, default=128)
    parser.add_argument("--lora-alpha", type=int, default=128)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--resume-from-checkpoint", default="auto")
    args = parser.parse_args()

    accelerator = Accelerator(
        mixed_precision="bf16",
        gradient_accumulation_steps=args.gradient_accumulation,
        log_with=None,
    )

    set_seed(args.seed)

    if accelerator.is_main_process:
        args.output_dir.mkdir(parents=True, exist_ok=True)
        print(f"Process count: {accelerator.num_processes}")
        print(f"Device: {accelerator.device}")

    # Resume logic
    resume_path = None
    resume_step = 0
    if args.resume_from_checkpoint == "auto":
        resume_path, resume_step = find_latest_checkpoint(args.output_dir)
        if resume_path:
            print(f"Resuming from {resume_path} (step {resume_step})")

    # Load transformer
    if accelerator.is_main_process:
        print("Loading Flux Transformer...")
    transformer = FluxTransformer2DModel.from_pretrained(
        args.model_name,
        subfolder="transformer",
        torch_dtype=torch.bfloat16,
        cache_dir=args.cache_dir,
    )

    # LoRA
    lora_config = LoraConfig(
        r=args.lora_rank,
        lora_alpha=args.lora_alpha,
        target_modules=["to_q", "to_k", "to_v", "to_out.0"],
        lora_dropout=0.0,
    )
    transformer = get_peft_model(transformer, lora_config)

    # Load LoRA weights if resuming
    if resume_path:
        from peft import set_peft_model_state_dict
        import safetensors.torch
        adapter_path = resume_path / "adapter_model.safetensors"
        if adapter_path.exists():
            state_dict = safetensors.torch.load_file(str(adapter_path))
            set_peft_model_state_dict(transformer, state_dict)
            print(f"  Loaded LoRA weights from {adapter_path}")
        else:
            adapter_bin = resume_path / "adapter_model.bin"
            if adapter_bin.exists():
                state_dict = torch.load(str(adapter_bin), map_location="cpu")
                set_peft_model_state_dict(transformer, state_dict)
                print(f"  Loaded LoRA weights from {adapter_bin}")

    # Cast trainable params to fp32 for stable training
    for name, p in transformer.named_parameters():
        if p.requires_grad:
            p.data = p.data.float()

    if accelerator.is_main_process:
        transformer.print_trainable_parameters()

    # Optimizer
    trainable_params = [p for p in transformer.parameters() if p.requires_grad]
    optimizer = torch.optim.AdamW(trainable_params, lr=args.learning_rate, weight_decay=0.01)

    lr_scheduler = get_scheduler(
        args.lr_scheduler,
        optimizer=optimizer,
        num_warmup_steps=args.lr_warmup_steps,
        num_training_steps=args.max_train_steps,
    )

    # Dataset
    dataset = EmbeddingDataset(args.embedding_dir)
    dataloader = DataLoader(
        dataset,
        batch_size=args.batch_size,
        shuffle=True,
        num_workers=2,
        pin_memory=True,
        drop_last=True,
    )

    # Prepare
    transformer, optimizer, dataloader, lr_scheduler = accelerator.prepare(
        transformer, optimizer, dataloader, lr_scheduler
    )

    # Skip steps if resuming
    global_step = resume_step
    if resume_step > 0:
        steps_to_skip = resume_step * args.gradient_accumulation
        if accelerator.is_main_process:
            print(f"  Skipping {steps_to_skip} dataloader batches...")
        skipped = 0
        skip_dl = iter(dataloader)
        while skipped < steps_to_skip:
            try:
                next(skip_dl)
                skipped += 1
            except StopIteration:
                skip_dl = iter(dataloader)
        del skip_dl

    # Training
    t0 = time.time()

    if accelerator.is_main_process:
        print(f"\nStarting training from step {global_step}...")
        print(f"  Batch size/GPU: {args.batch_size}")
        print(f"  Num GPUs: {accelerator.num_processes}")
        print(f"  Grad accumulation: {args.gradient_accumulation}")
        print(f"  Effective batch: {args.batch_size * accelerator.num_processes * args.gradient_accumulation}")
        print(f"  Max steps: {args.max_train_steps}")
        print(f"  Dataset: {len(dataset)} samples")

    transformer.train()

    while global_step < args.max_train_steps:
        for batch in dataloader:
            if global_step >= args.max_train_steps:
                break

            with accelerator.accumulate(transformer):
                packed_latents = batch["packed_latents"].to(dtype=torch.bfloat16)
                pooled_prompt_embeds = batch["pooled_prompt_embeds"].to(dtype=torch.bfloat16)
                encoder_hidden_states = batch["encoder_hidden_states"].to(dtype=torch.bfloat16)
                img_ids = batch["img_ids"][0]
                txt_ids = batch["txt_ids"][0]

                bs = packed_latents.shape[0]

                noise = torch.randn_like(packed_latents)
                t = torch.rand(bs, device=packed_latents.device, dtype=torch.bfloat16)
                t_expand = t.view(-1, 1, 1)

                noisy_latents = (1 - t_expand) * packed_latents + t_expand * noise
                timesteps = t

                model_pred = transformer(
                    hidden_states=noisy_latents,
                    timestep=timesteps,
                    encoder_hidden_states=encoder_hidden_states,
                    pooled_projections=pooled_prompt_embeds,
                    img_ids=img_ids,
                    txt_ids=txt_ids,
                    return_dict=False,
                )[0]

                target = noise - packed_latents
                loss = F.mse_loss(model_pred.float(), target.float())

                accelerator.backward(loss)

                if accelerator.sync_gradients:
                    accelerator.clip_grad_norm_(trainable_params, 1.0)

                optimizer.step()
                lr_scheduler.step()
                optimizer.zero_grad()

            if accelerator.sync_gradients:
                global_step += 1

                if global_step % 100 == 0 and accelerator.is_main_process:
                    elapsed = time.time() - t0
                    steps_done = global_step - resume_step
                    steps_per_sec = steps_done / elapsed if elapsed > 0 else 0
                    remaining = args.max_train_steps - global_step
                    eta_hours = remaining / steps_per_sec / 3600 if steps_per_sec > 0 else 0
                    print(
                        f"Step {global_step}/{args.max_train_steps} | "
                        f"Loss: {loss.item():.4f} | "
                        f"LR: {lr_scheduler.get_last_lr()[0]:.2e} | "
                        f"Speed: {steps_per_sec:.2f} steps/s | "
                        f"ETA: {eta_hours:.1f}h"
                    )

                if global_step % args.save_steps == 0:
                    if accelerator.is_main_process:
                        save_path = args.output_dir / f"checkpoint-{global_step}"
                        save_path.mkdir(parents=True, exist_ok=True)
                        unwrapped = accelerator.unwrap_model(transformer)
                        unwrapped.save_pretrained(save_path)
                        print(f"Saved checkpoint: {save_path}")
                    accelerator.wait_for_everyone()

    # Save final
    if accelerator.is_main_process:
        final_path = args.output_dir / "final"
        final_path.mkdir(parents=True, exist_ok=True)
        unwrapped = accelerator.unwrap_model(transformer)
        unwrapped.save_pretrained(final_path)
        total_time = (time.time() - t0) / 3600
        print(f"\nTraining complete! Saved to {final_path}")
        print(f"Total time: {total_time:.1f} hours")

    accelerator.wait_for_everyone()


if __name__ == "__main__":
    main()