memoryai commited on
Commit
5f4163e
·
verified ·
1 Parent(s): ed16a36

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/training/train_flux_lora.py +52 -16
scripts/training/train_flux_lora.py CHANGED
@@ -28,6 +28,12 @@ def get_train_transforms(resolution=1024):
28
  ])
29
 
30
 
 
 
 
 
 
 
31
  def create_webdataset(data_dir, resolution=1024, batch_size=4):
32
  transform = get_train_transforms(resolution)
33
 
@@ -46,11 +52,11 @@ def create_webdataset(data_dir, resolution=1024, batch_size=4):
46
  raise ValueError(f"No tar files found in {data_dir}")
47
 
48
  dataset = (
49
- wds.WebDataset([str(f) for f in tar_files], shardshuffle=True)
50
  .shuffle(1000)
51
  .decode("pil")
52
  .map(preprocess)
53
- .batched(batch_size)
54
  )
55
  return dataset
56
 
@@ -144,9 +150,9 @@ def main():
144
  train_dataset, batch_size=None, num_workers=4, pin_memory=True
145
  )
146
 
147
- # Prepare with accelerator
148
- transformer, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
149
- transformer, optimizer, train_dataloader, lr_scheduler
150
  )
151
 
152
  # Move frozen models to device
@@ -158,6 +164,13 @@ def main():
158
  global_step = 0
159
  print(f"Starting training for {args.max_train_steps} steps...")
160
 
 
 
 
 
 
 
 
161
  transformer.train()
162
  for batch in train_dataloader:
163
  if global_step >= args.max_train_steps:
@@ -172,38 +185,61 @@ def main():
172
  latents = vae.encode(images).latent_dist.sample()
173
  latents = (latents - vae.config.shift_factor) * vae.config.scaling_factor
174
 
175
- # Encode text
176
  with torch.no_grad():
 
177
  text_input_ids = tokenizer(
178
  captions, padding="max_length", max_length=77,
179
  truncation=True, return_tensors="pt"
180
  ).input_ids.to(accelerator.device)
181
- encoder_hidden_states = text_encoder(text_input_ids)[0]
182
 
 
183
  text_input_ids_2 = tokenizer_2(
184
  captions, padding="max_length", max_length=512,
185
  truncation=True, return_tensors="pt"
186
  ).input_ids.to(accelerator.device)
187
- pooled_prompt_embeds = text_encoder_2(text_input_ids_2)[0]
188
 
189
- # Sample noise and timesteps
190
  noise = torch.randn_like(latents)
191
- timesteps = torch.randint(0, 1000, (latents.shape[0],), device=latents.device).long()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
 
193
- # Add noise to latents
194
- noisy_latents = pipe.scheduler.add_noise(latents, noise, timesteps)
195
 
196
- # Predict noise
197
  model_pred = transformer(
198
  hidden_states=noisy_latents,
199
- timestep=timesteps,
200
  encoder_hidden_states=encoder_hidden_states,
201
  pooled_projections=pooled_prompt_embeds,
 
 
202
  return_dict=False,
203
  )[0]
204
 
205
- # Loss
206
- loss = torch.nn.functional.mse_loss(model_pred, noise, reduction="mean")
207
 
208
  accelerator.backward(loss)
209
  if accelerator.sync_gradients:
 
28
  ])
29
 
30
 
31
+ def collate_batch(samples):
32
+ images = torch.stack([s["image"] for s in samples])
33
+ captions = [s["caption"] for s in samples]
34
+ return {"image": images, "caption": captions}
35
+
36
+
37
  def create_webdataset(data_dir, resolution=1024, batch_size=4):
38
  transform = get_train_transforms(resolution)
39
 
 
52
  raise ValueError(f"No tar files found in {data_dir}")
53
 
54
  dataset = (
55
+ wds.WebDataset([str(f) for f in tar_files], shardshuffle=True, nodesplitter=wds.split_by_node)
56
  .shuffle(1000)
57
  .decode("pil")
58
  .map(preprocess)
59
+ .batched(batch_size, collation_fn=collate_batch)
60
  )
61
  return dataset
62
 
 
150
  train_dataset, batch_size=None, num_workers=4, pin_memory=True
151
  )
152
 
