memoryai commited on
Commit
5187e4e
·
verified ·
1 Parent(s): ab09065

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/training/train_flux_v2.py +187 -0
scripts/training/train_flux_v2.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Flux LoRA Training - Flow Matching with correct latent packing.
3
+ """
4
+ from diffusers import FluxPipeline
5
+ from diffusers.optimization import get_scheduler
6
+ from peft import LoraConfig, get_peft_model
7
+ from accelerate import Accelerator
8
+ import torch
9
+ import torch.nn.functional as F
10
+ import webdataset as wds
11
+ from pathlib import Path
12
+ from PIL import Image
13
+ import io
14
+ import time
15
+ from torchvision import transforms
16
+
17
+ MODEL_NAME = "black-forest-labs/FLUX.1-schnell"
18
+ DATA_DIR = "/data0/datasets/processed/flux_train/shards"
19
+ OUTPUT_DIR = "/data0/checkpoints/flux_lora"
20
+ CACHE_DIR = "/data0/models"
21
+ BATCH_SIZE = 1
22
+ GRAD_ACCUM = 4
23
+ LR = 1e-4
24
+ MAX_STEPS = 50000
25
+ SAVE_STEPS = 5000
26
+ LORA_RANK = 128
27
+
28
+ Path(OUTPUT_DIR).mkdir(parents=True, exist_ok=True)
29
+
30
+ accelerator = Accelerator(
31
+ mixed_precision="bf16",
32
+ gradient_accumulation_steps=GRAD_ACCUM,
33
+ )
34
+
35
+ print("Loading Flux...")
36
+ pipe = FluxPipeline.from_pretrained(
37
+ MODEL_NAME,
38
+ torch_dtype=torch.bfloat16,
39
+ cache_dir=CACHE_DIR,
40
+ )
41
+
42
+ transformer = pipe.transformer
43
+ vae = pipe.vae
44
+
45
+ vae.requires_grad_(False)
46
+ pipe.text_encoder.requires_grad_(False)
47
+ pipe.text_encoder_2.requires_grad_(False)
48
+
49
+ lora_config = LoraConfig(
50
+ r=LORA_RANK,
51
+ lora_alpha=LORA_RANK,
52
+ target_modules=["to_q", "to_k", "to_v", "to_out.0"],
53
+ lora_dropout=0.05,
54
+ )
55
+ transformer = get_peft_model(transformer, lora_config)
56
+ transformer.print_trainable_parameters()
57
+
58
+ optimizer = torch.optim.AdamW(transformer.parameters(), lr=LR, weight_decay=0.01)
59
+ lr_scheduler = get_scheduler("cosine", optimizer=optimizer, num_warmup_steps=500, num_training_steps=MAX_STEPS)
60
+
61
+ transform = transforms.Compose([
62
+ transforms.Resize(1024, interpolation=transforms.InterpolationMode.LANCZOS),
63
+ transforms.CenterCrop(1024),
64
+ transforms.ToTensor(),
65
+ transforms.Normalize([0.5], [0.5]),
66
+ ])
67
+
68
+ tar_files = sorted(Path(DATA_DIR).glob("*.tar"))
69
+ print(f"Found {len(tar_files)} tar shards")
70
+
71
+
72
+ def preprocess(sample):
73
+ try:
74
+ img = sample["jpg"]
75
+ if isinstance(img, bytes):
76
+ img = Image.open(io.BytesIO(img)).convert("RGB")
77
+ caption = sample.get("txt", b"")
78
+ if isinstance(caption, bytes):
79
+ caption = caption.decode("utf-8")
80
+ return {"image": transform(img), "caption": caption}
81
+ except:
82
+ return None
83
+
84
+
85
+ dataset = (
86
+ wds.WebDataset([str(f) for f in tar_files], shardshuffle=True)
87
+ .shuffle(1000)
88
+ .decode("pil")
89
+ .map(preprocess)
90
+ .select(lambda x: x is not None)
91
+ )
92
+ dataloader = torch.utils.data.DataLoader(dataset, batch_size=BATCH_SIZE, num_workers=4, pin_memory=True)
93
+
94
+ transformer, optimizer, dataloader, lr_scheduler = accelerator.prepare(
95
+ transformer, optimizer, dataloader, lr_scheduler
96
+ )
97
+ vae.to(accelerator.device, dtype=torch.bfloat16)
98
+ pipe.text_encoder.to(accelerator.device, dtype=torch.bfloat16)
99
+ pipe.text_encoder_2.to(accelerator.device, dtype=torch.bfloat16)
100
+
101
+
102
+ def pack_latents(latents, batch_size, num_channels, height, width):
103
+ latents = latents.view(batch_size, num_channels, height // 2, 2, width // 2, 2)
104
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
105
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels * 4)
106
+ return latents
107
+
108
+
109
+ def prepare_latent_image_ids(height, width, device, dtype):
110
+ latent_image_ids = torch.zeros(height // 2, width // 2, 3)
111
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height // 2)[:, None]
112
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width // 2)[None, :]
113
+ latent_image_ids = latent_image_ids.reshape(height // 2 * width // 2, 3)
114
+ return latent_image_ids.to(device=device, dtype=dtype)
115
+
116
+
117
+ global_step = 0
118
+ t0 = time.time()
119
+ print(f"Starting training... Max steps: {MAX_STEPS}")
120
+
121
+ transformer.train()
122
+ while global_step < MAX_STEPS:
123
+ for batch in dataloader:
124
+ if global_step >= MAX_STEPS:
125
+ break
126
+
127
+ with accelerator.accumulate(transformer):
128
+ images = batch["image"].to(accelerator.device, dtype=torch.bfloat16)
129
+ captions = batch["caption"]
130
+ bs = images.shape[0]
131
+
132
+ with torch.no_grad():
133
+ latents = vae.encode(images).latent_dist.sample()
134
+ latents = (latents - vae.config.shift_factor) * vae.config.scaling_factor
135
+
136
+ packed_latents = pack_latents(latents, bs, 16, 128, 128)
137
+ latent_image_ids = prepare_latent_image_ids(128, 128, accelerator.device, torch.bfloat16)
138
+
139
+ prompt_embeds, pooled_prompt_embeds, text_ids = pipe.encode_prompt(
140
+ prompt=captions if isinstance(captions, list) else [captions],
141
+ prompt_2=None,
142
+ device=accelerator.device,
143
+ )
144
+
145
+ noise = torch.randn_like(packed_latents)
146
+ t = torch.rand(bs, device=accelerator.device, dtype=torch.bfloat16)
147
+ t_expand = t.view(-1, 1, 1)
148
+
149
+ noisy_latents = (1 - t_expand) * packed_latents + t_expand * noise
150
+ timesteps = (t * 1000).to(dtype=packed_latents.dtype)
151
+
152
+ model_pred = transformer(
153
+ hidden_states=noisy_latents,
154
+ timestep=timesteps,
155
+ encoder_hidden_states=prompt_embeds,
156
+ pooled_projections=pooled_prompt_embeds,
157
+ txt_ids=text_ids,
158
+ img_ids=latent_image_ids,
159
+ return_dict=False,
160
+ )[0]
161
+
162
+ target = noise - packed_latents
163
+ loss = F.mse_loss(model_pred, target)
164
+
165
+ accelerator.backward(loss)
166
+ if accelerator.sync_gradients:
167
+ accelerator.clip_grad_norm_(transformer.parameters(), 1.0)
168
+ optimizer.step()
169
+ lr_scheduler.step()
170
+ optimizer.zero_grad()
171
+
172
+ if accelerator.sync_gradients:
173
+ global_step += 1
174
+
175
+ if global_step % 100 == 0:
176
+ elapsed = time.time() - t0
177
+ print(f"Step {global_step}/{MAX_STEPS} | Loss: {loss.item():.4f} | LR: {lr_scheduler.get_last_lr()[0]:.2e} | Time: {elapsed/3600:.1f}h")
178
+
179
+ if global_step % SAVE_STEPS == 0:
180
+ save_path = f"{OUTPUT_DIR}/checkpoint-{global_step}"
181
+ accelerator.unwrap_model(transformer).save_pretrained(save_path)
182
+ print(f"Saved: {save_path}")
183
+
184
+ final_path = f"{OUTPUT_DIR}/final"
185
+ accelerator.unwrap_model(transformer).save_pretrained(final_path)
186
+ print(f"Training complete! Saved to {final_path}")
187
+ print(f"Total time: {(time.time()-t0)/3600:.1f} hours")