153
+ # Prepare with accelerator (skip dataloader — it contains strings that can't be gathered)
154
+ transformer, optimizer, lr_scheduler = accelerator.prepare(
155
+ transformer, optimizer, lr_scheduler
156
  )
157
 
158
  # Move frozen models to device
 
164
  global_step = 0
165
  print(f"Starting training for {args.max_train_steps} steps...")
166
 
167
+ def pack_latents(latents):
168
+ # Pack 2x2 patches: (B, C, H, W) -> (B, H//2 * W//2, C*4)
169
+ b, c, h, w = latents.shape
170
+ latents = latents.reshape(b, c, h // 2, 2, w // 2, 2)
171
+ latents = latents.permute(0, 2, 4, 1, 3, 5).reshape(b, (h // 2) * (w // 2), c * 4)
172
+ return latents
173
+
174
  transformer.train()
175
  for batch in train_dataloader:
176
  if global_step >= args.max_train_steps:
 
185
  latents = vae.encode(images).latent_dist.sample()
186
  latents = (latents - vae.config.shift_factor) * vae.config.scaling_factor
187
 
188
+ # Encode text: CLIP for pooled, T5 for sequence
189
  with torch.no_grad():
190
+ # CLIP text encoder -> pooled embeddings
191
  text_input_ids = tokenizer(
192
  captions, padding="max_length", max_length=77,
193
  truncation=True, return_tensors="pt"
194
  ).input_ids.to(accelerator.device)
195
+ pooled_prompt_embeds = text_encoder(text_input_ids, output_hidden_states=False).pooler_output
196
 
197
+ # T5 text encoder -> sequence embeddings
198
  text_input_ids_2 = tokenizer_2(
199
  captions, padding="max_length", max_length=512,
200
  truncation=True, return_tensors="pt"
201
  ).input_ids.to(accelerator.device)
202
+ encoder_hidden_states = text_encoder_2(text_input_ids_2)[0]
203
 
204
+ # Flow matching: sample timesteps uniformly and interpolate
205
  noise = torch.randn_like(latents)
206
+ t = torch.rand(latents.shape[0], device=latents.device, dtype=latents.dtype)
207
+ t_expand = t.view(-1, 1, 1, 1)
208
+
209
+ # Noisy latents via linear interpolation
210
+ noisy_latents = (1 - t_expand) * latents + t_expand * noise
211
+
212
+ # Pack latents into sequence format for transformer
213
+ noisy_latents = pack_latents(noisy_latents)
214
+ target_latents = pack_latents(noise - latents)
215
+
216
+ # Flux expects timesteps scaled to [0, 1000]
217
+ timesteps = (t * 1000).to(dtype=noisy_latents.dtype)
218
+
219
+ # Generate image position IDs
220
+ b, seq_len, _ = noisy_latents.shape
221
+ img_ids = torch.zeros(seq_len, 3, device=accelerator.device, dtype=noisy_latents.dtype)
222
+ h_patches = w_patches = int(seq_len ** 0.5)
223
+ img_ids[:, 1] = torch.arange(h_patches, device=accelerator.device).repeat_interleave(w_patches).to(noisy_latents.dtype)
224
+ img_ids[:, 2] = torch.arange(w_patches, device=accelerator.device).repeat(h_patches).to(noisy_latents.dtype)
225
+ img_ids = img_ids.unsqueeze(0).expand(b, -1, -1)
226
 
227
+ # Text position IDs
228
+ txt_ids = torch.zeros(b, encoder_hidden_states.shape[1], 3, device=accelerator.device, dtype=noisy_latents.dtype)
229
 
230
+ # Predict velocity
231
  model_pred = transformer(
232
  hidden_states=noisy_latents,
233
+ timestep=timesteps / 1000,
234
  encoder_hidden_states=encoder_hidden_states,
235
  pooled_projections=pooled_prompt_embeds,
236
+ img_ids=img_ids,
237
+ txt_ids=txt_ids,
238
  return_dict=False,
239
  )[0]
240
 
241
+ # Flow matching loss
242
+ loss = torch.nn.functional.mse_loss(model_pred, target_latents, reduction="mean")
243
 
244
  accelerator.backward(loss)
245
  if accelerator.sync_gradients: